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
105static int e_gmp_destroy(ENGINE *e);
106static int e_gmp_init(ENGINE *e);
107static int e_gmp_finish(ENGINE *e);
108static int e_gmp_ctrl(ENGINE *e, int cmd, long i, void *p, void (*f) (void));
109
110#  ifndef OPENSSL_NO_RSA
111/* RSA stuff */
112static int e_gmp_rsa_mod_exp(BIGNUM *r, const BIGNUM *I, RSA *rsa,
113                             BN_CTX *ctx);
114static 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 */
119static const ENGINE_CMD_DEFN e_gmp_cmd_defns[] = {
120#  if 0
121    {E_GMP_CMD_SO_PATH,
122     "SO_PATH",
123     "Specifies the path to the 'e_gmp' shared library",
124     ENGINE_CMD_FLAG_STRING},
125#  endif
126    {0, NULL, NULL, 0}
127};
128
129#  ifndef OPENSSL_NO_RSA
130/* Our internal RSA_METHOD that we provide pointers to */
131static RSA_METHOD e_gmp_rsa = {
132    "GMP RSA method",
133    NULL,
134    NULL,
135    NULL,
136    NULL,
137    e_gmp_rsa_mod_exp,
138    NULL,
139    NULL,
140    e_gmp_rsa_finish,
141    /*
142     * These flags initialise montgomery crud that GMP ignores, however it
143     * makes sure the public key ops (which are done in openssl) don't seem
144     * *slower* than usual :-)
145     */
146    RSA_FLAG_CACHE_PUBLIC | RSA_FLAG_CACHE_PRIVATE,
147    NULL,
148    NULL,
149    NULL
150};
151#  endif
152
153/* Constants used when creating the ENGINE */
154static const char *engine_e_gmp_id = "gmp";
155static const char *engine_e_gmp_name = "GMP engine support";
156
157/*
158 * This internal function is used by ENGINE_gmp() and possibly by the
159 * "dynamic" ENGINE support too
160 */
161static int bind_helper(ENGINE *e)
162{
163#  ifndef OPENSSL_NO_RSA
164    const RSA_METHOD *meth1;
165#  endif
166    if (!ENGINE_set_id(e, engine_e_gmp_id) ||
167        !ENGINE_set_name(e, engine_e_gmp_name) ||
168#  ifndef OPENSSL_NO_RSA
169        !ENGINE_set_RSA(e, &e_gmp_rsa) ||
170#  endif
171        !ENGINE_set_destroy_function(e, e_gmp_destroy) ||
172        !ENGINE_set_init_function(e, e_gmp_init) ||
173        !ENGINE_set_finish_function(e, e_gmp_finish) ||
174        !ENGINE_set_ctrl_function(e, e_gmp_ctrl) ||
175        !ENGINE_set_cmd_defns(e, e_gmp_cmd_defns))
176        return 0;
177
178#  ifndef OPENSSL_NO_RSA
179    meth1 = RSA_PKCS1_SSLeay();
180    e_gmp_rsa.rsa_pub_enc = meth1->rsa_pub_enc;
181    e_gmp_rsa.rsa_pub_dec = meth1->rsa_pub_dec;
182    e_gmp_rsa.rsa_priv_enc = meth1->rsa_priv_enc;
183    e_gmp_rsa.rsa_priv_dec = meth1->rsa_priv_dec;
184    e_gmp_rsa.bn_mod_exp = meth1->bn_mod_exp;
185#  endif
186
187    /* Ensure the e_gmp error handling is set up */
188    ERR_load_GMP_strings();
189    return 1;
190}
191
192static ENGINE *engine_gmp(void)
193{
194    ENGINE *ret = ENGINE_new();
195    if (!ret)
196        return NULL;
197    if (!bind_helper(ret)) {
198        ENGINE_free(ret);
199        return NULL;
200    }
201    return ret;
202}
203
204void ENGINE_load_gmp(void)
205{
206    /* Copied from eng_[openssl|dyn].c */
207    ENGINE *toadd = engine_gmp();
208    if (!toadd)
209        return;
210    ENGINE_add(toadd);
211    ENGINE_free(toadd);
212    ERR_clear_error();
213}
214
215#  ifndef OPENSSL_NO_RSA
216/* Used to attach our own key-data to an RSA structure */
217static int hndidx_rsa = -1;
218#  endif
219
220static int e_gmp_destroy(ENGINE *e)
221{
222    ERR_unload_GMP_strings();
223    return 1;
224}
225
226/* (de)initialisation functions. */
227static int e_gmp_init(ENGINE *e)
228{
229#  ifndef OPENSSL_NO_RSA
230    if (hndidx_rsa == -1)
231        hndidx_rsa = RSA_get_ex_new_index(0,
232                                          "GMP-based RSA key handle",
233                                          NULL, NULL, NULL);
234#  endif
235    if (hndidx_rsa == -1)
236        return 0;
237    return 1;
238}
239
240static int e_gmp_finish(ENGINE *e)
241{
242    return 1;
243}
244
245static int e_gmp_ctrl(ENGINE *e, int cmd, long i, void *p, void (*f) (void))
246{
247    int to_return = 1;
248
249    switch (cmd) {
250#  if 0
251    case E_GMP_CMD_SO_PATH:
252        /* ... */
253#  endif
254        /* The command isn't understood by this engine */
255    default:
256        GMPerr(GMP_F_E_GMP_CTRL, GMP_R_CTRL_COMMAND_NOT_IMPLEMENTED);
257        to_return = 0;
258        break;
259    }
260
261    return to_return;
262}
263
264/*
265 * Most often limb sizes will be the same. If not, we use hex conversion
266 * which is neat, but extremely inefficient.
267 */
268static int bn2gmp(const BIGNUM *bn, mpz_t g)
269{
270    bn_check_top(bn);
271    if (((sizeof(bn->d[0]) * 8) == GMP_NUMB_BITS) &&
272        (BN_BITS2 == GMP_NUMB_BITS)) {
273        /* The common case */
274        if (!_mpz_realloc(g, bn->top))
275            return 0;
276        memcpy(&g->_mp_d[0], &bn->d[0], bn->top * sizeof(bn->d[0]));
277        g->_mp_size = bn->top;
278        if (bn->neg)
279            g->_mp_size = -g->_mp_size;
280        return 1;
281    } else {
282        int toret;
283        char *tmpchar = BN_bn2hex(bn);
284        if (!tmpchar)
285            return 0;
286        toret = (mpz_set_str(g, tmpchar, 16) == 0 ? 1 : 0);
287        OPENSSL_free(tmpchar);
288        return toret;
289    }
290}
291
292static int gmp2bn(mpz_t g, BIGNUM *bn)
293{
294    if (((sizeof(bn->d[0]) * 8) == GMP_NUMB_BITS) &&
295        (BN_BITS2 == GMP_NUMB_BITS)) {
296        /* The common case */
297        int s = (g->_mp_size >= 0) ? g->_mp_size : -g->_mp_size;
298        BN_zero(bn);
299        if (bn_expand2(bn, s) == NULL)
300            return 0;
301        bn->top = s;
302        memcpy(&bn->d[0], &g->_mp_d[0], s * sizeof(bn->d[0]));
303        bn_correct_top(bn);
304        bn->neg = g->_mp_size >= 0 ? 0 : 1;
305        return 1;
306    } else {
307        int toret;
308        char *tmpchar = OPENSSL_malloc(mpz_sizeinbase(g, 16) + 10);
309        if (!tmpchar)
310            return 0;
311        mpz_get_str(tmpchar, 16, g);
312        toret = BN_hex2bn(&bn, tmpchar);
313        OPENSSL_free(tmpchar);
314        return toret;
315    }
316}
317
318#  ifndef OPENSSL_NO_RSA
319typedef struct st_e_gmp_rsa_ctx {
320    int public_only;
321    mpz_t n;
322    mpz_t d;
323    mpz_t e;
324    mpz_t p;
325    mpz_t q;
326    mpz_t dmp1;
327    mpz_t dmq1;
328    mpz_t iqmp;
329    mpz_t r0, r1, I0, m1;
330} E_GMP_RSA_CTX;
331
332static E_GMP_RSA_CTX *e_gmp_get_rsa(RSA *rsa)
333{
334    E_GMP_RSA_CTX *hptr = RSA_get_ex_data(rsa, hndidx_rsa);
335    if (hptr)
336        return hptr;
337    hptr = OPENSSL_malloc(sizeof(E_GMP_RSA_CTX));
338    if (!hptr)
339        return NULL;
340    /*
341     * These inits could probably be replaced by more intelligent mpz_init2()
342     * versions, to reduce malloc-thrashing.
343     */
344    mpz_init(hptr->n);
345    mpz_init(hptr->d);
346    mpz_init(hptr->e);
347    mpz_init(hptr->p);
348    mpz_init(hptr->q);
349    mpz_init(hptr->dmp1);
350    mpz_init(hptr->dmq1);
351    mpz_init(hptr->iqmp);
352    mpz_init(hptr->r0);
353    mpz_init(hptr->r1);
354    mpz_init(hptr->I0);
355    mpz_init(hptr->m1);
356    if (!bn2gmp(rsa->n, hptr->n) || !bn2gmp(rsa->e, hptr->e))
357        goto err;
358    if (!rsa->p || !rsa->q || !rsa->d || !rsa->dmp1 || !rsa->dmq1
359        || !rsa->iqmp) {
360        hptr->public_only = 1;
361        return hptr;
362    }
363    if (!bn2gmp(rsa->d, hptr->d) || !bn2gmp(rsa->p, hptr->p) ||
364        !bn2gmp(rsa->q, hptr->q) || !bn2gmp(rsa->dmp1, hptr->dmp1) ||
365        !bn2gmp(rsa->dmq1, hptr->dmq1) || !bn2gmp(rsa->iqmp, hptr->iqmp))
366        goto err;
367    hptr->public_only = 0;
368    RSA_set_ex_data(rsa, hndidx_rsa, hptr);
369    return hptr;
370 err:
371    mpz_clear(hptr->n);
372    mpz_clear(hptr->d);
373    mpz_clear(hptr->e);
374    mpz_clear(hptr->p);
375    mpz_clear(hptr->q);
376    mpz_clear(hptr->dmp1);
377    mpz_clear(hptr->dmq1);
378    mpz_clear(hptr->iqmp);
379    mpz_clear(hptr->r0);
380    mpz_clear(hptr->r1);
381    mpz_clear(hptr->I0);
382    mpz_clear(hptr->m1);
383    OPENSSL_free(hptr);
384    return NULL;
385}
386
387static int e_gmp_rsa_finish(RSA *rsa)
388{
389    E_GMP_RSA_CTX *hptr = RSA_get_ex_data(rsa, hndidx_rsa);
390    if (!hptr)
391        return 0;
392    mpz_clear(hptr->n);
393    mpz_clear(hptr->d);
394    mpz_clear(hptr->e);
395    mpz_clear(hptr->p);
396    mpz_clear(hptr->q);
397    mpz_clear(hptr->dmp1);
398    mpz_clear(hptr->dmq1);
399    mpz_clear(hptr->iqmp);
400    mpz_clear(hptr->r0);
401    mpz_clear(hptr->r1);
402    mpz_clear(hptr->I0);
403    mpz_clear(hptr->m1);
404    OPENSSL_free(hptr);
405    RSA_set_ex_data(rsa, hndidx_rsa, NULL);
406    return 1;
407}
408
409static int e_gmp_rsa_mod_exp(BIGNUM *r, const BIGNUM *I, RSA *rsa,
410                             BN_CTX *ctx)
411{
412    E_GMP_RSA_CTX *hptr;
413    int to_return = 0;
414
415    hptr = e_gmp_get_rsa(rsa);
416    if (!hptr) {
417        GMPerr(GMP_F_E_GMP_RSA_MOD_EXP, GMP_R_KEY_CONTEXT_ERROR);
418        return 0;
419    }
420    if (hptr->public_only) {
421        GMPerr(GMP_F_E_GMP_RSA_MOD_EXP, GMP_R_MISSING_KEY_COMPONENTS);
422        return 0;
423    }
424
425    /* ugh!!! */
426    if (!bn2gmp(I, hptr->I0))
427        return 0;
428
429    /*
430     * This is basically the CRT logic in crypto/rsa/rsa_eay.c reworded into
431     * GMP-speak. It may be that GMP's API facilitates cleaner formulations
432     * of this stuff, eg. better handling of negatives, or functions that
433     * combine operations.
434     */
435
436    mpz_mod(hptr->r1, hptr->I0, hptr->q);
437    mpz_powm(hptr->m1, hptr->r1, hptr->dmq1, hptr->q);
438
439    mpz_mod(hptr->r1, hptr->I0, hptr->p);
440    mpz_powm(hptr->r0, hptr->r1, hptr->dmp1, hptr->p);
441
442    mpz_sub(hptr->r0, hptr->r0, hptr->m1);
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->iqmp);
447    mpz_mod(hptr->r0, hptr->r1, hptr->p);
448
449    if (mpz_sgn(hptr->r0) < 0)
450        mpz_add(hptr->r0, hptr->r0, hptr->p);
451    mpz_mul(hptr->r1, hptr->r0, hptr->q);
452    mpz_add(hptr->r0, hptr->r1, hptr->m1);
453
454    /* ugh!!! */
455    if (gmp2bn(hptr->r0, r))
456        to_return = 1;
457
458    return 1;
459}
460#  endif
461
462# endif                         /* !OPENSSL_NO_GMP */
463
464/*
465 * This stuff is needed if this ENGINE is being compiled into a
466 * self-contained shared-library.
467 */
468# ifndef OPENSSL_NO_DYNAMIC_ENGINE
469IMPLEMENT_DYNAMIC_CHECK_FN()
470#  ifndef OPENSSL_NO_GMP
471static int bind_fn(ENGINE *e, const char *id)
472{
473    if (id && (strcmp(id, engine_e_gmp_id) != 0))
474        return 0;
475    if (!bind_helper(e))
476        return 0;
477    return 1;
478}
479
480IMPLEMENT_DYNAMIC_BIND_FN(bind_fn)
481#  else
482OPENSSL_EXPORT
483    int bind_engine(ENGINE *e, const char *id, const dynamic_fns *fns);
484OPENSSL_EXPORT
485    int bind_engine(ENGINE *e, const char *id, const dynamic_fns *fns)
486{
487    return 0;
488}
489#  endif
490# endif                         /* !OPENSSL_NO_DYNAMIC_ENGINE */
491
492#endif                          /* !OPENSSL_NO_HW */
493