Coverage Report

Created: 2023-09-24 16:05

/src/openssl/engines/e_afalg.c
Line
Count
Source (jump to first uncovered line)
1
/*
2
 * Copyright 2016-2018 The OpenSSL Project Authors. All Rights Reserved.
3
 *
4
 * Licensed under the Apache License 2.0 (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
8
 */
9
10
/* Required for vmsplice */
11
#ifndef _GNU_SOURCE
12
# define _GNU_SOURCE
13
#endif
14
#include <stdio.h>
15
#include <string.h>
16
#include <unistd.h>
17
18
#include <openssl/engine.h>
19
#include <openssl/async.h>
20
#include <openssl/err.h>
21
#include "internal/nelem.h"
22
23
#include <sys/socket.h>
24
#include <linux/version.h>
25
#define K_MAJ   4
26
#define K_MIN1  1
27
#define K_MIN2  0
28
#if LINUX_VERSION_CODE < KERNEL_VERSION(K_MAJ, K_MIN1, K_MIN2) || \
29
    !defined(AF_ALG)
30
# ifndef PEDANTIC
31
#  warning "AFALG ENGINE requires Kernel Headers >= 4.1.0"
32
#  warning "Skipping Compilation of AFALG engine"
33
# endif
34
void engine_load_afalg_int(void);
35
void engine_load_afalg_int(void)
36
{
37
}
38
#else
39
40
# include <linux/if_alg.h>
41
# include <fcntl.h>
42
# include <sys/utsname.h>
43
44
# include <linux/aio_abi.h>
45
# include <sys/syscall.h>
46
# include <errno.h>
47
48
# include "e_afalg.h"
49
# include "e_afalg_err.c"
50
51
# ifndef SOL_ALG
52
#  define SOL_ALG 279
53
# endif
54
55
# ifdef ALG_ZERO_COPY
56
#  ifndef SPLICE_F_GIFT
57
#   define SPLICE_F_GIFT    (0x08)
58
#  endif
59
# endif
60
61
0
# define ALG_AES_IV_LEN 16
62
# define ALG_IV_LEN(len) (sizeof(struct af_alg_iv) + (len))
63
# define ALG_OP_TYPE     unsigned int
64
0
# define ALG_OP_LEN      (sizeof(ALG_OP_TYPE))
65
66
# ifdef OPENSSL_NO_DYNAMIC_ENGINE
67
void engine_load_afalg_int(void);
68
# endif
69
70
/* Local Linkage Functions */
71
static int afalg_init_aio(afalg_aio *aio);
72
static int afalg_fin_cipher_aio(afalg_aio *ptr, int sfd,
73
                                unsigned char *buf, size_t len);
74
static int afalg_create_sk(afalg_ctx *actx, const char *ciphertype,
75
                                const char *ciphername);
76
static int afalg_destroy(ENGINE *e);
77
static int afalg_init(ENGINE *e);
78
static int afalg_finish(ENGINE *e);
79
static const EVP_CIPHER *afalg_aes_cbc(int nid);
80
static cbc_handles *get_cipher_handle(int nid);
81
static int afalg_ciphers(ENGINE *e, const EVP_CIPHER **cipher,
82
                         const int **nids, int nid);
83
static int afalg_cipher_init(EVP_CIPHER_CTX *ctx, const unsigned char *key,
84
                             const unsigned char *iv, int enc);
85
static int afalg_do_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
86
                           const unsigned char *in, size_t inl);
87
static int afalg_cipher_cleanup(EVP_CIPHER_CTX *ctx);
88
static int afalg_chk_platform(void);
89
90
/* Engine Id and Name */
91
static const char *engine_afalg_id = "afalg";
92
static const char *engine_afalg_name = "AFALG engine support";
93
94
static int afalg_cipher_nids[] = {
95
    NID_aes_128_cbc,
96
    NID_aes_192_cbc,
97
    NID_aes_256_cbc,
98
};
99
100
static cbc_handles cbc_handle[] = {{AES_KEY_SIZE_128, NULL},
101
                                    {AES_KEY_SIZE_192, NULL},
102
                                    {AES_KEY_SIZE_256, NULL}};
103
104
static ossl_inline int io_setup(unsigned n, aio_context_t *ctx)
105
0
{
106
0
    return syscall(__NR_io_setup, n, ctx);
107
0
}
108
109
static ossl_inline int eventfd(int n)
110
0
{
111
0
    return syscall(__NR_eventfd2, n, 0);
112
0
}
113
114
static ossl_inline int io_destroy(aio_context_t ctx)
115
0
{
116
0
    return syscall(__NR_io_destroy, ctx);
117
0
}
118
119
static ossl_inline int io_read(aio_context_t ctx, long n, struct iocb **iocb)
120
0
{
121
0
    return syscall(__NR_io_submit, ctx, n, iocb);
122
0
}
123
124
static ossl_inline int io_getevents(aio_context_t ctx, long min, long max,
125
                               struct io_event *events,
126
                               struct timespec *timeout)
127
0
{
128
0
#if defined(__NR_io_getevents)
129
0
    return syscall(__NR_io_getevents, ctx, min, max, events, timeout);
130
#elif defined(__NR_io_pgetevents_time64)
131
    /* Let's only support the 64 suffix syscalls for 64-bit time_t.
132
     * This simplifies the code for us as we don't need to use a 64-bit
133
     * version of timespec with a 32-bit time_t and handle converting
134
     * between 64-bit and 32-bit times and check for overflows.
135
     */
136
    if (sizeof(timeout->tv_sec) == 8)
137
        return syscall(__NR_io_pgetevents_time64, ctx, min, max, events, timeout, NULL);
138
    else {
139
        errno = ENOSYS;
140
        return -1;
141
    }
142
#else
143
# error "We require either the io_getevents syscall or __NR_io_pgetevents_time64."
144
#endif
145
0
}
146
147
static void afalg_waitfd_cleanup(ASYNC_WAIT_CTX *ctx, const void *key,
148
                                 OSSL_ASYNC_FD waitfd, void *custom)
149
0
{
150
0
    close(waitfd);
151
0
}
152
153
static int afalg_setup_async_event_notification(afalg_aio *aio)
154
0
{
155
0
    ASYNC_JOB *job;
156
0
    ASYNC_WAIT_CTX *waitctx;
157
0
    void *custom = NULL;
158
0
    int ret;
159
160
0
    if ((job = ASYNC_get_current_job()) != NULL) {
161
        /* Async mode */
162
0
        waitctx = ASYNC_get_wait_ctx(job);
163
0
        if (waitctx == NULL) {
164
0
            ALG_WARN("%s(%d): ASYNC_get_wait_ctx error", __FILE__, __LINE__);
165
0
            return 0;
166
0
        }
167
        /* Get waitfd from ASYNC_WAIT_CTX if it is already set */
168
0
        ret = ASYNC_WAIT_CTX_get_fd(waitctx, engine_afalg_id,
169
0
                                    &aio->efd, &custom);
170
0
        if (ret == 0) {
171
            /*
172
             * waitfd is not set in ASYNC_WAIT_CTX, create a new one
173
             * and set it. efd will be signaled when AIO operation completes
174
             */
175
0
            aio->efd = eventfd(0);
176
0
            if (aio->efd == -1) {
177
0
                ALG_PERR("%s(%d): Failed to get eventfd : ", __FILE__,
178
0
                         __LINE__);
179
0
                AFALGerr(AFALG_F_AFALG_SETUP_ASYNC_EVENT_NOTIFICATION,
180
0
                         AFALG_R_EVENTFD_FAILED);
181
0
                return 0;
182
0
            }
183
0
            ret = ASYNC_WAIT_CTX_set_wait_fd(waitctx, engine_afalg_id,
184
0
                                             aio->efd, custom,
185
0
                                             afalg_waitfd_cleanup);
186
0
            if (ret == 0) {
187
0
                ALG_WARN("%s(%d): Failed to set wait fd", __FILE__, __LINE__);
188
0
                close(aio->efd);
189
0
                return 0;
190
0
            }
191
            /* make fd non-blocking in async mode */
192
0
            if (fcntl(aio->efd, F_SETFL, O_NONBLOCK) != 0) {
193
0
                ALG_WARN("%s(%d): Failed to set event fd as NONBLOCKING",
194
0
                         __FILE__, __LINE__);
195
0
            }
196
0
        }
197
0
        aio->mode = MODE_ASYNC;
198
0
    } else {
199
        /* Sync mode */
200
0
        aio->efd = eventfd(0);
201
0
        if (aio->efd == -1) {
202
0
            ALG_PERR("%s(%d): Failed to get eventfd : ", __FILE__, __LINE__);
203
0
            AFALGerr(AFALG_F_AFALG_SETUP_ASYNC_EVENT_NOTIFICATION,
204
0
                     AFALG_R_EVENTFD_FAILED);
205
0
            return 0;
206
0
        }
207
0
        aio->mode = MODE_SYNC;
208
0
    }
209
0
    return 1;
210
0
}
211
212
static int afalg_init_aio(afalg_aio *aio)
213
0
{
214
0
    int r = -1;
215
216
    /* Initialise for AIO */
217
0
    aio->aio_ctx = 0;
218
0
    r = io_setup(MAX_INFLIGHTS, &aio->aio_ctx);
219
0
    if (r < 0) {
220
0
        ALG_PERR("%s(%d): io_setup error : ", __FILE__, __LINE__);
221
0
        AFALGerr(AFALG_F_AFALG_INIT_AIO, AFALG_R_IO_SETUP_FAILED);
222
0
        return 0;
223
0
    }
224
225
0
    memset(aio->cbt, 0, sizeof(aio->cbt));
226
0
    aio->efd = -1;
227
0
    aio->mode = MODE_UNINIT;
228
229
0
    return 1;
230
0
}
231
232
static int afalg_fin_cipher_aio(afalg_aio *aio, int sfd, unsigned char *buf,
233
                                size_t len)
234
0
{
235
0
    int r;
236
0
    int retry = 0;
237
0
    unsigned int done = 0;
238
0
    struct iocb *cb;
239
0
    struct timespec timeout;
240
0
    struct io_event events[MAX_INFLIGHTS];
241
0
    u_int64_t eval = 0;
242
243
0
    timeout.tv_sec = 0;
244
0
    timeout.tv_nsec = 0;
245
246
    /* if efd has not been initialised yet do it here */
247
0
    if (aio->mode == MODE_UNINIT) {
248
0
        r = afalg_setup_async_event_notification(aio);
249
0
        if (r == 0)
250
0
            return 0;
251
0
    }
252
253
0
    cb = &(aio->cbt[0 % MAX_INFLIGHTS]);
254
0
    memset(cb, '\0', sizeof(*cb));
255
0
    cb->aio_fildes = sfd;
256
0
    cb->aio_lio_opcode = IOCB_CMD_PREAD;
257
    /*
258
     * The pointer has to be converted to unsigned value first to avoid
259
     * sign extension on cast to 64 bit value in 32-bit builds
260
     */
261
0
    cb->aio_buf = (size_t)buf;
262
0
    cb->aio_offset = 0;
263
0
    cb->aio_data = 0;
264
0
    cb->aio_nbytes = len;
265
0
    cb->aio_flags = IOCB_FLAG_RESFD;
266
0
    cb->aio_resfd = aio->efd;
267
268
    /*
269
     * Perform AIO read on AFALG socket, this in turn performs an async
270
     * crypto operation in kernel space
271
     */
272
0
    r = io_read(aio->aio_ctx, 1, &cb);
273
0
    if (r < 0) {
274
0
        ALG_PWARN("%s(%d): io_read failed : ", __FILE__, __LINE__);
275
0
        return 0;
276
0
    }
277
278
0
    do {
279
        /* While AIO read is being performed pause job */
280
0
        ASYNC_pause_job();
281
282
        /* Check for completion of AIO read */
283
0
        r = read(aio->efd, &eval, sizeof(eval));
284
0
        if (r < 0) {
285
0
            if (errno == EAGAIN || errno == EWOULDBLOCK)
286
0
                continue;
287
0
            ALG_PERR("%s(%d): read failed for event fd : ", __FILE__, __LINE__);
288
0
            return 0;
289
0
        } else if (r == 0 || eval <= 0) {
290
0
            ALG_WARN("%s(%d): eventfd read %d bytes, eval = %lu\n", __FILE__,
291
0
                     __LINE__, r, eval);
292
0
        }
293
0
        if (eval > 0) {
294
295
            /* Get results of AIO read */
296
0
            r = io_getevents(aio->aio_ctx, 1, MAX_INFLIGHTS,
297
0
                             events, &timeout);
298
0
            if (r > 0) {
299
                /*
300
                 * events.res indicates the actual status of the operation.
301
                 * Handle the error condition first.
302
                 */
303
0
                if (events[0].res < 0) {
304
                    /*
305
                     * Underlying operation cannot be completed at the time
306
                     * of previous submission. Resubmit for the operation.
307
                     */
308
0
                    if (events[0].res == -EBUSY && retry++ < 3) {
309
0
                        r = io_read(aio->aio_ctx, 1, &cb);
310
0
                        if (r < 0) {
311
0
                            ALG_PERR("%s(%d): retry %d for io_read failed : ",
312
0
                                     __FILE__, __LINE__, retry);
313
0
                            return 0;
314
0
                        }
315
0
                        continue;
316
0
                    } else {
317
                        /*
318
                         * Retries exceed for -EBUSY or unrecoverable error
319
                         * condition for this instance of operation.
320
                         */
321
0
                        ALG_WARN
322
0
                            ("%s(%d): Crypto Operation failed with code %lld\n",
323
0
                             __FILE__, __LINE__, events[0].res);
324
0
                        return 0;
325
0
                    }
326
0
                }
327
                /* Operation successful. */
328
0
                done = 1;
329
0
            } else if (r < 0) {
330
0
                ALG_PERR("%s(%d): io_getevents failed : ", __FILE__, __LINE__);
331
0
                return 0;
332
0
            } else {
333
0
                ALG_WARN("%s(%d): io_geteventd read 0 bytes\n", __FILE__,
334
0
                         __LINE__);
335
0
            }
336
0
        }
337
0
    } while (!done);
338
339
0
    return 1;
340
0
}
341
342
static ossl_inline void afalg_set_op_sk(struct cmsghdr *cmsg,
343
                                   const ALG_OP_TYPE op)
344
0
{
345
0
    cmsg->cmsg_level = SOL_ALG;
346
0
    cmsg->cmsg_type = ALG_SET_OP;
347
0
    cmsg->cmsg_len = CMSG_LEN(ALG_OP_LEN);
348
0
    memcpy(CMSG_DATA(cmsg), &op, ALG_OP_LEN);
349
0
}
350
351
static void afalg_set_iv_sk(struct cmsghdr *cmsg, const unsigned char *iv,
352
                            const unsigned int len)
353
0
{
354
0
    struct af_alg_iv *aiv;
355
356
0
    cmsg->cmsg_level = SOL_ALG;
357
0
    cmsg->cmsg_type = ALG_SET_IV;
358
0
    cmsg->cmsg_len = CMSG_LEN(ALG_IV_LEN(len));
359
0
    aiv = (struct af_alg_iv *)CMSG_DATA(cmsg);
360
0
    aiv->ivlen = len;
361
0
    memcpy(aiv->iv, iv, len);
362
0
}
363
364
static ossl_inline int afalg_set_key(afalg_ctx *actx, const unsigned char *key,
365
                                const int klen)
366
0
{
367
0
    int ret;
368
0
    ret = setsockopt(actx->bfd, SOL_ALG, ALG_SET_KEY, key, klen);
369
0
    if (ret < 0) {
370
0
        ALG_PERR("%s(%d): Failed to set socket option : ", __FILE__, __LINE__);
371
0
        AFALGerr(AFALG_F_AFALG_SET_KEY, AFALG_R_SOCKET_SET_KEY_FAILED);
372
0
        return 0;
373
0
    }
374
0
    return 1;
375
0
}
376
377
static int afalg_create_sk(afalg_ctx *actx, const char *ciphertype,
378
                                const char *ciphername)
379
0
{
380
0
    struct sockaddr_alg sa;
381
0
    int r = -1;
382
383
0
    actx->bfd = actx->sfd = -1;
384
385
0
    memset(&sa, 0, sizeof(sa));
386
0
    sa.salg_family = AF_ALG;
387
0
    OPENSSL_strlcpy((char *) sa.salg_type, ciphertype, sizeof(sa.salg_type));
388
0
    OPENSSL_strlcpy((char *) sa.salg_name, ciphername, sizeof(sa.salg_name));
389
390
0
    actx->bfd = socket(AF_ALG, SOCK_SEQPACKET, 0);
391
0
    if (actx->bfd == -1) {
392
0
        ALG_PERR("%s(%d): Failed to open socket : ", __FILE__, __LINE__);
393
0
        AFALGerr(AFALG_F_AFALG_CREATE_SK, AFALG_R_SOCKET_CREATE_FAILED);
394
0
        goto err;
395
0
    }
396
397
0
    r = bind(actx->bfd, (struct sockaddr *)&sa, sizeof(sa));
398
0
    if (r < 0) {
399
0
        ALG_PERR("%s(%d): Failed to bind socket : ", __FILE__, __LINE__);
400
0
        AFALGerr(AFALG_F_AFALG_CREATE_SK, AFALG_R_SOCKET_BIND_FAILED);
401
0
        goto err;
402
0
    }
403
404
0
    actx->sfd = accept(actx->bfd, NULL, 0);
405
0
    if (actx->sfd < 0) {
406
0
        ALG_PERR("%s(%d): Socket Accept Failed : ", __FILE__, __LINE__);
407
0
        AFALGerr(AFALG_F_AFALG_CREATE_SK, AFALG_R_SOCKET_ACCEPT_FAILED);
408
0
        goto err;
409
0
    }
410
411
0
    return 1;
412
413
0
 err:
414
0
    if (actx->bfd >= 0)
415
0
        close(actx->bfd);
416
0
    if (actx->sfd >= 0)
417
0
        close(actx->sfd);
418
0
    actx->bfd = actx->sfd = -1;
419
0
    return 0;
420
0
}
421
422
static int afalg_start_cipher_sk(afalg_ctx *actx, const unsigned char *in,
423
                                 size_t inl, const unsigned char *iv,
424
                                 unsigned int enc)
425
0
{
426
0
    struct msghdr msg;
427
0
    struct cmsghdr *cmsg;
428
0
    struct iovec iov;
429
0
    ssize_t sbytes;
430
# ifdef ALG_ZERO_COPY
431
    int ret;
432
# endif
433
0
    char cbuf[CMSG_SPACE(ALG_IV_LEN(ALG_AES_IV_LEN)) + CMSG_SPACE(ALG_OP_LEN)];
434
435
0
    memset(&msg, 0, sizeof(msg));
436
0
    memset(cbuf, 0, sizeof(cbuf));
437
0
    msg.msg_control = cbuf;
438
0
    msg.msg_controllen = sizeof(cbuf);
439
440
    /*
441
     * cipher direction (i.e. encrypt or decrypt) and iv are sent to the
442
     * kernel as part of sendmsg()'s ancillary data
443
     */
444
0
    cmsg = CMSG_FIRSTHDR(&msg);
445
0
    afalg_set_op_sk(cmsg, enc);
446
0
    cmsg = CMSG_NXTHDR(&msg, cmsg);
447
0
    afalg_set_iv_sk(cmsg, iv, ALG_AES_IV_LEN);
448
449
    /* iov that describes input data */
450
0
    iov.iov_base = (unsigned char *)in;
451
0
    iov.iov_len = inl;
452
453
0
    msg.msg_flags = MSG_MORE;
454
455
# ifdef ALG_ZERO_COPY
456
    /*
457
     * ZERO_COPY mode
458
     * Works best when buffer is 4k aligned
459
     * OPENS: out of place processing (i.e. out != in)
460
     */
461
462
    /* Input data is not sent as part of call to sendmsg() */
463
    msg.msg_iovlen = 0;
464
    msg.msg_iov = NULL;
465
466
    /* Sendmsg() sends iv and cipher direction to the kernel */
467
    sbytes = sendmsg(actx->sfd, &msg, 0);
468
    if (sbytes < 0) {
469
        ALG_PERR("%s(%d): sendmsg failed for zero copy cipher operation : ",
470
                 __FILE__, __LINE__);
471
        return 0;
472
    }
473
474
    /*
475
     * vmsplice and splice are used to pin the user space input buffer for
476
     * kernel space processing avoiding copies from user to kernel space
477
     */
478
    ret = vmsplice(actx->zc_pipe[1], &iov, 1, SPLICE_F_GIFT);
479
    if (ret < 0) {
480
        ALG_PERR("%s(%d): vmsplice failed : ", __FILE__, __LINE__);
481
        return 0;
482
    }
483
484
    ret = splice(actx->zc_pipe[0], NULL, actx->sfd, NULL, inl, 0);
485
    if (ret < 0) {
486
        ALG_PERR("%s(%d): splice failed : ", __FILE__, __LINE__);
487
        return 0;
488
    }
489
# else
490
0
    msg.msg_iovlen = 1;
491
0
    msg.msg_iov = &iov;
492
493
    /* Sendmsg() sends iv, cipher direction and input data to the kernel */
494
0
    sbytes = sendmsg(actx->sfd, &msg, 0);
495
0
    if (sbytes < 0) {
496
0
        ALG_PERR("%s(%d): sendmsg failed for cipher operation : ", __FILE__,
497
0
                 __LINE__);
498
0
        return 0;
499
0
    }
500
501
0
    if (sbytes != (ssize_t) inl) {
502
0
        ALG_WARN("Cipher operation send bytes %zd != inlen %zd\n", sbytes,
503
0
                inl);
504
0
        return 0;
505
0
    }
506
0
# endif
507
508
0
    return 1;
509
0
}
510
511
static int afalg_cipher_init(EVP_CIPHER_CTX *ctx, const unsigned char *key,
512
                             const unsigned char *iv, int enc)
513
0
{
514
0
    int ciphertype;
515
0
    int ret;
516
0
    afalg_ctx *actx;
517
0
    const char *ciphername;
518
519
0
    if (ctx == NULL || key == NULL) {
520
0
        ALG_WARN("%s(%d): Null Parameter\n", __FILE__, __LINE__);
521
0
        return 0;
522
0
    }
523
524
0
    if (EVP_CIPHER_CTX_cipher(ctx) == NULL) {
525
0
        ALG_WARN("%s(%d): Cipher object NULL\n", __FILE__, __LINE__);
526
0
        return 0;
527
0
    }
528
529
0
    actx = EVP_CIPHER_CTX_get_cipher_data(ctx);
530
0
    if (actx == NULL) {
531
0
        ALG_WARN("%s(%d): Cipher data NULL\n", __FILE__, __LINE__);
532
0
        return 0;
533
0
    }
534
535
0
    ciphertype = EVP_CIPHER_CTX_nid(ctx);
536
0
    switch (ciphertype) {
537
0
    case NID_aes_128_cbc:
538
0
    case NID_aes_192_cbc:
539
0
    case NID_aes_256_cbc:
540
0
        ciphername = "cbc(aes)";
541
0
        break;
542
0
    default:
543
0
        ALG_WARN("%s(%d): Unsupported Cipher type %d\n", __FILE__, __LINE__,
544
0
                 ciphertype);
545
0
        return 0;
546
0
    }
547
548
0
    if (ALG_AES_IV_LEN != EVP_CIPHER_CTX_iv_length(ctx)) {
549
0
        ALG_WARN("%s(%d): Unsupported IV length :%d\n", __FILE__, __LINE__,
550
0
                 EVP_CIPHER_CTX_iv_length(ctx));
551
0
        return 0;
552
0
    }
553
554
    /* Setup AFALG socket for crypto processing */
555
0
    ret = afalg_create_sk(actx, "skcipher", ciphername);
556
0
    if (ret < 1)
557
0
        return 0;
558
559
560
0
    ret = afalg_set_key(actx, key, EVP_CIPHER_CTX_key_length(ctx));
561
0
    if (ret < 1)
562
0
        goto err;
563
564
    /* Setup AIO ctx to allow async AFALG crypto processing */
565
0
    if (afalg_init_aio(&actx->aio) == 0)
566
0
        goto err;
567
568
# ifdef ALG_ZERO_COPY
569
    pipe(actx->zc_pipe);
570
# endif
571
572
0
    actx->init_done = MAGIC_INIT_NUM;
573
574
0
    return 1;
575
576
0
err:
577
0
    close(actx->sfd);
578
0
    close(actx->bfd);
579
0
    return 0;
580
0
}
581
582
static int afalg_do_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
583
                           const unsigned char *in, size_t inl)
584
0
{
585
0
    afalg_ctx *actx;
586
0
    int ret;
587
0
    char nxtiv[ALG_AES_IV_LEN] = { 0 };
588
589
0
    if (ctx == NULL || out == NULL || in == NULL) {
590
0
        ALG_WARN("NULL parameter passed to function %s(%d)\n", __FILE__,
591
0
                 __LINE__);
592
0
        return 0;
593
0
    }
594
595
0
    actx = (afalg_ctx *) EVP_CIPHER_CTX_get_cipher_data(ctx);
596
0
    if (actx == NULL || actx->init_done != MAGIC_INIT_NUM) {
597
0
        ALG_WARN("%s afalg ctx passed\n",
598
0
                 ctx == NULL ? "NULL" : "Uninitialised");
599
0
        return 0;
600
0
    }
601
602
    /*
603
     * set iv now for decrypt operation as the input buffer can be
604
     * overwritten for inplace operation where in = out.
605
     */
606
0
    if (EVP_CIPHER_CTX_encrypting(ctx) == 0) {
607
0
        memcpy(nxtiv, in + (inl - ALG_AES_IV_LEN), ALG_AES_IV_LEN);
608
0
    }
609
610
    /* Send input data to kernel space */
611
0
    ret = afalg_start_cipher_sk(actx, (unsigned char *)in, inl,
612
0
                                EVP_CIPHER_CTX_iv(ctx),
613
0
                                EVP_CIPHER_CTX_encrypting(ctx));
614
0
    if (ret < 1) {
615
0
        return 0;
616
0
    }
617
618
    /* Perform async crypto operation in kernel space */
619
0
    ret = afalg_fin_cipher_aio(&actx->aio, actx->sfd, out, inl);
620
0
    if (ret < 1)
621
0
        return 0;
622
623
0
    if (EVP_CIPHER_CTX_encrypting(ctx)) {
624
0
        memcpy(EVP_CIPHER_CTX_iv_noconst(ctx), out + (inl - ALG_AES_IV_LEN),
625
0
               ALG_AES_IV_LEN);
626
0
    } else {
627
0
        memcpy(EVP_CIPHER_CTX_iv_noconst(ctx), nxtiv, ALG_AES_IV_LEN);
628
0
    }
629
630
0
    return 1;
631
0
}
632
633
static int afalg_cipher_cleanup(EVP_CIPHER_CTX *ctx)
634
0
{
635
0
    afalg_ctx *actx;
636
637
0
    if (ctx == NULL) {
638
0
        ALG_WARN("NULL parameter passed to function %s(%d)\n", __FILE__,
639
0
                 __LINE__);
640
0
        return 0;
641
0
    }
642
643
0
    actx = (afalg_ctx *) EVP_CIPHER_CTX_get_cipher_data(ctx);
644
0
    if (actx == NULL || actx->init_done != MAGIC_INIT_NUM) {
645
0
        ALG_WARN("%s afalg ctx passed\n",
646
0
                 ctx == NULL ? "NULL" : "Uninitialised");
647
0
        return 0;
648
0
    }
649
650
0
    close(actx->sfd);
651
0
    close(actx->bfd);
652
# ifdef ALG_ZERO_COPY
653
    close(actx->zc_pipe[0]);
654
    close(actx->zc_pipe[1]);
655
# endif
656
    /* close efd in sync mode, async mode is closed in afalg_waitfd_cleanup() */
657
0
    if (actx->aio.mode == MODE_SYNC)
658
0
        close(actx->aio.efd);
659
0
    io_destroy(actx->aio.aio_ctx);
660
661
0
    return 1;
662
0
}
663
664
static cbc_handles *get_cipher_handle(int nid)
665
0
{
666
0
    switch (nid) {
667
0
    case NID_aes_128_cbc:
668
0
        return &cbc_handle[AES_CBC_128];
669
0
    case NID_aes_192_cbc:
670
0
        return &cbc_handle[AES_CBC_192];
671
0
    case NID_aes_256_cbc:
672
0
        return &cbc_handle[AES_CBC_256];
673
0
    default:
674
0
        return NULL;
675
0
    }
676
0
}
677
678
static const EVP_CIPHER *afalg_aes_cbc(int nid)
679
0
{
680
0
    cbc_handles *cipher_handle = get_cipher_handle(nid);
681
0
    if (cipher_handle->_hidden == NULL
682
0
        && ((cipher_handle->_hidden =
683
0
         EVP_CIPHER_meth_new(nid,
684
0
                             AES_BLOCK_SIZE,
685
0
                             cipher_handle->key_size)) == NULL
686
0
        || !EVP_CIPHER_meth_set_iv_length(cipher_handle->_hidden,
687
0
                                          AES_IV_LEN)
688
0
        || !EVP_CIPHER_meth_set_flags(cipher_handle->_hidden,
689
0
                                      EVP_CIPH_CBC_MODE |
690
0
                                      EVP_CIPH_FLAG_DEFAULT_ASN1)
691
0
        || !EVP_CIPHER_meth_set_init(cipher_handle->_hidden,
692
0
                                     afalg_cipher_init)
693
0
        || !EVP_CIPHER_meth_set_do_cipher(cipher_handle->_hidden,
694
0
                                          afalg_do_cipher)
695
0
        || !EVP_CIPHER_meth_set_cleanup(cipher_handle->_hidden,
696
0
                                        afalg_cipher_cleanup)
697
0
        || !EVP_CIPHER_meth_set_impl_ctx_size(cipher_handle->_hidden,
698
0
                                              sizeof(afalg_ctx)))) {
699
0
        EVP_CIPHER_meth_free(cipher_handle->_hidden);
700
0
        cipher_handle->_hidden= NULL;
701
0
    }
702
0
    return cipher_handle->_hidden;
703
0
}
704
705
static int afalg_ciphers(ENGINE *e, const EVP_CIPHER **cipher,
706
                         const int **nids, int nid)
707
0
{
708
0
    int r = 1;
709
710
0
    if (cipher == NULL) {
711
0
        *nids = afalg_cipher_nids;
712
0
        return (sizeof(afalg_cipher_nids) / sizeof(afalg_cipher_nids[0]));
713
0
    }
714
715
0
    switch (nid) {
716
0
    case NID_aes_128_cbc:
717
0
    case NID_aes_192_cbc:
718
0
    case NID_aes_256_cbc:
719
0
        *cipher = afalg_aes_cbc(nid);
720
0
        break;
721
0
    default:
722
0
        *cipher = NULL;
723
0
        r = 0;
724
0
    }
725
0
    return r;
726
0
}
727
728
static int bind_afalg(ENGINE *e)
729
0
{
730
    /* Ensure the afalg error handling is set up */
731
0
    unsigned short i;
732
0
    ERR_load_AFALG_strings();
733
734
0
    if (!ENGINE_set_id(e, engine_afalg_id)
735
0
        || !ENGINE_set_name(e, engine_afalg_name)
736
0
        || !ENGINE_set_destroy_function(e, afalg_destroy)
737
0
        || !ENGINE_set_init_function(e, afalg_init)
738
0
        || !ENGINE_set_finish_function(e, afalg_finish)) {
739
0
        AFALGerr(AFALG_F_BIND_AFALG, AFALG_R_INIT_FAILED);
740
0
        return 0;
741
0
    }
742
743
    /*
744
     * Create _hidden_aes_xxx_cbc by calling afalg_aes_xxx_cbc
745
     * now, as bind_aflag can only be called by one thread at a
746
     * time.
747
     */
748
0
    for(i = 0; i < OSSL_NELEM(afalg_cipher_nids); i++) {
749
0
        if (afalg_aes_cbc(afalg_cipher_nids[i]) == NULL) {
750
0
            AFALGerr(AFALG_F_BIND_AFALG, AFALG_R_INIT_FAILED);
751
0
            return 0;
752
0
        }
753
0
    }
754
755
0
    if (!ENGINE_set_ciphers(e, afalg_ciphers)) {
756
0
        AFALGerr(AFALG_F_BIND_AFALG, AFALG_R_INIT_FAILED);
757
0
        return 0;
758
0
    }
759
760
0
    return 1;
761
0
}
762
763
# ifndef OPENSSL_NO_DYNAMIC_ENGINE
764
static int bind_helper(ENGINE *e, const char *id)
765
{
766
    if (id && (strcmp(id, engine_afalg_id) != 0))
767
        return 0;
768
769
    if (!afalg_chk_platform())
770
        return 0;
771
772
    if (!bind_afalg(e))
773
        return 0;
774
    return 1;
775
}
776
777
IMPLEMENT_DYNAMIC_CHECK_FN()
778
    IMPLEMENT_DYNAMIC_BIND_FN(bind_helper)
779
# endif
780
781
static int afalg_chk_platform(void)
782
0
{
783
0
    int ret;
784
0
    int i;
785
0
    int kver[3] = { -1, -1, -1 };
786
0
    int sock;
787
0
    char *str;
788
0
    struct utsname ut;
789
790
0
    ret = uname(&ut);
791
0
    if (ret != 0) {
792
0
        AFALGerr(AFALG_F_AFALG_CHK_PLATFORM,
793
0
                 AFALG_R_FAILED_TO_GET_PLATFORM_INFO);
794
0
        return 0;
795
0
    }
796
797
0
    str = strtok(ut.release, ".");
798
0
    for (i = 0; i < 3 && str != NULL; i++) {
799
0
        kver[i] = atoi(str);
800
0
        str = strtok(NULL, ".");
801
0
    }
802
803
0
    if (KERNEL_VERSION(kver[0], kver[1], kver[2])
804
0
        < KERNEL_VERSION(K_MAJ, K_MIN1, K_MIN2)) {
805
0
        ALG_ERR("ASYNC AFALG not supported this kernel(%d.%d.%d)\n",
806
0
                 kver[0], kver[1], kver[2]);
807
0
        ALG_ERR("ASYNC AFALG requires kernel version %d.%d.%d or later\n",
808
0
                 K_MAJ, K_MIN1, K_MIN2);
809
0
        AFALGerr(AFALG_F_AFALG_CHK_PLATFORM,
810
0
                 AFALG_R_KERNEL_DOES_NOT_SUPPORT_ASYNC_AFALG);
811
0
        return 0;
812
0
    }
813
814
    /* Test if we can actually create an AF_ALG socket */
815
0
    sock = socket(AF_ALG, SOCK_SEQPACKET, 0);
816
0
    if (sock == -1) {
817
0
        AFALGerr(AFALG_F_AFALG_CHK_PLATFORM, AFALG_R_SOCKET_CREATE_FAILED);
818
0
        return 0;
819
0
    }
820
0
    close(sock);
821
822
0
    return 1;
823
0
}
824
825
# ifdef OPENSSL_NO_DYNAMIC_ENGINE
826
static ENGINE *engine_afalg(void)
827
0
{
828
0
    ENGINE *ret = ENGINE_new();
829
0
    if (ret == NULL)
830
0
        return NULL;
831
0
    if (!bind_afalg(ret)) {
832
0
        ENGINE_free(ret);
833
0
        return NULL;
834
0
    }
835
0
    return ret;
836
0
}
837
838
void engine_load_afalg_int(void)
839
0
{
840
0
    ENGINE *toadd;
841
842
0
    if (!afalg_chk_platform())
843
0
        return;
844
845
0
    toadd = engine_afalg();
846
0
    if (toadd == NULL)
847
0
        return;
848
0
    ENGINE_add(toadd);
849
0
    ENGINE_free(toadd);
850
0
    ERR_clear_error();
851
0
}
852
# endif
853
854
static int afalg_init(ENGINE *e)
855
0
{
856
0
    return 1;
857
0
}
858
859
static int afalg_finish(ENGINE *e)
860
0
{
861
0
    return 1;
862
0
}
863
864
static int free_cbc(void)
865
0
{
866
0
    short unsigned int i;
867
0
    for(i = 0; i < OSSL_NELEM(afalg_cipher_nids); i++) {
868
0
        EVP_CIPHER_meth_free(cbc_handle[i]._hidden);
869
0
        cbc_handle[i]._hidden = NULL;
870
0
    }
871
0
    return 1;
872
0
}
873
874
static int afalg_destroy(ENGINE *e)
875
0
{
876
0
    ERR_unload_AFALG_strings();
877
0
    free_cbc();
878
0
    return 1;
879
0
}
880
881
#endif                          /* KERNEL VERSION */