-
Notifications
You must be signed in to change notification settings - Fork 2.8k
/
Copy pathtls_builtin.c
1750 lines (1575 loc) · 58.7 KB
/
tls_builtin.c
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
#include "base64.h"
#include "config.h"
#include "printf.h"
#include "sha256.h"
#include "tls.h"
#include "tls_aes128.h"
#include "tls_chacha20.h"
#include "tls_rsa.h"
#include "tls_uecc.h"
#include "tls_x25519.h"
#include "util.h"
#if MG_TLS == MG_TLS_BUILTIN
#define CHACHA20 1
/* TLS 1.3 Record Content Type (RFC8446 B.1) */
#define MG_TLS_CHANGE_CIPHER 20
#define MG_TLS_ALERT 21
#define MG_TLS_HANDSHAKE 22
#define MG_TLS_APP_DATA 23
#define MG_TLS_HEARTBEAT 24
/* TLS 1.3 Handshake Message Type (RFC8446 B.3) */
#define MG_TLS_CLIENT_HELLO 1
#define MG_TLS_SERVER_HELLO 2
#define MG_TLS_ENCRYPTED_EXTENSIONS 8
#define MG_TLS_CERTIFICATE 11
#define MG_TLS_CERTIFICATE_REQUEST 13
#define MG_TLS_CERTIFICATE_VERIFY 15
#define MG_TLS_FINISHED 20
// handshake is re-entrant, so we need to keep track of its state state names
// refer to RFC8446#A.1
enum mg_tls_hs_state {
// Client state machine:
MG_TLS_STATE_CLIENT_START, // Send ClientHello
MG_TLS_STATE_CLIENT_WAIT_SH, // Wait for ServerHello
MG_TLS_STATE_CLIENT_WAIT_EE, // Wait for EncryptedExtensions
MG_TLS_STATE_CLIENT_WAIT_CERT, // Wait for Certificate
MG_TLS_STATE_CLIENT_WAIT_CV, // Wait for CertificateVerify
MG_TLS_STATE_CLIENT_WAIT_FINISHED, // Wait for Finished
MG_TLS_STATE_CLIENT_CONNECTED, // Done
// Server state machine:
MG_TLS_STATE_SERVER_START, // Wait for ClientHello
MG_TLS_STATE_SERVER_NEGOTIATED, // Wait for Finished
MG_TLS_STATE_SERVER_CONNECTED // Done
};
// encryption keys for a TLS connection
struct tls_enc {
uint32_t sseq; // server sequence number, used in encryption
uint32_t cseq; // client sequence number, used in decryption
// keys for AES encryption or ChaCha20
uint8_t handshake_secret[32];
uint8_t server_write_key[32];
uint8_t server_write_iv[12];
uint8_t server_finished_key[32];
uint8_t client_write_key[32];
uint8_t client_write_iv[12];
uint8_t client_finished_key[32];
};
// per-connection TLS data
struct tls_data {
enum mg_tls_hs_state state; // keep track of connection handshake progress
struct mg_iobuf send; // For the receive path, we're reusing c->rtls
size_t recv_offset; // While c->rtls contains full records, reuse that
size_t recv_len; // buffer but point at individual decrypted messages
uint8_t content_type; // Last received record content type
mg_sha256_ctx sha256; // incremental SHA-256 hash for TLS handshake
uint8_t random[32]; // client random from ClientHello
uint8_t session_id[32]; // client session ID between the handshake states
uint8_t x25519_cli[32]; // client X25519 key between the handshake states
uint8_t x25519_sec[32]; // x25519 secret between the handshake states
int skip_verification; // perform checks on server certificate?
int cert_requested; // client received a CertificateRequest?
struct mg_str cert_der; // certificate in DER format
struct mg_str ca_der; // CA certificate
uint8_t ec_key[32]; // EC private key
char hostname[254]; // server hostname (client extension)
int is_ec_pubkey; // EC or RSA?
uint8_t pubkey[512 + 16]; // server EC (64) or RSA (512+exp) public key to
// verify cert
size_t pubkeysz; // size of the server public key
uint8_t sighash[32]; // calculated signature verification hash
struct tls_enc enc;
};
#define TLS_RECHDR_SIZE 5 // 1 byte type, 2 bytes version, 2 bytes length
#define TLS_MSGHDR_SIZE 4 // 1 byte type, 3 bytes length
#ifdef MG_TLS_SSLKEYLOGFILE
#include <stdio.h>
static void mg_ssl_key_log(const char *label, uint8_t client_random[32],
uint8_t *secret, size_t secretsz) {
char *keylogfile = getenv("SSLKEYLOGFILE");
size_t i;
if (keylogfile != NULL) {
MG_DEBUG(("Dumping key log into %s", keylogfile));
FILE *f = fopen(keylogfile, "a");
if (f != NULL) {
fprintf(f, "%s ", label);
for (i = 0; i < 32; i++) {
fprintf(f, "%02x", client_random[i]);
}
fprintf(f, " ");
for (i = 0; i < secretsz; i++) {
fprintf(f, "%02x", secret[i]);
}
fprintf(f, "\n");
fclose(f);
} else {
MG_ERROR(("Cannot open %s", keylogfile));
}
}
}
#endif
// for derived tls keys we need SHA256([0]*32)
static uint8_t zeros[32] = {0};
static uint8_t zeros_sha256_digest[32] = {
0xe3, 0xb0, 0xc4, 0x42, 0x98, 0xfc, 0x1c, 0x14, 0x9a, 0xfb, 0xf4,
0xc8, 0x99, 0x6f, 0xb9, 0x24, 0x27, 0xae, 0x41, 0xe4, 0x64, 0x9b,
0x93, 0x4c, 0xa4, 0x95, 0x99, 0x1b, 0x78, 0x52, 0xb8, 0x55};
// helper to hexdump buffers inline
static void mg_tls_hexdump(const char *msg, uint8_t *buf, size_t bufsz) {
MG_VERBOSE(("%s: %M", msg, mg_print_hex, bufsz, buf));
}
// helper utilities to parse ASN.1 DER
struct mg_der_tlv {
uint8_t type;
uint32_t len;
uint8_t *value;
};
static int mg_der_parse(uint8_t *der, size_t dersz, struct mg_der_tlv *tlv) {
size_t header_len = 2;
uint32_t len = dersz < 2 ? 0 : der[1];
if (dersz < 2) return -1; // Invalid DER
tlv->type = der[0];
if (len > 0x7F) { // long-form length
uint8_t len_bytes = len & 0x7F;
if (dersz < (size_t) (2 + len_bytes)) return -1;
len = 0;
for (uint8_t i = 0; i < len_bytes; i++) {
len = (len << 8) | der[2 + i];
}
header_len += len_bytes;
}
if (dersz < header_len + len) return -1;
tlv->len = len;
tlv->value = der + header_len;
return (int) (header_len + len);
}
static int mg_der_next(struct mg_der_tlv *parent, struct mg_der_tlv *child) {
if (parent->len == 0) return 0;
int consumed = mg_der_parse(parent->value, parent->len, child);
if (consumed < 0) return -1;
parent->value += consumed;
parent->len -= (uint32_t) consumed;
return 1;
}
static int mg_der_find_oid(struct mg_der_tlv *tlv, const uint8_t *oid,
size_t oid_len, struct mg_der_tlv *found) {
struct mg_der_tlv parent, child;
parent = *tlv;
while (mg_der_next(&parent, &child) > 0) {
if (child.type == 0x06 && child.len == oid_len &&
memcmp(child.value, oid, oid_len) == 0) {
return mg_der_next(&parent, found);
} else if (child.type & 0x20) {
struct mg_der_tlv sub_parent = child;
if (mg_der_find_oid(&sub_parent, oid, oid_len, found)) return 1;
}
}
return 0;
}
#if 0
static void mg_der_debug(struct mg_der_tlv *tlv, int depth) {
MG_DEBUG(("> %.*sd=%d Type: 0x%02X, Length: %u\n", depth * 4, " ", depth,
tlv->type, tlv->len));
if (tlv->type & 0x20) { // Constructed: recurse into children
struct mg_der_tlv child;
struct mg_der_tlv parent = *tlv;
while (mg_der_next(&parent, &child) > 0) {
mg_der_debug(&child, depth + 1);
}
}
}
#endif
// parse DER into a TLV record
static int mg_der_to_tlv(uint8_t *der, size_t dersz, struct mg_der_tlv *tlv) {
if (dersz < 2) {
return -1;
}
tlv->type = der[0];
tlv->len = der[1];
tlv->value = der + 2;
if (tlv->len > 0x7f) {
uint32_t i, n = tlv->len - 0x80;
tlv->len = 0;
for (i = 0; i < n; i++) {
tlv->len = (tlv->len << 8) | (der[2 + i]);
}
tlv->value = der + 2 + n;
}
if (der + dersz < tlv->value + tlv->len) {
return -1;
}
return 0;
}
// Did we receive a full TLS record in the c->rtls buffer?
static bool mg_tls_got_record(struct mg_connection *c) {
return c->rtls.len >= (size_t) TLS_RECHDR_SIZE &&
c->rtls.len >=
(size_t) (TLS_RECHDR_SIZE + MG_LOAD_BE16(c->rtls.buf + 3));
}
// Remove a single TLS record from the recv buffer
static void mg_tls_drop_record(struct mg_connection *c) {
struct mg_iobuf *rio = &c->rtls;
uint16_t n = MG_LOAD_BE16(rio->buf + 3) + TLS_RECHDR_SIZE;
mg_iobuf_del(rio, 0, n);
}
// Remove a single TLS message from decrypted buffer, remove the wrapping
// record if it was the last message within a record
static void mg_tls_drop_message(struct mg_connection *c) {
uint32_t len;
struct tls_data *tls = (struct tls_data *) c->tls;
unsigned char *recv_buf = &c->rtls.buf[tls->recv_offset];
if (tls->recv_len == 0) return;
len = MG_LOAD_BE24(recv_buf + 1) + TLS_MSGHDR_SIZE;
if (tls->recv_len < len) {
mg_error(c, "wrong size");
return;
}
mg_sha256_update(&tls->sha256, recv_buf, len);
tls->recv_offset += len;
tls->recv_len -= len;
if (tls->recv_len == 0) {
mg_tls_drop_record(c);
}
}
// TLS1.3 secret derivation based on the key label
static void mg_tls_derive_secret(const char *label, uint8_t *key, size_t keysz,
uint8_t *data, size_t datasz, uint8_t *hash,
size_t hashsz) {
size_t labelsz = strlen(label);
uint8_t secret[32];
uint8_t packed[256] = {0, (uint8_t) hashsz, (uint8_t) labelsz};
// TODO: assert lengths of label, key, data and hash
if (labelsz > 0) memmove(packed + 3, label, labelsz);
packed[3 + labelsz] = (uint8_t) datasz;
if (datasz > 0) memmove(packed + labelsz + 4, data, datasz);
packed[4 + labelsz + datasz] = 1;
mg_hmac_sha256(secret, key, keysz, packed, 5 + labelsz + datasz);
memmove(hash, secret, hashsz);
}
// at this point we have x25519 shared secret, we can generate a set of derived
// handshake encryption keys
static void mg_tls_generate_handshake_keys(struct mg_connection *c) {
struct tls_data *tls = (struct tls_data *) c->tls;
mg_sha256_ctx sha256;
uint8_t early_secret[32];
uint8_t pre_extract_secret[32];
uint8_t hello_hash[32];
uint8_t server_hs_secret[32];
uint8_t client_hs_secret[32];
#if CHACHA20
const size_t keysz = 32;
#else
const size_t keysz = 16;
#endif
mg_hmac_sha256(early_secret, NULL, 0, zeros, sizeof(zeros));
mg_tls_derive_secret("tls13 derived", early_secret, 32, zeros_sha256_digest,
32, pre_extract_secret, 32);
mg_hmac_sha256(tls->enc.handshake_secret, pre_extract_secret,
sizeof(pre_extract_secret), tls->x25519_sec,
sizeof(tls->x25519_sec));
mg_tls_hexdump("hs secret", tls->enc.handshake_secret, 32);
// mg_sha256_final is not idempotent, need to copy sha256 context to calculate
// the digest
memmove(&sha256, &tls->sha256, sizeof(mg_sha256_ctx));
mg_sha256_final(hello_hash, &sha256);
mg_tls_hexdump("hello hash", hello_hash, 32);
// derive keys needed for the rest of the handshake
mg_tls_derive_secret("tls13 s hs traffic", tls->enc.handshake_secret, 32,
hello_hash, 32, server_hs_secret, 32);
mg_tls_derive_secret("tls13 c hs traffic", tls->enc.handshake_secret, 32,
hello_hash, 32, client_hs_secret, 32);
mg_tls_derive_secret("tls13 key", server_hs_secret, 32, NULL, 0,
tls->enc.server_write_key, keysz);
mg_tls_derive_secret("tls13 iv", server_hs_secret, 32, NULL, 0,
tls->enc.server_write_iv, 12);
mg_tls_derive_secret("tls13 finished", server_hs_secret, 32, NULL, 0,
tls->enc.server_finished_key, 32);
mg_tls_derive_secret("tls13 key", client_hs_secret, 32, NULL, 0,
tls->enc.client_write_key, keysz);
mg_tls_derive_secret("tls13 iv", client_hs_secret, 32, NULL, 0,
tls->enc.client_write_iv, 12);
mg_tls_derive_secret("tls13 finished", client_hs_secret, 32, NULL, 0,
tls->enc.client_finished_key, 32);
mg_tls_hexdump("s hs traffic", server_hs_secret, 32);
mg_tls_hexdump("s key", tls->enc.server_write_key, keysz);
mg_tls_hexdump("s iv", tls->enc.server_write_iv, 12);
mg_tls_hexdump("s finished", tls->enc.server_finished_key, 32);
mg_tls_hexdump("c hs traffic", client_hs_secret, 32);
mg_tls_hexdump("c key", tls->enc.client_write_key, keysz);
mg_tls_hexdump("c iv", tls->enc.client_write_iv, 12);
mg_tls_hexdump("c finished", tls->enc.client_finished_key, 32);
#ifdef MG_TLS_SSLKEYLOGFILE
mg_ssl_key_log("SERVER_HANDSHAKE_TRAFFIC_SECRET", tls->random,
server_hs_secret, 32);
mg_ssl_key_log("CLIENT_HANDSHAKE_TRAFFIC_SECRET", tls->random,
client_hs_secret, 32);
#endif
}
static void mg_tls_generate_application_keys(struct mg_connection *c) {
struct tls_data *tls = (struct tls_data *) c->tls;
uint8_t hash[32];
uint8_t premaster_secret[32];
uint8_t master_secret[32];
uint8_t server_secret[32];
uint8_t client_secret[32];
#if CHACHA20
const size_t keysz = 32;
#else
const size_t keysz = 16;
#endif
mg_sha256_ctx sha256;
memmove(&sha256, &tls->sha256, sizeof(mg_sha256_ctx));
mg_sha256_final(hash, &sha256);
mg_tls_derive_secret("tls13 derived", tls->enc.handshake_secret, 32,
zeros_sha256_digest, 32, premaster_secret, 32);
mg_hmac_sha256(master_secret, premaster_secret, 32, zeros, 32);
mg_tls_derive_secret("tls13 s ap traffic", master_secret, 32, hash, 32,
server_secret, 32);
mg_tls_derive_secret("tls13 key", server_secret, 32, NULL, 0,
tls->enc.server_write_key, keysz);
mg_tls_derive_secret("tls13 iv", server_secret, 32, NULL, 0,
tls->enc.server_write_iv, 12);
mg_tls_derive_secret("tls13 c ap traffic", master_secret, 32, hash, 32,
client_secret, 32);
mg_tls_derive_secret("tls13 key", client_secret, 32, NULL, 0,
tls->enc.client_write_key, keysz);
mg_tls_derive_secret("tls13 iv", client_secret, 32, NULL, 0,
tls->enc.client_write_iv, 12);
mg_tls_hexdump("s ap traffic", server_secret, 32);
mg_tls_hexdump("s key", tls->enc.server_write_key, keysz);
mg_tls_hexdump("s iv", tls->enc.server_write_iv, 12);
mg_tls_hexdump("s finished", tls->enc.server_finished_key, 32);
mg_tls_hexdump("c ap traffic", client_secret, 32);
mg_tls_hexdump("c key", tls->enc.client_write_key, keysz);
mg_tls_hexdump("c iv", tls->enc.client_write_iv, 12);
mg_tls_hexdump("c finished", tls->enc.client_finished_key, 32);
tls->enc.sseq = tls->enc.cseq = 0;
#ifdef MG_TLS_SSLKEYLOGFILE
mg_ssl_key_log("SERVER_TRAFFIC_SECRET_0", tls->random, server_secret, 32);
mg_ssl_key_log("CLIENT_TRAFFIC_SECRET_0", tls->random, client_secret, 32);
#endif
}
// AES GCM encryption of the message + put encoded data into the write buffer
static void mg_tls_encrypt(struct mg_connection *c, const uint8_t *msg,
size_t msgsz, uint8_t msgtype) {
struct tls_data *tls = (struct tls_data *) c->tls;
struct mg_iobuf *wio = &tls->send;
uint8_t *outmsg;
uint8_t *tag;
size_t encsz = msgsz + 16 + 1;
uint8_t hdr[5] = {MG_TLS_APP_DATA, 0x03, 0x03,
(uint8_t) ((encsz >> 8) & 0xff), (uint8_t) (encsz & 0xff)};
uint8_t associated_data[5] = {MG_TLS_APP_DATA, 0x03, 0x03,
(uint8_t) ((encsz >> 8) & 0xff),
(uint8_t) (encsz & 0xff)};
uint8_t nonce[12];
uint32_t seq = c->is_client ? tls->enc.cseq : tls->enc.sseq;
uint8_t *key =
c->is_client ? tls->enc.client_write_key : tls->enc.server_write_key;
uint8_t *iv =
c->is_client ? tls->enc.client_write_iv : tls->enc.server_write_iv;
#if !CHACHA20
mg_gcm_initialize();
#endif
memmove(nonce, iv, sizeof(nonce));
nonce[8] ^= (uint8_t) ((seq >> 24) & 255U);
nonce[9] ^= (uint8_t) ((seq >> 16) & 255U);
nonce[10] ^= (uint8_t) ((seq >> 8) & 255U);
nonce[11] ^= (uint8_t) ((seq) &255U);
mg_iobuf_add(wio, wio->len, hdr, sizeof(hdr));
mg_iobuf_resize(wio, wio->len + encsz);
outmsg = wio->buf + wio->len;
tag = wio->buf + wio->len + msgsz + 1;
memmove(outmsg, msg, msgsz);
outmsg[msgsz] = msgtype;
#if CHACHA20
(void) tag; // tag is only used in aes gcm
{
size_t maxlen = MG_IO_SIZE > 16384 ? 16384 : MG_IO_SIZE;
uint8_t *enc = (uint8_t *) calloc(1, maxlen + 256 + 1);
if (enc == NULL) {
mg_error(c, "TLS OOM");
return;
} else {
size_t n = mg_chacha20_poly1305_encrypt(enc, key, nonce, associated_data,
sizeof(associated_data), outmsg,
msgsz + 1);
memmove(outmsg, enc, n);
free(enc);
}
}
#else
mg_aes_gcm_encrypt(outmsg, outmsg, msgsz + 1, key, 16, nonce, sizeof(nonce),
associated_data, sizeof(associated_data), tag, 16);
#endif
c->is_client ? tls->enc.cseq++ : tls->enc.sseq++;
wio->len += encsz;
}
// read an encrypted record, decrypt it in place
static int mg_tls_recv_record(struct mg_connection *c) {
struct tls_data *tls = (struct tls_data *) c->tls;
struct mg_iobuf *rio = &c->rtls;
uint16_t msgsz;
uint8_t *msg;
uint8_t nonce[12];
int r;
uint32_t seq = c->is_client ? tls->enc.sseq : tls->enc.cseq;
uint8_t *key =
c->is_client ? tls->enc.server_write_key : tls->enc.client_write_key;
uint8_t *iv =
c->is_client ? tls->enc.server_write_iv : tls->enc.client_write_iv;
if (tls->recv_len > 0) {
return 0; /* some data from previous record is still present */
}
for (;;) {
if (!mg_tls_got_record(c)) {
return MG_IO_WAIT;
}
if (rio->buf[0] == MG_TLS_APP_DATA) {
break;
} else if (rio->buf[0] ==
MG_TLS_CHANGE_CIPHER) { // Skip ChangeCipher messages
mg_tls_drop_record(c);
} else if (rio->buf[0] == MG_TLS_ALERT) { // Skip Alerts
MG_INFO(("TLS ALERT packet received"));
mg_tls_drop_record(c);
} else {
mg_error(c, "unexpected packet");
return -1;
}
}
msgsz = MG_LOAD_BE16(rio->buf + 3);
msg = rio->buf + 5;
if (msgsz < 16) {
mg_error(c, "wrong size");
return -1;
}
memmove(nonce, iv, sizeof(nonce));
nonce[8] ^= (uint8_t) ((seq >> 24) & 255U);
nonce[9] ^= (uint8_t) ((seq >> 16) & 255U);
nonce[10] ^= (uint8_t) ((seq >> 8) & 255U);
nonce[11] ^= (uint8_t) ((seq) &255U);
#if CHACHA20
{
uint8_t *dec = (uint8_t *) calloc(1, msgsz);
size_t n;
if (dec == NULL) {
mg_error(c, "TLS OOM");
return -1;
}
n = mg_chacha20_poly1305_decrypt(dec, key, nonce, msg, msgsz);
memmove(msg, dec, n);
free(dec);
}
#else
mg_gcm_initialize();
mg_aes_gcm_decrypt(msg, msg, msgsz - 16, key, 16, nonce, sizeof(nonce));
#endif
r = msgsz - 16 - 1;
tls->content_type = msg[msgsz - 16 - 1];
tls->recv_offset = (size_t) msg - (size_t) rio->buf;
tls->recv_len = (size_t) msgsz - 16 - 1;
c->is_client ? tls->enc.sseq++ : tls->enc.cseq++;
return r;
}
static void mg_tls_calc_cert_verify_hash(struct mg_connection *c,
uint8_t hash[32], int is_client) {
struct tls_data *tls = (struct tls_data *) c->tls;
uint8_t server_context[34] = "TLS 1.3, server CertificateVerify";
uint8_t client_context[34] = "TLS 1.3, client CertificateVerify";
uint8_t sig_content[130];
mg_sha256_ctx sha256;
memset(sig_content, 0x20, 64);
if (is_client) {
memmove(sig_content + 64, client_context, sizeof(client_context));
} else {
memmove(sig_content + 64, server_context, sizeof(server_context));
}
memmove(&sha256, &tls->sha256, sizeof(mg_sha256_ctx));
mg_sha256_final(sig_content + 98, &sha256);
mg_sha256_init(&sha256);
mg_sha256_update(&sha256, sig_content, sizeof(sig_content));
mg_sha256_final(hash, &sha256);
}
// read and parse ClientHello record
static int mg_tls_server_recv_hello(struct mg_connection *c) {
struct tls_data *tls = (struct tls_data *) c->tls;
struct mg_iobuf *rio = &c->rtls;
uint8_t session_id_len;
uint16_t j;
uint16_t cipher_suites_len;
uint16_t ext_len;
uint8_t *ext;
uint16_t msgsz;
if (!mg_tls_got_record(c)) {
return MG_IO_WAIT;
}
if (rio->buf[0] != MG_TLS_HANDSHAKE || rio->buf[5] != MG_TLS_CLIENT_HELLO) {
mg_error(c, "not a client hello packet");
return -1;
}
msgsz = MG_LOAD_BE16(rio->buf + 3);
mg_sha256_update(&tls->sha256, rio->buf + 5, msgsz);
// store client random
memmove(tls->random, rio->buf + 11, sizeof(tls->random));
// store session_id
session_id_len = rio->buf[43];
if (session_id_len == sizeof(tls->session_id)) {
memmove(tls->session_id, rio->buf + 44, session_id_len);
} else if (session_id_len != 0) {
MG_INFO(("bad session id len"));
}
cipher_suites_len = MG_LOAD_BE16(rio->buf + 44 + session_id_len);
if (cipher_suites_len > (rio->len - 46 - session_id_len)) goto fail;
ext_len = MG_LOAD_BE16(rio->buf + 48 + session_id_len + cipher_suites_len);
ext = rio->buf + 50 + session_id_len + cipher_suites_len;
if (ext_len > (rio->len - 50 - session_id_len - cipher_suites_len)) goto fail;
for (j = 0; j < ext_len;) {
uint16_t k;
uint16_t key_exchange_len;
uint8_t *key_exchange;
uint16_t n = MG_LOAD_BE16(ext + j + 2);
if (MG_LOAD_BE16(ext + j) != 0x0033) { // not a key share extension, ignore
j += (uint16_t) (n + 4);
continue;
}
key_exchange_len = MG_LOAD_BE16(ext + j + 4);
key_exchange = ext + j + 6;
if (key_exchange_len >
rio->len - (uint16_t) ((size_t) key_exchange - (size_t) rio->buf))
goto fail;
for (k = 0; k < key_exchange_len;) {
uint16_t m = MG_LOAD_BE16(key_exchange + k + 2);
if (m > (key_exchange_len - k - 4)) goto fail;
if (m == 32 && key_exchange[k] == 0x00 && key_exchange[k + 1] == 0x1d) {
memmove(tls->x25519_cli, key_exchange + k + 4, m);
mg_tls_drop_record(c);
return 0;
}
k += (uint16_t) (m + 4);
}
j += (uint16_t) (n + 4);
}
fail:
mg_error(c, "bad client hello");
return -1;
}
#define PLACEHOLDER_8B 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X'
#define PLACEHOLDER_16B PLACEHOLDER_8B, PLACEHOLDER_8B
#define PLACEHOLDER_32B PLACEHOLDER_16B, PLACEHOLDER_16B
// put ServerHello record into wio buffer
static void mg_tls_server_send_hello(struct mg_connection *c) {
struct tls_data *tls = (struct tls_data *) c->tls;
struct mg_iobuf *wio = &tls->send;
// clang-format off
uint8_t msg_server_hello[122] = {
// server hello, tls 1.2
0x02, 0x00, 0x00, 0x76, 0x03, 0x03,
// random (32 bytes)
PLACEHOLDER_32B,
// session ID length + session ID (32 bytes)
0x20, PLACEHOLDER_32B,
#if defined(CHACHA20) && CHACHA20
// TLS_CHACHA20_POLY1305_SHA256 + no compression
0x13, 0x03, 0x00,
#else
// TLS_AES_128_GCM_SHA256 + no compression
0x13, 0x01, 0x00,
#endif
// extensions + keyshare
0x00, 0x2e, 0x00, 0x33, 0x00, 0x24, 0x00, 0x1d, 0x00, 0x20,
// x25519 keyshare
PLACEHOLDER_32B,
// supported versions (tls1.3 == 0x304)
0x00, 0x2b, 0x00, 0x02, 0x03, 0x04};
// clang-format on
// calculate keyshare
uint8_t x25519_pub[X25519_BYTES];
uint8_t x25519_prv[X25519_BYTES];
if (!mg_random(x25519_prv, sizeof(x25519_prv))) mg_error(c, "RNG");
mg_tls_x25519(x25519_pub, x25519_prv, X25519_BASE_POINT, 1);
mg_tls_x25519(tls->x25519_sec, x25519_prv, tls->x25519_cli, 1);
mg_tls_hexdump("s x25519 sec", tls->x25519_sec, sizeof(tls->x25519_sec));
// fill in the gaps: random + session ID + keyshare
memmove(msg_server_hello + 6, tls->random, sizeof(tls->random));
memmove(msg_server_hello + 39, tls->session_id, sizeof(tls->session_id));
memmove(msg_server_hello + 84, x25519_pub, sizeof(x25519_pub));
// server hello message
mg_iobuf_add(wio, wio->len, "\x16\x03\x03\x00\x7a", 5);
mg_iobuf_add(wio, wio->len, msg_server_hello, sizeof(msg_server_hello));
mg_sha256_update(&tls->sha256, msg_server_hello, sizeof(msg_server_hello));
// change cipher message
mg_iobuf_add(wio, wio->len, "\x14\x03\x03\x00\x01\x01", 6);
}
static void mg_tls_server_send_ext(struct mg_connection *c) {
struct tls_data *tls = (struct tls_data *) c->tls;
// server extensions
uint8_t ext[6] = {0x08, 0, 0, 2, 0, 0};
mg_sha256_update(&tls->sha256, ext, sizeof(ext));
mg_tls_encrypt(c, ext, sizeof(ext), MG_TLS_HANDSHAKE);
}
static void mg_tls_server_send_cert(struct mg_connection *c) {
struct tls_data *tls = (struct tls_data *) c->tls;
int send_ca = !c->is_client && tls->ca_der.len > 0;
// server DER certificate + CA (optional)
size_t n = tls->cert_der.len + (send_ca ? tls->ca_der.len + 5 : 0);
uint8_t *cert = (uint8_t *) calloc(1, 13 + n);
if (cert == NULL) {
mg_error(c, "tls cert oom");
return;
}
cert[0] = 0x0b; // handshake header
MG_STORE_BE24(cert + 1, n + 9);
cert[4] = 0; // request context
MG_STORE_BE24(cert + 5, n + 5); // 3 bytes: cert (s) length
MG_STORE_BE24(cert + 8, tls->cert_der.len); // 3 bytes: first cert len
// bytes 11+ are certificate in DER format
memmove(cert + 11, tls->cert_der.buf, tls->cert_der.len);
MG_STORE_BE16(cert + 11 + tls->cert_der.len,
0); // certificate extensions (none)
if (send_ca) {
size_t offset = 13 + tls->cert_der.len;
MG_STORE_BE24(cert + offset, tls->ca_der.len); // 3 bytes: CA cert length
memmove(cert + offset + 3, tls->ca_der.buf,
tls->ca_der.len); // CA cert data
MG_STORE_BE16(cert + 11 + n, 0); // certificate extensions (none)
}
mg_sha256_update(&tls->sha256, cert, 13 + n);
mg_tls_encrypt(c, cert, 13 + n, MG_TLS_HANDSHAKE);
free(cert);
}
// type adapter between uECC hash context and our sha256 implementation
typedef struct SHA256_HashContext {
MG_UECC_HashContext uECC;
mg_sha256_ctx ctx;
} SHA256_HashContext;
static void init_SHA256(const MG_UECC_HashContext *base) {
SHA256_HashContext *c = (SHA256_HashContext *) base;
mg_sha256_init(&c->ctx);
}
static void update_SHA256(const MG_UECC_HashContext *base,
const uint8_t *message, unsigned message_size) {
SHA256_HashContext *c = (SHA256_HashContext *) base;
mg_sha256_update(&c->ctx, message, message_size);
}
static void finish_SHA256(const MG_UECC_HashContext *base,
uint8_t *hash_result) {
SHA256_HashContext *c = (SHA256_HashContext *) base;
mg_sha256_final(hash_result, &c->ctx);
}
static void mg_tls_send_cert_verify(struct mg_connection *c, int is_client) {
struct tls_data *tls = (struct tls_data *) c->tls;
// server certificate verify packet
uint8_t verify[82] = {0x0f, 0x00, 0x00, 0x00, 0x04, 0x03, 0x00, 0x00};
size_t sigsz, verifysz = 0;
uint8_t hash[32] = {0}, tmp[2 * 32 + 64] = {0};
struct SHA256_HashContext ctx = {
{&init_SHA256, &update_SHA256, &finish_SHA256, 64, 32, tmp},
{{0}, 0, 0, {0}}};
int neg1, neg2;
uint8_t sig[64] = {0};
mg_tls_calc_cert_verify_hash(c, (uint8_t *) hash, is_client);
mg_uecc_sign_deterministic(tls->ec_key, hash, sizeof(hash), &ctx.uECC, sig,
mg_uecc_secp256r1());
neg1 = !!(sig[0] & 0x80);
neg2 = !!(sig[32] & 0x80);
verify[8] = 0x30; // ASN.1 SEQUENCE
verify[9] = (uint8_t) (68 + neg1 + neg2);
verify[10] = 0x02; // ASN.1 INTEGER
verify[11] = (uint8_t) (32 + neg1);
memmove(verify + 12 + neg1, sig, 32);
verify[12 + 32 + neg1] = 0x02; // ASN.1 INTEGER
verify[13 + 32 + neg1] = (uint8_t) (32 + neg2);
memmove(verify + 14 + 32 + neg1 + neg2, sig + 32, 32);
sigsz = (size_t) (70 + neg1 + neg2);
verifysz = 8U + sigsz;
verify[3] = (uint8_t) (sigsz + 4);
verify[7] = (uint8_t) sigsz;
mg_sha256_update(&tls->sha256, verify, verifysz);
mg_tls_encrypt(c, verify, verifysz, MG_TLS_HANDSHAKE);
}
static void mg_tls_server_send_finish(struct mg_connection *c) {
struct tls_data *tls = (struct tls_data *) c->tls;
struct mg_iobuf *wio = &tls->send;
mg_sha256_ctx sha256;
uint8_t hash[32];
uint8_t finish[36] = {0x14, 0, 0, 32};
memmove(&sha256, &tls->sha256, sizeof(mg_sha256_ctx));
mg_sha256_final(hash, &sha256);
mg_hmac_sha256(finish + 4, tls->enc.server_finished_key, 32, hash, 32);
mg_tls_encrypt(c, finish, sizeof(finish), MG_TLS_HANDSHAKE);
mg_io_send(c, wio->buf, wio->len);
wio->len = 0;
mg_sha256_update(&tls->sha256, finish, sizeof(finish));
}
static int mg_tls_server_recv_finish(struct mg_connection *c) {
struct tls_data *tls = (struct tls_data *) c->tls;
unsigned char *recv_buf;
// we have to backup sha256 value to restore it later, since Finished record
// is exceptional and is not supposed to be added to the rolling hash
// calculation.
mg_sha256_ctx sha256 = tls->sha256;
if (mg_tls_recv_record(c) < 0) {
return -1;
}
recv_buf = &c->rtls.buf[tls->recv_offset];
if (recv_buf[0] != MG_TLS_FINISHED) {
mg_error(c, "expected Finish but got msg 0x%02x", recv_buf[0]);
return -1;
}
mg_tls_drop_message(c);
// restore hash
tls->sha256 = sha256;
return 0;
}
static void mg_tls_client_send_hello(struct mg_connection *c) {
struct tls_data *tls = (struct tls_data *) c->tls;
struct mg_iobuf *wio = &tls->send;
uint8_t x25519_pub[X25519_BYTES];
// signature algorithms we actually support:
// rsa_pkcs1_sha256, rsa_pss_rsae_sha256 and ecdsa_secp256r1_sha256
uint8_t secp256r1_sig_algs[12] = {
0x00, 0x0d, 0x00, 0x08, 0x00, 0x06, 0x04, 0x03, 0x08, 0x04, 0x04, 0x01,
};
// all popular signature algorithms (if we don't care about verification)
uint8_t all_sig_algs[34] = {
0x00, 0x0d, 0x00, 0x1e, 0x00, 0x1c, 0x04, 0x03, 0x05, 0x03, 0x06, 0x03,
0x08, 0x07, 0x08, 0x08, 0x08, 0x09, 0x08, 0x0a, 0x08, 0x0b, 0x08, 0x04,
0x08, 0x05, 0x08, 0x06, 0x04, 0x01, 0x05, 0x01, 0x06, 0x01};
uint8_t server_name_ext[9] = {0x00, 0x00, 0x00, 0xfe, 0x00,
0xfe, 0x00, 0x00, 0xfe};
// clang-format off
uint8_t msg_client_hello[145] = {
// TLS Client Hello header reported as TLS1.2 (5)
0x16, 0x03, 0x03, 0x00, 0xfe,
// client hello, tls 1.2 (6)
0x01, 0x00, 0x00, 0x8c, 0x03, 0x03,
// random (32 bytes)
PLACEHOLDER_32B,
// session ID length + session ID (32 bytes)
0x20, PLACEHOLDER_32B, 0x00,
0x02, // size = 2 bytes
#if defined(CHACHA20) && CHACHA20
// TLS_CHACHA20_POLY1305_SHA256
0x13, 0x03,
#else
// TLS_AES_128_GCM_SHA256
0x13, 0x01,
#endif
// no compression
0x01, 0x00,
// extensions + keyshare
0x00, 0xfe,
// x25519 keyshare
0x00, 0x33, 0x00, 0x26, 0x00, 0x24, 0x00, 0x1d, 0x00, 0x20,
PLACEHOLDER_32B,
// supported groups (x25519)
0x00, 0x0a, 0x00, 0x04, 0x00, 0x02, 0x00, 0x1d,
// supported versions (tls1.3 == 0x304)
0x00, 0x2b, 0x00, 0x03, 0x02, 0x03, 0x04,
// session ticket (none)
0x00, 0x23, 0x00, 0x00, // 144 bytes till here
};
// clang-format on
const char *hostname = tls->hostname;
size_t hostnamesz = strlen(tls->hostname);
size_t hostname_extsz = hostnamesz ? hostnamesz + 9 : 0;
uint8_t *sig_alg = tls->skip_verification ? all_sig_algs : secp256r1_sig_algs;
size_t sig_alg_sz = tls->skip_verification ? sizeof(all_sig_algs)
: sizeof(secp256r1_sig_algs);
// patch ClientHello with correct hostname ext length (if any)
MG_STORE_BE16(msg_client_hello + 3,
hostname_extsz + 183 - 9 - 34 + sig_alg_sz);
MG_STORE_BE16(msg_client_hello + 7,
hostname_extsz + 179 - 9 - 34 + sig_alg_sz);
MG_STORE_BE16(msg_client_hello + 82,
hostname_extsz + 104 - 9 - 34 + sig_alg_sz);
if (hostnamesz > 0) {
MG_STORE_BE16(server_name_ext + 2, hostnamesz + 5);
MG_STORE_BE16(server_name_ext + 4, hostnamesz + 3);
MG_STORE_BE16(server_name_ext + 7, hostnamesz);
}
// calculate keyshare
if (!mg_random(tls->x25519_cli, sizeof(tls->x25519_cli))) mg_error(c, "RNG");
mg_tls_x25519(x25519_pub, tls->x25519_cli, X25519_BASE_POINT, 1);
// fill in the gaps: random + session ID + keyshare
if (!mg_random(tls->session_id, sizeof(tls->session_id))) mg_error(c, "RNG");
if (!mg_random(tls->random, sizeof(tls->random))) mg_error(c, "RNG");
memmove(msg_client_hello + 11, tls->random, sizeof(tls->random));
memmove(msg_client_hello + 44, tls->session_id, sizeof(tls->session_id));
memmove(msg_client_hello + 94, x25519_pub, sizeof(x25519_pub));
// client hello message
mg_iobuf_add(wio, wio->len, msg_client_hello, sizeof(msg_client_hello));
mg_sha256_update(&tls->sha256, msg_client_hello + 5,
sizeof(msg_client_hello) - 5);
mg_iobuf_add(wio, wio->len, sig_alg, sig_alg_sz);
mg_sha256_update(&tls->sha256, sig_alg, sig_alg_sz);
if (hostnamesz > 0) {
mg_iobuf_add(wio, wio->len, server_name_ext, sizeof(server_name_ext));
mg_iobuf_add(wio, wio->len, hostname, hostnamesz);
mg_sha256_update(&tls->sha256, server_name_ext, sizeof(server_name_ext));
mg_sha256_update(&tls->sha256, (uint8_t *) hostname, hostnamesz);
}
// change cipher message
mg_iobuf_add(wio, wio->len, (const char *) "\x14\x03\x03\x00\x01\x01", 6);
mg_io_send(c, wio->buf, wio->len);
wio->len = 0;
}
static int mg_tls_client_recv_hello(struct mg_connection *c) {
struct tls_data *tls = (struct tls_data *) c->tls;
struct mg_iobuf *rio = &c->rtls;
uint16_t msgsz;
uint8_t *ext;
uint16_t ext_len;
int j;
if (!mg_tls_got_record(c)) {
return MG_IO_WAIT;
}
if (rio->buf[0] != MG_TLS_HANDSHAKE || rio->buf[5] != MG_TLS_SERVER_HELLO) {
if (rio->buf[0] == MG_TLS_ALERT && rio->len >= 7) {
mg_error(c, "tls alert %d", rio->buf[6]);
return -1;
}
MG_INFO(("got packet type 0x%02x/0x%02x", rio->buf[0], rio->buf[5]));
mg_error(c, "not a server hello packet");
return -1;
}
msgsz = MG_LOAD_BE16(rio->buf + 3);
mg_sha256_update(&tls->sha256, rio->buf + 5, msgsz);
ext_len = MG_LOAD_BE16(rio->buf + 5 + 39 + 32 + 3);
ext = rio->buf + 5 + 39 + 32 + 3 + 2;
if (ext_len > (rio->len - (5 + 39 + 32 + 3 + 2))) goto fail;
for (j = 0; j < ext_len;) {
uint16_t ext_type = MG_LOAD_BE16(ext + j);
uint16_t ext_len2 = MG_LOAD_BE16(ext + j + 2);
uint16_t group;
uint8_t *key_exchange;
uint16_t key_exchange_len;
if (ext_len2 > (ext_len - j - 4)) goto fail;
if (ext_type != 0x0033) { // not a key share extension, ignore
j += (uint16_t) (ext_len2 + 4);
continue;
}
group = MG_LOAD_BE16(ext + j + 4);
if (group != 0x001d) {
mg_error(c, "bad key exchange group");
return -1;
}
key_exchange_len = MG_LOAD_BE16(ext + j + 6);
key_exchange = ext + j + 8;
if (key_exchange_len != 32) {
mg_error(c, "bad key exchange length");
return -1;
}
mg_tls_x25519(tls->x25519_sec, tls->x25519_cli, key_exchange, 1);
mg_tls_hexdump("c x25519 sec", tls->x25519_sec, 32);
mg_tls_drop_record(c);
/* generate handshake keys */
mg_tls_generate_handshake_keys(c);
return 0;
}
fail:
mg_error(c, "bad server hello");
return -1;
}
static int mg_tls_client_recv_ext(struct mg_connection *c) {
struct tls_data *tls = (struct tls_data *) c->tls;
unsigned char *recv_buf;
if (mg_tls_recv_record(c) < 0) {
return -1;
}
recv_buf = &c->rtls.buf[tls->recv_offset];
if (recv_buf[0] != MG_TLS_ENCRYPTED_EXTENSIONS) {
mg_error(c, "expected server extensions but got msg 0x%02x", recv_buf[0]);
return -1;
}
mg_tls_drop_message(c);
return 0;
}
struct mg_tls_cert {
int is_ec_pubkey;
struct mg_str sn;
struct mg_str pubkey;
struct mg_str sig; // signature
uint8_t tbshash[48]; // 32b for sha256/secp256, 48b for sha384/secp384
size_t tbshashsz; // actual TBS hash size
};
static void mg_der_debug_cert_name(const char *name, struct mg_der_tlv *tlv) {
struct mg_der_tlv v;