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