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