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