2 * Copyright 2016 The OpenSSL Project Authors. All Rights Reserved.
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
10 /* Required for vmsplice */
18 #include <openssl/engine.h>
19 #include <openssl/async.h>
20 #include <openssl/err.h>
22 #include <sys/socket.h>
23 #include <linux/version.h>
27 #if LINUX_VERSION_CODE <= KERNEL_VERSION(K_MAJ, K_MIN1, K_MIN2) || \
29 # warning "AFALG ENGINE requires Kernel Headers >= 4.1.0"
30 # warning "Skipping Compilation of AFALG engine"
31 void engine_load_afalg_int(void)
36 # include <linux/if_alg.h>
38 # include <sys/utsname.h>
40 # include <linux/aio_abi.h>
41 # include <sys/syscall.h>
46 # define AFALG_LIB_NAME "AFALG"
47 # include "e_afalg_err.h"
54 # ifndef SPLICE_F_GIFT
55 # define SPLICE_F_GIFT (0x08)
59 # define ALG_AES_IV_LEN 16
60 # define ALG_IV_LEN(len) (sizeof(struct af_alg_iv) + (len))
61 # define ALG_OP_TYPE unsigned int
62 # define ALG_OP_LEN (sizeof(ALG_OP_TYPE))
64 #define ALG_MAX_SALG_NAME 64
65 #define ALG_MAX_SALG_TYPE 14
67 # ifdef OPENSSL_NO_DYNAMIC_ENGINE
68 void engine_load_afalg_int(void);
71 /* Local Linkage Functions */
72 static int afalg_init_aio(afalg_aio *aio);
73 static int afalg_fin_cipher_aio(afalg_aio *ptr, int sfd,
74 unsigned char *buf, size_t len);
75 static int afalg_create_sk(afalg_ctx *actx, const char *ciphertype,
76 const char *ciphername);
77 static int afalg_destroy(ENGINE *e);
78 static int afalg_init(ENGINE *e);
79 static int afalg_finish(ENGINE *e);
80 const EVP_CIPHER *afalg_aes_128_cbc(void);
81 static int afalg_ciphers(ENGINE *e, const EVP_CIPHER **cipher,
82 const int **nids, int nid);
83 static int afalg_cipher_init(EVP_CIPHER_CTX *ctx, const unsigned char *key,
84 const unsigned char *iv, int enc);
85 static int afalg_do_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
86 const unsigned char *in, size_t inl);
87 static int afalg_cipher_cleanup(EVP_CIPHER_CTX *ctx);
88 static int afalg_chk_platform(void);
90 /* Engine Id and Name */
91 static const char *engine_afalg_id = "afalg";
92 static const char *engine_afalg_name = "AFALG engine support";
94 static int afalg_cipher_nids[] = {
98 static EVP_CIPHER *_hidden_aes_128_cbc = NULL;
100 static ossl_inline int io_setup(unsigned n, aio_context_t *ctx)
102 return syscall(__NR_io_setup, n, ctx);
105 static ossl_inline int eventfd(int n)
107 return syscall(__NR_eventfd, n);
110 static ossl_inline int io_destroy(aio_context_t ctx)
112 return syscall(__NR_io_destroy, ctx);
115 static ossl_inline int io_read(aio_context_t ctx, long n, struct iocb **iocb)
117 return syscall(__NR_io_submit, ctx, n, iocb);
120 static ossl_inline int io_getevents(aio_context_t ctx, long min, long max,
121 struct io_event *events,
122 struct timespec *timeout)
124 return syscall(__NR_io_getevents, ctx, min, max, events, timeout);
127 static void afalg_waitfd_cleanup(ASYNC_WAIT_CTX *ctx, const void *key,
128 OSSL_ASYNC_FD waitfd, void *custom)
133 static int afalg_setup_async_event_notification(afalg_aio *aio)
136 ASYNC_WAIT_CTX *waitctx;
140 if ((job = ASYNC_get_current_job()) != NULL) {
142 waitctx = ASYNC_get_wait_ctx(job);
143 if (waitctx == NULL) {
144 ALG_WARN("%s: ASYNC_get_wait_ctx error", __func__);
147 /* Get waitfd from ASYNC_WAIT_CTX if it is alreday set */
148 ret = ASYNC_WAIT_CTX_get_fd(waitctx, engine_afalg_id,
152 * waitfd is not set in ASYNC_WAIT_CTX, create a new one
153 * and set it. efd will be signaled when AIO operation completes
155 aio->efd = eventfd(0);
156 if (aio->efd == -1) {
157 ALG_PERR("%s: Failed to get eventfd : ", __func__);
158 AFALGerr(AFALG_F_AFALG_SETUP_ASYNC_EVENT_NOTIFICATION,
159 AFALG_R_EVENTFD_FAILED);
162 ret = ASYNC_WAIT_CTX_set_wait_fd(waitctx, engine_afalg_id,
164 afalg_waitfd_cleanup);
166 ALG_WARN("%s: Failed to set wait fd", __func__);
170 /* make fd non-blocking in async mode */
171 if (fcntl(aio->efd, F_SETFL, O_NONBLOCK) != 0) {
172 ALG_WARN("%s: Failed to set event fd as NONBLOCKING",
176 aio->mode = MODE_ASYNC;
179 aio->efd = eventfd(0);
180 if (aio->efd == -1) {
181 ALG_PERR("%s: Failed to get eventfd : ", __func__);
182 AFALGerr(AFALG_F_AFALG_SETUP_ASYNC_EVENT_NOTIFICATION,
183 AFALG_R_EVENTFD_FAILED);
186 aio->mode = MODE_SYNC;
191 int afalg_init_aio(afalg_aio *aio)
195 /* Initialise for AIO */
197 r = io_setup(MAX_INFLIGHTS, &aio->aio_ctx);
199 ALG_PERR("%s: io_setup error : ", __func__);
200 AFALGerr(AFALG_F_AFALG_INIT_AIO, AFALG_R_IO_SETUP_FAILED);
204 memset(aio->cbt, 0, sizeof(aio->cbt));
206 aio->mode = MODE_UNINIT;
211 int afalg_fin_cipher_aio(afalg_aio *aio, int sfd, unsigned char *buf,
216 unsigned int done = 0;
218 struct timespec timeout;
219 struct io_event events[MAX_INFLIGHTS];
225 /* if efd has not been initialised yet do it here */
226 if (aio->mode == MODE_UNINIT) {
227 r = afalg_setup_async_event_notification(aio);
232 cb = &(aio->cbt[0 % MAX_INFLIGHTS]);
233 memset(cb, '\0', sizeof(*cb));
234 cb->aio_fildes = sfd;
235 cb->aio_lio_opcode = IOCB_CMD_PREAD;
236 if (sizeof(buf) != sizeof(cb->aio_buf)) {
238 * The pointer has to be converted to 32 bit unsigned value first
239 * to avoid sign extension on cast to 64 bit value
241 cb->aio_buf = (uint64_t)(unsigned long)buf;
243 cb->aio_buf = (uint64_t)buf;
247 cb->aio_nbytes = len;
248 cb->aio_flags = IOCB_FLAG_RESFD;
249 cb->aio_resfd = aio->efd;
252 * Perform AIO read on AFALG socket, this in turn performs an async
253 * crypto operation in kernel space
255 r = io_read(aio->aio_ctx, 1, &cb);
257 ALG_PWARN("%s: io_read failed : ", __func__);
262 /* While AIO read is being performed pause job */
265 /* Check for completion of AIO read */
266 r = read(aio->efd, &eval, sizeof(eval));
268 if (errno == EAGAIN || errno == EWOULDBLOCK)
270 ALG_PERR("%s: read failed for event fd : ", __func__);
272 } else if (r == 0 || eval <= 0) {
273 ALG_WARN("%s: eventfd read %d bytes, eval = %lu\n", __func__, r,
278 /* Get results of AIO read */
279 r = io_getevents(aio->aio_ctx, 1, MAX_INFLIGHTS,
283 * events.res indicates the actual status of the operation.
284 * Handle the error condition first.
286 if (events[0].res < 0) {
288 * Underlying operation cannot be completed at the time
289 * of previous submission. Resubmit for the operation.
291 if (events[0].res == -EBUSY && retry++ < 3) {
292 r = io_read(aio->aio_ctx, 1, &cb);
294 ALG_PERR("%s: retry %d for io_read failed : ",
301 * Retries exceed for -EBUSY or unrecoverable error
302 * condition for this instance of operation.
305 ("%s: Crypto Operation failed with code %lld\n",
306 __func__, events[0].res);
310 /* Operation successful. */
313 ALG_PERR("%s: io_getevents failed : ", __func__);
316 ALG_WARN("%s: io_geteventd read 0 bytes\n", __func__);
324 static ossl_inline void afalg_set_op_sk(struct cmsghdr *cmsg,
325 const ALG_OP_TYPE op)
327 cmsg->cmsg_level = SOL_ALG;
328 cmsg->cmsg_type = ALG_SET_OP;
329 cmsg->cmsg_len = CMSG_LEN(ALG_OP_LEN);
330 memcpy(CMSG_DATA(cmsg), &op, ALG_OP_LEN);
333 static void afalg_set_iv_sk(struct cmsghdr *cmsg, const unsigned char *iv,
334 const unsigned int len)
336 struct af_alg_iv *aiv;
338 cmsg->cmsg_level = SOL_ALG;
339 cmsg->cmsg_type = ALG_SET_IV;
340 cmsg->cmsg_len = CMSG_LEN(ALG_IV_LEN(len));
341 aiv = (struct af_alg_iv *)CMSG_DATA(cmsg);
343 memcpy(aiv->iv, iv, len);
346 static ossl_inline int afalg_set_key(afalg_ctx *actx, const unsigned char *key,
350 ret = setsockopt(actx->bfd, SOL_ALG, ALG_SET_KEY, key, klen);
352 ALG_PERR("%s: Failed to set socket option : ", __func__);
353 AFALGerr(AFALG_F_AFALG_SET_KEY, AFALG_R_SOCKET_SET_KEY_FAILED);
360 static int afalg_create_sk(afalg_ctx *actx, const char *ciphertype,
361 const char *ciphername)
363 struct sockaddr_alg sa;
365 actx->bfd = actx->sfd = -1;
368 memset(&sa, 0, sizeof(sa));
369 sa.salg_family = AF_ALG;
370 strncpy((char *) sa.salg_type, ciphertype, ALG_MAX_SALG_TYPE);
371 sa.salg_type[ALG_MAX_SALG_TYPE-1] = '\0';
372 strncpy((char *) sa.salg_name, ciphername, ALG_MAX_SALG_NAME);
373 sa.salg_name[ALG_MAX_SALG_NAME-1] = '\0';
375 actx->bfd = socket(AF_ALG, SOCK_SEQPACKET, 0);
376 if (actx->bfd == -1) {
377 ALG_PERR("%s: Failed to open socket : ", __func__);
378 AFALGerr(AFALG_F_AFALG_CREATE_SK, AFALG_R_SOCKET_CREATE_FAILED);
382 r = bind(actx->bfd, (struct sockaddr *)&sa, sizeof(sa));
384 ALG_PERR("%s: Failed to bind socket : ", __func__);
385 AFALGerr(AFALG_F_AFALG_CREATE_SK, AFALG_R_SOCKET_BIND_FAILED);
389 actx->sfd = accept(actx->bfd, NULL, 0);
391 ALG_PERR("%s: Socket Accept Failed : ", __func__);
392 AFALGerr(AFALG_F_AFALG_CREATE_SK, AFALG_R_SOCKET_ACCEPT_FAILED);
403 actx->bfd = actx->sfd = -1;
407 static int afalg_start_cipher_sk(afalg_ctx *actx, const unsigned char *in,
408 size_t inl, const unsigned char *iv,
411 struct msghdr msg = { 0 };
412 struct cmsghdr *cmsg;
415 # ifdef ALG_ZERO_COPY
418 char cbuf[CMSG_SPACE(ALG_IV_LEN(ALG_AES_IV_LEN)) + CMSG_SPACE(ALG_OP_LEN)];
420 memset(cbuf, 0, sizeof(cbuf));
421 msg.msg_control = cbuf;
422 msg.msg_controllen = sizeof(cbuf);
425 * cipher direction (i.e. encrypt or decrypt) and iv are sent to the
426 * kernel as part of sendmsg()'s ancillary data
428 cmsg = CMSG_FIRSTHDR(&msg);
429 afalg_set_op_sk(cmsg, enc);
430 cmsg = CMSG_NXTHDR(&msg, cmsg);
431 afalg_set_iv_sk(cmsg, iv, ALG_AES_IV_LEN);
433 /* iov that describes input data */
434 iov.iov_base = (unsigned char *)in;
437 msg.msg_flags = MSG_MORE;
439 # ifdef ALG_ZERO_COPY
442 * Works best when buffer is 4k aligned
443 * OPENS: out of place processing (i.e. out != in)
446 /* Input data is not sent as part of call to sendmsg() */
450 /* Sendmsg() sends iv and cipher direction to the kernel */
451 sbytes = sendmsg(actx->sfd, &msg, 0);
453 ALG_PERR("%s: sendmsg failed for zero copy cipher operation : ",
459 * vmsplice and splice are used to pin the user space input buffer for
460 * kernel space processing avoiding copys from user to kernel space
462 ret = vmsplice(actx->zc_pipe[1], &iov, 1, SPLICE_F_GIFT);
464 ALG_PERR("%s: vmsplice failed : ", __func__);
468 ret = splice(actx->zc_pipe[0], NULL, actx->sfd, NULL, inl, 0);
470 ALG_PERR("%s: splice failed : ", __func__);
477 /* Sendmsg() sends iv, cipher direction and input data to the kernel */
478 sbytes = sendmsg(actx->sfd, &msg, 0);
480 ALG_PERR("%s: sendmsg failed for cipher operation : ", __func__);
484 if (sbytes != (ssize_t) inl) {
485 ALG_WARN("Cipher operation send bytes %zd != inlen %zd\n", sbytes,
494 static int afalg_cipher_init(EVP_CIPHER_CTX *ctx, const unsigned char *key,
495 const unsigned char *iv, int enc)
500 char ciphername[ALG_MAX_SALG_NAME];
502 if (ctx == NULL || key == NULL) {
503 ALG_WARN("%s: Null Parameter\n", __func__);
507 if (EVP_CIPHER_CTX_cipher(ctx) == NULL) {
508 ALG_WARN("%s: Cipher object NULL\n", __func__);
512 actx = EVP_CIPHER_CTX_get_cipher_data(ctx);
514 ALG_WARN("%s: Cipher data NULL\n", __func__);
518 ciphertype = EVP_CIPHER_CTX_nid(ctx);
519 switch (ciphertype) {
520 case NID_aes_128_cbc:
521 strncpy(ciphername, "cbc(aes)", ALG_MAX_SALG_NAME);
524 ALG_WARN("%s: Unsupported Cipher type %d\n", __func__, ciphertype);
527 ciphername[ALG_MAX_SALG_NAME-1]='\0';
529 if (ALG_AES_IV_LEN != EVP_CIPHER_CTX_iv_length(ctx)) {
530 ALG_WARN("%s: Unsupported IV length :%d\n", __func__,
531 EVP_CIPHER_CTX_iv_length(ctx));
535 /* Setup AFALG socket for crypto processing */
536 ret = afalg_create_sk(actx, "skcipher", ciphername);
541 ret = afalg_set_key(actx, key, EVP_CIPHER_CTX_key_length(ctx));
545 /* Setup AIO ctx to allow async AFALG crypto processing */
546 if (afalg_init_aio(&actx->aio) == 0)
549 # ifdef ALG_ZERO_COPY
553 actx->init_done = MAGIC_INIT_NUM;
563 static int afalg_do_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
564 const unsigned char *in, size_t inl)
568 char nxtiv[ALG_AES_IV_LEN] = { 0 };
570 if (ctx == NULL || out == NULL || in == NULL) {
571 ALG_WARN("NULL parameter passed to function %s\n", __func__);
575 actx = (afalg_ctx *) EVP_CIPHER_CTX_get_cipher_data(ctx);
576 if (actx == NULL || actx->init_done != MAGIC_INIT_NUM) {
577 ALG_WARN("%s afalg ctx passed\n",
578 ctx == NULL ? "NULL" : "Uninitialised");
583 * set iv now for decrypt operation as the input buffer can be
584 * overwritten for inplace operation where in = out.
586 if (EVP_CIPHER_CTX_encrypting(ctx) == 0) {
587 memcpy(nxtiv, in + (inl - ALG_AES_IV_LEN), ALG_AES_IV_LEN);
590 /* Send input data to kernel space */
591 ret = afalg_start_cipher_sk(actx, (unsigned char *)in, inl,
592 EVP_CIPHER_CTX_iv(ctx),
593 EVP_CIPHER_CTX_encrypting(ctx));
598 /* Perform async crypto operation in kernel space */
599 ret = afalg_fin_cipher_aio(&actx->aio, actx->sfd, out, inl);
603 if (EVP_CIPHER_CTX_encrypting(ctx)) {
604 memcpy(EVP_CIPHER_CTX_iv_noconst(ctx), out + (inl - ALG_AES_IV_LEN),
607 memcpy(EVP_CIPHER_CTX_iv_noconst(ctx), nxtiv, ALG_AES_IV_LEN);
613 static int afalg_cipher_cleanup(EVP_CIPHER_CTX *ctx)
618 ALG_WARN("NULL parameter passed to function %s\n", __func__);
622 actx = (afalg_ctx *) EVP_CIPHER_CTX_get_cipher_data(ctx);
623 if (actx == NULL || actx->init_done != MAGIC_INIT_NUM) {
624 ALG_WARN("%s afalg ctx passed\n",
625 ctx == NULL ? "NULL" : "Uninitialised");
631 # ifdef ALG_ZERO_COPY
632 close(actx->zc_pipe[0]);
633 close(actx->zc_pipe[1]);
635 /* close efd in sync mode, async mode is closed in afalg_waitfd_cleanup() */
636 if (actx->aio.mode == MODE_SYNC)
637 close(actx->aio.efd);
638 io_destroy(actx->aio.aio_ctx);
643 const EVP_CIPHER *afalg_aes_128_cbc(void)
645 if (_hidden_aes_128_cbc == NULL
646 && ((_hidden_aes_128_cbc =
647 EVP_CIPHER_meth_new(NID_aes_128_cbc,
649 AES_KEY_SIZE_128)) == NULL
650 || !EVP_CIPHER_meth_set_iv_length(_hidden_aes_128_cbc, AES_IV_LEN)
651 || !EVP_CIPHER_meth_set_flags(_hidden_aes_128_cbc,
653 EVP_CIPH_FLAG_DEFAULT_ASN1)
654 || !EVP_CIPHER_meth_set_init(_hidden_aes_128_cbc,
656 || !EVP_CIPHER_meth_set_do_cipher(_hidden_aes_128_cbc,
658 || !EVP_CIPHER_meth_set_cleanup(_hidden_aes_128_cbc,
659 afalg_cipher_cleanup)
660 || !EVP_CIPHER_meth_set_impl_ctx_size(_hidden_aes_128_cbc,
661 sizeof(afalg_ctx)))) {
662 EVP_CIPHER_meth_free(_hidden_aes_128_cbc);
663 _hidden_aes_128_cbc = NULL;
665 return _hidden_aes_128_cbc;
668 static int afalg_ciphers(ENGINE *e, const EVP_CIPHER **cipher,
669 const int **nids, int nid)
673 if (cipher == NULL) {
674 *nids = afalg_cipher_nids;
675 return (sizeof(afalg_cipher_nids) / sizeof(afalg_cipher_nids[0]));
679 case NID_aes_128_cbc:
680 *cipher = afalg_aes_128_cbc();
690 static int bind_afalg(ENGINE *e)
692 /* Ensure the afalg error handling is set up */
693 ERR_load_AFALG_strings();
695 if (!ENGINE_set_id(e, engine_afalg_id)
696 || !ENGINE_set_name(e, engine_afalg_name)
697 || !ENGINE_set_destroy_function(e, afalg_destroy)
698 || !ENGINE_set_init_function(e, afalg_init)
699 || !ENGINE_set_finish_function(e, afalg_finish)) {
700 AFALGerr(AFALG_F_BIND_AFALG, AFALG_R_INIT_FAILED);
705 * Create _hidden_aes_128_cbc by calling afalg_aes_128_cbc
706 * now, as bind_aflag can only be called by one thread at a
709 if (afalg_aes_128_cbc() == NULL) {
710 AFALGerr(AFALG_F_BIND_AFALG, AFALG_R_INIT_FAILED);
714 if (!ENGINE_set_ciphers(e, afalg_ciphers)) {
715 AFALGerr(AFALG_F_BIND_AFALG, AFALG_R_INIT_FAILED);
722 # ifndef OPENSSL_NO_DYNAMIC_ENGINE
723 static int bind_helper(ENGINE *e, const char *id)
725 if (id && (strcmp(id, engine_afalg_id) != 0))
728 if (!afalg_chk_platform())
736 IMPLEMENT_DYNAMIC_CHECK_FN()
737 IMPLEMENT_DYNAMIC_BIND_FN(bind_helper)
740 static int afalg_chk_platform(void)
744 int kver[3] = { -1, -1, -1 };
751 AFALGerr(AFALG_F_AFALG_CHK_PLATFORM,
752 AFALG_R_FAILED_TO_GET_PLATFORM_INFO);
756 str = strtok(ut.release, ".");
757 for (i = 0; i < 3 && str != NULL; i++) {
759 str = strtok(NULL, ".");
762 if (KERNEL_VERSION(kver[0], kver[1], kver[2])
763 < KERNEL_VERSION(K_MAJ, K_MIN1, K_MIN2)) {
764 ALG_ERR("ASYNC AFALG not supported this kernel(%d.%d.%d)\n",
765 kver[0], kver[1], kver[2]);
766 ALG_ERR("ASYNC AFALG requires kernel version %d.%d.%d or later\n",
767 K_MAJ, K_MIN1, K_MIN2);
768 AFALGerr(AFALG_F_AFALG_CHK_PLATFORM,
769 AFALG_R_KERNEL_DOES_NOT_SUPPORT_ASYNC_AFALG);
773 /* Test if we can actually create an AF_ALG socket */
774 sock = socket(AF_ALG, SOCK_SEQPACKET, 0);
776 AFALGerr(AFALG_F_AFALG_CHK_PLATFORM, AFALG_R_SOCKET_CREATE_FAILED);
784 # ifdef OPENSSL_NO_DYNAMIC_ENGINE
785 static ENGINE *engine_afalg(void)
787 ENGINE *ret = ENGINE_new();
790 if (!bind_afalg(ret)) {
797 void engine_load_afalg_int(void)
801 if (!afalg_chk_platform())
804 toadd = engine_afalg();
813 static int afalg_init(ENGINE *e)
818 static int afalg_finish(ENGINE *e)
823 static int afalg_destroy(ENGINE *e)
825 ERR_unload_AFALG_strings();
826 EVP_CIPHER_meth_free(_hidden_aes_128_cbc);
827 _hidden_aes_128_cbc = NULL;
831 #endif /* KERNEL VERSION */