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