-
Notifications
You must be signed in to change notification settings - Fork 171
Expand file tree
/
Copy pathpicotls.c
More file actions
3182 lines (2813 loc) · 120 KB
/
picotls.c
File metadata and controls
3182 lines (2813 loc) · 120 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.
*/
#include <assert.h>
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/time.h>
#include "picotls.h"
#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 1
#define PTLS_HELLO_RANDOM_SIZE 32
#define PTLS_CONTENT_TYPE_ALERT 21
#define PTLS_CONTENT_TYPE_HANDSHAKE 22
#define PTLS_CONTENT_TYPE_APPDATA 23
#define PTLS_HANDSHAKE_TYPE_CLIENT_HELLO 1
#define PTLS_HANDSHAKE_TYPE_SERVER_HELLO 2
#define PTLS_HANDSHAKE_TYPE_NEW_SESSION_TICKET 4
#define PTLS_HANDSHAKE_TYPE_HELLO_RETRY_REQUEST 6
#define PTLS_HANDSHAKE_TYPE_ENCRYPTED_EXTENSIONS 8
#define PTLS_HANDSHAKE_TYPE_CERTIFICATE 11
#define PTLS_HANDSHAKE_TYPE_CERTIFICATE_REQUEST 13
#define PTLS_HANDSHAKE_TYPE_CERTIFICATE_VERIFY 15
#define PTLS_HANDSHAKE_TYPE_FINISHED 20
#define PTLS_HANDSHAKE_TYPE_KEY_UPDATE 24
#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_KEY_SHARE 40
#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_TICKET_EARLY_DATA_INFO 46
#define PTLS_EXTENSION_TYPE_DELEGATED_CREDENTIAL 26 /* for now */
#define PTLS_PROTOCOL_VERSION_DRAFT18 0x7f12
#define PTLS_SERVER_NAME_TYPE_HOSTNAME 0
#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)
#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
struct st_ptls_traffic_protection_t {
uint8_t secret[PTLS_MAX_DIGEST_SIZE];
ptls_aead_context_t *aead;
};
struct st_ptls_early_data_receiver_t {
uint8_t next_secret[PTLS_MAX_DIGEST_SIZE];
};
struct st_ptls_t {
/**
* the context
*/
ptls_context_t *ctx;
/**
* the state
*/
enum {
PTLS_STATE_CLIENT_HANDSHAKE_START,
PTLS_STATE_CLIENT_SEND_EARLY_DATA,
PTLS_STATE_CLIENT_EXPECT_SERVER_HELLO,
PTLS_STATE_CLIENT_EXPECT_SECOND_SERVER_HELLO,
PTLS_STATE_CLIENT_EXPECT_ENCRYPTED_EXTENSIONS,
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_send can be called if the state is below here */
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
*/
struct st_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 cipher-suite
*/
ptls_cipher_suite_t *cipher_suite;
/**
* clienthello.random
*/
uint8_t client_random[PTLS_HELLO_RANDOM_SIZE];
/**
* misc.
*/
struct {
struct {
struct {
ptls_key_exchange_algorithm_t *algo;
ptls_key_exchange_context_t *ctx;
} key_exchange;
struct {
int (*cb)(void *verify_ctx, ptls_iovec_t data, ptls_iovec_t signature);
void *verify_ctx;
} certificate_verify;
unsigned offered_psk : 1;
unsigned send_early_data : 1;
} client;
struct {
/**
* expecting to recieve undecrytable early-data packets
*/
unsigned skip_early_data : 1;
/**
* if accepting early-data, the value contains the receiving traffic secret to be commisioned after receiving
* END_OF_EARLY_DATA
*/
struct st_ptls_early_data_receiver_t *early_data;
} server;
unsigned is_psk_handshake : 1;
};
};
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;
};
struct st_ptls_client_hello_t {
const uint8_t *random_bytes;
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 {
uint16_t list[16]; /* expand? */
size_t count;
} signature_algorithms;
ptls_iovec_t server_name;
struct {
ptls_iovec_t list[16];
size_t count;
} alpn;
ptls_iovec_t cookie;
struct {
const uint8_t *hash_end;
struct {
struct st_ptls_client_hello_psk_t list[4];
size_t count;
} identities;
unsigned ke_modes;
int early_data_indication;
} psk;
unsigned status_request : 1;
unsigned delegated_credential : 1;
};
struct st_ptls_server_hello_t {
uint8_t random[PTLS_HELLO_RANDOM_SIZE];
ptls_iovec_t peerkey;
};
struct st_ptls_key_schedule_t {
ptls_hash_algorithm_t *algo;
ptls_hash_context_t *msghash;
unsigned generation; /* early secret (1), hanshake secret (2), master secret (3) */
uint8_t secret[PTLS_MAX_DIGEST_SIZE];
};
struct st_ptls_extension_decoder_t {
uint16_t type;
int (*cb)(ptls_t *tls, void *arg, const uint8_t *src, const uint8_t *end);
};
struct st_ptls_extension_bitmap_t {
uint8_t bits[8]; /* only ids below 64 is tracked */
};
static uint8_t zeroes_of_max_digest_size[PTLS_MAX_DIGEST_SIZE] = {};
static inline int extension_bitmap_is_set(struct st_ptls_extension_bitmap_t *bitmap, uint16_t id)
{
if (id < sizeof(bitmap->bits) * 8)
return (bitmap->bits[id / 8] & (1 << (id % 8))) != 0;
return 0;
}
static inline void extension_bitmap_set(struct st_ptls_extension_bitmap_t *bitmap, uint16_t id)
{
if (id < sizeof(bitmap->bits) * 8)
bitmap->bits[id / 8] |= 1 << (id % 8);
}
static inline void init_extension_bitmap(struct st_ptls_extension_bitmap_t *bitmap, uint8_t hstype)
{
*bitmap = (struct st_ptls_extension_bitmap_t){{0}};
#define EXT(extid, proc) \
do { \
int _found = 0; \
do { \
proc \
} while (0); \
if (!_found) \
extension_bitmap_set(bitmap, PTLS_EXTENSION_TYPE_##extid); \
} while (0)
#define ALLOW(allowed_hstype) _found = _found || hstype == PTLS_HANDSHAKE_TYPE_##allowed_hstype
/* Implements the table found in section 4.2 of draft-19; "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."
*/
EXT(SERVER_NAME, {
ALLOW(CLIENT_HELLO);
ALLOW(ENCRYPTED_EXTENSIONS);
});
EXT(STATUS_REQUEST, {
ALLOW(CLIENT_HELLO);
ALLOW(CERTIFICATE);
});
EXT(SUPPORTED_GROUPS, {
ALLOW(CLIENT_HELLO);
ALLOW(ENCRYPTED_EXTENSIONS);
});
EXT(SIGNATURE_ALGORITHMS, { ALLOW(CLIENT_HELLO); });
EXT(ALPN, {
ALLOW(CLIENT_HELLO);
ALLOW(ENCRYPTED_EXTENSIONS);
});
EXT(KEY_SHARE, {
ALLOW(CLIENT_HELLO);
ALLOW(SERVER_HELLO);
ALLOW(HELLO_RETRY_REQUEST);
});
EXT(PRE_SHARED_KEY, {
ALLOW(CLIENT_HELLO);
ALLOW(SERVER_HELLO);
});
EXT(PSK_KEY_EXCHANGE_MODES, { ALLOW(CLIENT_HELLO); });
EXT(EARLY_DATA, {
ALLOW(CLIENT_HELLO);
ALLOW(ENCRYPTED_EXTENSIONS);
});
EXT(COOKIE, {
ALLOW(CLIENT_HELLO);
ALLOW(HELLO_RETRY_REQUEST);
});
EXT(SUPPORTED_VERSIONS, { ALLOW(CLIENT_HELLO); });
EXT(TICKET_EARLY_DATA_INFO, { ALLOW(NEW_SESSION_TICKET); });
#undef ALLOW
#undef EXT
}
static uint64_t gettime_millis(void)
{
struct timeval tv;
gettimeofday(&tv, NULL);
return (uint64_t)tv.tv_sec * 1000 + tv.tv_usec / 1000;
}
static uint16_t ntoh16(const uint8_t *src)
{
return (uint16_t)src[0] << 8 | src[1];
}
static uint32_t ntoh24(const uint8_t *src)
{
return (uint32_t)src[0] << 16 | (uint32_t)src[1] << 8 | src[2];
}
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];
}
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];
}
void ptls_buffer__release_memory(ptls_buffer_t *buf)
{
ptls_clear_memory(buf->base, buf->off);
if (buf->is_allocated)
free(buf->base);
}
int ptls_buffer_reserve(ptls_buffer_t *buf, size_t delta)
{
if (buf->base == NULL)
return PTLS_ERROR_NO_MEMORY;
if (PTLS_MEMORY_DEBUG || buf->capacity < buf->off + delta) {
uint8_t *newp;
size_t new_capacity = buf->capacity;
if (new_capacity < 1024)
new_capacity = 1024;
while (new_capacity < buf->off + delta) {
new_capacity *= 2;
}
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;
}
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_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, *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;
}
static int buffer_encrypt_record(ptls_buffer_t *buf, size_t rec_start, ptls_aead_context_t *aead)
{
uint8_t encrypted[PTLS_MAX_ENCRYPTED_RECORD_SIZE];
size_t enclen, bodylen = buf->off - rec_start - 5;
int ret;
assert(bodylen <= PTLS_MAX_PLAINTEXT_RECORD_SIZE);
if ((ret = ptls_aead_transform(aead, encrypted, &enclen, buf->base + rec_start + 5, bodylen, buf->base[rec_start])) != 0)
goto Exit;
buf->off = rec_start;
ptls_buffer_push(buf, PTLS_CONTENT_TYPE_APPDATA, 3, 1);
ptls_buffer_push16(buf, enclen);
ptls_buffer_pushv(buf, encrypted, enclen);
Exit:
return ret;
}
#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)
#define buffer_encrypt(buf, enc, block) \
do { \
size_t rec_start = (buf)->off; \
do { \
block \
} while (0); \
if ((ret = buffer_encrypt_record((buf), rec_start, (enc))) != 0) \
goto Exit; \
} while (0);
#define buffer_push_handshake_core(buf, key_sched, type, mess_start, block) \
do { \
ptls_buffer_push((buf), (type)); \
ptls_buffer_push_block((buf), 3, { \
do { \
block \
} while (0); \
}); \
if ((key_sched) != NULL) \
key_schedule_update_hash((key_sched), (buf)->base + mess_start, (buf)->off - (mess_start)); \
} while (0)
#define buffer_push_handshake(buf, key_sched, type, block) \
buffer_push_record((buf), PTLS_CONTENT_TYPE_HANDSHAKE, { \
size_t mess_start = (buf)->off; \
buffer_push_handshake_core((buf), (key_sched), (type), mess_start, block); \
})
#define buffer_calc_handshake_hash(buf, key_sched, type, block) \
do { \
size_t mess_start = (buf)->off; \
buffer_push_handshake_core((buf), (key_sched), (type), mess_start, block); \
(buf)->off = mess_start; \
} while (0)
#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_block(src, end, capacity, block) \
do { \
size_t _capacity = (capacity); \
if (_capacity > end - (src)) { \
ret = PTLS_ALERT_DECODE_ERROR; \
goto Exit; \
} \
size_t _block_size = 0; \
do { \
_block_size = _block_size << 8 | *(src)++; \
} while (--_capacity != 0); \
if (_block_size > end - (src)) { \
ret = PTLS_ALERT_DECODE_ERROR; \
goto Exit; \
} \
do { \
const uint8_t *end = (src) + _block_size; \
do { \
block \
} while (0); \
if ((src) != end) { \
ret = PTLS_ALERT_DECODE_ERROR; \
goto Exit; \
} \
} while (0); \
} while (0)
#define decode_assert_block_close(src, end) \
do { \
if ((src) != end) { \
ret = PTLS_ALERT_DECODE_ERROR; \
goto Exit; \
} \
} while (0);
#define decode_block(src, end, capacity, block) \
do { \
decode_open_block((src), end, capacity, block); \
decode_assert_block_close((src), end); \
} while (0)
#define decode_open_extensions(src, end, hstype, exttype, block) \
do { \
struct st_ptls_extension_bitmap_t bitmap; \
init_extension_bitmap(&bitmap, (hstype)); \
decode_open_block((src), end, 2, { \
while ((src) != end) { \
if ((ret = decode16((exttype), &(src), end)) != 0) \
goto Exit; \
if (extension_bitmap_is_set(&bitmap, *(exttype)) != 0) { \
ret = PTLS_ALERT_ILLEGAL_PARAMETER; \
goto Exit; \
} \
extension_bitmap_set(&bitmap, *(exttype)); \
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); \
decode_assert_block_close((src), end); \
} while (0)
static int 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;
}
static int 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;
}
static int 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;
}
static int hkdf_expand_label(ptls_hash_algorithm_t *algo, void *output, size_t outlen, ptls_iovec_t secret, const char *label,
ptls_iovec_t hash_value)
{
ptls_buffer_t hkdf_label;
uint8_t hkdf_label_buf[512];
int ret;
ptls_buffer_init(&hkdf_label, hkdf_label_buf, sizeof(hkdf_label_buf));
ptls_buffer_push16(&hkdf_label, outlen);
ptls_buffer_push_block(&hkdf_label, 1, {
const char *prefix = "TLS 1.3, ";
ptls_buffer_pushv(&hkdf_label, prefix, strlen(prefix));
ptls_buffer_pushv(&hkdf_label, label, strlen(label));
});
ptls_buffer_push_block(&hkdf_label, 1, { ptls_buffer_pushv(&hkdf_label, hash_value.base, hash_value.len); });
ret = ptls_hkdf_expand(algo, output, outlen, secret, ptls_iovec_init(hkdf_label.base, hkdf_label.off));
Exit:
ptls_buffer_dispose(&hkdf_label);
return ret;
}
static struct st_ptls_key_schedule_t *key_schedule_new(ptls_hash_algorithm_t *algo)
{
struct st_ptls_key_schedule_t *sched = NULL;
ptls_hash_context_t *hash = NULL;
if ((sched = malloc(sizeof(*sched))) == NULL)
return NULL;
if ((hash = algo->create()) == NULL) {
free(sched);
return NULL;
}
*sched = (struct st_ptls_key_schedule_t){algo, hash};
return sched;
}
static void key_schedule_free(struct st_ptls_key_schedule_t *sched)
{
sched->msghash->final(sched->msghash, NULL, PTLS_HASH_FINAL_MODE_FREE);
free(sched);
}
static int key_schedule_extract(struct st_ptls_key_schedule_t *sched, ptls_iovec_t ikm)
{
if (ikm.base == NULL)
ikm = ptls_iovec_init(zeroes_of_max_digest_size, sched->algo->digest_size);
++sched->generation;
int ret = ptls_hkdf_extract(sched->algo, sched->secret, ptls_iovec_init(sched->secret, sched->algo->digest_size), ikm);
PTLS_DEBUGF("%s: %u, %02x%02x\n", __FUNCTION__, sched->generation, (int)sched->secret[0], (int)sched->secret[1]);
return ret;
}
static int key_schedule_reset_psk(struct st_ptls_key_schedule_t *sched)
{
assert(sched->generation == 1);
--sched->generation;
memset(sched->secret, 0, sizeof(sched->secret));
return key_schedule_extract(sched, ptls_iovec_init(NULL, 0));
}
static void key_schedule_update_hash(struct st_ptls_key_schedule_t *sched, const uint8_t *msg, size_t msglen)
{
PTLS_DEBUGF("%s:%zu\n", __FUNCTION__, msglen);
sched->msghash->update(sched->msghash, msg, msglen);
}
static int derive_secret(struct st_ptls_key_schedule_t *sched, void *secret, const char *label)
{
uint8_t hash_value[PTLS_MAX_DIGEST_SIZE];
sched->msghash->final(sched->msghash, hash_value, PTLS_HASH_FINAL_MODE_SNAPSHOT);
int ret =
hkdf_expand_label(sched->algo, secret, sched->algo->digest_size, ptls_iovec_init(sched->secret, sched->algo->digest_size),
label, ptls_iovec_init(hash_value, sched->algo->digest_size));
ptls_clear_memory(hash_value, sched->algo->digest_size * 2);
return ret;
}
static int derive_resumption_secret(struct st_ptls_key_schedule_t *sched, uint8_t *secret)
{
return derive_secret(sched, secret, "resumption master secret");
}
static int decode_new_session_ticket(uint32_t *lifetime, uint32_t *age_add, ptls_iovec_t *ticket, uint32_t *max_early_data_size,
const uint8_t *src, const uint8_t *end)
{
uint16_t exttype;
int ret;
if ((ret = decode32(lifetime, &src, end)) != 0)
goto Exit;
if ((ret = decode32(age_add, &src, end)) != 0)
goto Exit;
decode_open_block(src, end, 2, {
if (src == end) {
ret = PTLS_ALERT_DECODE_ERROR;
goto Exit;
}
*ticket = ptls_iovec_init(src, end - src);
src = end;
});
*max_early_data_size = 0;
decode_extensions(src, end, PTLS_HANDSHAKE_TYPE_NEW_SESSION_TICKET, &exttype, {
switch (exttype) {
case PTLS_EXTENSION_TYPE_TICKET_EARLY_DATA_INFO:
if ((ret = decode32(max_early_data_size, &src, end)) != 0)
goto Exit;
break;
default:
src = end;
break;
}
});
ret = 0;
Exit:
return ret;
}
static int decode_stored_session_ticket(ptls_context_t *ctx, ptls_cipher_suite_t **cs, ptls_iovec_t *secret,
uint32_t *obfuscated_ticket_age, ptls_iovec_t *ticket, uint32_t *max_early_data_size,
const uint8_t *src, const uint8_t *end)
{
uint16_t csid;
uint32_t lifetime, age_add;
uint64_t obtained_at, now;
int ret;
/* decode */
if ((ret = decode64(&obtained_at, &src, end)) != 0)
goto Exit;
if ((ret = decode16(&csid, &src, end)) != 0)
goto Exit;
decode_open_block(src, end, 3, {
if ((ret = decode_new_session_ticket(&lifetime, &age_add, ticket, max_early_data_size, src, end)) != 0)
goto Exit;
src = end;
});
decode_block(src, end, 2, {
*secret = ptls_iovec_init(src, end - src);
src = end;
});
{ /* determine the cipher-suite */
ptls_cipher_suite_t **cand;
for (cand = ctx->cipher_suites; *cand != NULL; ++cand)
if ((*cand)->id == csid)
break;
if (*cand == NULL) {
ret = PTLS_ERROR_LIBRARY;
goto Exit;
}
*cs = *cand;
}
/* calculate obfuscated_ticket_age */
now = gettime_millis();
if (!(obtained_at <= now && now - obtained_at < 7 * 86400 * 1000)) {
ret = PTLS_ERROR_LIBRARY;
goto Exit;
}
*obfuscated_ticket_age = (uint32_t)(now - obtained_at) + age_add;
ret = 0;
Exit:
return ret;
}
static int get_traffic_key(ptls_hash_algorithm_t *algo, void *key, size_t key_size, int is_iv, const void *secret)
{
return hkdf_expand_label(algo, key, key_size, ptls_iovec_init(secret, algo->digest_size), is_iv ? "iv" : "key",
ptls_iovec_init(NULL, 0));
}
static int setup_traffic_protection(ptls_t *tls, ptls_cipher_suite_t *cs, int is_enc, const char *secret_label,
const char *log_label)
{
struct st_ptls_traffic_protection_t *ctx = is_enc ? &tls->traffic_protection.enc : &tls->traffic_protection.dec;
if (secret_label != NULL) {
int ret;
if ((ret = derive_secret(tls->key_schedule, ctx->secret, secret_label)) != 0)
return ret;
}
if (ctx->aead != NULL)
ptls_aead_free(ctx->aead);
if ((ctx->aead = ptls_aead_new(cs->aead, cs->hash, is_enc, ctx->secret)) == NULL)
return PTLS_ERROR_NO_MEMORY; /* TODO obtain error from ptls_aead_new */
if (tls->ctx->log_secret != NULL)
tls->ctx->log_secret->cb(tls->ctx->log_secret, tls, log_label,
ptls_iovec_init(ctx->secret, tls->key_schedule->algo->digest_size));
PTLS_DEBUGF("[%s] %02x%02x,%02x%02x\n", secret_label, (unsigned)ctx->secret[0], (unsigned)ctx->secret[1],
(unsigned)ctx->aead->static_iv[0], (unsigned)ctx->aead->static_iv[1]);
return 0;
}
#define SESSION_IDENTIFIER_MAGIC "ptls0000" /* the number should be changed upon incompatible format change */
#define SESSION_IDENTIFIER_MAGIC_SIZE (sizeof(SESSION_IDENTIFIER_MAGIC) - 1)
int encode_session_identifier(ptls_buffer_t *buf, uint32_t ticket_age_add, struct st_ptls_key_schedule_t *sched,
const char *server_name, uint16_t csid, const char *negotiated_protocol)
{
int ret = 0;
ptls_buffer_push_block(buf, 2, {
/* format id */
ptls_buffer_pushv(buf, SESSION_IDENTIFIER_MAGIC, SESSION_IDENTIFIER_MAGIC_SIZE);
/* date */
ptls_buffer_push64(buf, gettime_millis());
/* resumption master secret */
ptls_buffer_push_block(buf, 2, {
if ((ret = ptls_buffer_reserve(buf, sched->algo->digest_size)) != 0)
goto Exit;
if ((ret = derive_resumption_secret(sched, buf->base + buf->off)) != 0)
goto Exit;
buf->off += sched->algo->digest_size;
});
/* cipher-suite */
ptls_buffer_push16(buf, csid);
/* ticket_age_add */
ptls_buffer_push32(buf, ticket_age_add);
/* server-name */
ptls_buffer_push_block(buf, 2, {
if (server_name != NULL)
ptls_buffer_pushv(buf, server_name, strlen(server_name));
});
/* alpn */
ptls_buffer_push_block(buf, 1, {
if (negotiated_protocol != NULL)
ptls_buffer_pushv(buf, negotiated_protocol, strlen(negotiated_protocol));
});
});
Exit:
return ret;
}
int decode_session_identifier(uint64_t *issued_at, ptls_iovec_t *psk, uint32_t *ticket_age_add, ptls_iovec_t *server_name,
uint16_t *csid, ptls_iovec_t *negotiated_protocol, const uint8_t *src, const uint8_t *end)
{
int ret = 0;
decode_block(src, end, 2, {
if (end - src < SESSION_IDENTIFIER_MAGIC_SIZE ||
memcmp(src, SESSION_IDENTIFIER_MAGIC, SESSION_IDENTIFIER_MAGIC_SIZE) != 0) {
ret = PTLS_ALERT_DECODE_ERROR;
goto Exit;
}
src += SESSION_IDENTIFIER_MAGIC_SIZE;
if ((ret = decode64(issued_at, &src, end)) != 0)
goto Exit;
decode_open_block(src, end, 2, {
*psk = ptls_iovec_init(src, end - src);
src = end;
});
if ((ret = decode16(csid, &src, end)) != 0)
goto Exit;
if ((ret = decode32(ticket_age_add, &src, end)) != 0)
goto Exit;
decode_open_block(src, end, 2, {
*server_name = ptls_iovec_init(src, end - src);
src = end;
});
decode_open_block(src, end, 1, {
*negotiated_protocol = ptls_iovec_init(src, end - src);
src = end;
});
});
Exit:
return ret;
}
static size_t build_certificate_verify_signdata(uint8_t *data, struct st_ptls_key_schedule_t *sched, const char *context_string)
{
size_t datalen = 0;
memset(data + datalen, 32, 64);
datalen += 64;
memcpy(data + datalen, context_string, strlen(context_string) + 1);
datalen += strlen(context_string) + 1;
sched->msghash->final(sched->msghash, data + datalen, PTLS_HASH_FINAL_MODE_SNAPSHOT);
datalen += sched->algo->digest_size;
assert(datalen <= PTLS_MAX_CERTIFICATE_VERIFY_SIGNDATA_SIZE);
return datalen;
}
static int calc_verify_data(void *output, struct st_ptls_key_schedule_t *sched, const void *secret)
{
ptls_hash_context_t *hmac;
uint8_t digest[PTLS_MAX_DIGEST_SIZE];
int ret;
if ((ret = hkdf_expand_label(sched->algo, digest, sched->algo->digest_size, ptls_iovec_init(secret, sched->algo->digest_size),
"finished", ptls_iovec_init(NULL, 0))) != 0)
return ret;
if ((hmac = ptls_hmac_create(sched->algo, digest, sched->algo->digest_size)) == NULL) {
ptls_clear_memory(digest, sizeof(digest));
return PTLS_ERROR_NO_MEMORY;
}
sched->msghash->final(sched->msghash, digest, PTLS_HASH_FINAL_MODE_SNAPSHOT);
PTLS_DEBUGF("%s: %02x%02x,%02x%02x\n", __FUNCTION__, ((uint8_t *)secret)[0], ((uint8_t *)secret)[1], digest[0], digest[1]);
hmac->update(hmac, digest, sched->algo->digest_size);
ptls_clear_memory(digest, sizeof(digest));
hmac->final(hmac, output, PTLS_HASH_FINAL_MODE_FREE);
return 0;
}
static int verify_finished(ptls_t *tls, ptls_iovec_t message)
{
uint8_t verify_data[PTLS_MAX_DIGEST_SIZE];
int ret;
if (PTLS_HANDSHAKE_HEADER_SIZE + tls->key_schedule->algo->digest_size != message.len) {
ret = PTLS_ALERT_DECODE_ERROR;
goto Exit;
}
if ((ret = calc_verify_data(verify_data, tls->key_schedule, tls->traffic_protection.dec.secret)) != 0)
goto Exit;
if (memcmp(message.base + PTLS_HANDSHAKE_HEADER_SIZE, verify_data, tls->key_schedule->algo->digest_size) != 0) {
ret = PTLS_ALERT_HANDSHAKE_FAILURE;
goto Exit;
}
Exit:
ptls_clear_memory(verify_data, sizeof(verify_data));
return ret;
}
static int send_finished(ptls_t *tls, ptls_buffer_t *sendbuf)
{
int ret;
buffer_encrypt(sendbuf, tls->traffic_protection.enc.aead, {
buffer_push_handshake(sendbuf, tls->key_schedule, PTLS_HANDSHAKE_TYPE_FINISHED, {
if ((ret = ptls_buffer_reserve(sendbuf, tls->key_schedule->algo->digest_size)) != 0)
goto Exit;
if ((ret = calc_verify_data(sendbuf->base + sendbuf->off, tls->key_schedule, tls->traffic_protection.enc.secret)) != 0)
goto Exit;
sendbuf->off += tls->key_schedule->algo->digest_size;
});
});
Exit:
return ret;
}
static int send_session_ticket(ptls_t *tls, ptls_buffer_t *sendbuf)
{
ptls_hash_context_t *msghash_backup = tls->key_schedule->msghash->clone_(tls->key_schedule->msghash);
ptls_buffer_t session_id;
char session_id_smallbuf[128];
uint32_t ticket_age_add;
int ret = 0;
assert(tls->ctx->ticket_lifetime != 0);
assert(tls->ctx->encrypt_ticket != NULL);
/* calculate verify-data that will be sent by the client */
buffer_calc_handshake_hash(sendbuf, tls->key_schedule, PTLS_HANDSHAKE_TYPE_FINISHED, {
if ((ret = ptls_buffer_reserve(sendbuf, tls->key_schedule->algo->digest_size)) != 0)
goto Exit;
if ((ret = calc_verify_data(sendbuf->base + sendbuf->off, tls->key_schedule,
tls->server.early_data != NULL ? tls->server.early_data->next_secret
: tls->traffic_protection.dec.secret)) != 0)
goto Exit;
sendbuf->off += tls->key_schedule->algo->digest_size;
});
tls->ctx->random_bytes(&ticket_age_add, sizeof(ticket_age_add));
/* build the raw nsk */
ptls_buffer_init(&session_id, session_id_smallbuf, sizeof(session_id_smallbuf));
ret = encode_session_identifier(&session_id, ticket_age_add, tls->key_schedule, tls->server_name, tls->cipher_suite->id,
tls->negotiated_protocol);
if (ret != 0)
goto Exit;
/* encrypt and send */
buffer_encrypt(sendbuf, tls->traffic_protection.enc.aead, {
buffer_push_handshake(sendbuf, tls->key_schedule, PTLS_HANDSHAKE_TYPE_NEW_SESSION_TICKET, {
ptls_buffer_push32(sendbuf, tls->ctx->ticket_lifetime);
ptls_buffer_push32(sendbuf, ticket_age_add);
ptls_buffer_push_block(sendbuf, 2, {
if ((ret = tls->ctx->encrypt_ticket->cb(tls->ctx->encrypt_ticket, tls, sendbuf,
ptls_iovec_init(session_id.base, session_id.off))) != 0)
goto Exit;
});
ptls_buffer_push_block(sendbuf, 2, {