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