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