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;
233 cb->aio_buf = (uint64_t)buf;
236 cb->aio_nbytes = len;
237 cb->aio_flags = IOCB_FLAG_RESFD;
238 cb->aio_resfd = aio->efd;
241 * Perform AIO read on AFALG socket, this in turn performs an async
242 * crypto operation in kernel space
244 r = io_read(aio->aio_ctx, 1, &cb);
246 ALG_PWARN("%s: io_read failed : ", __func__);
251 /* While AIO read is being performed pause job */
254 /* Check for completion of AIO read */
255 r = read(aio->efd, &eval, sizeof(eval));
257 if (errno == EAGAIN || errno == EWOULDBLOCK)
259 ALG_PERR("%s: read failed for event fd : ", __func__);
261 } else if (r == 0 || eval <= 0) {
262 ALG_WARN("%s: eventfd read %d bytes, eval = %lu\n", __func__, r,
267 /* Get results of AIO read */
268 r = io_getevents(aio->aio_ctx, 1, MAX_INFLIGHTS,
272 * events.res indicates the actual status of the operation.
273 * Handle the error condition first.
275 if (events[0].res < 0) {
277 * Underlying operation cannot be completed at the time
278 * of previous submission. Resubmit for the operation.
280 if (events[0].res == -EBUSY && retry++ < 3) {
281 r = io_read(aio->aio_ctx, 1, &cb);
283 ALG_PERR("%s: retry %d for io_read failed : ",
290 * Retries exceed for -EBUSY or unrecoverable error
291 * condition for this instance of operation.
294 ("%s: Crypto Operation failed with code %lld\n",
295 __func__, events[0].res);
299 /* Operation successful. */
302 ALG_PERR("%s: io_getevents failed : ", __func__);
305 ALG_WARN("%s: io_geteventd read 0 bytes\n", __func__);
313 static ossl_inline void afalg_set_op_sk(struct cmsghdr *cmsg,
314 const unsigned int op)
316 cmsg->cmsg_level = SOL_ALG;
317 cmsg->cmsg_type = ALG_SET_OP;
318 cmsg->cmsg_len = CMSG_LEN(ALG_OP_LEN);
319 *CMSG_DATA(cmsg) = (char)op;
322 static void afalg_set_iv_sk(struct cmsghdr *cmsg, const unsigned char *iv,
323 const unsigned int len)
325 struct af_alg_iv *aiv;
327 cmsg->cmsg_level = SOL_ALG;
328 cmsg->cmsg_type = ALG_SET_IV;
329 cmsg->cmsg_len = CMSG_LEN(ALG_IV_LEN(len));
330 aiv = (struct af_alg_iv *)CMSG_DATA(cmsg);
332 memcpy(aiv->iv, iv, len);
335 static ossl_inline int afalg_set_key(afalg_ctx *actx, const unsigned char *key,
339 ret = setsockopt(actx->bfd, SOL_ALG, ALG_SET_KEY, key, klen);
341 ALG_PERR("%s: Failed to set socket option : ", __func__);
342 AFALGerr(AFALG_F_AFALG_SET_KEY, AFALG_R_SOCKET_SET_KEY_FAILED);
349 static int afalg_create_sk(afalg_ctx *actx, const char *ciphertype,
350 const char *ciphername)
352 struct sockaddr_alg sa;
354 actx->bfd = actx->sfd = -1;
357 memset(&sa, 0, sizeof(sa));
358 sa.salg_family = AF_ALG;
359 strncpy((char *) sa.salg_type, ciphertype, ALG_MAX_SALG_TYPE);
360 sa.salg_type[ALG_MAX_SALG_TYPE-1] = '\0';
361 strncpy((char *) sa.salg_name, ciphername, ALG_MAX_SALG_NAME);
362 sa.salg_name[ALG_MAX_SALG_NAME-1] = '\0';
364 actx->bfd = socket(AF_ALG, SOCK_SEQPACKET, 0);
365 if (actx->bfd == -1) {
366 ALG_PERR("%s: Failed to open socket : ", __func__);
367 AFALGerr(AFALG_F_AFALG_CREATE_SK, AFALG_R_SOCKET_CREATE_FAILED);
371 r = bind(actx->bfd, (struct sockaddr *)&sa, sizeof(sa));
373 ALG_PERR("%s: Failed to bind socket : ", __func__);
374 AFALGerr(AFALG_F_AFALG_CREATE_SK, AFALG_R_SOCKET_BIND_FAILED);
378 actx->sfd = accept(actx->bfd, NULL, 0);
380 ALG_PERR("%s: Socket Accept Failed : ", __func__);
381 AFALGerr(AFALG_F_AFALG_CREATE_SK, AFALG_R_SOCKET_ACCEPT_FAILED);
392 actx->bfd = actx->sfd = -1;
396 static int afalg_start_cipher_sk(afalg_ctx *actx, const unsigned char *in,
397 size_t inl, const unsigned char *iv,
400 struct msghdr msg = { 0 };
401 struct cmsghdr *cmsg;
404 # ifdef ALG_ZERO_COPY
407 char cbuf[CMSG_SPACE(ALG_IV_LEN(ALG_AES_IV_LEN)) + CMSG_SPACE(ALG_OP_LEN)];
409 memset(cbuf, 0, sizeof(cbuf));
410 msg.msg_control = cbuf;
411 msg.msg_controllen = sizeof(cbuf);
414 * cipher direction (i.e. encrypt or decrypt) and iv are sent to the
415 * kernel as part of sendmsg()'s ancillary data
417 cmsg = CMSG_FIRSTHDR(&msg);
418 afalg_set_op_sk(cmsg, enc);
419 cmsg = CMSG_NXTHDR(&msg, cmsg);
420 afalg_set_iv_sk(cmsg, iv, ALG_AES_IV_LEN);
422 /* iov that describes input data */
423 iov.iov_base = (unsigned char *)in;
426 msg.msg_flags = MSG_MORE;
428 # ifdef ALG_ZERO_COPY
431 * Works best when buffer is 4k aligned
432 * OPENS: out of place processing (i.e. out != in)
435 /* Input data is not sent as part of call to sendmsg() */
439 /* Sendmsg() sends iv and cipher direction to the kernel */
440 sbytes = sendmsg(actx->sfd, &msg, 0);
442 ALG_PERR("%s: sendmsg failed for zero copy cipher operation : ",
448 * vmsplice and splice are used to pin the user space input buffer for
449 * kernel space processing avoiding copys from user to kernel space
451 ret = vmsplice(actx->zc_pipe[1], &iov, 1, SPLICE_F_GIFT);
453 ALG_PERR("%s: vmsplice failed : ", __func__);
457 ret = splice(actx->zc_pipe[0], NULL, actx->sfd, NULL, inl, 0);
459 ALG_PERR("%s: splice failed : ", __func__);
466 /* Sendmsg() sends iv, cipher direction and input data to the kernel */
467 sbytes = sendmsg(actx->sfd, &msg, 0);
469 ALG_PERR("%s: sendmsg failed for cipher operation : ", __func__);
473 if (sbytes != (ssize_t) inl) {
474 ALG_WARN("Cipher operation send bytes %zd != inlen %zd\n", sbytes,
483 static int afalg_cipher_init(EVP_CIPHER_CTX *ctx, const unsigned char *key,
484 const unsigned char *iv, int enc)
489 char ciphername[ALG_MAX_SALG_NAME];
491 if (ctx == NULL || key == NULL) {
492 ALG_WARN("%s: Null Parameter\n", __func__);
496 if (EVP_CIPHER_CTX_cipher(ctx) == NULL) {
497 ALG_WARN("%s: Cipher object NULL\n", __func__);
501 actx = EVP_CIPHER_CTX_get_cipher_data(ctx);
503 ALG_WARN("%s: Cipher data NULL\n", __func__);
507 ciphertype = EVP_CIPHER_CTX_nid(ctx);
508 switch (ciphertype) {
509 case NID_aes_128_cbc:
510 strncpy(ciphername, "cbc(aes)", ALG_MAX_SALG_NAME);
513 ALG_WARN("%s: Unsupported Cipher type %d\n", __func__, ciphertype);
516 ciphername[ALG_MAX_SALG_NAME-1]='\0';
518 if (ALG_AES_IV_LEN != EVP_CIPHER_CTX_iv_length(ctx)) {
519 ALG_WARN("%s: Unsupported IV length :%d\n", __func__,
520 EVP_CIPHER_CTX_iv_length(ctx));
524 /* Setup AFALG socket for crypto processing */
525 ret = afalg_create_sk(actx, "skcipher", ciphername);
530 ret = afalg_set_key(actx, key, EVP_CIPHER_CTX_key_length(ctx));
534 /* Setup AIO ctx to allow async AFALG crypto processing */
535 if (afalg_init_aio(&actx->aio) == 0)
538 # ifdef ALG_ZERO_COPY
542 actx->init_done = MAGIC_INIT_NUM;
552 static int afalg_do_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
553 const unsigned char *in, size_t inl)
557 char nxtiv[ALG_AES_IV_LEN] = { 0 };
559 if (ctx == NULL || out == NULL || in == NULL) {
560 ALG_WARN("NULL parameter passed to function %s\n", __func__);
564 actx = (afalg_ctx *) EVP_CIPHER_CTX_get_cipher_data(ctx);
565 if (actx == NULL || actx->init_done != MAGIC_INIT_NUM) {
566 ALG_WARN("%s afalg ctx passed\n",
567 ctx == NULL ? "NULL" : "Uninitialised");
572 * set iv now for decrypt operation as the input buffer can be
573 * overwritten for inplace operation where in = out.
575 if (EVP_CIPHER_CTX_encrypting(ctx) == 0) {
576 memcpy(nxtiv, in + (inl - ALG_AES_IV_LEN), ALG_AES_IV_LEN);
579 /* Send input data to kernel space */
580 ret = afalg_start_cipher_sk(actx, (unsigned char *)in, inl,
581 EVP_CIPHER_CTX_iv(ctx),
582 EVP_CIPHER_CTX_encrypting(ctx));
587 /* Perform async crypto operation in kernel space */
588 ret = afalg_fin_cipher_aio(&actx->aio, actx->sfd, out, inl);
592 if (EVP_CIPHER_CTX_encrypting(ctx)) {
593 memcpy(EVP_CIPHER_CTX_iv_noconst(ctx), out + (inl - ALG_AES_IV_LEN),
596 memcpy(EVP_CIPHER_CTX_iv_noconst(ctx), nxtiv, ALG_AES_IV_LEN);
602 static int afalg_cipher_cleanup(EVP_CIPHER_CTX *ctx)
607 ALG_WARN("NULL parameter passed to function %s\n", __func__);
611 actx = (afalg_ctx *) EVP_CIPHER_CTX_get_cipher_data(ctx);
612 if (actx == NULL || actx->init_done != MAGIC_INIT_NUM) {
613 ALG_WARN("%s afalg ctx passed\n",
614 ctx == NULL ? "NULL" : "Uninitialised");
620 # ifdef ALG_ZERO_COPY
621 close(actx->zc_pipe[0]);
622 close(actx->zc_pipe[1]);
624 /* close efd in sync mode, async mode is closed in afalg_waitfd_cleanup() */
625 if (actx->aio.mode == MODE_SYNC)
626 close(actx->aio.efd);
627 io_destroy(actx->aio.aio_ctx);
632 const EVP_CIPHER *afalg_aes_128_cbc(void)
634 if (_hidden_aes_128_cbc == NULL
635 && ((_hidden_aes_128_cbc =
636 EVP_CIPHER_meth_new(NID_aes_128_cbc,
638 AES_KEY_SIZE_128)) == NULL
639 || !EVP_CIPHER_meth_set_iv_length(_hidden_aes_128_cbc, AES_IV_LEN)
640 || !EVP_CIPHER_meth_set_flags(_hidden_aes_128_cbc,
642 EVP_CIPH_FLAG_DEFAULT_ASN1)
643 || !EVP_CIPHER_meth_set_init(_hidden_aes_128_cbc,
645 || !EVP_CIPHER_meth_set_do_cipher(_hidden_aes_128_cbc,
647 || !EVP_CIPHER_meth_set_cleanup(_hidden_aes_128_cbc,
648 afalg_cipher_cleanup)
649 || !EVP_CIPHER_meth_set_impl_ctx_size(_hidden_aes_128_cbc,
650 sizeof(afalg_ctx)))) {
651 EVP_CIPHER_meth_free(_hidden_aes_128_cbc);
652 _hidden_aes_128_cbc = NULL;
654 return _hidden_aes_128_cbc;
657 static int afalg_ciphers(ENGINE *e, const EVP_CIPHER **cipher,
658 const int **nids, int nid)
662 if (cipher == NULL) {
663 *nids = afalg_cipher_nids;
664 return (sizeof(afalg_cipher_nids) / sizeof(afalg_cipher_nids[0]));
668 case NID_aes_128_cbc:
669 *cipher = afalg_aes_128_cbc();
679 static int bind_afalg(ENGINE *e)
681 /* Ensure the afalg error handling is set up */
682 ERR_load_AFALG_strings();
684 if (!ENGINE_set_id(e, engine_afalg_id)
685 || !ENGINE_set_name(e, engine_afalg_name)
686 || !ENGINE_set_destroy_function(e, afalg_destroy)
687 || !ENGINE_set_init_function(e, afalg_init)
688 || !ENGINE_set_finish_function(e, afalg_finish)) {
689 AFALGerr(AFALG_F_BIND_AFALG, AFALG_R_INIT_FAILED);
694 * Create _hidden_aes_128_cbc by calling afalg_aes_128_cbc
695 * now, as bind_aflag can only be called by one thread at a
698 if (afalg_aes_128_cbc() == NULL) {
699 AFALGerr(AFALG_F_BIND_AFALG, AFALG_R_INIT_FAILED);
703 if (!ENGINE_set_ciphers(e, afalg_ciphers)) {
704 AFALGerr(AFALG_F_BIND_AFALG, AFALG_R_INIT_FAILED);
711 # ifndef OPENSSL_NO_DYNAMIC_ENGINE
712 static int bind_helper(ENGINE *e, const char *id)
714 if (id && (strcmp(id, engine_afalg_id) != 0))
717 if (!afalg_chk_platform())
725 IMPLEMENT_DYNAMIC_CHECK_FN()
726 IMPLEMENT_DYNAMIC_BIND_FN(bind_helper)
729 static int afalg_chk_platform(void)
733 int kver[3] = { -1, -1, -1 };
739 AFALGerr(AFALG_F_AFALG_CHK_PLATFORM,
740 AFALG_R_FAILED_TO_GET_PLATFORM_INFO);
744 str = strtok(ut.release, ".");
745 for (i = 0; i < 3 && str != NULL; i++) {
747 str = strtok(NULL, ".");
750 if (KERNEL_VERSION(kver[0], kver[1], kver[2])
751 < KERNEL_VERSION(K_MAJ, K_MIN1, K_MIN2)) {
752 ALG_ERR("ASYNC AFALG not supported this kernel(%d.%d.%d)\n",
753 kver[0], kver[1], kver[2]);
754 ALG_ERR("ASYNC AFALG requires kernel version %d.%d.%d or later\n",
755 K_MAJ, K_MIN1, K_MIN2);
756 AFALGerr(AFALG_F_AFALG_CHK_PLATFORM,
757 AFALG_R_KERNEL_DOES_NOT_SUPPORT_ASYNC_AFALG);
764 # ifdef OPENSSL_NO_DYNAMIC_ENGINE
765 static ENGINE *engine_afalg(void)
767 ENGINE *ret = ENGINE_new();
770 if (!bind_afalg(ret)) {
777 void engine_load_afalg_int(void)
781 if (!afalg_chk_platform())
784 toadd = engine_afalg();
793 static int afalg_init(ENGINE *e)
798 static int afalg_finish(ENGINE *e)
803 static int afalg_destroy(ENGINE *e)
805 ERR_unload_AFALG_strings();
806 EVP_CIPHER_meth_free(_hidden_aes_128_cbc);
807 _hidden_aes_128_cbc = NULL;
811 #endif /* KERNEL VERSION */