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