-
Notifications
You must be signed in to change notification settings - Fork 171
Expand file tree
/
Copy pathpicotls.c
More file actions
6611 lines (5852 loc) · 258 KB
/
picotls.c
File metadata and controls
6611 lines (5852 loc) · 258 KB
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
/*
* Copyright (c) 2016 DeNA Co., Ltd., Kazuho Oku
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
#ifdef _WIN32
#include "wincompat.h"
#endif
#include <assert.h>
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifndef _WIN32
#include <errno.h>
#include <pthread.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/time.h>
#endif
#include "picotls.h"
#if PICOTLS_USE_DTRACE
#include "picotls-probes.h"
#endif
#define PTLS_MAX_PLAINTEXT_RECORD_SIZE 16384
#define PTLS_MAX_ENCRYPTED_RECORD_SIZE (16384 + 256)
#define PTLS_RECORD_VERSION_MAJOR 3
#define PTLS_RECORD_VERSION_MINOR 3
#define PTLS_CONTENT_TYPE_CHANGE_CIPHER_SPEC 20
#define PTLS_CONTENT_TYPE_ALERT 21
#define PTLS_CONTENT_TYPE_HANDSHAKE 22
#define PTLS_CONTENT_TYPE_APPDATA 23
#define PTLS_PSK_KE_MODE_PSK 0
#define PTLS_PSK_KE_MODE_PSK_DHE 1
#define PTLS_HANDSHAKE_HEADER_SIZE 4
#define PTLS_EXTENSION_TYPE_SERVER_NAME 0
#define PTLS_EXTENSION_TYPE_STATUS_REQUEST 5
#define PTLS_EXTENSION_TYPE_SUPPORTED_GROUPS 10
#define PTLS_EXTENSION_TYPE_SIGNATURE_ALGORITHMS 13
#define PTLS_EXTENSION_TYPE_ALPN 16
#define PTLS_EXTENSION_TYPE_SERVER_CERTIFICATE_TYPE 20
#define PTLS_EXTENSION_TYPE_COMPRESS_CERTIFICATE 27
#define PTLS_EXTENSION_TYPE_PRE_SHARED_KEY 41
#define PTLS_EXTENSION_TYPE_EARLY_DATA 42
#define PTLS_EXTENSION_TYPE_SUPPORTED_VERSIONS 43
#define PTLS_EXTENSION_TYPE_COOKIE 44
#define PTLS_EXTENSION_TYPE_PSK_KEY_EXCHANGE_MODES 45
#define PTLS_EXTENSION_TYPE_KEY_SHARE 51
#define PTLS_EXTENSION_TYPE_ECH_OUTER_EXTENSIONS 0xfd00
#define PTLS_EXTENSION_TYPE_ENCRYPTED_CLIENT_HELLO 0xfe0d
#define PTLS_SERVER_NAME_TYPE_HOSTNAME 0
#define PTLS_ECH_CONFIG_VERSION 0xfe0d
#define PTLS_ECH_CLIENT_HELLO_TYPE_OUTER 0
#define PTLS_ECH_CLIENT_HELLO_TYPE_INNER 1
#define PTLS_ECH_CONFIRM_LENGTH 8
static const char ech_info_prefix[8] = "tls ech";
#define PTLS_SERVER_CERTIFICATE_VERIFY_CONTEXT_STRING "TLS 1.3, server CertificateVerify"
#define PTLS_CLIENT_CERTIFICATE_VERIFY_CONTEXT_STRING "TLS 1.3, client CertificateVerify"
#define PTLS_MAX_CERTIFICATE_VERIFY_SIGNDATA_SIZE \
(64 + sizeof(PTLS_SERVER_CERTIFICATE_VERIFY_CONTEXT_STRING) + PTLS_MAX_DIGEST_SIZE * 2)
#define PTLS_EARLY_DATA_MAX_DELAY 10000 /* max. RTT (in msec) to permit early data */
#ifndef PTLS_MAX_EARLY_DATA_SKIP_SIZE
#define PTLS_MAX_EARLY_DATA_SKIP_SIZE 65536
#endif
#if defined(PTLS_DEBUG) && PTLS_DEBUG
#define PTLS_DEBUGF(...) fprintf(stderr, __VA_ARGS__)
#else
#define PTLS_DEBUGF(...)
#endif
#ifndef PTLS_MEMORY_DEBUG
#define PTLS_MEMORY_DEBUG 0
#endif
#if PICOTLS_USE_DTRACE
#define PTLS_SHOULD_PROBE(LABEL, tls) (PTLS_UNLIKELY(PICOTLS_##LABEL##_ENABLED()) && !(tls)->skip_tracing)
#define PTLS_PROBE0(LABEL, tls) \
do { \
ptls_t *_tls = (tls); \
if (PTLS_SHOULD_PROBE(LABEL, _tls)) \
PICOTLS_##LABEL(_tls); \
} while (0)
#define PTLS_PROBE(LABEL, tls, ...) \
do { \
ptls_t *_tls = (tls); \
if (PTLS_SHOULD_PROBE(LABEL, _tls)) \
PICOTLS_##LABEL(_tls, __VA_ARGS__); \
} while (0)
#else
#define PTLS_PROBE0(LABEL, tls)
#define PTLS_PROBE(LABEL, tls, ...)
#endif
/**
* list of supported versions in the preferred order
*/
static const uint16_t supported_versions[] = {PTLS_PROTOCOL_VERSION_TLS13};
static const uint8_t hello_retry_random[PTLS_HELLO_RANDOM_SIZE] = {0xCF, 0x21, 0xAD, 0x74, 0xE5, 0x9A, 0x61, 0x11, 0xBE, 0x1D, 0x8C,
0x02, 0x1E, 0x65, 0xB8, 0x91, 0xC2, 0xA2, 0x11, 0x16, 0x7A, 0xBB,
0x8C, 0x5E, 0x07, 0x9E, 0x09, 0xE2, 0xC8, 0xA8, 0x33, 0x9C};
struct st_ptls_traffic_protection_t {
uint8_t secret[PTLS_MAX_DIGEST_SIZE];
size_t epoch;
/* the following fields are not used if the key_change callback is set */
ptls_aead_context_t *aead;
uint64_t seq;
unsigned tls12 : 1;
uint64_t tls12_enc_record_iv;
};
struct st_ptls_record_message_emitter_t {
ptls_message_emitter_t super;
size_t rec_start;
};
struct st_ptls_signature_algorithms_t {
uint16_t list[16]; /* expand? */
size_t count;
};
struct st_ptls_certificate_request_t {
/**
* context.base becomes non-NULL when a CertificateRequest is pending for processing
*/
ptls_iovec_t context;
struct st_ptls_signature_algorithms_t signature_algorithms;
};
struct st_decoded_ech_config_t {
uint8_t id;
ptls_hpke_kem_t *kem;
ptls_iovec_t public_key;
ptls_hpke_cipher_suite_t *cipher;
uint8_t max_name_length;
ptls_iovec_t public_name;
ptls_iovec_t bytes;
};
/**
* Properties for ECH. Iff ECH is used and not rejected, `aead` is non-NULL.
*/
struct st_ptls_ech_t {
uint8_t offered : 1;
uint8_t offered_grease : 1;
uint8_t accepted : 1;
uint8_t config_id;
ptls_hpke_kem_t *kem;
ptls_hpke_cipher_suite_t *cipher;
ptls_aead_context_t *aead;
uint8_t inner_client_random[PTLS_HELLO_RANDOM_SIZE];
struct {
ptls_iovec_t enc;
uint8_t max_name_length;
char *public_name;
/**
* retains a copy of entire ECH extension so that it can be replayed in the 2nd CH when ECH is rejected via HRR
*/
ptls_iovec_t first_ech;
} client;
};
struct st_ptls_t {
/**
* the context
*/
ptls_context_t *ctx;
/**
* the state
*/
enum en_ptls_state_t {
PTLS_STATE_CLIENT_HANDSHAKE_START,
PTLS_STATE_CLIENT_EXPECT_SERVER_HELLO,
PTLS_STATE_CLIENT_EXPECT_SECOND_SERVER_HELLO,
PTLS_STATE_CLIENT_EXPECT_ENCRYPTED_EXTENSIONS,
PTLS_STATE_CLIENT_EXPECT_CERTIFICATE_REQUEST_OR_CERTIFICATE,
PTLS_STATE_CLIENT_EXPECT_CERTIFICATE,
PTLS_STATE_CLIENT_EXPECT_CERTIFICATE_VERIFY,
PTLS_STATE_CLIENT_EXPECT_FINISHED,
PTLS_STATE_SERVER_EXPECT_CLIENT_HELLO,
PTLS_STATE_SERVER_EXPECT_SECOND_CLIENT_HELLO,
PTLS_STATE_SERVER_GENERATING_CERTIFICATE_VERIFY,
PTLS_STATE_SERVER_EXPECT_CERTIFICATE,
PTLS_STATE_SERVER_EXPECT_CERTIFICATE_VERIFY,
/* ptls_send can be called if the state is below here */
PTLS_STATE_SERVER_EXPECT_END_OF_EARLY_DATA,
PTLS_STATE_SERVER_EXPECT_FINISHED,
PTLS_STATE_POST_HANDSHAKE_MIN,
PTLS_STATE_CLIENT_POST_HANDSHAKE = PTLS_STATE_POST_HANDSHAKE_MIN,
PTLS_STATE_SERVER_POST_HANDSHAKE
} state;
/**
* receive buffers
*/
struct {
ptls_buffer_t rec;
ptls_buffer_t mess;
} recvbuf;
/**
* key schedule
*/
ptls_key_schedule_t *key_schedule;
/**
* values used for record protection
*/
struct {
struct st_ptls_traffic_protection_t dec;
struct st_ptls_traffic_protection_t enc;
} traffic_protection;
/**
* server-name passed using SNI
*/
char *server_name;
/**
* result of ALPN
*/
char *negotiated_protocol;
/**
* selected key-exchange
*/
ptls_key_exchange_algorithm_t *key_share;
/**
* selected cipher-suite
*/
ptls_cipher_suite_t *cipher_suite;
/**
* ClientHello.random that appears on the wire. When ECH is used, that of inner CH is retained separately.
*/
uint8_t client_random[PTLS_HELLO_RANDOM_SIZE];
/**
* exporter master secret (either 0rtt or 1rtt)
*/
struct {
uint8_t *early;
uint8_t *one_rtt;
} exporter_master_secret;
/**
* ECH
*/
struct st_ptls_ech_t ech;
/* flags */
unsigned is_server : 1;
unsigned is_psk_handshake : 1;
unsigned send_change_cipher_spec : 1;
unsigned needs_key_update : 1;
unsigned key_update_send_request : 1;
unsigned skip_tracing : 1;
/**
* misc.
*/
union {
struct {
ptls_iovec_t legacy_session_id;
uint8_t legacy_session_id_buf[32];
ptls_key_exchange_context_t *key_share_ctx;
unsigned offered_psk : 1;
/**
* if 1-RTT write key is active
*/
unsigned using_early_data : 1;
struct st_ptls_certificate_request_t certificate_request;
} client;
struct {
uint8_t pending_traffic_secret[PTLS_MAX_DIGEST_SIZE];
uint32_t early_data_skipped_bytes; /* if not UINT32_MAX, the server is skipping early data */
unsigned can_send_session_ticket : 1;
ptls_async_job_t *async_job;
} server;
};
/**
* certificate verify; will be used by the client and the server (if require_client_authentication is set)
*/
struct {
int (*cb)(void *verify_ctx, uint16_t algo, ptls_iovec_t data, ptls_iovec_t signature);
void *verify_ctx;
} certificate_verify;
/**
* handshake traffic secret to be commisioned (an array of `uint8_t [PTLS_MAX_DIGEST_SIZE]` or NULL)
*/
uint8_t *pending_handshake_secret;
/**
* user data
*/
void *data_ptr;
};
struct st_ptls_record_t {
uint8_t type;
uint16_t version;
size_t length;
const uint8_t *fragment;
};
struct st_ptls_client_hello_psk_t {
ptls_iovec_t identity;
uint32_t obfuscated_ticket_age;
ptls_iovec_t binder;
};
#define MAX_UNKNOWN_EXTENSIONS 16
#define MAX_CLIENT_CIPHERS 32
#define MAX_CERTIFICATE_TYPES 8
struct st_ptls_client_hello_t {
uint16_t legacy_version;
const uint8_t *random_bytes;
ptls_iovec_t legacy_session_id;
struct {
const uint8_t *ids;
size_t count;
} compression_methods;
uint16_t selected_version;
ptls_iovec_t cipher_suites;
ptls_iovec_t negotiated_groups;
ptls_iovec_t key_shares;
struct st_ptls_signature_algorithms_t signature_algorithms;
ptls_iovec_t server_name;
struct {
ptls_iovec_t list[16];
size_t count;
} alpn;
struct {
uint16_t list[16];
size_t count;
} cert_compression_algos;
struct {
uint16_t list[MAX_CLIENT_CIPHERS];
size_t count;
} client_ciphers;
struct {
ptls_iovec_t all;
ptls_iovec_t tbs;
ptls_iovec_t ch1_hash;
ptls_iovec_t signature;
unsigned sent_key_share : 1;
} cookie;
struct {
uint8_t list[MAX_CERTIFICATE_TYPES];
size_t count;
} server_certificate_types;
unsigned status_request : 1;
/**
* ECH: payload.base != NULL indicates that the extension was received
*/
struct {
uint8_t type;
uint8_t config_id;
ptls_hpke_cipher_suite_id_t cipher_suite;
ptls_iovec_t enc;
ptls_iovec_t payload;
} ech;
struct {
const uint8_t *hash_end;
struct {
struct st_ptls_client_hello_psk_t list[4];
size_t count;
} identities;
unsigned ke_modes;
unsigned early_data_indication : 1;
unsigned is_last_extension : 1;
} psk;
ptls_raw_extension_t unknown_extensions[MAX_UNKNOWN_EXTENSIONS + 1];
size_t first_extension_at;
};
struct st_ptls_server_hello_t {
uint8_t random_[PTLS_HELLO_RANDOM_SIZE];
ptls_iovec_t legacy_session_id;
int is_retry_request;
union {
ptls_iovec_t peerkey;
struct {
uint16_t selected_group;
ptls_iovec_t cookie;
const uint8_t *ech;
} retry_request;
};
};
struct st_ptls_key_schedule_t {
unsigned generation; /* early secret (1), hanshake secret (2), master secret (3) */
uint8_t secret[PTLS_MAX_DIGEST_SIZE];
size_t num_hashes;
struct {
ptls_hash_algorithm_t *algo;
ptls_hash_context_t *ctx, *ctx_outer;
} hashes[1];
};
struct st_ptls_extension_decoder_t {
uint16_t type;
int (*cb)(ptls_t *tls, void *arg, const uint8_t *src, const uint8_t *const end);
};
struct st_ptls_extension_bitmap_t {
uint64_t bits;
};
static const uint8_t zeroes_of_max_digest_size[PTLS_MAX_DIGEST_SIZE] = {0};
static ptls_aead_context_t *new_aead(ptls_aead_algorithm_t *aead, ptls_hash_algorithm_t *hash, int is_enc, const void *secret,
ptls_iovec_t hash_value, const char *label_prefix);
static int server_finish_handshake(ptls_t *tls, ptls_message_emitter_t *emitter, int send_cert_verify,
struct st_ptls_signature_algorithms_t *signature_algorithms);
static int is_supported_version(uint16_t v)
{
size_t i;
for (i = 0; i != PTLS_ELEMENTSOF(supported_versions); ++i)
if (supported_versions[i] == v)
return 1;
return 0;
}
static int extension_bitmap_testandset(struct st_ptls_extension_bitmap_t *bitmap, int hstype, uint16_t extid)
{
#define HSTYPE_TO_BIT(hstype) ((uint64_t)1 << ((hstype) + 1)) /* min(hstype) is -1 (PSEUDO_HRR) */
#define DEFINE_BIT(abbrev, hstype) static const uint64_t abbrev = HSTYPE_TO_BIT(PTLS_HANDSHAKE_TYPE_##hstype)
#define EXT(candext, allowed_bits) \
do { \
if (PTLS_UNLIKELY(extid == PTLS_EXTENSION_TYPE_##candext)) { \
allowed_hs_bits = allowed_bits; \
goto Found; \
} \
ext_bitmap_mask <<= 1; \
} while (0)
DEFINE_BIT(CH, CLIENT_HELLO);
DEFINE_BIT(SH, SERVER_HELLO);
DEFINE_BIT(HRR, PSEUDO_HRR);
DEFINE_BIT(EE, ENCRYPTED_EXTENSIONS);
DEFINE_BIT(CR, CERTIFICATE_REQUEST);
DEFINE_BIT(CT, CERTIFICATE);
DEFINE_BIT(NST, NEW_SESSION_TICKET);
uint64_t allowed_hs_bits, ext_bitmap_mask = 1;
/* clang-format off */
/* RFC 8446 section 4.2: "The table below indicates the messages where a given extension may appear... If an implementation
* receives an extension which it recognizes and which is not specified for the message in which it appears, it MUST abort the
* handshake with an "illegal_parameter" alert.
*
* +-------------------------+---------------+
* + Extension | Allowed |
* +-------------------------+---------------+ */
EXT( SERVER_NAME , CH + EE );
EXT( STATUS_REQUEST , CH + CR + CT );
EXT( SUPPORTED_GROUPS , CH + EE );
EXT( SIGNATURE_ALGORITHMS , CH + CR );
EXT( ALPN , CH + EE );
EXT( SERVER_CERTIFICATE_TYPE , CH + EE );
EXT( KEY_SHARE , CH + SH + HRR );
EXT( PRE_SHARED_KEY , CH + SH );
EXT( PSK_KEY_EXCHANGE_MODES , CH );
EXT( EARLY_DATA , CH + EE + NST );
EXT( COOKIE , CH + HRR );
EXT( SUPPORTED_VERSIONS , CH + SH + HRR );
EXT( COMPRESS_CERTIFICATE , CH + CR ); /* from RFC 8879 */
EXT( ENCRYPTED_CLIENT_HELLO , CH + HRR + EE ); /* from draft-ietf-tls-esni-15 */
EXT( ECH_OUTER_EXTENSIONS , 0 );
/* +-----------------------------------------+ */
/* clang-format on */
return 1;
Found:
if ((allowed_hs_bits & HSTYPE_TO_BIT(hstype)) == 0)
return 0;
if ((bitmap->bits & ext_bitmap_mask) != 0)
return 0;
bitmap->bits |= ext_bitmap_mask;
return 1;
#undef HSTYPE_TO_BIT
#undef DEFINE_ABBREV
#undef EXT
}
#ifndef ntoh16
static uint16_t ntoh16(const uint8_t *src)
{
return (uint16_t)src[0] << 8 | src[1];
}
#endif
#ifndef ntoh24
static uint32_t ntoh24(const uint8_t *src)
{
return (uint32_t)src[0] << 16 | (uint32_t)src[1] << 8 | src[2];
}
#endif
#ifndef ntoh32
static uint32_t ntoh32(const uint8_t *src)
{
return (uint32_t)src[0] << 24 | (uint32_t)src[1] << 16 | (uint32_t)src[2] << 8 | src[3];
}
#endif
#ifndef ntoh64
static uint64_t ntoh64(const uint8_t *src)
{
return (uint64_t)src[0] << 56 | (uint64_t)src[1] << 48 | (uint64_t)src[2] << 40 | (uint64_t)src[3] << 32 |
(uint64_t)src[4] << 24 | (uint64_t)src[5] << 16 | (uint64_t)src[6] << 8 | src[7];
}
#endif
static void encode64(uint8_t *dst, uint64_t v)
{
for (size_t i = 0; i < 8; ++i)
dst[i] = (uint8_t)(v >> (56 - 8 * i));
}
static char *duplicate_as_str(const void *src, size_t len)
{
char *dst;
if ((dst = malloc(len + 1)) == NULL)
return NULL;
memcpy(dst, src, len);
dst[len] = '\0';
return dst;
}
void ptls_buffer__release_memory(ptls_buffer_t *buf)
{
ptls_clear_memory(buf->base, buf->off);
if (buf->is_allocated) {
#ifdef _WIN32
if (buf->align_bits != 0) {
_aligned_free(buf->base);
} else {
free(buf->base);
}
#else
free(buf->base);
#endif
}
}
int ptls_buffer_reserve(ptls_buffer_t *buf, size_t delta)
{
return ptls_buffer_reserve_aligned(buf, delta, 0);
}
int ptls_buffer_reserve_aligned(ptls_buffer_t *buf, size_t delta, uint8_t align_bits)
{
if (buf->base == NULL)
return PTLS_ERROR_NO_MEMORY;
if (PTLS_MEMORY_DEBUG || buf->capacity < buf->off + delta ||
(buf->align_bits < align_bits && ((uintptr_t)buf->base & (((uintptr_t)1 << align_bits) - 1)) != 0)) {
void *newp;
size_t new_capacity = buf->capacity;
if (new_capacity < 1024)
new_capacity = 1024;
while (new_capacity < buf->off + delta) {
new_capacity *= 2;
}
if (align_bits != 0) {
#ifdef _WIN32
if ((newp = _aligned_malloc(new_capacity, (size_t)1 << align_bits)) == NULL)
return PTLS_ERROR_NO_MEMORY;
#else
if (posix_memalign(&newp, 1 << align_bits, new_capacity) != 0)
return PTLS_ERROR_NO_MEMORY;
#endif
} else {
if ((newp = malloc(new_capacity)) == NULL)
return PTLS_ERROR_NO_MEMORY;
}
memcpy(newp, buf->base, buf->off);
ptls_buffer__release_memory(buf);
buf->base = newp;
buf->capacity = new_capacity;
buf->is_allocated = 1;
buf->align_bits = align_bits;
}
return 0;
}
int ptls_buffer__do_pushv(ptls_buffer_t *buf, const void *src, size_t len)
{
int ret;
if (len == 0)
return 0;
if ((ret = ptls_buffer_reserve(buf, len)) != 0)
return ret;
memcpy(buf->base + buf->off, src, len);
buf->off += len;
return 0;
}
int ptls_buffer__adjust_quic_blocksize(ptls_buffer_t *buf, size_t body_size)
{
uint8_t sizebuf[PTLS_ENCODE_QUICINT_CAPACITY];
size_t sizelen = ptls_encode_quicint(sizebuf, body_size) - sizebuf;
/* adjust amount of space before body_size to `sizelen` bytes */
if (sizelen != 1) {
int ret;
if ((ret = ptls_buffer_reserve(buf, sizelen - 1)) != 0)
return ret;
memmove(buf->base + buf->off - body_size - 1 + sizelen, buf->base + buf->off - body_size, body_size);
buf->off += sizelen - 1;
}
/* write the size */
memcpy(buf->base + buf->off - body_size - sizelen, sizebuf, sizelen);
return 0;
}
int ptls_buffer__adjust_asn1_blocksize(ptls_buffer_t *buf, size_t body_size)
{
fprintf(stderr, "unimplemented\n");
abort();
}
int ptls_buffer_push_asn1_ubigint(ptls_buffer_t *buf, const void *bignum, size_t size)
{
const uint8_t *p = bignum, *const end = p + size;
int ret;
/* skip zeroes */
for (; end - p >= 1; ++p)
if (*p != 0)
break;
/* emit */
ptls_buffer_push(buf, 2);
ptls_buffer_push_asn1_block(buf, {
if (*p >= 0x80)
ptls_buffer_push(buf, 0);
if (p != end) {
ptls_buffer_pushv(buf, p, end - p);
} else {
ptls_buffer_pushv(buf, "", 1);
}
});
ret = 0;
Exit:
return ret;
}
#if PTLS_FUZZ_HANDSHAKE
static size_t aead_encrypt(struct st_ptls_traffic_protection_t *ctx, void *output, const void *input, size_t inlen,
uint8_t content_type)
{
memcpy(output, input, inlen);
memcpy(output + inlen, &content_type, 1);
return inlen + 1 + 16;
}
static int aead_decrypt(struct st_ptls_traffic_protection_t *ctx, void *output, size_t *outlen, const void *input, size_t inlen)
{
if (inlen < 16) {
return PTLS_ALERT_BAD_RECORD_MAC;
}
memcpy(output, input, inlen - 16);
*outlen = inlen - 16; /* removing the 16 bytes of tag */
return 0;
}
#else
static void build_aad(uint8_t aad[5], size_t reclen)
{
aad[0] = PTLS_CONTENT_TYPE_APPDATA;
aad[1] = PTLS_RECORD_VERSION_MAJOR;
aad[2] = PTLS_RECORD_VERSION_MINOR;
aad[3] = (uint8_t)(reclen >> 8);
aad[4] = (uint8_t)reclen;
}
static size_t aead_encrypt(struct st_ptls_traffic_protection_t *ctx, void *output, const void *input, size_t inlen,
uint8_t content_type)
{
ptls_iovec_t invec[2] = {ptls_iovec_init(input, inlen), ptls_iovec_init(&content_type, 1)};
uint8_t aad[5];
build_aad(aad, inlen + 1 + ctx->aead->algo->tag_size);
ptls_aead_encrypt_v(ctx->aead, output, invec, PTLS_ELEMENTSOF(invec), ctx->seq++, aad, sizeof(aad));
return inlen + 1 + ctx->aead->algo->tag_size;
}
static int aead_decrypt(struct st_ptls_traffic_protection_t *ctx, void *output, size_t *outlen, const void *input, size_t inlen)
{
uint8_t aad[5];
build_aad(aad, inlen);
if ((*outlen = ptls_aead_decrypt(ctx->aead, output, input, inlen, ctx->seq, aad, sizeof(aad))) == SIZE_MAX)
return PTLS_ALERT_BAD_RECORD_MAC;
++ctx->seq;
return 0;
}
#endif /* #if PTLS_FUZZ_HANDSHAKE */
static void build_tls12_aad(uint8_t *aad, uint8_t type, uint64_t seq, uint16_t length)
{
for (size_t i = 0; i < 8; ++i)
aad[i] = (uint8_t)(seq >> (56 - i * 8));
aad[8] = type;
aad[9] = PTLS_RECORD_VERSION_MAJOR;
aad[10] = PTLS_RECORD_VERSION_MINOR;
aad[11] = length >> 8;
aad[12] = (uint8_t)length;
}
#define buffer_push_record(buf, type, block) \
do { \
ptls_buffer_push((buf), (type), PTLS_RECORD_VERSION_MAJOR, PTLS_RECORD_VERSION_MINOR); \
ptls_buffer_push_block((buf), 2, block); \
} while (0)
static int buffer_push_encrypted_records(ptls_buffer_t *buf, uint8_t type, const uint8_t *src, size_t len,
struct st_ptls_traffic_protection_t *enc)
{
int ret = 0;
while (len != 0) {
size_t chunk_size = len;
if (chunk_size > PTLS_MAX_PLAINTEXT_RECORD_SIZE)
chunk_size = PTLS_MAX_PLAINTEXT_RECORD_SIZE;
if (enc->tls12) {
buffer_push_record(buf, type, {
/* reserve memory */
if ((ret = ptls_buffer_reserve_aligned(
buf, enc->aead->algo->tls12.record_iv_size + chunk_size + enc->aead->algo->tag_size,
enc->aead->algo->align_bits)) != 0)
goto Exit;
/* determine nonce, as well as prepending that walue as the record IV (AES-GCM) */
uint64_t nonce;
if (enc->aead->algo->tls12.record_iv_size != 0) {
assert(enc->aead->algo->tls12.record_iv_size == 8);
nonce = enc->tls12_enc_record_iv++;
encode64(buf->base + buf->off, nonce);
buf->off += 8;
} else {
nonce = enc->seq;
}
/* build AAD */
uint8_t aad[PTLS_TLS12_AAD_SIZE];
build_tls12_aad(aad, type, enc->seq, (uint16_t)chunk_size);
/* encrypt */
buf->off += ptls_aead_encrypt(enc->aead, buf->base + buf->off, src, chunk_size, nonce, aad, sizeof(aad));
++enc->seq;
});
} else {
buffer_push_record(buf, PTLS_CONTENT_TYPE_APPDATA, {
if ((ret = ptls_buffer_reserve_aligned(buf, chunk_size + enc->aead->algo->tag_size + 1,
enc->aead->algo->align_bits)) != 0)
goto Exit;
buf->off += aead_encrypt(enc, buf->base + buf->off, src, chunk_size, type);
});
}
src += chunk_size;
len -= chunk_size;
}
Exit:
return ret;
}
static int buffer_encrypt_record(ptls_buffer_t *buf, size_t rec_start, struct st_ptls_traffic_protection_t *enc)
{
size_t bodylen = buf->off - rec_start - 5;
uint8_t *tmpbuf, type = buf->base[rec_start];
int ret;
/* Fast path: do in-place encryption if only one record needs to be emitted. (For simplicity, do not take this path if TLS 1.2
* is used, as this function will be called no more than once per connection, for encrypting an alert.) */
if (!enc->tls12 && bodylen <= PTLS_MAX_PLAINTEXT_RECORD_SIZE) {
size_t overhead = 1 + enc->aead->algo->tag_size;
if ((ret = ptls_buffer_reserve_aligned(buf, overhead, enc->aead->algo->align_bits)) != 0)
return ret;
size_t encrypted_len = aead_encrypt(enc, buf->base + rec_start + 5, buf->base + rec_start + 5, bodylen, type);
assert(encrypted_len == bodylen + overhead);
buf->off += overhead;
buf->base[rec_start] = PTLS_CONTENT_TYPE_APPDATA;
buf->base[rec_start + 3] = (encrypted_len >> 8) & 0xff;
buf->base[rec_start + 4] = encrypted_len & 0xff;
return 0;
}
/* move plaintext to temporary buffer */
if ((tmpbuf = malloc(bodylen)) == NULL) {
ret = PTLS_ERROR_NO_MEMORY;
goto Exit;
}
memcpy(tmpbuf, buf->base + rec_start + 5, bodylen);
ptls_clear_memory(buf->base + rec_start, bodylen + 5);
buf->off = rec_start;
/* push encrypted records */
ret = buffer_push_encrypted_records(buf, type, tmpbuf, bodylen, enc);
Exit:
if (tmpbuf != NULL) {
ptls_clear_memory(tmpbuf, bodylen);
free(tmpbuf);
}
return ret;
}
static int begin_record_message(ptls_message_emitter_t *_self)
{
struct st_ptls_record_message_emitter_t *self = (void *)_self;
int ret;
self->rec_start = self->super.buf->off;
ptls_buffer_push(self->super.buf, PTLS_CONTENT_TYPE_HANDSHAKE, PTLS_RECORD_VERSION_MAJOR, PTLS_RECORD_VERSION_MINOR, 0, 0);
ret = 0;
Exit:
return ret;
}
static int commit_record_message(ptls_message_emitter_t *_self)
{
struct st_ptls_record_message_emitter_t *self = (void *)_self;
int ret;
if (self->super.enc->aead != NULL) {
ret = buffer_encrypt_record(self->super.buf, self->rec_start, self->super.enc);
} else {
/* TODO allow CH,SH,HRR above 16KB */
size_t sz = self->super.buf->off - self->rec_start - 5;
assert(sz <= PTLS_MAX_PLAINTEXT_RECORD_SIZE);
self->super.buf->base[self->rec_start + 3] = (uint8_t)(sz >> 8);
self->super.buf->base[self->rec_start + 4] = (uint8_t)(sz);
ret = 0;
}
return ret;
}
#define buffer_push_extension(buf, type, block) \
do { \
ptls_buffer_push16((buf), (type)); \
ptls_buffer_push_block((buf), 2, block); \
} while (0);
#define decode_open_extensions(src, end, hstype, exttype, block) \
do { \
struct st_ptls_extension_bitmap_t bitmap = {0}; \
ptls_decode_open_block((src), end, 2, { \
while ((src) != end) { \
if ((ret = ptls_decode16((exttype), &(src), end)) != 0) \
goto Exit; \
if (!extension_bitmap_testandset(&bitmap, (hstype), *(exttype))) { \
ret = PTLS_ALERT_ILLEGAL_PARAMETER; \
goto Exit; \
} \
ptls_decode_open_block((src), end, 2, block); \
} \
}); \
} while (0)
#define decode_extensions(src, end, hstype, exttype, block) \
do { \
decode_open_extensions((src), end, hstype, exttype, block); \
ptls_decode_assert_block_close((src), end); \
} while (0)
int ptls_decode8(uint8_t *value, const uint8_t **src, const uint8_t *end)
{
if (*src == end)
return PTLS_ALERT_DECODE_ERROR;
*value = *(*src)++;
return 0;
}
int ptls_decode16(uint16_t *value, const uint8_t **src, const uint8_t *end)
{
if (end - *src < 2)
return PTLS_ALERT_DECODE_ERROR;
*value = ntoh16(*src);
*src += 2;
return 0;
}
int ptls_decode24(uint32_t *value, const uint8_t **src, const uint8_t *end)
{
if (end - *src < 3)
return PTLS_ALERT_DECODE_ERROR;
*value = ((uint32_t)(*src)[0] << 16) | ((uint32_t)(*src)[1] << 8) | (*src)[2];
*src += 3;
return 0;
}
int ptls_decode32(uint32_t *value, const uint8_t **src, const uint8_t *end)
{
if (end - *src < 4)
return PTLS_ALERT_DECODE_ERROR;
*value = ntoh32(*src);
*src += 4;
return 0;
}
int ptls_decode64(uint64_t *value, const uint8_t **src, const uint8_t *end)
{
if (end - *src < 8)
return PTLS_ALERT_DECODE_ERROR;
*value = ntoh64(*src);
*src += 8;
return 0;
}
uint64_t ptls_decode_quicint(const uint8_t **src, const uint8_t *end)
{
if (PTLS_UNLIKELY(*src == end))
return UINT64_MAX;
uint8_t b = *(*src)++;
if (PTLS_LIKELY(b <= 0x3f))
return b;
uint64_t v = b & 0x3f;
unsigned bytes_left = (1 << (b >> 6)) - 1;
if (PTLS_UNLIKELY((size_t)(end - *src) < bytes_left))
return UINT64_MAX;
do {
v = (v << 8) | *(*src)++;
} while (--bytes_left != 0);
return v;
}
static void log_secret(ptls_t *tls, const char *type, ptls_iovec_t secret)
{
char hexbuf[PTLS_MAX_DIGEST_SIZE * 2 + 1];
PTLS_PROBE(NEW_SECRET, tls, type, ptls_hexdump(hexbuf, secret.base, secret.len));
PTLS_LOG_CONN(new_secret, tls, { PTLS_LOG_ELEMENT_SAFESTR(label, type); });
if (tls->ctx->log_event != NULL)
tls->ctx->log_event->cb(tls->ctx->log_event, tls, type, "%s", ptls_hexdump(hexbuf, secret.base, secret.len));
}
/**
* This function preserves the flags and modes (e.g., `offered`, `accepted`, `cipher`), they can be used afterwards.
*/
static void clear_ech(struct st_ptls_ech_t *ech, int is_server)
{
if (ech->aead != NULL) {
ptls_aead_free(ech->aead);
ech->aead = NULL;
}
ptls_clear_memory(ech->inner_client_random, PTLS_HELLO_RANDOM_SIZE);
if (!is_server) {
free(ech->client.enc.base);
ech->client.enc = ptls_iovec_init(NULL, 0);
if (ech->client.public_name != NULL) {
free(ech->client.public_name);
ech->client.public_name = NULL;
}
free(ech->client.first_ech.base);
ech->client.first_ech = ptls_iovec_init(NULL, 0);
}
}
/**
* Decodes one ECHConfigContents (tls-esni-15 section 4). `decoded->kem` and `cipher` may be NULL even when the function returns
* zero, if the corresponding entries are not found.