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