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 */
16 #include <openssl/engine.h>
17 #include <openssl/async.h>
18 #include <openssl/err.h>
20 #include <linux/version.h>
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)
32 # include <linux/if_alg.h>
33 # include <sys/socket.h>
35 # include <sys/utsname.h>
37 # include <linux/aio_abi.h>
38 # include <sys/syscall.h>
43 # define AFALG_LIB_NAME "AFALG"
44 # include "e_afalg_err.h"
51 # ifndef SPLICE_F_GIFT
52 # define SPLICE_F_GIFT (0x08)
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))
61 #define ALG_MAX_SALG_NAME 64
62 #define ALG_MAX_SALG_TYPE 14
64 # ifdef OPENSSL_NO_DYNAMIC_ENGINE
65 void engine_load_afalg_int(void);
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);
87 /* Engine Id and Name */
88 static const char *engine_afalg_id = "afalg";
89 static const char *engine_afalg_name = "AFALG engine support";
91 static int afalg_cipher_nids[] = {
95 static EVP_CIPHER *_hidden_aes_128_cbc = NULL;
97 static ossl_inline int io_setup(unsigned n, aio_context_t *ctx)
99 return syscall(__NR_io_setup, n, ctx);
102 static ossl_inline int eventfd(int n)
104 return syscall(__NR_eventfd, n);
107 static ossl_inline int io_destroy(aio_context_t ctx)
109 return syscall(__NR_io_destroy, ctx);
112 static ossl_inline int io_read(aio_context_t ctx, long n, struct iocb **iocb)
114 return syscall(__NR_io_submit, ctx, n, iocb);
117 static ossl_inline int io_getevents(aio_context_t ctx, long min, long max,
118 struct io_event *events,
119 struct timespec *timeout)
121 return syscall(__NR_io_getevents, ctx, min, max, events, timeout);
124 static void afalg_waitfd_cleanup(ASYNC_WAIT_CTX *ctx, const void *key,
125 OSSL_ASYNC_FD waitfd, void *custom)
130 static int afalg_setup_async_event_notification(afalg_aio *aio)
133 ASYNC_WAIT_CTX *waitctx;
137 if ((job = ASYNC_get_current_job()) != NULL) {
139 waitctx = ASYNC_get_wait_ctx(job);
140 if (waitctx == NULL) {
141 ALG_WARN("%s: ASYNC_get_wait_ctx error", __func__);
144 /* Get waitfd from ASYNC_WAIT_CTX if it is alreday set */
145 ret = ASYNC_WAIT_CTX_get_fd(waitctx, engine_afalg_id,
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
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);
159 ret = ASYNC_WAIT_CTX_set_wait_fd(waitctx, engine_afalg_id,
161 afalg_waitfd_cleanup);
163 ALG_WARN("%s: Failed to set wait fd", __func__);
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",
173 aio->mode = MODE_ASYNC;
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);
183 aio->mode = MODE_SYNC;
188 int afalg_init_aio(afalg_aio *aio)
192 /* Initialise for AIO */
194 r = io_setup(MAX_INFLIGHTS, &aio->aio_ctx);
196 ALG_PERR("%s: io_setup error : ", __func__);
197 AFALGerr(AFALG_F_AFALG_INIT_AIO, AFALG_R_IO_SETUP_FAILED);
201 memset(aio->cbt, 0, sizeof(aio->cbt));
203 aio->mode = MODE_UNINIT;
208 int afalg_fin_cipher_aio(afalg_aio *aio, int sfd, unsigned char *buf,
213 unsigned int done = 0;
215 struct timespec timeout;
216 struct io_event events[MAX_INFLIGHTS];
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);
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;
234 * The pointer has to be converted to unsigned value first to avoid
235 * sign extension on cast to 64 bit value
237 cb->aio_buf = (uint64_t)(unsigned long)buf;
240 cb->aio_nbytes = len;
241 cb->aio_flags = IOCB_FLAG_RESFD;
242 cb->aio_resfd = aio->efd;
245 * Perform AIO read on AFALG socket, this in turn performs an async
246 * crypto operation in kernel space
248 r = io_read(aio->aio_ctx, 1, &cb);
250 ALG_PWARN("%s: io_read failed : ", __func__);
255 /* While AIO read is being performed pause job */
258 /* Check for completion of AIO read */
259 r = read(aio->efd, &eval, sizeof(eval));
261 if (errno == EAGAIN || errno == EWOULDBLOCK)
263 ALG_PERR("%s: read failed for event fd : ", __func__);
265 } else if (r == 0 || eval <= 0) {
266 ALG_WARN("%s: eventfd read %d bytes, eval = %lu\n", __func__, r,
271 /* Get results of AIO read */
272 r = io_getevents(aio->aio_ctx, 1, MAX_INFLIGHTS,
276 * events.res indicates the actual status of the operation.
277 * Handle the error condition first.
279 if (events[0].res < 0) {
281 * Underlying operation cannot be completed at the time
282 * of previous submission. Resubmit for the operation.
284 if (events[0].res == -EBUSY && retry++ < 3) {
285 r = io_read(aio->aio_ctx, 1, &cb);
287 ALG_PERR("%s: retry %d for io_read failed : ",
294 * Retries exceed for -EBUSY or unrecoverable error
295 * condition for this instance of operation.
298 ("%s: Crypto Operation failed with code %lld\n",
299 __func__, events[0].res);
303 /* Operation successful. */
306 ALG_PERR("%s: io_getevents failed : ", __func__);
309 ALG_WARN("%s: io_geteventd read 0 bytes\n", __func__);
317 static ossl_inline void afalg_set_op_sk(struct cmsghdr *cmsg,
318 const unsigned int op)
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;
326 static void afalg_set_iv_sk(struct cmsghdr *cmsg, const unsigned char *iv,
327 const unsigned int len)
329 struct af_alg_iv *aiv;
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);
336 memcpy(aiv->iv, iv, len);
339 static ossl_inline int afalg_set_key(afalg_ctx *actx, const unsigned char *key,
343 ret = setsockopt(actx->bfd, SOL_ALG, ALG_SET_KEY, key, klen);
345 ALG_PERR("%s: Failed to set socket option : ", __func__);
346 AFALGerr(AFALG_F_AFALG_SET_KEY, AFALG_R_SOCKET_SET_KEY_FAILED);
353 static int afalg_create_sk(afalg_ctx *actx, const char *ciphertype,
354 const char *ciphername)
356 struct sockaddr_alg sa;
358 actx->bfd = actx->sfd = -1;
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';
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);
375 r = bind(actx->bfd, (struct sockaddr *)&sa, sizeof(sa));
377 ALG_PERR("%s: Failed to bind socket : ", __func__);
378 AFALGerr(AFALG_F_AFALG_CREATE_SK, AFALG_R_SOCKET_BIND_FAILED);
382 actx->sfd = accept(actx->bfd, NULL, 0);
384 ALG_PERR("%s: Socket Accept Failed : ", __func__);
385 AFALGerr(AFALG_F_AFALG_CREATE_SK, AFALG_R_SOCKET_ACCEPT_FAILED);
396 actx->bfd = actx->sfd = -1;
400 static int afalg_start_cipher_sk(afalg_ctx *actx, const unsigned char *in,
401 size_t inl, const unsigned char *iv,
404 struct msghdr msg = { 0 };
405 struct cmsghdr *cmsg;
408 # ifdef ALG_ZERO_COPY
411 char cbuf[CMSG_SPACE(ALG_IV_LEN(ALG_AES_IV_LEN)) + CMSG_SPACE(ALG_OP_LEN)];
413 memset(cbuf, 0, sizeof(cbuf));
414 msg.msg_control = cbuf;
415 msg.msg_controllen = sizeof(cbuf);
418 * cipher direction (i.e. encrypt or decrypt) and iv are sent to the
419 * kernel as part of sendmsg()'s ancillary data
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);
426 /* iov that describes input data */
427 iov.iov_base = (unsigned char *)in;
430 msg.msg_flags = MSG_MORE;
432 # ifdef ALG_ZERO_COPY
435 * Works best when buffer is 4k aligned
436 * OPENS: out of place processing (i.e. out != in)
439 /* Input data is not sent as part of call to sendmsg() */
443 /* Sendmsg() sends iv and cipher direction to the kernel */
444 sbytes = sendmsg(actx->sfd, &msg, 0);
446 ALG_PERR("%s: sendmsg failed for zero copy cipher operation : ",
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
455 ret = vmsplice(actx->zc_pipe[1], &iov, 1, SPLICE_F_GIFT);
457 ALG_PERR("%s: vmsplice failed : ", __func__);
461 ret = splice(actx->zc_pipe[0], NULL, actx->sfd, NULL, inl, 0);
463 ALG_PERR("%s: splice failed : ", __func__);
470 /* Sendmsg() sends iv, cipher direction and input data to the kernel */
471 sbytes = sendmsg(actx->sfd, &msg, 0);
473 ALG_PERR("%s: sendmsg failed for cipher operation : ", __func__);
477 if (sbytes != (ssize_t) inl) {
478 ALG_WARN("Cipher operation send bytes %zd != inlen %zd\n", sbytes,
487 static int afalg_cipher_init(EVP_CIPHER_CTX *ctx, const unsigned char *key,
488 const unsigned char *iv, int enc)
493 char ciphername[ALG_MAX_SALG_NAME];
495 if (ctx == NULL || key == NULL) {
496 ALG_WARN("%s: Null Parameter\n", __func__);
500 if (EVP_CIPHER_CTX_cipher(ctx) == NULL) {
501 ALG_WARN("%s: Cipher object NULL\n", __func__);
505 actx = EVP_CIPHER_CTX_get_cipher_data(ctx);
507 ALG_WARN("%s: Cipher data NULL\n", __func__);
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);
517 ALG_WARN("%s: Unsupported Cipher type %d\n", __func__, ciphertype);
520 ciphername[ALG_MAX_SALG_NAME-1]='\0';
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));
528 /* Setup AFALG socket for crypto processing */
529 ret = afalg_create_sk(actx, "skcipher", ciphername);
534 ret = afalg_set_key(actx, key, EVP_CIPHER_CTX_key_length(ctx));
538 /* Setup AIO ctx to allow async AFALG crypto processing */
539 if (afalg_init_aio(&actx->aio) == 0)
542 # ifdef ALG_ZERO_COPY
546 actx->init_done = MAGIC_INIT_NUM;
556 static int afalg_do_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
557 const unsigned char *in, size_t inl)
561 char nxtiv[ALG_AES_IV_LEN] = { 0 };
563 if (ctx == NULL || out == NULL || in == NULL) {
564 ALG_WARN("NULL parameter passed to function %s\n", __func__);
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");
576 * set iv now for decrypt operation as the input buffer can be
577 * overwritten for inplace operation where in = out.
579 if (EVP_CIPHER_CTX_encrypting(ctx) == 0) {
580 memcpy(nxtiv, in + (inl - ALG_AES_IV_LEN), ALG_AES_IV_LEN);
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));
591 /* Perform async crypto operation in kernel space */
592 ret = afalg_fin_cipher_aio(&actx->aio, actx->sfd, out, inl);
596 if (EVP_CIPHER_CTX_encrypting(ctx)) {
597 memcpy(EVP_CIPHER_CTX_iv_noconst(ctx), out + (inl - ALG_AES_IV_LEN),
600 memcpy(EVP_CIPHER_CTX_iv_noconst(ctx), nxtiv, ALG_AES_IV_LEN);
606 static int afalg_cipher_cleanup(EVP_CIPHER_CTX *ctx)
611 ALG_WARN("NULL parameter passed to function %s\n", __func__);
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");
624 # ifdef ALG_ZERO_COPY
625 close(actx->zc_pipe[0]);
626 close(actx->zc_pipe[1]);
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);
636 const EVP_CIPHER *afalg_aes_128_cbc(void)
638 if (_hidden_aes_128_cbc == NULL
639 && ((_hidden_aes_128_cbc =
640 EVP_CIPHER_meth_new(NID_aes_128_cbc,
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,
646 EVP_CIPH_FLAG_DEFAULT_ASN1)
647 || !EVP_CIPHER_meth_set_init(_hidden_aes_128_cbc,
649 || !EVP_CIPHER_meth_set_do_cipher(_hidden_aes_128_cbc,
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;
658 return _hidden_aes_128_cbc;
661 static int afalg_ciphers(ENGINE *e, const EVP_CIPHER **cipher,
662 const int **nids, int nid)
666 if (cipher == NULL) {
667 *nids = afalg_cipher_nids;
668 return (sizeof(afalg_cipher_nids) / sizeof(afalg_cipher_nids[0]));
672 case NID_aes_128_cbc:
673 *cipher = afalg_aes_128_cbc();
683 static int bind_afalg(ENGINE *e)
685 /* Ensure the afalg error handling is set up */
686 ERR_load_AFALG_strings();
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);
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
702 if (afalg_aes_128_cbc() == NULL) {
703 AFALGerr(AFALG_F_BIND_AFALG, AFALG_R_INIT_FAILED);
707 if (!ENGINE_set_ciphers(e, afalg_ciphers)) {
708 AFALGerr(AFALG_F_BIND_AFALG, AFALG_R_INIT_FAILED);
715 # ifndef OPENSSL_NO_DYNAMIC_ENGINE
716 static int bind_helper(ENGINE *e, const char *id)
718 if (id && (strcmp(id, engine_afalg_id) != 0))
721 if (!afalg_chk_platform())
729 IMPLEMENT_DYNAMIC_CHECK_FN()
730 IMPLEMENT_DYNAMIC_BIND_FN(bind_helper)
733 static int afalg_chk_platform(void)
737 int kver[3] = { -1, -1, -1 };
744 AFALGerr(AFALG_F_AFALG_CHK_PLATFORM,
745 AFALG_R_FAILED_TO_GET_PLATFORM_INFO);
749 str = strtok(ut.release, ".");
750 for (i = 0; i < 3 && str != NULL; i++) {
752 str = strtok(NULL, ".");
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);
766 /* Test if we can actually create an AF_ALG socket */
767 sock = socket(AF_ALG, SOCK_SEQPACKET, 0);
769 AFALGerr(AFALG_F_AFALG_CHK_PLATFORM, AFALG_R_SOCKET_CREATE_FAILED);
777 # ifdef OPENSSL_NO_DYNAMIC_ENGINE
778 static ENGINE *engine_afalg(void)
780 ENGINE *ret = ENGINE_new();
783 if (!bind_afalg(ret)) {
790 void engine_load_afalg_int(void)
794 if (!afalg_chk_platform())
797 toadd = engine_afalg();
806 static int afalg_init(ENGINE *e)
811 static int afalg_finish(ENGINE *e)
816 static int afalg_destroy(ENGINE *e)
818 ERR_unload_AFALG_strings();
819 EVP_CIPHER_meth_free(_hidden_aes_128_cbc);
820 _hidden_aes_128_cbc = NULL;
824 #endif /* KERNEL VERSION */