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