When the "dynamic" ENGINE loads another ENGINE from a shared-library, it
[openssl.git] / crypto / engine / hw_openbsd_dev_crypto.c
1 /* Written by Ben Laurie <ben@algroup.co.uk> August 2001 */
2 /* ====================================================================
3  * Copyright (c) 1999-2001 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 <openssl/engine.h>
57 #include <openssl/evp.h>
58 #include "eng_int.h"
59 /* Maybe this is needed? ... */
60 #ifdef FLAT_INC
61 #include "evp_locl.h"
62 #else
63 #include "../evp/evp_locl.h"
64 #endif
65
66 #ifndef OPENSSL_OPENBSD_DEV_CRYPTO
67
68 void ENGINE_load_openbsd_dev_crypto(void)
69         {
70         /* This is a NOP unless OPENSSL_OPENBSD_DEV_CRYPTO is defined */
71         return;
72         }
73
74 #else /* OPENSSL_OPENBSD_DEV_CRYPTO */
75
76 #include <fcntl.h>
77 #include <stdio.h>
78 #include <errno.h>
79 #include <assert.h>
80 #include <unistd.h>
81 #include <sys/ioctl.h>
82
83 #include <crypto/cryptodev.h>
84
85 /****************************************************/
86 /* Declare the normal generic ENGINE stuff here ... */
87
88 static int dev_crypto_ciphers(ENGINE *e, const EVP_CIPHER **cipher,
89                                 const int **nids, int nid);
90 static int dev_crypto_digests(ENGINE *e, const EVP_MD **digest,
91                                 const int **nids, int nid);
92
93 static const char dev_crypto_id[] = "openbsd_dev_crypto";
94 static const char dev_crypto_name[] = "OpenBSD /dev/crypto";
95
96 static ENGINE *engine_openbsd_dev_crypto(void)
97         {
98         ENGINE *engine=ENGINE_new();
99
100         if(!ENGINE_set_id(engine, dev_crypto_id) ||
101                         !ENGINE_set_name(engine, dev_crypto_name) ||
102                         !ENGINE_set_ciphers(engine, dev_crypto_ciphers) ||
103                         !ENGINE_set_digests(engine, dev_crypto_digests))
104                 {
105                 ENGINE_free(engine);
106                 return NULL;
107                 }
108
109         return engine;
110         }
111
112 void ENGINE_load_openbsd_dev_crypto(void)
113         {
114         /* Copied from eng_[openssl|dyn].c */
115         ENGINE *toadd = engine_openbsd_dev_crypto();
116         if(!toadd) return;
117         ENGINE_add(toadd);
118         ENGINE_free(toadd);
119         ERR_clear_error();
120         }
121
122 /******************************************************************************/
123 /* Clip in the stuff from crypto/evp/openbsd_hw.c here. NB: What has changed? */
124 /* I've removed the exposed EVP_*** functions, they're accessed through the   */
125 /* "dev_crypto_[ciphers|digests]" handlers. I've also moved the EVP_CIPHER    */
126 /* and EVP_MD structures to the bottom where they are close to the handlers   */
127 /* that expose them. What should be done? The global data (file-descriptors,  */
128 /* etc) should be put into ENGINE's ex_data support, and per-context data     */
129 /* (also file-descriptors perhaps) should be put into the contexts. Also code */
130 /* formatting, fprintf statements, and OpenSSL-style error handling should be */
131 /* added (dynamically, like the other ENGINEs). Also, "dynamic" support       */
132 /* be added to this ENGINE once it's up and running so that it could be built */
133 /* as a shared-library. What else? device initialisation should take place    */
134 /* inside an ENGINE 'init()' handler (and likewise 'finish()'). ciphers and   */
135 /* digests won't be used by the framework unless the ENGINE has been          */
136 /* successfully initialised (that's one of the things you get for free) so    */
137 /* initialisation, including returning failure if device setup fails, can be  */
138 /* handled quite cleanly. This could presumably handle the opening (and then  */
139 /* closing inside 'finish()') of the 'cryptodev_fd' file-descriptor).         */
140
141 /* longest key supported in hardware */
142 #define MAX_HW_KEY      24
143 #define MAX_HW_IV       8
144
145 #define MD5_DIGEST_LENGTH       16
146 #define MD5_CBLOCK              64
147
148 static int fd;
149 static int dev_failed;
150
151 typedef struct session_op session_op;
152
153 #define CDATA(ctx) EVP_C_DATA(session_op,ctx)
154
155 static void err(const char *str)
156     {
157     fprintf(stderr,"%s: errno %d\n",str,errno);
158     }
159
160 static int dev_crypto_init(session_op *ses)
161     {
162     if(dev_failed)
163         return 0;
164     if(!fd)
165         {
166         int cryptodev_fd;
167
168         if ((cryptodev_fd=open("/dev/crypto",O_RDWR,0)) < 0)
169             {
170             err("/dev/crypto");
171             dev_failed=1;
172             return 0;
173             }
174         if (ioctl(cryptodev_fd,CRIOGET,&fd) == -1)
175             {
176             err("CRIOGET failed");
177             close(cryptodev_fd);
178             dev_failed=1;
179             return 0;
180             }
181         close(cryptodev_fd);
182         }
183     assert(ses);
184     memset(ses,'\0',sizeof *ses);
185
186     return 1;
187     }
188
189 static int dev_crypto_cleanup(EVP_CIPHER_CTX *ctx)
190     {
191     fprintf(stderr,"cleanup %d\n",CDATA(ctx)->ses);
192     if(ioctl(fd,CIOCFSESSION,&CDATA(ctx)->ses) == -1)
193         err("CIOCFSESSION failed");
194
195     OPENSSL_free(CDATA(ctx)->key);
196
197     return 1;
198     }
199
200 static int dev_crypto_init_key(EVP_CIPHER_CTX *ctx,int cipher,
201                                const unsigned char *key,int klen)
202     {
203     if(!dev_crypto_init(CDATA(ctx)))
204         return 0;
205
206     CDATA(ctx)->key=OPENSSL_malloc(MAX_HW_KEY);
207
208     assert(ctx->cipher->iv_len <= MAX_HW_IV);
209
210     memcpy(CDATA(ctx)->key,key,klen);
211     
212     CDATA(ctx)->cipher=cipher;
213     CDATA(ctx)->keylen=klen;
214
215     if (ioctl(fd,CIOCGSESSION,CDATA(ctx)) == -1)
216         {
217         err("CIOCGSESSION failed");
218         return 0;
219         }
220     return 1;
221     }
222
223 static int dev_crypto_cipher(EVP_CIPHER_CTX *ctx,unsigned char *out,
224                              const unsigned char *in,unsigned int inl)
225     {
226     struct crypt_op cryp;
227     unsigned char lb[MAX_HW_IV];
228
229     if(!inl)
230         return 1;
231
232     assert(CDATA(ctx));
233     assert(!dev_failed);
234
235     memset(&cryp,'\0',sizeof cryp);
236     cryp.ses=CDATA(ctx)->ses;
237     cryp.op=ctx->encrypt ? COP_ENCRYPT : COP_DECRYPT;
238     cryp.flags=0;
239     cryp.len=inl;
240     assert((inl&(ctx->cipher->block_size-1)) == 0);
241     cryp.src=(caddr_t)in;
242     cryp.dst=(caddr_t)out;
243     cryp.mac=0;
244     if(ctx->cipher->iv_len)
245         cryp.iv=(caddr_t)ctx->iv;
246
247     if(!ctx->encrypt)
248         memcpy(lb,&in[cryp.len-ctx->cipher->iv_len],ctx->cipher->iv_len);
249
250     if(ioctl(fd, CIOCCRYPT, &cryp) == -1)
251         {
252         if(errno == EINVAL) /* buffers are misaligned */
253             {
254             unsigned int cinl=0;
255             char *cin=NULL;
256             char *cout=NULL;
257
258             /* NB: this can only make cinl != inl with stream ciphers */
259             cinl=(inl+3)/4*4;
260
261             if(((unsigned long)in&3) || cinl != inl)
262                 {
263                 cin=OPENSSL_malloc(cinl);
264                 memcpy(cin,in,inl);
265                 cryp.src=cin;
266                 }
267
268             if(((unsigned long)out&3) || cinl != inl)
269                 {
270                 cout=OPENSSL_malloc(cinl);
271                 cryp.dst=cout;
272                 }
273
274             cryp.len=cinl;
275
276             if(ioctl(fd, CIOCCRYPT, &cryp) == -1)
277                 {
278                 err("CIOCCRYPT(2) failed");
279                 printf("src=%p dst=%p\n",cryp.src,cryp.dst);
280                 abort();
281                 return 0;
282                 }
283                 
284             if(cout)
285                 {
286                 memcpy(out,cout,inl);
287                 OPENSSL_free(cout);
288                 }
289             if(cin)
290                 OPENSSL_free(cin);
291             }
292         else 
293             {       
294             err("CIOCCRYPT failed");
295             abort();
296             return 0;
297             }
298         }
299
300     if(ctx->encrypt)
301         memcpy(ctx->iv,&out[cryp.len-ctx->cipher->iv_len],ctx->cipher->iv_len);
302     else
303         memcpy(ctx->iv,lb,ctx->cipher->iv_len);
304
305     return 1;
306     }
307
308 static int dev_crypto_des_ede3_init_key(EVP_CIPHER_CTX *ctx,
309                                         const unsigned char *key,
310                                         const unsigned char *iv, int enc)
311     { return dev_crypto_init_key(ctx,CRYPTO_3DES_CBC,key,24); }
312
313 static int dev_crypto_rc4_init_key(EVP_CIPHER_CTX *ctx,
314                                         const unsigned char *key,
315                                         const unsigned char *iv, int enc)
316     { return dev_crypto_init_key(ctx,CRYPTO_ARC4,key,16); }
317
318 typedef struct
319     {
320     session_op sess;
321     char *data;
322     int len;
323     unsigned char md[EVP_MAX_MD_SIZE];
324     } MD_DATA;
325
326 static int dev_crypto_init_digest(MD_DATA *md_data,int mac)
327     {
328     if(!dev_crypto_init(&md_data->sess))
329         return 0;
330
331     md_data->len=0;
332     md_data->data=NULL;
333
334     md_data->sess.mac=mac;
335
336     if (ioctl(fd,CIOCGSESSION,&md_data->sess) == -1)
337         {
338         err("CIOCGSESSION failed");
339         return 0;
340         }
341     fprintf(stderr,"opened %d\n",md_data->sess.ses);
342     return 1;
343     }
344
345 static int dev_crypto_cleanup_digest(MD_DATA *md_data)
346     {
347     fprintf(stderr,"cleanup %d\n",md_data->sess.ses);
348     if (ioctl(fd,CIOCFSESSION,&md_data->sess.ses) == -1)
349         {
350         err("CIOCFSESSION failed");
351         return 0;
352         }
353
354     return 1;
355     }
356
357 /* FIXME: if device can do chained MACs, then don't accumulate */
358 /* FIXME: move accumulation to the framework */
359 static int dev_crypto_md5_init(EVP_MD_CTX *ctx)
360     { return dev_crypto_init_digest(ctx->md_data,CRYPTO_MD5); }
361
362 static int do_digest(int ses,unsigned char *md,const void *data,int len)
363     {
364     struct crypt_op cryp;
365     static unsigned char md5zero[16]=
366         {
367         0xd4,0x1d,0x8c,0xd9,0x8f,0x00,0xb2,0x04,
368         0xe9,0x80,0x09,0x98,0xec,0xf8,0x42,0x7e
369         };
370
371     /* some cards can't do zero length */
372     if(!len)
373         {
374         memcpy(md,md5zero,16);
375         return 1;
376         }
377
378     memset(&cryp,'\0',sizeof cryp);
379     cryp.ses=ses;
380     cryp.op=COP_ENCRYPT;/* required to do the MAC rather than check it */
381     cryp.len=len;
382     cryp.src=(caddr_t)data;
383     cryp.dst=(caddr_t)data; // FIXME!!!
384     cryp.mac=(caddr_t)md;
385
386     if(ioctl(fd, CIOCCRYPT, &cryp) == -1)
387         {
388         if(errno == EINVAL) /* buffer is misaligned */
389             {
390             char *dcopy;
391
392             dcopy=OPENSSL_malloc(len);
393             memcpy(dcopy,data,len);
394             cryp.src=dcopy;
395             cryp.dst=cryp.src; // FIXME!!!
396
397             if(ioctl(fd, CIOCCRYPT, &cryp) == -1)
398                 {
399                 err("CIOCCRYPT(MAC2) failed");
400                 abort();
401                 return 0;
402                 }
403             OPENSSL_free(dcopy);
404             }
405         else
406             {
407             err("CIOCCRYPT(MAC) failed");
408             abort();
409             return 0;
410             }
411         }
412     //    printf("done\n");
413
414     return 1;
415     }
416
417 static int dev_crypto_md5_update(EVP_MD_CTX *ctx,const void *data,
418                                  unsigned long len)
419     {
420     MD_DATA *md_data=ctx->md_data;
421
422     if(ctx->flags&EVP_MD_CTX_FLAG_ONESHOT)
423         return do_digest(md_data->sess.ses,md_data->md,data,len);
424
425     md_data->data=OPENSSL_realloc(md_data->data,md_data->len+len);
426     memcpy(md_data->data+md_data->len,data,len);
427     md_data->len+=len;
428
429     return 1;
430     }   
431
432 static int dev_crypto_md5_final(EVP_MD_CTX *ctx,unsigned char *md)
433     {
434     int ret;
435     MD_DATA *md_data=ctx->md_data;
436
437     if(ctx->flags&EVP_MD_CTX_FLAG_ONESHOT)
438         {
439         memcpy(md,md_data->md,MD5_DIGEST_LENGTH);
440         ret=1;
441         }
442     else
443         {
444         ret=do_digest(md_data->sess.ses,md,md_data->data,md_data->len);
445         OPENSSL_free(md_data->data);
446         md_data->data=NULL;
447         md_data->len=0;
448         }
449
450     return ret;
451     }
452
453 static int dev_crypto_md5_copy(EVP_MD_CTX *to,const EVP_MD_CTX *from)
454     {
455     const MD_DATA *from_md=from->md_data;
456     MD_DATA *to_md=to->md_data;
457
458     // How do we copy sessions?
459     assert(from->digest->flags&EVP_MD_FLAG_ONESHOT);
460
461     to_md->data=OPENSSL_malloc(from_md->len);
462     memcpy(to_md->data,from_md->data,from_md->len);
463
464     return 1;
465     }
466
467 static int dev_crypto_md5_cleanup(EVP_MD_CTX *ctx)
468     {
469     return dev_crypto_cleanup_digest(ctx->md_data);
470     }
471
472 /**************************************************************************/
473 /* Here are the moved declarations of the EVP_CIPHER and EVP_MD           */
474 /* implementations. They're down here to be within easy editor-distance   */
475 /* of the digests and ciphers handler functions.                          */
476
477 #define dev_crypto_des_ede3_cbc_cipher dev_crypto_cipher
478
479 BLOCK_CIPHER_def_cbc(dev_crypto_des_ede3, session_op, NID_des_ede3, 8, 24, 8,
480                      0, dev_crypto_des_ede3_init_key,
481                      dev_crypto_cleanup, 
482                      EVP_CIPHER_set_asn1_iv,
483                      EVP_CIPHER_get_asn1_iv,
484                      NULL)
485
486 static const EVP_CIPHER r4_cipher=
487     {
488     NID_rc4,
489     1,16,0,     /* FIXME: key should be up to 256 bytes */
490     EVP_CIPH_VARIABLE_LENGTH,
491     dev_crypto_rc4_init_key,
492     dev_crypto_cipher,
493     dev_crypto_cleanup,
494     sizeof(session_op),
495     NULL,
496     NULL,
497     NULL
498     };
499
500 static const EVP_MD md5_md=
501     {
502     NID_md5,
503     NID_md5WithRSAEncryption,
504     MD5_DIGEST_LENGTH,
505     EVP_MD_FLAG_ONESHOT,        // XXX: set according to device info...
506     dev_crypto_md5_init,
507     dev_crypto_md5_update,
508     dev_crypto_md5_final,
509     dev_crypto_md5_copy,
510     dev_crypto_md5_cleanup,
511     EVP_PKEY_RSA_method,
512     MD5_CBLOCK,
513     sizeof(MD_DATA),
514     };
515
516 /****************************************************************/
517 /* Implement the dev_crypto_[ciphers|digests] handlers here ... */
518
519 static int cipher_nids[] = {NID_des_ede3_cbc, NID_rc4};
520 static int cipher_nids_num = 2;
521 static int digest_nids[] = {NID_md5};
522 static int digest_nids_num = 1;
523
524 static int dev_crypto_ciphers(ENGINE *e, const EVP_CIPHER **cipher,
525                                 const int **nids, int nid)
526         {
527         if(!cipher)
528                 {
529                 /* We are returning a list of supported nids */
530                 *nids = cipher_nids;
531                 return cipher_nids_num;
532                 }
533         /* We are being asked for a specific cipher */
534         if(nid == NID_rc4)
535                 *cipher = &r4_cipher;
536         else if(nid == NID_des_ede3_cbc)
537                 *cipher = &dev_crypto_des_ede3_cbc;
538         else
539                 {
540                 *cipher = NULL;
541                 return 0;
542                 }
543         return 1;
544         }
545
546 static int dev_crypto_digests(ENGINE *e, const EVP_MD **digest,
547                                 const int **nids, int nid)
548         {
549         if(!digest)
550                 {
551                 /* We are returning a list of supported nids */
552                 *nids = digest_nids;
553                 return digest_nids_num;
554                 }
555         /* We are being asked for a specific digest */
556         if(nid == NID_md5)
557                 *digest = &md5_md;
558         else
559                 {
560                 *digest = NULL;
561                 return 0;
562                 }
563         return 1;
564         }
565
566 #endif /* OPENSSL_OPENBSD_DEV_CRYPTO */