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