Debian Codegraph @

src/vendor/azure-uamqp-c/deps/azure-c-shared-utility/adapters/tlsio_bearssl.c

raw
1 // Copyright (c) Microsoft. All rights reserved.
2 // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3
4 // Portions of this code are based upon code in BearSSL. License included below.
5
6 /*
7 * Copyright (c) 2017 Thomas Pornin <[email protected]>
8 *
9 * Permission is hereby granted, free of charge, to any person obtaining
10 * a copy of this software and associated documentation files (the
11 * "Software"), to deal in the Software without restriction, including
12 * without limitation the rights to use, copy, modify, merge, publish,
13 * distribute, sublicense, and/or sell copies of the Software, and to
14 * permit persons to whom the Software is furnished to do so, subject to
15 * the following conditions:
16 *
17 * The above copyright notice and this permission notice shall be
18 * included in all copies or substantial portions of the Software.
19 *
20 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
21 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
22 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
23 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
24 * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
25 * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
26 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
27 * SOFTWARE.
28 */
29
30 #include <stdlib.h>
31
32 #include "bearssl.h"
33
34 #include "azure_c_shared_utility/gballoc.h"
35 #include "azure_c_shared_utility/optimize_size.h"
36 #include "azure_c_shared_utility/tlsio.h"
37 #include "azure_c_shared_utility/socketio.h"
38 #include "azure_c_shared_utility/crt_abstractions.h"
39 #include "azure_c_shared_utility/shared_util_options.h"
40 #include "azure_c_shared_utility/singlylinkedlist.h"
41 #include "azure_c_shared_utility/vector.h"
42 #include "azure_c_shared_utility/buffer_.h"
43 #include "azure_c_shared_utility/tlsio_bearssl.h"
44 #include "azure_c_shared_utility/safe_math.h"
45
46 static const char *const OPTION_UNDERLYING_IO_OPTIONS = "underlying_io_options";
47
48 typedef enum TLSIO_STATE_ENUM_TAG
49 {
50 TLSIO_STATE_NOT_OPEN,
51 TLSIO_STATE_OPENING_UNDERLYING_IO,
52 TLSIO_STATE_IN_HANDSHAKE,
53 TLSIO_STATE_OPEN,
54 TLSIO_STATE_CLOSING,
55 TLSIO_STATE_ERROR
56 } TLSIO_STATE_ENUM;
57
58 typedef struct PENDING_TLS_IO_TAG
59 {
60 unsigned char* bytes;
61 size_t size;
62 ON_SEND_COMPLETE on_send_complete;
63 void* callback_context;
64 SINGLYLINKEDLIST_HANDLE pending_io_list;
65 } PENDING_TLS_IO;
66
67 typedef struct {
68 int key_type; /* BR_KEYTYPE_RSA or BR_KEYTYPE_EC */
69 union {
70 br_rsa_private_key rsa;
71 br_ec_private_key ec;
72 } key;
73 } private_key;
74
75 typedef struct TLS_IO_INSTANCE_TAG
76 {
77 XIO_HANDLE socket_io;
78 ON_BYTES_RECEIVED on_bytes_received;
79 ON_IO_OPEN_COMPLETE on_io_open_complete;
80 ON_IO_CLOSE_COMPLETE on_io_close_complete;
81 ON_IO_ERROR on_io_error;
82 void *on_bytes_received_context;
83 void *on_io_open_complete_context;
84 void *on_io_close_complete_context;
85 void *on_io_error_context;
86 TLSIO_STATE_ENUM tlsio_state;
87 unsigned char *socket_io_read_bytes;
88 size_t socket_io_read_byte_count;
89 ON_SEND_COMPLETE on_send_complete;
90 void *on_send_complete_callback_context;
91 SINGLYLINKEDLIST_HANDLE pending_toencrypt_list;
92 SINGLYLINKEDLIST_HANDLE pending_todecrypt_list;
93
94 br_ssl_client_context sc;
95 br_x509_minimal_context xc;
96 br_sslio_context ioc;
97 br_x509_trust_anchor *tas;
98 br_x509_certificate *x509_cert;
99 size_t x509_cert_len;
100 private_key *x509_pk;
101 size_t ta_count;
102 char *trusted_certificates;
103 char *x509_certificate;
104 char *x509_private_key;
105 unsigned char iobuf[BR_SSL_BUFSIZE_BIDI];
106 char *hostname;
107 } TLS_IO_INSTANCE;
108
109 typedef struct {
110 char *name;
111 unsigned char *data;
112 size_t data_len;
113 } pem_object;
114
115 static void indicate_error(TLS_IO_INSTANCE *tls_io_instance)
116 {
117 if ((tls_io_instance->tlsio_state == TLSIO_STATE_NOT_OPEN) || (tls_io_instance->tlsio_state == TLSIO_STATE_ERROR))
118 {
119 return;
120 }
121
122 tls_io_instance->tlsio_state = TLSIO_STATE_ERROR;
123
124 if (tls_io_instance->on_io_error != NULL)
125 {
126 tls_io_instance->on_io_error(tls_io_instance->on_io_error_context);
127 }
128 }
129
130 static void indicate_open_complete(TLS_IO_INSTANCE *tls_io_instance, IO_OPEN_RESULT open_result)
131 {
132 if (tls_io_instance->on_io_open_complete != NULL)
133 {
134 tls_io_instance->on_io_open_complete(tls_io_instance->on_io_open_complete_context, open_result);
135 }
136 }
137
138 static int add_pending_operation(SINGLYLINKEDLIST_HANDLE list, const unsigned char *buffer, size_t size, ON_SEND_COMPLETE on_send_complete, void *context)
139 {
140 int result;
141 PENDING_TLS_IO* pending_tls_io = (PENDING_TLS_IO*)malloc(sizeof(PENDING_TLS_IO));
142
143 if (pending_tls_io == NULL)
144 {
145 result = MU_FAILURE;
146 }
147 else
148 {
149 pending_tls_io->bytes = (unsigned char*)malloc(size);
150
151 if (pending_tls_io->bytes == NULL)
152 {
153 LogError("Allocation Failure: Unable to allocate pending list.");
154 free(pending_tls_io);
155 result = MU_FAILURE;
156 }
157 else
158 {
159 pending_tls_io->size = size;
160 pending_tls_io->on_send_complete = on_send_complete;
161 pending_tls_io->callback_context = context;
162 (void)memcpy(pending_tls_io->bytes, buffer, size);
163
164 if (singlylinkedlist_add(list, pending_tls_io) == NULL)
165 {
166 LogError("Failure: Unable to add tls io to pending list.");
167 free(pending_tls_io->bytes);
168 free(pending_tls_io);
169 result = MU_FAILURE;
170 }
171 else
172 {
173 result = 0;
174 }
175 }
176 }
177
178 return result;
179 }
180
181 static void on_underlying_io_open_complete(void *context, IO_OPEN_RESULT open_result)
182 {
183 if (context == NULL)
184 {
185 LogError("Invalid context NULL value passed");
186 }
187 else
188 {
189 TLS_IO_INSTANCE *tls_io_instance = (TLS_IO_INSTANCE *)context;
190
191 if (open_result != IO_OPEN_OK)
192 {
193 xio_close(tls_io_instance->socket_io, NULL, NULL);
194 tls_io_instance->tlsio_state = TLSIO_STATE_NOT_OPEN;
195 indicate_open_complete(tls_io_instance, IO_OPEN_ERROR);
196 }
197 else
198 {
199 tls_io_instance->tlsio_state = TLSIO_STATE_IN_HANDSHAKE;
200 }
201 }
202 }
203
204 static void on_underlying_io_bytes_received(void *context, const unsigned char *buffer, size_t size)
205 {
206 if (context != NULL)
207 {
208 TLS_IO_INSTANCE *tls_io_instance = (TLS_IO_INSTANCE *)context;
209
210 // Dump this on the queue and let dowork deal with it
211 add_pending_operation(tls_io_instance->pending_todecrypt_list, buffer, size, NULL, NULL);
212 }
213 }
214
215 static void on_underlying_io_error(void *context)
216 {
217 if (context == NULL)
218 {
219 LogError("Invalid context NULL value passed");
220 }
221 else
222 {
223 TLS_IO_INSTANCE *tls_io_instance = (TLS_IO_INSTANCE *)context;
224
225 switch (tls_io_instance->tlsio_state)
226 {
227 default:
228 case TLSIO_STATE_NOT_OPEN:
229 case TLSIO_STATE_ERROR:
230 break;
231
232 case TLSIO_STATE_OPENING_UNDERLYING_IO:
233 case TLSIO_STATE_IN_HANDSHAKE:
234 xio_close(tls_io_instance->socket_io, NULL, NULL);
235 tls_io_instance->tlsio_state = TLSIO_STATE_NOT_OPEN;
236 indicate_open_complete(tls_io_instance, IO_OPEN_ERROR);
237 break;
238
239 case TLSIO_STATE_OPEN:
240 indicate_error(tls_io_instance);
241 break;
242 }
243 }
244 }
245
246 static void on_underlying_io_close_complete_during_close(void *context)
247 {
248 if (context == NULL)
249 {
250 LogError("NULL value passed in context");
251 }
252 else
253 {
254 TLS_IO_INSTANCE *tls_io_instance = (TLS_IO_INSTANCE *)context;
255
256 tls_io_instance->tlsio_state = TLSIO_STATE_NOT_OPEN;
257
258 if (tls_io_instance->on_io_close_complete != NULL)
259 {
260 tls_io_instance->on_io_close_complete(tls_io_instance->on_io_close_complete_context);
261 }
262 }
263 }
264
265 static void vblob_append(void *cc, const void *data, size_t len)
266 {
267 int result = BUFFER_append_build((BUFFER_HANDLE)cc, (const unsigned char *)data, len);
268
269 if (result != 0)
270 {
271 // Unfortunately the design does not allow for this error to be passed back
272 LogError("Failed to reallocate pem decode buffer");
273 }
274 }
275
276 VECTOR_HANDLE decode_pem(const void *src, size_t len)
277 {
278 VECTOR_HANDLE pem_list;
279 br_pem_decoder_context pc;
280 pem_object po;
281 //pem_object *pos;
282 const unsigned char *buf;
283 BUFFER_HANDLE bv = NULL;
284 int inobj;
285 int extra_nl;
286 size_t i;
287
288 pem_list = VECTOR_create(sizeof(pem_object));
289
290 if (pem_list == NULL)
291 {
292 LogError("Unable to allocate vectore to decode PEM");
293 }
294 else
295 {
296 br_pem_decoder_init(&pc);
297 buf = src;
298 inobj = 0;
299 po.name = NULL;
300 po.data = NULL;
301 po.data_len = 0;
302 extra_nl = 1;
303
304 while (len > 0) {
305 size_t tlen;
306
307 tlen = br_pem_decoder_push(&pc, buf, len);
308 buf += tlen;
309 len -= tlen;
310 switch (br_pem_decoder_event(&pc)) {
311
312 case BR_PEM_BEGIN_OBJ:
313 inobj = 1;
314
315 if (0 != mallocAndStrcpy_s(&po.name, br_pem_decoder_name(&pc)))
316 {
317 LogError("Unable to allocate memory for certificate name");
318 break;
319 }
320
321 bv = BUFFER_new();
322
323 if (bv == NULL)
324 {
325 LogError("Unable to allocate buffer to decode pem");
326 len = 0;
327 extra_nl = 0;
328 }
329 else
330 {
331 br_pem_decoder_setdest(&pc, vblob_append, bv);
332 }
333 break;
334
335 case BR_PEM_END_OBJ:
336 if (inobj)
337 {
338 po.data = BUFFER_u_char(bv);
339 po.data_len = BUFFER_length(bv);
340 free(bv);
341 bv = NULL;
342 VECTOR_push_back(pem_list, &po, 1);
343 po.name = NULL;
344 po.data = NULL;
345 po.data_len = 0;
346 inobj = 0;
347 }
348 break;
349
350 case BR_PEM_ERROR:
351 LogError("ERROR: invalid PEM encoding");
352 inobj = 1;
353 break;
354 }
355
356 /*
357 * We add an extra newline at the end, in order to
358 * support PEM files that lack the newline on their last
359 * line (this is somewhat invalid, but PEM format is not
360 * standardised and such files do exist in the wild, so
361 * we'd better accept them).
362 */
363 if (len == 0 && extra_nl) {
364 extra_nl = 0;
365 buf = (const unsigned char *)"\n";
366 len = 1;
367 }
368 }
369
370 if (inobj)
371 {
372 LogError("Unable to decode pem");
373
374
375 for (i = 0; i < VECTOR_size(pem_list); i++)
376 {
377 free(((pem_object *)VECTOR_element(pem_list, i))->name);
378 free(((pem_object *)VECTOR_element(pem_list, i))->data);
379 }
380
381 VECTOR_clear(pem_list);
382 free(po.name);
383 po.name = NULL;
384 BUFFER_delete(bv);
385 bv = NULL;
386 pem_list = NULL;
387 }
388 }
389
390 return pem_list;
391 }
392
393 static void free_private_key(private_key *privkey)
394 {
395 switch (privkey->key_type)
396 {
397 case BR_KEYTYPE_RSA:
398 free(privkey->key.rsa.iq);
399 free(privkey->key.rsa.dq);
400 free(privkey->key.rsa.dp);
401 free(privkey->key.rsa.q);
402 free(privkey->key.rsa.p);
403 privkey->key.rsa.iq = NULL;
404 privkey->key.rsa.dq = NULL;
405 privkey->key.rsa.dp = NULL;
406 privkey->key.rsa.q = NULL;
407 privkey->key.rsa.p = NULL;
408 break;
409 case BR_KEYTYPE_EC:
410 free(privkey->key.ec.x);
411 privkey->key.ec.x = NULL;
412 break;
413 default:
414 LogError("Unknown private key type %d", privkey->key_type);
415 }
416 }
417
418 static private_key *decode_key(const unsigned char *buf, size_t len)
419 {
420 br_skey_decoder_context dc;
421 int result;
422 private_key *sk;
423 int curve;
424 uint32_t supp;
425
426 br_skey_decoder_init(&dc);
427 br_skey_decoder_push(&dc, buf, len);
428 result = br_skey_decoder_last_error(&dc);
429
430 if (result != 0)
431 {
432 LogError("Error decoding private key: %d", result);
433 sk = NULL;
434 }
435 else
436 {
437 switch (br_skey_decoder_key_type(&dc))
438 {
439 const br_rsa_private_key *rk;
440 const br_ec_private_key *ek;
441
442 case BR_KEYTYPE_RSA:
443 rk = br_skey_decoder_get_rsa(&dc);
444 if (NULL == (sk = (private_key *)malloc(sizeof *sk)))
445 {
446 LogError("Failed to allocate memory for RSA key structure");
447 }
448 else
449 {
450 memset(sk, 0, sizeof(private_key));
451
452 if (
453 NULL == (sk->key.rsa.p = (unsigned char *)malloc(rk->plen)) ||
454 NULL == (sk->key.rsa.q = (unsigned char *)malloc(rk->plen)) ||
455 NULL == (sk->key.rsa.dp = (unsigned char *)malloc(rk->plen)) ||
456 NULL == (sk->key.rsa.dq = (unsigned char *)malloc(rk->plen)) ||
457 NULL == (sk->key.rsa.iq = (unsigned char *)malloc(rk->plen))
458 )
459 {
460 LogError("Failed to allocate memory for RSA key structure");
461 free_private_key(sk);
462 sk = NULL;
463 }
464 else
465 {
466 sk->key_type = BR_KEYTYPE_RSA;
467 sk->key.rsa.n_bitlen = rk->n_bitlen;
468 sk->key.rsa.plen = rk->plen;
469 sk->key.rsa.qlen = rk->qlen;
470 sk->key.rsa.dplen = rk->dplen;
471 sk->key.rsa.dqlen = rk->dqlen;
472 sk->key.rsa.iqlen = rk->iqlen;
473 memcpy(sk->key.rsa.p, rk->p, rk->plen);
474 memcpy(sk->key.rsa.q, rk->q, rk->qlen);
475 memcpy(sk->key.rsa.dp, rk->dp, rk->dplen);
476 memcpy(sk->key.rsa.dq, rk->dq, rk->dqlen);
477 memcpy(sk->key.rsa.iq, rk->iq, rk->iqlen);
478 }
479 }
480 break;
481
482 case BR_KEYTYPE_EC:
483 ek = br_skey_decoder_get_ec(&dc);
484 if (NULL == (sk = (private_key *)malloc(sizeof *sk)))
485 {
486 LogError("Failed to allocate memory for EC key structure");
487 }
488 else
489 {
490 memset(sk, 0, sizeof(private_key));
491
492 if (NULL == (sk->key.ec.x = (unsigned char *)malloc(ek->xlen)))
493 {
494 LogError("Failed to allocate memory for EC key structure");
495 free(sk);
496 sk = NULL;
497 }
498 else
499 {
500 sk->key_type = BR_KEYTYPE_EC;
501 sk->key.ec.curve = ek->curve;
502 memcpy(sk->key.ec.x, ek->x, ek->xlen);
503 sk->key.ec.xlen = ek->xlen;
504 curve = sk->key.ec.curve;
505 supp = br_ec_get_default()->supported_curves;
506
507 if (curve > 31 || !((supp >> curve) & 1))
508 {
509 LogError("Private key curve (%d) is not supported\n", curve);
510 free_private_key(sk);
511 free(sk);
512 sk = NULL;
513 }
514 }
515 }
516 break;
517
518 default:
519 LogError("Unknown key type: %d", br_skey_decoder_key_type(&dc));
520 sk = NULL;
521 break;
522 }
523 }
524
525 return sk;
526 }
527
528 static private_key *read_private_key(const unsigned char *buf, size_t len)
529 {
530 static const char RSA_PRIVATE_KEY[] = "RSA PRIVATE KEY";
531 static const char EC_PRIVATE_KEY[] = "EC PRIVATE KEY";
532 static const char PRIVATE_KEY[] = "PRIVATE KEY";
533 static const int RSA_PRIVATE_KEY_LENGTH = sizeof(RSA_PRIVATE_KEY) - 1;
534 static const int EC_PRIVATE_KEY_LENGTH = sizeof(EC_PRIVATE_KEY) - 1;
535 static const int PRIVATE_KEY_LENGTH = sizeof(PRIVATE_KEY) - 1;
536
537 private_key *sk = NULL;
538 VECTOR_HANDLE pos; // vector of pem_object
539 pem_object *work;
540 size_t u;
541
542 pos = decode_pem(buf, len);
543
544 if (pos != NULL)
545 {
546
547 for (u = 0; u < VECTOR_size(pos); u++)
548 {
549 work = (pem_object *)VECTOR_element(pos, u);
550
551 if (0 == memcmp(work->name, RSA_PRIVATE_KEY, RSA_PRIVATE_KEY_LENGTH) ||
552 0 == memcmp(work->name, EC_PRIVATE_KEY, EC_PRIVATE_KEY_LENGTH) ||
553 0 == memcmp(work->name, RSA_PRIVATE_KEY, RSA_PRIVATE_KEY_LENGTH))
554 {
555 sk = decode_key(work->data, work->data_len);
556 break;
557 }
558 }
559
560 if (u >= VECTOR_size(pos))
561 {
562 LogError("No private key found in X.509 private key option");
563 sk = NULL;
564 }
565
566 for (u = 0; u < VECTOR_size(pos); u++)
567 {
568 free(((pem_object *)VECTOR_element(pos, u))->name);
569 free(((pem_object *)VECTOR_element(pos, u))->data);
570 }
571
572 VECTOR_destroy(pos);
573 }
574 else
575 {
576 sk = NULL;
577 }
578
579 return sk;
580 }
581
582 static VECTOR_HANDLE read_certificates_string(const char *buf, size_t len)
583 {
584 VECTOR_HANDLE cert_list; //(br_x509_certificate) cert_list = VEC_INIT;
585 VECTOR_HANDLE pem_list;
586 size_t u;
587 int result = 0;
588 static const char CERTIFICATE[] = "CERTIFICATE";
589 static const char X509_CERTIFICATE[] = "X509 CERTIFICATE";
590 static const int CERTIFICATE_LEN = sizeof(CERTIFICATE) - 1;
591 static const int X509_CERTIFICATE_LEN = sizeof(X509_CERTIFICATE) - 1;
592
593 cert_list = VECTOR_create(sizeof(br_x509_certificate));
594
595 if (cert_list == NULL)
596 {
597 LogError("Unable to allocate memory to decode pem strings");
598 VECTOR_destroy(cert_list);
599 cert_list = NULL;
600 }
601 else
602 {
603 pem_list = decode_pem(buf, len);
604
605 if (pem_list == NULL)
606 {
607 LogError("Failed to decode pem");
608 VECTOR_destroy(cert_list);
609 cert_list = NULL;
610 }
611 else
612 {
613 for (u = 0; u < VECTOR_size(pem_list); u++)
614 {
615 if (0 == memcmp(CERTIFICATE, ((pem_object *)VECTOR_element(pem_list, u))->name, CERTIFICATE_LEN) ||
616 0 == memcmp(X509_CERTIFICATE, ((pem_object *)VECTOR_element(pem_list, u))->name, X509_CERTIFICATE_LEN))
617 {
618 br_x509_certificate xc;
619
620 xc.data = ((pem_object *)VECTOR_element(pem_list, u))->data;
621 xc.data_len = ((pem_object *)VECTOR_element(pem_list, u))->data_len;
622 ((pem_object *)VECTOR_element(pem_list, u))->data = NULL;
623 ((pem_object *)VECTOR_element(pem_list, u))->data_len = 0;
624 free(((pem_object *)VECTOR_element(pem_list, u))->name);
625 ((pem_object *)VECTOR_element(pem_list, u))->name = NULL;
626
627 result = VECTOR_push_back(cert_list, &xc, 1);
628
629 if (result != 0)
630 {
631 LogError("Failed to add certificate to vector");
632 break;
633 }
634 }
635 else
636 {
637 LogError("Unable to determine the certificate type");
638 }
639 }
640
641 // If we enter this loop something failed
642 for (; u < VECTOR_size(pem_list); u++)
643 {
644 free(((pem_object *)VECTOR_element(pem_list, u))->name);
645 free(((pem_object *)VECTOR_element(pem_list, u))->data);
646 }
647
648 VECTOR_destroy(pem_list);
649
650 if (0 == VECTOR_size(cert_list))
651 {
652 fprintf(stderr, "No certificate in string");
653 result = MU_FAILURE;
654 }
655
656 if (result != 0)
657 {
658 for (u = 0; u < VECTOR_size(cert_list); u++)
659 {
660 free(((br_x509_certificate*)VECTOR_element(cert_list, u))->data);
661 }
662
663 VECTOR_destroy(cert_list);
664 cert_list = NULL;
665 }
666 }
667 }
668
669 return cert_list;
670 }
671
672 static void dn_append(void *ctx, const void *buf, size_t len)
673 {
674 if (0 != (BUFFER_append_build((BUFFER_HANDLE)ctx, buf, len)))
675 {
676 // Design does not allow this error to be reported to caller
677 LogError("Failed to append data");
678 }
679 }
680
681 void free_ta_contents(br_x509_trust_anchor *ta)
682 {
683 free(ta->dn.data);
684 switch (ta->pkey.key_type)
685 {
686 case BR_KEYTYPE_RSA:
687 free(ta->pkey.key.rsa.n);
688 free(ta->pkey.key.rsa.e);
689 ta->pkey.key.rsa.n = NULL;
690 ta->pkey.key.rsa.e = NULL;
691 break;
692 case BR_KEYTYPE_EC:
693 free(ta->pkey.key.ec.q);
694 ta->pkey.key.ec.q = NULL;
695 break;
696 }
697 }
698
699 void free_certificates(br_x509_certificate *certs, size_t num)
700 {
701 size_t u;
702
703 for (u = 0; u < num; u ++) {
704 free(certs[u].data);
705 certs[u].data = NULL;
706 }
707 }
708
709 static int certificate_to_trust_anchor(br_x509_certificate *xc, br_x509_trust_anchor *ta)
710 {
711 br_x509_decoder_context dc;
712 br_x509_pkey *pk;
713 BUFFER_HANDLE vdn;
714 //br_x509_trust_anchor *ta;
715 int result = 0;
716
717 vdn = BUFFER_new();
718
719 if (NULL == vdn)
720 {
721 LogError("Failed to allocate memory to decode x509 certificate");
722 result = MU_FAILURE;
723 }
724 else
725 {
726 memset(ta, 0, sizeof(br_x509_trust_anchor));
727 br_x509_decoder_init(&dc, dn_append, vdn);
728 br_x509_decoder_push(&dc, xc->data, xc->data_len);
729 pk = br_x509_decoder_get_pkey(&dc);
730
731 if (pk == NULL)
732 {
733 LogError("ERROR: CA decoding failed with error %d", br_x509_decoder_last_error(&dc));
734 BUFFER_delete(vdn);
735 }
736 else
737 {
738 ta->dn.data = BUFFER_u_char(vdn);
739 ta->dn.len = BUFFER_length(vdn);
740 free(vdn);
741 vdn = NULL;
742 ta->flags = 0;
743
744 if (br_x509_decoder_isCA(&dc))
745 {
746 ta->flags |= BR_X509_TA_CA;
747 }
748
749 switch (pk->key_type)
750 {
751 case BR_KEYTYPE_RSA:
752 ta->pkey.key_type = BR_KEYTYPE_RSA;
753 ta->pkey.key.rsa.nlen = pk->key.rsa.nlen;
754 ta->pkey.key.rsa.elen = pk->key.rsa.elen;
755
756 if (NULL == (ta->pkey.key.rsa.n = (unsigned char *)malloc(ta->pkey.key.rsa.nlen)) ||
757 NULL == ( ta->pkey.key.rsa.e = (unsigned char *)malloc(ta->pkey.key.rsa.elen)))
758 {
759 LogError("Unable to allocate memory");
760 free_ta_contents(ta);
761 result = MU_FAILURE;
762 }
763 else
764 {
765 memcpy(ta->pkey.key.rsa.n, pk->key.rsa.n, ta->pkey.key.rsa.nlen);
766 memcpy(ta->pkey.key.rsa.e, pk->key.rsa.e, ta->pkey.key.rsa.elen);
767 result = 0;
768 }
769 break;
770 case BR_KEYTYPE_EC:
771 ta->pkey.key_type = BR_KEYTYPE_EC;
772 ta->pkey.key.ec.curve = pk->key.ec.curve;
773 ta->pkey.key.ec.qlen = pk->key.ec.qlen;
774
775 if (NULL == (ta->pkey.key.ec.q = (unsigned char *)malloc(ta->pkey.key.ec.qlen)))
776 {
777 LogError("Unable to allocate memory");
778 free_ta_contents(ta);
779 result = MU_FAILURE;
780 }
781 else
782 {
783 memcpy(ta->pkey.key.ec.q, pk->key.ec.q, ta->pkey.key.ec.qlen);
784 result = 0;
785 }
786 break;
787 default:
788 fprintf(stderr, "ERROR: unsupported public key type in CA\n");
789 free_ta_contents(ta);
790 result = MU_FAILURE;
791 }
792 }
793 }
794
795 return result;
796 }
797
798 static size_t get_trusted_anchors(const char *certificates, size_t len, br_x509_trust_anchor *anchOut[])
799 {
800 // Converts a PEM certificate in a string into the format required by BearSSL
801 VECTOR_HANDLE xcs;
802 br_x509_trust_anchor work;
803 br_x509_trust_anchor *anchArray;
804 size_t u;
805 size_t v;
806 size_t num;
807 int result;
808
809 xcs = read_certificates_string(certificates, len);
810 num = VECTOR_size(xcs);
811
812 if (VECTOR_size(xcs) == 0)
813 {
814 LogError("No certificates found in string");
815 }
816 else
817 {
818 size_t malloc_size = safe_multiply_size_t(sizeof(br_x509_trust_anchor), num);
819 if (malloc_size == SIZE_MAX)
820 {
821 LogError("Invalid buffer size for trustedanchors");
822 anchArray = NULL;
823 }
824 else
825 {
826 anchArray = (br_x509_trust_anchor*)malloc(malloc_size);
827 }
828
829 if (anchArray == NULL)
830 {
831 LogError("Memory allocation for trust anchors failed");
832 }
833 else
834 {
835 *anchOut = anchArray;
836
837 for (u = 0; u < num; u++)
838 {
839 result = certificate_to_trust_anchor((br_x509_certificate *)VECTOR_element(xcs, u), &work);
840
841 if (result != 0)
842 {
843 for (v = 0; v < u; v++)
844 {
845 free_ta_contents((anchOut[u]));
846 }
847
848 free(anchArray);
849 *anchOut = NULL;
850 num = 0;
851 break;
852 }
853
854 anchArray[u] = work;
855 }
856 }
857 }
858
859 free_certificates((br_x509_certificate *)VECTOR_front(xcs), VECTOR_size(xcs));
860 VECTOR_destroy(xcs);
861
862 return num;
863 }
864
865 static int get_cert_signer_algo(br_x509_certificate *xc)
866 {
867 br_x509_decoder_context dc;
868 int result;
869
870 br_x509_decoder_init(&dc, 0, 0);
871 br_x509_decoder_push(&dc, xc->data, xc->data_len);
872 result = br_x509_decoder_last_error(&dc);
873
874 if (result != 0)
875 {
876 LogError("Failed to get signer algorithm %d\n", result);
877 result = 0;
878 }
879 else
880 {
881 result = br_x509_decoder_get_signer_key_type(&dc);
882 }
883
884 return result;
885 }
886
887 CONCRETE_IO_HANDLE tlsio_bearssl_create(void *io_create_parameters)
888 {
889 TLSIO_CONFIG *tls_io_config = (TLSIO_CONFIG *)io_create_parameters;
890 TLS_IO_INSTANCE *result;
891
892 if (tls_io_config == NULL)
893 {
894 LogError("NULL tls_io_config");
895 result = NULL;
896 }
897 else
898 {
899 /* Codes_SRS_TLSIO_BEAR_OS5_TLS_99_006: [ The tlsio_bearssl_create shall return NULL if allocating memory for TLS_IO_INSTANCE failed. ]*/
900 result = calloc(1, sizeof(TLS_IO_INSTANCE));
901 if (result != NULL)
902 {
903 SOCKETIO_CONFIG socketio_config;
904 const IO_INTERFACE_DESCRIPTION *underlying_io_interface;
905 void *io_interface_parameters;
906
907 if (tls_io_config->underlying_io_interface != NULL)
908 {
909 underlying_io_interface = tls_io_config->underlying_io_interface;
910 io_interface_parameters = tls_io_config->underlying_io_parameters;
911 }
912 else
913 {
914 socketio_config.hostname = tls_io_config->hostname;
915 socketio_config.port = tls_io_config->port;
916 socketio_config.accepted_socket = NULL;
917 underlying_io_interface = socketio_get_interface_description();
918 io_interface_parameters = &socketio_config;
919 }
920
921 if (underlying_io_interface == NULL)
922 {
923 free(result);
924 result = NULL;
925 LogError("Failed getting socket IO interface description.");
926 }
927 else
928 {
929 mallocAndStrcpy_s(&result->hostname, tls_io_config->hostname);
930 if (result->hostname == NULL)
931 {
932 free(result);
933 result = NULL;
934 }
935 else
936 {
937 result->socket_io = xio_create(underlying_io_interface, io_interface_parameters);
938 if (result->socket_io == NULL)
939 {
940 LogError("socket xio create failed");
941 free(result->hostname);
942 free(result);
943 result = NULL;
944 }
945 else
946 {
947 result->pending_toencrypt_list = singlylinkedlist_create();
948 result->pending_todecrypt_list = singlylinkedlist_create();
949 result->trusted_certificates = NULL;
950 result->x509_certificate = NULL;
951 result->x509_private_key = NULL;
952 result->tas = NULL;
953 result->x509_cert = NULL;
954 result->x509_pk = NULL;
955 result->tlsio_state = TLSIO_STATE_NOT_OPEN;
956 }
957 }
958 }
959 }
960 }
961
962 return result;
963 }
964
965 void tlsio_bearssl_destroy(CONCRETE_IO_HANDLE tls_io)
966 {
967 size_t i;
968 LIST_ITEM_HANDLE first_pending_io;
969
970 if (tls_io == NULL)
971 {
972 LogError("NULL handle");
973 }
974 else
975 {
976 TLS_IO_INSTANCE *tls_io_instance = (TLS_IO_INSTANCE *)tls_io;
977
978 if (tls_io_instance->socket_io_read_bytes != NULL)
979 {
980 free(tls_io_instance->socket_io_read_bytes);
981 tls_io_instance->socket_io_read_bytes = NULL;
982 }
983
984 xio_destroy(tls_io_instance->socket_io);
985
986 first_pending_io = singlylinkedlist_get_head_item(tls_io_instance->pending_toencrypt_list);
987
988 while (first_pending_io != NULL)
989 {
990 PENDING_TLS_IO *pending_tls_io = (PENDING_TLS_IO *)singlylinkedlist_item_get_value(first_pending_io);
991 if (pending_tls_io != NULL)
992 {
993 free(pending_tls_io->bytes);
994 free(pending_tls_io);
995 }
996
997 (void)singlylinkedlist_remove(tls_io_instance->pending_toencrypt_list, first_pending_io);
998 first_pending_io = singlylinkedlist_get_head_item(tls_io_instance->pending_toencrypt_list);
999 }
1000
1001 singlylinkedlist_destroy(tls_io_instance->pending_toencrypt_list);
1002 tls_io_instance->pending_toencrypt_list = NULL;
1003
1004 first_pending_io = singlylinkedlist_get_head_item(tls_io_instance->pending_todecrypt_list);
1005
1006 while (first_pending_io != NULL)
1007 {
1008 PENDING_TLS_IO *pending_tls_io = (PENDING_TLS_IO *)singlylinkedlist_item_get_value(first_pending_io);
1009 if (pending_tls_io != NULL)
1010 {
1011 free(pending_tls_io->bytes);
1012 free(pending_tls_io);
1013 }
1014
1015 (void)singlylinkedlist_remove(tls_io_instance->pending_todecrypt_list, first_pending_io);
1016 first_pending_io = singlylinkedlist_get_head_item(tls_io_instance->pending_todecrypt_list);
1017 }
1018
1019 singlylinkedlist_destroy(tls_io_instance->pending_todecrypt_list);
1020 tls_io_instance->pending_todecrypt_list = NULL;
1021
1022 if (tls_io_instance->hostname != NULL)
1023 {
1024 free(tls_io_instance->hostname);
1025 tls_io_instance->hostname = NULL;
1026 }
1027 if (tls_io_instance->trusted_certificates != NULL)
1028 {
1029 free(tls_io_instance->trusted_certificates);
1030 tls_io_instance->trusted_certificates = NULL;
1031
1032 if (tls_io_instance->tas != NULL)
1033 {
1034 // Free the memory if it has been previously allocated
1035 for (i = 0; i < tls_io_instance->ta_count; i++)
1036 {
1037 free_ta_contents(&(tls_io_instance->tas[i]));
1038 }
1039
1040 free(tls_io_instance->tas);
1041 tls_io_instance->tas = NULL;
1042 tls_io_instance->ta_count = 0;
1043 }
1044
1045 }
1046 if (tls_io_instance->x509_certificate != NULL)
1047 {
1048 free(tls_io_instance->x509_certificate);
1049 tls_io_instance->x509_certificate = NULL;
1050
1051 if (tls_io_instance->x509_cert != NULL)
1052 {
1053 free_certificates(tls_io_instance->x509_cert, tls_io_instance->x509_cert_len);
1054 free(tls_io_instance->x509_cert);
1055 tls_io_instance->x509_cert = NULL;
1056 }
1057 }
1058 if (tls_io_instance->x509_private_key != NULL)
1059 {
1060 free(tls_io_instance->x509_private_key);
1061 tls_io_instance->x509_private_key = NULL;
1062
1063 if (tls_io_instance->x509_pk != NULL)
1064 {
1065 free_private_key(tls_io_instance->x509_pk);
1066 free(tls_io_instance->x509_pk);
1067 tls_io_instance->x509_pk = NULL;
1068 }
1069 }
1070
1071 free(tls_io);
1072 }
1073 }
1074
1075 int tlsio_bearssl_open(CONCRETE_IO_HANDLE tls_io, ON_IO_OPEN_COMPLETE on_io_open_complete, void *on_io_open_complete_context, ON_BYTES_RECEIVED on_bytes_received, void *on_bytes_received_context, ON_IO_ERROR on_io_error, void *on_io_error_context)
1076 {
1077 int result = 0;
1078 unsigned int cert_signer_algo;
1079
1080 if (tls_io == NULL)
1081 {
1082 LogError("NULL tls_io");
1083 result = MU_FAILURE;
1084 }
1085 else
1086 {
1087 TLS_IO_INSTANCE *tls_io_instance = (TLS_IO_INSTANCE *)tls_io;
1088
1089 if (tls_io_instance->tlsio_state != TLSIO_STATE_NOT_OPEN)
1090 {
1091 LogError("TLS already open");
1092 result = MU_FAILURE;
1093 }
1094 else
1095 {
1096
1097 tls_io_instance->on_bytes_received = on_bytes_received;
1098 tls_io_instance->on_bytes_received_context = on_bytes_received_context;
1099
1100 tls_io_instance->on_io_open_complete = on_io_open_complete;
1101 tls_io_instance->on_io_open_complete_context = on_io_open_complete_context;
1102
1103 tls_io_instance->on_io_error = on_io_error;
1104 tls_io_instance->on_io_error_context = on_io_error_context;
1105
1106 tls_io_instance->tlsio_state = TLSIO_STATE_OPENING_UNDERLYING_IO;
1107
1108 if (tls_io_instance->ta_count == 0)
1109 {
1110 LogError("Trusted certificates are required but missing");
1111 result = MU_FAILURE;
1112 }
1113 else
1114 {
1115 if ((tls_io_instance->x509_pk == NULL && tls_io_instance->x509_cert != NULL) ||
1116 (tls_io_instance->x509_pk != NULL && tls_io_instance->x509_cert == NULL))
1117 {
1118 LogError("X.509 certificate and private key need to be both present or both absent");
1119 result = MU_FAILURE;
1120 }
1121 else
1122 {
1123 br_ssl_client_init_full(&tls_io_instance->sc, &tls_io_instance->xc, tls_io_instance->tas, tls_io_instance->ta_count);
1124 br_ssl_engine_set_buffer(&tls_io_instance->sc.eng, tls_io_instance->iobuf, sizeof(tls_io_instance->iobuf), 1);
1125 br_ssl_client_reset(&tls_io_instance->sc, tls_io_instance->hostname, 0);
1126
1127 if (tls_io_instance->x509_cert != NULL)
1128 {
1129 switch (tls_io_instance->x509_pk->key_type)
1130 {
1131 case BR_KEYTYPE_RSA:
1132 br_ssl_client_set_single_rsa(&tls_io_instance->sc,
1133 tls_io_instance->x509_cert,
1134 tls_io_instance->x509_cert_len,
1135 &tls_io_instance->x509_pk->key.rsa,
1136 br_rsa_pkcs1_sign_get_default());
1137 break;
1138 case BR_KEYTYPE_EC:
1139 cert_signer_algo = get_cert_signer_algo(tls_io_instance->x509_cert);
1140
1141 if (cert_signer_algo == 0)
1142 {
1143 result = MU_FAILURE;
1144 }
1145 else
1146 {
1147 br_ssl_client_set_single_ec(&tls_io_instance->sc,
1148 tls_io_instance->x509_cert,
1149 tls_io_instance->x509_cert_len,
1150 &tls_io_instance->x509_pk->key.ec,
1151 BR_KEYTYPE_KEYX | BR_KEYTYPE_SIGN,
1152 cert_signer_algo,
1153 br_ec_get_default(),
1154 br_ecdsa_sign_asn1_get_default());
1155 }
1156 break;
1157 default:
1158 LogError("Unrecognized private key type");
1159 tls_io_instance->tlsio_state = TLSIO_STATE_NOT_OPEN;
1160 result = MU_FAILURE;
1161 }
1162 }
1163
1164 if (result == 0)
1165 {
1166 if (xio_open(tls_io_instance->socket_io, on_underlying_io_open_complete, tls_io_instance, on_underlying_io_bytes_received, tls_io_instance, on_underlying_io_error, tls_io_instance) != 0)
1167 {
1168
1169 LogError("Underlying IO open failed");
1170 tls_io_instance->tlsio_state = TLSIO_STATE_NOT_OPEN;
1171 result = MU_FAILURE;
1172 }
1173 }
1174 }
1175 }
1176 }
1177 }
1178
1179 return result;
1180 }
1181
1182 int tlsio_bearssl_close(CONCRETE_IO_HANDLE tls_io, ON_IO_CLOSE_COMPLETE on_io_close_complete, void *callback_context)
1183 {
1184 int result = 0;
1185
1186 if (tls_io == NULL)
1187 {
1188 LogError("NULL tls_io");
1189 result = MU_FAILURE;
1190 }
1191 else
1192 {
1193 TLS_IO_INSTANCE *tls_io_instance = (TLS_IO_INSTANCE *)tls_io;
1194
1195 if ((tls_io_instance->tlsio_state == TLSIO_STATE_NOT_OPEN) ||
1196 (tls_io_instance->tlsio_state == TLSIO_STATE_CLOSING))
1197 {
1198 LogError("Invalid state");
1199 result = MU_FAILURE;
1200 }
1201 else
1202 {
1203 tls_io_instance->on_io_close_complete = on_io_close_complete;
1204 tls_io_instance->on_io_close_complete_context = callback_context;
1205 tls_io_instance->tlsio_state = TLSIO_STATE_CLOSING;
1206
1207 xio_close(tls_io_instance->socket_io, on_underlying_io_close_complete_during_close, tls_io_instance);
1208 result = 0;
1209 }
1210 }
1211
1212 return result;
1213 }
1214
1215 int tlsio_bearssl_send(CONCRETE_IO_HANDLE tls_io, const void *buffer, size_t size, ON_SEND_COMPLETE on_send_complete, void *callback_context)
1216 {
1217 int result;
1218
1219 if ((tls_io == NULL) ||
1220 (buffer == NULL) ||
1221 (size == 0))
1222 {
1223 // Invalid arguments
1224 LogError("Invalid argument: tls_io is NULL");
1225 result = MU_FAILURE;
1226 }
1227 else
1228 {
1229 TLS_IO_INSTANCE *tls_io_instance = (TLS_IO_INSTANCE *)tls_io;
1230
1231 if (tls_io_instance->tlsio_state != TLSIO_STATE_OPEN &&
1232 tls_io_instance->tlsio_state != TLSIO_STATE_IN_HANDSHAKE &&
1233 tls_io_instance->tlsio_state != TLSIO_STATE_OPENING_UNDERLYING_IO)
1234 {
1235 LogError("TLS is not open");
1236 result = MU_FAILURE;
1237 }
1238 else
1239 {
1240 if (add_pending_operation(tls_io_instance->pending_toencrypt_list, buffer, size, on_send_complete, callback_context) != 0)
1241 {
1242 LogError("Failure: add_pending_io failed.");
1243 result = MU_FAILURE;
1244 }
1245 else
1246 {
1247 result = 0;
1248 }
1249 }
1250 }
1251
1252 return result;
1253 }
1254
1255 void tlsio_bearssl_dowork(CONCRETE_IO_HANDLE tls_io)
1256 {
1257 unsigned char *buffer;
1258 size_t bufferLen;
1259 unsigned long bearResult;
1260 int lasterr;
1261
1262 if (tls_io != NULL)
1263 {
1264 TLS_IO_INSTANCE *tls_io_instance = (TLS_IO_INSTANCE *)tls_io;
1265
1266 if (tls_io_instance->tlsio_state == TLSIO_STATE_NOT_OPEN)
1267 {
1268 // Not open do nothing
1269 }
1270 else
1271 {
1272 if (tls_io_instance->tlsio_state != TLSIO_STATE_OPENING_UNDERLYING_IO && tls_io_instance->tlsio_state != TLSIO_STATE_CLOSING)
1273 {
1274 bearResult = br_ssl_engine_current_state(&tls_io_instance->sc.eng);
1275
1276 if (bearResult & BR_SSL_SENDREC)
1277 {
1278 // The engine has data to send
1279 buffer = br_ssl_engine_sendrec_buf(&tls_io_instance->sc.eng, &bufferLen);
1280
1281 if (xio_send(tls_io_instance->socket_io, buffer, bufferLen, NULL, NULL) != 0)
1282 {
1283 LogError("Error in xio_send.");
1284 indicate_error(tls_io_instance);
1285 }
1286 else
1287 {
1288 br_ssl_engine_sendrec_ack(&tls_io_instance->sc.eng, bufferLen);
1289 }
1290 }
1291
1292 bearResult = br_ssl_engine_current_state(&tls_io_instance->sc.eng);
1293
1294 if (bearResult & BR_SSL_RECVREC)
1295 {
1296 // The engine can accept data from the peer if there is any
1297 LIST_ITEM_HANDLE first_pending_io = singlylinkedlist_get_head_item(tls_io_instance->pending_todecrypt_list);
1298
1299 if (first_pending_io != NULL)
1300 {
1301 PENDING_TLS_IO *pending_tls_io = (PENDING_TLS_IO*)singlylinkedlist_item_get_value(first_pending_io);
1302
1303 if (pending_tls_io != NULL)
1304 {
1305 buffer = br_ssl_engine_recvrec_buf(&tls_io_instance->sc.eng, &bufferLen);
1306
1307 if (bufferLen == 0)
1308 {
1309 LogError("Zero length buffer returned by BearSSL");
1310 indicate_error(tls_io_instance);
1311 }
1312 else
1313 {
1314 if (pending_tls_io->size < bufferLen)
1315 {
1316 bufferLen = pending_tls_io->size;
1317 }
1318 memcpy(buffer, pending_tls_io->bytes, bufferLen);
1319 br_ssl_engine_recvrec_ack(&tls_io_instance->sc.eng, bufferLen);
1320
1321 if (bufferLen < pending_tls_io->size)
1322 {
1323 pending_tls_io->size -= bufferLen;
1324 memcpy(pending_tls_io->bytes, pending_tls_io->bytes + bufferLen, pending_tls_io->size);
1325 }
1326 else
1327 {
1328 free(pending_tls_io->bytes);
1329 free(pending_tls_io);
1330 (void)singlylinkedlist_remove(tls_io_instance->pending_todecrypt_list, first_pending_io);
1331 }
1332 }
1333 }
1334 }
1335 }
1336
1337 bearResult = br_ssl_engine_current_state(&tls_io_instance->sc.eng);
1338
1339 if (bearResult & BR_SSL_SENDAPP)
1340 {
1341 if (tls_io_instance->tlsio_state == TLSIO_STATE_IN_HANDSHAKE)
1342 {
1343 tls_io_instance->tlsio_state = TLSIO_STATE_OPEN;
1344 indicate_open_complete(tls_io_instance, IO_OPEN_OK);
1345 }
1346
1347 // Engine is ready for application data - send it if we have any
1348 LIST_ITEM_HANDLE first_pending_io = singlylinkedlist_get_head_item(tls_io_instance->pending_toencrypt_list);
1349
1350 if (first_pending_io != NULL)
1351 {
1352 PENDING_TLS_IO *pending_tls_io = (PENDING_TLS_IO*)singlylinkedlist_item_get_value(first_pending_io);
1353
1354 if (pending_tls_io != NULL)
1355 {
1356 buffer = br_ssl_engine_sendapp_buf(&tls_io_instance->sc.eng, &bufferLen);
1357
1358 if (pending_tls_io->size < bufferLen)
1359 {
1360 bufferLen = pending_tls_io->size;
1361 }
1362 memcpy(buffer, pending_tls_io->bytes, bufferLen);
1363 br_ssl_engine_sendapp_ack(&tls_io_instance->sc.eng, bufferLen);
1364
1365 if (bufferLen < pending_tls_io->size)
1366 {
1367 pending_tls_io->size -= bufferLen;
1368 memcpy(pending_tls_io->bytes, pending_tls_io->bytes + bufferLen, pending_tls_io->size);
1369 }
1370 else
1371 {
1372 pending_tls_io->on_send_complete(pending_tls_io->callback_context, IO_SEND_OK);
1373 free(pending_tls_io->bytes);
1374 free(pending_tls_io);
1375 (void)singlylinkedlist_remove(tls_io_instance->pending_toencrypt_list, first_pending_io);
1376 br_ssl_engine_flush(&tls_io_instance->sc.eng, 0);
1377 }
1378 }
1379 }
1380
1381 }
1382
1383 bearResult = br_ssl_engine_current_state(&tls_io_instance->sc.eng);
1384
1385 if (bearResult & BR_SSL_RECVAPP)
1386 {
1387 // Application data is waiting to be forwarded
1388 buffer = br_ssl_engine_recvapp_buf(&tls_io_instance->sc.eng, &bufferLen);
1389 tls_io_instance->on_bytes_received(tls_io_instance->on_bytes_received_context, buffer, bufferLen);
1390 br_ssl_engine_recvapp_ack(&tls_io_instance->sc.eng, bufferLen);
1391 }
1392 }
1393
1394 if ((lasterr = br_ssl_engine_last_error(&tls_io_instance->sc.eng)) != 0)
1395 {
1396 LogError("BearSSL reported an error: %d", lasterr);
1397 indicate_error(tls_io_instance);
1398 }
1399
1400 xio_dowork(tls_io_instance->socket_io);
1401 }
1402 }
1403 }
1404
1405 // This function will clone an option given by name and value
1406 static void *tlsio_bearssl_CloneOption(const char *name, const void *value)
1407 {
1408 void *result = NULL;
1409 if (name == NULL || value == NULL)
1410 {
1411 LogError("invalid parameter detected: const char* name=%p, const void* value=%p", name, value);
1412 result = NULL;
1413 }
1414 else
1415 {
1416 if (strcmp(name, OPTION_UNDERLYING_IO_OPTIONS) == 0)
1417 {
1418 result = (void*)OptionHandler_Clone((OPTIONHANDLER_HANDLE)value);
1419 }
1420 else if (strcmp(name, OPTION_TRUSTED_CERT) == 0)
1421 {
1422 if (mallocAndStrcpy_s((char **)&result, value) != 0)
1423 {
1424 LogError("unable to mallocAndStrcpy_s TrustedCerts value");
1425 result = NULL;
1426 }
1427 else
1428 {
1429 // return as is
1430 }
1431 }
1432 else if (strcmp(name, SU_OPTION_X509_CERT) == 0)
1433 {
1434 if (mallocAndStrcpy_s((char**)&result, value) != 0)
1435 {
1436 LogError("unable to mallocAndStrcpy_s x509certificate value");
1437 result = NULL;
1438 }
1439 else
1440 {
1441 // return as is
1442 }
1443 }
1444 else if (strcmp(name, SU_OPTION_X509_PRIVATE_KEY) == 0)
1445 {
1446 if (mallocAndStrcpy_s((char**)&result, value) != 0)
1447 {
1448 LogError("unable to mallocAndStrcpy_s x509privatekey value");
1449 result = NULL;
1450 }
1451 else
1452 {
1453 // return as is
1454 }
1455 }
1456 else if (strcmp(name, OPTION_X509_ECC_CERT) == 0)
1457 {
1458 if (mallocAndStrcpy_s((char**)&result, value) != 0)
1459 {
1460 LogError("unable to mallocAndStrcpy_s x509EccCertificate value");
1461 result = NULL;
1462 }
1463 else
1464 {
1465 // return as is
1466 }
1467 }
1468 else if (strcmp(name, OPTION_X509_ECC_KEY) == 0)
1469 {
1470 if (mallocAndStrcpy_s((char**)&result, value) != 0)
1471 {
1472 LogError("unable to mallocAndStrcpy_s x509EccKey value");
1473 result = NULL;
1474 }
1475 else
1476 {
1477 // return as is
1478 }
1479 }
1480 else
1481 {
1482 LogError("not handled option : %s", name);
1483 result = NULL;
1484 }
1485 }
1486
1487 return result;
1488 }
1489
1490 // This function destroys an option previously created
1491 static void tlsio_bearssl_DestroyOption(const char *name, const void *value)
1492 {
1493 // Since all options for this layer are actually string copies., disposing of one is just a matter calling free
1494 if (name == NULL || value == NULL)
1495 {
1496 LogError("invalid parameter detected: const char* name=%p, const void* value=%p", name, value);
1497 }
1498 else
1499 {
1500 if (
1501 (strcmp(name, OPTION_TRUSTED_CERT) == 0) ||
1502 (strcmp(name, SU_OPTION_X509_CERT) == 0) ||
1503 (strcmp(name, SU_OPTION_X509_PRIVATE_KEY) == 0) ||
1504 (strcmp(name, OPTION_X509_ECC_CERT) == 0) ||
1505 (strcmp(name, OPTION_X509_ECC_KEY) == 0)
1506 )
1507 {
1508 free((void*)value);
1509 }
1510 else if (strcmp(name, OPTION_UNDERLYING_IO_OPTIONS) == 0)
1511 {
1512 OptionHandler_Destroy((OPTIONHANDLER_HANDLE)value);
1513 }
1514 else
1515 {
1516 LogError("not handled option : %s", name);
1517 }
1518 }
1519 }
1520
1521 int tlsio_bearssl_setoption(CONCRETE_IO_HANDLE tls_io, const char *optionName, const void *value)
1522 {
1523 int result = 0;
1524 size_t i;
1525 VECTOR_HANDLE certs;
1526
1527 if (tls_io == NULL || optionName == NULL)
1528 {
1529 result = MU_FAILURE;
1530 }
1531 else
1532 {
1533 TLS_IO_INSTANCE *tls_io_instance = (TLS_IO_INSTANCE *)tls_io;
1534
1535 if (strcmp(OPTION_TRUSTED_CERT, optionName) == 0)
1536 {
1537 if (tls_io_instance->tas != NULL)
1538 {
1539 // Free the memory if it has been previously allocated
1540 for (i = 0; i < tls_io_instance->ta_count; i++)
1541 {
1542 free_ta_contents(&(tls_io_instance->tas[i]));
1543 }
1544
1545 free(tls_io_instance->tas);
1546 tls_io_instance->tas = NULL;
1547 tls_io_instance->ta_count = 0;
1548 free(tls_io_instance->trusted_certificates);
1549 tls_io_instance->trusted_certificates = NULL;
1550 }
1551
1552 if (value != NULL)
1553 {
1554 mallocAndStrcpy_s(&tls_io_instance->trusted_certificates, (const char *)value);
1555
1556 if (tls_io_instance->trusted_certificates == NULL)
1557 {
1558 LogError("Failed to allocate memory for certificate string");
1559 result = MU_FAILURE;
1560 }
1561 else
1562 {
1563 tls_io_instance->ta_count = get_trusted_anchors((const char*)value, strlen((const char *)value) + 1, &tls_io_instance->tas);
1564
1565 if (tls_io_instance->ta_count == 0)
1566 {
1567 LogError("Failed to extract certificate from option value");
1568 result = MU_FAILURE;
1569 }
1570 else
1571 {
1572 result = 0;
1573 }
1574 }
1575 }
1576 }
1577 else if (strcmp(optionName, OPTION_UNDERLYING_IO_OPTIONS) == 0)
1578 {
1579 if (OptionHandler_FeedOptions((OPTIONHANDLER_HANDLE)value, (void*)tls_io_instance->socket_io) != OPTIONHANDLER_OK)
1580 {
1581 LogError("failed feeding options to underlying I/O instance");
1582 result = MU_FAILURE;
1583 }
1584 else
1585 {
1586 result = 0;
1587 }
1588 }
1589 else if (strcmp(SU_OPTION_X509_CERT, optionName) == 0 || strcmp(OPTION_X509_ECC_CERT, optionName) == 0)
1590 {
1591 if (tls_io_instance->x509_certificate != NULL)
1592 {
1593 // Free the memory if it has been previously allocated
1594 free(tls_io_instance->x509_certificate);
1595 tls_io_instance->x509_certificate = NULL;
1596 }
1597
1598 if (mallocAndStrcpy_s(&tls_io_instance->x509_certificate, (const char *)value) != 0)
1599 {
1600 LogError("unable to mallocAndStrcpy_s on certificate");
1601 result = MU_FAILURE;
1602 }
1603 else
1604 {
1605 if (tls_io_instance->x509_cert != NULL)
1606 {
1607 free_certificates(tls_io_instance->x509_cert, tls_io_instance->x509_cert_len);
1608 free(tls_io_instance->x509_cert);
1609 tls_io_instance->x509_cert = NULL;
1610 }
1611
1612 certs = read_certificates_string(value, strlen(value));
1613 tls_io_instance->x509_cert_len = VECTOR_size(certs);
1614 tls_io_instance->x509_cert = VECTOR_front(certs);
1615 free(certs);
1616 result = 0;
1617 }
1618 }
1619 else if (strcmp(SU_OPTION_X509_PRIVATE_KEY, optionName) == 0 || strcmp(OPTION_X509_ECC_KEY, optionName) == 0)
1620 {
1621 if (tls_io_instance->x509_private_key != NULL)
1622 {
1623 // Free the memory if it has been previously allocated
1624 free(tls_io_instance->x509_private_key);
1625 tls_io_instance->x509_private_key = NULL;
1626 }
1627
1628 if (mallocAndStrcpy_s(&tls_io_instance->x509_private_key, (const char *)value) != 0)
1629 {
1630 LogError("unable to mallocAndStrcpy_s on private key");
1631 result = MU_FAILURE;
1632 }
1633 else
1634 {
1635 if (tls_io_instance->x509_pk != NULL)
1636 {
1637 free_private_key(tls_io_instance->x509_pk);
1638 free(tls_io_instance->x509_pk);
1639 tls_io_instance->x509_pk = NULL;
1640 }
1641
1642 tls_io_instance->x509_pk = read_private_key(value, strlen(value));
1643 result = 0;
1644 }
1645 }
1646 else if (strcmp(optionName, OPTION_SET_TLS_RENEGOTIATION) == 0)
1647 {
1648 // No need to do anything for BearSSL
1649 result = 0;
1650 }
1651 else
1652 {
1653 // tls_io_instance->socket_io is never NULL
1654 result = xio_setoption(tls_io_instance->socket_io, optionName, value);
1655 }
1656 }
1657
1658 return result;
1659 }
1660
1661 OPTIONHANDLER_HANDLE tlsio_bearssl_retrieveoptions(CONCRETE_IO_HANDLE handle)
1662 {
1663 OPTIONHANDLER_HANDLE result = NULL;
1664 if (handle == NULL)
1665 {
1666 LogError("invalid parameter detected: CONCRETE_IO_HANDLE handle=%p", handle);
1667 result = NULL;
1668 }
1669 else
1670 {
1671 result = OptionHandler_Create(tlsio_bearssl_CloneOption, tlsio_bearssl_DestroyOption, tlsio_bearssl_setoption);
1672 if (result == NULL)
1673 {
1674 LogError("unable to OptionHandler_Create");
1675 /*return as is*/
1676 }
1677 else
1678 {
1679 // This layer cares about the certificates
1680 TLS_IO_INSTANCE *tls_io_instance = (TLS_IO_INSTANCE *)handle;
1681 OPTIONHANDLER_HANDLE underlying_io_options;
1682
1683 if ((underlying_io_options = xio_retrieveoptions(tls_io_instance->socket_io)) == NULL)
1684 {
1685 LogError("unable to retrieve underlying_io options");
1686 OptionHandler_Destroy(result);
1687 result = NULL;
1688 }
1689 else
1690 {
1691 if (OptionHandler_AddOption(result, OPTION_UNDERLYING_IO_OPTIONS, underlying_io_options) != OPTIONHANDLER_OK)
1692 {
1693 LogError("unable to save underlying_io options");
1694 OptionHandler_Destroy(result);
1695 result = NULL;
1696 }
1697 else if (tls_io_instance->trusted_certificates != NULL &&
1698 OptionHandler_AddOption(result, OPTION_TRUSTED_CERT, tls_io_instance->trusted_certificates) != OPTIONHANDLER_OK)
1699 {
1700 LogError("unable to save TrustedCerts option");
1701 OptionHandler_Destroy(result);
1702 result = NULL;
1703 }
1704 else if (tls_io_instance->x509_certificate != NULL &&
1705 OptionHandler_AddOption(result, SU_OPTION_X509_CERT, tls_io_instance->x509_certificate) != OPTIONHANDLER_OK)
1706 {
1707 LogError("unable to save x509certificate option");
1708 OptionHandler_Destroy(result);
1709 result = NULL;
1710 }
1711 else if (tls_io_instance->x509_private_key != NULL &&
1712 OptionHandler_AddOption(result, SU_OPTION_X509_PRIVATE_KEY, tls_io_instance->x509_private_key) != OPTIONHANDLER_OK)
1713 {
1714 LogError("unable to save x509privatekey option");
1715 OptionHandler_Destroy(result);
1716 result = NULL;
1717 }
1718 else
1719 {
1720 /*all is fine, all interesting options have been saved*/
1721 /*return as is*/
1722 }
1723
1724 OptionHandler_Destroy(underlying_io_options);
1725 }
1726 }
1727 }
1728 return result;
1729 }
1730
1731 static const IO_INTERFACE_DESCRIPTION tlsio_bearssl_interface_description =
1732 {
1733 tlsio_bearssl_retrieveoptions,
1734 tlsio_bearssl_create,
1735 tlsio_bearssl_destroy,
1736 tlsio_bearssl_open,
1737 tlsio_bearssl_close,
1738 tlsio_bearssl_send,
1739 tlsio_bearssl_dowork,
1740 tlsio_bearssl_setoption};
1741
1742 const IO_INTERFACE_DESCRIPTION *tlsio_bearssl_get_interface_description(void)
1743 {
1744 return &tlsio_bearssl_interface_description;
1745 }