1b4e4e876ecac0253d85a74b3a839efe8a8bd1f1
[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-2001 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 #define CSWIFT_LIB_NAME "cswift engine"
87 #include "hw_cswift_err.c"
88
89 static int cswift_destroy(ENGINE *e);
90 static int cswift_init(ENGINE *e);
91 static int cswift_finish(ENGINE *e);
92 static int cswift_ctrl(ENGINE *e, int cmd, long i, void *p, void (*f)());
93
94 /* BIGNUM stuff */
95 static int cswift_mod_exp(BIGNUM *r, const BIGNUM *a, const BIGNUM *p,
96                 const BIGNUM *m, BN_CTX *ctx);
97 static int cswift_mod_exp_crt(BIGNUM *r, const BIGNUM *a, const BIGNUM *p,
98                 const BIGNUM *q, const BIGNUM *dmp1, const BIGNUM *dmq1,
99                 const BIGNUM *iqmp, BN_CTX *ctx);
100
101 #ifndef OPENSSL_NO_RSA
102 /* RSA stuff */
103 static int cswift_rsa_mod_exp(BIGNUM *r0, const BIGNUM *I, RSA *rsa);
104 #endif
105 /* This function is aliased to mod_exp (with the mont stuff dropped). */
106 static int cswift_mod_exp_mont(BIGNUM *r, const BIGNUM *a, const BIGNUM *p,
107                 const BIGNUM *m, BN_CTX *ctx, BN_MONT_CTX *m_ctx);
108
109 #ifndef OPENSSL_NO_DSA
110 /* DSA stuff */
111 static DSA_SIG *cswift_dsa_sign(const unsigned char *dgst, int dlen, DSA *dsa);
112 static int cswift_dsa_verify(const unsigned char *dgst, int dgst_len,
113                                 DSA_SIG *sig, DSA *dsa);
114 #endif
115
116 #ifndef OPENSSL_NO_DH
117 /* DH stuff */
118 /* This function is alised to mod_exp (with the DH and mont dropped). */
119 static int cswift_mod_exp_dh(const DH *dh, BIGNUM *r,
120                 const BIGNUM *a, const BIGNUM *p,
121                 const BIGNUM *m, BN_CTX *ctx, BN_MONT_CTX *m_ctx);
122 #endif
123
124 /* RAND stuff */
125 static int cswift_rand_bytes(unsigned char *buf, int num);
126 static int cswift_rand_status(void);
127
128 /* The definitions for control commands specific to this engine */
129 #define CSWIFT_CMD_SO_PATH              ENGINE_CMD_BASE
130 static const ENGINE_CMD_DEFN cswift_cmd_defns[] = {
131         {CSWIFT_CMD_SO_PATH,
132                 "SO_PATH",
133                 "Specifies the path to the 'cswift' shared library",
134                 ENGINE_CMD_FLAG_STRING},
135         {0, NULL, NULL, 0}
136         };
137
138 #ifndef OPENSSL_NO_RSA
139 /* Our internal RSA_METHOD that we provide pointers to */
140 static RSA_METHOD cswift_rsa =
141         {
142         "CryptoSwift RSA method",
143         NULL,
144         NULL,
145         NULL,
146         NULL,
147         cswift_rsa_mod_exp,
148         cswift_mod_exp_mont,
149         NULL,
150         NULL,
151         0,
152         NULL,
153         NULL,
154         NULL
155         };
156 #endif
157
158 #ifndef OPENSSL_NO_DSA
159 /* Our internal DSA_METHOD that we provide pointers to */
160 static DSA_METHOD cswift_dsa =
161         {
162         "CryptoSwift DSA method",
163         cswift_dsa_sign,
164         NULL, /* dsa_sign_setup */
165         cswift_dsa_verify,
166         NULL, /* dsa_mod_exp */
167         NULL, /* bn_mod_exp */
168         NULL, /* init */
169         NULL, /* finish */
170         0, /* flags */
171         NULL /* app_data */
172         };
173 #endif
174
175 #ifndef OPENSSL_NO_DH
176 /* Our internal DH_METHOD that we provide pointers to */
177 static DH_METHOD cswift_dh =
178         {
179         "CryptoSwift DH method",
180         NULL,
181         NULL,
182         cswift_mod_exp_dh,
183         NULL,
184         NULL,
185         0,
186         NULL
187         };
188 #endif
189
190 static RAND_METHOD cswift_random =
191     {
192     /* "CryptoSwift RAND method", */
193     NULL,
194     cswift_rand_bytes,
195     NULL,
196     NULL,
197     cswift_rand_bytes,
198     cswift_rand_status,
199     };
200
201
202 /* Constants used when creating the ENGINE */
203 static const char *engine_cswift_id = "cswift";
204 static const char *engine_cswift_name = "CryptoSwift hardware engine support";
205
206 /* This internal function is used by ENGINE_cswift() and possibly by the
207  * "dynamic" ENGINE support too */
208 static int bind_helper(ENGINE *e)
209         {
210 #ifndef OPENSSL_NO_RSA
211         const RSA_METHOD *meth1;
212 #endif
213 #ifndef OPENSSL_NO_DH
214         const DH_METHOD *meth2;
215 #endif
216         if(!ENGINE_set_id(e, engine_cswift_id) ||
217                         !ENGINE_set_name(e, engine_cswift_name) ||
218 #ifndef OPENSSL_NO_RSA
219                         !ENGINE_set_RSA(e, &cswift_rsa) ||
220 #endif
221 #ifndef OPENSSL_NO_DSA
222                         !ENGINE_set_DSA(e, &cswift_dsa) ||
223 #endif
224 #ifndef OPENSSL_NO_DH
225                         !ENGINE_set_DH(e, &cswift_dh) ||
226 #endif
227                         !ENGINE_set_RAND(e, &cswift_random) ||
228                         !ENGINE_set_destroy_function(e, cswift_destroy) ||
229                         !ENGINE_set_init_function(e, cswift_init) ||
230                         !ENGINE_set_finish_function(e, cswift_finish) ||
231                         !ENGINE_set_ctrl_function(e, cswift_ctrl) ||
232                         !ENGINE_set_cmd_defns(e, cswift_cmd_defns))
233                 return 0;
234
235 #ifndef OPENSSL_NO_RSA
236         /* We know that the "PKCS1_SSLeay()" functions hook properly
237          * to the cswift-specific mod_exp and mod_exp_crt so we use
238          * those functions. NB: We don't use ENGINE_openssl() or
239          * anything "more generic" because something like the RSAref
240          * code may not hook properly, and if you own one of these
241          * cards then you have the right to do RSA operations on it
242          * anyway! */ 
243         meth1 = RSA_PKCS1_SSLeay();
244         cswift_rsa.rsa_pub_enc = meth1->rsa_pub_enc;
245         cswift_rsa.rsa_pub_dec = meth1->rsa_pub_dec;
246         cswift_rsa.rsa_priv_enc = meth1->rsa_priv_enc;
247         cswift_rsa.rsa_priv_dec = meth1->rsa_priv_dec;
248 #endif
249
250 #ifndef OPENSSL_NO_DH
251         /* Much the same for Diffie-Hellman */
252         meth2 = DH_OpenSSL();
253         cswift_dh.generate_key = meth2->generate_key;
254         cswift_dh.compute_key = meth2->compute_key;
255 #endif
256
257         /* Ensure the cswift error handling is set up */
258         ERR_load_CSWIFT_strings();
259         return 1;
260         }
261
262 static ENGINE *engine_cswift(void)
263         {
264         ENGINE *ret = ENGINE_new();
265         if(!ret)
266                 return NULL;
267         if(!bind_helper(ret))
268                 {
269                 ENGINE_free(ret);
270                 return NULL;
271                 }
272         return ret;
273         }
274
275 void ENGINE_load_cswift(void)
276         {
277         /* Copied from eng_[openssl|dyn].c */
278         ENGINE *toadd = engine_cswift();
279         if(!toadd) return;
280         ENGINE_add(toadd);
281         ENGINE_free(toadd);
282         ERR_clear_error();
283         }
284
285 /* This is a process-global DSO handle used for loading and unloading
286  * the CryptoSwift library. NB: This is only set (or unset) during an
287  * init() or finish() call (reference counts permitting) and they're
288  * operating with global locks, so this should be thread-safe
289  * implicitly. */
290 static DSO *cswift_dso = NULL;
291
292 /* These are the function pointers that are (un)set when the library has
293  * successfully (un)loaded. */
294 t_swAcquireAccContext *p_CSwift_AcquireAccContext = NULL;
295 t_swAttachKeyParam *p_CSwift_AttachKeyParam = NULL;
296 t_swSimpleRequest *p_CSwift_SimpleRequest = NULL;
297 t_swReleaseAccContext *p_CSwift_ReleaseAccContext = NULL;
298
299 /* Used in the DSO operations. */
300 static const char *CSWIFT_LIBNAME = NULL;
301 static const char *get_CSWIFT_LIBNAME(void)
302         {
303         if(CSWIFT_LIBNAME)
304                 return CSWIFT_LIBNAME;
305         return "swift";
306         }
307 static void free_CSWIFT_LIBNAME(void)
308         {
309         if(CSWIFT_LIBNAME)
310                 OPENSSL_free((void*)CSWIFT_LIBNAME);
311         CSWIFT_LIBNAME = NULL;
312         }
313 static long set_CSWIFT_LIBNAME(const char *name)
314         {
315         free_CSWIFT_LIBNAME();
316         return (((CSWIFT_LIBNAME = BUF_strdup(name)) != NULL) ? 1 : 0);
317         }
318 static const char *CSWIFT_F1 = "swAcquireAccContext";
319 static const char *CSWIFT_F2 = "swAttachKeyParam";
320 static const char *CSWIFT_F3 = "swSimpleRequest";
321 static const char *CSWIFT_F4 = "swReleaseAccContext";
322
323
324 /* CryptoSwift library functions and mechanics - these are used by the
325  * higher-level functions further down. NB: As and where there's no
326  * error checking, take a look lower down where these functions are
327  * called, the checking and error handling is probably down there. */
328
329 /* utility function to obtain a context */
330 static int get_context(SW_CONTEXT_HANDLE *hac)
331         {
332         SW_STATUS status;
333  
334         status = p_CSwift_AcquireAccContext(hac);
335         if(status != SW_OK)
336                 return 0;
337         return 1;
338         }
339  
340 /* similarly to release one. */
341 static void release_context(SW_CONTEXT_HANDLE hac)
342         {
343         p_CSwift_ReleaseAccContext(hac);
344         }
345
346 /* Destructor (complements the "ENGINE_cswift()" constructor) */
347 static int cswift_destroy(ENGINE *e)
348         {
349         free_CSWIFT_LIBNAME();
350         ERR_unload_CSWIFT_strings();
351         return 1;
352         }
353
354 /* (de)initialisation functions. */
355 static int cswift_init(ENGINE *e)
356         {
357         SW_CONTEXT_HANDLE hac;
358         t_swAcquireAccContext *p1;
359         t_swAttachKeyParam *p2;
360         t_swSimpleRequest *p3;
361         t_swReleaseAccContext *p4;
362
363         if(cswift_dso != NULL)
364                 {
365                 CSWIFTerr(CSWIFT_F_CSWIFT_INIT,CSWIFT_R_ALREADY_LOADED);
366                 goto err;
367                 }
368         /* Attempt to load libswift.so/swift.dll/whatever. */
369         cswift_dso = DSO_load(NULL, get_CSWIFT_LIBNAME(), NULL, 0);
370         if(cswift_dso == NULL)
371                 {
372                 CSWIFTerr(CSWIFT_F_CSWIFT_INIT,CSWIFT_R_NOT_LOADED);
373                 goto err;
374                 }
375         if(!(p1 = (t_swAcquireAccContext *)
376                                 DSO_bind_func(cswift_dso, CSWIFT_F1)) ||
377                         !(p2 = (t_swAttachKeyParam *)
378                                 DSO_bind_func(cswift_dso, CSWIFT_F2)) ||
379                         !(p3 = (t_swSimpleRequest *)
380                                 DSO_bind_func(cswift_dso, CSWIFT_F3)) ||
381                         !(p4 = (t_swReleaseAccContext *)
382                                 DSO_bind_func(cswift_dso, CSWIFT_F4)))
383                 {
384                 CSWIFTerr(CSWIFT_F_CSWIFT_INIT,CSWIFT_R_NOT_LOADED);
385                 goto err;
386                 }
387         /* Copy the pointers */
388         p_CSwift_AcquireAccContext = p1;
389         p_CSwift_AttachKeyParam = p2;
390         p_CSwift_SimpleRequest = p3;
391         p_CSwift_ReleaseAccContext = p4;
392         /* Try and get a context - if not, we may have a DSO but no
393          * accelerator! */
394         if(!get_context(&hac))
395                 {
396                 CSWIFTerr(CSWIFT_F_CSWIFT_INIT,CSWIFT_R_UNIT_FAILURE);
397                 goto err;
398                 }
399         release_context(hac);
400         /* Everything's fine. */
401         return 1;
402 err:
403         if(cswift_dso)
404                 DSO_free(cswift_dso);
405         p_CSwift_AcquireAccContext = NULL;
406         p_CSwift_AttachKeyParam = NULL;
407         p_CSwift_SimpleRequest = NULL;
408         p_CSwift_ReleaseAccContext = NULL;
409         return 0;
410         }
411
412 static int cswift_finish(ENGINE *e)
413         {
414         free_CSWIFT_LIBNAME();
415         if(cswift_dso == NULL)
416                 {
417                 CSWIFTerr(CSWIFT_F_CSWIFT_FINISH,CSWIFT_R_NOT_LOADED);
418                 return 0;
419                 }
420         if(!DSO_free(cswift_dso))
421                 {
422                 CSWIFTerr(CSWIFT_F_CSWIFT_FINISH,CSWIFT_R_UNIT_FAILURE);
423                 return 0;
424                 }
425         cswift_dso = NULL;
426         p_CSwift_AcquireAccContext = NULL;
427         p_CSwift_AttachKeyParam = NULL;
428         p_CSwift_SimpleRequest = NULL;
429         p_CSwift_ReleaseAccContext = NULL;
430         return 1;
431         }
432
433 static int cswift_ctrl(ENGINE *e, int cmd, long i, void *p, void (*f)())
434         {
435         int initialised = ((cswift_dso == NULL) ? 0 : 1);
436         switch(cmd)
437                 {
438         case CSWIFT_CMD_SO_PATH:
439                 if(p == NULL)
440                         {
441                         CSWIFTerr(CSWIFT_F_CSWIFT_CTRL,ERR_R_PASSED_NULL_PARAMETER);
442                         return 0;
443                         }
444                 if(initialised)
445                         {
446                         CSWIFTerr(CSWIFT_F_CSWIFT_CTRL,CSWIFT_R_ALREADY_LOADED);
447                         return 0;
448                         }
449                 return set_CSWIFT_LIBNAME((const char *)p);
450         default:
451                 break;
452                 }
453         CSWIFTerr(CSWIFT_F_CSWIFT_CTRL,CSWIFT_R_CTRL_COMMAND_NOT_IMPLEMENTED);
454         return 0;
455         }
456
457 /* Un petit mod_exp */
458 static int cswift_mod_exp(BIGNUM *r, const BIGNUM *a, const BIGNUM *p,
459                         const BIGNUM *m, BN_CTX *ctx)
460         {
461         /* I need somewhere to store temporary serialised values for
462          * use with the CryptoSwift API calls. A neat cheat - I'll use
463          * BIGNUMs from the BN_CTX but access their arrays directly as
464          * byte arrays <grin>. This way I don't have to clean anything
465          * up. */
466         BIGNUM *modulus;
467         BIGNUM *exponent;
468         BIGNUM *argument;
469         BIGNUM *result;
470         SW_STATUS sw_status;
471         SW_LARGENUMBER arg, res;
472         SW_PARAM sw_param;
473         SW_CONTEXT_HANDLE hac;
474         int to_return, acquired;
475  
476         modulus = exponent = argument = result = NULL;
477         to_return = 0; /* expect failure */
478         acquired = 0;
479  
480         if(!get_context(&hac))
481                 {
482                 CSWIFTerr(CSWIFT_F_CSWIFT_MOD_EXP,CSWIFT_R_UNIT_FAILURE);
483                 goto err;
484                 }
485         acquired = 1;
486         /* Prepare the params */
487         BN_CTX_start(ctx);
488         modulus = BN_CTX_get(ctx);
489         exponent = BN_CTX_get(ctx);
490         argument = BN_CTX_get(ctx);
491         result = BN_CTX_get(ctx);
492         if(!result)
493                 {
494                 CSWIFTerr(CSWIFT_F_CSWIFT_MOD_EXP,CSWIFT_R_BN_CTX_FULL);
495                 goto err;
496                 }
497         if(!bn_wexpand(modulus, m->top) || !bn_wexpand(exponent, p->top) ||
498                 !bn_wexpand(argument, a->top) || !bn_wexpand(result, m->top))
499                 {
500                 CSWIFTerr(CSWIFT_F_CSWIFT_MOD_EXP,CSWIFT_R_BN_EXPAND_FAIL);
501                 goto err;
502                 }
503         sw_param.type = SW_ALG_EXP;
504         sw_param.up.exp.modulus.nbytes = BN_bn2bin(m,
505                 (unsigned char *)modulus->d);
506         sw_param.up.exp.modulus.value = (unsigned char *)modulus->d;
507         sw_param.up.exp.exponent.nbytes = BN_bn2bin(p,
508                 (unsigned char *)exponent->d);
509         sw_param.up.exp.exponent.value = (unsigned char *)exponent->d;
510         /* Attach the key params */
511         sw_status = p_CSwift_AttachKeyParam(hac, &sw_param);
512         switch(sw_status)
513                 {
514         case SW_OK:
515                 break;
516         case SW_ERR_INPUT_SIZE:
517                 CSWIFTerr(CSWIFT_F_CSWIFT_MOD_EXP,CSWIFT_R_BAD_KEY_SIZE);
518                 goto err;
519         default:
520                 {
521                 char tmpbuf[DECIMAL_SIZE(sw_status)+1];
522                 CSWIFTerr(CSWIFT_F_CSWIFT_MOD_EXP,CSWIFT_R_REQUEST_FAILED);
523                 sprintf(tmpbuf, "%ld", sw_status);
524                 ERR_add_error_data(2, "CryptoSwift error number is ",tmpbuf);
525                 }
526                 goto err;
527                 }
528         /* Prepare the argument and response */
529         arg.nbytes = BN_bn2bin(a, (unsigned char *)argument->d);
530         arg.value = (unsigned char *)argument->d;
531         res.nbytes = BN_num_bytes(m);
532         memset(result->d, 0, res.nbytes);
533         res.value = (unsigned char *)result->d;
534         /* Perform the operation */
535         if((sw_status = p_CSwift_SimpleRequest(hac, SW_CMD_MODEXP, &arg, 1,
536                 &res, 1)) != SW_OK)
537                 {
538                 char tmpbuf[DECIMAL_SIZE(sw_status)+1];
539                 CSWIFTerr(CSWIFT_F_CSWIFT_MOD_EXP,CSWIFT_R_REQUEST_FAILED);
540                 sprintf(tmpbuf, "%ld", sw_status);
541                 ERR_add_error_data(2, "CryptoSwift error number is ",tmpbuf);
542                 goto err;
543                 }
544         /* Convert the response */
545         BN_bin2bn((unsigned char *)result->d, res.nbytes, r);
546         to_return = 1;
547 err:
548         if(acquired)
549                 release_context(hac);
550         BN_CTX_end(ctx);
551         return to_return;
552         }
553
554 /* Un petit mod_exp chinois */
555 static int cswift_mod_exp_crt(BIGNUM *r, const BIGNUM *a, const BIGNUM *p,
556                         const BIGNUM *q, const BIGNUM *dmp1,
557                         const BIGNUM *dmq1, const BIGNUM *iqmp, BN_CTX *ctx)
558         {
559         SW_STATUS sw_status;
560         SW_LARGENUMBER arg, res;
561         SW_PARAM sw_param;
562         SW_CONTEXT_HANDLE hac;
563         BIGNUM *rsa_p = NULL;
564         BIGNUM *rsa_q = NULL;
565         BIGNUM *rsa_dmp1 = NULL;
566         BIGNUM *rsa_dmq1 = NULL;
567         BIGNUM *rsa_iqmp = NULL;
568         BIGNUM *argument = NULL;
569         BIGNUM *result = NULL;
570         int to_return = 0; /* expect failure */
571         int acquired = 0;
572  
573         if(!get_context(&hac))
574                 {
575                 CSWIFTerr(CSWIFT_F_CSWIFT_MOD_EXP_CRT,CSWIFT_R_UNIT_FAILURE);
576                 goto err;
577                 }
578         acquired = 1;
579         /* Prepare the params */
580         BN_CTX_start(ctx);
581         rsa_p = BN_CTX_get(ctx);
582         rsa_q = BN_CTX_get(ctx);
583         rsa_dmp1 = BN_CTX_get(ctx);
584         rsa_dmq1 = BN_CTX_get(ctx);
585         rsa_iqmp = BN_CTX_get(ctx);
586         argument = BN_CTX_get(ctx);
587         result = BN_CTX_get(ctx);
588         if(!result)
589                 {
590                 CSWIFTerr(CSWIFT_F_CSWIFT_MOD_EXP_CRT,CSWIFT_R_BN_CTX_FULL);
591                 goto err;
592                 }
593         if(!bn_wexpand(rsa_p, p->top) || !bn_wexpand(rsa_q, q->top) ||
594                         !bn_wexpand(rsa_dmp1, dmp1->top) ||
595                         !bn_wexpand(rsa_dmq1, dmq1->top) ||
596                         !bn_wexpand(rsa_iqmp, iqmp->top) ||
597                         !bn_wexpand(argument, a->top) ||
598                         !bn_wexpand(result, p->top + q->top))
599                 {
600                 CSWIFTerr(CSWIFT_F_CSWIFT_MOD_EXP_CRT,CSWIFT_R_BN_EXPAND_FAIL);
601                 goto err;
602                 }
603         sw_param.type = SW_ALG_CRT;
604         sw_param.up.crt.p.nbytes = BN_bn2bin(p, (unsigned char *)rsa_p->d);
605         sw_param.up.crt.p.value = (unsigned char *)rsa_p->d;
606         sw_param.up.crt.q.nbytes = BN_bn2bin(q, (unsigned char *)rsa_q->d);
607         sw_param.up.crt.q.value = (unsigned char *)rsa_q->d;
608         sw_param.up.crt.dmp1.nbytes = BN_bn2bin(dmp1,
609                 (unsigned char *)rsa_dmp1->d);
610         sw_param.up.crt.dmp1.value = (unsigned char *)rsa_dmp1->d;
611         sw_param.up.crt.dmq1.nbytes = BN_bn2bin(dmq1,
612                 (unsigned char *)rsa_dmq1->d);
613         sw_param.up.crt.dmq1.value = (unsigned char *)rsa_dmq1->d;
614         sw_param.up.crt.iqmp.nbytes = BN_bn2bin(iqmp,
615                 (unsigned char *)rsa_iqmp->d);
616         sw_param.up.crt.iqmp.value = (unsigned char *)rsa_iqmp->d;
617         /* Attach the key params */
618         sw_status = p_CSwift_AttachKeyParam(hac, &sw_param);
619         switch(sw_status)
620                 {
621         case SW_OK:
622                 break;
623         case SW_ERR_INPUT_SIZE:
624                 CSWIFTerr(CSWIFT_F_CSWIFT_MOD_EXP_CRT,CSWIFT_R_BAD_KEY_SIZE);
625                 goto err;
626         default:
627                 {
628                 char tmpbuf[DECIMAL_SIZE(sw_status)+1];
629                 CSWIFTerr(CSWIFT_F_CSWIFT_MOD_EXP_CRT,CSWIFT_R_REQUEST_FAILED);
630                 sprintf(tmpbuf, "%ld", sw_status);
631                 ERR_add_error_data(2, "CryptoSwift error number is ",tmpbuf);
632                 }
633                 goto err;
634                 }
635         /* Prepare the argument and response */
636         arg.nbytes = BN_bn2bin(a, (unsigned char *)argument->d);
637         arg.value = (unsigned char *)argument->d;
638         res.nbytes = 2 * BN_num_bytes(p);
639         memset(result->d, 0, res.nbytes);
640         res.value = (unsigned char *)result->d;
641         /* Perform the operation */
642         if((sw_status = p_CSwift_SimpleRequest(hac, SW_CMD_MODEXP_CRT, &arg, 1,
643                 &res, 1)) != SW_OK)
644                 {
645                 char tmpbuf[DECIMAL_SIZE(sw_status)+1];
646                 CSWIFTerr(CSWIFT_F_CSWIFT_MOD_EXP_CRT,CSWIFT_R_REQUEST_FAILED);
647                 sprintf(tmpbuf, "%ld", sw_status);
648                 ERR_add_error_data(2, "CryptoSwift error number is ",tmpbuf);
649                 goto err;
650                 }
651         /* Convert the response */
652         BN_bin2bn((unsigned char *)result->d, res.nbytes, r);
653         to_return = 1;
654 err:
655         if(acquired)
656                 release_context(hac);
657         BN_CTX_end(ctx);
658         return to_return;
659         }
660  
661 #ifndef OPENSSL_NO_RSA
662 static int cswift_rsa_mod_exp(BIGNUM *r0, const BIGNUM *I, RSA *rsa)
663         {
664         BN_CTX *ctx;
665         int to_return = 0;
666
667         if((ctx = BN_CTX_new()) == NULL)
668                 goto err;
669         if(!rsa->p || !rsa->q || !rsa->dmp1 || !rsa->dmq1 || !rsa->iqmp)
670                 {
671                 CSWIFTerr(CSWIFT_F_CSWIFT_RSA_MOD_EXP,CSWIFT_R_MISSING_KEY_COMPONENTS);
672                 goto err;
673                 }
674         to_return = cswift_mod_exp_crt(r0, I, rsa->p, rsa->q, rsa->dmp1,
675                 rsa->dmq1, rsa->iqmp, ctx);
676 err:
677         if(ctx)
678                 BN_CTX_free(ctx);
679         return to_return;
680         }
681 #endif
682
683 /* This function is aliased to mod_exp (with the mont stuff dropped). */
684 static int cswift_mod_exp_mont(BIGNUM *r, const BIGNUM *a, const BIGNUM *p,
685                 const BIGNUM *m, BN_CTX *ctx, BN_MONT_CTX *m_ctx)
686         {
687         return cswift_mod_exp(r, a, p, m, ctx);
688         }
689
690 #ifndef OPENSSL_NO_DSA
691 static DSA_SIG *cswift_dsa_sign(const unsigned char *dgst, int dlen, DSA *dsa)
692         {
693         SW_CONTEXT_HANDLE hac;
694         SW_PARAM sw_param;
695         SW_STATUS sw_status;
696         SW_LARGENUMBER arg, res;
697         unsigned char *ptr;
698         BN_CTX *ctx;
699         BIGNUM *dsa_p = NULL;
700         BIGNUM *dsa_q = NULL;
701         BIGNUM *dsa_g = NULL;
702         BIGNUM *dsa_key = NULL;
703         BIGNUM *result = NULL;
704         DSA_SIG *to_return = NULL;
705         int acquired = 0;
706
707         if((ctx = BN_CTX_new()) == NULL)
708                 goto err;
709         if(!get_context(&hac))
710                 {
711                 CSWIFTerr(CSWIFT_F_CSWIFT_DSA_SIGN,CSWIFT_R_UNIT_FAILURE);
712                 goto err;
713                 }
714         acquired = 1;
715         /* Prepare the params */
716         BN_CTX_start(ctx);
717         dsa_p = BN_CTX_get(ctx);
718         dsa_q = BN_CTX_get(ctx);
719         dsa_g = BN_CTX_get(ctx);
720         dsa_key = BN_CTX_get(ctx);
721         result = BN_CTX_get(ctx);
722         if(!result)
723                 {
724                 CSWIFTerr(CSWIFT_F_CSWIFT_DSA_SIGN,CSWIFT_R_BN_CTX_FULL);
725                 goto err;
726                 }
727         if(!bn_wexpand(dsa_p, dsa->p->top) ||
728                         !bn_wexpand(dsa_q, dsa->q->top) ||
729                         !bn_wexpand(dsa_g, dsa->g->top) ||
730                         !bn_wexpand(dsa_key, dsa->priv_key->top) ||
731                         !bn_wexpand(result, dsa->p->top))
732                 {
733                 CSWIFTerr(CSWIFT_F_CSWIFT_DSA_SIGN,CSWIFT_R_BN_EXPAND_FAIL);
734                 goto err;
735                 }
736         sw_param.type = SW_ALG_DSA;
737         sw_param.up.dsa.p.nbytes = BN_bn2bin(dsa->p,
738                                 (unsigned char *)dsa_p->d);
739         sw_param.up.dsa.p.value = (unsigned char *)dsa_p->d;
740         sw_param.up.dsa.q.nbytes = BN_bn2bin(dsa->q,
741                                 (unsigned char *)dsa_q->d);
742         sw_param.up.dsa.q.value = (unsigned char *)dsa_q->d;
743         sw_param.up.dsa.g.nbytes = BN_bn2bin(dsa->g,
744                                 (unsigned char *)dsa_g->d);
745         sw_param.up.dsa.g.value = (unsigned char *)dsa_g->d;
746         sw_param.up.dsa.key.nbytes = BN_bn2bin(dsa->priv_key,
747                                 (unsigned char *)dsa_key->d);
748         sw_param.up.dsa.key.value = (unsigned char *)dsa_key->d;
749         /* Attach the key params */
750         sw_status = p_CSwift_AttachKeyParam(hac, &sw_param);
751         switch(sw_status)
752                 {
753         case SW_OK:
754                 break;
755         case SW_ERR_INPUT_SIZE:
756                 CSWIFTerr(CSWIFT_F_CSWIFT_DSA_SIGN,CSWIFT_R_BAD_KEY_SIZE);
757                 goto err;
758         default:
759                 {
760                 char tmpbuf[DECIMAL_SIZE(sw_status)+1];
761                 CSWIFTerr(CSWIFT_F_CSWIFT_DSA_SIGN,CSWIFT_R_REQUEST_FAILED);
762                 sprintf(tmpbuf, "%ld", sw_status);
763                 ERR_add_error_data(2, "CryptoSwift error number is ",tmpbuf);
764                 }
765                 goto err;
766                 }
767         /* Prepare the argument and response */
768         arg.nbytes = dlen;
769         arg.value = (unsigned char *)dgst;
770         res.nbytes = BN_num_bytes(dsa->p);
771         memset(result->d, 0, res.nbytes);
772         res.value = (unsigned char *)result->d;
773         /* Perform the operation */
774         sw_status = p_CSwift_SimpleRequest(hac, SW_CMD_DSS_SIGN, &arg, 1,
775                 &res, 1);
776         if(sw_status != SW_OK)
777                 {
778                 char tmpbuf[DECIMAL_SIZE(sw_status)+1];
779                 CSWIFTerr(CSWIFT_F_CSWIFT_DSA_SIGN,CSWIFT_R_REQUEST_FAILED);
780                 sprintf(tmpbuf, "%ld", sw_status);
781                 ERR_add_error_data(2, "CryptoSwift error number is ",tmpbuf);
782                 goto err;
783                 }
784         /* Convert the response */
785         ptr = (unsigned char *)result->d;
786         if((to_return = DSA_SIG_new()) == NULL)
787                 goto err;
788         to_return->r = BN_bin2bn((unsigned char *)result->d, 20, NULL);
789         to_return->s = BN_bin2bn((unsigned char *)result->d + 20, 20, NULL);
790
791 err:
792         if(acquired)
793                 release_context(hac);
794         if(ctx)
795                 {
796                 BN_CTX_end(ctx);
797                 BN_CTX_free(ctx);
798                 }
799         return to_return;
800         }
801
802 static int cswift_dsa_verify(const unsigned char *dgst, int dgst_len,
803                                 DSA_SIG *sig, DSA *dsa)
804         {
805         SW_CONTEXT_HANDLE hac;
806         SW_PARAM sw_param;
807         SW_STATUS sw_status;
808         SW_LARGENUMBER arg[2], res;
809         unsigned long sig_result;
810         BN_CTX *ctx;
811         BIGNUM *dsa_p = NULL;
812         BIGNUM *dsa_q = NULL;
813         BIGNUM *dsa_g = NULL;
814         BIGNUM *dsa_key = NULL;
815         BIGNUM *argument = NULL;
816         int to_return = -1;
817         int acquired = 0;
818
819         if((ctx = BN_CTX_new()) == NULL)
820                 goto err;
821         if(!get_context(&hac))
822                 {
823                 CSWIFTerr(CSWIFT_F_CSWIFT_DSA_VERIFY,CSWIFT_R_UNIT_FAILURE);
824                 goto err;
825                 }
826         acquired = 1;
827         /* Prepare the params */
828         BN_CTX_start(ctx);
829         dsa_p = BN_CTX_get(ctx);
830         dsa_q = BN_CTX_get(ctx);
831         dsa_g = BN_CTX_get(ctx);
832         dsa_key = BN_CTX_get(ctx);
833         argument = BN_CTX_get(ctx);
834         if(!argument)
835                 {
836                 CSWIFTerr(CSWIFT_F_CSWIFT_DSA_VERIFY,CSWIFT_R_BN_CTX_FULL);
837                 goto err;
838                 }
839         if(!bn_wexpand(dsa_p, dsa->p->top) ||
840                         !bn_wexpand(dsa_q, dsa->q->top) ||
841                         !bn_wexpand(dsa_g, dsa->g->top) ||
842                         !bn_wexpand(dsa_key, dsa->pub_key->top) ||
843                         !bn_wexpand(argument, 40))
844                 {
845                 CSWIFTerr(CSWIFT_F_CSWIFT_DSA_VERIFY,CSWIFT_R_BN_EXPAND_FAIL);
846                 goto err;
847                 }
848         sw_param.type = SW_ALG_DSA;
849         sw_param.up.dsa.p.nbytes = BN_bn2bin(dsa->p,
850                                 (unsigned char *)dsa_p->d);
851         sw_param.up.dsa.p.value = (unsigned char *)dsa_p->d;
852         sw_param.up.dsa.q.nbytes = BN_bn2bin(dsa->q,
853                                 (unsigned char *)dsa_q->d);
854         sw_param.up.dsa.q.value = (unsigned char *)dsa_q->d;
855         sw_param.up.dsa.g.nbytes = BN_bn2bin(dsa->g,
856                                 (unsigned char *)dsa_g->d);
857         sw_param.up.dsa.g.value = (unsigned char *)dsa_g->d;
858         sw_param.up.dsa.key.nbytes = BN_bn2bin(dsa->pub_key,
859                                 (unsigned char *)dsa_key->d);
860         sw_param.up.dsa.key.value = (unsigned char *)dsa_key->d;
861         /* Attach the key params */
862         sw_status = p_CSwift_AttachKeyParam(hac, &sw_param);
863         switch(sw_status)
864                 {
865         case SW_OK:
866                 break;
867         case SW_ERR_INPUT_SIZE:
868                 CSWIFTerr(CSWIFT_F_CSWIFT_DSA_VERIFY,CSWIFT_R_BAD_KEY_SIZE);
869                 goto err;
870         default:
871                 {
872                 char tmpbuf[DECIMAL_SIZE(sw_status)+1];
873                 CSWIFTerr(CSWIFT_F_CSWIFT_DSA_VERIFY,CSWIFT_R_REQUEST_FAILED);
874                 sprintf(tmpbuf, "%ld", sw_status);
875                 ERR_add_error_data(2, "CryptoSwift error number is ",tmpbuf);
876                 }
877                 goto err;
878                 }
879         /* Prepare the argument and response */
880         arg[0].nbytes = dgst_len;
881         arg[0].value = (unsigned char *)dgst;
882         arg[1].nbytes = 40;
883         arg[1].value = (unsigned char *)argument->d;
884         memset(arg[1].value, 0, 40);
885         BN_bn2bin(sig->r, arg[1].value + 20 - BN_num_bytes(sig->r));
886         BN_bn2bin(sig->s, arg[1].value + 40 - BN_num_bytes(sig->s));
887         res.nbytes = 4; /* unsigned long */
888         res.value = (unsigned char *)(&sig_result);
889         /* Perform the operation */
890         sw_status = p_CSwift_SimpleRequest(hac, SW_CMD_DSS_VERIFY, arg, 2,
891                 &res, 1);
892         if(sw_status != SW_OK)
893                 {
894                 char tmpbuf[DECIMAL_SIZE(sw_status)+1];
895                 CSWIFTerr(CSWIFT_F_CSWIFT_DSA_VERIFY,CSWIFT_R_REQUEST_FAILED);
896                 sprintf(tmpbuf, "%ld", sw_status);
897                 ERR_add_error_data(2, "CryptoSwift error number is ",tmpbuf);
898                 goto err;
899                 }
900         /* Convert the response */
901         to_return = ((sig_result == 0) ? 0 : 1);
902
903 err:
904         if(acquired)
905                 release_context(hac);
906         if(ctx)
907                 {
908                 BN_CTX_end(ctx);
909                 BN_CTX_free(ctx);
910                 }
911         return to_return;
912         }
913 #endif
914
915 #ifndef OPENSSL_NO_DH
916 /* This function is aliased to mod_exp (with the dh and mont dropped). */
917 static int cswift_mod_exp_dh(const DH *dh, BIGNUM *r,
918                 const BIGNUM *a, const BIGNUM *p,
919                 const BIGNUM *m, BN_CTX *ctx, BN_MONT_CTX *m_ctx)
920         {
921         return cswift_mod_exp(r, a, p, m, ctx);
922         }
923 #endif
924
925 /* Random bytes are good */
926 static int cswift_rand_bytes(unsigned char *buf, int num)
927 {
928         SW_CONTEXT_HANDLE hac;
929         SW_STATUS swrc;
930         SW_LARGENUMBER largenum;
931         size_t nbytes = 0;
932         int acquired = 0;
933         int to_return = 0; /* assume failure */
934
935         if (!get_context(&hac))
936         {
937                 CSWIFTerr(CSWIFT_F_CSWIFT_CTRL, CSWIFT_R_UNIT_FAILURE);
938                 goto err;
939         }
940         acquired = 1;
941
942         while (nbytes < (size_t)num)
943         {
944                 /* tell CryptoSwift how many bytes we want and where we want it.
945                  * Note: - CryptoSwift cannot do more than 4096 bytes at a time.
946                  *       - CryptoSwift can only do multiple of 32-bits. */
947                 largenum.value = (SW_BYTE *) buf + nbytes;
948                 if (4096 > num - nbytes)
949                         largenum.nbytes = num - nbytes;
950                 else
951                         largenum.nbytes = 4096;
952
953                 swrc = p_CSwift_SimpleRequest(hac, SW_CMD_RAND, NULL, 0, &largenum, 1);
954                 if (swrc != SW_OK)
955                 {
956                         char tmpbuf[20];
957                         CSWIFTerr(CSWIFT_F_CSWIFT_CTRL, CSWIFT_R_REQUEST_FAILED);
958                         sprintf(tmpbuf, "%ld", swrc);
959                         ERR_add_error_data(2, "CryptoSwift error number is ", tmpbuf);
960                         goto err;
961                 }
962
963                 nbytes += largenum.nbytes;
964         }
965         to_return = 1;  /* success */
966
967 err:
968         if (acquired)
969                 release_context(hac);
970         return to_return;
971 }
972
973 static int cswift_rand_status(void)
974 {
975         return 1;
976 }
977
978
979 /* This stuff is needed if this ENGINE is being compiled into a self-contained
980  * shared-library. */
981 #ifdef ENGINE_DYNAMIC_SUPPORT
982 static int bind_fn(ENGINE *e, const char *id)
983         {
984         if(id && (strcmp(id, engine_cswift_id) != 0))
985                 return 0;
986         if(!bind_helper(e))
987                 return 0;
988         return 1;
989         }       
990 IMPLEMENT_DYNAMIC_CHECK_FN()
991 IMPLEMENT_DYNAMIC_BIND_FN(bind_fn)
992 #endif /* ENGINE_DYNAMIC_SUPPORT */
993
994 #endif /* !OPENSSL_NO_HW_CSWIFT */
995 #endif /* !OPENSSL_NO_HW */