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