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) || \
30 # warning "AFALG ENGINE requires Kernel Headers >= 4.1.0"
31 # warning "Skipping Compilation of AFALG engine"
33 void engine_load_afalg_int(void);
34 void engine_load_afalg_int(void)
39 # include <linux/if_alg.h>
41 # include <sys/utsname.h>
43 # include <linux/aio_abi.h>
44 # include <sys/syscall.h>
49 # define AFALG_LIB_NAME "AFALG"
50 # include "e_afalg_err.h"
57 # ifndef SPLICE_F_GIFT
58 # define SPLICE_F_GIFT (0x08)
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))
67 #define ALG_MAX_SALG_NAME 64
68 #define ALG_MAX_SALG_TYPE 14
70 # ifdef OPENSSL_NO_DYNAMIC_ENGINE
71 void engine_load_afalg_int(void);
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);
93 /* Engine Id and Name */
94 static const char *engine_afalg_id = "afalg";
95 static const char *engine_afalg_name = "AFALG engine support";
97 static int afalg_cipher_nids[] = {
101 static EVP_CIPHER *_hidden_aes_128_cbc = NULL;
103 static ossl_inline int io_setup(unsigned n, aio_context_t *ctx)
105 return syscall(__NR_io_setup, n, ctx);
108 static ossl_inline int eventfd(int n)
110 return syscall(__NR_eventfd, n);
113 static ossl_inline int io_destroy(aio_context_t ctx)
115 return syscall(__NR_io_destroy, ctx);
118 static ossl_inline int io_read(aio_context_t ctx, long n, struct iocb **iocb)
120 return syscall(__NR_io_submit, ctx, n, iocb);
123 static ossl_inline int io_getevents(aio_context_t ctx, long min, long max,
124 struct io_event *events,
125 struct timespec *timeout)
127 return syscall(__NR_io_getevents, ctx, min, max, events, timeout);
130 static void afalg_waitfd_cleanup(ASYNC_WAIT_CTX *ctx, const void *key,
131 OSSL_ASYNC_FD waitfd, void *custom)
136 static int afalg_setup_async_event_notification(afalg_aio *aio)
139 ASYNC_WAIT_CTX *waitctx;
143 if ((job = ASYNC_get_current_job()) != NULL) {
145 waitctx = ASYNC_get_wait_ctx(job);
146 if (waitctx == NULL) {
147 ALG_WARN("%s: ASYNC_get_wait_ctx error", __func__);
150 /* Get waitfd from ASYNC_WAIT_CTX if it is alreday set */
151 ret = ASYNC_WAIT_CTX_get_fd(waitctx, engine_afalg_id,
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
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);
165 ret = ASYNC_WAIT_CTX_set_wait_fd(waitctx, engine_afalg_id,
167 afalg_waitfd_cleanup);
169 ALG_WARN("%s: Failed to set wait fd", __func__);
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",
179 aio->mode = MODE_ASYNC;
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);
189 aio->mode = MODE_SYNC;
194 int afalg_init_aio(afalg_aio *aio)
198 /* Initialise for AIO */
200 r = io_setup(MAX_INFLIGHTS, &aio->aio_ctx);
202 ALG_PERR("%s: io_setup error : ", __func__);
203 AFALGerr(AFALG_F_AFALG_INIT_AIO, AFALG_R_IO_SETUP_FAILED);
207 memset(aio->cbt, 0, sizeof(aio->cbt));
209 aio->mode = MODE_UNINIT;
214 int afalg_fin_cipher_aio(afalg_aio *aio, int sfd, unsigned char *buf,
219 unsigned int done = 0;
221 struct timespec timeout;
222 struct io_event events[MAX_INFLIGHTS];
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);
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;
240 * The pointer has to be converted to unsigned value first to avoid
241 * sign extension on cast to 64 bit value in 32-bit builds
243 cb->aio_buf = (size_t)buf;
246 cb->aio_nbytes = len;
247 cb->aio_flags = IOCB_FLAG_RESFD;
248 cb->aio_resfd = aio->efd;
251 * Perform AIO read on AFALG socket, this in turn performs an async
252 * crypto operation in kernel space
254 r = io_read(aio->aio_ctx, 1, &cb);
256 ALG_PWARN("%s: io_read failed : ", __func__);
261 /* While AIO read is being performed pause job */
264 /* Check for completion of AIO read */
265 r = read(aio->efd, &eval, sizeof(eval));
267 if (errno == EAGAIN || errno == EWOULDBLOCK)
269 ALG_PERR("%s: read failed for event fd : ", __func__);
271 } else if (r == 0 || eval <= 0) {
272 ALG_WARN("%s: eventfd read %d bytes, eval = %lu\n", __func__, r,
277 /* Get results of AIO read */
278 r = io_getevents(aio->aio_ctx, 1, MAX_INFLIGHTS,
282 * events.res indicates the actual status of the operation.
283 * Handle the error condition first.
285 if (events[0].res < 0) {
287 * Underlying operation cannot be completed at the time
288 * of previous submission. Resubmit for the operation.
290 if (events[0].res == -EBUSY && retry++ < 3) {
291 r = io_read(aio->aio_ctx, 1, &cb);
293 ALG_PERR("%s: retry %d for io_read failed : ",
300 * Retries exceed for -EBUSY or unrecoverable error
301 * condition for this instance of operation.
304 ("%s: Crypto Operation failed with code %lld\n",
305 __func__, events[0].res);
309 /* Operation successful. */
312 ALG_PERR("%s: io_getevents failed : ", __func__);
315 ALG_WARN("%s: io_geteventd read 0 bytes\n", __func__);
323 static ossl_inline void afalg_set_op_sk(struct cmsghdr *cmsg,
324 const ALG_OP_TYPE op)
326 cmsg->cmsg_level = SOL_ALG;
327 cmsg->cmsg_type = ALG_SET_OP;
328 cmsg->cmsg_len = CMSG_LEN(ALG_OP_LEN);
329 memcpy(CMSG_DATA(cmsg), &op, ALG_OP_LEN);
332 static void afalg_set_iv_sk(struct cmsghdr *cmsg, const unsigned char *iv,
333 const unsigned int len)
335 struct af_alg_iv *aiv;
337 cmsg->cmsg_level = SOL_ALG;
338 cmsg->cmsg_type = ALG_SET_IV;
339 cmsg->cmsg_len = CMSG_LEN(ALG_IV_LEN(len));
340 aiv = (struct af_alg_iv *)CMSG_DATA(cmsg);
342 memcpy(aiv->iv, iv, len);
345 static ossl_inline int afalg_set_key(afalg_ctx *actx, const unsigned char *key,
349 ret = setsockopt(actx->bfd, SOL_ALG, ALG_SET_KEY, key, klen);
351 ALG_PERR("%s: Failed to set socket option : ", __func__);
352 AFALGerr(AFALG_F_AFALG_SET_KEY, AFALG_R_SOCKET_SET_KEY_FAILED);
359 static int afalg_create_sk(afalg_ctx *actx, const char *ciphertype,
360 const char *ciphername)
362 struct sockaddr_alg sa;
365 actx->bfd = actx->sfd = -1;
367 memset(&sa, 0, sizeof(sa));
368 sa.salg_family = AF_ALG;
369 strncpy((char *) sa.salg_type, ciphertype, ALG_MAX_SALG_TYPE);
370 sa.salg_type[ALG_MAX_SALG_TYPE-1] = '\0';
371 strncpy((char *) sa.salg_name, ciphername, ALG_MAX_SALG_NAME);
372 sa.salg_name[ALG_MAX_SALG_NAME-1] = '\0';
374 actx->bfd = socket(AF_ALG, SOCK_SEQPACKET, 0);
375 if (actx->bfd == -1) {
376 ALG_PERR("%s: Failed to open socket : ", __func__);
377 AFALGerr(AFALG_F_AFALG_CREATE_SK, AFALG_R_SOCKET_CREATE_FAILED);
381 r = bind(actx->bfd, (struct sockaddr *)&sa, sizeof(sa));
383 ALG_PERR("%s: Failed to bind socket : ", __func__);
384 AFALGerr(AFALG_F_AFALG_CREATE_SK, AFALG_R_SOCKET_BIND_FAILED);
388 actx->sfd = accept(actx->bfd, NULL, 0);
390 ALG_PERR("%s: Socket Accept Failed : ", __func__);
391 AFALGerr(AFALG_F_AFALG_CREATE_SK, AFALG_R_SOCKET_ACCEPT_FAILED);
402 actx->bfd = actx->sfd = -1;
406 static int afalg_start_cipher_sk(afalg_ctx *actx, const unsigned char *in,
407 size_t inl, const unsigned char *iv,
410 struct msghdr msg = { 0 };
411 struct cmsghdr *cmsg;
414 # ifdef ALG_ZERO_COPY
417 char cbuf[CMSG_SPACE(ALG_IV_LEN(ALG_AES_IV_LEN)) + CMSG_SPACE(ALG_OP_LEN)];
419 memset(cbuf, 0, sizeof(cbuf));
420 msg.msg_control = cbuf;
421 msg.msg_controllen = sizeof(cbuf);
424 * cipher direction (i.e. encrypt or decrypt) and iv are sent to the
425 * kernel as part of sendmsg()'s ancillary data
427 cmsg = CMSG_FIRSTHDR(&msg);
428 afalg_set_op_sk(cmsg, enc);
429 cmsg = CMSG_NXTHDR(&msg, cmsg);
430 afalg_set_iv_sk(cmsg, iv, ALG_AES_IV_LEN);
432 /* iov that describes input data */
433 iov.iov_base = (unsigned char *)in;
436 msg.msg_flags = MSG_MORE;
438 # ifdef ALG_ZERO_COPY
441 * Works best when buffer is 4k aligned
442 * OPENS: out of place processing (i.e. out != in)
445 /* Input data is not sent as part of call to sendmsg() */
449 /* Sendmsg() sends iv and cipher direction to the kernel */
450 sbytes = sendmsg(actx->sfd, &msg, 0);
452 ALG_PERR("%s: sendmsg failed for zero copy cipher operation : ",
458 * vmsplice and splice are used to pin the user space input buffer for
459 * kernel space processing avoiding copys from user to kernel space
461 ret = vmsplice(actx->zc_pipe[1], &iov, 1, SPLICE_F_GIFT);
463 ALG_PERR("%s: vmsplice failed : ", __func__);
467 ret = splice(actx->zc_pipe[0], NULL, actx->sfd, NULL, inl, 0);
469 ALG_PERR("%s: splice failed : ", __func__);
476 /* Sendmsg() sends iv, cipher direction and input data to the kernel */
477 sbytes = sendmsg(actx->sfd, &msg, 0);
479 ALG_PERR("%s: sendmsg failed for cipher operation : ", __func__);
483 if (sbytes != (ssize_t) inl) {
484 ALG_WARN("Cipher operation send bytes %zd != inlen %zd\n", sbytes,
493 static int afalg_cipher_init(EVP_CIPHER_CTX *ctx, const unsigned char *key,
494 const unsigned char *iv, int enc)
499 char ciphername[ALG_MAX_SALG_NAME];
501 if (ctx == NULL || key == NULL) {
502 ALG_WARN("%s: Null Parameter\n", __func__);
506 if (EVP_CIPHER_CTX_cipher(ctx) == NULL) {
507 ALG_WARN("%s: Cipher object NULL\n", __func__);
511 actx = EVP_CIPHER_CTX_get_cipher_data(ctx);
513 ALG_WARN("%s: Cipher data NULL\n", __func__);
517 ciphertype = EVP_CIPHER_CTX_nid(ctx);
518 switch (ciphertype) {
519 case NID_aes_128_cbc:
520 strncpy(ciphername, "cbc(aes)", ALG_MAX_SALG_NAME);
523 ALG_WARN("%s: Unsupported Cipher type %d\n", __func__, ciphertype);
526 ciphername[ALG_MAX_SALG_NAME-1]='\0';
528 if (ALG_AES_IV_LEN != EVP_CIPHER_CTX_iv_length(ctx)) {
529 ALG_WARN("%s: Unsupported IV length :%d\n", __func__,
530 EVP_CIPHER_CTX_iv_length(ctx));
534 /* Setup AFALG socket for crypto processing */
535 ret = afalg_create_sk(actx, "skcipher", ciphername);
540 ret = afalg_set_key(actx, key, EVP_CIPHER_CTX_key_length(ctx));
544 /* Setup AIO ctx to allow async AFALG crypto processing */
545 if (afalg_init_aio(&actx->aio) == 0)
548 # ifdef ALG_ZERO_COPY
552 actx->init_done = MAGIC_INIT_NUM;
562 static int afalg_do_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
563 const unsigned char *in, size_t inl)
567 char nxtiv[ALG_AES_IV_LEN] = { 0 };
569 if (ctx == NULL || out == NULL || in == NULL) {
570 ALG_WARN("NULL parameter passed to function %s\n", __func__);
574 actx = (afalg_ctx *) EVP_CIPHER_CTX_get_cipher_data(ctx);
575 if (actx == NULL || actx->init_done != MAGIC_INIT_NUM) {
576 ALG_WARN("%s afalg ctx passed\n",
577 ctx == NULL ? "NULL" : "Uninitialised");
582 * set iv now for decrypt operation as the input buffer can be
583 * overwritten for inplace operation where in = out.
585 if (EVP_CIPHER_CTX_encrypting(ctx) == 0) {
586 memcpy(nxtiv, in + (inl - ALG_AES_IV_LEN), ALG_AES_IV_LEN);
589 /* Send input data to kernel space */
590 ret = afalg_start_cipher_sk(actx, (unsigned char *)in, inl,
591 EVP_CIPHER_CTX_iv(ctx),
592 EVP_CIPHER_CTX_encrypting(ctx));
597 /* Perform async crypto operation in kernel space */
598 ret = afalg_fin_cipher_aio(&actx->aio, actx->sfd, out, inl);
602 if (EVP_CIPHER_CTX_encrypting(ctx)) {
603 memcpy(EVP_CIPHER_CTX_iv_noconst(ctx), out + (inl - ALG_AES_IV_LEN),
606 memcpy(EVP_CIPHER_CTX_iv_noconst(ctx), nxtiv, ALG_AES_IV_LEN);
612 static int afalg_cipher_cleanup(EVP_CIPHER_CTX *ctx)
617 ALG_WARN("NULL parameter passed to function %s\n", __func__);
621 actx = (afalg_ctx *) EVP_CIPHER_CTX_get_cipher_data(ctx);
622 if (actx == NULL || actx->init_done != MAGIC_INIT_NUM) {
623 ALG_WARN("%s afalg ctx passed\n",
624 ctx == NULL ? "NULL" : "Uninitialised");
630 # ifdef ALG_ZERO_COPY
631 close(actx->zc_pipe[0]);
632 close(actx->zc_pipe[1]);
634 /* close efd in sync mode, async mode is closed in afalg_waitfd_cleanup() */
635 if (actx->aio.mode == MODE_SYNC)
636 close(actx->aio.efd);
637 io_destroy(actx->aio.aio_ctx);
642 const EVP_CIPHER *afalg_aes_128_cbc(void)
644 if (_hidden_aes_128_cbc == NULL
645 && ((_hidden_aes_128_cbc =
646 EVP_CIPHER_meth_new(NID_aes_128_cbc,
648 AES_KEY_SIZE_128)) == NULL
649 || !EVP_CIPHER_meth_set_iv_length(_hidden_aes_128_cbc, AES_IV_LEN)
650 || !EVP_CIPHER_meth_set_flags(_hidden_aes_128_cbc,
652 EVP_CIPH_FLAG_DEFAULT_ASN1)
653 || !EVP_CIPHER_meth_set_init(_hidden_aes_128_cbc,
655 || !EVP_CIPHER_meth_set_do_cipher(_hidden_aes_128_cbc,
657 || !EVP_CIPHER_meth_set_cleanup(_hidden_aes_128_cbc,
658 afalg_cipher_cleanup)
659 || !EVP_CIPHER_meth_set_impl_ctx_size(_hidden_aes_128_cbc,
660 sizeof(afalg_ctx)))) {
661 EVP_CIPHER_meth_free(_hidden_aes_128_cbc);
662 _hidden_aes_128_cbc = NULL;
664 return _hidden_aes_128_cbc;
667 static int afalg_ciphers(ENGINE *e, const EVP_CIPHER **cipher,
668 const int **nids, int nid)
672 if (cipher == NULL) {
673 *nids = afalg_cipher_nids;
674 return (sizeof(afalg_cipher_nids) / sizeof(afalg_cipher_nids[0]));
678 case NID_aes_128_cbc:
679 *cipher = afalg_aes_128_cbc();
689 static int bind_afalg(ENGINE *e)
691 /* Ensure the afalg error handling is set up */
692 ERR_load_AFALG_strings();
694 if (!ENGINE_set_id(e, engine_afalg_id)
695 || !ENGINE_set_name(e, engine_afalg_name)
696 || !ENGINE_set_destroy_function(e, afalg_destroy)
697 || !ENGINE_set_init_function(e, afalg_init)
698 || !ENGINE_set_finish_function(e, afalg_finish)) {
699 AFALGerr(AFALG_F_BIND_AFALG, AFALG_R_INIT_FAILED);
704 * Create _hidden_aes_128_cbc by calling afalg_aes_128_cbc
705 * now, as bind_aflag can only be called by one thread at a
708 if (afalg_aes_128_cbc() == NULL) {
709 AFALGerr(AFALG_F_BIND_AFALG, AFALG_R_INIT_FAILED);
713 if (!ENGINE_set_ciphers(e, afalg_ciphers)) {
714 AFALGerr(AFALG_F_BIND_AFALG, AFALG_R_INIT_FAILED);
721 # ifndef OPENSSL_NO_DYNAMIC_ENGINE
722 static int bind_helper(ENGINE *e, const char *id)
724 if (id && (strcmp(id, engine_afalg_id) != 0))
727 if (!afalg_chk_platform())
735 IMPLEMENT_DYNAMIC_CHECK_FN()
736 IMPLEMENT_DYNAMIC_BIND_FN(bind_helper)
739 static int afalg_chk_platform(void)
743 int kver[3] = { -1, -1, -1 };
750 AFALGerr(AFALG_F_AFALG_CHK_PLATFORM,
751 AFALG_R_FAILED_TO_GET_PLATFORM_INFO);
755 str = strtok(ut.release, ".");
756 for (i = 0; i < 3 && str != NULL; i++) {
758 str = strtok(NULL, ".");
761 if (KERNEL_VERSION(kver[0], kver[1], kver[2])
762 < KERNEL_VERSION(K_MAJ, K_MIN1, K_MIN2)) {
763 ALG_ERR("ASYNC AFALG not supported this kernel(%d.%d.%d)\n",
764 kver[0], kver[1], kver[2]);
765 ALG_ERR("ASYNC AFALG requires kernel version %d.%d.%d or later\n",
766 K_MAJ, K_MIN1, K_MIN2);
767 AFALGerr(AFALG_F_AFALG_CHK_PLATFORM,
768 AFALG_R_KERNEL_DOES_NOT_SUPPORT_ASYNC_AFALG);
772 /* Test if we can actually create an AF_ALG socket */
773 sock = socket(AF_ALG, SOCK_SEQPACKET, 0);
775 AFALGerr(AFALG_F_AFALG_CHK_PLATFORM, AFALG_R_SOCKET_CREATE_FAILED);
783 # ifdef OPENSSL_NO_DYNAMIC_ENGINE
784 static ENGINE *engine_afalg(void)
786 ENGINE *ret = ENGINE_new();
789 if (!bind_afalg(ret)) {
796 void engine_load_afalg_int(void)
800 if (!afalg_chk_platform())
803 toadd = engine_afalg();
812 static int afalg_init(ENGINE *e)
817 static int afalg_finish(ENGINE *e)
822 static int afalg_destroy(ENGINE *e)
824 ERR_unload_AFALG_strings();
825 EVP_CIPHER_meth_free(_hidden_aes_128_cbc);
826 _hidden_aes_128_cbc = NULL;
830 #endif /* KERNEL VERSION */