-
Notifications
You must be signed in to change notification settings - Fork 13.3k
/
WiFiClientSecureBearSSL.cpp
1676 lines (1515 loc) · 61.1 KB
/
WiFiClientSecureBearSSL.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
WiFiClientBearSSL- SSL client/server for esp8266 using BearSSL libraries
- Mostly compatible with Arduino WiFi shield library and standard
WiFiClient/ServerSecure (except for certificate handling).
Copyright (c) 2018 Earle F. Philhower, III
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <list>
#include <errno.h>
#include <algorithm>
#include <Esp.h>
extern "C" {
#include "osapi.h"
#include "ets_sys.h"
}
#include "debug.h"
#include "ESP8266WiFi.h"
#include "PolledTimeout.h"
#include "WiFiClient.h"
#include "WiFiClientSecureBearSSL.h"
#include "StackThunk.h"
#include "lwip/opt.h"
#include "lwip/ip.h"
#include "lwip/tcp.h"
#include "lwip/inet.h"
#include "lwip/netif.h"
#include <include/ClientContext.h>
#include "c_types.h"
#include <mmu_iram.h>
#include <umm_malloc/umm_malloc.h>
#include <umm_malloc/umm_heap_select.h>
#if !CORE_MOCK
// The BearSSL thunks in use for now
#define br_ssl_engine_recvapp_ack thunk_br_ssl_engine_recvapp_ack
#define br_ssl_engine_recvapp_buf thunk_br_ssl_engine_recvapp_buf
#define br_ssl_engine_recvrec_ack thunk_br_ssl_engine_recvrec_ack
#define br_ssl_engine_recvrec_buf thunk_br_ssl_engine_recvrec_buf
#define br_ssl_engine_sendapp_ack thunk_br_ssl_engine_sendapp_ack
#define br_ssl_engine_sendapp_buf thunk_br_ssl_engine_sendapp_buf
#define br_ssl_engine_sendrec_ack thunk_br_ssl_engine_sendrec_ack
#define br_ssl_engine_sendrec_buf thunk_br_ssl_engine_sendrec_buf
#endif
#if defined(DEBUG_ESP_SSL) && defined(DEBUG_ESP_PORT)
#define DEBUG_BSSL(fmt, ...) DEBUG_ESP_PORT.printf_P((PGM_P)PSTR( "BSSL:" fmt), ## __VA_ARGS__)
#else
#define DEBUG_BSSL(...)
#endif
namespace BearSSL {
void WiFiClientSecureCtx::_clear() {
// TLS handshake may take more than the 5 second default timeout
_timeout = 15000;
_sc = nullptr;
_sc_svr = nullptr;
_eng = nullptr;
_x509_minimal = nullptr;
_x509_insecure = nullptr;
_x509_knownkey = nullptr;
_iobuf_in = nullptr;
_iobuf_out = nullptr;
_now = 0; // You can override or ensure time() is correct w/configTime
_ta = nullptr;
setBufferSizes(16384, 512); // Minimum safe
_handshake_done = false;
_recvapp_buf = nullptr;
_recvapp_len = 0;
_oom_err = false;
_session = nullptr;
_cipher_list = nullptr;
_cipher_cnt = 0;
_tls_min = BR_TLS10;
_tls_max = BR_TLS12;
}
void WiFiClientSecureCtx::_clearAuthenticationSettings() {
_use_insecure = false;
_use_fingerprint = false;
_use_self_signed = false;
_knownkey = nullptr;
_ta = nullptr;
}
WiFiClientSecureCtx::WiFiClientSecureCtx() : WiFiClient() {
_clear();
_clearAuthenticationSettings();
_certStore = nullptr; // Don't want to remove cert store on a clear, should be long lived
_sk = nullptr;
stack_thunk_add_ref();
}
WiFiClientSecureCtx::~WiFiClientSecureCtx() {
if (_client) {
_client->unref();
_client = nullptr;
}
_cipher_list = nullptr; // std::shared will free if last reference
_freeSSL();
stack_thunk_del_ref();
}
WiFiClientSecureCtx::WiFiClientSecureCtx(ClientContext* client,
const X509List *chain, const PrivateKey *sk,
int iobuf_in_size, int iobuf_out_size, ServerSessions *cache,
const X509List *client_CA_ta, int tls_min, int tls_max) {
_clear();
_clearAuthenticationSettings();
stack_thunk_add_ref();
_iobuf_in_size = iobuf_in_size;
_iobuf_out_size = iobuf_out_size;
_client = client;
_client->ref();
_tls_min = tls_min;
_tls_max = tls_max;
if (!_connectSSLServerRSA(chain, sk, cache, client_CA_ta)) {
_client->unref();
_client = nullptr;
_clear();
}
}
WiFiClientSecureCtx::WiFiClientSecureCtx(ClientContext *client,
const X509List *chain,
unsigned cert_issuer_key_type, const PrivateKey *sk,
int iobuf_in_size, int iobuf_out_size, ServerSessions *cache,
const X509List *client_CA_ta, int tls_min, int tls_max) {
_clear();
_clearAuthenticationSettings();
stack_thunk_add_ref();
_iobuf_in_size = iobuf_in_size;
_iobuf_out_size = iobuf_out_size;
_client = client;
_client->ref();
_tls_min = tls_min;
_tls_max = tls_max;
if (!_connectSSLServerEC(chain, cert_issuer_key_type, sk, cache, client_CA_ta)) {
_client->unref();
_client = nullptr;
_clear();
}
}
void WiFiClientSecureCtx::setClientRSACert(const X509List *chain, const PrivateKey *sk) {
_chain = chain;
_sk = sk;
}
void WiFiClientSecureCtx::setClientECCert(const X509List *chain,
const PrivateKey *sk, unsigned allowed_usages, unsigned cert_issuer_key_type) {
_chain = chain;
_sk = sk;
_allowed_usages = allowed_usages;
_cert_issuer_key_type = cert_issuer_key_type;
}
void WiFiClientSecureCtx::setBufferSizes(int recv, int xmit) {
// Following constants taken from bearssl/src/ssl/ssl_engine.c (not exported unfortunately)
const int MAX_OUT_OVERHEAD = 85;
const int MAX_IN_OVERHEAD = 325;
// The data buffers must be between 512B and 16KB
recv = std::max(512, std::min(16384, recv));
xmit = std::max(512, std::min(16384, xmit));
// Add in overhead for SSL protocol
recv += MAX_IN_OVERHEAD;
xmit += MAX_OUT_OVERHEAD;
_iobuf_in_size = recv;
_iobuf_out_size = xmit;
}
bool WiFiClientSecureCtx::stop(unsigned int maxWaitMs) {
bool ret = WiFiClient::stop(maxWaitMs); // calls our virtual flush()
// Only if we've already connected, store session params and clear the connection options
if (_handshake_done) {
if (_session) {
br_ssl_engine_get_session_parameters(_eng, _session->getSession());
}
}
_freeSSL();
return ret;
}
bool WiFiClientSecureCtx::flush(unsigned int maxWaitMs) {
(void) _run_until(BR_SSL_SENDAPP);
return WiFiClient::flush(maxWaitMs);
}
int WiFiClientSecureCtx::connect(IPAddress ip, uint16_t port) {
if (!WiFiClient::connect(ip, port)) {
return 0;
}
return _connectSSL(nullptr);
}
int WiFiClientSecureCtx::connect(const char* name, uint16_t port) {
IPAddress remote_addr;
if (!WiFi.hostByName(name, remote_addr)) {
DEBUG_BSSL("connect: Name lookup failure\n");
return 0;
}
if (!WiFiClient::connect(remote_addr, port)) {
DEBUG_BSSL("connect: Unable to connect TCP socket\n");
return 0;
}
return _connectSSL(name);
}
int WiFiClientSecureCtx::connect(const String& host, uint16_t port) {
return connect(host.c_str(), port);
}
void WiFiClientSecureCtx::_freeSSL() {
// These are smart pointers and will free if refcnt==0
_sc = nullptr;
_sc_svr = nullptr;
_x509_minimal = nullptr;
_x509_insecure = nullptr;
_x509_knownkey = nullptr;
_iobuf_in = nullptr;
_iobuf_out = nullptr;
// Reset non-allocated ptrs (pointing to bits potentially free'd above)
_recvapp_buf = nullptr;
_recvapp_len = 0;
// This connection is toast
_handshake_done = false;
_timeout = 15000;
}
bool WiFiClientSecureCtx::_clientConnected() {
if (!_client || (_client->state() == CLOSED)) {
return false;
}
return _client->state() == ESTABLISHED;
}
bool WiFiClientSecureCtx::_engineConnected() {
return _clientConnected() && _handshake_done && _eng && (br_ssl_engine_current_state(_eng) != BR_SSL_CLOSED);
}
uint8_t WiFiClientSecureCtx::connected() {
if (!_engineConnected()) {
return false;
}
if (_pollRecvBuffer() > 0) {
return true;
}
return _engineConnected();
}
int WiFiClientSecureCtx::availableForWrite () {
// Can't write things when there's no connection or br_ssl engine is closed
if (!_engineConnected()) {
return 0;
}
// Get BearSSL to a state where we can send
if (_run_until(BR_SSL_SENDAPP) < 0) {
return 0;
}
if (br_ssl_engine_current_state(_eng) & BR_SSL_SENDAPP) {
size_t sendapp_len;
(void)br_ssl_engine_sendapp_buf(_eng, &sendapp_len);
// We want to call br_ssl_engine_sendapp_ack(0) but 0 is forbidden (bssl doc).
// After checking br_ssl_engine_sendapp_buf() src code,
// it seems that it is OK to not call ack when the buffer is left untouched.
//forbidden: br_ssl_engine_sendapp_ack(_eng, 0);
return (int)sendapp_len;
}
return 0;
}
size_t WiFiClientSecureCtx::_write(const uint8_t *buf, size_t size, bool pmem) {
size_t sent_bytes = 0;
if (!size || !_engineConnected()) {
return 0;
}
do {
// Ensure we yield if we need multiple fragments to avoid WDT
if (sent_bytes) {
optimistic_yield(1000);
}
// Get BearSSL to a state where we can send
if (_run_until(BR_SSL_SENDAPP) < 0) {
break;
}
if (br_ssl_engine_current_state(_eng) & BR_SSL_SENDAPP) {
size_t sendapp_len;
unsigned char *sendapp_buf = br_ssl_engine_sendapp_buf(_eng, &sendapp_len);
int to_send = size > sendapp_len ? sendapp_len : size;
if (pmem) {
memcpy_P(sendapp_buf, buf, to_send);
} else {
memcpy(sendapp_buf, buf, to_send);
}
br_ssl_engine_sendapp_ack(_eng, to_send);
br_ssl_engine_flush(_eng, 0);
flush();
buf += to_send;
sent_bytes += to_send;
size -= to_send;
} else {
break;
}
} while (size);
return sent_bytes;
}
size_t WiFiClientSecureCtx::write(const uint8_t *buf, size_t size) {
return _write(buf, size, false);
}
size_t WiFiClientSecureCtx::write_P(PGM_P buf, size_t size) {
return _write((const uint8_t *)buf, size, true);
}
size_t WiFiClientSecureCtx::write(Stream& stream) {
if (!_engineConnected()) {
DEBUG_BSSL("write: no br_ssl engine to work with\n");
return 0;
}
return stream.sendAll(this);
}
int WiFiClientSecureCtx::read(uint8_t *buf, size_t size) {
if (!ctx_present() || !_handshake_done) {
return -1;
}
// will either check the internal buffer, or try to wait for some data
// *may* attempt to write some pending ::write() data b/c of _run_until
int avail = _pollRecvBuffer();
// internal buffer might still be available for some time
bool engine = _engineConnected();
// we're still connected, but nothing to read
if (!avail && engine) {
return 0;
}
// or, available failed to assign the internal buffer and we are already disconnected
if (!avail && !engine) {
DEBUG_BSSL("read: Not connected, none left available\n");
return -1;
}
if (avail) {
// Take data from the recvapp buffer
int to_copy = _recvapp_len < size ? _recvapp_len : size;
memcpy(buf, _recvapp_buf, to_copy);
br_ssl_engine_recvapp_ack(_eng, to_copy);
_recvapp_buf = nullptr;
_recvapp_len = 0;
return to_copy;
}
if (!engine) {
DEBUG_BSSL("read: Not connected\n");
return -1;
}
return 0; // If we're connected, no error but no read.
}
// return a pointer to available data buffer (size = peekAvailable())
// semantic forbids any kind of read() before calling peekConsume()
const char* WiFiClientSecureCtx::peekBuffer ()
{
return (const char*)_recvapp_buf;
}
// consume bytes after use (see peekBuffer)
void WiFiClientSecureCtx::peekConsume (size_t consume)
{
// according to WiFiClientSecureCtx::read:
br_ssl_engine_recvapp_ack(_eng, consume);
_recvapp_buf = nullptr;
_recvapp_len = 0;
}
int WiFiClientSecureCtx::read() {
uint8_t c;
if (1 == read(&c, 1)) {
return c;
}
return -1;
}
int WiFiClientSecureCtx::_pollRecvBuffer() {
if (_recvapp_buf) {
return _recvapp_len; // Anything from last call?
}
_recvapp_buf = nullptr;
_recvapp_len = 0;
if (!ctx_present() || _run_until(BR_SSL_RECVAPP, false) < 0) {
return 0;
}
int st = br_ssl_engine_current_state(_eng);
if (st == BR_SSL_CLOSED) {
return 0; // Nothing leftover, SSL is closed
}
if (st & BR_SSL_RECVAPP) {
_recvapp_buf = br_ssl_engine_recvapp_buf(_eng, &_recvapp_len);
return _recvapp_len;
}
return 0;
}
int WiFiClientSecureCtx::available() {
return _pollRecvBuffer();
}
int WiFiClientSecureCtx::peek() {
if (!ctx_present() || (0 == _pollRecvBuffer())) {
DEBUG_BSSL("peek: Not connected, none left available\n");
return -1;
}
if (_recvapp_buf && _recvapp_len) {
return _recvapp_buf[0];
}
DEBUG_BSSL("peek: No data left\n");
return -1;
}
size_t WiFiClientSecureCtx::peekBytes(uint8_t *buffer, size_t length) {
size_t to_copy = 0;
if (!ctx_present()) {
DEBUG_BSSL("peekBytes: Not connected\n");
return 0;
}
_startMillis = millis();
while ((_pollRecvBuffer() < (int) length) && ((millis() - _startMillis) < 5000)) {
yield();
}
to_copy = _recvapp_len < length ? _recvapp_len : length;
memcpy(buffer, _recvapp_buf, to_copy);
return to_copy;
}
/* --- Copied almost verbatim from BEARSSL SSL_IO.C ---
Run the engine, until the specified target state is achieved, or
an error occurs. The target state is SENDAPP, RECVAPP, or the
combination of both (the combination matches either). When a match is
achieved, this function returns 0. On error, it returns -1.
*/
int WiFiClientSecureCtx::_run_until(unsigned target, bool blocking) {
if (!ctx_present()) {
DEBUG_BSSL("_run_until: Not connected\n");
return -1;
}
esp8266::polledTimeout::oneShotMs loopTimeout(_timeout);
for (int no_work = 0; blocking || no_work < 2;) {
optimistic_yield(100);
if (loopTimeout) {
DEBUG_BSSL("_run_until: Timeout\n");
return -1;
}
int state;
state = br_ssl_engine_current_state(_eng);
if (state & BR_SSL_CLOSED) {
return -1;
}
if (!(_client->state() == ESTABLISHED) && !WiFiClient::available()) {
return (state & target) ? 0 : -1;
}
/*
If there is some record data to send, do it. This takes
precedence over everything else.
*/
if (state & BR_SSL_SENDREC) {
unsigned char *buf;
size_t len;
int wlen;
size_t availForWrite;
buf = br_ssl_engine_sendrec_buf(_eng, &len);
availForWrite = WiFiClient::availableForWrite();
if (!blocking && len > availForWrite) {
/*
writes on WiFiClient will block if len > availableForWrite()
this is needed to prevent available() calls from blocking
on dropped connections
*/
len = availForWrite;
}
wlen = WiFiClient::write(buf, len);
if (wlen <= 0) {
/*
If we received a close_notify and we
still send something, then we have our
own response close_notify to send, and
the peer is allowed by RFC 5246 not to
wait for it.
*/
return -1;
}
if (wlen > 0) {
br_ssl_engine_sendrec_ack(_eng, wlen);
}
no_work = 0;
continue;
}
/*
If we reached our target, then we are finished.
*/
if (state & target) {
return 0;
}
/*
If some application data must be read, and we did not
exit, then this means that we are trying to write data,
and that's not possible until the application data is
read. This may happen if using a shared in/out buffer,
and the underlying protocol is not strictly half-duplex.
This is unrecoverable here, so we report an error.
*/
if (state & BR_SSL_RECVAPP) {
DEBUG_BSSL("_run_until: Fatal protocol state\n");
return -1;
}
/*
If we reached that point, then either we are trying
to read data and there is some, or the engine is stuck
until a new record is obtained.
*/
if (state & BR_SSL_RECVREC) {
if (WiFiClient::available()) {
unsigned char *buf;
size_t len;
int rlen;
buf = br_ssl_engine_recvrec_buf(_eng, &len);
rlen = WiFiClient::read(buf, len);
if (rlen < 0) {
return -1;
}
if (rlen > 0) {
br_ssl_engine_recvrec_ack(_eng, rlen);
}
no_work = 0;
continue;
}
}
/*
We can reach that point if the target RECVAPP, and
the state contains SENDAPP only. This may happen with
a shared in/out buffer. In that case, we must flush
the buffered data to "make room" for a new incoming
record.
*/
br_ssl_engine_flush(_eng, 0);
no_work++; // We didn't actually advance here
}
// We only get here if we ran through the loop without getting anything done
return -1;
}
bool WiFiClientSecureCtx::_wait_for_handshake() {
_handshake_done = false;
while (!_handshake_done && _clientConnected()) {
int ret = _run_until(BR_SSL_SENDAPP);
if (ret < 0) {
DEBUG_BSSL("_wait_for_handshake: failed\n");
break;
}
if (br_ssl_engine_current_state(_eng) & BR_SSL_SENDAPP) {
_handshake_done = true;
}
optimistic_yield(1000);
}
return _handshake_done;
}
static uint8_t htoi (unsigned char c)
{
if (c>='0' && c <='9') return c - '0';
else if (c>='A' && c<='F') return 10 + c - 'A';
else if (c>='a' && c<='f') return 10 + c - 'a';
else return 255;
}
// Set a fingerprint by parsing an ASCII string
bool WiFiClientSecureCtx::setFingerprint(const char *fpStr) {
int idx = 0;
uint8_t c, d;
uint8_t fp[20];
while (idx < 20) {
c = pgm_read_byte(fpStr++);
if (!c) break; // String ended, done processing
d = pgm_read_byte(fpStr++);
if (!d) {
DEBUG_BSSL("setFingerprint: FP too short\n");
return false; // Only half of the last hex digit, error
}
c = htoi(c);
d = htoi(d);
if ((c>15) || (d>15)) {
DEBUG_BSSL("setFingerprint: Invalid char\n");
return false; // Error in one of the hex characters
}
fp[idx++] = (c<<4)|d;
// Skip 0 or more spaces or colons
while ( pgm_read_byte(fpStr) && (pgm_read_byte(fpStr)==' ' || pgm_read_byte(fpStr)==':') ) {
fpStr++;
}
}
if ((idx != 20) || pgm_read_byte(fpStr)) {
DEBUG_BSSL("setFingerprint: Garbage at end of fp\n");
return false; // Garbage at EOL or we didn't have enough hex digits
}
return setFingerprint(fp);
}
extern "C" {
// BearSSL doesn't define a true insecure decoder, so we make one ourselves
// from the simple parser. It generates the issuer and subject hashes and
// the SHA1 fingerprint, only one (or none!) of which will be used to
// "verify" the certificate.
// Private x509 decoder state
struct br_x509_insecure_context {
const br_x509_class *vtable;
bool done_cert;
const uint8_t *match_fingerprint;
br_sha1_context sha1_cert;
bool allow_self_signed;
br_sha256_context sha256_subject;
br_sha256_context sha256_issuer;
br_x509_decoder_context ctx;
};
// Callback for the x509_minimal subject DN
static void insecure_subject_dn_append(void *ctx, const void *buf, size_t len) {
br_x509_insecure_context *xc = (br_x509_insecure_context *)ctx;
br_sha256_update(&xc->sha256_subject, buf, len);
}
// Callback for the x509_minimal issuer DN
static void insecure_issuer_dn_append(void *ctx, const void *buf, size_t len) {
br_x509_insecure_context *xc = (br_x509_insecure_context *)ctx;
br_sha256_update(&xc->sha256_issuer, buf, len);
}
// Callback on the first byte of any certificate
static void insecure_start_chain(const br_x509_class **ctx, const char *server_name) {
br_x509_insecure_context *xc = (br_x509_insecure_context *)ctx;
br_x509_decoder_init(&xc->ctx, insecure_subject_dn_append, xc, insecure_issuer_dn_append, xc);
xc->done_cert = false;
br_sha1_init(&xc->sha1_cert);
br_sha256_init(&xc->sha256_subject);
br_sha256_init(&xc->sha256_issuer);
(void)server_name;
}
// Callback for each certificate present in the chain (but only operates
// on the first one by design).
static void insecure_start_cert(const br_x509_class **ctx, uint32_t length) {
(void) ctx;
(void) length;
}
// Callback for each byte stream in the chain. Only process first cert.
static void insecure_append(const br_x509_class **ctx, const unsigned char *buf, size_t len) {
br_x509_insecure_context *xc = (br_x509_insecure_context *)ctx;
// Don't process anything but the first certificate in the chain
if (!xc->done_cert) {
br_sha1_update(&xc->sha1_cert, buf, len);
br_x509_decoder_push(&xc->ctx, (const void*)buf, len);
#if defined(DEBUG_ESP_SSL) && defined(DEBUG_ESP_PORT)
DEBUG_BSSL("CERT: ");
for (size_t i=0; i<len; i++) {
DEBUG_ESP_PORT.printf_P(PSTR("%02x "), buf[i] & 0xff);
}
DEBUG_ESP_PORT.printf_P(PSTR("\n"));
#endif
}
}
// Callback on individual cert end.
static void insecure_end_cert(const br_x509_class **ctx) {
br_x509_insecure_context *xc = (br_x509_insecure_context *)ctx;
xc->done_cert = true;
}
// Callback when complete chain has been parsed.
// Return 0 on validation success, !0 on validation error
static unsigned insecure_end_chain(const br_x509_class **ctx) {
const br_x509_insecure_context *xc = (const br_x509_insecure_context *)ctx;
if (!xc->done_cert) {
DEBUG_BSSL("insecure_end_chain: No cert seen\n");
return 1; // error
}
// Handle SHA1 fingerprint matching
char res[20];
br_sha1_out(&xc->sha1_cert, res);
if (xc->match_fingerprint && memcmp(res, xc->match_fingerprint, sizeof(res))) {
#ifdef DEBUG_ESP_SSL
DEBUG_BSSL("insecure_end_chain: Received cert FP doesn't match\n");
char buff[3 * sizeof(res) + 1]; // 3 chars per byte XX_, and null
buff[0] = 0;
for (size_t i=0; i<sizeof(res); i++) {
char hex[4]; // XX_\0
snprintf(hex, sizeof(hex), "%02x ", xc->match_fingerprint[i] & 0xff);
strlcat(buff, hex, sizeof(buff));
}
DEBUG_BSSL("insecure_end_chain: expected %s\n", buff);
buff[0] =0;
for (size_t i=0; i<sizeof(res); i++) {
char hex[4]; // XX_\0
snprintf(hex, sizeof(hex), "%02x ", res[i] & 0xff);
strlcat(buff, hex, sizeof(buff));
}
DEBUG_BSSL("insecure_end_chain: received %s\n", buff);
#endif
return BR_ERR_X509_NOT_TRUSTED;
}
// Handle self-signer certificate acceptance
char res_issuer[32];
char res_subject[32];
br_sha256_out(&xc->sha256_issuer, res_issuer);
br_sha256_out(&xc->sha256_subject, res_subject);
if (xc->allow_self_signed && memcmp(res_subject, res_issuer, sizeof(res_issuer))) {
DEBUG_BSSL("insecure_end_chain: Didn't get self-signed cert\n");
return BR_ERR_X509_NOT_TRUSTED;
}
// Default (no validation at all) or no errors in prior checks = success.
return 0;
}
// Return the public key from the validator (set by x509_minimal)
static const br_x509_pkey *insecure_get_pkey(const br_x509_class *const *ctx, unsigned *usages) {
const br_x509_insecure_context *xc = (const br_x509_insecure_context *)ctx;
if (usages != NULL) {
*usages = BR_KEYTYPE_KEYX | BR_KEYTYPE_SIGN; // I said we were insecure!
}
return &xc->ctx.pkey;
}
// Set up the x509 insecure data structures for BearSSL core to use.
void br_x509_insecure_init(br_x509_insecure_context *ctx, int _use_fingerprint, const uint8_t _fingerprint[20], int _allow_self_signed) {
static const br_x509_class br_x509_insecure_vtable PROGMEM = {
sizeof(br_x509_insecure_context),
insecure_start_chain,
insecure_start_cert,
insecure_append,
insecure_end_cert,
insecure_end_chain,
insecure_get_pkey
};
memset(ctx, 0, sizeof * ctx);
ctx->vtable = &br_x509_insecure_vtable;
ctx->done_cert = false;
ctx->match_fingerprint = _use_fingerprint ? _fingerprint : nullptr;
ctx->allow_self_signed = _allow_self_signed ? 1 : 0;
}
// Some constants uses to init the server/client contexts
// Note that suites_P needs to be copied to RAM before use w/BearSSL!
// List copied verbatim from BearSSL/ssl_client_full.c
/*
* The "full" profile supports all implemented cipher suites.
*
* Rationale for suite order, from most important to least
* important rule:
*
* -- Don't use 3DES if AES or ChaCha20 is available.
* -- Try to have Forward Secrecy (ECDHE suite) if possible.
* -- When not using Forward Secrecy, ECDH key exchange is
* better than RSA key exchange (slightly more expensive on the
* client, but much cheaper on the server, and it implies smaller
* messages).
* -- ChaCha20+Poly1305 is better than AES/GCM (faster, smaller code).
* -- GCM is better than CCM and CBC. CCM is better than CBC.
* -- CCM is preferable over CCM_8 (with CCM_8, forgeries may succeed
* with probability 2^(-64)).
* -- AES-128 is preferred over AES-256 (AES-128 is already
* strong enough, and AES-256 is 40% more expensive).
*/
static const uint16_t suites_P[] PROGMEM = {
#ifndef BEARSSL_SSL_BASIC
BR_TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256,
BR_TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256,
BR_TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
BR_TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
BR_TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
BR_TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
BR_TLS_ECDHE_ECDSA_WITH_AES_128_CCM,
BR_TLS_ECDHE_ECDSA_WITH_AES_256_CCM,
BR_TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8,
BR_TLS_ECDHE_ECDSA_WITH_AES_256_CCM_8,
BR_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256,
BR_TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256,
BR_TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384,
BR_TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384,
BR_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA,
BR_TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,
BR_TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA,
BR_TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,
BR_TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256,
BR_TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256,
BR_TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384,
BR_TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384,
BR_TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256,
BR_TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256,
BR_TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384,
BR_TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384,
BR_TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA,
BR_TLS_ECDH_RSA_WITH_AES_128_CBC_SHA,
BR_TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA,
BR_TLS_ECDH_RSA_WITH_AES_256_CBC_SHA,
BR_TLS_RSA_WITH_AES_128_GCM_SHA256,
BR_TLS_RSA_WITH_AES_256_GCM_SHA384,
BR_TLS_RSA_WITH_AES_128_CCM,
BR_TLS_RSA_WITH_AES_256_CCM,
BR_TLS_RSA_WITH_AES_128_CCM_8,
BR_TLS_RSA_WITH_AES_256_CCM_8,
#endif
BR_TLS_RSA_WITH_AES_128_CBC_SHA256,
BR_TLS_RSA_WITH_AES_256_CBC_SHA256,
BR_TLS_RSA_WITH_AES_128_CBC_SHA,
BR_TLS_RSA_WITH_AES_256_CBC_SHA,
#ifndef BEARSSL_SSL_BASIC
BR_TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA,
BR_TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA,
BR_TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA,
BR_TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA,
BR_TLS_RSA_WITH_3DES_EDE_CBC_SHA
#endif
};
#ifndef BEARSSL_SSL_BASIC
// Server w/EC has one set, not possible with basic SSL config
static const uint16_t suites_server_ec_P [] PROGMEM = {
BR_TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256,
BR_TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
BR_TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
BR_TLS_ECDHE_ECDSA_WITH_AES_128_CCM,
BR_TLS_ECDHE_ECDSA_WITH_AES_256_CCM,
BR_TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8,
BR_TLS_ECDHE_ECDSA_WITH_AES_256_CCM_8,
BR_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256,
BR_TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384,
BR_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA,
BR_TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA,
BR_TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256,
BR_TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256,
BR_TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384,
BR_TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384,
BR_TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256,
BR_TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256,
BR_TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384,
BR_TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384,
BR_TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA,
BR_TLS_ECDH_RSA_WITH_AES_128_CBC_SHA,
BR_TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA,
BR_TLS_ECDH_RSA_WITH_AES_256_CBC_SHA,
BR_TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA,
BR_TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA,
BR_TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA
};
#endif
static const uint16_t suites_server_rsa_P[] PROGMEM = {
#ifndef BEARSSL_SSL_BASIC
BR_TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256,
BR_TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
BR_TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
BR_TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256,
BR_TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384,
BR_TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,
BR_TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,
BR_TLS_RSA_WITH_AES_128_GCM_SHA256,
BR_TLS_RSA_WITH_AES_256_GCM_SHA384,
BR_TLS_RSA_WITH_AES_128_CCM,
BR_TLS_RSA_WITH_AES_256_CCM,
BR_TLS_RSA_WITH_AES_128_CCM_8,
BR_TLS_RSA_WITH_AES_256_CCM_8,
#endif
BR_TLS_RSA_WITH_AES_128_CBC_SHA256,
BR_TLS_RSA_WITH_AES_256_CBC_SHA256,
BR_TLS_RSA_WITH_AES_128_CBC_SHA,
BR_TLS_RSA_WITH_AES_256_CBC_SHA,
#ifndef BEARSSL_SSL_BASIC
BR_TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA,
BR_TLS_RSA_WITH_3DES_EDE_CBC_SHA
#endif
};
// For apps which want to use less secure but faster ciphers, only
static const uint16_t faster_suites_P[] PROGMEM = {
BR_TLS_RSA_WITH_AES_256_CBC_SHA256,
BR_TLS_RSA_WITH_AES_128_CBC_SHA256,
BR_TLS_RSA_WITH_AES_256_CBC_SHA,
BR_TLS_RSA_WITH_AES_128_CBC_SHA };
// Install hashes into the SSL engine
static void br_ssl_client_install_hashes(br_ssl_engine_context *eng) {
br_ssl_engine_set_hash(eng, br_md5_ID, &br_md5_vtable);
br_ssl_engine_set_hash(eng, br_sha1_ID, &br_sha1_vtable);
br_ssl_engine_set_hash(eng, br_sha224_ID, &br_sha224_vtable);
br_ssl_engine_set_hash(eng, br_sha256_ID, &br_sha256_vtable);
br_ssl_engine_set_hash(eng, br_sha384_ID, &br_sha384_vtable);
br_ssl_engine_set_hash(eng, br_sha512_ID, &br_sha512_vtable);
}
static void br_x509_minimal_install_hashes(br_x509_minimal_context *x509) {
br_x509_minimal_set_hash(x509, br_md5_ID, &br_md5_vtable);
br_x509_minimal_set_hash(x509, br_sha1_ID, &br_sha1_vtable);
br_x509_minimal_set_hash(x509, br_sha224_ID, &br_sha224_vtable);
br_x509_minimal_set_hash(x509, br_sha256_ID, &br_sha256_vtable);
br_x509_minimal_set_hash(x509, br_sha384_ID, &br_sha384_vtable);
br_x509_minimal_set_hash(x509, br_sha512_ID, &br_sha512_vtable);
}
// Default initializion for our SSL clients
static void br_ssl_client_base_init(br_ssl_client_context *cc, const uint16_t *cipher_list, int cipher_cnt) {
uint16_t suites[cipher_cnt];
memcpy_P(suites, cipher_list, cipher_cnt * sizeof(cipher_list[0]));
br_ssl_client_zero(cc);
br_ssl_engine_add_flags(&cc->eng, BR_OPT_NO_RENEGOTIATION); // forbid SSL renegotiation, as we free the Private Key after handshake
br_ssl_engine_set_versions(&cc->eng, BR_TLS10, BR_TLS12);
br_ssl_engine_set_suites(&cc->eng, suites, (sizeof suites) / (sizeof suites[0]));
br_ssl_client_set_default_rsapub(cc);
br_ssl_engine_set_default_rsavrfy(&cc->eng);
#ifndef BEARSSL_SSL_BASIC
br_ssl_engine_set_default_ecdsa(&cc->eng);
#endif
br_ssl_client_install_hashes(&cc->eng);
br_ssl_engine_set_prf10(&cc->eng, &br_tls10_prf);
br_ssl_engine_set_prf_sha256(&cc->eng, &br_tls12_sha256_prf);
br_ssl_engine_set_prf_sha384(&cc->eng, &br_tls12_sha384_prf);
br_ssl_engine_set_default_aes_cbc(&cc->eng);
#ifndef BEARSSL_SSL_BASIC
br_ssl_engine_set_default_aes_gcm(&cc->eng);
br_ssl_engine_set_default_aes_ccm(&cc->eng);
br_ssl_engine_set_default_des_cbc(&cc->eng);
br_ssl_engine_set_default_chapol(&cc->eng);
#endif
}
// Default initializion for our SSL clients
static void br_ssl_server_base_init(br_ssl_server_context *cc, const uint16_t *cipher_list, int cipher_cnt) {
uint16_t suites[cipher_cnt];
memcpy_P(suites, cipher_list, cipher_cnt * sizeof(cipher_list[0]));
br_ssl_server_zero(cc);
br_ssl_engine_add_flags(&cc->eng, BR_OPT_NO_RENEGOTIATION); // forbid SSL renegotiation, as we free the Private Key after handshake
br_ssl_engine_set_versions(&cc->eng, BR_TLS10, BR_TLS12);