GH773: Possible leak on CRYPTO_THREAD_lock_new failure
[openssl.git] / engines / e_dasync.c
1 /*
2  * Written by Matt Caswell (matt@openssl.org) for the OpenSSL project.
3  */
4 /* ====================================================================
5  * Copyright (c) 2015 The OpenSSL Project.  All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  *
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  *
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in
16  *    the documentation and/or other materials provided with the
17  *    distribution.
18  *
19  * 3. All advertising materials mentioning features or use of this
20  *    software must display the following acknowledgment:
21  *    "This product includes software developed by the OpenSSL Project
22  *    for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
23  *
24  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
25  *    endorse or promote products derived from this software without
26  *    prior written permission. For written permission, please contact
27  *    licensing@OpenSSL.org.
28  *
29  * 5. Products derived from this software may not be called "OpenSSL"
30  *    nor may "OpenSSL" appear in their names without prior written
31  *    permission of the OpenSSL Project.
32  *
33  * 6. Redistributions of any form whatsoever must retain the following
34  *    acknowledgment:
35  *    "This product includes software developed by the OpenSSL Project
36  *    for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
37  *
38  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
39  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
40  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
41  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
42  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
43  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
44  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
45  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
46  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
47  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
48  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
49  * OF THE POSSIBILITY OF SUCH DAMAGE.
50  * ====================================================================
51  */
52
53 #include <stdio.h>
54 #include <string.h>
55
56 #include <openssl/engine.h>
57 #include <openssl/sha.h>
58 #include <openssl/rsa.h>
59 #include <openssl/evp.h>
60 #include <openssl/async.h>
61 #include <openssl/bn.h>
62 #include <openssl/crypto.h>
63
64 #if (defined(OPENSSL_SYS_UNIX) || defined(OPENSSL_SYS_CYGWIN)) && defined(OPENSSL_THREADS)
65 # undef ASYNC_POSIX
66 # define ASYNC_POSIX
67 # include <unistd.h>
68 #elif defined(_WIN32)
69 # undef ASYNC_WIN
70 # define ASYNC_WIN
71 # include <windows.h>
72 #endif
73
74 #define DASYNC_LIB_NAME "DASYNC"
75 #include "e_dasync_err.c"
76
77 /* Engine Id and Name */
78 static const char *engine_dasync_id = "dasync";
79 static const char *engine_dasync_name = "Dummy Async engine support";
80
81
82 /* Engine Lifetime functions */
83 static int dasync_destroy(ENGINE *e);
84 static int dasync_init(ENGINE *e);
85 static int dasync_finish(ENGINE *e);
86 void engine_load_dasync_internal(void);
87
88
89 /* Set up digests. Just SHA1 for now */
90 static int dasync_digests(ENGINE *e, const EVP_MD **digest,
91                           const int **nids, int nid);
92
93 static void dummy_pause_job(void);
94
95 /* SHA1 */
96 static int dasync_sha1_init(EVP_MD_CTX *ctx);
97 static int dasync_sha1_update(EVP_MD_CTX *ctx, const void *data,
98                              size_t count);
99 static int dasync_sha1_final(EVP_MD_CTX *ctx, unsigned char *md);
100
101 static EVP_MD *_hidden_sha1_md = NULL;
102 static const EVP_MD *dasync_sha1(void)
103 {
104     if (_hidden_sha1_md == NULL) {
105         EVP_MD *md;
106
107         if ((md = EVP_MD_meth_new(NID_sha1, NID_sha1WithRSAEncryption)) == NULL
108             || !EVP_MD_meth_set_result_size(md, SHA_DIGEST_LENGTH)
109             || !EVP_MD_meth_set_input_blocksize(md, SHA_CBLOCK)
110             || !EVP_MD_meth_set_app_datasize(md,
111                                              sizeof(EVP_MD *) + sizeof(SHA_CTX))
112             || !EVP_MD_meth_set_flags(md, EVP_MD_FLAG_DIGALGID_ABSENT)
113             || !EVP_MD_meth_set_init(md, dasync_sha1_init)
114             || !EVP_MD_meth_set_update(md, dasync_sha1_update)
115             || !EVP_MD_meth_set_final(md, dasync_sha1_final)) {
116             EVP_MD_meth_free(md);
117             md = NULL;
118         }
119         _hidden_sha1_md = md;
120     }
121     return _hidden_sha1_md;
122 }
123 static void destroy_digests(void)
124 {
125     EVP_MD_meth_free(_hidden_sha1_md);
126     _hidden_sha1_md = NULL;
127 }
128 static int dasync_digest_nids(const int **nids)
129 {
130     static int digest_nids[2] = { 0, 0 };
131     static int pos = 0;
132     static int init = 0;
133
134     if (!init) {
135         const EVP_MD *md;
136         if ((md = dasync_sha1()) != NULL)
137             digest_nids[pos++] = EVP_MD_type(md);
138         digest_nids[pos] = 0;
139         init = 1;
140     }
141     *nids = digest_nids;
142     return pos;
143 }
144
145 /* RSA */
146
147 static int dasync_pub_enc(int flen, const unsigned char *from,
148                     unsigned char *to, RSA *rsa, int padding);
149 static int dasync_pub_dec(int flen, const unsigned char *from,
150                     unsigned char *to, RSA *rsa, int padding);
151 static int dasync_rsa_priv_enc(int flen, const unsigned char *from,
152                       unsigned char *to, RSA *rsa, int padding);
153 static int dasync_rsa_priv_dec(int flen, const unsigned char *from,
154                       unsigned char *to, RSA *rsa, int padding);
155 static int dasync_rsa_mod_exp(BIGNUM *r0, const BIGNUM *I, RSA *rsa,
156                               BN_CTX *ctx);
157
158 static int dasync_rsa_init(RSA *rsa);
159 static int dasync_rsa_finish(RSA *rsa);
160
161 static RSA_METHOD dasync_rsa_method = {
162     "Dummy Async RSA method",
163     dasync_pub_enc,             /* pub_enc */
164     dasync_pub_dec,             /* pub_dec */
165     dasync_rsa_priv_enc,        /* priv_enc */
166     dasync_rsa_priv_dec,        /* priv_dec */
167     dasync_rsa_mod_exp,         /* rsa_mod_exp */
168     BN_mod_exp_mont,            /* bn_mod_exp */
169     dasync_rsa_init,            /* init */
170     dasync_rsa_finish,          /* finish */
171     0,                          /* flags */
172     NULL,                       /* app_data */
173     0,                          /* rsa_sign */
174     0,                          /* rsa_verify */
175     NULL                        /* rsa_keygen */
176 };
177
178
179 static int bind_dasync(ENGINE *e)
180 {
181     /* Ensure the dasync error handling is set up */
182     ERR_load_DASYNC_strings();
183
184     if (!ENGINE_set_id(e, engine_dasync_id)
185         || !ENGINE_set_name(e, engine_dasync_name)
186         || !ENGINE_set_RSA(e, &dasync_rsa_method)
187         || !ENGINE_set_digests(e, dasync_digests)
188         || !ENGINE_set_destroy_function(e, dasync_destroy)
189         || !ENGINE_set_init_function(e, dasync_init)
190         || !ENGINE_set_finish_function(e, dasync_finish)) {
191         DASYNCerr(DASYNC_F_BIND_DASYNC, DASYNC_R_INIT_FAILED);
192         return 0;
193     }
194
195     return 1;
196 }
197
198 # ifndef OPENSSL_NO_DYNAMIC_ENGINE
199 static int bind_helper(ENGINE *e, const char *id)
200 {
201     if (id && (strcmp(id, engine_dasync_id) != 0))
202         return 0;
203     if (!bind_dasync(e))
204         return 0;
205     return 1;
206 }
207
208 IMPLEMENT_DYNAMIC_CHECK_FN()
209     IMPLEMENT_DYNAMIC_BIND_FN(bind_helper)
210 # endif
211
212 static ENGINE *engine_dasync(void)
213 {
214     ENGINE *ret = ENGINE_new();
215     if (!ret)
216         return NULL;
217     if (!bind_dasync(ret)) {
218         ENGINE_free(ret);
219         return NULL;
220     }
221     return ret;
222 }
223
224 void engine_load_dasync_internal(void)
225 {
226     ENGINE *toadd = engine_dasync();
227     if (!toadd)
228         return;
229     ENGINE_add(toadd);
230     ENGINE_free(toadd);
231     ERR_clear_error();
232 }
233
234 static int dasync_init(ENGINE *e)
235 {
236     return 1;
237 }
238
239
240 static int dasync_finish(ENGINE *e)
241 {
242     return 1;
243 }
244
245
246 static int dasync_destroy(ENGINE *e)
247 {
248     destroy_digests();
249     ERR_unload_DASYNC_strings();
250     return 1;
251 }
252
253 static int dasync_digests(ENGINE *e, const EVP_MD **digest,
254                           const int **nids, int nid)
255 {
256     int ok = 1;
257     if (!digest) {
258         /* We are returning a list of supported nids */
259         return dasync_digest_nids(nids);
260     }
261     /* We are being asked for a specific digest */
262     switch (nid) {
263     case NID_sha1:
264         *digest = dasync_sha1();
265         break;
266     default:
267         ok = 0;
268         *digest = NULL;
269         break;
270     }
271     return ok;
272 }
273
274 static void wait_cleanup(ASYNC_WAIT_CTX *ctx, const void *key,
275                          OSSL_ASYNC_FD readfd, void *pvwritefd)
276 {
277     OSSL_ASYNC_FD *pwritefd = (OSSL_ASYNC_FD *)pvwritefd;
278 #if defined(ASYNC_WIN)
279     CloseHandle(readfd);
280     CloseHandle(*pwritefd);
281 #elif defined(ASYNC_POSIX)
282     close(readfd);
283     close(*pwritefd);
284 #endif
285     OPENSSL_free(pwritefd);
286 }
287
288 #define DUMMY_CHAR 'X'
289
290 static void dummy_pause_job(void) {
291     ASYNC_JOB *job;
292     ASYNC_WAIT_CTX *waitctx;
293     OSSL_ASYNC_FD pipefds[2] = {0, 0};
294     OSSL_ASYNC_FD *writefd;
295 #if defined(ASYNC_WIN)
296     DWORD numwritten, numread;
297     char buf = DUMMY_CHAR;
298 #elif defined(ASYNC_POSIX)
299     char buf = DUMMY_CHAR;
300 #endif
301
302     if ((job = ASYNC_get_current_job()) == NULL)
303         return;
304
305     waitctx = ASYNC_get_wait_ctx(job);
306
307     if (ASYNC_WAIT_CTX_get_fd(waitctx, engine_dasync_id, &pipefds[0],
308                               (void **)&writefd)) {
309         pipefds[1] = *writefd;
310     } else {
311         writefd = OPENSSL_malloc(sizeof(*writefd));
312         if (writefd == NULL)
313             return;
314 #if defined(ASYNC_WIN)
315         if (CreatePipe(&pipefds[0], &pipefds[1], NULL, 256) == 0) {
316             OPENSSL_free(writefd);
317             return;
318         }
319 #elif defined(ASYNC_POSIX)
320         if (pipe(pipefds) != 0) {
321             OPENSSL_free(writefd);
322             return;
323         }
324 #endif
325         *writefd = pipefds[1];
326
327         if(!ASYNC_WAIT_CTX_set_wait_fd(waitctx, engine_dasync_id, pipefds[0],
328                                        writefd, wait_cleanup)) {
329             wait_cleanup(waitctx, engine_dasync_id, pipefds[0], writefd);
330             return;
331         }
332     }
333     /*
334      * In the Dummy async engine we are cheating. We signal that the job
335      * is complete by waking it before the call to ASYNC_pause_job(). A real
336      * async engine would only wake when the job was actually complete
337      */
338 #if defined(ASYNC_WIN)
339     WriteFile(pipefds[1], &buf, 1, &numwritten, NULL);
340 #elif defined(ASYNC_POSIX)
341     write(pipefds[1], &buf, 1);
342 #endif
343
344     /* Ignore errors - we carry on anyway */
345     ASYNC_pause_job();
346
347     /* Clear the wake signal */
348 #if defined(ASYNC_WIN)
349     ReadFile(pipefds[0], &buf, 1, &numread, NULL);
350 #elif defined(ASYNC_POSIX)
351     read(pipefds[0], &buf, 1);
352 #endif
353 }
354
355 /*
356  * SHA1 implementation. At the moment we just defer to the standard
357  * implementation
358  */
359 #undef data
360 #define data(ctx) ((SHA_CTX *)EVP_MD_CTX_md_data(ctx))
361 static int dasync_sha1_init(EVP_MD_CTX *ctx)
362 {
363     dummy_pause_job();
364
365     return SHA1_Init(data(ctx));
366 }
367
368 static int dasync_sha1_update(EVP_MD_CTX *ctx, const void *data,
369                              size_t count)
370 {
371     dummy_pause_job();
372
373     return SHA1_Update(data(ctx), data, (size_t)count);
374 }
375
376 static int dasync_sha1_final(EVP_MD_CTX *ctx, unsigned char *md)
377 {
378     dummy_pause_job();
379
380     return SHA1_Final(md, data(ctx));
381 }
382
383 /*
384  * RSA implementation
385  */
386
387 static int dasync_pub_enc(int flen, const unsigned char *from,
388                     unsigned char *to, RSA *rsa, int padding) {
389     /* Ignore errors - we carry on anyway */
390     dummy_pause_job();
391     return RSA_PKCS1_OpenSSL()->rsa_pub_enc(flen, from, to, rsa, padding);
392 }
393
394 static int dasync_pub_dec(int flen, const unsigned char *from,
395                     unsigned char *to, RSA *rsa, int padding) {
396     /* Ignore errors - we carry on anyway */
397     dummy_pause_job();
398     return RSA_PKCS1_OpenSSL()->rsa_pub_dec(flen, from, to, rsa, padding);
399 }
400
401 static int dasync_rsa_priv_enc(int flen, const unsigned char *from,
402                       unsigned char *to, RSA *rsa, int padding)
403 {
404     /* Ignore errors - we carry on anyway */
405     dummy_pause_job();
406     return RSA_PKCS1_OpenSSL()->rsa_priv_enc(flen, from, to, rsa, padding);
407 }
408
409 static int dasync_rsa_priv_dec(int flen, const unsigned char *from,
410                       unsigned char *to, RSA *rsa, int padding)
411 {
412     /* Ignore errors - we carry on anyway */
413     dummy_pause_job();
414     return RSA_PKCS1_OpenSSL()->rsa_priv_dec(flen, from, to, rsa, padding);
415 }
416
417 static int dasync_rsa_mod_exp(BIGNUM *r0, const BIGNUM *I, RSA *rsa, BN_CTX *ctx)
418 {
419     /* Ignore errors - we carry on anyway */
420     dummy_pause_job();
421     return RSA_PKCS1_OpenSSL()->rsa_mod_exp(r0, I, rsa, ctx);
422 }
423
424 static int dasync_rsa_init(RSA *rsa)
425 {
426     return RSA_PKCS1_OpenSSL()->init(rsa);
427 }
428 static int dasync_rsa_finish(RSA *rsa)
429 {
430     return RSA_PKCS1_OpenSSL()->finish(rsa);
431 }