extending afalg with aes-cbc-192/256, afalgtest.c also updated accordingly. comments...
[openssl.git] / engines / e_afalg.c
1 /*
2  * Copyright 2016 The OpenSSL Project Authors. All Rights Reserved.
3  *
4  * Licensed under the OpenSSL license (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 /* Required for vmsplice */
11 #ifndef _GNU_SOURCE
12 # define _GNU_SOURCE
13 #endif
14 #include <stdio.h>
15 #include <string.h>
16 #include <unistd.h>
17
18 #include <openssl/engine.h>
19 #include <openssl/async.h>
20 #include <openssl/err.h>
21 #include "internal/nelem.h"
22
23 #include <sys/socket.h>
24 #include <linux/version.h>
25 #define K_MAJ   4
26 #define K_MIN1  1
27 #define K_MIN2  0
28 #if LINUX_VERSION_CODE < KERNEL_VERSION(K_MAJ, K_MIN1, K_MIN2) || \
29     !defined(AF_ALG)
30 # ifndef PEDANTIC
31 #  warning "AFALG ENGINE requires Kernel Headers >= 4.1.0"
32 #  warning "Skipping Compilation of AFALG engine"
33 # endif
34 void engine_load_afalg_int(void);
35 void engine_load_afalg_int(void)
36 {
37 }
38 #else
39
40 # include <linux/if_alg.h>
41 # include <fcntl.h>
42 # include <sys/utsname.h>
43
44 # include <linux/aio_abi.h>
45 # include <sys/syscall.h>
46 # include <errno.h>
47
48 # include "e_afalg.h"
49 # include "e_afalg_err.c"
50
51 # ifndef SOL_ALG
52 #  define SOL_ALG 279
53 # endif
54
55 # ifdef ALG_ZERO_COPY
56 #  ifndef SPLICE_F_GIFT
57 #   define SPLICE_F_GIFT    (0x08)
58 #  endif
59 # endif
60
61 # define ALG_AES_IV_LEN 16
62 # define ALG_IV_LEN(len) (sizeof(struct af_alg_iv) + (len))
63 # define ALG_OP_TYPE     unsigned int
64 # define ALG_OP_LEN      (sizeof(ALG_OP_TYPE))
65
66 #define ALG_MAX_SALG_NAME       64
67 #define ALG_MAX_SALG_TYPE       14
68
69 # ifdef OPENSSL_NO_DYNAMIC_ENGINE
70 void engine_load_afalg_int(void);
71 # endif
72
73 /* Local Linkage Functions */
74 static int afalg_init_aio(afalg_aio *aio);
75 static int afalg_fin_cipher_aio(afalg_aio *ptr, int sfd,
76                                 unsigned char *buf, size_t len);
77 static int afalg_create_sk(afalg_ctx *actx, const char *ciphertype,
78                                 const char *ciphername);
79 static int afalg_destroy(ENGINE *e);
80 static int afalg_init(ENGINE *e);
81 static int afalg_finish(ENGINE *e);
82 const EVP_CIPHER *afalg_aes_cbc(int nid);
83 static int afalg_ciphers(ENGINE *e, const EVP_CIPHER **cipher,
84                          const int **nids, int nid);
85 static int afalg_cipher_init(EVP_CIPHER_CTX *ctx, const unsigned char *key,
86                              const unsigned char *iv, int enc);
87 static int afalg_do_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
88                            const unsigned char *in, size_t inl);
89 static int afalg_cipher_cleanup(EVP_CIPHER_CTX *ctx);
90 static int afalg_chk_platform(void);
91
92 /* Engine Id and Name */
93 static const char *engine_afalg_id = "afalg";
94 static const char *engine_afalg_name = "AFALG engine support";
95
96 static int afalg_cipher_nids[] = {
97     NID_aes_128_cbc,
98     NID_aes_192_cbc,
99     NID_aes_256_cbc,
100 };
101
102 static cbc_handles cbc_handle[] = {{AES_KEY_SIZE_128, NULL},
103                                     {AES_KEY_SIZE_192, NULL},
104                                     {AES_KEY_SIZE_256, NULL}};
105
106 static ossl_inline int io_setup(unsigned n, aio_context_t *ctx)
107 {
108     return syscall(__NR_io_setup, n, ctx);
109 }
110
111 static ossl_inline int eventfd(int n)
112 {
113     return syscall(__NR_eventfd2, n, 0);
114 }
115
116 static ossl_inline int io_destroy(aio_context_t ctx)
117 {
118     return syscall(__NR_io_destroy, ctx);
119 }
120
121 static ossl_inline int io_read(aio_context_t ctx, long n, struct iocb **iocb)
122 {
123     return syscall(__NR_io_submit, ctx, n, iocb);
124 }
125
126 static ossl_inline int io_getevents(aio_context_t ctx, long min, long max,
127                                struct io_event *events,
128                                struct timespec *timeout)
129 {
130     return syscall(__NR_io_getevents, ctx, min, max, events, timeout);
131 }
132
133 static void afalg_waitfd_cleanup(ASYNC_WAIT_CTX *ctx, const void *key,
134                                  OSSL_ASYNC_FD waitfd, void *custom)
135 {
136     close(waitfd);
137 }
138
139 static int afalg_setup_async_event_notification(afalg_aio *aio)
140 {
141     ASYNC_JOB *job;
142     ASYNC_WAIT_CTX *waitctx;
143     void *custom = NULL;
144     int ret;
145
146     if ((job = ASYNC_get_current_job()) != NULL) {
147         /* Async mode */
148         waitctx = ASYNC_get_wait_ctx(job);
149         if (waitctx == NULL) {
150             ALG_WARN("%s: ASYNC_get_wait_ctx error", __func__);
151             return 0;
152         }
153         /* Get waitfd from ASYNC_WAIT_CTX if it is already set */
154         ret = ASYNC_WAIT_CTX_get_fd(waitctx, engine_afalg_id,
155                                     &aio->efd, &custom);
156         if (ret == 0) {
157             /*
158              * waitfd is not set in ASYNC_WAIT_CTX, create a new one
159              * and set it. efd will be signaled when AIO operation completes
160              */
161             aio->efd = eventfd(0);
162             if (aio->efd == -1) {
163                 ALG_PERR("%s: Failed to get eventfd : ", __func__);
164                 AFALGerr(AFALG_F_AFALG_SETUP_ASYNC_EVENT_NOTIFICATION,
165                          AFALG_R_EVENTFD_FAILED);
166                 return 0;
167             }
168             ret = ASYNC_WAIT_CTX_set_wait_fd(waitctx, engine_afalg_id,
169                                              aio->efd, custom,
170                                              afalg_waitfd_cleanup);
171             if (ret == 0) {
172                 ALG_WARN("%s: Failed to set wait fd", __func__);
173                 close(aio->efd);
174                 return 0;
175             }
176             /* make fd non-blocking in async mode */
177             if (fcntl(aio->efd, F_SETFL, O_NONBLOCK) != 0) {
178                 ALG_WARN("%s: Failed to set event fd as NONBLOCKING",
179                          __func__);
180             }
181         }
182         aio->mode = MODE_ASYNC;
183     } else {
184         /* Sync mode */
185         aio->efd = eventfd(0);
186         if (aio->efd == -1) {
187             ALG_PERR("%s: Failed to get eventfd : ", __func__);
188             AFALGerr(AFALG_F_AFALG_SETUP_ASYNC_EVENT_NOTIFICATION,
189                      AFALG_R_EVENTFD_FAILED);
190             return 0;
191         }
192         aio->mode = MODE_SYNC;
193     }
194     return 1;
195 }
196
197 int afalg_init_aio(afalg_aio *aio)
198 {
199     int r = -1;
200
201     /* Initialise for AIO */
202     aio->aio_ctx = 0;
203     r = io_setup(MAX_INFLIGHTS, &aio->aio_ctx);
204     if (r < 0) {
205         ALG_PERR("%s: io_setup error : ", __func__);
206         AFALGerr(AFALG_F_AFALG_INIT_AIO, AFALG_R_IO_SETUP_FAILED);
207         return 0;
208     }
209
210     memset(aio->cbt, 0, sizeof(aio->cbt));
211     aio->efd = -1;
212     aio->mode = MODE_UNINIT;
213
214     return 1;
215 }
216
217 int afalg_fin_cipher_aio(afalg_aio *aio, int sfd, unsigned char *buf,
218                          size_t len)
219 {
220     int r;
221     int retry = 0;
222     unsigned int done = 0;
223     struct iocb *cb;
224     struct timespec timeout;
225     struct io_event events[MAX_INFLIGHTS];
226     u_int64_t eval = 0;
227
228     timeout.tv_sec = 0;
229     timeout.tv_nsec = 0;
230
231     /* if efd has not been initialised yet do it here */
232     if (aio->mode == MODE_UNINIT) {
233         r = afalg_setup_async_event_notification(aio);
234         if (r == 0)
235             return 0;
236     }
237
238     cb = &(aio->cbt[0 % MAX_INFLIGHTS]);
239     memset(cb, '\0', sizeof(*cb));
240     cb->aio_fildes = sfd;
241     cb->aio_lio_opcode = IOCB_CMD_PREAD;
242     /*
243      * The pointer has to be converted to unsigned value first to avoid
244      * sign extension on cast to 64 bit value in 32-bit builds
245      */
246     cb->aio_buf = (size_t)buf;
247     cb->aio_offset = 0;
248     cb->aio_data = 0;
249     cb->aio_nbytes = len;
250     cb->aio_flags = IOCB_FLAG_RESFD;
251     cb->aio_resfd = aio->efd;
252
253     /*
254      * Perform AIO read on AFALG socket, this in turn performs an async
255      * crypto operation in kernel space
256      */
257     r = io_read(aio->aio_ctx, 1, &cb);
258     if (r < 0) {
259         ALG_PWARN("%s: io_read failed : ", __func__);
260         return 0;
261     }
262
263     do {
264         /* While AIO read is being performed pause job */
265         ASYNC_pause_job();
266
267         /* Check for completion of AIO read */
268         r = read(aio->efd, &eval, sizeof(eval));
269         if (r < 0) {
270             if (errno == EAGAIN || errno == EWOULDBLOCK)
271                 continue;
272             ALG_PERR("%s: read failed for event fd : ", __func__);
273             return 0;
274         } else if (r == 0 || eval <= 0) {
275             ALG_WARN("%s: eventfd read %d bytes, eval = %lu\n", __func__, r,
276                      eval);
277         }
278         if (eval > 0) {
279
280             /* Get results of AIO read */
281             r = io_getevents(aio->aio_ctx, 1, MAX_INFLIGHTS,
282                              events, &timeout);
283             if (r > 0) {
284                 /*
285                  * events.res indicates the actual status of the operation.
286                  * Handle the error condition first.
287                  */
288                 if (events[0].res < 0) {
289                     /*
290                      * Underlying operation cannot be completed at the time
291                      * of previous submission. Resubmit for the operation.
292                      */
293                     if (events[0].res == -EBUSY && retry++ < 3) {
294                         r = io_read(aio->aio_ctx, 1, &cb);
295                         if (r < 0) {
296                             ALG_PERR("%s: retry %d for io_read failed : ",
297                                      __func__, retry);
298                             return 0;
299                         }
300                         continue;
301                     } else {
302                         /*
303                          * Retries exceed for -EBUSY or unrecoverable error
304                          * condition for this instance of operation.
305                          */
306                         ALG_WARN
307                             ("%s: Crypto Operation failed with code %lld\n",
308                              __func__, events[0].res);
309                         return 0;
310                     }
311                 }
312                 /* Operation successful. */
313                 done = 1;
314             } else if (r < 0) {
315                 ALG_PERR("%s: io_getevents failed : ", __func__);
316                 return 0;
317             } else {
318                 ALG_WARN("%s: io_geteventd read 0 bytes\n", __func__);
319             }
320         }
321     } while (!done);
322
323     return 1;
324 }
325
326 static ossl_inline void afalg_set_op_sk(struct cmsghdr *cmsg,
327                                    const ALG_OP_TYPE op)
328 {
329     cmsg->cmsg_level = SOL_ALG;
330     cmsg->cmsg_type = ALG_SET_OP;
331     cmsg->cmsg_len = CMSG_LEN(ALG_OP_LEN);
332     memcpy(CMSG_DATA(cmsg), &op, ALG_OP_LEN);
333 }
334
335 static void afalg_set_iv_sk(struct cmsghdr *cmsg, const unsigned char *iv,
336                             const unsigned int len)
337 {
338     struct af_alg_iv *aiv;
339
340     cmsg->cmsg_level = SOL_ALG;
341     cmsg->cmsg_type = ALG_SET_IV;
342     cmsg->cmsg_len = CMSG_LEN(ALG_IV_LEN(len));
343     aiv = (struct af_alg_iv *)CMSG_DATA(cmsg);
344     aiv->ivlen = len;
345     memcpy(aiv->iv, iv, len);
346 }
347
348 static ossl_inline int afalg_set_key(afalg_ctx *actx, const unsigned char *key,
349                                 const int klen)
350 {
351     int ret;
352     ret = setsockopt(actx->bfd, SOL_ALG, ALG_SET_KEY, key, klen);
353     if (ret < 0) {
354         ALG_PERR("%s: Failed to set socket option : ", __func__);
355         AFALGerr(AFALG_F_AFALG_SET_KEY, AFALG_R_SOCKET_SET_KEY_FAILED);
356         return 0;
357     }
358     return 1;
359 }
360
361 static int afalg_create_sk(afalg_ctx *actx, const char *ciphertype,
362                                 const char *ciphername)
363 {
364     struct sockaddr_alg sa;
365     int r = -1;
366
367     actx->bfd = actx->sfd = -1;
368
369     memset(&sa, 0, sizeof(sa));
370     sa.salg_family = AF_ALG;
371     strncpy((char *) sa.salg_type, ciphertype, ALG_MAX_SALG_TYPE);
372     sa.salg_type[ALG_MAX_SALG_TYPE-1] = '\0';
373     strncpy((char *) sa.salg_name, ciphername, ALG_MAX_SALG_NAME);
374     sa.salg_name[ALG_MAX_SALG_NAME-1] = '\0';
375
376     actx->bfd = socket(AF_ALG, SOCK_SEQPACKET, 0);
377     if (actx->bfd == -1) {
378         ALG_PERR("%s: Failed to open socket : ", __func__);
379         AFALGerr(AFALG_F_AFALG_CREATE_SK, AFALG_R_SOCKET_CREATE_FAILED);
380         goto err;
381     }
382
383     r = bind(actx->bfd, (struct sockaddr *)&sa, sizeof(sa));
384     if (r < 0) {
385         ALG_PERR("%s: Failed to bind socket : ", __func__);
386         AFALGerr(AFALG_F_AFALG_CREATE_SK, AFALG_R_SOCKET_BIND_FAILED);
387         goto err;
388     }
389
390     actx->sfd = accept(actx->bfd, NULL, 0);
391     if (actx->sfd < 0) {
392         ALG_PERR("%s: Socket Accept Failed : ", __func__);
393         AFALGerr(AFALG_F_AFALG_CREATE_SK, AFALG_R_SOCKET_ACCEPT_FAILED);
394         goto err;
395     }
396
397     return 1;
398
399  err:
400     if (actx->bfd >= 0)
401         close(actx->bfd);
402     if (actx->sfd >= 0)
403         close(actx->sfd);
404     actx->bfd = actx->sfd = -1;
405     return 0;
406 }
407
408 static int afalg_start_cipher_sk(afalg_ctx *actx, const unsigned char *in,
409                                  size_t inl, const unsigned char *iv,
410                                  unsigned int enc)
411 {
412     struct msghdr msg = { 0 };
413     struct cmsghdr *cmsg;
414     struct iovec iov;
415     ssize_t sbytes;
416 # ifdef ALG_ZERO_COPY
417     int ret;
418 # endif
419     char cbuf[CMSG_SPACE(ALG_IV_LEN(ALG_AES_IV_LEN)) + CMSG_SPACE(ALG_OP_LEN)];
420
421     memset(cbuf, 0, sizeof(cbuf));
422     msg.msg_control = cbuf;
423     msg.msg_controllen = sizeof(cbuf);
424
425     /*
426      * cipher direction (i.e. encrypt or decrypt) and iv are sent to the
427      * kernel as part of sendmsg()'s ancillary data
428      */
429     cmsg = CMSG_FIRSTHDR(&msg);
430     afalg_set_op_sk(cmsg, enc);
431     cmsg = CMSG_NXTHDR(&msg, cmsg);
432     afalg_set_iv_sk(cmsg, iv, ALG_AES_IV_LEN);
433
434     /* iov that describes input data */
435     iov.iov_base = (unsigned char *)in;
436     iov.iov_len = inl;
437
438     msg.msg_flags = MSG_MORE;
439
440 # ifdef ALG_ZERO_COPY
441     /*
442      * ZERO_COPY mode
443      * Works best when buffer is 4k aligned
444      * OPENS: out of place processing (i.e. out != in)
445      */
446
447     /* Input data is not sent as part of call to sendmsg() */
448     msg.msg_iovlen = 0;
449     msg.msg_iov = NULL;
450
451     /* Sendmsg() sends iv and cipher direction to the kernel */
452     sbytes = sendmsg(actx->sfd, &msg, 0);
453     if (sbytes < 0) {
454         ALG_PERR("%s: sendmsg failed for zero copy cipher operation : ",
455                  __func__);
456         return 0;
457     }
458
459     /*
460      * vmsplice and splice are used to pin the user space input buffer for
461      * kernel space processing avoiding copys from user to kernel space
462      */
463     ret = vmsplice(actx->zc_pipe[1], &iov, 1, SPLICE_F_GIFT);
464     if (ret < 0) {
465         ALG_PERR("%s: vmsplice failed : ", __func__);
466         return 0;
467     }
468
469     ret = splice(actx->zc_pipe[0], NULL, actx->sfd, NULL, inl, 0);
470     if (ret < 0) {
471         ALG_PERR("%s: splice failed : ", __func__);
472         return 0;
473     }
474 # else
475     msg.msg_iovlen = 1;
476     msg.msg_iov = &iov;
477
478     /* Sendmsg() sends iv, cipher direction and input data to the kernel */
479     sbytes = sendmsg(actx->sfd, &msg, 0);
480     if (sbytes < 0) {
481         ALG_PERR("%s: sendmsg failed for cipher operation : ", __func__);
482         return 0;
483     }
484
485     if (sbytes != (ssize_t) inl) {
486         ALG_WARN("Cipher operation send bytes %zd != inlen %zd\n", sbytes,
487                 inl);
488         return 0;
489     }
490 # endif
491
492     return 1;
493 }
494
495 static int afalg_cipher_init(EVP_CIPHER_CTX *ctx, const unsigned char *key,
496                              const unsigned char *iv, int enc)
497 {
498     int ciphertype;
499     int ret;
500     afalg_ctx *actx;
501     char ciphername[ALG_MAX_SALG_NAME];
502
503     if (ctx == NULL || key == NULL) {
504         ALG_WARN("%s: Null Parameter\n", __func__);
505         return 0;
506     }
507
508     if (EVP_CIPHER_CTX_cipher(ctx) == NULL) {
509         ALG_WARN("%s: Cipher object NULL\n", __func__);
510         return 0;
511     }
512
513     actx = EVP_CIPHER_CTX_get_cipher_data(ctx);
514     if (actx == NULL) {
515         ALG_WARN("%s: Cipher data NULL\n", __func__);
516         return 0;
517     }
518
519     ciphertype = EVP_CIPHER_CTX_nid(ctx);
520     switch (ciphertype) {
521     case NID_aes_128_cbc:
522     case NID_aes_192_cbc:
523     case NID_aes_256_cbc:
524         strncpy(ciphername, "cbc(aes)", ALG_MAX_SALG_NAME);
525         break;
526     default:
527         ALG_WARN("%s: Unsupported Cipher type %d\n", __func__, ciphertype);
528         return 0;
529     }
530     ciphername[ALG_MAX_SALG_NAME-1]='\0';
531
532     if (ALG_AES_IV_LEN != EVP_CIPHER_CTX_iv_length(ctx)) {
533         ALG_WARN("%s: Unsupported IV length :%d\n", __func__,
534                 EVP_CIPHER_CTX_iv_length(ctx));
535         return 0;
536     }
537
538     /* Setup AFALG socket for crypto processing */
539     ret = afalg_create_sk(actx, "skcipher", ciphername);
540     if (ret < 1)
541         return 0;
542
543
544     ret = afalg_set_key(actx, key, EVP_CIPHER_CTX_key_length(ctx));
545     if (ret < 1)
546         goto err;
547
548     /* Setup AIO ctx to allow async AFALG crypto processing */
549     if (afalg_init_aio(&actx->aio) == 0)
550         goto err;
551
552 # ifdef ALG_ZERO_COPY
553     pipe(actx->zc_pipe);
554 # endif
555
556     actx->init_done = MAGIC_INIT_NUM;
557
558     return 1;
559
560 err:
561     close(actx->sfd);
562     close(actx->bfd);
563     return 0;
564 }
565
566 static int afalg_do_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
567                            const unsigned char *in, size_t inl)
568 {
569     afalg_ctx *actx;
570     int ret;
571     char nxtiv[ALG_AES_IV_LEN] = { 0 };
572
573     if (ctx == NULL || out == NULL || in == NULL) {
574         ALG_WARN("NULL parameter passed to function %s\n", __func__);
575         return 0;
576     }
577
578     actx = (afalg_ctx *) EVP_CIPHER_CTX_get_cipher_data(ctx);
579     if (actx == NULL || actx->init_done != MAGIC_INIT_NUM) {
580         ALG_WARN("%s afalg ctx passed\n",
581                  ctx == NULL ? "NULL" : "Uninitialised");
582         return 0;
583     }
584
585     /*
586      * set iv now for decrypt operation as the input buffer can be
587      * overwritten for inplace operation where in = out.
588      */
589     if (EVP_CIPHER_CTX_encrypting(ctx) == 0) {
590         memcpy(nxtiv, in + (inl - ALG_AES_IV_LEN), ALG_AES_IV_LEN);
591     }
592
593     /* Send input data to kernel space */
594     ret = afalg_start_cipher_sk(actx, (unsigned char *)in, inl,
595                                 EVP_CIPHER_CTX_iv(ctx),
596                                 EVP_CIPHER_CTX_encrypting(ctx));
597     if (ret < 1) {
598         return 0;
599     }
600
601     /* Perform async crypto operation in kernel space */
602     ret = afalg_fin_cipher_aio(&actx->aio, actx->sfd, out, inl);
603     if (ret < 1)
604         return 0;
605
606     if (EVP_CIPHER_CTX_encrypting(ctx)) {
607         memcpy(EVP_CIPHER_CTX_iv_noconst(ctx), out + (inl - ALG_AES_IV_LEN),
608                ALG_AES_IV_LEN);
609     } else {
610         memcpy(EVP_CIPHER_CTX_iv_noconst(ctx), nxtiv, ALG_AES_IV_LEN);
611     }
612
613     return 1;
614 }
615
616 static int afalg_cipher_cleanup(EVP_CIPHER_CTX *ctx)
617 {
618     afalg_ctx *actx;
619
620     if (ctx == NULL) {
621         ALG_WARN("NULL parameter passed to function %s\n", __func__);
622         return 0;
623     }
624
625     actx = (afalg_ctx *) EVP_CIPHER_CTX_get_cipher_data(ctx);
626     if (actx == NULL || actx->init_done != MAGIC_INIT_NUM) {
627         ALG_WARN("%s afalg ctx passed\n",
628                  ctx == NULL ? "NULL" : "Uninitialised");
629         return 0;
630     }
631
632     close(actx->sfd);
633     close(actx->bfd);
634 # ifdef ALG_ZERO_COPY
635     close(actx->zc_pipe[0]);
636     close(actx->zc_pipe[1]);
637 # endif
638     /* close efd in sync mode, async mode is closed in afalg_waitfd_cleanup() */
639     if (actx->aio.mode == MODE_SYNC)
640         close(actx->aio.efd);
641     io_destroy(actx->aio.aio_ctx);
642
643     return 1;
644 }
645
646 cbc_handles *get_cipher_handle(int nid)
647 {
648     switch (nid) {
649     case NID_aes_128_cbc:
650         return &cbc_handle[AES_CBC_128];
651     case NID_aes_192_cbc:
652         return &cbc_handle[AES_CBC_192];
653     case NID_aes_256_cbc:
654         return &cbc_handle[AES_CBC_256];
655     default:
656         return NULL;
657     }
658 }
659
660 const EVP_CIPHER *afalg_aes_cbc(int nid)
661 {
662     cbc_handles *cipher_handle = get_cipher_handle(nid);
663     if (cipher_handle->_hidden == NULL
664         && ((cipher_handle->_hidden =
665          EVP_CIPHER_meth_new(nid,
666                              AES_BLOCK_SIZE,
667                              cipher_handle->key_size)) == NULL
668         || !EVP_CIPHER_meth_set_iv_length(cipher_handle->_hidden,
669                                           AES_IV_LEN)
670         || !EVP_CIPHER_meth_set_flags(cipher_handle->_hidden,
671                                       EVP_CIPH_CBC_MODE |
672                                       EVP_CIPH_FLAG_DEFAULT_ASN1)
673         || !EVP_CIPHER_meth_set_init(cipher_handle->_hidden,
674                                      afalg_cipher_init)
675         || !EVP_CIPHER_meth_set_do_cipher(cipher_handle->_hidden,
676                                           afalg_do_cipher)
677         || !EVP_CIPHER_meth_set_cleanup(cipher_handle->_hidden,
678                                         afalg_cipher_cleanup)
679         || !EVP_CIPHER_meth_set_impl_ctx_size(cipher_handle->_hidden,
680                                               sizeof(afalg_ctx)))) {
681         EVP_CIPHER_meth_free(cipher_handle->_hidden);
682         cipher_handle->_hidden= NULL;
683     }
684     return cipher_handle->_hidden;
685 }
686
687 static int afalg_ciphers(ENGINE *e, const EVP_CIPHER **cipher,
688                          const int **nids, int nid)
689 {
690     int r = 1;
691
692     if (cipher == NULL) {
693         *nids = afalg_cipher_nids;
694         return (sizeof(afalg_cipher_nids) / sizeof(afalg_cipher_nids[0]));
695     }
696
697     switch (nid) {
698     case NID_aes_128_cbc:
699     case NID_aes_192_cbc:
700     case NID_aes_256_cbc:
701         *cipher = afalg_aes_cbc(nid);
702         break;
703     default:
704         *cipher = NULL;
705         r = 0;
706     }
707     return r;
708 }
709
710 static int bind_afalg(ENGINE *e)
711 {
712     /* Ensure the afalg error handling is set up */
713     unsigned short i;
714     ERR_load_AFALG_strings();
715
716     if (!ENGINE_set_id(e, engine_afalg_id)
717         || !ENGINE_set_name(e, engine_afalg_name)
718         || !ENGINE_set_destroy_function(e, afalg_destroy)
719         || !ENGINE_set_init_function(e, afalg_init)
720         || !ENGINE_set_finish_function(e, afalg_finish)) {
721         AFALGerr(AFALG_F_BIND_AFALG, AFALG_R_INIT_FAILED);
722         return 0;
723     }
724
725     /*
726      * Create _hidden_aes_xxx_cbc by calling afalg_aes_xxx_cbc
727      * now, as bind_aflag can only be called by one thread at a
728      * time.
729      */
730     for(i = 0; i < OSSL_NELEM(afalg_cipher_nids); i++) {
731         if (afalg_aes_cbc(afalg_cipher_nids[i]) == NULL) {
732             AFALGerr(AFALG_F_BIND_AFALG, AFALG_R_INIT_FAILED);
733             return 0;
734         }
735     }
736
737     if (!ENGINE_set_ciphers(e, afalg_ciphers)) {
738         AFALGerr(AFALG_F_BIND_AFALG, AFALG_R_INIT_FAILED);
739         return 0;
740     }
741
742     return 1;
743 }
744
745 # ifndef OPENSSL_NO_DYNAMIC_ENGINE
746 static int bind_helper(ENGINE *e, const char *id)
747 {
748     if (id && (strcmp(id, engine_afalg_id) != 0))
749         return 0;
750
751     if (!afalg_chk_platform())
752         return 0;
753
754     if (!bind_afalg(e))
755         return 0;
756     return 1;
757 }
758
759 IMPLEMENT_DYNAMIC_CHECK_FN()
760     IMPLEMENT_DYNAMIC_BIND_FN(bind_helper)
761 # endif
762
763 static int afalg_chk_platform(void)
764 {
765     int ret;
766     int i;
767     int kver[3] = { -1, -1, -1 };
768     int sock;
769     char *str;
770     struct utsname ut;
771
772     ret = uname(&ut);
773     if (ret != 0) {
774         AFALGerr(AFALG_F_AFALG_CHK_PLATFORM,
775                  AFALG_R_FAILED_TO_GET_PLATFORM_INFO);
776         return 0;
777     }
778
779     str = strtok(ut.release, ".");
780     for (i = 0; i < 3 && str != NULL; i++) {
781         kver[i] = atoi(str);
782         str = strtok(NULL, ".");
783     }
784
785     if (KERNEL_VERSION(kver[0], kver[1], kver[2])
786         < KERNEL_VERSION(K_MAJ, K_MIN1, K_MIN2)) {
787         ALG_ERR("ASYNC AFALG not supported this kernel(%d.%d.%d)\n",
788                  kver[0], kver[1], kver[2]);
789         ALG_ERR("ASYNC AFALG requires kernel version %d.%d.%d or later\n",
790                  K_MAJ, K_MIN1, K_MIN2);
791         AFALGerr(AFALG_F_AFALG_CHK_PLATFORM,
792                  AFALG_R_KERNEL_DOES_NOT_SUPPORT_ASYNC_AFALG);
793         return 0;
794     }
795
796     /* Test if we can actually create an AF_ALG socket */
797     sock = socket(AF_ALG, SOCK_SEQPACKET, 0);
798     if (sock == -1) {
799         AFALGerr(AFALG_F_AFALG_CHK_PLATFORM, AFALG_R_SOCKET_CREATE_FAILED);
800         return 0;
801     }
802     close(sock);
803
804     return 1;
805 }
806
807 # ifdef OPENSSL_NO_DYNAMIC_ENGINE
808 static ENGINE *engine_afalg(void)
809 {
810     ENGINE *ret = ENGINE_new();
811     if (ret == NULL)
812         return NULL;
813     if (!bind_afalg(ret)) {
814         ENGINE_free(ret);
815         return NULL;
816     }
817     return ret;
818 }
819
820 void engine_load_afalg_int(void)
821 {
822     ENGINE *toadd;
823
824     if (!afalg_chk_platform())
825         return;
826
827     toadd = engine_afalg();
828     if (toadd == NULL)
829         return;
830     ENGINE_add(toadd);
831     ENGINE_free(toadd);
832     ERR_clear_error();
833 }
834 # endif
835
836 static int afalg_init(ENGINE *e)
837 {
838     return 1;
839 }
840
841 static int afalg_finish(ENGINE *e)
842 {
843     return 1;
844 }
845
846 static int free_cbc(void)
847 {
848     short int i;
849     for(i = 0; i < OSSL_NELEM(afalg_cipher_nids); i++) {
850         EVP_CIPHER_meth_free(cbc_handle[i]._hidden);
851         cbc_handle[i]._hidden = NULL;
852     }
853     return 1;
854 }
855
856 static int afalg_destroy(ENGINE *e)
857 {
858     ERR_unload_AFALG_strings();
859     free_cbc();
860     return 1;
861 }
862
863 #endif                          /* KERNEL VERSION */