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