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