Import of openssl-0.9.8, a feature release.
[dragonfly.git] / crypto / openssl-0.9 / engines / e_4758cca.c
1 /* Author: Maurice Gittens <maurice@gittens.nl>                       */
2 /* ====================================================================
3  * Copyright (c) 1999 The OpenSSL Project.  All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  *
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer. 
11  *
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in
14  *    the documentation and/or other materials provided with the
15  *    distribution.
16  *
17  * 3. All advertising materials mentioning features or use of this
18  *    software must display the following acknowledgment:
19  *    "This product includes software developed by the OpenSSL Project
20  *    for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
21  *
22  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
23  *    endorse or promote products derived from this software without
24  *    prior written permission. For written permission, please contact
25  *    licensing@OpenSSL.org.
26  *
27  * 5. Products derived from this software may not be called "OpenSSL"
28  *    nor may "OpenSSL" appear in their names without prior written
29  *    permission of the OpenSSL Project.
30  *
31  * 6. Redistributions of any form whatsoever must retain the following
32  *    acknowledgment:
33  *    "This product includes software developed by the OpenSSL Project
34  *    for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
35  *
36  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
37  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
38  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
39  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
40  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
41  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
42  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
43  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
44  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
45  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
46  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
47  * OF THE POSSIBILITY OF SUCH DAMAGE.
48  * ====================================================================
49  *
50  * This product includes cryptographic software written by Eric Young
51  * (eay@cryptsoft.com).  This product includes software written by Tim
52  * Hudson (tjh@cryptsoft.com).
53  *
54  */
55
56 #include <stdio.h>
57 #include <string.h>
58 #include <openssl/crypto.h>
59 #include <openssl/dso.h>
60 #include <openssl/x509.h>
61 #include <openssl/objects.h>
62 #include <openssl/engine.h>
63 #include <openssl/rand.h>
64 #include <openssl/rsa.h>
65 #include <openssl/bn.h>
66
67 #ifndef OPENSSL_NO_HW
68 #ifndef OPENSSL_NO_HW_4758_CCA
69
70 #ifdef FLAT_INC
71 #include "hw_4758_cca.h"
72 #else
73 #include "vendor_defns/hw_4758_cca.h"
74 #endif
75
76 #include "e_4758cca_err.c"
77
78 static int ibm_4758_cca_destroy(ENGINE *e);
79 static int ibm_4758_cca_init(ENGINE *e);
80 static int ibm_4758_cca_finish(ENGINE *e);
81 static int ibm_4758_cca_ctrl(ENGINE *e, int cmd, long i, void *p, void (*f)(void));
82
83 /* rsa functions */
84 /*---------------*/
85 #ifndef OPENSSL_NO_RSA
86 static int cca_rsa_pub_enc(int flen, const unsigned char *from,
87                 unsigned char *to, RSA *rsa,int padding);
88 static int cca_rsa_priv_dec(int flen, const unsigned char *from,
89                 unsigned char *to, RSA *rsa,int padding);
90 static int cca_rsa_sign(int type, const unsigned char *m, unsigned int m_len,
91                 unsigned char *sigret, unsigned int *siglen, const RSA *rsa);
92 static int cca_rsa_verify(int dtype, const unsigned char *m, unsigned int m_len,
93                 unsigned char *sigbuf, unsigned int siglen, const RSA *rsa);
94
95 /* utility functions */
96 /*-----------------------*/
97 static EVP_PKEY *ibm_4758_load_privkey(ENGINE*, const char*,
98                 UI_METHOD *ui_method, void *callback_data);
99 static EVP_PKEY *ibm_4758_load_pubkey(ENGINE*, const char*,
100                 UI_METHOD *ui_method, void *callback_data);
101
102 static int getModulusAndExponent(const unsigned char *token, long *exponentLength,
103                 unsigned char *exponent, long *modulusLength,
104                 long *modulusFieldLength, unsigned char *modulus);
105 #endif
106
107 /* RAND number functions */
108 /*-----------------------*/
109 static int cca_get_random_bytes(unsigned char*, int );
110 static int cca_random_status(void);
111
112 static void cca_ex_free(void *obj, void *item, CRYPTO_EX_DATA *ad,
113                 int idx,long argl, void *argp);
114
115 /* Function pointers for CCA verbs */
116 /*---------------------------------*/
117 #ifndef OPENSSL_NO_RSA
118 static F_KEYRECORDREAD keyRecordRead;
119 static F_DIGITALSIGNATUREGENERATE digitalSignatureGenerate;
120 static F_DIGITALSIGNATUREVERIFY digitalSignatureVerify;
121 static F_PUBLICKEYEXTRACT publicKeyExtract;
122 static F_PKAENCRYPT pkaEncrypt;
123 static F_PKADECRYPT pkaDecrypt;
124 #endif
125 static F_RANDOMNUMBERGENERATE randomNumberGenerate;
126
127 /* static variables */
128 /*------------------*/
129 static const char *CCA4758_LIB_NAME = NULL;
130 static const char *get_CCA4758_LIB_NAME(void)
131         {
132         if(CCA4758_LIB_NAME)
133                 return CCA4758_LIB_NAME;
134         return CCA_LIB_NAME;
135         }
136 static void free_CCA4758_LIB_NAME(void)
137         {
138         if(CCA4758_LIB_NAME)
139                 OPENSSL_free((void*)CCA4758_LIB_NAME);
140         CCA4758_LIB_NAME = NULL;
141         }
142 static long set_CCA4758_LIB_NAME(const char *name)
143         {
144         free_CCA4758_LIB_NAME();
145         return (((CCA4758_LIB_NAME = BUF_strdup(name)) != NULL) ? 1 : 0);
146         }
147 #ifndef OPENSSL_NO_RSA
148 static const char* n_keyRecordRead = CSNDKRR;
149 static const char* n_digitalSignatureGenerate = CSNDDSG;
150 static const char* n_digitalSignatureVerify = CSNDDSV;
151 static const char* n_publicKeyExtract = CSNDPKX;
152 static const char* n_pkaEncrypt = CSNDPKE;
153 static const char* n_pkaDecrypt = CSNDPKD;
154 #endif
155 static const char* n_randomNumberGenerate = CSNBRNG;
156
157 static int hndidx = -1;
158 static DSO *dso = NULL;
159
160 /* openssl engine initialization structures */
161 /*------------------------------------------*/
162
163 #define CCA4758_CMD_SO_PATH             ENGINE_CMD_BASE
164 static const ENGINE_CMD_DEFN    cca4758_cmd_defns[] = {
165         {CCA4758_CMD_SO_PATH,
166                 "SO_PATH",
167                 "Specifies the path to the '4758cca' shared library",
168                 ENGINE_CMD_FLAG_STRING},
169         {0, NULL, NULL, 0}
170         };
171
172 #ifndef OPENSSL_NO_RSA
173 static RSA_METHOD ibm_4758_cca_rsa =
174         {
175         "IBM 4758 CCA RSA method",
176         cca_rsa_pub_enc,
177         NULL,
178         NULL,
179         cca_rsa_priv_dec,
180         NULL, /*rsa_mod_exp,*/
181         NULL, /*mod_exp_mont,*/
182         NULL, /* init */
183         NULL, /* finish */
184         RSA_FLAG_SIGN_VER,        /* flags */
185         NULL, /* app_data */
186         cca_rsa_sign, /* rsa_sign */
187         cca_rsa_verify, /* rsa_verify */
188         NULL /* rsa_keygen */
189         };
190 #endif
191
192 static RAND_METHOD ibm_4758_cca_rand =
193         {
194         /* "IBM 4758 RAND method", */
195         NULL, /* seed */
196         cca_get_random_bytes, /* get random bytes from the card */
197         NULL, /* cleanup */
198         NULL, /* add */
199         cca_get_random_bytes, /* pseudo rand */
200         cca_random_status, /* status */
201         };
202
203 static const char *engine_4758_cca_id = "4758cca";
204 static const char *engine_4758_cca_name = "IBM 4758 CCA hardware engine support";
205 #ifndef OPENSSL_NO_DYNAMIC_ENGINE 
206 /* Compatibility hack, the dynamic library uses this form in the path */
207 static const char *engine_4758_cca_id_alt = "4758_cca";
208 #endif
209
210 /* engine implementation */
211 /*-----------------------*/
212 static int bind_helper(ENGINE *e)
213         {
214         if(!ENGINE_set_id(e, engine_4758_cca_id) ||
215                         !ENGINE_set_name(e, engine_4758_cca_name) ||
216 #ifndef OPENSSL_NO_RSA
217                         !ENGINE_set_RSA(e, &ibm_4758_cca_rsa) ||
218 #endif
219                         !ENGINE_set_RAND(e, &ibm_4758_cca_rand) ||
220                         !ENGINE_set_destroy_function(e, ibm_4758_cca_destroy) ||
221                         !ENGINE_set_init_function(e, ibm_4758_cca_init) ||
222                         !ENGINE_set_finish_function(e, ibm_4758_cca_finish) ||
223                         !ENGINE_set_ctrl_function(e, ibm_4758_cca_ctrl) ||
224                         !ENGINE_set_load_privkey_function(e, ibm_4758_load_privkey) ||
225                         !ENGINE_set_load_pubkey_function(e, ibm_4758_load_pubkey) ||
226                         !ENGINE_set_cmd_defns(e, cca4758_cmd_defns))
227                 return 0;
228         /* Ensure the error handling is set up */
229         ERR_load_CCA4758_strings();
230         return 1;
231         }
232
233 #ifdef OPENSSL_NO_DYNAMIC_ENGINE
234 static ENGINE *engine_4758_cca(void)
235         {
236         ENGINE *ret = ENGINE_new();
237         if(!ret)
238                 return NULL;
239         if(!bind_helper(ret))
240                 {
241                 ENGINE_free(ret);
242                 return NULL;
243                 }
244         return ret;
245         }
246
247 void ENGINE_load_4758cca(void)
248         {
249         ENGINE *e_4758 = engine_4758_cca();
250         if (!e_4758) return;
251         ENGINE_add(e_4758);
252         ENGINE_free(e_4758);
253         ERR_clear_error();   
254         }
255 #endif
256
257 static int ibm_4758_cca_destroy(ENGINE *e)
258         {
259         ERR_unload_CCA4758_strings();
260         free_CCA4758_LIB_NAME();
261         return 1;
262         }
263
264 static int ibm_4758_cca_init(ENGINE *e)
265         {
266         if(dso)
267                 {
268                 CCA4758err(CCA4758_F_IBM_4758_CCA_INIT,CCA4758_R_ALREADY_LOADED);
269                 goto err;
270                 }
271
272         dso = DSO_load(NULL, get_CCA4758_LIB_NAME(), NULL, 0);
273         if(!dso)
274                 {
275                 CCA4758err(CCA4758_F_IBM_4758_CCA_INIT,CCA4758_R_DSO_FAILURE);
276                 goto err;
277                 }
278
279 #ifndef OPENSSL_NO_RSA
280         if(!(keyRecordRead = (F_KEYRECORDREAD)
281                                 DSO_bind_func(dso, n_keyRecordRead)) ||
282                         !(randomNumberGenerate = (F_RANDOMNUMBERGENERATE)
283                                 DSO_bind_func(dso, n_randomNumberGenerate)) ||
284                         !(digitalSignatureGenerate = (F_DIGITALSIGNATUREGENERATE)
285                                 DSO_bind_func(dso, n_digitalSignatureGenerate)) ||
286                         !(digitalSignatureVerify = (F_DIGITALSIGNATUREVERIFY)
287                                 DSO_bind_func(dso, n_digitalSignatureVerify)) ||
288                         !(publicKeyExtract = (F_PUBLICKEYEXTRACT)
289                                 DSO_bind_func(dso, n_publicKeyExtract)) ||
290                         !(pkaEncrypt = (F_PKAENCRYPT)
291                                 DSO_bind_func(dso, n_pkaEncrypt)) ||
292                         !(pkaDecrypt = (F_PKADECRYPT)
293                                 DSO_bind_func(dso, n_pkaDecrypt)))
294                 {
295                 CCA4758err(CCA4758_F_IBM_4758_CCA_INIT,CCA4758_R_DSO_FAILURE);
296                 goto err;
297                 }
298 #else
299         if(!(randomNumberGenerate = (F_RANDOMNUMBERGENERATE)
300                                 DSO_bind_func(dso, n_randomNumberGenerate)))
301                 {
302                 CCA4758err(CCA4758_F_IBM_4758_CCA_INIT,CCA4758_R_DSO_FAILURE);
303                 goto err;
304                 }
305 #endif
306
307         hndidx = RSA_get_ex_new_index(0, "IBM 4758 CCA RSA key handle",
308                 NULL, NULL, cca_ex_free);
309
310         return 1;
311 err:
312         if(dso)
313                 DSO_free(dso);
314         dso = NULL;
315
316         keyRecordRead = (F_KEYRECORDREAD)0;
317         randomNumberGenerate = (F_RANDOMNUMBERGENERATE)0;
318         digitalSignatureGenerate = (F_DIGITALSIGNATUREGENERATE)0;
319         digitalSignatureVerify = (F_DIGITALSIGNATUREVERIFY)0;
320         publicKeyExtract = (F_PUBLICKEYEXTRACT)0;
321         pkaEncrypt = (F_PKAENCRYPT)0;
322         pkaDecrypt = (F_PKADECRYPT)0;
323         return 0;
324         }
325
326 static int ibm_4758_cca_finish(ENGINE *e)
327         {
328         free_CCA4758_LIB_NAME();
329         if(!dso)
330                 {
331                 CCA4758err(CCA4758_F_IBM_4758_CCA_FINISH,
332                                 CCA4758_R_NOT_LOADED);
333                 return 0;
334                 }
335         if(!DSO_free(dso))
336                 {
337                 CCA4758err(CCA4758_F_IBM_4758_CCA_FINISH,
338                                 CCA4758_R_UNIT_FAILURE);
339                 return 0;
340                 }
341         dso = NULL;
342         keyRecordRead = (F_KEYRECORDREAD)0;
343         randomNumberGenerate = (F_RANDOMNUMBERGENERATE)0;
344         digitalSignatureGenerate = (F_DIGITALSIGNATUREGENERATE)0;
345         digitalSignatureVerify = (F_DIGITALSIGNATUREVERIFY)0;
346         publicKeyExtract = (F_PUBLICKEYEXTRACT)0;
347         pkaEncrypt = (F_PKAENCRYPT)0;
348         pkaDecrypt = (F_PKADECRYPT)0;
349         return 1;
350         }
351
352 static int ibm_4758_cca_ctrl(ENGINE *e, int cmd, long i, void *p, void (*f)(void))
353         {
354         int initialised = ((dso == NULL) ? 0 : 1);
355         switch(cmd)
356                 {
357         case CCA4758_CMD_SO_PATH:
358                 if(p == NULL)
359                         {
360                         CCA4758err(CCA4758_F_IBM_4758_CCA_CTRL,
361                                         ERR_R_PASSED_NULL_PARAMETER);
362                         return 0;
363                         }
364                 if(initialised)
365                         {
366                         CCA4758err(CCA4758_F_IBM_4758_CCA_CTRL,
367                                         CCA4758_R_ALREADY_LOADED);
368                         return 0;
369                         }
370                 return set_CCA4758_LIB_NAME((const char *)p);
371         default:
372                 break;
373                 }
374         CCA4758err(CCA4758_F_IBM_4758_CCA_CTRL,
375                         CCA4758_R_COMMAND_NOT_IMPLEMENTED);
376         return 0;
377         }
378
379 #ifndef OPENSSL_NO_RSA
380
381 #define MAX_CCA_PKA_TOKEN_SIZE 2500
382
383 static EVP_PKEY *ibm_4758_load_privkey(ENGINE* e, const char* key_id,
384                         UI_METHOD *ui_method, void *callback_data)
385         {
386         RSA *rtmp = NULL;
387         EVP_PKEY *res = NULL;
388         unsigned char* keyToken = NULL;
389         unsigned char pubKeyToken[MAX_CCA_PKA_TOKEN_SIZE];
390         long pubKeyTokenLength = MAX_CCA_PKA_TOKEN_SIZE;
391         long keyTokenLength = MAX_CCA_PKA_TOKEN_SIZE;
392         long returnCode;
393         long reasonCode;
394         long exitDataLength = 0;
395         long ruleArrayLength = 0;
396         unsigned char exitData[8];
397         unsigned char ruleArray[8];
398         unsigned char keyLabel[64];
399         unsigned long keyLabelLength = strlen(key_id);
400         unsigned char modulus[256];
401         long modulusFieldLength = sizeof(modulus);
402         long modulusLength = 0;
403         unsigned char exponent[256];
404         long exponentLength = sizeof(exponent);
405
406         if (keyLabelLength > sizeof(keyLabel))
407                 {
408                 CCA4758err(CCA4758_F_IBM_4758_LOAD_PRIVKEY,
409                 CCA4758_R_SIZE_TOO_LARGE_OR_TOO_SMALL);
410                 return NULL;
411                 }
412
413         memset(keyLabel,' ', sizeof(keyLabel));
414         memcpy(keyLabel, key_id, keyLabelLength);
415
416         keyToken = OPENSSL_malloc(MAX_CCA_PKA_TOKEN_SIZE + sizeof(long));
417         if (!keyToken)
418                 {
419                 CCA4758err(CCA4758_F_IBM_4758_LOAD_PRIVKEY,
420                                 ERR_R_MALLOC_FAILURE);
421                 goto err;
422                 }
423
424         keyRecordRead(&returnCode, &reasonCode, &exitDataLength,
425                 exitData, &ruleArrayLength, ruleArray, keyLabel,
426                 &keyTokenLength, keyToken+sizeof(long));
427
428         if (returnCode)
429                 {
430                 CCA4758err(CCA4758_F_IBM_4758_LOAD_PRIVKEY,
431                         CCA4758_R_FAILED_LOADING_PRIVATE_KEY);
432                 goto err;
433                 }
434
435         publicKeyExtract(&returnCode, &reasonCode, &exitDataLength,
436                 exitData, &ruleArrayLength, ruleArray, &keyTokenLength,
437                 keyToken+sizeof(long), &pubKeyTokenLength, pubKeyToken);
438
439         if (returnCode)
440                 {
441                 CCA4758err(CCA4758_F_IBM_4758_LOAD_PRIVKEY,
442                         CCA4758_R_FAILED_LOADING_PRIVATE_KEY);
443                 goto err;
444                 }
445
446         if (!getModulusAndExponent(pubKeyToken, &exponentLength,
447                         exponent, &modulusLength, &modulusFieldLength,
448                         modulus))
449                 {
450                 CCA4758err(CCA4758_F_IBM_4758_LOAD_PRIVKEY,
451                         CCA4758_R_FAILED_LOADING_PRIVATE_KEY);
452                 goto err;
453                 }
454
455         (*(long*)keyToken) = keyTokenLength;
456         rtmp = RSA_new_method(e);
457         RSA_set_ex_data(rtmp, hndidx, (char *)keyToken);
458
459         rtmp->e = BN_bin2bn(exponent, exponentLength, NULL);
460         rtmp->n = BN_bin2bn(modulus, modulusFieldLength, NULL);
461         rtmp->flags |= RSA_FLAG_EXT_PKEY;
462
463         res = EVP_PKEY_new();
464         EVP_PKEY_assign_RSA(res, rtmp);
465
466         return res;
467 err:
468         if (keyToken)
469                 OPENSSL_free(keyToken);
470         if (res)
471                 EVP_PKEY_free(res);
472         if (rtmp)
473                 RSA_free(rtmp);
474         return NULL;
475         }
476
477 static EVP_PKEY *ibm_4758_load_pubkey(ENGINE* e, const char* key_id,
478                         UI_METHOD *ui_method, void *callback_data)
479         {
480         RSA *rtmp = NULL;
481         EVP_PKEY *res = NULL;
482         unsigned char* keyToken = NULL;
483         long keyTokenLength = MAX_CCA_PKA_TOKEN_SIZE;
484         long returnCode;
485         long reasonCode;
486         long exitDataLength = 0;
487         long ruleArrayLength = 0;
488         unsigned char exitData[8];
489         unsigned char ruleArray[8];
490         unsigned char keyLabel[64];
491         unsigned long keyLabelLength = strlen(key_id);
492         unsigned char modulus[512];
493         long modulusFieldLength = sizeof(modulus);
494         long modulusLength = 0;
495         unsigned char exponent[512];
496         long exponentLength = sizeof(exponent);
497
498         if (keyLabelLength > sizeof(keyLabel))
499                 {
500                 CCA4758err(CCA4758_F_IBM_4758_LOAD_PUBKEY,
501                         CCA4758_R_SIZE_TOO_LARGE_OR_TOO_SMALL);
502                 return NULL;
503                 }
504
505         memset(keyLabel,' ', sizeof(keyLabel));
506         memcpy(keyLabel, key_id, keyLabelLength);
507
508         keyToken = OPENSSL_malloc(MAX_CCA_PKA_TOKEN_SIZE + sizeof(long));
509         if (!keyToken)
510                 {
511                 CCA4758err(CCA4758_F_IBM_4758_LOAD_PUBKEY,
512                                 ERR_R_MALLOC_FAILURE);
513                 goto err;
514                 }
515
516         keyRecordRead(&returnCode, &reasonCode, &exitDataLength, exitData,
517                 &ruleArrayLength, ruleArray, keyLabel, &keyTokenLength,
518                 keyToken+sizeof(long));
519
520         if (returnCode)
521                 {
522                 CCA4758err(CCA4758_F_IBM_4758_LOAD_PUBKEY,
523                                 ERR_R_MALLOC_FAILURE);
524                 goto err;
525                 }
526
527         if (!getModulusAndExponent(keyToken+sizeof(long), &exponentLength,
528                         exponent, &modulusLength, &modulusFieldLength, modulus))
529                 {
530                 CCA4758err(CCA4758_F_IBM_4758_LOAD_PUBKEY,
531                         CCA4758_R_FAILED_LOADING_PUBLIC_KEY);
532                 goto err;
533                 }
534
535         (*(long*)keyToken) = keyTokenLength;
536         rtmp = RSA_new_method(e);
537         RSA_set_ex_data(rtmp, hndidx, (char *)keyToken);
538         rtmp->e = BN_bin2bn(exponent, exponentLength, NULL);
539         rtmp->n = BN_bin2bn(modulus, modulusFieldLength, NULL);
540         rtmp->flags |= RSA_FLAG_EXT_PKEY;
541         res = EVP_PKEY_new();
542         EVP_PKEY_assign_RSA(res, rtmp);
543
544         return res;
545 err:
546         if (keyToken)
547                 OPENSSL_free(keyToken);
548         if (res)
549                 EVP_PKEY_free(res);
550         if (rtmp)
551                 RSA_free(rtmp);
552         return NULL;
553         }
554
555 static int cca_rsa_pub_enc(int flen, const unsigned char *from,
556                         unsigned char *to, RSA *rsa,int padding)
557         {
558         long returnCode;
559         long reasonCode;
560         long lflen = flen;
561         long exitDataLength = 0;
562         unsigned char exitData[8];
563         long ruleArrayLength = 1;
564         unsigned char ruleArray[8] = "PKCS-1.2";
565         long dataStructureLength = 0;
566         unsigned char dataStructure[8];
567         long outputLength = RSA_size(rsa);
568         long keyTokenLength;
569         unsigned char* keyToken = (unsigned char*)RSA_get_ex_data(rsa, hndidx);
570
571         keyTokenLength = *(long*)keyToken;
572         keyToken+=sizeof(long);
573
574         pkaEncrypt(&returnCode, &reasonCode, &exitDataLength, exitData,
575                 &ruleArrayLength, ruleArray, &lflen, (unsigned char*)from,
576                 &dataStructureLength, dataStructure, &keyTokenLength,
577                 keyToken, &outputLength, to);
578
579         if (returnCode || reasonCode)
580                 return -(returnCode << 16 | reasonCode);
581         return outputLength;
582         }
583
584 static int cca_rsa_priv_dec(int flen, const unsigned char *from,
585                         unsigned char *to, RSA *rsa,int padding)
586         {
587         long returnCode;
588         long reasonCode;
589         long lflen = flen;
590         long exitDataLength = 0;
591         unsigned char exitData[8];
592         long ruleArrayLength = 1;
593         unsigned char ruleArray[8] = "PKCS-1.2";
594         long dataStructureLength = 0;
595         unsigned char dataStructure[8];
596         long outputLength = RSA_size(rsa);
597         long keyTokenLength;
598         unsigned char* keyToken = (unsigned char*)RSA_get_ex_data(rsa, hndidx);
599
600         keyTokenLength = *(long*)keyToken;
601         keyToken+=sizeof(long);
602
603         pkaDecrypt(&returnCode, &reasonCode, &exitDataLength, exitData,
604                 &ruleArrayLength, ruleArray, &lflen, (unsigned char*)from,
605                 &dataStructureLength, dataStructure, &keyTokenLength,
606                 keyToken, &outputLength, to);
607
608         return (returnCode | reasonCode) ? 0 : 1;
609         }
610
611 #define SSL_SIG_LEN 36
612
613 static int cca_rsa_verify(int type, const unsigned char *m, unsigned int m_len,
614                 unsigned char *sigbuf, unsigned int siglen, const RSA *rsa)
615         {
616         long returnCode;
617         long reasonCode;
618         long lsiglen = siglen;
619         long exitDataLength = 0;
620         unsigned char exitData[8];
621         long ruleArrayLength = 1;
622         unsigned char ruleArray[8] = "PKCS-1.1";
623         long keyTokenLength;
624         unsigned char* keyToken = (unsigned char*)RSA_get_ex_data(rsa, hndidx);
625         long length = SSL_SIG_LEN;
626         long keyLength ;
627         unsigned char *hashBuffer = NULL;
628         X509_SIG sig;
629         ASN1_TYPE parameter;
630         X509_ALGOR algorithm;
631         ASN1_OCTET_STRING digest;
632
633         keyTokenLength = *(long*)keyToken;
634         keyToken+=sizeof(long);
635
636         if (type == NID_md5 || type == NID_sha1)
637                 {
638                 sig.algor = &algorithm;
639                 algorithm.algorithm = OBJ_nid2obj(type);
640
641                 if (!algorithm.algorithm)
642                         {
643                         CCA4758err(CCA4758_F_CCA_RSA_VERIFY,
644                                 CCA4758_R_UNKNOWN_ALGORITHM_TYPE);
645                         return 0;
646                         }
647
648                 if (!algorithm.algorithm->length)
649                         {
650                         CCA4758err(CCA4758_F_CCA_RSA_VERIFY,
651                                 CCA4758_R_ASN1_OID_UNKNOWN_FOR_MD);
652                         return 0;
653                         }
654
655                 parameter.type = V_ASN1_NULL;
656                 parameter.value.ptr = NULL;
657                 algorithm.parameter = &parameter;
658
659                 sig.digest = &digest;
660                 sig.digest->data = (unsigned char*)m;
661                 sig.digest->length = m_len;
662
663                 length = i2d_X509_SIG(&sig, NULL);
664                 }
665
666         keyLength = RSA_size(rsa);
667
668         if (length - RSA_PKCS1_PADDING > keyLength)
669                 {
670                 CCA4758err(CCA4758_F_CCA_RSA_VERIFY,
671                         CCA4758_R_SIZE_TOO_LARGE_OR_TOO_SMALL);
672                 return 0;
673                 }
674
675         switch (type)
676                 {
677                 case NID_md5_sha1 :
678                         if (m_len != SSL_SIG_LEN)
679                                 {
680                                 CCA4758err(CCA4758_F_CCA_RSA_VERIFY,
681                                 CCA4758_R_SIZE_TOO_LARGE_OR_TOO_SMALL);
682                                 return 0;
683                                 }
684
685                         hashBuffer = (unsigned char *)m;
686                         length = m_len;
687                         break;
688                 case NID_md5 :
689                         {
690                         unsigned char *ptr;
691                         ptr = hashBuffer = OPENSSL_malloc(
692                                         (unsigned int)keyLength+1);
693                         if (!hashBuffer)
694                                 {
695                                 CCA4758err(CCA4758_F_CCA_RSA_VERIFY,
696                                                 ERR_R_MALLOC_FAILURE);
697                                 return 0;
698                                 }
699
700                         i2d_X509_SIG(&sig, &ptr);
701                         }
702                         break;
703                 case NID_sha1 :
704                         {
705                         unsigned char *ptr;
706                         ptr = hashBuffer = OPENSSL_malloc(
707                                         (unsigned int)keyLength+1);
708                         if (!hashBuffer)
709                                 {
710                                 CCA4758err(CCA4758_F_CCA_RSA_VERIFY,
711                                                 ERR_R_MALLOC_FAILURE);
712                                 return 0;
713                                 }
714                         i2d_X509_SIG(&sig, &ptr);
715                         }
716                         break;
717                 default:
718                         return 0;
719                 }
720
721         digitalSignatureVerify(&returnCode, &reasonCode, &exitDataLength,
722                 exitData, &ruleArrayLength, ruleArray, &keyTokenLength,
723                 keyToken, &length, hashBuffer, &lsiglen, sigbuf);
724
725         if (type == NID_sha1 || type == NID_md5)
726                 {
727                 OPENSSL_cleanse(hashBuffer, keyLength+1);
728                 OPENSSL_free(hashBuffer);
729                 }
730
731         return ((returnCode || reasonCode) ? 0 : 1);
732         }
733
734 #define SSL_SIG_LEN 36
735
736 static int cca_rsa_sign(int type, const unsigned char *m, unsigned int m_len,
737                 unsigned char *sigret, unsigned int *siglen, const RSA *rsa)
738         {
739         long returnCode;
740         long reasonCode;
741         long exitDataLength = 0;
742         unsigned char exitData[8];
743         long ruleArrayLength = 1;
744         unsigned char ruleArray[8] = "PKCS-1.1";
745         long outputLength=256;
746         long outputBitLength;
747         long keyTokenLength;
748         unsigned char *hashBuffer = NULL;
749         unsigned char* keyToken = (unsigned char*)RSA_get_ex_data(rsa, hndidx);
750         long length = SSL_SIG_LEN;
751         long keyLength ;
752         X509_SIG sig;
753         ASN1_TYPE parameter;
754         X509_ALGOR algorithm;
755         ASN1_OCTET_STRING digest;
756
757         keyTokenLength = *(long*)keyToken;
758         keyToken+=sizeof(long);
759
760         if (type == NID_md5 || type == NID_sha1)
761                 {
762                 sig.algor = &algorithm;
763                 algorithm.algorithm = OBJ_nid2obj(type);
764
765                 if (!algorithm.algorithm)
766                         {
767                         CCA4758err(CCA4758_F_CCA_RSA_SIGN,
768                                 CCA4758_R_UNKNOWN_ALGORITHM_TYPE);
769                         return 0;
770                         }
771
772                 if (!algorithm.algorithm->length)
773                         {
774                         CCA4758err(CCA4758_F_CCA_RSA_SIGN,
775                                 CCA4758_R_ASN1_OID_UNKNOWN_FOR_MD);
776                         return 0;
777                         }
778
779                 parameter.type = V_ASN1_NULL;
780                 parameter.value.ptr = NULL;
781                 algorithm.parameter = &parameter;
782
783                 sig.digest = &digest;
784                 sig.digest->data = (unsigned char*)m;
785                 sig.digest->length = m_len;
786
787                 length = i2d_X509_SIG(&sig, NULL);
788                 }
789
790         keyLength = RSA_size(rsa);
791
792         if (length - RSA_PKCS1_PADDING > keyLength)
793                 {
794                 CCA4758err(CCA4758_F_CCA_RSA_SIGN,
795                         CCA4758_R_SIZE_TOO_LARGE_OR_TOO_SMALL);
796                 return 0;
797                 }
798
799         switch (type)
800                 {
801                 case NID_md5_sha1 :
802                         if (m_len != SSL_SIG_LEN)
803                                 {
804                                 CCA4758err(CCA4758_F_CCA_RSA_SIGN,
805                                 CCA4758_R_SIZE_TOO_LARGE_OR_TOO_SMALL);
806                                 return 0;
807                                 }
808                         hashBuffer = (unsigned char*)m;
809                         length = m_len;
810                         break;
811                 case NID_md5 :
812                         {
813                         unsigned char *ptr;
814                         ptr = hashBuffer = OPENSSL_malloc(
815                                         (unsigned int)keyLength+1);
816                         if (!hashBuffer)
817                                 {
818                                 CCA4758err(CCA4758_F_CCA_RSA_SIGN,
819                                                 ERR_R_MALLOC_FAILURE);
820                                 return 0;
821                                 }
822                         i2d_X509_SIG(&sig, &ptr);
823                         }
824                         break;
825                 case NID_sha1 :
826                         {
827                         unsigned char *ptr;
828                         ptr = hashBuffer = OPENSSL_malloc(
829                                         (unsigned int)keyLength+1);
830                         if (!hashBuffer)
831                                 {
832                                 CCA4758err(CCA4758_F_CCA_RSA_SIGN,
833                                                 ERR_R_MALLOC_FAILURE);
834                                 return 0;
835                                 }
836                         i2d_X509_SIG(&sig, &ptr);
837                         }
838                         break;
839                 default:
840                         return 0;
841                 }
842
843         digitalSignatureGenerate(&returnCode, &reasonCode, &exitDataLength,
844                 exitData, &ruleArrayLength, ruleArray, &keyTokenLength,
845                 keyToken, &length, hashBuffer, &outputLength, &outputBitLength,
846                 sigret);
847
848         if (type == NID_sha1 || type == NID_md5)
849                 {
850                 OPENSSL_cleanse(hashBuffer, keyLength+1);
851                 OPENSSL_free(hashBuffer);
852                 }
853
854         *siglen = outputLength;
855
856         return ((returnCode || reasonCode) ? 0 : 1);
857         }
858
859 static int getModulusAndExponent(const unsigned char*token, long *exponentLength,
860                 unsigned char *exponent, long *modulusLength, long *modulusFieldLength,
861                 unsigned char *modulus)
862         {
863         unsigned long len;
864
865         if (*token++ != (char)0x1E) /* internal PKA token? */
866                 return 0;
867
868         if (*token++) /* token version must be zero */
869                 return 0;
870
871         len = *token++;
872         len = len << 8;
873         len |= (unsigned char)*token++;
874
875         token += 4; /* skip reserved bytes */
876
877         if (*token++ == (char)0x04)
878                 {
879                 if (*token++) /* token version must be zero */
880                         return 0;
881
882                 len = *token++;
883                 len = len << 8;
884                 len |= (unsigned char)*token++;
885
886                 token+=2; /* skip reserved section */
887
888                 len = *token++;
889                 len = len << 8;
890                 len |= (unsigned char)*token++;
891
892                 *exponentLength = len;
893
894                 len = *token++;
895                 len = len << 8;
896                 len |= (unsigned char)*token++;
897
898                 *modulusLength = len;
899
900                 len = *token++;
901                 len = len << 8;
902                 len |= (unsigned char)*token++;
903
904                 *modulusFieldLength = len;
905
906                 memcpy(exponent, token, *exponentLength);
907                 token+= *exponentLength;
908
909                 memcpy(modulus, token, *modulusFieldLength);
910                 return 1;
911                 }
912         return 0;
913         }
914
915 #endif /* OPENSSL_NO_RSA */
916
917 static int cca_random_status(void)
918         {
919         return 1;
920         }
921
922 static int cca_get_random_bytes(unsigned char* buf, int num)
923         {
924         long ret_code;
925         long reason_code;
926         long exit_data_length;
927         unsigned char exit_data[4];
928         unsigned char form[] = "RANDOM  ";
929         unsigned char rand_buf[8];
930
931         while(num >= (int)sizeof(rand_buf))
932                 {
933                 randomNumberGenerate(&ret_code, &reason_code, &exit_data_length,
934                         exit_data, form, rand_buf);
935                 if (ret_code)
936                         return 0;
937                 num -= sizeof(rand_buf);
938                 memcpy(buf, rand_buf, sizeof(rand_buf));
939                 buf += sizeof(rand_buf);
940                 }
941
942         if (num)
943                 {
944                 randomNumberGenerate(&ret_code, &reason_code, NULL, NULL,
945                         form, rand_buf);
946                 if (ret_code)
947                         return 0;
948                 memcpy(buf, rand_buf, num);
949                 }
950
951         return 1;
952         }
953
954 static void cca_ex_free(void *obj, void *item, CRYPTO_EX_DATA *ad, int idx,
955                 long argl, void *argp)
956         {
957         if (item)
958                 OPENSSL_free(item);
959         }
960
961 /* Goo to handle building as a dynamic engine */
962 #ifndef OPENSSL_NO_DYNAMIC_ENGINE 
963 static int bind_fn(ENGINE *e, const char *id)
964         {
965         if(id && (strcmp(id, engine_4758_cca_id) != 0) &&
966                         (strcmp(id, engine_4758_cca_id_alt) != 0))
967                 return 0;
968         if(!bind_helper(e))
969                 return 0;
970         return 1;
971         }       
972 IMPLEMENT_DYNAMIC_CHECK_FN()
973 IMPLEMENT_DYNAMIC_BIND_FN(bind_fn)
974 #endif /* OPENSSL_NO_DYNAMIC_ENGINE */
975
976 #endif /* !OPENSSL_NO_HW_4758_CCA */
977 #endif /* !OPENSSL_NO_HW */