s390x: fix ecx derive
[openssl.git] / engines / e_dasync.c
1 /*
2  * Copyright 2015-2021 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 engine deprecated APIs */
11 #define OPENSSL_SUPPRESS_DEPRECATED
12
13 /*
14  * SHA-1 low level APIs are deprecated for public use, but still ok for
15  * internal use.  Note, that due to symbols not being exported, only the
16  * #defines and strucures can be accessed, in this case SHA_CBLOCK and
17  * sizeof(SHA_CTX).
18  */
19 #include "internal/deprecated.h"
20
21 #include <openssl/opensslconf.h>
22 #if defined(_WIN32)
23 # include <windows.h>
24 #endif
25
26 #include <stdio.h>
27 #include <string.h>
28
29 #include <openssl/engine.h>
30 #include <openssl/sha.h>
31 #include <openssl/aes.h>
32 #include <openssl/rsa.h>
33 #include <openssl/evp.h>
34 #include <openssl/async.h>
35 #include <openssl/bn.h>
36 #include <openssl/crypto.h>
37 #include <openssl/ssl.h>
38 #include <openssl/modes.h>
39
40 #if defined(OPENSSL_SYS_UNIX) && defined(OPENSSL_THREADS)
41 # undef ASYNC_POSIX
42 # define ASYNC_POSIX
43 # include <unistd.h>
44 #elif defined(_WIN32)
45 # undef ASYNC_WIN
46 # define ASYNC_WIN
47 #endif
48
49 #include "e_dasync_err.c"
50
51 /* Engine Id and Name */
52 static const char *engine_dasync_id = "dasync";
53 static const char *engine_dasync_name = "Dummy Async engine support";
54
55
56 /* Engine Lifetime functions */
57 static int dasync_destroy(ENGINE *e);
58 static int dasync_init(ENGINE *e);
59 static int dasync_finish(ENGINE *e);
60 void engine_load_dasync_int(void);
61
62
63 /* Set up digests. Just SHA1 for now */
64 static int dasync_digests(ENGINE *e, const EVP_MD **digest,
65                           const int **nids, int nid);
66
67 static void dummy_pause_job(void);
68
69 /* SHA1 */
70 static int dasync_sha1_init(EVP_MD_CTX *ctx);
71 static int dasync_sha1_update(EVP_MD_CTX *ctx, const void *data,
72                              size_t count);
73 static int dasync_sha1_final(EVP_MD_CTX *ctx, unsigned char *md);
74
75 /*
76  * Holds the EVP_MD object for sha1 in this engine. Set up once only during
77  * engine bind and can then be reused many times.
78  */
79 static EVP_MD *_hidden_sha1_md = NULL;
80 static const EVP_MD *dasync_sha1(void)
81 {
82     return _hidden_sha1_md;
83 }
84 static void destroy_digests(void)
85 {
86     EVP_MD_meth_free(_hidden_sha1_md);
87     _hidden_sha1_md = NULL;
88 }
89
90 static int dasync_digest_nids(const int **nids)
91 {
92     static int digest_nids[2] = { 0, 0 };
93     static int pos = 0;
94     static int init = 0;
95
96     if (!init) {
97         const EVP_MD *md;
98         if ((md = dasync_sha1()) != NULL)
99             digest_nids[pos++] = EVP_MD_get_type(md);
100         digest_nids[pos] = 0;
101         init = 1;
102     }
103     *nids = digest_nids;
104     return pos;
105 }
106
107 /* RSA */
108 static int dasync_pkey(ENGINE *e, EVP_PKEY_METHOD **pmeth,
109                        const int **pnids, int nid);
110
111 static int dasync_rsa_init(EVP_PKEY_CTX *ctx);
112 static void dasync_rsa_cleanup(EVP_PKEY_CTX *ctx);
113 static int dasync_rsa_paramgen_init(EVP_PKEY_CTX *ctx);
114 static int dasync_rsa_paramgen(EVP_PKEY_CTX *ctx, EVP_PKEY *pkey);
115 static int dasync_rsa_keygen_init(EVP_PKEY_CTX *ctx);
116 static int dasync_rsa_keygen(EVP_PKEY_CTX *ctx, EVP_PKEY *pkey);
117 static int dasync_rsa_encrypt_init(EVP_PKEY_CTX *ctx);
118 static int dasync_rsa_encrypt(EVP_PKEY_CTX *ctx, unsigned char *out,
119                               size_t *outlen, const unsigned char *in,
120                               size_t inlen);
121 static int dasync_rsa_decrypt_init(EVP_PKEY_CTX *ctx);
122 static int dasync_rsa_decrypt(EVP_PKEY_CTX *ctx, unsigned char *out,
123                               size_t *outlen, const unsigned char *in,
124                               size_t inlen);
125 static int dasync_rsa_ctrl(EVP_PKEY_CTX *ctx, int type, int p1, void *p2);
126 static int dasync_rsa_ctrl_str(EVP_PKEY_CTX *ctx, const char *type,
127                                const char *value);
128
129 static EVP_PKEY_METHOD *dasync_rsa;
130 static const EVP_PKEY_METHOD *dasync_rsa_orig;
131
132 /* AES */
133
134 static int dasync_aes128_cbc_ctrl(EVP_CIPHER_CTX *ctx, int type, int arg,
135                                   void *ptr);
136 static int dasync_aes128_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *key,
137                                   const unsigned char *iv, int enc);
138 static int dasync_aes128_cbc_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
139                                     const unsigned char *in, size_t inl);
140 static int dasync_aes128_cbc_cleanup(EVP_CIPHER_CTX *ctx);
141
142 static int dasync_aes128_cbc_hmac_sha1_ctrl(EVP_CIPHER_CTX *ctx, int type,
143                                              int arg, void *ptr);
144 static int dasync_aes128_cbc_hmac_sha1_init_key(EVP_CIPHER_CTX *ctx,
145                                                  const unsigned char *key,
146                                                  const unsigned char *iv,
147                                                  int enc);
148 static int dasync_aes128_cbc_hmac_sha1_cipher(EVP_CIPHER_CTX *ctx,
149                                                unsigned char *out,
150                                                const unsigned char *in,
151                                                size_t inl);
152 static int dasync_aes128_cbc_hmac_sha1_cleanup(EVP_CIPHER_CTX *ctx);
153
154 struct dasync_pipeline_ctx {
155     void *inner_cipher_data;
156     unsigned int numpipes;
157     unsigned char **inbufs;
158     unsigned char **outbufs;
159     size_t *lens;
160     unsigned char tlsaad[SSL_MAX_PIPELINES][EVP_AEAD_TLS1_AAD_LEN];
161     unsigned int aadctr;
162 };
163
164 /*
165  * Holds the EVP_CIPHER object for aes_128_cbc in this engine. Set up once only
166  * during engine bind and can then be reused many times.
167  */
168 static EVP_CIPHER *_hidden_aes_128_cbc = NULL;
169 static const EVP_CIPHER *dasync_aes_128_cbc(void)
170 {
171     return _hidden_aes_128_cbc;
172 }
173
174 /*
175  * Holds the EVP_CIPHER object for aes_128_cbc_hmac_sha1 in this engine. Set up
176  * once only during engine bind and can then be reused many times.
177  *
178  * This 'stitched' cipher depends on the EVP_aes_128_cbc_hmac_sha1() cipher,
179  * which is implemented only if the AES-NI instruction set extension is available
180  * (see OPENSSL_IA32CAP(3)). If that's not the case, then this cipher will not
181  * be available either.
182  *
183  * Note: Since it is a legacy mac-then-encrypt cipher, modern TLS peers (which
184  * negotiate the encrypt-then-mac extension) won't negotiate it anyway.
185  */
186 static EVP_CIPHER *_hidden_aes_128_cbc_hmac_sha1 = NULL;
187 static const EVP_CIPHER *dasync_aes_128_cbc_hmac_sha1(void)
188 {
189     return _hidden_aes_128_cbc_hmac_sha1;
190 }
191
192 static void destroy_ciphers(void)
193 {
194     EVP_CIPHER_meth_free(_hidden_aes_128_cbc);
195     EVP_CIPHER_meth_free(_hidden_aes_128_cbc_hmac_sha1);
196     _hidden_aes_128_cbc = NULL;
197     _hidden_aes_128_cbc_hmac_sha1 = NULL;
198 }
199
200 static int dasync_ciphers(ENGINE *e, const EVP_CIPHER **cipher,
201                                    const int **nids, int nid);
202
203 static int dasync_cipher_nids[] = {
204     NID_aes_128_cbc,
205     NID_aes_128_cbc_hmac_sha1,
206     0
207 };
208
209 static int bind_dasync(ENGINE *e)
210 {
211     /* Setup RSA */
212     ;
213     if ((dasync_rsa_orig = EVP_PKEY_meth_find(EVP_PKEY_RSA)) == NULL
214         || (dasync_rsa = EVP_PKEY_meth_new(EVP_PKEY_RSA,
215                                            EVP_PKEY_FLAG_AUTOARGLEN)) == NULL)
216         return 0;
217     EVP_PKEY_meth_set_init(dasync_rsa, dasync_rsa_init);
218     EVP_PKEY_meth_set_cleanup(dasync_rsa, dasync_rsa_cleanup);
219     EVP_PKEY_meth_set_paramgen(dasync_rsa, dasync_rsa_paramgen_init,
220                                dasync_rsa_paramgen);
221     EVP_PKEY_meth_set_keygen(dasync_rsa, dasync_rsa_keygen_init,
222                              dasync_rsa_keygen);
223     EVP_PKEY_meth_set_encrypt(dasync_rsa, dasync_rsa_encrypt_init,
224                               dasync_rsa_encrypt);
225     EVP_PKEY_meth_set_decrypt(dasync_rsa, dasync_rsa_decrypt_init,
226                               dasync_rsa_decrypt);
227     EVP_PKEY_meth_set_ctrl(dasync_rsa, dasync_rsa_ctrl,
228                            dasync_rsa_ctrl_str);
229
230     /* Ensure the dasync error handling is set up */
231     ERR_load_DASYNC_strings();
232
233     if (!ENGINE_set_id(e, engine_dasync_id)
234         || !ENGINE_set_name(e, engine_dasync_name)
235         || !ENGINE_set_pkey_meths(e, dasync_pkey)
236         || !ENGINE_set_digests(e, dasync_digests)
237         || !ENGINE_set_ciphers(e, dasync_ciphers)
238         || !ENGINE_set_destroy_function(e, dasync_destroy)
239         || !ENGINE_set_init_function(e, dasync_init)
240         || !ENGINE_set_finish_function(e, dasync_finish)) {
241         DASYNCerr(DASYNC_F_BIND_DASYNC, DASYNC_R_INIT_FAILED);
242         return 0;
243     }
244
245     /*
246      * Set up the EVP_CIPHER and EVP_MD objects for the ciphers/digests
247      * supplied by this engine
248      */
249     _hidden_sha1_md = EVP_MD_meth_new(NID_sha1, NID_sha1WithRSAEncryption);
250     if (_hidden_sha1_md == NULL
251         || !EVP_MD_meth_set_result_size(_hidden_sha1_md, SHA_DIGEST_LENGTH)
252         || !EVP_MD_meth_set_input_blocksize(_hidden_sha1_md, SHA_CBLOCK)
253         || !EVP_MD_meth_set_app_datasize(_hidden_sha1_md,
254                                          sizeof(EVP_MD *) + sizeof(SHA_CTX))
255         || !EVP_MD_meth_set_flags(_hidden_sha1_md, EVP_MD_FLAG_DIGALGID_ABSENT)
256         || !EVP_MD_meth_set_init(_hidden_sha1_md, dasync_sha1_init)
257         || !EVP_MD_meth_set_update(_hidden_sha1_md, dasync_sha1_update)
258         || !EVP_MD_meth_set_final(_hidden_sha1_md, dasync_sha1_final)) {
259         EVP_MD_meth_free(_hidden_sha1_md);
260         _hidden_sha1_md = NULL;
261     }
262
263     _hidden_aes_128_cbc = EVP_CIPHER_meth_new(NID_aes_128_cbc,
264                                               16 /* block size */,
265                                               16 /* key len */);
266     if (_hidden_aes_128_cbc == NULL
267             || !EVP_CIPHER_meth_set_iv_length(_hidden_aes_128_cbc,16)
268             || !EVP_CIPHER_meth_set_flags(_hidden_aes_128_cbc,
269                                           EVP_CIPH_FLAG_DEFAULT_ASN1
270                                           | EVP_CIPH_CBC_MODE
271                                           | EVP_CIPH_FLAG_PIPELINE
272                                           | EVP_CIPH_CUSTOM_COPY)
273             || !EVP_CIPHER_meth_set_init(_hidden_aes_128_cbc,
274                                          dasync_aes128_init_key)
275             || !EVP_CIPHER_meth_set_do_cipher(_hidden_aes_128_cbc,
276                                               dasync_aes128_cbc_cipher)
277             || !EVP_CIPHER_meth_set_cleanup(_hidden_aes_128_cbc,
278                                             dasync_aes128_cbc_cleanup)
279             || !EVP_CIPHER_meth_set_ctrl(_hidden_aes_128_cbc,
280                                          dasync_aes128_cbc_ctrl)
281             || !EVP_CIPHER_meth_set_impl_ctx_size(_hidden_aes_128_cbc,
282                                 sizeof(struct dasync_pipeline_ctx))) {
283         EVP_CIPHER_meth_free(_hidden_aes_128_cbc);
284         _hidden_aes_128_cbc = NULL;
285     }
286
287     _hidden_aes_128_cbc_hmac_sha1 = EVP_CIPHER_meth_new(
288                                                 NID_aes_128_cbc_hmac_sha1,
289                                                 16 /* block size */,
290                                                 16 /* key len */);
291     if (_hidden_aes_128_cbc_hmac_sha1 == NULL
292             || !EVP_CIPHER_meth_set_iv_length(_hidden_aes_128_cbc_hmac_sha1,16)
293             || !EVP_CIPHER_meth_set_flags(_hidden_aes_128_cbc_hmac_sha1,
294                                             EVP_CIPH_CBC_MODE
295                                           | EVP_CIPH_FLAG_DEFAULT_ASN1
296                                           | EVP_CIPH_FLAG_AEAD_CIPHER
297                                           | EVP_CIPH_FLAG_PIPELINE
298                                           | EVP_CIPH_CUSTOM_COPY)
299             || !EVP_CIPHER_meth_set_init(_hidden_aes_128_cbc_hmac_sha1,
300                                          dasync_aes128_cbc_hmac_sha1_init_key)
301             || !EVP_CIPHER_meth_set_do_cipher(_hidden_aes_128_cbc_hmac_sha1,
302                                             dasync_aes128_cbc_hmac_sha1_cipher)
303             || !EVP_CIPHER_meth_set_cleanup(_hidden_aes_128_cbc_hmac_sha1,
304                                             dasync_aes128_cbc_hmac_sha1_cleanup)
305             || !EVP_CIPHER_meth_set_ctrl(_hidden_aes_128_cbc_hmac_sha1,
306                                          dasync_aes128_cbc_hmac_sha1_ctrl)
307             || !EVP_CIPHER_meth_set_impl_ctx_size(_hidden_aes_128_cbc_hmac_sha1,
308                                 sizeof(struct dasync_pipeline_ctx))) {
309         EVP_CIPHER_meth_free(_hidden_aes_128_cbc_hmac_sha1);
310         _hidden_aes_128_cbc_hmac_sha1 = NULL;
311     }
312
313     return 1;
314 }
315
316 static void destroy_pkey(void)
317 {
318     /*
319      * We don't actually need to free the dasync_rsa method since this is
320      * automatically freed for us by libcrypto.
321      */
322     dasync_rsa_orig = NULL;
323     dasync_rsa = NULL;
324 }
325
326 # ifndef OPENSSL_NO_DYNAMIC_ENGINE
327 static int bind_helper(ENGINE *e, const char *id)
328 {
329     if (id && (strcmp(id, engine_dasync_id) != 0))
330         return 0;
331     if (!bind_dasync(e))
332         return 0;
333     return 1;
334 }
335
336 IMPLEMENT_DYNAMIC_CHECK_FN()
337     IMPLEMENT_DYNAMIC_BIND_FN(bind_helper)
338 # endif
339
340 static ENGINE *engine_dasync(void)
341 {
342     ENGINE *ret = ENGINE_new();
343     if (!ret)
344         return NULL;
345     if (!bind_dasync(ret)) {
346         ENGINE_free(ret);
347         return NULL;
348     }
349     return ret;
350 }
351
352 void engine_load_dasync_int(void)
353 {
354     ENGINE *toadd = engine_dasync();
355     if (!toadd)
356         return;
357     ERR_set_mark();
358     ENGINE_add(toadd);
359     /*
360      * If the "add" worked, it gets a structural reference. So either way, we
361      * release our just-created reference.
362      */
363     ENGINE_free(toadd);
364     /*
365      * If the "add" didn't work, it was probably a conflict because it was
366      * already added (eg. someone calling ENGINE_load_blah then calling
367      * ENGINE_load_builtin_engines() perhaps).
368      */
369     ERR_pop_to_mark();
370 }
371
372 static int dasync_init(ENGINE *e)
373 {
374     return 1;
375 }
376
377
378 static int dasync_finish(ENGINE *e)
379 {
380     return 1;
381 }
382
383
384 static int dasync_destroy(ENGINE *e)
385 {
386     destroy_digests();
387     destroy_ciphers();
388     destroy_pkey();
389     ERR_unload_DASYNC_strings();
390     return 1;
391 }
392
393 static int dasync_pkey(ENGINE *e, EVP_PKEY_METHOD **pmeth,
394                        const int **pnids, int nid)
395 {
396     static const int rnid = EVP_PKEY_RSA;
397
398     if (pmeth == NULL) {
399         *pnids = &rnid;
400         return 1;
401     }
402
403     if (nid == EVP_PKEY_RSA) {
404         *pmeth = dasync_rsa;
405         return 1;
406     }
407
408     *pmeth = NULL;
409     return 0;
410 }
411
412 static int dasync_digests(ENGINE *e, const EVP_MD **digest,
413                           const int **nids, int nid)
414 {
415     int ok = 1;
416     if (!digest) {
417         /* We are returning a list of supported nids */
418         return dasync_digest_nids(nids);
419     }
420     /* We are being asked for a specific digest */
421     switch (nid) {
422     case NID_sha1:
423         *digest = dasync_sha1();
424         break;
425     default:
426         ok = 0;
427         *digest = NULL;
428         break;
429     }
430     return ok;
431 }
432
433 static int dasync_ciphers(ENGINE *e, const EVP_CIPHER **cipher,
434                                    const int **nids, int nid)
435 {
436     int ok = 1;
437     if (cipher == NULL) {
438         /* We are returning a list of supported nids */
439         *nids = dasync_cipher_nids;
440         return (sizeof(dasync_cipher_nids) -
441                 1) / sizeof(dasync_cipher_nids[0]);
442     }
443     /* We are being asked for a specific cipher */
444     switch (nid) {
445     case NID_aes_128_cbc:
446         *cipher = dasync_aes_128_cbc();
447         break;
448     case NID_aes_128_cbc_hmac_sha1:
449         *cipher = dasync_aes_128_cbc_hmac_sha1();
450         break;
451     default:
452         ok = 0;
453         *cipher = NULL;
454         break;
455     }
456     return ok;
457 }
458
459 static void wait_cleanup(ASYNC_WAIT_CTX *ctx, const void *key,
460                          OSSL_ASYNC_FD readfd, void *pvwritefd)
461 {
462     OSSL_ASYNC_FD *pwritefd = (OSSL_ASYNC_FD *)pvwritefd;
463 #if defined(ASYNC_WIN)
464     CloseHandle(readfd);
465     CloseHandle(*pwritefd);
466 #elif defined(ASYNC_POSIX)
467     close(readfd);
468     close(*pwritefd);
469 #endif
470     OPENSSL_free(pwritefd);
471 }
472
473 #define DUMMY_CHAR 'X'
474
475 static void dummy_pause_job(void) {
476     ASYNC_JOB *job;
477     ASYNC_WAIT_CTX *waitctx;
478     ASYNC_callback_fn callback;
479     void * callback_arg;
480     OSSL_ASYNC_FD pipefds[2] = {0, 0};
481     OSSL_ASYNC_FD *writefd;
482 #if defined(ASYNC_WIN)
483     DWORD numwritten, numread;
484     char buf = DUMMY_CHAR;
485 #elif defined(ASYNC_POSIX)
486     char buf = DUMMY_CHAR;
487 #endif
488
489     if ((job = ASYNC_get_current_job()) == NULL)
490         return;
491
492     waitctx = ASYNC_get_wait_ctx(job);
493
494     if (ASYNC_WAIT_CTX_get_callback(waitctx, &callback, &callback_arg) && callback != NULL) {
495         /*
496          * In the Dummy async engine we are cheating. We call the callback that the job
497          * is complete before the call to ASYNC_pause_job(). A real
498          * async engine would only call the callback when the job was actually complete
499          */
500         (*callback)(callback_arg);
501         ASYNC_pause_job();
502         return;
503     }
504
505
506     if (ASYNC_WAIT_CTX_get_fd(waitctx, engine_dasync_id, &pipefds[0],
507                               (void **)&writefd)) {
508         pipefds[1] = *writefd;
509     } else {
510         writefd = OPENSSL_malloc(sizeof(*writefd));
511         if (writefd == NULL)
512             return;
513 #if defined(ASYNC_WIN)
514         if (CreatePipe(&pipefds[0], &pipefds[1], NULL, 256) == 0) {
515             OPENSSL_free(writefd);
516             return;
517         }
518 #elif defined(ASYNC_POSIX)
519         if (pipe(pipefds) != 0) {
520             OPENSSL_free(writefd);
521             return;
522         }
523 #endif
524         *writefd = pipefds[1];
525
526         if (!ASYNC_WAIT_CTX_set_wait_fd(waitctx, engine_dasync_id, pipefds[0],
527                                         writefd, wait_cleanup)) {
528             wait_cleanup(waitctx, engine_dasync_id, pipefds[0], writefd);
529             return;
530         }
531     }
532     /*
533      * In the Dummy async engine we are cheating. We signal that the job
534      * is complete by waking it before the call to ASYNC_pause_job(). A real
535      * async engine would only wake when the job was actually complete
536      */
537 #if defined(ASYNC_WIN)
538     WriteFile(pipefds[1], &buf, 1, &numwritten, NULL);
539 #elif defined(ASYNC_POSIX)
540     if (write(pipefds[1], &buf, 1) < 0)
541         return;
542 #endif
543
544     /* Ignore errors - we carry on anyway */
545     ASYNC_pause_job();
546
547     /* Clear the wake signal */
548 #if defined(ASYNC_WIN)
549     ReadFile(pipefds[0], &buf, 1, &numread, NULL);
550 #elif defined(ASYNC_POSIX)
551     if (read(pipefds[0], &buf, 1) < 0)
552         return;
553 #endif
554 }
555
556 /*
557  * SHA1 implementation. At the moment we just defer to the standard
558  * implementation
559  */
560 static int dasync_sha1_init(EVP_MD_CTX *ctx)
561 {
562     dummy_pause_job();
563
564     return EVP_MD_meth_get_init(EVP_sha1())(ctx);
565 }
566
567 static int dasync_sha1_update(EVP_MD_CTX *ctx, const void *data,
568                              size_t count)
569 {
570     dummy_pause_job();
571
572     return EVP_MD_meth_get_update(EVP_sha1())(ctx, data, count);
573 }
574
575 static int dasync_sha1_final(EVP_MD_CTX *ctx, unsigned char *md)
576 {
577     dummy_pause_job();
578
579     return EVP_MD_meth_get_final(EVP_sha1())(ctx, md);
580 }
581
582 /* Cipher helper functions */
583
584 static int dasync_cipher_ctrl_helper(EVP_CIPHER_CTX *ctx, int type, int arg,
585                                      void *ptr, int aeadcapable,
586                                      const EVP_CIPHER *ciph)
587 {
588     int ret;
589     struct dasync_pipeline_ctx *pipe_ctx =
590         (struct dasync_pipeline_ctx *)EVP_CIPHER_CTX_get_cipher_data(ctx);
591
592     if (pipe_ctx == NULL)
593         return 0;
594
595     switch (type) {
596         case EVP_CTRL_COPY:
597             {
598                 size_t sz = EVP_CIPHER_impl_ctx_size(ciph);
599                 void *inner_cipher_data = OPENSSL_malloc(sz);
600
601                 if (inner_cipher_data == NULL)
602                     return -1;
603                 memcpy(inner_cipher_data, pipe_ctx->inner_cipher_data, sz);
604                 pipe_ctx->inner_cipher_data = inner_cipher_data;
605             }
606             break;
607
608         case EVP_CTRL_SET_PIPELINE_OUTPUT_BUFS:
609             pipe_ctx->numpipes = arg;
610             pipe_ctx->outbufs = (unsigned char **)ptr;
611             break;
612
613         case EVP_CTRL_SET_PIPELINE_INPUT_BUFS:
614             pipe_ctx->numpipes = arg;
615             pipe_ctx->inbufs = (unsigned char **)ptr;
616             break;
617
618         case EVP_CTRL_SET_PIPELINE_INPUT_LENS:
619             pipe_ctx->numpipes = arg;
620             pipe_ctx->lens = (size_t *)ptr;
621             break;
622
623         case EVP_CTRL_AEAD_SET_MAC_KEY:
624             if (!aeadcapable)
625                 return -1;
626             EVP_CIPHER_CTX_set_cipher_data(ctx, pipe_ctx->inner_cipher_data);
627             ret = EVP_CIPHER_meth_get_ctrl(EVP_aes_128_cbc_hmac_sha1())
628                                           (ctx, type, arg, ptr);
629             EVP_CIPHER_CTX_set_cipher_data(ctx, pipe_ctx);
630             return ret;
631
632         case EVP_CTRL_AEAD_TLS1_AAD:
633         {
634             unsigned char *p = ptr;
635             unsigned int len;
636
637             if (!aeadcapable || arg != EVP_AEAD_TLS1_AAD_LEN)
638                 return -1;
639
640             if (pipe_ctx->aadctr >= SSL_MAX_PIPELINES)
641                 return -1;
642
643             memcpy(pipe_ctx->tlsaad[pipe_ctx->aadctr], ptr,
644                    EVP_AEAD_TLS1_AAD_LEN);
645             pipe_ctx->aadctr++;
646
647             len = p[arg - 2] << 8 | p[arg - 1];
648
649             if (EVP_CIPHER_CTX_is_encrypting(ctx)) {
650                 if ((p[arg - 4] << 8 | p[arg - 3]) >= TLS1_1_VERSION) {
651                     if (len < AES_BLOCK_SIZE)
652                         return 0;
653                     len -= AES_BLOCK_SIZE;
654                 }
655
656                 return ((len + SHA_DIGEST_LENGTH + AES_BLOCK_SIZE)
657                         & -AES_BLOCK_SIZE) - len;
658             } else {
659                 return SHA_DIGEST_LENGTH;
660             }
661         }
662
663         default:
664             return 0;
665     }
666
667     return 1;
668 }
669
670 static int dasync_cipher_init_key_helper(EVP_CIPHER_CTX *ctx,
671                                          const unsigned char *key,
672                                          const unsigned char *iv, int enc,
673                                          const EVP_CIPHER *cipher)
674 {
675     int ret;
676     struct dasync_pipeline_ctx *pipe_ctx =
677         (struct dasync_pipeline_ctx *)EVP_CIPHER_CTX_get_cipher_data(ctx);
678
679     if (pipe_ctx->inner_cipher_data == NULL
680             && EVP_CIPHER_impl_ctx_size(cipher) != 0) {
681         pipe_ctx->inner_cipher_data = OPENSSL_zalloc(
682             EVP_CIPHER_impl_ctx_size(cipher));
683         if (pipe_ctx->inner_cipher_data == NULL) {
684             DASYNCerr(DASYNC_F_DASYNC_CIPHER_INIT_KEY_HELPER,
685                         ERR_R_MALLOC_FAILURE);
686             return 0;
687         }
688     }
689
690     pipe_ctx->numpipes = 0;
691     pipe_ctx->aadctr = 0;
692
693     EVP_CIPHER_CTX_set_cipher_data(ctx, pipe_ctx->inner_cipher_data);
694     ret = EVP_CIPHER_meth_get_init(cipher)(ctx, key, iv, enc);
695     EVP_CIPHER_CTX_set_cipher_data(ctx, pipe_ctx);
696
697     return ret;
698 }
699
700 static int dasync_cipher_helper(EVP_CIPHER_CTX *ctx, unsigned char *out,
701                                 const unsigned char *in, size_t inl,
702                                 const EVP_CIPHER *cipher)
703 {
704     int ret = 1;
705     unsigned int i, pipes;
706     struct dasync_pipeline_ctx *pipe_ctx =
707         (struct dasync_pipeline_ctx *)EVP_CIPHER_CTX_get_cipher_data(ctx);
708
709     pipes = pipe_ctx->numpipes;
710     EVP_CIPHER_CTX_set_cipher_data(ctx, pipe_ctx->inner_cipher_data);
711     if (pipes == 0) {
712         if (pipe_ctx->aadctr != 0) {
713             if (pipe_ctx->aadctr != 1)
714                 return -1;
715             EVP_CIPHER_meth_get_ctrl(cipher)
716                                     (ctx, EVP_CTRL_AEAD_TLS1_AAD,
717                                      EVP_AEAD_TLS1_AAD_LEN,
718                                      pipe_ctx->tlsaad[0]);
719         }
720         ret = EVP_CIPHER_meth_get_do_cipher(cipher)
721                                            (ctx, out, in, inl);
722     } else {
723         if (pipe_ctx->aadctr > 0 && pipe_ctx->aadctr != pipes)
724             return -1;
725         for (i = 0; i < pipes; i++) {
726             if (pipe_ctx->aadctr > 0) {
727                 EVP_CIPHER_meth_get_ctrl(cipher)
728                                         (ctx, EVP_CTRL_AEAD_TLS1_AAD,
729                                          EVP_AEAD_TLS1_AAD_LEN,
730                                          pipe_ctx->tlsaad[i]);
731             }
732             ret = ret && EVP_CIPHER_meth_get_do_cipher(cipher)
733                                 (ctx, pipe_ctx->outbufs[i], pipe_ctx->inbufs[i],
734                                  pipe_ctx->lens[i]);
735         }
736         pipe_ctx->numpipes = 0;
737     }
738     pipe_ctx->aadctr = 0;
739     EVP_CIPHER_CTX_set_cipher_data(ctx, pipe_ctx);
740     return ret;
741 }
742
743 static int dasync_cipher_cleanup_helper(EVP_CIPHER_CTX *ctx,
744                                         const EVP_CIPHER *cipher)
745 {
746     struct dasync_pipeline_ctx *pipe_ctx =
747         (struct dasync_pipeline_ctx *)EVP_CIPHER_CTX_get_cipher_data(ctx);
748
749     OPENSSL_clear_free(pipe_ctx->inner_cipher_data,
750                        EVP_CIPHER_impl_ctx_size(cipher));
751
752     return 1;
753 }
754
755 /*
756  * AES128 CBC Implementation
757  */
758
759 static int dasync_aes128_cbc_ctrl(EVP_CIPHER_CTX *ctx, int type, int arg,
760                                   void *ptr)
761 {
762     return dasync_cipher_ctrl_helper(ctx, type, arg, ptr, 0, EVP_aes_128_cbc());
763 }
764
765 static int dasync_aes128_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *key,
766                              const unsigned char *iv, int enc)
767 {
768     return dasync_cipher_init_key_helper(ctx, key, iv, enc, EVP_aes_128_cbc());
769 }
770
771 static int dasync_aes128_cbc_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
772                                const unsigned char *in, size_t inl)
773 {
774     return dasync_cipher_helper(ctx, out, in, inl, EVP_aes_128_cbc());
775 }
776
777 static int dasync_aes128_cbc_cleanup(EVP_CIPHER_CTX *ctx)
778 {
779     return dasync_cipher_cleanup_helper(ctx, EVP_aes_128_cbc());
780 }
781
782
783 /*
784  * AES128 CBC HMAC SHA1 Implementation
785  */
786
787 static int dasync_aes128_cbc_hmac_sha1_ctrl(EVP_CIPHER_CTX *ctx, int type,
788                                              int arg, void *ptr)
789 {
790     return dasync_cipher_ctrl_helper(ctx, type, arg, ptr, 1, EVP_aes_128_cbc_hmac_sha1());
791 }
792
793 static int dasync_aes128_cbc_hmac_sha1_init_key(EVP_CIPHER_CTX *ctx,
794                                                 const unsigned char *key,
795                                                 const unsigned char *iv,
796                                                 int enc)
797 {
798     /*
799      * We can safely assume that EVP_aes_128_cbc_hmac_sha1() != NULL,
800      * see comment before the definition of dasync_aes_128_cbc_hmac_sha1().
801      */
802     return dasync_cipher_init_key_helper(ctx, key, iv, enc,
803                                          EVP_aes_128_cbc_hmac_sha1());
804 }
805
806 static int dasync_aes128_cbc_hmac_sha1_cipher(EVP_CIPHER_CTX *ctx,
807                                                unsigned char *out,
808                                                const unsigned char *in,
809                                                size_t inl)
810 {
811     return dasync_cipher_helper(ctx, out, in, inl, EVP_aes_128_cbc_hmac_sha1());
812 }
813
814 static int dasync_aes128_cbc_hmac_sha1_cleanup(EVP_CIPHER_CTX *ctx)
815 {
816     /*
817      * We can safely assume that EVP_aes_128_cbc_hmac_sha1() != NULL,
818      * see comment before the definition of dasync_aes_128_cbc_hmac_sha1().
819      */
820     return dasync_cipher_cleanup_helper(ctx, EVP_aes_128_cbc_hmac_sha1());
821 }
822
823
824 /*
825  * RSA implementation
826  */
827 static int dasync_rsa_init(EVP_PKEY_CTX *ctx)
828 {
829     static int (*pinit)(EVP_PKEY_CTX *ctx);
830
831     if (pinit == NULL)
832         EVP_PKEY_meth_get_init(dasync_rsa_orig, &pinit);
833     return pinit(ctx);
834 }
835
836 static void dasync_rsa_cleanup(EVP_PKEY_CTX *ctx)
837 {
838     static void (*pcleanup)(EVP_PKEY_CTX *ctx);
839
840     if (pcleanup == NULL)
841         EVP_PKEY_meth_get_cleanup(dasync_rsa_orig, &pcleanup);
842     pcleanup(ctx);
843 }
844
845 static int dasync_rsa_paramgen_init(EVP_PKEY_CTX *ctx)
846 {
847     static int (*pparamgen_init)(EVP_PKEY_CTX *ctx);
848
849     if (pparamgen_init == NULL)
850         EVP_PKEY_meth_get_paramgen(dasync_rsa_orig, &pparamgen_init, NULL);
851     return pparamgen_init != NULL ? pparamgen_init(ctx) : 1;
852 }
853
854 static int dasync_rsa_paramgen(EVP_PKEY_CTX *ctx, EVP_PKEY *pkey)
855 {
856     static int (*pparamgen)(EVP_PKEY_CTX *c, EVP_PKEY *pkey);
857
858     if (pparamgen == NULL)
859         EVP_PKEY_meth_get_paramgen(dasync_rsa_orig, NULL, &pparamgen);
860     return pparamgen != NULL ? pparamgen(ctx, pkey) : 1;
861 }
862
863 static int dasync_rsa_keygen_init(EVP_PKEY_CTX *ctx)
864 {
865     static int (*pkeygen_init)(EVP_PKEY_CTX *ctx);
866
867     if (pkeygen_init == NULL)
868         EVP_PKEY_meth_get_keygen(dasync_rsa_orig, &pkeygen_init, NULL);
869     return pkeygen_init != NULL ? pkeygen_init(ctx) : 1;
870 }
871
872 static int dasync_rsa_keygen(EVP_PKEY_CTX *ctx, EVP_PKEY *pkey)
873 {
874     static int (*pkeygen)(EVP_PKEY_CTX *c, EVP_PKEY *pkey);
875
876     if (pkeygen == NULL)
877         EVP_PKEY_meth_get_keygen(dasync_rsa_orig, NULL, &pkeygen);
878     return pkeygen(ctx, pkey);
879 }
880
881 static int dasync_rsa_encrypt_init(EVP_PKEY_CTX *ctx)
882 {
883     static int (*pencrypt_init)(EVP_PKEY_CTX *ctx);
884
885     if (pencrypt_init == NULL)
886         EVP_PKEY_meth_get_encrypt(dasync_rsa_orig, &pencrypt_init, NULL);
887     return pencrypt_init != NULL ? pencrypt_init(ctx) : 1;
888 }
889
890 static int dasync_rsa_encrypt(EVP_PKEY_CTX *ctx, unsigned char *out,
891                               size_t *outlen, const unsigned char *in,
892                               size_t inlen)
893 {
894     static int (*pencryptfn)(EVP_PKEY_CTX *ctx, unsigned char *out,
895                              size_t *outlen, const unsigned char *in,
896                              size_t inlen);
897
898     if (pencryptfn == NULL)
899         EVP_PKEY_meth_get_encrypt(dasync_rsa_orig, NULL, &pencryptfn);
900     return pencryptfn(ctx, out, outlen, in, inlen);
901 }
902
903 static int dasync_rsa_decrypt_init(EVP_PKEY_CTX *ctx)
904 {
905     static int (*pdecrypt_init)(EVP_PKEY_CTX *ctx);
906
907     if (pdecrypt_init == NULL)
908         EVP_PKEY_meth_get_decrypt(dasync_rsa_orig, &pdecrypt_init, NULL);
909     return pdecrypt_init != NULL ? pdecrypt_init(ctx) : 1;
910 }
911
912 static int dasync_rsa_decrypt(EVP_PKEY_CTX *ctx, unsigned char *out,
913                               size_t *outlen, const unsigned char *in,
914                               size_t inlen)
915 {
916     static int (*pdecrypt)(EVP_PKEY_CTX *ctx, unsigned char *out,
917                              size_t *outlen, const unsigned char *in,
918                              size_t inlen);
919
920     if (pdecrypt == NULL)
921         EVP_PKEY_meth_get_encrypt(dasync_rsa_orig, NULL, &pdecrypt);
922     return pdecrypt(ctx, out, outlen, in, inlen);
923 }
924
925 static int dasync_rsa_ctrl(EVP_PKEY_CTX *ctx, int type, int p1, void *p2)
926 {
927     static int (*pctrl)(EVP_PKEY_CTX *ctx, int type, int p1, void *p2);
928
929     if (pctrl == NULL)
930         EVP_PKEY_meth_get_ctrl(dasync_rsa_orig, &pctrl, NULL);
931     return pctrl(ctx, type, p1, p2);
932 }
933
934 static int dasync_rsa_ctrl_str(EVP_PKEY_CTX *ctx, const char *type,
935                                const char *value)
936 {
937     static int (*pctrl_str)(EVP_PKEY_CTX *ctx, const char *type,
938                             const char *value);
939
940     if (pctrl_str == NULL)
941         EVP_PKEY_meth_get_ctrl(dasync_rsa_orig, NULL, &pctrl_str);
942     return pctrl_str(ctx, type, value);
943 }