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