Add rehash command to openssl
[openssl.git] / engines / e_gmp.c
1 /* crypto/engine/e_gmp.c */
2 /*
3  * Written by Geoff Thorpe (geoff@geoffthorpe.net) for the OpenSSL project
4  * 2003.
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 /*
61  * This engine is not (currently) compiled in by default. Do enable it,
62  * reconfigure OpenSSL with "enable-gmp -lgmp". The GMP libraries and headers
63  * must reside in one of the paths searched by the compiler/linker, otherwise
64  * paths must be specified - eg. try configuring with "enable-gmp
65  * -I<includepath> -L<libpath> -lgmp". YMMV.
66  */
67
68 /*-
69  * As for what this does - it's a largely unoptimised implementation of an
70  * ENGINE that uses the GMP library to perform RSA private key operations. To
71  * obtain more information about what "unoptimised" means, see my original mail
72  * on the subject (though ignore the build instructions which have since
73  * changed);
74  *
75  *    http://www.mail-archive.com/openssl-dev@openssl.org/msg12227.html
76  *
77  * On my athlon system at least, it appears the builtin OpenSSL code is now
78  * slightly faster, which is to say that the RSA-related MPI performance
79  * between OpenSSL's BIGNUM and GMP's mpz implementations is probably pretty
80  * balanced for this chip, and so the performance degradation in this ENGINE by
81  * having to convert to/from GMP formats (and not being able to cache
82  * montgomery forms) is probably the difference. However, if some unconfirmed
83  * reports from users is anything to go by, the situation on some other
84  * chipsets might be a good deal more favourable to the GMP version (eg. PPC).
85  * Feedback welcome. */
86
87 #include <stdio.h>
88 #include <string.h>
89 #include <openssl/crypto.h>
90 #include <openssl/buffer.h>
91 #include <openssl/engine.h>
92 #ifndef OPENSSL_NO_RSA
93 # include <openssl/rsa.h>
94 #endif
95 #include <openssl/bn.h>
96
97 #ifndef OPENSSL_NO_HW
98 # ifndef OPENSSL_NO_GMP
99
100 #  include <gmp.h>
101
102 #  define E_GMP_LIB_NAME "gmp engine"
103 #  include "e_gmp_err.c"
104
105 static int e_gmp_destroy(ENGINE *e);
106 static int e_gmp_init(ENGINE *e);
107 static int e_gmp_finish(ENGINE *e);
108 static int e_gmp_ctrl(ENGINE *e, int cmd, long i, void *p, void (*f) (void));
109
110 #  ifndef OPENSSL_NO_RSA
111 /* RSA stuff */
112 static int e_gmp_rsa_mod_exp(BIGNUM *r, const BIGNUM *I, RSA *rsa,
113                              BN_CTX *ctx);
114 static int e_gmp_rsa_finish(RSA *r);
115 #  endif
116
117 /* The definitions for control commands specific to this engine */
118 /* #define E_GMP_CMD_SO_PATH            ENGINE_CMD_BASE */
119 static const ENGINE_CMD_DEFN e_gmp_cmd_defns[] = {
120     {0, NULL, NULL, 0}
121 };
122
123 #  ifndef OPENSSL_NO_RSA
124 /* Our internal RSA_METHOD that we provide pointers to */
125 static RSA_METHOD e_gmp_rsa = {
126     "GMP RSA method",
127     NULL,
128     NULL,
129     NULL,
130     NULL,
131     e_gmp_rsa_mod_exp,
132     NULL,
133     NULL,
134     e_gmp_rsa_finish,
135     /*
136      * These flags initialise montgomery crud that GMP ignores, however it
137      * makes sure the public key ops (which are done in openssl) don't seem
138      * *slower* than usual :-)
139      */
140     RSA_FLAG_CACHE_PUBLIC | RSA_FLAG_CACHE_PRIVATE,
141     NULL,
142     NULL,
143     NULL
144 };
145 #  endif
146
147 /* Constants used when creating the ENGINE */
148 static const char *engine_e_gmp_id = "gmp";
149 static const char *engine_e_gmp_name = "GMP engine support";
150
151 /*
152  * This internal function is used by ENGINE_gmp() and possibly by the
153  * "dynamic" ENGINE support too
154  */
155 static int bind_helper(ENGINE *e)
156 {
157 #  ifndef OPENSSL_NO_RSA
158     const RSA_METHOD *meth1;
159 #  endif
160     if (!ENGINE_set_id(e, engine_e_gmp_id) ||
161         !ENGINE_set_name(e, engine_e_gmp_name) ||
162 #  ifndef OPENSSL_NO_RSA
163         !ENGINE_set_RSA(e, &e_gmp_rsa) ||
164 #  endif
165         !ENGINE_set_destroy_function(e, e_gmp_destroy) ||
166         !ENGINE_set_init_function(e, e_gmp_init) ||
167         !ENGINE_set_finish_function(e, e_gmp_finish) ||
168         !ENGINE_set_ctrl_function(e, e_gmp_ctrl) ||
169         !ENGINE_set_cmd_defns(e, e_gmp_cmd_defns))
170         return 0;
171
172 #  ifndef OPENSSL_NO_RSA
173     meth1 = RSA_PKCS1_SSLeay();
174     e_gmp_rsa.rsa_pub_enc = meth1->rsa_pub_enc;
175     e_gmp_rsa.rsa_pub_dec = meth1->rsa_pub_dec;
176     e_gmp_rsa.rsa_priv_enc = meth1->rsa_priv_enc;
177     e_gmp_rsa.rsa_priv_dec = meth1->rsa_priv_dec;
178     e_gmp_rsa.bn_mod_exp = meth1->bn_mod_exp;
179 #  endif
180
181     /* Ensure the e_gmp error handling is set up */
182     ERR_load_GMP_strings();
183     return 1;
184 }
185
186 static ENGINE *engine_gmp(void)
187 {
188     ENGINE *ret = ENGINE_new();
189     if (!ret)
190         return NULL;
191     if (!bind_helper(ret)) {
192         ENGINE_free(ret);
193         return NULL;
194     }
195     return ret;
196 }
197
198 void ENGINE_load_gmp(void)
199 {
200     /* Copied from eng_[openssl|dyn].c */
201     ENGINE *toadd = engine_gmp();
202     if (!toadd)
203         return;
204     ENGINE_add(toadd);
205     ENGINE_free(toadd);
206     ERR_clear_error();
207 }
208
209 #  ifndef OPENSSL_NO_RSA
210 /* Used to attach our own key-data to an RSA structure */
211 static int hndidx_rsa = -1;
212 #  endif
213
214 static int e_gmp_destroy(ENGINE *e)
215 {
216     ERR_unload_GMP_strings();
217     return 1;
218 }
219
220 /* (de)initialisation functions. */
221 static int e_gmp_init(ENGINE *e)
222 {
223 #  ifndef OPENSSL_NO_RSA
224     if (hndidx_rsa == -1)
225         hndidx_rsa = RSA_get_ex_new_index(0,
226                                           "GMP-based RSA key handle",
227                                           NULL, NULL, NULL);
228 #  endif
229     if (hndidx_rsa == -1)
230         return 0;
231     return 1;
232 }
233
234 static int e_gmp_finish(ENGINE *e)
235 {
236     return 1;
237 }
238
239 static int e_gmp_ctrl(ENGINE *e, int cmd, long i, void *p, void (*f) (void))
240 {
241     int to_return = 1;
242
243     switch (cmd) {
244         /* The command isn't understood by this engine */
245     default:
246         GMPerr(GMP_F_E_GMP_CTRL, GMP_R_CTRL_COMMAND_NOT_IMPLEMENTED);
247         to_return = 0;
248         break;
249     }
250
251     return to_return;
252 }
253
254 /*
255  * Most often limb sizes will be the same. If not, we use hex conversion
256  * which is neat, but extremely inefficient.
257  */
258 static int bn2gmp(const BIGNUM *bn, mpz_t g)
259 {
260     bn_check_top(bn);
261     if (((sizeof(bn->d[0]) * 8) == GMP_NUMB_BITS) &&
262         (BN_BITS2 == GMP_NUMB_BITS)) {
263         /* The common case */
264         if (!_mpz_realloc(g, bn->top))
265             return 0;
266         memcpy(&g->_mp_d[0], &bn->d[0], bn->top * sizeof(bn->d[0]));
267         g->_mp_size = bn->top;
268         if (bn->neg)
269             g->_mp_size = -g->_mp_size;
270         return 1;
271     } else {
272         int toret;
273         char *tmpchar = BN_bn2hex(bn);
274         if (!tmpchar)
275             return 0;
276         toret = (mpz_set_str(g, tmpchar, 16) == 0 ? 1 : 0);
277         OPENSSL_free(tmpchar);
278         return toret;
279     }
280 }
281
282 static int gmp2bn(mpz_t g, BIGNUM *bn)
283 {
284     if (((sizeof(bn->d[0]) * 8) == GMP_NUMB_BITS) &&
285         (BN_BITS2 == GMP_NUMB_BITS)) {
286         /* The common case */
287         int s = (g->_mp_size >= 0) ? g->_mp_size : -g->_mp_size;
288         BN_zero(bn);
289         if (bn_expand2(bn, s) == NULL)
290             return 0;
291         bn->top = s;
292         memcpy(&bn->d[0], &g->_mp_d[0], s * sizeof(bn->d[0]));
293         bn_correct_top(bn);
294         bn->neg = g->_mp_size >= 0 ? 0 : 1;
295         return 1;
296     } else {
297         int toret;
298         char *tmpchar = OPENSSL_malloc(mpz_sizeinbase(g, 16) + 10);
299         if (!tmpchar)
300             return 0;
301         mpz_get_str(tmpchar, 16, g);
302         toret = BN_hex2bn(&bn, tmpchar);
303         OPENSSL_free(tmpchar);
304         return toret;
305     }
306 }
307
308 #  ifndef OPENSSL_NO_RSA
309 typedef struct st_e_gmp_rsa_ctx {
310     int public_only;
311     mpz_t n;
312     mpz_t d;
313     mpz_t e;
314     mpz_t p;
315     mpz_t q;
316     mpz_t dmp1;
317     mpz_t dmq1;
318     mpz_t iqmp;
319     mpz_t r0, r1, I0, m1;
320 } E_GMP_RSA_CTX;
321
322 static E_GMP_RSA_CTX *e_gmp_get_rsa(RSA *rsa)
323 {
324     E_GMP_RSA_CTX *hptr = RSA_get_ex_data(rsa, hndidx_rsa);
325
326     if (hptr)
327         return hptr;
328     hptr = OPENSSL_malloc(sizeof(*hptr));
329     if (!hptr)
330         return NULL;
331     /*
332      * These inits could probably be replaced by more intelligent mpz_init2()
333      * versions, to reduce malloc-thrashing.
334      */
335     mpz_init(hptr->n);
336     mpz_init(hptr->d);
337     mpz_init(hptr->e);
338     mpz_init(hptr->p);
339     mpz_init(hptr->q);
340     mpz_init(hptr->dmp1);
341     mpz_init(hptr->dmq1);
342     mpz_init(hptr->iqmp);
343     mpz_init(hptr->r0);
344     mpz_init(hptr->r1);
345     mpz_init(hptr->I0);
346     mpz_init(hptr->m1);
347     if (!bn2gmp(rsa->n, hptr->n) || !bn2gmp(rsa->e, hptr->e))
348         goto err;
349     if (!rsa->p || !rsa->q || !rsa->d || !rsa->dmp1 || !rsa->dmq1
350         || !rsa->iqmp) {
351         hptr->public_only = 1;
352         return hptr;
353     }
354     if (!bn2gmp(rsa->d, hptr->d) || !bn2gmp(rsa->p, hptr->p) ||
355         !bn2gmp(rsa->q, hptr->q) || !bn2gmp(rsa->dmp1, hptr->dmp1) ||
356         !bn2gmp(rsa->dmq1, hptr->dmq1) || !bn2gmp(rsa->iqmp, hptr->iqmp))
357         goto err;
358     hptr->public_only = 0;
359     RSA_set_ex_data(rsa, hndidx_rsa, hptr);
360     return hptr;
361  err:
362     mpz_clear(hptr->n);
363     mpz_clear(hptr->d);
364     mpz_clear(hptr->e);
365     mpz_clear(hptr->p);
366     mpz_clear(hptr->q);
367     mpz_clear(hptr->dmp1);
368     mpz_clear(hptr->dmq1);
369     mpz_clear(hptr->iqmp);
370     mpz_clear(hptr->r0);
371     mpz_clear(hptr->r1);
372     mpz_clear(hptr->I0);
373     mpz_clear(hptr->m1);
374     OPENSSL_free(hptr);
375     return NULL;
376 }
377
378 static int e_gmp_rsa_finish(RSA *rsa)
379 {
380     E_GMP_RSA_CTX *hptr = RSA_get_ex_data(rsa, hndidx_rsa);
381     if (!hptr)
382         return 0;
383     mpz_clear(hptr->n);
384     mpz_clear(hptr->d);
385     mpz_clear(hptr->e);
386     mpz_clear(hptr->p);
387     mpz_clear(hptr->q);
388     mpz_clear(hptr->dmp1);
389     mpz_clear(hptr->dmq1);
390     mpz_clear(hptr->iqmp);
391     mpz_clear(hptr->r0);
392     mpz_clear(hptr->r1);
393     mpz_clear(hptr->I0);
394     mpz_clear(hptr->m1);
395     OPENSSL_free(hptr);
396     RSA_set_ex_data(rsa, hndidx_rsa, NULL);
397     return 1;
398 }
399
400 static int e_gmp_rsa_mod_exp(BIGNUM *r, const BIGNUM *I, RSA *rsa,
401                              BN_CTX *ctx)
402 {
403     E_GMP_RSA_CTX *hptr;
404     int to_return = 0;
405
406     hptr = e_gmp_get_rsa(rsa);
407     if (!hptr) {
408         GMPerr(GMP_F_E_GMP_RSA_MOD_EXP, GMP_R_KEY_CONTEXT_ERROR);
409         return 0;
410     }
411     if (hptr->public_only) {
412         GMPerr(GMP_F_E_GMP_RSA_MOD_EXP, GMP_R_MISSING_KEY_COMPONENTS);
413         return 0;
414     }
415
416     /* ugh!!! */
417     if (!bn2gmp(I, hptr->I0))
418         return 0;
419
420     /*
421      * This is basically the CRT logic in crypto/rsa/rsa_eay.c reworded into
422      * GMP-speak. It may be that GMP's API facilitates cleaner formulations
423      * of this stuff, eg. better handling of negatives, or functions that
424      * combine operations.
425      */
426
427     mpz_mod(hptr->r1, hptr->I0, hptr->q);
428     mpz_powm(hptr->m1, hptr->r1, hptr->dmq1, hptr->q);
429
430     mpz_mod(hptr->r1, hptr->I0, hptr->p);
431     mpz_powm(hptr->r0, hptr->r1, hptr->dmp1, hptr->p);
432
433     mpz_sub(hptr->r0, hptr->r0, hptr->m1);
434
435     if (mpz_sgn(hptr->r0) < 0)
436         mpz_add(hptr->r0, hptr->r0, hptr->p);
437     mpz_mul(hptr->r1, hptr->r0, hptr->iqmp);
438     mpz_mod(hptr->r0, hptr->r1, hptr->p);
439
440     if (mpz_sgn(hptr->r0) < 0)
441         mpz_add(hptr->r0, hptr->r0, hptr->p);
442     mpz_mul(hptr->r1, hptr->r0, hptr->q);
443     mpz_add(hptr->r0, hptr->r1, hptr->m1);
444
445     /* ugh!!! */
446     if (gmp2bn(hptr->r0, r))
447         to_return = 1;
448
449     return 1;
450 }
451 #  endif
452
453 # endif                         /* !OPENSSL_NO_GMP */
454
455 /*
456  * This stuff is needed if this ENGINE is being compiled into a
457  * self-contained shared-library.
458  */
459 # ifndef OPENSSL_NO_DYNAMIC_ENGINE
460 IMPLEMENT_DYNAMIC_CHECK_FN()
461 #  ifndef OPENSSL_NO_GMP
462 static int bind_fn(ENGINE *e, const char *id)
463 {
464     if (id && (strcmp(id, engine_e_gmp_id) != 0))
465         return 0;
466     if (!bind_helper(e))
467         return 0;
468     return 1;
469 }
470
471 IMPLEMENT_DYNAMIC_BIND_FN(bind_fn)
472 #  else
473 OPENSSL_EXPORT
474     int bind_engine(ENGINE *e, const char *id, const dynamic_fns *fns);
475 OPENSSL_EXPORT
476     int bind_engine(ENGINE *e, const char *id, const dynamic_fns *fns)
477 {
478     return 0;
479 }
480 #  endif
481 # endif                         /* !OPENSSL_NO_DYNAMIC_ENGINE */
482
483 #endif                          /* !OPENSSL_NO_HW */