e_afalg.c 23.1 KB
Newer Older
R
Rich Salz 已提交
1 2
/*
 * Copyright 2016 The OpenSSL Project Authors. All Rights Reserved.
C
clucey 已提交
3
 *
R
Rich Salz 已提交
4 5 6 7
 * Licensed under the OpenSSL license (the "License").  You may not use
 * this file except in compliance with the License.  You can obtain a copy
 * in the file LICENSE in the source distribution or at
 * https://www.openssl.org/source/license.html
C
clucey 已提交
8 9 10
 */

/* Required for vmsplice */
11 12 13
#ifndef _GNU_SOURCE
# define _GNU_SOURCE
#endif
C
clucey 已提交
14 15 16 17 18 19
#include <stdio.h>
#include <string.h>
#include <unistd.h>

#include <openssl/engine.h>
#include <openssl/async.h>
M
Matt Caswell 已提交
20
#include <openssl/err.h>
C
clucey 已提交
21

22
#include <sys/socket.h>
C
clucey 已提交
23 24 25 26
#include <linux/version.h>
#define K_MAJ   4
#define K_MIN1  1
#define K_MIN2  0
27 28
#if LINUX_VERSION_CODE <= KERNEL_VERSION(K_MAJ, K_MIN1, K_MIN2) || \
    !defined(AF_ALG)
C
clucey 已提交
29 30
# warning "AFALG ENGINE requires Kernel Headers >= 4.1.0"
# warning "Skipping Compilation of AFALG engine"
31
void engine_load_afalg_int(void);
32 33 34
void engine_load_afalg_int(void)
{
}
C
clucey 已提交
35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
#else

# include <linux/if_alg.h>
# include <fcntl.h>
# include <sys/utsname.h>

# include <linux/aio_abi.h>
# include <sys/syscall.h>
# include <errno.h>

# include "e_afalg.h"

# define AFALG_LIB_NAME "AFALG"
# include "e_afalg_err.h"

# ifndef SOL_ALG
#  define SOL_ALG 279
# endif

# ifdef ALG_ZERO_COPY
#  ifndef SPLICE_F_GIFT
#   define SPLICE_F_GIFT    (0x08)
#  endif
# endif

# define ALG_AES_IV_LEN 16
# define ALG_IV_LEN(len) (sizeof(struct af_alg_iv) + (len))
# define ALG_OP_TYPE     unsigned int
# define ALG_OP_LEN      (sizeof(ALG_OP_TYPE))

C
clucey 已提交
65 66 67 68
#define ALG_MAX_SALG_NAME       64
#define ALG_MAX_SALG_TYPE       14

# ifdef OPENSSL_NO_DYNAMIC_ENGINE
69
void engine_load_afalg_int(void);
C
clucey 已提交
70 71
# endif

C
clucey 已提交
72 73 74 75
/* Local Linkage Functions */
static int afalg_init_aio(afalg_aio *aio);
static int afalg_fin_cipher_aio(afalg_aio *ptr, int sfd,
                                unsigned char *buf, size_t len);
C
clucey 已提交
76 77
static int afalg_create_sk(afalg_ctx *actx, const char *ciphertype,
                                const char *ciphername);
C
clucey 已提交
78 79 80 81 82 83 84 85 86 87 88 89 90 91 92
static int afalg_destroy(ENGINE *e);
static int afalg_init(ENGINE *e);
static int afalg_finish(ENGINE *e);
const EVP_CIPHER *afalg_aes_128_cbc(void);
static int afalg_ciphers(ENGINE *e, const EVP_CIPHER **cipher,
                         const int **nids, int nid);
static int afalg_cipher_init(EVP_CIPHER_CTX *ctx, const unsigned char *key,
                             const unsigned char *iv, int enc);
static int afalg_do_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
                           const unsigned char *in, size_t inl);
static int afalg_cipher_cleanup(EVP_CIPHER_CTX *ctx);
static int afalg_chk_platform(void);

/* Engine Id and Name */
static const char *engine_afalg_id = "afalg";
D
typo  
Dr. Stephen Henson 已提交
93
static const char *engine_afalg_name = "AFALG engine support";
C
clucey 已提交
94

M
Matt Caswell 已提交
95
static int afalg_cipher_nids[] = {
C
clucey 已提交
96 97 98 99 100
    NID_aes_128_cbc
};

static EVP_CIPHER *_hidden_aes_128_cbc = NULL;

J
Jeffrey Walton 已提交
101
static ossl_inline int io_setup(unsigned n, aio_context_t *ctx)
C
clucey 已提交
102 103 104 105
{
    return syscall(__NR_io_setup, n, ctx);
}

J
Jeffrey Walton 已提交
106
static ossl_inline int eventfd(int n)
C
clucey 已提交
107 108 109 110
{
    return syscall(__NR_eventfd, n);
}

J
Jeffrey Walton 已提交
111
static ossl_inline int io_destroy(aio_context_t ctx)
C
clucey 已提交
112 113 114 115
{
    return syscall(__NR_io_destroy, ctx);
}

J
Jeffrey Walton 已提交
116
static ossl_inline int io_read(aio_context_t ctx, long n, struct iocb **iocb)
C
clucey 已提交
117 118 119 120
{
    return syscall(__NR_io_submit, ctx, n, iocb);
}

J
Jeffrey Walton 已提交
121
static ossl_inline int io_getevents(aio_context_t ctx, long min, long max,
C
clucey 已提交
122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138
                               struct io_event *events,
                               struct timespec *timeout)
{
    return syscall(__NR_io_getevents, ctx, min, max, events, timeout);
}

static void afalg_waitfd_cleanup(ASYNC_WAIT_CTX *ctx, const void *key,
                                 OSSL_ASYNC_FD waitfd, void *custom)
{
    close(waitfd);
}

static int afalg_setup_async_event_notification(afalg_aio *aio)
{
    ASYNC_JOB *job;
    ASYNC_WAIT_CTX *waitctx;
    void *custom = NULL;
C
clucey 已提交
139
    int ret;
C
clucey 已提交
140 141 142 143 144 145 146 147 148

    if ((job = ASYNC_get_current_job()) != NULL) {
        /* Async mode */
        waitctx = ASYNC_get_wait_ctx(job);
        if (waitctx == NULL) {
            ALG_WARN("%s: ASYNC_get_wait_ctx error", __func__);
            return 0;
        }
        /* Get waitfd from ASYNC_WAIT_CTX if it is alreday set */
C
clucey 已提交
149 150 151 152 153 154 155 156 157
        ret = ASYNC_WAIT_CTX_get_fd(waitctx, engine_afalg_id,
                                    &aio->efd, &custom);
        if (ret == 0) {
            /*
             * waitfd is not set in ASYNC_WAIT_CTX, create a new one
             * and set it. efd will be signaled when AIO operation completes
             */
            aio->efd = eventfd(0);
            if (aio->efd == -1) {
C
clucey 已提交
158 159 160 161 162
                ALG_PERR("%s: Failed to get eventfd : ", __func__);
                AFALGerr(AFALG_F_AFALG_SETUP_ASYNC_EVENT_NOTIFICATION,
                         AFALG_R_EVENTFD_FAILED);
                return 0;
            }
C
clucey 已提交
163 164 165 166
            ret = ASYNC_WAIT_CTX_set_wait_fd(waitctx, engine_afalg_id,
                                             aio->efd, custom,
                                             afalg_waitfd_cleanup);
            if (ret == 0) {
C
clucey 已提交
167
                ALG_WARN("%s: Failed to set wait fd", __func__);
C
clucey 已提交
168
                close(aio->efd);
C
clucey 已提交
169 170 171
                return 0;
            }
            /* make fd non-blocking in async mode */
C
clucey 已提交
172
            if (fcntl(aio->efd, F_SETFL, O_NONBLOCK) != 0) {
C
clucey 已提交
173 174 175 176
                ALG_WARN("%s: Failed to set event fd as NONBLOCKING",
                         __func__);
            }
        }
C
clucey 已提交
177
        aio->mode = MODE_ASYNC;
C
clucey 已提交
178 179
    } else {
        /* Sync mode */
C
clucey 已提交
180 181
        aio->efd = eventfd(0);
        if (aio->efd == -1) {
C
clucey 已提交
182 183 184 185 186
            ALG_PERR("%s: Failed to get eventfd : ", __func__);
            AFALGerr(AFALG_F_AFALG_SETUP_ASYNC_EVENT_NOTIFICATION,
                     AFALG_R_EVENTFD_FAILED);
            return 0;
        }
C
clucey 已提交
187
        aio->mode = MODE_SYNC;
C
clucey 已提交
188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206
    }
    return 1;
}

int afalg_init_aio(afalg_aio *aio)
{
    int r = -1;

    /* Initialise for AIO */
    aio->aio_ctx = 0;
    r = io_setup(MAX_INFLIGHTS, &aio->aio_ctx);
    if (r < 0) {
        ALG_PERR("%s: io_setup error : ", __func__);
        AFALGerr(AFALG_F_AFALG_INIT_AIO, AFALG_R_IO_SETUP_FAILED);
        return 0;
    }

    memset(aio->cbt, 0, sizeof(aio->cbt));
    aio->efd = -1;
C
clucey 已提交
207
    aio->mode = MODE_UNINIT;
C
clucey 已提交
208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226

    return 1;
}

int afalg_fin_cipher_aio(afalg_aio *aio, int sfd, unsigned char *buf,
                         size_t len)
{
    int r;
    int retry = 0;
    unsigned int done = 0;
    struct iocb *cb;
    struct timespec timeout;
    struct io_event events[MAX_INFLIGHTS];
    u_int64_t eval = 0;

    timeout.tv_sec = 0;
    timeout.tv_nsec = 0;

    /* if efd has not been initialised yet do it here */
C
clucey 已提交
227
    if (aio->mode == MODE_UNINIT) {
C
clucey 已提交
228 229 230 231 232 233 234 235 236
        r = afalg_setup_async_event_notification(aio);
        if (r == 0)
            return 0;
    }

    cb = &(aio->cbt[0 % MAX_INFLIGHTS]);
    memset(cb, '\0', sizeof(*cb));
    cb->aio_fildes = sfd;
    cb->aio_lio_opcode = IOCB_CMD_PREAD;
237 238 239 240 241 242 243 244 245
    if (sizeof(buf) != sizeof(cb->aio_buf)) {
        /*
         * The pointer has to be converted to 32 bit unsigned value first
         * to avoid sign extension on cast to 64 bit value
         */
        cb->aio_buf = (uint64_t)(unsigned long)buf;
    } else {
        cb->aio_buf = (uint64_t)buf;
    }
C
clucey 已提交
246 247 248 249 250 251 252 253 254 255 256 257
    cb->aio_offset = 0;
    cb->aio_data = 0;
    cb->aio_nbytes = len;
    cb->aio_flags = IOCB_FLAG_RESFD;
    cb->aio_resfd = aio->efd;

    /*
     * Perform AIO read on AFALG socket, this in turn performs an async
     * crypto operation in kernel space
     */
    r = io_read(aio->aio_ctx, 1, &cb);
    if (r < 0) {
C
clucey 已提交
258
        ALG_PWARN("%s: io_read failed : ", __func__);
C
clucey 已提交
259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279
        return 0;
    }

    do {
        /* While AIO read is being performed pause job */
        ASYNC_pause_job();

        /* Check for completion of AIO read */
        r = read(aio->efd, &eval, sizeof(eval));
        if (r < 0) {
            if (errno == EAGAIN || errno == EWOULDBLOCK)
                continue;
            ALG_PERR("%s: read failed for event fd : ", __func__);
            return 0;
        } else if (r == 0 || eval <= 0) {
            ALG_WARN("%s: eventfd read %d bytes, eval = %lu\n", __func__, r,
                     eval);
        }
        if (eval > 0) {

            /* Get results of AIO read */
C
clucey 已提交
280 281
            r = io_getevents(aio->aio_ctx, 1, MAX_INFLIGHTS,
                             events, &timeout);
C
clucey 已提交
282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324
            if (r > 0) {
                /*
                 * events.res indicates the actual status of the operation.
                 * Handle the error condition first.
                 */
                if (events[0].res < 0) {
                    /*
                     * Underlying operation cannot be completed at the time
                     * of previous submission. Resubmit for the operation.
                     */
                    if (events[0].res == -EBUSY && retry++ < 3) {
                        r = io_read(aio->aio_ctx, 1, &cb);
                        if (r < 0) {
                            ALG_PERR("%s: retry %d for io_read failed : ",
                                     __func__, retry);
                            return 0;
                        }
                        continue;
                    } else {
                        /*
                         * Retries exceed for -EBUSY or unrecoverable error
                         * condition for this instance of operation.
                         */
                        ALG_WARN
                            ("%s: Crypto Operation failed with code %lld\n",
                             __func__, events[0].res);
                        return 0;
                    }
                }
                /* Operation successful. */
                done = 1;
            } else if (r < 0) {
                ALG_PERR("%s: io_getevents failed : ", __func__);
                return 0;
            } else {
                ALG_WARN("%s: io_geteventd read 0 bytes\n", __func__);
            }
        }
    } while (!done);

    return 1;
}

J
Jeffrey Walton 已提交
325
static ossl_inline void afalg_set_op_sk(struct cmsghdr *cmsg,
326
                                   const ALG_OP_TYPE op)
C
clucey 已提交
327 328 329 330
{
    cmsg->cmsg_level = SOL_ALG;
    cmsg->cmsg_type = ALG_SET_OP;
    cmsg->cmsg_len = CMSG_LEN(ALG_OP_LEN);
331
    memcpy(CMSG_DATA(cmsg), &op, ALG_OP_LEN);
C
clucey 已提交
332 333 334 335 336 337 338 339 340 341 342 343 344 345 346
}

static void afalg_set_iv_sk(struct cmsghdr *cmsg, const unsigned char *iv,
                            const unsigned int len)
{
    struct af_alg_iv *aiv;

    cmsg->cmsg_level = SOL_ALG;
    cmsg->cmsg_type = ALG_SET_IV;
    cmsg->cmsg_len = CMSG_LEN(ALG_IV_LEN(len));
    aiv = (struct af_alg_iv *)CMSG_DATA(cmsg);
    aiv->ivlen = len;
    memcpy(aiv->iv, iv, len);
}

J
Jeffrey Walton 已提交
347
static ossl_inline int afalg_set_key(afalg_ctx *actx, const unsigned char *key,
C
clucey 已提交
348
                                const int klen)
C
clucey 已提交
349 350
{
    int ret;
C
clucey 已提交
351 352 353 354 355 356 357 358 359 360 361 362 363 364
    ret = setsockopt(actx->bfd, SOL_ALG, ALG_SET_KEY, key, klen);
    if (ret < 0) {
        ALG_PERR("%s: Failed to set socket option : ", __func__);
        AFALGerr(AFALG_F_AFALG_SET_KEY, AFALG_R_SOCKET_SET_KEY_FAILED);
        return 0;
    }

    return 1;
}

static int afalg_create_sk(afalg_ctx *actx, const char *ciphertype,
                                const char *ciphername)
{
    struct sockaddr_alg sa;
C
clucey 已提交
365 366

    actx->bfd = actx->sfd = -1;
C
clucey 已提交
367
    int r = -1;
C
clucey 已提交
368

C
clucey 已提交
369 370 371 372 373 374 375 376 377 378 379 380
    memset(&sa, 0, sizeof(sa));
    sa.salg_family = AF_ALG;
    strncpy((char *) sa.salg_type, ciphertype, ALG_MAX_SALG_TYPE);
    sa.salg_type[ALG_MAX_SALG_TYPE-1] = '\0';
    strncpy((char *) sa.salg_name, ciphername, ALG_MAX_SALG_NAME);
    sa.salg_name[ALG_MAX_SALG_NAME-1] = '\0';

    actx->bfd = socket(AF_ALG, SOCK_SEQPACKET, 0);
    if (actx->bfd == -1) {
        ALG_PERR("%s: Failed to open socket : ", __func__);
        AFALGerr(AFALG_F_AFALG_CREATE_SK, AFALG_R_SOCKET_CREATE_FAILED);
        goto err;
C
clucey 已提交
381 382
    }

C
clucey 已提交
383 384 385 386
    r = bind(actx->bfd, (struct sockaddr *)&sa, sizeof(sa));
    if (r < 0) {
        ALG_PERR("%s: Failed to bind socket : ", __func__);
        AFALGerr(AFALG_F_AFALG_CREATE_SK, AFALG_R_SOCKET_BIND_FAILED);
C
clucey 已提交
387 388 389 390 391 392
        goto err;
    }

    actx->sfd = accept(actx->bfd, NULL, 0);
    if (actx->sfd < 0) {
        ALG_PERR("%s: Socket Accept Failed : ", __func__);
C
clucey 已提交
393
        AFALGerr(AFALG_F_AFALG_CREATE_SK, AFALG_R_SOCKET_ACCEPT_FAILED);
C
clucey 已提交
394 395 396
        goto err;
    }

C
clucey 已提交
397
    return 1;
C
clucey 已提交
398 399 400 401 402 403 404

 err:
    if (actx->bfd >= 0)
        close(actx->bfd);
    if (actx->sfd >= 0)
        close(actx->sfd);
    actx->bfd = actx->sfd = -1;
C
clucey 已提交
405
    return 0;
C
clucey 已提交
406 407 408 409 410 411 412 413 414 415 416 417 418
}

static int afalg_start_cipher_sk(afalg_ctx *actx, const unsigned char *in,
                                 size_t inl, const unsigned char *iv,
                                 unsigned int enc)
{
    struct msghdr msg = { 0 };
    struct cmsghdr *cmsg;
    struct iovec iov;
    ssize_t sbytes;
# ifdef ALG_ZERO_COPY
    int ret;
# endif
M
Matt Caswell 已提交
419
    char cbuf[CMSG_SPACE(ALG_IV_LEN(ALG_AES_IV_LEN)) + CMSG_SPACE(ALG_OP_LEN)];
C
clucey 已提交
420

M
Matt Caswell 已提交
421
    memset(cbuf, 0, sizeof(cbuf));
C
clucey 已提交
422
    msg.msg_control = cbuf;
M
Matt Caswell 已提交
423
    msg.msg_controllen = sizeof(cbuf);
C
clucey 已提交
424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485

    /*
     * cipher direction (i.e. encrypt or decrypt) and iv are sent to the
     * kernel as part of sendmsg()'s ancillary data
     */
    cmsg = CMSG_FIRSTHDR(&msg);
    afalg_set_op_sk(cmsg, enc);
    cmsg = CMSG_NXTHDR(&msg, cmsg);
    afalg_set_iv_sk(cmsg, iv, ALG_AES_IV_LEN);

    /* iov that describes input data */
    iov.iov_base = (unsigned char *)in;
    iov.iov_len = inl;

    msg.msg_flags = MSG_MORE;

# ifdef ALG_ZERO_COPY
    /*
     * ZERO_COPY mode
     * Works best when buffer is 4k aligned
     * OPENS: out of place processing (i.e. out != in)
     */

    /* Input data is not sent as part of call to sendmsg() */
    msg.msg_iovlen = 0;
    msg.msg_iov = NULL;

    /* Sendmsg() sends iv and cipher direction to the kernel */
    sbytes = sendmsg(actx->sfd, &msg, 0);
    if (sbytes < 0) {
        ALG_PERR("%s: sendmsg failed for zero copy cipher operation : ",
                 __func__);
        return 0;
    }

    /*
     * vmsplice and splice are used to pin the user space input buffer for
     * kernel space processing avoiding copys from user to kernel space
     */
    ret = vmsplice(actx->zc_pipe[1], &iov, 1, SPLICE_F_GIFT);
    if (ret < 0) {
        ALG_PERR("%s: vmsplice failed : ", __func__);
        return 0;
    }

    ret = splice(actx->zc_pipe[0], NULL, actx->sfd, NULL, inl, 0);
    if (ret < 0) {
        ALG_PERR("%s: splice failed : ", __func__);
        return 0;
    }
# else
    msg.msg_iovlen = 1;
    msg.msg_iov = &iov;

    /* Sendmsg() sends iv, cipher direction and input data to the kernel */
    sbytes = sendmsg(actx->sfd, &msg, 0);
    if (sbytes < 0) {
        ALG_PERR("%s: sendmsg failed for cipher operation : ", __func__);
        return 0;
    }

    if (sbytes != (ssize_t) inl) {
C
clucey 已提交
486
        ALG_WARN("Cipher operation send bytes %zd != inlen %zd\n", sbytes,
C
clucey 已提交
487 488 489 490 491 492 493 494 495 496 497 498
                inl);
        return 0;
    }
# endif

    return 1;
}

static int afalg_cipher_init(EVP_CIPHER_CTX *ctx, const unsigned char *key,
                             const unsigned char *iv, int enc)
{
    int ciphertype;
C
clucey 已提交
499
    int ret;
C
clucey 已提交
500
    afalg_ctx *actx;
C
clucey 已提交
501
    char ciphername[ALG_MAX_SALG_NAME];
C
clucey 已提交
502 503 504 505 506 507 508 509 510 511 512

    if (ctx == NULL || key == NULL) {
        ALG_WARN("%s: Null Parameter\n", __func__);
        return 0;
    }

    if (EVP_CIPHER_CTX_cipher(ctx) == NULL) {
        ALG_WARN("%s: Cipher object NULL\n", __func__);
        return 0;
    }

513
    actx = EVP_CIPHER_CTX_get_cipher_data(ctx);
C
clucey 已提交
514 515 516 517 518 519 520 521
    if (actx == NULL) {
        ALG_WARN("%s: Cipher data NULL\n", __func__);
        return 0;
    }

    ciphertype = EVP_CIPHER_CTX_nid(ctx);
    switch (ciphertype) {
    case NID_aes_128_cbc:
C
clucey 已提交
522
        strncpy(ciphername, "cbc(aes)", ALG_MAX_SALG_NAME);
C
clucey 已提交
523 524 525 526 527
        break;
    default:
        ALG_WARN("%s: Unsupported Cipher type %d\n", __func__, ciphertype);
        return 0;
    }
C
clucey 已提交
528
    ciphername[ALG_MAX_SALG_NAME-1]='\0';
C
clucey 已提交
529 530

    if (ALG_AES_IV_LEN != EVP_CIPHER_CTX_iv_length(ctx)) {
C
clucey 已提交
531
        ALG_WARN("%s: Unsupported IV length :%d\n", __func__,
C
clucey 已提交
532 533 534 535 536
                EVP_CIPHER_CTX_iv_length(ctx));
        return 0;
    }

    /* Setup AFALG socket for crypto processing */
C
clucey 已提交
537 538
    ret = afalg_create_sk(actx, "skcipher", ciphername);
    if (ret < 1)
C
clucey 已提交
539
        return 0;
C
clucey 已提交
540 541 542 543 544


    ret = afalg_set_key(actx, key, EVP_CIPHER_CTX_key_length(ctx));
    if (ret < 1)
        goto err;
C
clucey 已提交
545 546

    /* Setup AIO ctx to allow async AFALG crypto processing */
C
clucey 已提交
547 548 549
    if (afalg_init_aio(&actx->aio) == 0)
        goto err;

C
clucey 已提交
550 551 552 553 554 555 556
# ifdef ALG_ZERO_COPY
    pipe(actx->zc_pipe);
# endif

    actx->init_done = MAGIC_INIT_NUM;

    return 1;
C
clucey 已提交
557 558 559 560 561

err:
    close(actx->sfd);
    close(actx->bfd);
    return 0;
C
clucey 已提交
562 563 564 565 566 567 568 569 570 571 572 573 574 575
}

static int afalg_do_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
                           const unsigned char *in, size_t inl)
{
    afalg_ctx *actx;
    int ret;
    char nxtiv[ALG_AES_IV_LEN] = { 0 };

    if (ctx == NULL || out == NULL || in == NULL) {
        ALG_WARN("NULL parameter passed to function %s\n", __func__);
        return 0;
    }

576
    actx = (afalg_ctx *) EVP_CIPHER_CTX_get_cipher_data(ctx);
C
clucey 已提交
577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600
    if (actx == NULL || actx->init_done != MAGIC_INIT_NUM) {
        ALG_WARN("%s afalg ctx passed\n",
                 ctx == NULL ? "NULL" : "Uninitialised");
        return 0;
    }

    /*
     * set iv now for decrypt operation as the input buffer can be
     * overwritten for inplace operation where in = out.
     */
    if (EVP_CIPHER_CTX_encrypting(ctx) == 0) {
        memcpy(nxtiv, in + (inl - ALG_AES_IV_LEN), ALG_AES_IV_LEN);
    }

    /* Send input data to kernel space */
    ret = afalg_start_cipher_sk(actx, (unsigned char *)in, inl,
                                EVP_CIPHER_CTX_iv(ctx),
                                EVP_CIPHER_CTX_encrypting(ctx));
    if (ret < 1) {
        return 0;
    }

    /* Perform async crypto operation in kernel space */
    ret = afalg_fin_cipher_aio(&actx->aio, actx->sfd, out, inl);
C
clucey 已提交
601
    if (ret < 1)
C
clucey 已提交
602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622
        return 0;

    if (EVP_CIPHER_CTX_encrypting(ctx)) {
        memcpy(EVP_CIPHER_CTX_iv_noconst(ctx), out + (inl - ALG_AES_IV_LEN),
               ALG_AES_IV_LEN);
    } else {
        memcpy(EVP_CIPHER_CTX_iv_noconst(ctx), nxtiv, ALG_AES_IV_LEN);
    }

    return 1;
}

static int afalg_cipher_cleanup(EVP_CIPHER_CTX *ctx)
{
    afalg_ctx *actx;

    if (ctx == NULL) {
        ALG_WARN("NULL parameter passed to function %s\n", __func__);
        return 0;
    }

623
    actx = (afalg_ctx *) EVP_CIPHER_CTX_get_cipher_data(ctx);
C
clucey 已提交
624 625 626 627 628 629 630 631 632 633 634 635
    if (actx == NULL || actx->init_done != MAGIC_INIT_NUM) {
        ALG_WARN("%s afalg ctx passed\n",
                 ctx == NULL ? "NULL" : "Uninitialised");
        return 0;
    }

    close(actx->sfd);
    close(actx->bfd);
# ifdef ALG_ZERO_COPY
    close(actx->zc_pipe[0]);
    close(actx->zc_pipe[1]);
# endif
C
clucey 已提交
636 637 638
    /* close efd in sync mode, async mode is closed in afalg_waitfd_cleanup() */
    if (actx->aio.mode == MODE_SYNC)
        close(actx->aio.efd);
C
clucey 已提交
639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704
    io_destroy(actx->aio.aio_ctx);

    return 1;
}

const EVP_CIPHER *afalg_aes_128_cbc(void)
{
    if (_hidden_aes_128_cbc == NULL
        && ((_hidden_aes_128_cbc =
             EVP_CIPHER_meth_new(NID_aes_128_cbc,
                                 AES_BLOCK_SIZE,
                                 AES_KEY_SIZE_128)) == NULL
            || !EVP_CIPHER_meth_set_iv_length(_hidden_aes_128_cbc, AES_IV_LEN)
            || !EVP_CIPHER_meth_set_flags(_hidden_aes_128_cbc,
                                          EVP_CIPH_CBC_MODE |
                                          EVP_CIPH_FLAG_DEFAULT_ASN1)
            || !EVP_CIPHER_meth_set_init(_hidden_aes_128_cbc,
                                         afalg_cipher_init)
            || !EVP_CIPHER_meth_set_do_cipher(_hidden_aes_128_cbc,
                                              afalg_do_cipher)
            || !EVP_CIPHER_meth_set_cleanup(_hidden_aes_128_cbc,
                                            afalg_cipher_cleanup)
            || !EVP_CIPHER_meth_set_impl_ctx_size(_hidden_aes_128_cbc,
                                                  sizeof(afalg_ctx)))) {
        EVP_CIPHER_meth_free(_hidden_aes_128_cbc);
        _hidden_aes_128_cbc = NULL;
    }
    return _hidden_aes_128_cbc;
}

static int afalg_ciphers(ENGINE *e, const EVP_CIPHER **cipher,
                         const int **nids, int nid)
{
    int r = 1;

    if (cipher == NULL) {
        *nids = afalg_cipher_nids;
        return (sizeof(afalg_cipher_nids) / sizeof(afalg_cipher_nids[0]));
    }

    switch (nid) {
    case NID_aes_128_cbc:
        *cipher = afalg_aes_128_cbc();
        break;
    default:
        *cipher = NULL;
        r = 0;
    }

    return r;
}

static int bind_afalg(ENGINE *e)
{
    /* Ensure the afalg error handling is set up */
    ERR_load_AFALG_strings();

    if (!ENGINE_set_id(e, engine_afalg_id)
        || !ENGINE_set_name(e, engine_afalg_name)
        || !ENGINE_set_destroy_function(e, afalg_destroy)
        || !ENGINE_set_init_function(e, afalg_init)
        || !ENGINE_set_finish_function(e, afalg_finish)) {
        AFALGerr(AFALG_F_BIND_AFALG, AFALG_R_INIT_FAILED);
        return 0;
    }

C
clucey 已提交
705 706 707 708 709 710 711 712 713 714
    /*
     * Create _hidden_aes_128_cbc by calling afalg_aes_128_cbc
     * now, as bind_aflag can only be called by one thread at a
     * time.
     */
    if (afalg_aes_128_cbc() == NULL) {
        AFALGerr(AFALG_F_BIND_AFALG, AFALG_R_INIT_FAILED);
        return 0;
    }

C
clucey 已提交
715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739
    if (!ENGINE_set_ciphers(e, afalg_ciphers)) {
        AFALGerr(AFALG_F_BIND_AFALG, AFALG_R_INIT_FAILED);
        return 0;
    }

    return 1;
}

# ifndef OPENSSL_NO_DYNAMIC_ENGINE
static int bind_helper(ENGINE *e, const char *id)
{
    if (id && (strcmp(id, engine_afalg_id) != 0))
        return 0;

    if (!afalg_chk_platform())
        return 0;

    if (!bind_afalg(e))
        return 0;
    return 1;
}

IMPLEMENT_DYNAMIC_CHECK_FN()
    IMPLEMENT_DYNAMIC_BIND_FN(bind_helper)
# endif
C
clucey 已提交
740

C
clucey 已提交
741 742 743 744 745
static int afalg_chk_platform(void)
{
    int ret;
    int i;
    int kver[3] = { -1, -1, -1 };
746
    int sock;
C
clucey 已提交
747 748 749 750 751
    char *str;
    struct utsname ut;

    ret = uname(&ut);
    if (ret != 0) {
C
clucey 已提交
752 753
        AFALGerr(AFALG_F_AFALG_CHK_PLATFORM,
                 AFALG_R_FAILED_TO_GET_PLATFORM_INFO);
C
clucey 已提交
754 755 756 757 758 759 760 761 762 763 764
        return 0;
    }

    str = strtok(ut.release, ".");
    for (i = 0; i < 3 && str != NULL; i++) {
        kver[i] = atoi(str);
        str = strtok(NULL, ".");
    }

    if (KERNEL_VERSION(kver[0], kver[1], kver[2])
        < KERNEL_VERSION(K_MAJ, K_MIN1, K_MIN2)) {
C
clucey 已提交
765
        ALG_ERR("ASYNC AFALG not supported this kernel(%d.%d.%d)\n",
C
clucey 已提交
766
                 kver[0], kver[1], kver[2]);
C
clucey 已提交
767
        ALG_ERR("ASYNC AFALG requires kernel version %d.%d.%d or later\n",
C
clucey 已提交
768 769 770 771 772 773
                 K_MAJ, K_MIN1, K_MIN2);
        AFALGerr(AFALG_F_AFALG_CHK_PLATFORM,
                 AFALG_R_KERNEL_DOES_NOT_SUPPORT_ASYNC_AFALG);
        return 0;
    }

774 775 776 777 778 779 780 781
    /* Test if we can actually create an AF_ALG socket */
    sock = socket(AF_ALG, SOCK_SEQPACKET, 0);
    if (sock == -1) {
        AFALGerr(AFALG_F_AFALG_CHK_PLATFORM, AFALG_R_SOCKET_CREATE_FAILED);
        return 0;
    }
    close(sock);

C
clucey 已提交
782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797
    return 1;
}

# ifdef OPENSSL_NO_DYNAMIC_ENGINE
static ENGINE *engine_afalg(void)
{
    ENGINE *ret = ENGINE_new();
    if (ret == NULL)
        return NULL;
    if (!bind_afalg(ret)) {
        ENGINE_free(ret);
        return NULL;
    }
    return ret;
}

798
void engine_load_afalg_int(void)
C
clucey 已提交
799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826
{
    ENGINE *toadd;

    if (!afalg_chk_platform())
        return;

    toadd = engine_afalg();
    if (toadd == NULL)
        return;
    ENGINE_add(toadd);
    ENGINE_free(toadd);
    ERR_clear_error();
}
# endif

static int afalg_init(ENGINE *e)
{
    return 1;
}

static int afalg_finish(ENGINE *e)
{
    return 1;
}

static int afalg_destroy(ENGINE *e)
{
    ERR_unload_AFALG_strings();
827 828
    EVP_CIPHER_meth_free(_hidden_aes_128_cbc);
    _hidden_aes_128_cbc = NULL;
C
clucey 已提交
829 830 831 832
    return 1;
}

#endif                          /* KERNEL VERSION */