8e019d4903efd91db7ff2a7602e1ea12ebae9661
[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 void engine_load_afalg_int(void)
33 {
34 }
35 #else
36
37 # include <linux/if_alg.h>
38 # include <fcntl.h>
39 # include <sys/utsname.h>
40
41 # include <linux/aio_abi.h>
42 # include <sys/syscall.h>
43 # include <errno.h>
44
45 # include "e_afalg.h"
46
47 # define AFALG_LIB_NAME "AFALG"
48 # include "e_afalg_err.h"
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     if (sizeof(buf) != sizeof(cb->aio_buf)) {
238         /*
239          * The pointer has to be converted to 32 bit unsigned value first
240          * to avoid sign extension on cast to 64 bit value
241          */
242         cb->aio_buf = (uint64_t)(unsigned long)buf;
243     } else {
244         cb->aio_buf = (uint64_t)buf;
245     }
246     cb->aio_offset = 0;
247     cb->aio_data = 0;
248     cb->aio_nbytes = len;
249     cb->aio_flags = IOCB_FLAG_RESFD;
250     cb->aio_resfd = aio->efd;
251
252     /*
253      * Perform AIO read on AFALG socket, this in turn performs an async
254      * crypto operation in kernel space
255      */
256     r = io_read(aio->aio_ctx, 1, &cb);
257     if (r < 0) {
258         ALG_PWARN("%s: io_read failed : ", __func__);
259         return 0;
260     }
261
262     do {
263         /* While AIO read is being performed pause job */
264         ASYNC_pause_job();
265
266         /* Check for completion of AIO read */
267         r = read(aio->efd, &eval, sizeof(eval));
268         if (r < 0) {
269             if (errno == EAGAIN || errno == EWOULDBLOCK)
270                 continue;
271             ALG_PERR("%s: read failed for event fd : ", __func__);
272             return 0;
273         } else if (r == 0 || eval <= 0) {
274             ALG_WARN("%s: eventfd read %d bytes, eval = %lu\n", __func__, r,
275                      eval);
276         }
277         if (eval > 0) {
278
279             /* Get results of AIO read */
280             r = io_getevents(aio->aio_ctx, 1, MAX_INFLIGHTS,
281                              events, &timeout);
282             if (r > 0) {
283                 /*
284                  * events.res indicates the actual status of the operation.
285                  * Handle the error condition first.
286                  */
287                 if (events[0].res < 0) {
288                     /*
289                      * Underlying operation cannot be completed at the time
290                      * of previous submission. Resubmit for the operation.
291                      */
292                     if (events[0].res == -EBUSY && retry++ < 3) {
293                         r = io_read(aio->aio_ctx, 1, &cb);
294                         if (r < 0) {
295                             ALG_PERR("%s: retry %d for io_read failed : ",
296                                      __func__, retry);
297                             return 0;
298                         }
299                         continue;
300                     } else {
301                         /*
302                          * Retries exceed for -EBUSY or unrecoverable error
303                          * condition for this instance of operation.
304                          */
305                         ALG_WARN
306                             ("%s: Crypto Operation failed with code %lld\n",
307                              __func__, events[0].res);
308                         return 0;
309                     }
310                 }
311                 /* Operation successful. */
312                 done = 1;
313             } else if (r < 0) {
314                 ALG_PERR("%s: io_getevents failed : ", __func__);
315                 return 0;
316             } else {
317                 ALG_WARN("%s: io_geteventd read 0 bytes\n", __func__);
318             }
319         }
320     } while (!done);
321
322     return 1;
323 }
324
325 static ossl_inline void afalg_set_op_sk(struct cmsghdr *cmsg,
326                                    const ALG_OP_TYPE op)
327 {
328     cmsg->cmsg_level = SOL_ALG;
329     cmsg->cmsg_type = ALG_SET_OP;
330     cmsg->cmsg_len = CMSG_LEN(ALG_OP_LEN);
331     memcpy(CMSG_DATA(cmsg), &op, ALG_OP_LEN);
332 }
333
334 static void afalg_set_iv_sk(struct cmsghdr *cmsg, const unsigned char *iv,
335                             const unsigned int len)
336 {
337     struct af_alg_iv *aiv;
338
339     cmsg->cmsg_level = SOL_ALG;
340     cmsg->cmsg_type = ALG_SET_IV;
341     cmsg->cmsg_len = CMSG_LEN(ALG_IV_LEN(len));
342     aiv = (struct af_alg_iv *)CMSG_DATA(cmsg);
343     aiv->ivlen = len;
344     memcpy(aiv->iv, iv, len);
345 }
346
347 static ossl_inline int afalg_set_key(afalg_ctx *actx, const unsigned char *key,
348                                 const int klen)
349 {
350     int ret;
351     ret = setsockopt(actx->bfd, SOL_ALG, ALG_SET_KEY, key, klen);
352     if (ret < 0) {
353         ALG_PERR("%s: Failed to set socket option : ", __func__);
354         AFALGerr(AFALG_F_AFALG_SET_KEY, AFALG_R_SOCKET_SET_KEY_FAILED);
355         return 0;
356     }
357
358     return 1;
359 }
360
361 static int afalg_create_sk(afalg_ctx *actx, const char *ciphertype,
362                                 const char *ciphername)
363 {
364     struct sockaddr_alg sa;
365
366     actx->bfd = actx->sfd = -1;
367     int r = -1;
368
369     memset(&sa, 0, sizeof(sa));
370     sa.salg_family = AF_ALG;
371     strncpy((char *) sa.salg_type, ciphertype, ALG_MAX_SALG_TYPE);
372     sa.salg_type[ALG_MAX_SALG_TYPE-1] = '\0';
373     strncpy((char *) sa.salg_name, ciphername, ALG_MAX_SALG_NAME);
374     sa.salg_name[ALG_MAX_SALG_NAME-1] = '\0';
375
376     actx->bfd = socket(AF_ALG, SOCK_SEQPACKET, 0);
377     if (actx->bfd == -1) {
378         ALG_PERR("%s: Failed to open socket : ", __func__);
379         AFALGerr(AFALG_F_AFALG_CREATE_SK, AFALG_R_SOCKET_CREATE_FAILED);
380         goto err;
381     }
382
383     r = bind(actx->bfd, (struct sockaddr *)&sa, sizeof(sa));
384     if (r < 0) {
385         ALG_PERR("%s: Failed to bind socket : ", __func__);
386         AFALGerr(AFALG_F_AFALG_CREATE_SK, AFALG_R_SOCKET_BIND_FAILED);
387         goto err;
388     }
389
390     actx->sfd = accept(actx->bfd, NULL, 0);
391     if (actx->sfd < 0) {
392         ALG_PERR("%s: Socket Accept Failed : ", __func__);
393         AFALGerr(AFALG_F_AFALG_CREATE_SK, AFALG_R_SOCKET_ACCEPT_FAILED);
394         goto err;
395     }
396
397     return 1;
398
399  err:
400     if (actx->bfd >= 0)
401         close(actx->bfd);
402     if (actx->sfd >= 0)
403         close(actx->sfd);
404     actx->bfd = actx->sfd = -1;
405     return 0;
406 }
407
408 static int afalg_start_cipher_sk(afalg_ctx *actx, const unsigned char *in,
409                                  size_t inl, const unsigned char *iv,
410                                  unsigned int enc)
411 {
412     struct msghdr msg = { 0 };
413     struct cmsghdr *cmsg;
414     struct iovec iov;
415     ssize_t sbytes;
416 # ifdef ALG_ZERO_COPY
417     int ret;
418 # endif
419     char cbuf[CMSG_SPACE(ALG_IV_LEN(ALG_AES_IV_LEN)) + CMSG_SPACE(ALG_OP_LEN)];
420
421     memset(cbuf, 0, sizeof(cbuf));
422     msg.msg_control = cbuf;
423     msg.msg_controllen = sizeof(cbuf);
424
425     /*
426      * cipher direction (i.e. encrypt or decrypt) and iv are sent to the
427      * kernel as part of sendmsg()'s ancillary data
428      */
429     cmsg = CMSG_FIRSTHDR(&msg);
430     afalg_set_op_sk(cmsg, enc);
431     cmsg = CMSG_NXTHDR(&msg, cmsg);
432     afalg_set_iv_sk(cmsg, iv, ALG_AES_IV_LEN);
433
434     /* iov that describes input data */
435     iov.iov_base = (unsigned char *)in;
436     iov.iov_len = inl;
437
438     msg.msg_flags = MSG_MORE;
439
440 # ifdef ALG_ZERO_COPY
441     /*
442      * ZERO_COPY mode
443      * Works best when buffer is 4k aligned
444      * OPENS: out of place processing (i.e. out != in)
445      */
446
447     /* Input data is not sent as part of call to sendmsg() */
448     msg.msg_iovlen = 0;
449     msg.msg_iov = NULL;
450
451     /* Sendmsg() sends iv and cipher direction to the kernel */
452     sbytes = sendmsg(actx->sfd, &msg, 0);
453     if (sbytes < 0) {
454         ALG_PERR("%s: sendmsg failed for zero copy cipher operation : ",
455                  __func__);
456         return 0;
457     }
458
459     /*
460      * vmsplice and splice are used to pin the user space input buffer for
461      * kernel space processing avoiding copys from user to kernel space
462      */
463     ret = vmsplice(actx->zc_pipe[1], &iov, 1, SPLICE_F_GIFT);
464     if (ret < 0) {
465         ALG_PERR("%s: vmsplice failed : ", __func__);
466         return 0;
467     }
468
469     ret = splice(actx->zc_pipe[0], NULL, actx->sfd, NULL, inl, 0);
470     if (ret < 0) {
471         ALG_PERR("%s: splice failed : ", __func__);
472         return 0;
473     }
474 # else
475     msg.msg_iovlen = 1;
476     msg.msg_iov = &iov;
477
478     /* Sendmsg() sends iv, cipher direction and input data to the kernel */
479     sbytes = sendmsg(actx->sfd, &msg, 0);
480     if (sbytes < 0) {
481         ALG_PERR("%s: sendmsg failed for cipher operation : ", __func__);
482         return 0;
483     }
484
485     if (sbytes != (ssize_t) inl) {
486         ALG_WARN("Cipher operation send bytes %zd != inlen %zd\n", sbytes,
487                 inl);
488         return 0;
489     }
490 # endif
491
492     return 1;
493 }
494
495 static int afalg_cipher_init(EVP_CIPHER_CTX *ctx, const unsigned char *key,
496                              const unsigned char *iv, int enc)
497 {
498     int ciphertype;
499     int ret;
500     afalg_ctx *actx;
501     char ciphername[ALG_MAX_SALG_NAME];
502
503     if (ctx == NULL || key == NULL) {
504         ALG_WARN("%s: Null Parameter\n", __func__);
505         return 0;
506     }
507
508     if (EVP_CIPHER_CTX_cipher(ctx) == NULL) {
509         ALG_WARN("%s: Cipher object NULL\n", __func__);
510         return 0;
511     }
512
513     actx = EVP_CIPHER_CTX_get_cipher_data(ctx);
514     if (actx == NULL) {
515         ALG_WARN("%s: Cipher data NULL\n", __func__);
516         return 0;
517     }
518
519     ciphertype = EVP_CIPHER_CTX_nid(ctx);
520     switch (ciphertype) {
521     case NID_aes_128_cbc:
522         strncpy(ciphername, "cbc(aes)", ALG_MAX_SALG_NAME);
523         break;
524     default:
525         ALG_WARN("%s: Unsupported Cipher type %d\n", __func__, ciphertype);
526         return 0;
527     }
528     ciphername[ALG_MAX_SALG_NAME-1]='\0';
529
530     if (ALG_AES_IV_LEN != EVP_CIPHER_CTX_iv_length(ctx)) {
531         ALG_WARN("%s: Unsupported IV length :%d\n", __func__,
532                 EVP_CIPHER_CTX_iv_length(ctx));
533         return 0;
534     }
535
536     /* Setup AFALG socket for crypto processing */
537     ret = afalg_create_sk(actx, "skcipher", ciphername);
538     if (ret < 1)
539         return 0;
540
541
542     ret = afalg_set_key(actx, key, EVP_CIPHER_CTX_key_length(ctx));
543     if (ret < 1)
544         goto err;
545
546     /* Setup AIO ctx to allow async AFALG crypto processing */
547     if (afalg_init_aio(&actx->aio) == 0)
548         goto err;
549
550 # ifdef ALG_ZERO_COPY
551     pipe(actx->zc_pipe);
552 # endif
553
554     actx->init_done = MAGIC_INIT_NUM;
555
556     return 1;
557
558 err:
559     close(actx->sfd);
560     close(actx->bfd);
561     return 0;
562 }
563
564 static int afalg_do_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
565                            const unsigned char *in, size_t inl)
566 {
567     afalg_ctx *actx;
568     int ret;
569     char nxtiv[ALG_AES_IV_LEN] = { 0 };
570
571     if (ctx == NULL || out == NULL || in == NULL) {
572         ALG_WARN("NULL parameter passed to function %s\n", __func__);
573         return 0;
574     }
575
576     actx = (afalg_ctx *) EVP_CIPHER_CTX_get_cipher_data(ctx);
577     if (actx == NULL || actx->init_done != MAGIC_INIT_NUM) {
578         ALG_WARN("%s afalg ctx passed\n",
579                  ctx == NULL ? "NULL" : "Uninitialised");
580         return 0;
581     }
582
583     /*
584      * set iv now for decrypt operation as the input buffer can be
585      * overwritten for inplace operation where in = out.
586      */
587     if (EVP_CIPHER_CTX_encrypting(ctx) == 0) {
588         memcpy(nxtiv, in + (inl - ALG_AES_IV_LEN), ALG_AES_IV_LEN);
589     }
590
591     /* Send input data to kernel space */
592     ret = afalg_start_cipher_sk(actx, (unsigned char *)in, inl,
593                                 EVP_CIPHER_CTX_iv(ctx),
594                                 EVP_CIPHER_CTX_encrypting(ctx));
595     if (ret < 1) {
596         return 0;
597     }
598
599     /* Perform async crypto operation in kernel space */
600     ret = afalg_fin_cipher_aio(&actx->aio, actx->sfd, out, inl);
601     if (ret < 1)
602         return 0;
603
604     if (EVP_CIPHER_CTX_encrypting(ctx)) {
605         memcpy(EVP_CIPHER_CTX_iv_noconst(ctx), out + (inl - ALG_AES_IV_LEN),
606                ALG_AES_IV_LEN);
607     } else {
608         memcpy(EVP_CIPHER_CTX_iv_noconst(ctx), nxtiv, ALG_AES_IV_LEN);
609     }
610
611     return 1;
612 }
613
614 static int afalg_cipher_cleanup(EVP_CIPHER_CTX *ctx)
615 {
616     afalg_ctx *actx;
617
618     if (ctx == NULL) {
619         ALG_WARN("NULL parameter passed to function %s\n", __func__);
620         return 0;
621     }
622
623     actx = (afalg_ctx *) EVP_CIPHER_CTX_get_cipher_data(ctx);
624     if (actx == NULL || actx->init_done != MAGIC_INIT_NUM) {
625         ALG_WARN("%s afalg ctx passed\n",
626                  ctx == NULL ? "NULL" : "Uninitialised");
627         return 0;
628     }
629
630     close(actx->sfd);
631     close(actx->bfd);
632 # ifdef ALG_ZERO_COPY
633     close(actx->zc_pipe[0]);
634     close(actx->zc_pipe[1]);
635 # endif
636     /* close efd in sync mode, async mode is closed in afalg_waitfd_cleanup() */
637     if (actx->aio.mode == MODE_SYNC)
638         close(actx->aio.efd);
639     io_destroy(actx->aio.aio_ctx);
640
641     return 1;
642 }
643
644 const EVP_CIPHER *afalg_aes_128_cbc(void)
645 {
646     if (_hidden_aes_128_cbc == NULL
647         && ((_hidden_aes_128_cbc =
648              EVP_CIPHER_meth_new(NID_aes_128_cbc,
649                                  AES_BLOCK_SIZE,
650                                  AES_KEY_SIZE_128)) == NULL
651             || !EVP_CIPHER_meth_set_iv_length(_hidden_aes_128_cbc, AES_IV_LEN)
652             || !EVP_CIPHER_meth_set_flags(_hidden_aes_128_cbc,
653                                           EVP_CIPH_CBC_MODE |
654                                           EVP_CIPH_FLAG_DEFAULT_ASN1)
655             || !EVP_CIPHER_meth_set_init(_hidden_aes_128_cbc,
656                                          afalg_cipher_init)
657             || !EVP_CIPHER_meth_set_do_cipher(_hidden_aes_128_cbc,
658                                               afalg_do_cipher)
659             || !EVP_CIPHER_meth_set_cleanup(_hidden_aes_128_cbc,
660                                             afalg_cipher_cleanup)
661             || !EVP_CIPHER_meth_set_impl_ctx_size(_hidden_aes_128_cbc,
662                                                   sizeof(afalg_ctx)))) {
663         EVP_CIPHER_meth_free(_hidden_aes_128_cbc);
664         _hidden_aes_128_cbc = NULL;
665     }
666     return _hidden_aes_128_cbc;
667 }
668
669 static int afalg_ciphers(ENGINE *e, const EVP_CIPHER **cipher,
670                          const int **nids, int nid)
671 {
672     int r = 1;
673
674     if (cipher == NULL) {
675         *nids = afalg_cipher_nids;
676         return (sizeof(afalg_cipher_nids) / sizeof(afalg_cipher_nids[0]));
677     }
678
679     switch (nid) {
680     case NID_aes_128_cbc:
681         *cipher = afalg_aes_128_cbc();
682         break;
683     default:
684         *cipher = NULL;
685         r = 0;
686     }
687
688     return r;
689 }
690
691 static int bind_afalg(ENGINE *e)
692 {
693     /* Ensure the afalg error handling is set up */
694     ERR_load_AFALG_strings();
695
696     if (!ENGINE_set_id(e, engine_afalg_id)
697         || !ENGINE_set_name(e, engine_afalg_name)
698         || !ENGINE_set_destroy_function(e, afalg_destroy)
699         || !ENGINE_set_init_function(e, afalg_init)
700         || !ENGINE_set_finish_function(e, afalg_finish)) {
701         AFALGerr(AFALG_F_BIND_AFALG, AFALG_R_INIT_FAILED);
702         return 0;
703     }
704
705     /*
706      * Create _hidden_aes_128_cbc by calling afalg_aes_128_cbc
707      * now, as bind_aflag can only be called by one thread at a
708      * time.
709      */
710     if (afalg_aes_128_cbc() == NULL) {
711         AFALGerr(AFALG_F_BIND_AFALG, AFALG_R_INIT_FAILED);
712         return 0;
713     }
714
715     if (!ENGINE_set_ciphers(e, afalg_ciphers)) {
716         AFALGerr(AFALG_F_BIND_AFALG, AFALG_R_INIT_FAILED);
717         return 0;
718     }
719
720     return 1;
721 }
722
723 # ifndef OPENSSL_NO_DYNAMIC_ENGINE
724 static int bind_helper(ENGINE *e, const char *id)
725 {
726     if (id && (strcmp(id, engine_afalg_id) != 0))
727         return 0;
728
729     if (!afalg_chk_platform())
730         return 0;
731
732     if (!bind_afalg(e))
733         return 0;
734     return 1;
735 }
736
737 IMPLEMENT_DYNAMIC_CHECK_FN()
738     IMPLEMENT_DYNAMIC_BIND_FN(bind_helper)
739 # endif
740
741 static int afalg_chk_platform(void)
742 {
743     int ret;
744     int i;
745     int kver[3] = { -1, -1, -1 };
746     int sock;
747     char *str;
748     struct utsname ut;
749
750     ret = uname(&ut);
751     if (ret != 0) {
752         AFALGerr(AFALG_F_AFALG_CHK_PLATFORM,
753                  AFALG_R_FAILED_TO_GET_PLATFORM_INFO);
754         return 0;
755     }
756
757     str = strtok(ut.release, ".");
758     for (i = 0; i < 3 && str != NULL; i++) {
759         kver[i] = atoi(str);
760         str = strtok(NULL, ".");
761     }
762
763     if (KERNEL_VERSION(kver[0], kver[1], kver[2])
764         < KERNEL_VERSION(K_MAJ, K_MIN1, K_MIN2)) {
765         ALG_ERR("ASYNC AFALG not supported this kernel(%d.%d.%d)\n",
766                  kver[0], kver[1], kver[2]);
767         ALG_ERR("ASYNC AFALG requires kernel version %d.%d.%d or later\n",
768                  K_MAJ, K_MIN1, K_MIN2);
769         AFALGerr(AFALG_F_AFALG_CHK_PLATFORM,
770                  AFALG_R_KERNEL_DOES_NOT_SUPPORT_ASYNC_AFALG);
771         return 0;
772     }
773
774     /* Test if we can actually create an AF_ALG socket */
775     sock = socket(AF_ALG, SOCK_SEQPACKET, 0);
776     if (sock == -1) {
777         AFALGerr(AFALG_F_AFALG_CHK_PLATFORM, AFALG_R_SOCKET_CREATE_FAILED);
778         return 0;
779     }
780     close(sock);
781
782     return 1;
783 }
784
785 # ifdef OPENSSL_NO_DYNAMIC_ENGINE
786 static ENGINE *engine_afalg(void)
787 {
788     ENGINE *ret = ENGINE_new();
789     if (ret == NULL)
790         return NULL;
791     if (!bind_afalg(ret)) {
792         ENGINE_free(ret);
793         return NULL;
794     }
795     return ret;
796 }
797
798 void engine_load_afalg_int(void)
799 {
800     ENGINE *toadd;
801
802     if (!afalg_chk_platform())
803         return;
804
805     toadd = engine_afalg();
806     if (toadd == NULL)
807         return;
808     ENGINE_add(toadd);
809     ENGINE_free(toadd);
810     ERR_clear_error();
811 }
812 # endif
813
814 static int afalg_init(ENGINE *e)
815 {
816     return 1;
817 }
818
819 static int afalg_finish(ENGINE *e)
820 {
821     return 1;
822 }
823
824 static int afalg_destroy(ENGINE *e)
825 {
826     ERR_unload_AFALG_strings();
827     EVP_CIPHER_meth_free(_hidden_aes_128_cbc);
828     _hidden_aes_128_cbc = NULL;
829     return 1;
830 }
831
832 #endif                          /* KERNEL VERSION */