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