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