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