Coverage Report

Created: 2025-12-31 06:58

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