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