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);
32 void engine_load_afalg_int(void)
37 # include <linux/if_alg.h>
39 # include <sys/utsname.h>
41 # include <linux/aio_abi.h>
42 # include <sys/syscall.h>
47 # define AFALG_LIB_NAME "AFALG"
48 # include "e_afalg_err.h"
55 # ifndef SPLICE_F_GIFT
56 # define SPLICE_F_GIFT (0x08)
60 # define ALG_AES_IV_LEN 16
61 # define ALG_IV_LEN(len) (sizeof(struct af_alg_iv) + (len))
62 # define ALG_OP_TYPE unsigned int
63 # define ALG_OP_LEN (sizeof(ALG_OP_TYPE))
65 #define ALG_MAX_SALG_NAME 64
66 #define ALG_MAX_SALG_TYPE 14
68 # ifdef OPENSSL_NO_DYNAMIC_ENGINE
69 void engine_load_afalg_int(void);
72 /* Local Linkage Functions */
73 static int afalg_init_aio(afalg_aio *aio);
74 static int afalg_fin_cipher_aio(afalg_aio *ptr, int sfd,
75 unsigned char *buf, size_t len);
76 static int afalg_create_sk(afalg_ctx *actx, const char *ciphertype,
77 const char *ciphername);
78 static int afalg_destroy(ENGINE *e);
79 static int afalg_init(ENGINE *e);
80 static int afalg_finish(ENGINE *e);
81 const EVP_CIPHER *afalg_aes_128_cbc(void);
82 static int afalg_ciphers(ENGINE *e, const EVP_CIPHER **cipher,
83 const int **nids, int nid);
84 static int afalg_cipher_init(EVP_CIPHER_CTX *ctx, const unsigned char *key,
85 const unsigned char *iv, int enc);
86 static int afalg_do_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
87 const unsigned char *in, size_t inl);
88 static int afalg_cipher_cleanup(EVP_CIPHER_CTX *ctx);
89 static int afalg_chk_platform(void);
91 /* Engine Id and Name */
92 static const char *engine_afalg_id = "afalg";
93 static const char *engine_afalg_name = "AFALG engine support";
95 static int afalg_cipher_nids[] = {
99 static EVP_CIPHER *_hidden_aes_128_cbc = NULL;
101 static ossl_inline int io_setup(unsigned n, aio_context_t *ctx)
103 return syscall(__NR_io_setup, n, ctx);
106 static ossl_inline int eventfd(int n)
108 return syscall(__NR_eventfd, n);
111 static ossl_inline int io_destroy(aio_context_t ctx)
113 return syscall(__NR_io_destroy, ctx);
116 static ossl_inline int io_read(aio_context_t ctx, long n, struct iocb **iocb)
118 return syscall(__NR_io_submit, ctx, n, iocb);
121 static ossl_inline int io_getevents(aio_context_t ctx, long min, long max,
122 struct io_event *events,
123 struct timespec *timeout)
125 return syscall(__NR_io_getevents, ctx, min, max, events, timeout);
128 static void afalg_waitfd_cleanup(ASYNC_WAIT_CTX *ctx, const void *key,
129 OSSL_ASYNC_FD waitfd, void *custom)
134 static int afalg_setup_async_event_notification(afalg_aio *aio)
137 ASYNC_WAIT_CTX *waitctx;
141 if ((job = ASYNC_get_current_job()) != NULL) {
143 waitctx = ASYNC_get_wait_ctx(job);
144 if (waitctx == NULL) {
145 ALG_WARN("%s: ASYNC_get_wait_ctx error", __func__);
148 /* Get waitfd from ASYNC_WAIT_CTX if it is alreday set */
149 ret = ASYNC_WAIT_CTX_get_fd(waitctx, engine_afalg_id,
153 * waitfd is not set in ASYNC_WAIT_CTX, create a new one
154 * and set it. efd will be signaled when AIO operation completes
156 aio->efd = eventfd(0);
157 if (aio->efd == -1) {
158 ALG_PERR("%s: Failed to get eventfd : ", __func__);
159 AFALGerr(AFALG_F_AFALG_SETUP_ASYNC_EVENT_NOTIFICATION,
160 AFALG_R_EVENTFD_FAILED);
163 ret = ASYNC_WAIT_CTX_set_wait_fd(waitctx, engine_afalg_id,
165 afalg_waitfd_cleanup);
167 ALG_WARN("%s: Failed to set wait fd", __func__);
171 /* make fd non-blocking in async mode */
172 if (fcntl(aio->efd, F_SETFL, O_NONBLOCK) != 0) {
173 ALG_WARN("%s: Failed to set event fd as NONBLOCKING",
177 aio->mode = MODE_ASYNC;
180 aio->efd = eventfd(0);
181 if (aio->efd == -1) {
182 ALG_PERR("%s: Failed to get eventfd : ", __func__);
183 AFALGerr(AFALG_F_AFALG_SETUP_ASYNC_EVENT_NOTIFICATION,
184 AFALG_R_EVENTFD_FAILED);
187 aio->mode = MODE_SYNC;
192 int afalg_init_aio(afalg_aio *aio)
196 /* Initialise for AIO */
198 r = io_setup(MAX_INFLIGHTS, &aio->aio_ctx);
200 ALG_PERR("%s: io_setup error : ", __func__);
201 AFALGerr(AFALG_F_AFALG_INIT_AIO, AFALG_R_IO_SETUP_FAILED);
205 memset(aio->cbt, 0, sizeof(aio->cbt));
207 aio->mode = MODE_UNINIT;
212 int afalg_fin_cipher_aio(afalg_aio *aio, int sfd, unsigned char *buf,
217 unsigned int done = 0;
219 struct timespec timeout;
220 struct io_event events[MAX_INFLIGHTS];
226 /* if efd has not been initialised yet do it here */
227 if (aio->mode == MODE_UNINIT) {
228 r = afalg_setup_async_event_notification(aio);
233 cb = &(aio->cbt[0 % MAX_INFLIGHTS]);
234 memset(cb, '\0', sizeof(*cb));
235 cb->aio_fildes = sfd;
236 cb->aio_lio_opcode = IOCB_CMD_PREAD;
237 if (sizeof(buf) != sizeof(cb->aio_buf)) {
239 * The pointer has to be converted to 32 bit unsigned value first
240 * to avoid sign extension on cast to 64 bit value
242 cb->aio_buf = (uint64_t)(unsigned long)buf;
244 cb->aio_buf = (uint64_t)buf;
248 cb->aio_nbytes = len;
249 cb->aio_flags = IOCB_FLAG_RESFD;
250 cb->aio_resfd = aio->efd;
253 * Perform AIO read on AFALG socket, this in turn performs an async
254 * crypto operation in kernel space
256 r = io_read(aio->aio_ctx, 1, &cb);
258 ALG_PWARN("%s: io_read failed : ", __func__);
263 /* While AIO read is being performed pause job */
266 /* Check for completion of AIO read */
267 r = read(aio->efd, &eval, sizeof(eval));
269 if (errno == EAGAIN || errno == EWOULDBLOCK)
271 ALG_PERR("%s: read failed for event fd : ", __func__);
273 } else if (r == 0 || eval <= 0) {
274 ALG_WARN("%s: eventfd read %d bytes, eval = %lu\n", __func__, r,
279 /* Get results of AIO read */
280 r = io_getevents(aio->aio_ctx, 1, MAX_INFLIGHTS,
284 * events.res indicates the actual status of the operation.
285 * Handle the error condition first.
287 if (events[0].res < 0) {
289 * Underlying operation cannot be completed at the time
290 * of previous submission. Resubmit for the operation.
292 if (events[0].res == -EBUSY && retry++ < 3) {
293 r = io_read(aio->aio_ctx, 1, &cb);
295 ALG_PERR("%s: retry %d for io_read failed : ",
302 * Retries exceed for -EBUSY or unrecoverable error
303 * condition for this instance of operation.
306 ("%s: Crypto Operation failed with code %lld\n",
307 __func__, events[0].res);
311 /* Operation successful. */
314 ALG_PERR("%s: io_getevents failed : ", __func__);
317 ALG_WARN("%s: io_geteventd read 0 bytes\n", __func__);
325 static ossl_inline void afalg_set_op_sk(struct cmsghdr *cmsg,
326 const ALG_OP_TYPE op)
328 cmsg->cmsg_level = SOL_ALG;
329 cmsg->cmsg_type = ALG_SET_OP;
330 cmsg->cmsg_len = CMSG_LEN(ALG_OP_LEN);
331 memcpy(CMSG_DATA(cmsg), &op, ALG_OP_LEN);
334 static void afalg_set_iv_sk(struct cmsghdr *cmsg, const unsigned char *iv,
335 const unsigned int len)
337 struct af_alg_iv *aiv;
339 cmsg->cmsg_level = SOL_ALG;
340 cmsg->cmsg_type = ALG_SET_IV;
341 cmsg->cmsg_len = CMSG_LEN(ALG_IV_LEN(len));
342 aiv = (struct af_alg_iv *)CMSG_DATA(cmsg);
344 memcpy(aiv->iv, iv, len);
347 static ossl_inline int afalg_set_key(afalg_ctx *actx, const unsigned char *key,
351 ret = setsockopt(actx->bfd, SOL_ALG, ALG_SET_KEY, key, klen);
353 ALG_PERR("%s: Failed to set socket option : ", __func__);
354 AFALGerr(AFALG_F_AFALG_SET_KEY, AFALG_R_SOCKET_SET_KEY_FAILED);
361 static int afalg_create_sk(afalg_ctx *actx, const char *ciphertype,
362 const char *ciphername)
364 struct sockaddr_alg sa;
366 actx->bfd = actx->sfd = -1;
369 memset(&sa, 0, sizeof(sa));
370 sa.salg_family = AF_ALG;
371 strncpy((char *) sa.salg_type, ciphertype, ALG_MAX_SALG_TYPE);
372 sa.salg_type[ALG_MAX_SALG_TYPE-1] = '\0';
373 strncpy((char *) sa.salg_name, ciphername, ALG_MAX_SALG_NAME);
374 sa.salg_name[ALG_MAX_SALG_NAME-1] = '\0';
376 actx->bfd = socket(AF_ALG, SOCK_SEQPACKET, 0);
377 if (actx->bfd == -1) {
378 ALG_PERR("%s: Failed to open socket : ", __func__);
379 AFALGerr(AFALG_F_AFALG_CREATE_SK, AFALG_R_SOCKET_CREATE_FAILED);
383 r = bind(actx->bfd, (struct sockaddr *)&sa, sizeof(sa));
385 ALG_PERR("%s: Failed to bind socket : ", __func__);
386 AFALGerr(AFALG_F_AFALG_CREATE_SK, AFALG_R_SOCKET_BIND_FAILED);
390 actx->sfd = accept(actx->bfd, NULL, 0);
392 ALG_PERR("%s: Socket Accept Failed : ", __func__);
393 AFALGerr(AFALG_F_AFALG_CREATE_SK, AFALG_R_SOCKET_ACCEPT_FAILED);
404 actx->bfd = actx->sfd = -1;
408 static int afalg_start_cipher_sk(afalg_ctx *actx, const unsigned char *in,
409 size_t inl, const unsigned char *iv,
412 struct msghdr msg = { 0 };
413 struct cmsghdr *cmsg;
416 # ifdef ALG_ZERO_COPY
419 char cbuf[CMSG_SPACE(ALG_IV_LEN(ALG_AES_IV_LEN)) + CMSG_SPACE(ALG_OP_LEN)];
421 memset(cbuf, 0, sizeof(cbuf));
422 msg.msg_control = cbuf;
423 msg.msg_controllen = sizeof(cbuf);
426 * cipher direction (i.e. encrypt or decrypt) and iv are sent to the
427 * kernel as part of sendmsg()'s ancillary data
429 cmsg = CMSG_FIRSTHDR(&msg);
430 afalg_set_op_sk(cmsg, enc);
431 cmsg = CMSG_NXTHDR(&msg, cmsg);
432 afalg_set_iv_sk(cmsg, iv, ALG_AES_IV_LEN);
434 /* iov that describes input data */
435 iov.iov_base = (unsigned char *)in;
438 msg.msg_flags = MSG_MORE;
440 # ifdef ALG_ZERO_COPY
443 * Works best when buffer is 4k aligned
444 * OPENS: out of place processing (i.e. out != in)
447 /* Input data is not sent as part of call to sendmsg() */
451 /* Sendmsg() sends iv and cipher direction to the kernel */
452 sbytes = sendmsg(actx->sfd, &msg, 0);
454 ALG_PERR("%s: sendmsg failed for zero copy cipher operation : ",
460 * vmsplice and splice are used to pin the user space input buffer for
461 * kernel space processing avoiding copys from user to kernel space
463 ret = vmsplice(actx->zc_pipe[1], &iov, 1, SPLICE_F_GIFT);
465 ALG_PERR("%s: vmsplice failed : ", __func__);
469 ret = splice(actx->zc_pipe[0], NULL, actx->sfd, NULL, inl, 0);
471 ALG_PERR("%s: splice failed : ", __func__);
478 /* Sendmsg() sends iv, cipher direction and input data to the kernel */
479 sbytes = sendmsg(actx->sfd, &msg, 0);
481 ALG_PERR("%s: sendmsg failed for cipher operation : ", __func__);
485 if (sbytes != (ssize_t) inl) {
486 ALG_WARN("Cipher operation send bytes %zd != inlen %zd\n", sbytes,
495 static int afalg_cipher_init(EVP_CIPHER_CTX *ctx, const unsigned char *key,
496 const unsigned char *iv, int enc)
501 char ciphername[ALG_MAX_SALG_NAME];
503 if (ctx == NULL || key == NULL) {
504 ALG_WARN("%s: Null Parameter\n", __func__);
508 if (EVP_CIPHER_CTX_cipher(ctx) == NULL) {
509 ALG_WARN("%s: Cipher object NULL\n", __func__);
513 actx = EVP_CIPHER_CTX_get_cipher_data(ctx);
515 ALG_WARN("%s: Cipher data NULL\n", __func__);
519 ciphertype = EVP_CIPHER_CTX_nid(ctx);
520 switch (ciphertype) {
521 case NID_aes_128_cbc:
522 strncpy(ciphername, "cbc(aes)", ALG_MAX_SALG_NAME);
525 ALG_WARN("%s: Unsupported Cipher type %d\n", __func__, ciphertype);
528 ciphername[ALG_MAX_SALG_NAME-1]='\0';
530 if (ALG_AES_IV_LEN != EVP_CIPHER_CTX_iv_length(ctx)) {
531 ALG_WARN("%s: Unsupported IV length :%d\n", __func__,
532 EVP_CIPHER_CTX_iv_length(ctx));
536 /* Setup AFALG socket for crypto processing */
537 ret = afalg_create_sk(actx, "skcipher", ciphername);
542 ret = afalg_set_key(actx, key, EVP_CIPHER_CTX_key_length(ctx));
546 /* Setup AIO ctx to allow async AFALG crypto processing */
547 if (afalg_init_aio(&actx->aio) == 0)
550 # ifdef ALG_ZERO_COPY
554 actx->init_done = MAGIC_INIT_NUM;
564 static int afalg_do_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
565 const unsigned char *in, size_t inl)
569 char nxtiv[ALG_AES_IV_LEN] = { 0 };
571 if (ctx == NULL || out == NULL || in == NULL) {
572 ALG_WARN("NULL parameter passed to function %s\n", __func__);
576 actx = (afalg_ctx *) EVP_CIPHER_CTX_get_cipher_data(ctx);
577 if (actx == NULL || actx->init_done != MAGIC_INIT_NUM) {
578 ALG_WARN("%s afalg ctx passed\n",
579 ctx == NULL ? "NULL" : "Uninitialised");
584 * set iv now for decrypt operation as the input buffer can be
585 * overwritten for inplace operation where in = out.
587 if (EVP_CIPHER_CTX_encrypting(ctx) == 0) {
588 memcpy(nxtiv, in + (inl - ALG_AES_IV_LEN), ALG_AES_IV_LEN);
591 /* Send input data to kernel space */
592 ret = afalg_start_cipher_sk(actx, (unsigned char *)in, inl,
593 EVP_CIPHER_CTX_iv(ctx),
594 EVP_CIPHER_CTX_encrypting(ctx));
599 /* Perform async crypto operation in kernel space */
600 ret = afalg_fin_cipher_aio(&actx->aio, actx->sfd, out, inl);
604 if (EVP_CIPHER_CTX_encrypting(ctx)) {
605 memcpy(EVP_CIPHER_CTX_iv_noconst(ctx), out + (inl - ALG_AES_IV_LEN),
608 memcpy(EVP_CIPHER_CTX_iv_noconst(ctx), nxtiv, ALG_AES_IV_LEN);
614 static int afalg_cipher_cleanup(EVP_CIPHER_CTX *ctx)
619 ALG_WARN("NULL parameter passed to function %s\n", __func__);
623 actx = (afalg_ctx *) EVP_CIPHER_CTX_get_cipher_data(ctx);
624 if (actx == NULL || actx->init_done != MAGIC_INIT_NUM) {
625 ALG_WARN("%s afalg ctx passed\n",
626 ctx == NULL ? "NULL" : "Uninitialised");
632 # ifdef ALG_ZERO_COPY
633 close(actx->zc_pipe[0]);
634 close(actx->zc_pipe[1]);
636 /* close efd in sync mode, async mode is closed in afalg_waitfd_cleanup() */
637 if (actx->aio.mode == MODE_SYNC)
638 close(actx->aio.efd);
639 io_destroy(actx->aio.aio_ctx);
644 const EVP_CIPHER *afalg_aes_128_cbc(void)
646 if (_hidden_aes_128_cbc == NULL
647 && ((_hidden_aes_128_cbc =
648 EVP_CIPHER_meth_new(NID_aes_128_cbc,
650 AES_KEY_SIZE_128)) == NULL
651 || !EVP_CIPHER_meth_set_iv_length(_hidden_aes_128_cbc, AES_IV_LEN)
652 || !EVP_CIPHER_meth_set_flags(_hidden_aes_128_cbc,
654 EVP_CIPH_FLAG_DEFAULT_ASN1)
655 || !EVP_CIPHER_meth_set_init(_hidden_aes_128_cbc,
657 || !EVP_CIPHER_meth_set_do_cipher(_hidden_aes_128_cbc,
659 || !EVP_CIPHER_meth_set_cleanup(_hidden_aes_128_cbc,
660 afalg_cipher_cleanup)
661 || !EVP_CIPHER_meth_set_impl_ctx_size(_hidden_aes_128_cbc,
662 sizeof(afalg_ctx)))) {
663 EVP_CIPHER_meth_free(_hidden_aes_128_cbc);
664 _hidden_aes_128_cbc = NULL;
666 return _hidden_aes_128_cbc;
669 static int afalg_ciphers(ENGINE *e, const EVP_CIPHER **cipher,
670 const int **nids, int nid)
674 if (cipher == NULL) {
675 *nids = afalg_cipher_nids;
676 return (sizeof(afalg_cipher_nids) / sizeof(afalg_cipher_nids[0]));
680 case NID_aes_128_cbc:
681 *cipher = afalg_aes_128_cbc();
691 static int bind_afalg(ENGINE *e)
693 /* Ensure the afalg error handling is set up */
694 ERR_load_AFALG_strings();
696 if (!ENGINE_set_id(e, engine_afalg_id)
697 || !ENGINE_set_name(e, engine_afalg_name)
698 || !ENGINE_set_destroy_function(e, afalg_destroy)
699 || !ENGINE_set_init_function(e, afalg_init)
700 || !ENGINE_set_finish_function(e, afalg_finish)) {
701 AFALGerr(AFALG_F_BIND_AFALG, AFALG_R_INIT_FAILED);
706 * Create _hidden_aes_128_cbc by calling afalg_aes_128_cbc
707 * now, as bind_aflag can only be called by one thread at a
710 if (afalg_aes_128_cbc() == NULL) {
711 AFALGerr(AFALG_F_BIND_AFALG, AFALG_R_INIT_FAILED);
715 if (!ENGINE_set_ciphers(e, afalg_ciphers)) {
716 AFALGerr(AFALG_F_BIND_AFALG, AFALG_R_INIT_FAILED);
723 # ifndef OPENSSL_NO_DYNAMIC_ENGINE
724 static int bind_helper(ENGINE *e, const char *id)
726 if (id && (strcmp(id, engine_afalg_id) != 0))
729 if (!afalg_chk_platform())
737 IMPLEMENT_DYNAMIC_CHECK_FN()
738 IMPLEMENT_DYNAMIC_BIND_FN(bind_helper)
741 static int afalg_chk_platform(void)
745 int kver[3] = { -1, -1, -1 };
752 AFALGerr(AFALG_F_AFALG_CHK_PLATFORM,
753 AFALG_R_FAILED_TO_GET_PLATFORM_INFO);
757 str = strtok(ut.release, ".");
758 for (i = 0; i < 3 && str != NULL; i++) {
760 str = strtok(NULL, ".");
763 if (KERNEL_VERSION(kver[0], kver[1], kver[2])
764 < KERNEL_VERSION(K_MAJ, K_MIN1, K_MIN2)) {
765 ALG_ERR("ASYNC AFALG not supported this kernel(%d.%d.%d)\n",
766 kver[0], kver[1], kver[2]);
767 ALG_ERR("ASYNC AFALG requires kernel version %d.%d.%d or later\n",
768 K_MAJ, K_MIN1, K_MIN2);
769 AFALGerr(AFALG_F_AFALG_CHK_PLATFORM,
770 AFALG_R_KERNEL_DOES_NOT_SUPPORT_ASYNC_AFALG);
774 /* Test if we can actually create an AF_ALG socket */
775 sock = socket(AF_ALG, SOCK_SEQPACKET, 0);
777 AFALGerr(AFALG_F_AFALG_CHK_PLATFORM, AFALG_R_SOCKET_CREATE_FAILED);
785 # ifdef OPENSSL_NO_DYNAMIC_ENGINE
786 static ENGINE *engine_afalg(void)
788 ENGINE *ret = ENGINE_new();
791 if (!bind_afalg(ret)) {
798 void engine_load_afalg_int(void)
802 if (!afalg_chk_platform())
805 toadd = engine_afalg();
814 static int afalg_init(ENGINE *e)
819 static int afalg_finish(ENGINE *e)
824 static int afalg_destroy(ENGINE *e)
826 ERR_unload_AFALG_strings();
827 EVP_CIPHER_meth_free(_hidden_aes_128_cbc);
828 _hidden_aes_128_cbc = NULL;
832 #endif /* KERNEL VERSION */