Coverage Report

Created: 2020-08-14 21:15

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