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