Some more tweaks to ENGINE code.
[openssl.git] / crypto / engine / hw_atalla.c
1 /* crypto/engine/hw_atalla.c */
2 /* Written by Geoff Thorpe (geoff@geoffthorpe.net) for the OpenSSL
3  * project 2000.
4  */
5 /* ====================================================================
6  * Copyright (c) 1999 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 <openssl/crypto.h>
61 #include "cryptlib.h"
62 #include <openssl/dso.h>
63 #include <openssl/engine.h>
64
65 #ifndef OPENSSL_NO_HW
66 #ifndef OPENSSL_NO_HW_ATALLA
67
68 #ifdef FLAT_INC
69 #include "atalla.h"
70 #else
71 #include "vendor_defns/atalla.h"
72 #endif
73
74 static int atalla_init(ENGINE *e);
75 static int atalla_finish(ENGINE *e);
76 static int atalla_ctrl(ENGINE *e, int cmd, long i, void *p, void (*f)());
77
78 /* BIGNUM stuff */
79 static int atalla_mod_exp(BIGNUM *r, const BIGNUM *a, const BIGNUM *p,
80                 const BIGNUM *m, BN_CTX *ctx);
81
82 /* RSA stuff */
83 static int atalla_rsa_mod_exp(BIGNUM *r0, const BIGNUM *I, RSA *rsa);
84 /* This function is aliased to mod_exp (with the mont stuff dropped). */
85 static int atalla_mod_exp_mont(BIGNUM *r, const BIGNUM *a, const BIGNUM *p,
86                 const BIGNUM *m, BN_CTX *ctx, BN_MONT_CTX *m_ctx);
87
88 /* DSA stuff */
89 static int atalla_dsa_mod_exp(DSA *dsa, BIGNUM *rr, BIGNUM *a1,
90                 BIGNUM *p1, BIGNUM *a2, BIGNUM *p2, BIGNUM *m,
91                 BN_CTX *ctx, BN_MONT_CTX *in_mont);
92 static int atalla_mod_exp_dsa(DSA *dsa, BIGNUM *r, BIGNUM *a,
93                 const BIGNUM *p, const BIGNUM *m, BN_CTX *ctx,
94                 BN_MONT_CTX *m_ctx);
95
96 /* DH stuff */
97 /* This function is alised to mod_exp (with the DH and mont dropped). */
98 static int atalla_mod_exp_dh(const DH *dh, BIGNUM *r,
99                 const BIGNUM *a, const BIGNUM *p,
100                 const BIGNUM *m, BN_CTX *ctx, BN_MONT_CTX *m_ctx);
101
102 /* The definitions for control commands specific to this engine */
103 #define ATALLA_CMD_SO_PATH              ENGINE_CMD_BASE
104 static const ENGINE_CMD_DEFN atalla_cmd_defns[] = {
105         {ATALLA_CMD_SO_PATH,
106                 "SO_PATH",
107                 "Specifies the path to the 'atasi' shared library",
108                 ENGINE_CMD_FLAG_STRING},
109         {0, NULL, NULL, 0}
110         };
111
112 /* Our internal RSA_METHOD that we provide pointers to */
113 static RSA_METHOD atalla_rsa =
114         {
115         "Atalla RSA method",
116         NULL,
117         NULL,
118         NULL,
119         NULL,
120         atalla_rsa_mod_exp,
121         atalla_mod_exp_mont,
122         NULL,
123         NULL,
124         0,
125         NULL,
126         NULL,
127         NULL
128         };
129
130 /* Our internal DSA_METHOD that we provide pointers to */
131 static DSA_METHOD atalla_dsa =
132         {
133         "Atalla DSA method",
134         NULL, /* dsa_do_sign */
135         NULL, /* dsa_sign_setup */
136         NULL, /* dsa_do_verify */
137         atalla_dsa_mod_exp, /* dsa_mod_exp */
138         atalla_mod_exp_dsa, /* bn_mod_exp */
139         NULL, /* init */
140         NULL, /* finish */
141         0, /* flags */
142         NULL /* app_data */
143         };
144
145 /* Our internal DH_METHOD that we provide pointers to */
146 static DH_METHOD atalla_dh =
147         {
148         "Atalla DH method",
149         NULL,
150         NULL,
151         atalla_mod_exp_dh,
152         NULL,
153         NULL,
154         0,
155         NULL
156         };
157
158 /* Constants used when creating the ENGINE */
159 static const char *engine_atalla_id = "atalla";
160 static const char *engine_atalla_name = "Atalla hardware engine support";
161
162 /* As this is only ever called once, there's no need for locking
163  * (indeed - the lock will already be held by our caller!!!) */
164 ENGINE *ENGINE_atalla()
165         {
166         const RSA_METHOD *meth1;
167         const DSA_METHOD *meth2;
168         const DH_METHOD *meth3;
169         ENGINE *ret = ENGINE_new();
170         if(!ret)
171                 return NULL;
172         if(!ENGINE_set_id(ret, engine_atalla_id) ||
173                         !ENGINE_set_name(ret, engine_atalla_name) ||
174                         !ENGINE_set_RSA(ret, &atalla_rsa) ||
175                         !ENGINE_set_DSA(ret, &atalla_dsa) ||
176                         !ENGINE_set_DH(ret, &atalla_dh) ||
177                         !ENGINE_set_BN_mod_exp(ret, atalla_mod_exp) ||
178                         !ENGINE_set_init_function(ret, atalla_init) ||
179                         !ENGINE_set_finish_function(ret, atalla_finish) ||
180                         !ENGINE_set_ctrl_function(ret, atalla_ctrl) ||
181                         !ENGINE_set_cmd_defns(ret, atalla_cmd_defns))
182                 {
183                 ENGINE_free(ret);
184                 return NULL;
185                 }
186
187         /* We know that the "PKCS1_SSLeay()" functions hook properly
188          * to the atalla-specific mod_exp and mod_exp_crt so we use
189          * those functions. NB: We don't use ENGINE_openssl() or
190          * anything "more generic" because something like the RSAref
191          * code may not hook properly, and if you own one of these
192          * cards then you have the right to do RSA operations on it
193          * anyway! */ 
194         meth1 = RSA_PKCS1_SSLeay();
195         atalla_rsa.rsa_pub_enc = meth1->rsa_pub_enc;
196         atalla_rsa.rsa_pub_dec = meth1->rsa_pub_dec;
197         atalla_rsa.rsa_priv_enc = meth1->rsa_priv_enc;
198         atalla_rsa.rsa_priv_dec = meth1->rsa_priv_dec;
199
200         /* Use the DSA_OpenSSL() method and just hook the mod_exp-ish
201          * bits. */
202         meth2 = DSA_OpenSSL();
203         atalla_dsa.dsa_do_sign = meth2->dsa_do_sign;
204         atalla_dsa.dsa_sign_setup = meth2->dsa_sign_setup;
205         atalla_dsa.dsa_do_verify = meth2->dsa_do_verify;
206
207         /* Much the same for Diffie-Hellman */
208         meth3 = DH_OpenSSL();
209         atalla_dh.generate_key = meth3->generate_key;
210         atalla_dh.compute_key = meth3->compute_key;
211         return ret;
212         }
213
214 /* This is a process-global DSO handle used for loading and unloading
215  * the Atalla library. NB: This is only set (or unset) during an
216  * init() or finish() call (reference counts permitting) and they're
217  * operating with global locks, so this should be thread-safe
218  * implicitly. */
219 static DSO *atalla_dso = NULL;
220
221 /* These are the function pointers that are (un)set when the library has
222  * successfully (un)loaded. */
223 static tfnASI_GetHardwareConfig *p_Atalla_GetHardwareConfig = NULL;
224 static tfnASI_RSAPrivateKeyOpFn *p_Atalla_RSAPrivateKeyOpFn = NULL;
225 static tfnASI_GetPerformanceStatistics *p_Atalla_GetPerformanceStatistics = NULL;
226
227 /* These are the static string constants for the DSO file name and the function
228  * symbol names to bind to. Regrettably, the DSO name on *nix appears to be
229  * "atasi.so" rather than something more consistent like "libatasi.so". At the
230  * time of writing, I'm not sure what the file name on win32 is but clearly
231  * native name translation is not possible (eg libatasi.so on *nix, and
232  * atasi.dll on win32). For the purposes of testing, I have created a symbollic
233  * link called "libatasi.so" so that we can use native name-translation - a
234  * better solution will be needed. */
235 static const char def_ATALLA_LIBNAME[] = "atasi";
236 static const char *ATALLA_LIBNAME = def_ATALLA_LIBNAME;
237 static const char *ATALLA_F1 = "ASI_GetHardwareConfig";
238 static const char *ATALLA_F2 = "ASI_RSAPrivateKeyOpFn";
239 static const char *ATALLA_F3 = "ASI_GetPerformanceStatistics";
240
241 /* (de)initialisation functions. */
242 static int atalla_init(ENGINE *e)
243         {
244         tfnASI_GetHardwareConfig *p1;
245         tfnASI_RSAPrivateKeyOpFn *p2;
246         tfnASI_GetPerformanceStatistics *p3;
247         /* Not sure of the origin of this magic value, but Ben's code had it
248          * and it seemed to have been working for a few people. :-) */
249         unsigned int config_buf[1024];
250
251         if(atalla_dso != NULL)
252                 {
253                 ENGINEerr(ENGINE_F_ATALLA_INIT,ENGINE_R_ALREADY_LOADED);
254                 goto err;
255                 }
256         /* Attempt to load libatasi.so/atasi.dll/whatever. Needs to be
257          * changed unfortunately because the Atalla drivers don't have
258          * standard library names that can be platform-translated well. */
259         /* TODO: Work out how to actually map to the names the Atalla
260          * drivers really use - for now a symbollic link needs to be
261          * created on the host system from libatasi.so to atasi.so on
262          * unix variants. */
263         atalla_dso = DSO_load(NULL, ATALLA_LIBNAME, NULL, 0);
264         if(atalla_dso == NULL)
265                 {
266                 ENGINEerr(ENGINE_F_ATALLA_INIT,ENGINE_R_DSO_FAILURE);
267                 goto err;
268                 }
269         if(!(p1 = (tfnASI_GetHardwareConfig *)DSO_bind_func(
270                                 atalla_dso, ATALLA_F1)) ||
271                         !(p2 = (tfnASI_RSAPrivateKeyOpFn *)DSO_bind_func(
272                                 atalla_dso, ATALLA_F2)) ||
273                         !(p3 = (tfnASI_GetPerformanceStatistics *)DSO_bind_func(
274                                 atalla_dso, ATALLA_F3)))
275                 {
276                 ENGINEerr(ENGINE_F_ATALLA_INIT,ENGINE_R_DSO_FAILURE);
277                 goto err;
278                 }
279         /* Copy the pointers */
280         p_Atalla_GetHardwareConfig = p1;
281         p_Atalla_RSAPrivateKeyOpFn = p2;
282         p_Atalla_GetPerformanceStatistics = p3;
283         /* Perform a basic test to see if there's actually any unit
284          * running. */
285         if(p1(0L, config_buf) != 0)
286                 {
287                 ENGINEerr(ENGINE_F_ATALLA_INIT,ENGINE_R_UNIT_FAILURE);
288                 goto err;
289                 }
290         /* Everything's fine. */
291         return 1;
292 err:
293         if(atalla_dso)
294                 DSO_free(atalla_dso);
295         p_Atalla_GetHardwareConfig = NULL;
296         p_Atalla_RSAPrivateKeyOpFn = NULL;
297         p_Atalla_GetPerformanceStatistics = NULL;
298         return 0;
299         }
300
301 static int atalla_finish(ENGINE *e)
302         {
303         if(atalla_dso == NULL)
304                 {
305                 ENGINEerr(ENGINE_F_ATALLA_FINISH,ENGINE_R_NOT_LOADED);
306                 return 0;
307                 }
308         if(!DSO_free(atalla_dso))
309                 {
310                 ENGINEerr(ENGINE_F_ATALLA_FINISH,ENGINE_R_DSO_FAILURE);
311                 return 0;
312                 }
313         atalla_dso = NULL;
314         p_Atalla_GetHardwareConfig = NULL;
315         p_Atalla_RSAPrivateKeyOpFn = NULL;
316         p_Atalla_GetPerformanceStatistics = NULL;
317         return 1;
318         }
319
320 static int atalla_ctrl(ENGINE *e, int cmd, long i, void *p, void (*f)())
321         {
322         int initialised = ((atalla_dso == NULL) ? 0 : 1);
323         switch(cmd)
324                 {
325         case ATALLA_CMD_SO_PATH:
326                 if(p == NULL)
327                         {
328                         ENGINEerr(ENGINE_F_ATALLA_CTRL,ERR_R_PASSED_NULL_PARAMETER);
329                         return 0;
330                         }
331                 if(initialised)
332                         {
333                         ENGINEerr(ENGINE_F_ATALLA_CTRL,ENGINE_R_ALREADY_LOADED);
334                         return 0;
335                         }
336                 ATALLA_LIBNAME = (const char *)p;
337                 return 1;
338         default:
339                 break;
340                 }
341         ENGINEerr(ENGINE_F_ATALLA_CTRL,ENGINE_R_CTRL_COMMAND_NOT_IMPLEMENTED);
342         return 0;
343         }
344
345 static int atalla_mod_exp(BIGNUM *r, const BIGNUM *a, const BIGNUM *p,
346                         const BIGNUM *m, BN_CTX *ctx)
347         {
348         /* I need somewhere to store temporary serialised values for
349          * use with the Atalla API calls. A neat cheat - I'll use
350          * BIGNUMs from the BN_CTX but access their arrays directly as
351          * byte arrays <grin>. This way I don't have to clean anything
352          * up. */
353         BIGNUM *modulus;
354         BIGNUM *exponent;
355         BIGNUM *argument;
356         BIGNUM *result;
357         RSAPrivateKey keydata;
358         int to_return, numbytes;
359
360         modulus = exponent = argument = result = NULL;
361         to_return = 0; /* expect failure */
362
363         if(!atalla_dso)
364         {
365                 ENGINEerr(ENGINE_F_ATALLA_MOD_EXP,ENGINE_R_NOT_LOADED);
366                 goto err;
367         }
368         /* Prepare the params */
369         BN_CTX_start(ctx);
370         modulus = BN_CTX_get(ctx);
371         exponent = BN_CTX_get(ctx);
372         argument = BN_CTX_get(ctx);
373         result = BN_CTX_get(ctx);
374         if (!result)
375         {
376                 ENGINEerr(ENGINE_F_ATALLA_MOD_EXP,ENGINE_R_BN_CTX_FULL);
377                 goto err;
378         }
379         if(!bn_wexpand(modulus, m->top) || !bn_wexpand(exponent, m->top) ||
380            !bn_wexpand(argument, m->top) || !bn_wexpand(result, m->top))
381         {
382                 ENGINEerr(ENGINE_F_ATALLA_MOD_EXP,ENGINE_R_BN_EXPAND_FAIL);
383                 goto err;
384         }
385         /* Prepare the key-data */
386         memset(&keydata, 0,sizeof keydata);
387         numbytes = BN_num_bytes(m);
388         memset(exponent->d, 0, numbytes);
389         memset(modulus->d, 0, numbytes);
390         BN_bn2bin(p, (unsigned char *)exponent->d + numbytes - BN_num_bytes(p));
391         BN_bn2bin(m, (unsigned char *)modulus->d + numbytes - BN_num_bytes(m));
392         keydata.privateExponent.data = (unsigned char *)exponent->d;
393         keydata.privateExponent.len = numbytes;
394         keydata.modulus.data = (unsigned char *)modulus->d;
395         keydata.modulus.len = numbytes;
396         /* Prepare the argument */
397         memset(argument->d, 0, numbytes);
398         memset(result->d, 0, numbytes);
399         BN_bn2bin(a, (unsigned char *)argument->d + numbytes - BN_num_bytes(a));
400         /* Perform the operation */
401         if(p_Atalla_RSAPrivateKeyOpFn(&keydata, (unsigned char *)result->d,
402                         (unsigned char *)argument->d,
403                         keydata.modulus.len) != 0)
404         {
405                 ENGINEerr(ENGINE_F_ATALLA_MOD_EXP,ENGINE_R_REQUEST_FAILED);
406                 goto err;
407         }
408         /* Convert the response */
409         BN_bin2bn((unsigned char *)result->d, numbytes, r);
410         to_return = 1;
411 err:
412         BN_CTX_end(ctx);
413         return to_return;
414         }
415
416 static int atalla_rsa_mod_exp(BIGNUM *r0, const BIGNUM *I, RSA *rsa)
417         {
418         BN_CTX *ctx = NULL;
419         int to_return = 0;
420
421         if(!atalla_dso)
422         {
423                 ENGINEerr(ENGINE_F_ATALLA_RSA_MOD_EXP,ENGINE_R_NOT_LOADED);
424                 goto err;
425         }
426         if((ctx = BN_CTX_new()) == NULL)
427                 goto err;
428         if(!rsa->d || !rsa->n)
429                 {
430                 ENGINEerr(ENGINE_F_ATALLA_RSA_MOD_EXP,ENGINE_R_MISSING_KEY_COMPONENTS);
431                 goto err;
432                 }
433         to_return = atalla_mod_exp(r0, I, rsa->d, rsa->n, ctx);
434 err:
435         if(ctx)
436                 BN_CTX_free(ctx);
437         return to_return;
438         }
439
440 /* This code was liberated and adapted from the commented-out code in
441  * dsa_ossl.c. Because of the unoptimised form of the Atalla acceleration
442  * (it doesn't have a CRT form for RSA), this function means that an
443  * Atalla system running with a DSA server certificate can handshake
444  * around 5 or 6 times faster/more than an equivalent system running with
445  * RSA. Just check out the "signs" statistics from the RSA and DSA parts
446  * of "openssl speed -engine atalla dsa1024 rsa1024". */
447 static int atalla_dsa_mod_exp(DSA *dsa, BIGNUM *rr, BIGNUM *a1,
448                 BIGNUM *p1, BIGNUM *a2, BIGNUM *p2, BIGNUM *m,
449                 BN_CTX *ctx, BN_MONT_CTX *in_mont)
450         {
451         BIGNUM t;
452         int to_return = 0;
453  
454         BN_init(&t);
455         /* let rr = a1 ^ p1 mod m */
456         if (!atalla_mod_exp(rr,a1,p1,m,ctx)) goto end;
457         /* let t = a2 ^ p2 mod m */
458         if (!atalla_mod_exp(&t,a2,p2,m,ctx)) goto end;
459         /* let rr = rr * t mod m */
460         if (!BN_mod_mul(rr,rr,&t,m,ctx)) goto end;
461         to_return = 1;
462 end:
463         BN_free(&t);
464         return to_return;
465         }
466
467
468 static int atalla_mod_exp_dsa(DSA *dsa, BIGNUM *r, BIGNUM *a,
469                 const BIGNUM *p, const BIGNUM *m, BN_CTX *ctx,
470                 BN_MONT_CTX *m_ctx)
471         {
472         return atalla_mod_exp(r, a, p, m, ctx);
473         }
474
475 /* This function is aliased to mod_exp (with the mont stuff dropped). */
476 static int atalla_mod_exp_mont(BIGNUM *r, const BIGNUM *a, const BIGNUM *p,
477                 const BIGNUM *m, BN_CTX *ctx, BN_MONT_CTX *m_ctx)
478         {
479         return atalla_mod_exp(r, a, p, m, ctx);
480         }
481
482 /* This function is aliased to mod_exp (with the dh and mont dropped). */
483 static int atalla_mod_exp_dh(const DH *dh, BIGNUM *r,
484                 const BIGNUM *a, const BIGNUM *p,
485                 const BIGNUM *m, BN_CTX *ctx, BN_MONT_CTX *m_ctx)
486         {
487         return atalla_mod_exp(r, a, p, m, ctx);
488         }
489
490 #endif /* !OPENSSL_NO_HW_ATALLA */
491 #endif /* !OPENSSL_NO_HW */