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