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