MIPS32R3 provides the EXT instruction to extract bits from
[openssl.git] / engines / e_devcrypto.c
1 /*
2  * Copyright 2017-2018 The OpenSSL Project Authors. All Rights Reserved.
3  *
4  * Licensed under the Apache License 2.0 (the "License").  You may not use
5  * this file except in compliance with the License.  You can obtain a copy
6  * in the file LICENSE in the source distribution or at
7  * https://www.openssl.org/source/license.html
8  */
9
10 #include "../e_os.h"
11 #include <string.h>
12 #include <sys/types.h>
13 #include <sys/stat.h>
14 #include <fcntl.h>
15 #include <sys/ioctl.h>
16 #include <unistd.h>
17 #include <assert.h>
18
19 #include <openssl/conf.h>
20 #include <openssl/evp.h>
21 #include <openssl/err.h>
22 #include <openssl/engine.h>
23 #include <openssl/objects.h>
24 #include <crypto/cryptodev.h>
25
26 /* #define ENGINE_DEVCRYPTO_DEBUG */
27
28 #ifdef CRYPTO_ALGORITHM_MIN
29 # define CHECK_BSD_STYLE_MACROS
30 #endif
31
32 #define engine_devcrypto_id "devcrypto"
33
34 /*
35  * ONE global file descriptor for all sessions.  This allows operations
36  * such as digest session data copying (see digest_copy()), but is also
37  * saner...  why re-open /dev/crypto for every session?
38  */
39 static int cfd = -1;
40 #define DEVCRYPTO_REQUIRE_ACCELERATED 0 /* require confirmation of acceleration */
41 #define DEVCRYPTO_USE_SOFTWARE        1 /* allow software drivers */
42 #define DEVCRYPTO_REJECT_SOFTWARE     2 /* only disallow confirmed software drivers */
43
44 #define DEVCRYPTO_DEFAULT_USE_SOFTDRIVERS DEVCRYPTO_REJECT_SOFTWARE
45 static int use_softdrivers = DEVCRYPTO_DEFAULT_USE_SOFTDRIVERS;
46
47 /*
48  * cipher/digest status & acceleration definitions
49  * Make sure the defaults are set to 0
50  */
51 struct driver_info_st {
52     enum devcrypto_status_t {
53         DEVCRYPTO_STATUS_FAILURE         = -3, /* unusable for other reason */
54         DEVCRYPTO_STATUS_NO_CIOCCPHASH   = -2, /* hash state copy not supported */
55         DEVCRYPTO_STATUS_NO_CIOCGSESSION = -1, /* session open failed */
56         DEVCRYPTO_STATUS_UNKNOWN         =  0, /* not tested yet */
57         DEVCRYPTO_STATUS_USABLE          =  1  /* algo can be used */
58     } status;
59
60     enum devcrypto_accelerated_t {
61         DEVCRYPTO_NOT_ACCELERATED        = -1, /* software implemented */
62         DEVCRYPTO_ACCELERATION_UNKNOWN   =  0, /* acceleration support unkown */
63         DEVCRYPTO_ACCELERATED            =  1  /* hardware accelerated */
64     } accelerated;
65
66     char *driver_name;
67 };
68
69 #ifdef OPENSSL_NO_DYNAMIC_ENGINE
70 void engine_load_devcrypto_int(void);
71 #endif
72
73 /******************************************************************************
74  *
75  * Ciphers
76  *
77  * Because they all do the same basic operation, we have only one set of
78  * method functions for them all to share, and a mapping table between
79  * NIDs and cryptodev IDs, with all the necessary size data.
80  *
81  *****/
82
83 struct cipher_ctx {
84     struct session_op sess;
85     int op;                      /* COP_ENCRYPT or COP_DECRYPT */
86     unsigned long mode;          /* EVP_CIPH_*_MODE */
87
88     /* to handle ctr mode being a stream cipher */
89     unsigned char partial[EVP_MAX_BLOCK_LENGTH];
90     unsigned int blocksize, num;
91 };
92
93 static const struct cipher_data_st {
94     int nid;
95     int blocksize;
96     int keylen;
97     int ivlen;
98     int flags;
99     int devcryptoid;
100 } cipher_data[] = {
101 #ifndef OPENSSL_NO_DES
102     { NID_des_cbc, 8, 8, 8, EVP_CIPH_CBC_MODE, CRYPTO_DES_CBC },
103     { NID_des_ede3_cbc, 8, 24, 8, EVP_CIPH_CBC_MODE, CRYPTO_3DES_CBC },
104 #endif
105 #ifndef OPENSSL_NO_BF
106     { NID_bf_cbc, 8, 16, 8, EVP_CIPH_CBC_MODE, CRYPTO_BLF_CBC },
107 #endif
108 #ifndef OPENSSL_NO_CAST
109     { NID_cast5_cbc, 8, 16, 8, EVP_CIPH_CBC_MODE, CRYPTO_CAST_CBC },
110 #endif
111     { NID_aes_128_cbc, 16, 128 / 8, 16, EVP_CIPH_CBC_MODE, CRYPTO_AES_CBC },
112     { NID_aes_192_cbc, 16, 192 / 8, 16, EVP_CIPH_CBC_MODE, CRYPTO_AES_CBC },
113     { NID_aes_256_cbc, 16, 256 / 8, 16, EVP_CIPH_CBC_MODE, CRYPTO_AES_CBC },
114 #ifndef OPENSSL_NO_RC4
115     { NID_rc4, 1, 16, 0, EVP_CIPH_STREAM_CIPHER, CRYPTO_ARC4 },
116 #endif
117 #if !defined(CHECK_BSD_STYLE_MACROS) || defined(CRYPTO_AES_CTR)
118     { NID_aes_128_ctr, 16, 128 / 8, 16, EVP_CIPH_CTR_MODE, CRYPTO_AES_CTR },
119     { NID_aes_192_ctr, 16, 192 / 8, 16, EVP_CIPH_CTR_MODE, CRYPTO_AES_CTR },
120     { NID_aes_256_ctr, 16, 256 / 8, 16, EVP_CIPH_CTR_MODE, CRYPTO_AES_CTR },
121 #endif
122 #if 0                            /* Not yet supported */
123     { NID_aes_128_xts, 16, 128 / 8 * 2, 16, EVP_CIPH_XTS_MODE, CRYPTO_AES_XTS },
124     { NID_aes_256_xts, 16, 256 / 8 * 2, 16, EVP_CIPH_XTS_MODE, CRYPTO_AES_XTS },
125 #endif
126 #if !defined(CHECK_BSD_STYLE_MACROS) || defined(CRYPTO_AES_ECB)
127     { NID_aes_128_ecb, 16, 128 / 8, 0, EVP_CIPH_ECB_MODE, CRYPTO_AES_ECB },
128     { NID_aes_192_ecb, 16, 192 / 8, 0, EVP_CIPH_ECB_MODE, CRYPTO_AES_ECB },
129     { NID_aes_256_ecb, 16, 256 / 8, 0, EVP_CIPH_ECB_MODE, CRYPTO_AES_ECB },
130 #endif
131 #if 0                            /* Not yet supported */
132     { NID_aes_128_gcm, 16, 128 / 8, 16, EVP_CIPH_GCM_MODE, CRYPTO_AES_GCM },
133     { NID_aes_192_gcm, 16, 192 / 8, 16, EVP_CIPH_GCM_MODE, CRYPTO_AES_GCM },
134     { NID_aes_256_gcm, 16, 256 / 8, 16, EVP_CIPH_GCM_MODE, CRYPTO_AES_GCM },
135 #endif
136 #ifndef OPENSSL_NO_CAMELLIA
137     { NID_camellia_128_cbc, 16, 128 / 8, 16, EVP_CIPH_CBC_MODE,
138       CRYPTO_CAMELLIA_CBC },
139     { NID_camellia_192_cbc, 16, 192 / 8, 16, EVP_CIPH_CBC_MODE,
140       CRYPTO_CAMELLIA_CBC },
141     { NID_camellia_256_cbc, 16, 256 / 8, 16, EVP_CIPH_CBC_MODE,
142       CRYPTO_CAMELLIA_CBC },
143 #endif
144 };
145
146 static size_t find_cipher_data_index(int nid)
147 {
148     size_t i;
149
150     for (i = 0; i < OSSL_NELEM(cipher_data); i++)
151         if (nid == cipher_data[i].nid)
152             return i;
153     return (size_t)-1;
154 }
155
156 static size_t get_cipher_data_index(int nid)
157 {
158     size_t i = find_cipher_data_index(nid);
159
160     if (i != (size_t)-1)
161         return i;
162
163     /*
164      * Code further down must make sure that only NIDs in the table above
165      * are used.  If any other NID reaches this function, there's a grave
166      * coding error further down.
167      */
168     assert("Code that never should be reached" == NULL);
169     return -1;
170 }
171
172 static const struct cipher_data_st *get_cipher_data(int nid)
173 {
174     return &cipher_data[get_cipher_data_index(nid)];
175 }
176
177 /*
178  * Following are the three necessary functions to map OpenSSL functionality
179  * with cryptodev.
180  */
181
182 static int cipher_init(EVP_CIPHER_CTX *ctx, const unsigned char *key,
183                        const unsigned char *iv, int enc)
184 {
185     struct cipher_ctx *cipher_ctx =
186         (struct cipher_ctx *)EVP_CIPHER_CTX_get_cipher_data(ctx);
187     const struct cipher_data_st *cipher_d =
188         get_cipher_data(EVP_CIPHER_CTX_nid(ctx));
189     int sess = cipher_ctx->sess.ses;
190
191     /* close a previous open session */
192     if (cipher_ctx->sess.ses != 0 &&
193         ioctl(cfd, CIOCFSESSION, &cipher_ctx->sess.ses) <0)
194         SYSerr(SYS_F_IOCTL, errno);
195
196     cipher_ctx->sess.cipher = cipher_d->devcryptoid;
197     cipher_ctx->sess.keylen = cipher_d->keylen;
198     cipher_ctx->sess.key = (void *)key;
199     cipher_ctx->op = enc ? COP_ENCRYPT : COP_DECRYPT;
200     cipher_ctx->mode = cipher_d->flags & EVP_CIPH_MODE;
201     cipher_ctx->blocksize = cipher_d->blocksize;
202     if (ioctl(cfd, CIOCGSESSION, &cipher_ctx->sess) < 0) {
203         SYSerr(SYS_F_IOCTL, errno);
204         return 0;
205     }
206
207     return 1;
208 }
209
210 static int cipher_do_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
211                             const unsigned char *in, size_t inl)
212 {
213     struct cipher_ctx *cipher_ctx =
214         (struct cipher_ctx *)EVP_CIPHER_CTX_get_cipher_data(ctx);
215     struct crypt_op cryp;
216     unsigned char *iv = EVP_CIPHER_CTX_iv_noconst(ctx);
217 #if !defined(COP_FLAG_WRITE_IV)
218     unsigned char saved_iv[EVP_MAX_IV_LENGTH];
219     const unsigned char *ivptr;
220     size_t nblocks, ivlen;
221 #endif
222
223     memset(&cryp, 0, sizeof(cryp));
224     cryp.ses = cipher_ctx->sess.ses;
225     cryp.len = inl;
226     cryp.src = (void *)in;
227     cryp.dst = (void *)out;
228     cryp.iv = (void *)iv;
229     cryp.op = cipher_ctx->op;
230 #if !defined(COP_FLAG_WRITE_IV)
231     cryp.flags = 0;
232
233     ivlen = EVP_CIPHER_CTX_iv_length(ctx);
234     if (ivlen > 0)
235         switch (cipher_ctx->mode) {
236         case EVP_CIPH_CBC_MODE:
237             assert(inl >= ivlen);
238             if (!EVP_CIPHER_CTX_encrypting(ctx)) {
239                 ivptr = in + inl - ivlen;
240                 memcpy(saved_iv, ivptr, ivlen);
241             }
242             break;
243
244         case EVP_CIPH_CTR_MODE:
245             break;
246
247         default: /* should not happen */
248             return 0;
249         }
250 #else
251     cryp.flags = COP_FLAG_WRITE_IV;
252 #endif
253
254     if (ioctl(cfd, CIOCCRYPT, &cryp) < 0) {
255         SYSerr(SYS_F_IOCTL, errno);
256         return 0;
257     }
258
259 #if !defined(COP_FLAG_WRITE_IV)
260     if (ivlen > 0)
261         switch (cipher_ctx->mode) {
262         case EVP_CIPH_CBC_MODE:
263             assert(inl >= ivlen);
264             if (EVP_CIPHER_CTX_encrypting(ctx))
265                 ivptr = out + inl - ivlen;
266             else
267                 ivptr = saved_iv;
268
269             memcpy(iv, ivptr, ivlen);
270             break;
271
272         case EVP_CIPH_CTR_MODE:
273             nblocks = (inl + cipher_ctx->blocksize - 1)
274                       / cipher_ctx->blocksize;
275             do {
276                 ivlen--;
277                 nblocks += iv[ivlen];
278                 iv[ivlen] = (uint8_t) nblocks;
279                 nblocks >>= 8;
280             } while (ivlen);
281             break;
282
283         default: /* should not happen */
284             return 0;
285         }
286 #endif
287
288     return 1;
289 }
290
291 static int ctr_do_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
292                          const unsigned char *in, size_t inl)
293 {
294     struct cipher_ctx *cipher_ctx =
295         (struct cipher_ctx *)EVP_CIPHER_CTX_get_cipher_data(ctx);
296     size_t nblocks, len;
297
298     /* initial partial block */
299     while (cipher_ctx->num && inl) {
300         (*out++) = *(in++) ^ cipher_ctx->partial[cipher_ctx->num];
301         --inl;
302         cipher_ctx->num = (cipher_ctx->num + 1) % cipher_ctx->blocksize;
303     }
304
305     /* full blocks */
306     if (inl > (unsigned int) cipher_ctx->blocksize) {
307         nblocks = inl/cipher_ctx->blocksize;
308         len = nblocks * cipher_ctx->blocksize;
309         if (cipher_do_cipher(ctx, out, in, len) < 1)
310             return 0;
311         inl -= len;
312         out += len;
313         in += len;
314     }
315
316     /* final partial block */
317     if (inl) {
318         memset(cipher_ctx->partial, 0, cipher_ctx->blocksize);
319         if (cipher_do_cipher(ctx, cipher_ctx->partial, cipher_ctx->partial,
320             cipher_ctx->blocksize) < 1)
321             return 0;
322         while (inl--) {
323             out[cipher_ctx->num] = in[cipher_ctx->num]
324                                    ^ cipher_ctx->partial[cipher_ctx->num];
325             cipher_ctx->num++;
326         }
327     }
328
329     return 1;
330 }
331
332 static int cipher_ctrl(EVP_CIPHER_CTX *ctx, int type, int p1, void* p2)
333 {
334     EVP_CIPHER_CTX *to_ctx = (EVP_CIPHER_CTX *)p2;
335     struct cipher_ctx *cipher_ctx;
336
337     if (type == EVP_CTRL_COPY || type == EVP_CTRL_INIT) {
338         cipher_ctx = (struct cipher_ctx *)EVP_CIPHER_CTX_get_cipher_data(ctx);
339
340         if (cipher_ctx == NULL) /* OK for copy, error for init */
341             return (type == EVP_CTRL_COPY);
342
343         /* both COPY & INIT need a clean context */
344         memset(&cipher_ctx->sess, 0, sizeof(cipher_ctx->sess));
345
346         /* when copying the context, a new session needs to be open as well */
347         return (type == EVP_CTRL_INIT)
348             || cipher_init(to_ctx, cipher_ctx->sess.key, EVP_CIPHER_CTX_iv(ctx),
349                            (cipher_ctx->op == COP_ENCRYPT));
350     }
351
352     return -1;
353 }
354
355 static int cipher_cleanup(EVP_CIPHER_CTX *ctx)
356 {
357     struct cipher_ctx *cipher_ctx =
358         (struct cipher_ctx *)EVP_CIPHER_CTX_get_cipher_data(ctx);
359
360     if (ioctl(cfd, CIOCFSESSION, &cipher_ctx->sess.ses) < 0) {
361         SYSerr(SYS_F_IOCTL, errno);
362         return 0;
363     }
364     memset(&cipher_ctx->sess, 0, sizeof(cipher_ctx->sess));
365
366     return 1;
367 }
368
369 /*
370  * Keep tables of known nids, associated methods, selected ciphers, and driver
371  * info.
372  * Note that known_cipher_nids[] isn't necessarily indexed the same way as
373  * cipher_data[] above, which the other tables are.
374  */
375 static int known_cipher_nids[OSSL_NELEM(cipher_data)];
376 static int known_cipher_nids_amount = -1; /* -1 indicates not yet initialised */
377 static EVP_CIPHER *known_cipher_methods[OSSL_NELEM(cipher_data)] = { NULL, };
378 static int selected_ciphers[OSSL_NELEM(cipher_data)];
379 static struct driver_info_st cipher_driver_info[OSSL_NELEM(cipher_data)];
380
381
382 static int devcrypto_test_cipher(size_t cipher_data_index)
383 {
384     return (cipher_driver_info[cipher_data_index].status == DEVCRYPTO_STATUS_USABLE
385             && selected_ciphers[cipher_data_index] == 1
386             && (cipher_driver_info[cipher_data_index].accelerated
387                     == DEVCRYPTO_ACCELERATED
388                 || use_softdrivers == DEVCRYPTO_USE_SOFTWARE
389                 || (cipher_driver_info[cipher_data_index].accelerated
390                         != DEVCRYPTO_NOT_ACCELERATED
391                     && use_softdrivers == DEVCRYPTO_REJECT_SOFTWARE)));
392 }
393
394 static void prepare_cipher_methods(void)
395 {
396     size_t i;
397     struct session_op sess;
398     unsigned long cipher_mode;
399 #ifdef CIOCGSESSINFO
400     struct session_info_op siop;
401 #endif
402
403     memset(&cipher_driver_info, 0, sizeof(cipher_driver_info));
404
405     memset(&sess, 0, sizeof(sess));
406     sess.key = (void *)"01234567890123456789012345678901234567890123456789";
407
408     for (i = 0, known_cipher_nids_amount = 0;
409          i < OSSL_NELEM(cipher_data); i++) {
410
411         selected_ciphers[i] = 1;
412         /*
413          * Check that the cipher is usable
414          */
415         sess.cipher = cipher_data[i].devcryptoid;
416         sess.keylen = cipher_data[i].keylen;
417         if (ioctl(cfd, CIOCGSESSION, &sess) < 0) {
418             cipher_driver_info[i].status = DEVCRYPTO_STATUS_NO_CIOCGSESSION;
419             continue;
420         }
421
422         cipher_mode = cipher_data[i].flags & EVP_CIPH_MODE;
423
424         if ((known_cipher_methods[i] =
425                  EVP_CIPHER_meth_new(cipher_data[i].nid,
426                                      cipher_mode == EVP_CIPH_CTR_MODE ? 1 :
427                                                     cipher_data[i].blocksize,
428                                      cipher_data[i].keylen)) == NULL
429             || !EVP_CIPHER_meth_set_iv_length(known_cipher_methods[i],
430                                               cipher_data[i].ivlen)
431             || !EVP_CIPHER_meth_set_flags(known_cipher_methods[i],
432                                           cipher_data[i].flags
433                                           | EVP_CIPH_CUSTOM_COPY
434                                           | EVP_CIPH_CTRL_INIT
435                                           | EVP_CIPH_FLAG_DEFAULT_ASN1)
436             || !EVP_CIPHER_meth_set_init(known_cipher_methods[i], cipher_init)
437             || !EVP_CIPHER_meth_set_do_cipher(known_cipher_methods[i],
438                                      cipher_mode == EVP_CIPH_CTR_MODE ?
439                                               ctr_do_cipher :
440                                               cipher_do_cipher)
441             || !EVP_CIPHER_meth_set_ctrl(known_cipher_methods[i], cipher_ctrl)
442             || !EVP_CIPHER_meth_set_cleanup(known_cipher_methods[i],
443                                             cipher_cleanup)
444             || !EVP_CIPHER_meth_set_impl_ctx_size(known_cipher_methods[i],
445                                                   sizeof(struct cipher_ctx))) {
446             cipher_driver_info[i].status = DEVCRYPTO_STATUS_FAILURE;
447             EVP_CIPHER_meth_free(known_cipher_methods[i]);
448             known_cipher_methods[i] = NULL;
449         } else {
450             cipher_driver_info[i].status = DEVCRYPTO_STATUS_USABLE;
451 #ifdef CIOCGSESSINFO
452             siop.ses = sess.ses;
453             if (ioctl(cfd, CIOCGSESSINFO, &siop) < 0) {
454                 cipher_driver_info[i].accelerated = DEVCRYPTO_ACCELERATION_UNKNOWN;
455             } else {
456                 cipher_driver_info[i].driver_name =
457                     OPENSSL_strndup(siop.cipher_info.cra_driver_name,
458                                     CRYPTODEV_MAX_ALG_NAME);
459                 if (!(siop.flags & SIOP_FLAG_KERNEL_DRIVER_ONLY))
460                     cipher_driver_info[i].accelerated = DEVCRYPTO_NOT_ACCELERATED;
461                 else
462                     cipher_driver_info[i].accelerated = DEVCRYPTO_ACCELERATED;
463             }
464 #endif /* CIOCGSESSINFO */
465         }
466         ioctl(cfd, CIOCFSESSION, &sess.ses);
467         if (devcrypto_test_cipher(i)) {
468             known_cipher_nids[known_cipher_nids_amount++] =
469                 cipher_data[i].nid;
470         }
471     }
472 }
473
474 static void rebuild_known_cipher_nids(ENGINE *e)
475 {
476     size_t i;
477
478     for (i = 0, known_cipher_nids_amount = 0; i < OSSL_NELEM(cipher_data); i++) {
479         if (devcrypto_test_cipher(i))
480             known_cipher_nids[known_cipher_nids_amount++] = cipher_data[i].nid;
481     }
482     ENGINE_unregister_ciphers(e);
483     ENGINE_register_ciphers(e);
484 }
485
486 static const EVP_CIPHER *get_cipher_method(int nid)
487 {
488     size_t i = get_cipher_data_index(nid);
489
490     if (i == (size_t)-1)
491         return NULL;
492     return known_cipher_methods[i];
493 }
494
495 static int get_cipher_nids(const int **nids)
496 {
497     *nids = known_cipher_nids;
498     return known_cipher_nids_amount;
499 }
500
501 static void destroy_cipher_method(int nid)
502 {
503     size_t i = get_cipher_data_index(nid);
504
505     EVP_CIPHER_meth_free(known_cipher_methods[i]);
506     known_cipher_methods[i] = NULL;
507 }
508
509 static void destroy_all_cipher_methods(void)
510 {
511     size_t i;
512
513     for (i = 0; i < OSSL_NELEM(cipher_data); i++) {
514         destroy_cipher_method(cipher_data[i].nid);
515         OPENSSL_free(cipher_driver_info[i].driver_name);
516         cipher_driver_info[i].driver_name = NULL;
517     }
518 }
519
520 static int devcrypto_ciphers(ENGINE *e, const EVP_CIPHER **cipher,
521                              const int **nids, int nid)
522 {
523     if (cipher == NULL)
524         return get_cipher_nids(nids);
525
526     *cipher = get_cipher_method(nid);
527
528     return *cipher != NULL;
529 }
530
531 static void devcrypto_select_all_ciphers(int *cipher_list)
532 {
533     size_t i;
534
535     for (i = 0; i < OSSL_NELEM(cipher_data); i++)
536         cipher_list[i] = 1;
537 }
538
539 static int cryptodev_select_cipher_cb(const char *str, int len, void *usr)
540 {
541     int *cipher_list = (int *)usr;
542     char *name;
543     const EVP_CIPHER *EVP;
544     size_t i;
545
546     if (len == 0)
547         return 1;
548     if (usr == NULL || (name = OPENSSL_strndup(str, len)) == NULL)
549         return 0;
550     EVP = EVP_get_cipherbyname(name);
551     if (EVP == NULL)
552         fprintf(stderr, "devcrypto: unknown cipher %s\n", name);
553     else if ((i = find_cipher_data_index(EVP_CIPHER_nid(EVP))) != (size_t)-1)
554         cipher_list[i] = 1;
555     else
556         fprintf(stderr, "devcrypto: cipher %s not available\n", name);
557     OPENSSL_free(name);
558     return 1;
559 }
560
561 static void dump_cipher_info(void)
562 {
563     size_t i;
564     const char *name;
565
566     fprintf (stderr, "Information about ciphers supported by the /dev/crypto"
567              " engine:\n");
568 #ifndef CIOCGSESSINFO
569     fprintf(stderr, "CIOCGSESSINFO (session info call) unavailable\n");
570 #endif
571     for (i = 0; i < OSSL_NELEM(cipher_data); i++) {
572         name = OBJ_nid2sn(cipher_data[i].nid);
573         fprintf (stderr, "Cipher %s, NID=%d, /dev/crypto info: id=%d, ",
574                  name ? name : "unknown", cipher_data[i].nid,
575                  cipher_data[i].devcryptoid);
576         if (cipher_driver_info[i].status == DEVCRYPTO_STATUS_NO_CIOCGSESSION ) {
577             fprintf (stderr, "CIOCGSESSION (session open call) failed\n");
578             continue;
579         }
580         fprintf (stderr, "driver=%s ", cipher_driver_info[i].driver_name ?
581                  cipher_driver_info[i].driver_name : "unknown");
582         if (cipher_driver_info[i].accelerated == DEVCRYPTO_ACCELERATED)
583             fprintf(stderr, "(hw accelerated)");
584         else if (cipher_driver_info[i].accelerated == DEVCRYPTO_NOT_ACCELERATED)
585             fprintf(stderr, "(software)");
586         else
587             fprintf(stderr, "(acceleration status unknown)");
588         if (cipher_driver_info[i].status == DEVCRYPTO_STATUS_FAILURE)
589             fprintf (stderr, ". Cipher setup failed");
590         fprintf(stderr, "\n");
591     }
592     fprintf(stderr, "\n");
593 }
594
595 /*
596  * We only support digests if the cryptodev implementation supports multiple
597  * data updates and session copying.  Otherwise, we would be forced to maintain
598  * a cache, which is perilous if there's a lot of data coming in (if someone
599  * wants to checksum an OpenSSL tarball, for example).
600  */
601 #if defined(CIOCCPHASH) && defined(COP_FLAG_UPDATE) && defined(COP_FLAG_FINAL)
602 #define IMPLEMENT_DIGEST
603
604 /******************************************************************************
605  *
606  * Digests
607  *
608  * Because they all do the same basic operation, we have only one set of
609  * method functions for them all to share, and a mapping table between
610  * NIDs and cryptodev IDs, with all the necessary size data.
611  *
612  *****/
613
614 struct digest_ctx {
615     struct session_op sess;
616     /* This signals that the init function was called, not that it succeeded. */
617     int init_called;
618     unsigned char digest_res[HASH_MAX_LEN];
619 };
620
621 static const struct digest_data_st {
622     int nid;
623     int digestlen;
624     int devcryptoid;
625 } digest_data[] = {
626 #ifndef OPENSSL_NO_MD5
627     { NID_md5, 16, CRYPTO_MD5 },
628 #endif
629     { NID_sha1, 20, CRYPTO_SHA1 },
630 #ifndef OPENSSL_NO_RMD160
631 # if !defined(CHECK_BSD_STYLE_MACROS) || defined(CRYPTO_RIPEMD160)
632     { NID_ripemd160, 20, CRYPTO_RIPEMD160 },
633 # endif
634 #endif
635 #if !defined(CHECK_BSD_STYLE_MACROS) || defined(CRYPTO_SHA2_224)
636     { NID_sha224, 224 / 8, CRYPTO_SHA2_224 },
637 #endif
638 #if !defined(CHECK_BSD_STYLE_MACROS) || defined(CRYPTO_SHA2_256)
639     { NID_sha256, 256 / 8, CRYPTO_SHA2_256 },
640 #endif
641 #if !defined(CHECK_BSD_STYLE_MACROS) || defined(CRYPTO_SHA2_384)
642     { NID_sha384, 384 / 8, CRYPTO_SHA2_384 },
643 #endif
644 #if !defined(CHECK_BSD_STYLE_MACROS) || defined(CRYPTO_SHA2_512)
645     { NID_sha512, 512 / 8, CRYPTO_SHA2_512 },
646 #endif
647 };
648
649 static size_t find_digest_data_index(int nid)
650 {
651     size_t i;
652
653     for (i = 0; i < OSSL_NELEM(digest_data); i++)
654         if (nid == digest_data[i].nid)
655             return i;
656     return (size_t)-1;
657 }
658
659 static size_t get_digest_data_index(int nid)
660 {
661     size_t i = find_digest_data_index(nid);
662
663     if (i != (size_t)-1)
664         return i;
665
666     /*
667      * Code further down must make sure that only NIDs in the table above
668      * are used.  If any other NID reaches this function, there's a grave
669      * coding error further down.
670      */
671     assert("Code that never should be reached" == NULL);
672     return -1;
673 }
674
675 static const struct digest_data_st *get_digest_data(int nid)
676 {
677     return &digest_data[get_digest_data_index(nid)];
678 }
679
680 /*
681  * Following are the five necessary functions to map OpenSSL functionality
682  * with cryptodev: init, update, final, cleanup, and copy.
683  */
684
685 static int digest_init(EVP_MD_CTX *ctx)
686 {
687     struct digest_ctx *digest_ctx =
688         (struct digest_ctx *)EVP_MD_CTX_md_data(ctx);
689     const struct digest_data_st *digest_d =
690         get_digest_data(EVP_MD_CTX_type(ctx));
691
692     digest_ctx->init_called = 1;
693
694     memset(&digest_ctx->sess, 0, sizeof(digest_ctx->sess));
695     digest_ctx->sess.mac = digest_d->devcryptoid;
696     if (ioctl(cfd, CIOCGSESSION, &digest_ctx->sess) < 0) {
697         SYSerr(SYS_F_IOCTL, errno);
698         return 0;
699     }
700
701     return 1;
702 }
703
704 static int digest_op(struct digest_ctx *ctx, const void *src, size_t srclen,
705                      void *res, unsigned int flags)
706 {
707     struct crypt_op cryp;
708
709     memset(&cryp, 0, sizeof(cryp));
710     cryp.ses = ctx->sess.ses;
711     cryp.len = srclen;
712     cryp.src = (void *)src;
713     cryp.dst = NULL;
714     cryp.mac = res;
715     cryp.flags = flags;
716     return ioctl(cfd, CIOCCRYPT, &cryp);
717 }
718
719 static int digest_update(EVP_MD_CTX *ctx, const void *data, size_t count)
720 {
721     struct digest_ctx *digest_ctx =
722         (struct digest_ctx *)EVP_MD_CTX_md_data(ctx);
723
724     if (count == 0)
725         return 1;
726
727     if (digest_ctx == NULL)
728         return 0;
729
730     if (EVP_MD_CTX_test_flags(ctx, EVP_MD_CTX_FLAG_ONESHOT)) {
731         if (digest_op(digest_ctx, data, count, digest_ctx->digest_res, 0) >= 0)
732             return 1;
733     } else if (digest_op(digest_ctx, data, count, NULL, COP_FLAG_UPDATE) >= 0) {
734         return 1;
735     }
736
737     SYSerr(SYS_F_IOCTL, errno);
738     return 0;
739 }
740
741 static int digest_final(EVP_MD_CTX *ctx, unsigned char *md)
742 {
743     struct digest_ctx *digest_ctx =
744         (struct digest_ctx *)EVP_MD_CTX_md_data(ctx);
745
746     if (md == NULL || digest_ctx == NULL)
747         return 0;
748
749     if (EVP_MD_CTX_test_flags(ctx, EVP_MD_CTX_FLAG_ONESHOT)) {
750         memcpy(md, digest_ctx->digest_res, EVP_MD_CTX_size(ctx));
751     } else if (digest_op(digest_ctx, NULL, 0, md, COP_FLAG_FINAL) < 0) {
752         SYSerr(SYS_F_IOCTL, errno);
753         return 0;
754     }
755
756     return 1;
757 }
758
759 static int digest_copy(EVP_MD_CTX *to, const EVP_MD_CTX *from)
760 {
761     struct digest_ctx *digest_from =
762         (struct digest_ctx *)EVP_MD_CTX_md_data(from);
763     struct digest_ctx *digest_to =
764         (struct digest_ctx *)EVP_MD_CTX_md_data(to);
765     struct cphash_op cphash;
766
767     if (digest_from == NULL || digest_from->init_called != 1)
768         return 1;
769
770     if (!digest_init(to)) {
771         SYSerr(SYS_F_IOCTL, errno);
772         return 0;
773     }
774
775     cphash.src_ses = digest_from->sess.ses;
776     cphash.dst_ses = digest_to->sess.ses;
777     if (ioctl(cfd, CIOCCPHASH, &cphash) < 0) {
778         SYSerr(SYS_F_IOCTL, errno);
779         return 0;
780     }
781     return 1;
782 }
783
784 static int digest_cleanup(EVP_MD_CTX *ctx)
785 {
786     struct digest_ctx *digest_ctx =
787         (struct digest_ctx *)EVP_MD_CTX_md_data(ctx);
788
789     if (digest_ctx == NULL)
790         return 1;
791     if (ioctl(cfd, CIOCFSESSION, &digest_ctx->sess.ses) < 0) {
792         SYSerr(SYS_F_IOCTL, errno);
793         return 0;
794     }
795     return 1;
796 }
797
798 /*
799  * Keep tables of known nids, associated methods, selected digests, and
800  * driver info.
801  * Note that known_digest_nids[] isn't necessarily indexed the same way as
802  * digest_data[] above, which the other tables are.
803  */
804 static int known_digest_nids[OSSL_NELEM(digest_data)];
805 static int known_digest_nids_amount = -1; /* -1 indicates not yet initialised */
806 static EVP_MD *known_digest_methods[OSSL_NELEM(digest_data)] = { NULL, };
807 static int selected_digests[OSSL_NELEM(digest_data)];
808 static struct driver_info_st digest_driver_info[OSSL_NELEM(digest_data)];
809
810 static int devcrypto_test_digest(size_t digest_data_index)
811 {
812     return (digest_driver_info[digest_data_index].status == DEVCRYPTO_STATUS_USABLE
813             && selected_digests[digest_data_index] == 1
814             && (digest_driver_info[digest_data_index].accelerated
815                     == DEVCRYPTO_ACCELERATED
816                 || use_softdrivers == DEVCRYPTO_USE_SOFTWARE
817                 || (digest_driver_info[digest_data_index].accelerated
818                         != DEVCRYPTO_NOT_ACCELERATED
819                     && use_softdrivers == DEVCRYPTO_REJECT_SOFTWARE)));
820 }
821
822 static void rebuild_known_digest_nids(ENGINE *e)
823 {
824     size_t i;
825
826     for (i = 0, known_digest_nids_amount = 0; i < OSSL_NELEM(digest_data); i++) {
827         if (devcrypto_test_digest(i))
828             known_digest_nids[known_digest_nids_amount++] = digest_data[i].nid;
829     }
830     ENGINE_unregister_digests(e);
831     ENGINE_register_digests(e);
832 }
833
834 static void prepare_digest_methods(void)
835 {
836     size_t i;
837     struct session_op sess1, sess2;
838 #ifdef CIOCGSESSINFO
839     struct session_info_op siop;
840 #endif
841     struct cphash_op cphash;
842
843     memset(&digest_driver_info, 0, sizeof(digest_driver_info));
844
845     memset(&sess1, 0, sizeof(sess1));
846     memset(&sess2, 0, sizeof(sess2));
847
848     for (i = 0, known_digest_nids_amount = 0; i < OSSL_NELEM(digest_data);
849          i++) {
850
851         selected_digests[i] = 1;
852
853         /*
854          * Check that the digest is usable
855          */
856         sess1.mac = digest_data[i].devcryptoid;
857         sess2.ses = 0;
858         if (ioctl(cfd, CIOCGSESSION, &sess1) < 0) {
859             digest_driver_info[i].status = DEVCRYPTO_STATUS_NO_CIOCGSESSION;
860             goto finish;
861         }
862
863 #ifdef CIOCGSESSINFO
864         /* gather hardware acceleration info from the driver */
865         siop.ses = sess1.ses;
866         if (ioctl(cfd, CIOCGSESSINFO, &siop) < 0) {
867             digest_driver_info[i].accelerated = DEVCRYPTO_ACCELERATION_UNKNOWN;
868         } else {
869             digest_driver_info[i].driver_name =
870                 OPENSSL_strndup(siop.hash_info.cra_driver_name,
871                                 CRYPTODEV_MAX_ALG_NAME);
872             if (siop.flags & SIOP_FLAG_KERNEL_DRIVER_ONLY)
873                 digest_driver_info[i].accelerated = DEVCRYPTO_ACCELERATED;
874             else
875                 digest_driver_info[i].accelerated = DEVCRYPTO_NOT_ACCELERATED;
876         }
877 #endif
878
879         /* digest must be capable of hash state copy */
880         sess2.mac = sess1.mac;
881         if (ioctl(cfd, CIOCGSESSION, &sess2) < 0) {
882             digest_driver_info[i].status = DEVCRYPTO_STATUS_FAILURE;
883             goto finish;
884         }
885         cphash.src_ses = sess1.ses;
886         cphash.dst_ses = sess2.ses;
887         if (ioctl(cfd, CIOCCPHASH, &cphash) < 0) {
888             digest_driver_info[i].status = DEVCRYPTO_STATUS_NO_CIOCCPHASH;
889             goto finish;
890         }
891         if ((known_digest_methods[i] = EVP_MD_meth_new(digest_data[i].nid,
892                                                        NID_undef)) == NULL
893             || !EVP_MD_meth_set_result_size(known_digest_methods[i],
894                                             digest_data[i].digestlen)
895             || !EVP_MD_meth_set_init(known_digest_methods[i], digest_init)
896             || !EVP_MD_meth_set_update(known_digest_methods[i], digest_update)
897             || !EVP_MD_meth_set_final(known_digest_methods[i], digest_final)
898             || !EVP_MD_meth_set_copy(known_digest_methods[i], digest_copy)
899             || !EVP_MD_meth_set_cleanup(known_digest_methods[i], digest_cleanup)
900             || !EVP_MD_meth_set_app_datasize(known_digest_methods[i],
901                                              sizeof(struct digest_ctx))) {
902             digest_driver_info[i].status = DEVCRYPTO_STATUS_FAILURE;
903             EVP_MD_meth_free(known_digest_methods[i]);
904             known_digest_methods[i] = NULL;
905             goto finish;
906         }
907         digest_driver_info[i].status = DEVCRYPTO_STATUS_USABLE;
908 finish:
909         ioctl(cfd, CIOCFSESSION, &sess1.ses);
910         if (sess2.ses != 0)
911             ioctl(cfd, CIOCFSESSION, &sess2.ses);
912         if (devcrypto_test_digest(i))
913             known_digest_nids[known_digest_nids_amount++] = digest_data[i].nid;
914     }
915 }
916
917 static const EVP_MD *get_digest_method(int nid)
918 {
919     size_t i = get_digest_data_index(nid);
920
921     if (i == (size_t)-1)
922         return NULL;
923     return known_digest_methods[i];
924 }
925
926 static int get_digest_nids(const int **nids)
927 {
928     *nids = known_digest_nids;
929     return known_digest_nids_amount;
930 }
931
932 static void destroy_digest_method(int nid)
933 {
934     size_t i = get_digest_data_index(nid);
935
936     EVP_MD_meth_free(known_digest_methods[i]);
937     known_digest_methods[i] = NULL;
938 }
939
940 static void destroy_all_digest_methods(void)
941 {
942     size_t i;
943
944     for (i = 0; i < OSSL_NELEM(digest_data); i++) {
945         destroy_digest_method(digest_data[i].nid);
946         OPENSSL_free(digest_driver_info[i].driver_name);
947         digest_driver_info[i].driver_name = NULL;
948     }
949 }
950
951 static int devcrypto_digests(ENGINE *e, const EVP_MD **digest,
952                              const int **nids, int nid)
953 {
954     if (digest == NULL)
955         return get_digest_nids(nids);
956
957     *digest = get_digest_method(nid);
958
959     return *digest != NULL;
960 }
961
962 static void devcrypto_select_all_digests(int *digest_list)
963 {
964     size_t i;
965
966     for (i = 0; i < OSSL_NELEM(digest_data); i++)
967         digest_list[i] = 1;
968 }
969
970 static int cryptodev_select_digest_cb(const char *str, int len, void *usr)
971 {
972     int *digest_list = (int *)usr;
973     char *name;
974     const EVP_MD *EVP;
975     size_t i;
976
977     if (len == 0)
978         return 1;
979     if (usr == NULL || (name = OPENSSL_strndup(str, len)) == NULL)
980         return 0;
981     EVP = EVP_get_digestbyname(name);
982     if (EVP == NULL)
983         fprintf(stderr, "devcrypto: unknown digest %s\n", name);
984     else if ((i = find_digest_data_index(EVP_MD_type(EVP))) != (size_t)-1)
985         digest_list[i] = 1;
986     else
987         fprintf(stderr, "devcrypto: digest %s not available\n", name);
988     OPENSSL_free(name);
989     return 1;
990 }
991
992 static void dump_digest_info(void)
993 {
994     size_t i;
995     const char *name;
996
997     fprintf (stderr, "Information about digests supported by the /dev/crypto"
998              " engine:\n");
999 #ifndef CIOCGSESSINFO
1000     fprintf(stderr, "CIOCGSESSINFO (session info call) unavailable\n");
1001 #endif
1002
1003     for (i = 0; i < OSSL_NELEM(digest_data); i++) {
1004         name = OBJ_nid2sn(digest_data[i].nid);
1005         fprintf (stderr, "Digest %s, NID=%d, /dev/crypto info: id=%d, driver=%s",
1006                  name ? name : "unknown", digest_data[i].nid,
1007                  digest_data[i].devcryptoid,
1008                  digest_driver_info[i].driver_name ? digest_driver_info[i].driver_name : "unknown");
1009         if (digest_driver_info[i].status == DEVCRYPTO_STATUS_NO_CIOCGSESSION) {
1010             fprintf (stderr, ". CIOCGSESSION (session open) failed\n");
1011             continue;
1012         }
1013         if (digest_driver_info[i].accelerated == DEVCRYPTO_ACCELERATED)
1014             fprintf(stderr, " (hw accelerated)");
1015         else if (digest_driver_info[i].accelerated == DEVCRYPTO_NOT_ACCELERATED)
1016             fprintf(stderr, " (software)");
1017         else
1018             fprintf(stderr, " (acceleration status unknown)");
1019         if (cipher_driver_info[i].status == DEVCRYPTO_STATUS_FAILURE)
1020             fprintf (stderr, ". Cipher setup failed\n");
1021         else if (digest_driver_info[i].status == DEVCRYPTO_STATUS_NO_CIOCCPHASH)
1022             fprintf(stderr, ", CIOCCPHASH failed\n");
1023         else
1024             fprintf(stderr, ", CIOCCPHASH capable\n");
1025     }
1026     fprintf(stderr, "\n");
1027 }
1028
1029 #endif
1030
1031 /******************************************************************************
1032  *
1033  * CONTROL COMMANDS
1034  *
1035  *****/
1036
1037 #define DEVCRYPTO_CMD_USE_SOFTDRIVERS ENGINE_CMD_BASE
1038 #define DEVCRYPTO_CMD_CIPHERS (ENGINE_CMD_BASE + 1)
1039 #define DEVCRYPTO_CMD_DIGESTS (ENGINE_CMD_BASE + 2)
1040 #define DEVCRYPTO_CMD_DUMP_INFO (ENGINE_CMD_BASE + 3)
1041
1042 static const ENGINE_CMD_DEFN devcrypto_cmds[] = {
1043 #ifdef CIOCGSESSINFO
1044    {DEVCRYPTO_CMD_USE_SOFTDRIVERS,
1045     "USE_SOFTDRIVERS",
1046     "specifies whether to use software (not accelerated) drivers ("
1047         OPENSSL_MSTR(DEVCRYPTO_REQUIRE_ACCELERATED) "=use only accelerated drivers, "
1048         OPENSSL_MSTR(DEVCRYPTO_USE_SOFTWARE) "=allow all drivers, "
1049         OPENSSL_MSTR(DEVCRYPTO_REJECT_SOFTWARE)
1050         "=use if acceleration can't be determined) [default="
1051         OPENSSL_MSTR(DEVCRYPTO_DEFAULT_USE_SOFTDRIVERS) "]",
1052     ENGINE_CMD_FLAG_NUMERIC},
1053 #endif
1054
1055    {DEVCRYPTO_CMD_CIPHERS,
1056     "CIPHERS",
1057     "either ALL, NONE, or a comma-separated list of ciphers to enable [default=ALL]",
1058     ENGINE_CMD_FLAG_STRING},
1059
1060 #ifdef IMPLEMENT_DIGEST
1061    {DEVCRYPTO_CMD_DIGESTS,
1062     "DIGESTS",
1063     "either ALL, NONE, or a comma-separated list of digests to enable [default=ALL]",
1064     ENGINE_CMD_FLAG_STRING},
1065 #endif
1066
1067    {DEVCRYPTO_CMD_DUMP_INFO,
1068     "DUMP_INFO",
1069     "dump info about each algorithm to stderr; use 'openssl engine -pre DUMP_INFO devcrypto'",
1070     ENGINE_CMD_FLAG_NO_INPUT},
1071
1072    {0, NULL, NULL, 0}
1073 };
1074
1075 static int devcrypto_ctrl(ENGINE *e, int cmd, long i, void *p, void (*f) (void))
1076 {
1077     int *new_list;
1078     switch (cmd) {
1079 #ifdef CIOCGSESSINFO
1080     case DEVCRYPTO_CMD_USE_SOFTDRIVERS:
1081         switch (i) {
1082         case DEVCRYPTO_REQUIRE_ACCELERATED:
1083         case DEVCRYPTO_USE_SOFTWARE:
1084         case DEVCRYPTO_REJECT_SOFTWARE:
1085             break;
1086         default:
1087             fprintf(stderr, "devcrypto: invalid value (%ld) for USE_SOFTDRIVERS\n", i);
1088             return 0;
1089         }
1090         if (use_softdrivers == i)
1091             return 1;
1092         use_softdrivers = i;
1093 #ifdef IMPLEMENT_DIGEST
1094         rebuild_known_digest_nids(e);
1095 #endif
1096         rebuild_known_cipher_nids(e);
1097         return 1;
1098 #endif /* CIOCGSESSINFO */
1099
1100     case DEVCRYPTO_CMD_CIPHERS:
1101         if (p == NULL)
1102             return 1;
1103         if (strcasecmp((const char *)p, "ALL") == 0) {
1104             devcrypto_select_all_ciphers(selected_ciphers);
1105         } else if (strcasecmp((const char*)p, "NONE") == 0) {
1106             memset(selected_ciphers, 0, sizeof(selected_ciphers));
1107         } else {
1108             new_list=OPENSSL_zalloc(sizeof(selected_ciphers));
1109             if (!CONF_parse_list(p, ',', 1, cryptodev_select_cipher_cb, new_list)) {
1110                 OPENSSL_free(new_list);
1111                 return 0;
1112             }
1113             memcpy(selected_ciphers, new_list, sizeof(selected_ciphers));
1114             OPENSSL_free(new_list);
1115         }
1116         rebuild_known_cipher_nids(e);
1117         return 1;
1118
1119 #ifdef IMPLEMENT_DIGEST
1120     case DEVCRYPTO_CMD_DIGESTS:
1121         if (p == NULL)
1122             return 1;
1123         if (strcasecmp((const char *)p, "ALL") == 0) {
1124             devcrypto_select_all_digests(selected_digests);
1125         } else if (strcasecmp((const char*)p, "NONE") == 0) {
1126             memset(selected_digests, 0, sizeof(selected_digests));
1127         } else {
1128             new_list=OPENSSL_zalloc(sizeof(selected_digests));
1129             if (!CONF_parse_list(p, ',', 1, cryptodev_select_digest_cb, new_list)) {
1130                 OPENSSL_free(new_list);
1131                 return 0;
1132             }
1133             memcpy(selected_digests, new_list, sizeof(selected_digests));
1134             OPENSSL_free(new_list);
1135         }
1136         rebuild_known_digest_nids(e);
1137         return 1;
1138 #endif /* IMPLEMENT_DIGEST */
1139
1140     case DEVCRYPTO_CMD_DUMP_INFO:
1141         dump_cipher_info();
1142 #ifdef IMPLEMENT_DIGEST
1143         dump_digest_info();
1144 #endif
1145         return 1;
1146
1147     default:
1148         break;
1149     }
1150     return 0;
1151 }
1152
1153 /******************************************************************************
1154  *
1155  * LOAD / UNLOAD
1156  *
1157  *****/
1158
1159 /*
1160  * Opens /dev/crypto
1161  */
1162 static int open_devcrypto(void)
1163 {
1164     if (cfd >= 0)
1165         return 1;
1166
1167     if ((cfd = open("/dev/crypto", O_RDWR, 0)) < 0) {
1168 #ifndef ENGINE_DEVCRYPTO_DEBUG
1169         if (errno != ENOENT)
1170 #endif
1171             fprintf(stderr, "Could not open /dev/crypto: %s\n", strerror(errno));
1172         return 0;
1173     }
1174
1175     return 1;
1176 }
1177
1178 static int close_devcrypto(void)
1179 {
1180     if (cfd < 0)
1181         return 1;
1182     cfd = -1;
1183     if (close(cfd) == 0) {
1184         fprintf(stderr, "Error closing /dev/crypto: %s\n", strerror(errno));
1185         return 0;
1186     }
1187     return 1;
1188 }
1189
1190 static int devcrypto_unload(ENGINE *e)
1191 {
1192     destroy_all_cipher_methods();
1193 #ifdef IMPLEMENT_DIGEST
1194     destroy_all_digest_methods();
1195 #endif
1196
1197     close_devcrypto();
1198
1199     return 1;
1200 }
1201
1202 static int bind_devcrypto(ENGINE *e) {
1203
1204     if (!ENGINE_set_id(e, engine_devcrypto_id)
1205         || !ENGINE_set_name(e, "/dev/crypto engine")
1206         || !ENGINE_set_destroy_function(e, devcrypto_unload)
1207         || !ENGINE_set_cmd_defns(e, devcrypto_cmds)
1208         || !ENGINE_set_ctrl_function(e, devcrypto_ctrl))
1209         return 0;
1210
1211     prepare_cipher_methods();
1212 #ifdef IMPLEMENT_DIGEST
1213     prepare_digest_methods();
1214 #endif
1215
1216     return (ENGINE_set_ciphers(e, devcrypto_ciphers)
1217 #ifdef IMPLEMENT_DIGEST
1218         && ENGINE_set_digests(e, devcrypto_digests)
1219 #endif
1220 /*
1221  * Asymmetric ciphers aren't well supported with /dev/crypto.  Among the BSD
1222  * implementations, it seems to only exist in FreeBSD, and regarding the
1223  * parameters in its crypt_kop, the manual crypto(4) has this to say:
1224  *
1225  *    The semantics of these arguments are currently undocumented.
1226  *
1227  * Reading through the FreeBSD source code doesn't give much more than
1228  * their CRK_MOD_EXP implementation for ubsec.
1229  *
1230  * It doesn't look much better with cryptodev-linux.  They have the crypt_kop
1231  * structure as well as the command (CRK_*) in cryptodev.h, but no support
1232  * seems to be implemented at all for the moment.
1233  *
1234  * At the time of writing, it seems impossible to write proper support for
1235  * FreeBSD's asym features without some very deep knowledge and access to
1236  * specific kernel modules.
1237  *
1238  * /Richard Levitte, 2017-05-11
1239  */
1240 #if 0
1241 # ifndef OPENSSL_NO_RSA
1242         && ENGINE_set_RSA(e, devcrypto_rsa)
1243 # endif
1244 # ifndef OPENSSL_NO_DSA
1245         && ENGINE_set_DSA(e, devcrypto_dsa)
1246 # endif
1247 # ifndef OPENSSL_NO_DH
1248         && ENGINE_set_DH(e, devcrypto_dh)
1249 # endif
1250 # ifndef OPENSSL_NO_EC
1251         && ENGINE_set_EC(e, devcrypto_ec)
1252 # endif
1253 #endif
1254         );
1255 }
1256
1257 #ifdef OPENSSL_NO_DYNAMIC_ENGINE
1258 /*
1259  * In case this engine is built into libcrypto, then it doesn't offer any
1260  * ability to be dynamically loadable.
1261  */
1262 void engine_load_devcrypto_int(void)
1263 {
1264     ENGINE *e = NULL;
1265
1266     if (!open_devcrypto())
1267         return;
1268
1269     if ((e = ENGINE_new()) == NULL
1270         || !bind_devcrypto(e)) {
1271         close_devcrypto();
1272         ENGINE_free(e);
1273         return;
1274     }
1275
1276     ENGINE_add(e);
1277     ENGINE_free(e);          /* Loose our local reference */
1278     ERR_clear_error();
1279 }
1280
1281 #else
1282
1283 static int bind_helper(ENGINE *e, const char *id)
1284 {
1285     if ((id && (strcmp(id, engine_devcrypto_id) != 0))
1286         || !open_devcrypto())
1287         return 0;
1288     if (!bind_devcrypto(e)) {
1289         close_devcrypto();
1290         return 0;
1291     }
1292     return 1;
1293 }
1294
1295 IMPLEMENT_DYNAMIC_CHECK_FN()
1296 IMPLEMENT_DYNAMIC_BIND_FN(bind_helper)
1297
1298 #endif