1 /*
2 * Copyright (c) 2016 DeNA Co., Ltd., Kazuho Oku
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining a copy
5 * of this software and associated documentation files (the "Software"), to
6 * deal in the Software without restriction, including without limitation the
7 * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
8 * sell copies of the Software, and to permit persons to whom the Software is
9 * furnished to do so, subject to the following conditions:
10 *
11 * The above copyright notice and this permission notice shall be included in
12 * all copies or substantial portions of the Software.
13 *
14 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
19 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
20 * IN THE SOFTWARE.
21 */
22 #include <assert.h>
23 #include <stddef.h>
24 #include <stdio.h>
25 #include <stdlib.h>
26 #include <string.h>
27 #ifdef _WINDOWS
28 #include "wincompat.h"
29 #else
30 #include <arpa/inet.h>
31 #include <sys/time.h>
32 #endif
33 #include "picotls.h"
34 #if PICOTLS_USE_DTRACE
35 #include "picotls-probes.h"
36 #endif
37
38 #define PTLS_MAX_PLAINTEXT_RECORD_SIZE 16384
39 #define PTLS_MAX_ENCRYPTED_RECORD_SIZE (16384 + 256)
40
41 #define PTLS_RECORD_VERSION_MAJOR 3
42 #define PTLS_RECORD_VERSION_MINOR 3
43
44 #define PTLS_CONTENT_TYPE_CHANGE_CIPHER_SPEC 20
45 #define PTLS_CONTENT_TYPE_ALERT 21
46 #define PTLS_CONTENT_TYPE_HANDSHAKE 22
47 #define PTLS_CONTENT_TYPE_APPDATA 23
48
49 #define PTLS_PSK_KE_MODE_PSK 0
50 #define PTLS_PSK_KE_MODE_PSK_DHE 1
51
52 #define PTLS_HANDSHAKE_HEADER_SIZE 4
53
54 #define PTLS_EXTENSION_TYPE_SERVER_NAME 0
55 #define PTLS_EXTENSION_TYPE_STATUS_REQUEST 5
56 #define PTLS_EXTENSION_TYPE_SUPPORTED_GROUPS 10
57 #define PTLS_EXTENSION_TYPE_SIGNATURE_ALGORITHMS 13
58 #define PTLS_EXTENSION_TYPE_ALPN 16
59 #define PTLS_EXTENSION_TYPE_SERVER_CERTIFICATE_TYPE 20
60 #define PTLS_EXTENSION_TYPE_COMPRESS_CERTIFICATE 27
61 #define PTLS_EXTENSION_TYPE_PRE_SHARED_KEY 41
62 #define PTLS_EXTENSION_TYPE_EARLY_DATA 42
63 #define PTLS_EXTENSION_TYPE_SUPPORTED_VERSIONS 43
64 #define PTLS_EXTENSION_TYPE_COOKIE 44
65 #define PTLS_EXTENSION_TYPE_PSK_KEY_EXCHANGE_MODES 45
66 #define PTLS_EXTENSION_TYPE_KEY_SHARE 51
67 #define PTLS_EXTENSION_TYPE_ENCRYPTED_SERVER_NAME 0xffce
68
69 #define PTLS_PROTOCOL_VERSION_TLS13_FINAL 0x0304
70 #define PTLS_PROTOCOL_VERSION_TLS13_DRAFT26 0x7f1a
71 #define PTLS_PROTOCOL_VERSION_TLS13_DRAFT27 0x7f1b
72 #define PTLS_PROTOCOL_VERSION_TLS13_DRAFT28 0x7f1c
73
74 #define PTLS_SERVER_NAME_TYPE_HOSTNAME 0
75
76 #define PTLS_SERVER_CERTIFICATE_VERIFY_CONTEXT_STRING "TLS 1.3, server CertificateVerify"
77 #define PTLS_CLIENT_CERTIFICATE_VERIFY_CONTEXT_STRING "TLS 1.3, client CertificateVerify"
78 #define PTLS_MAX_CERTIFICATE_VERIFY_SIGNDATA_SIZE \
79 (64 + sizeof(PTLS_SERVER_CERTIFICATE_VERIFY_CONTEXT_STRING) + PTLS_MAX_DIGEST_SIZE * 2)
80
81 #define PTLS_EARLY_DATA_MAX_DELAY 10000 /* max. RTT (in msec) to permit early data */
82
83 #ifndef PTLS_MAX_EARLY_DATA_SKIP_SIZE
84 #define PTLS_MAX_EARLY_DATA_SKIP_SIZE 65536
85 #endif
86 #if defined(PTLS_DEBUG) && PTLS_DEBUG
87 #define PTLS_DEBUGF(...) fprintf(stderr, __VA_ARGS__)
88 #else
89 #define PTLS_DEBUGF(...)
90 #endif
91
92 #ifndef PTLS_MEMORY_DEBUG
93 #define PTLS_MEMORY_DEBUG 0
94 #endif
95
96 #if PICOTLS_USE_DTRACE
97 #define PTLS_SHOULD_PROBE(LABEL, tls) (PTLS_UNLIKELY(PICOTLS_##LABEL##_ENABLED()) && !(tls)->skip_tracing)
98 #define PTLS_PROBE0(LABEL, tls) \
99 do { \
100 ptls_t *_tls = (tls); \
101 if (PTLS_SHOULD_PROBE(LABEL, _tls)) \
102 PICOTLS_##LABEL(_tls); \
103 } while (0)
104 #define PTLS_PROBE(LABEL, tls, ...) \
105 do { \
106 ptls_t *_tls = (tls); \
107 if (PTLS_SHOULD_PROBE(LABEL, _tls)) \
108 PICOTLS_##LABEL(_tls, __VA_ARGS__); \
109 } while (0)
110 #else
111 #define PTLS_PROBE0(LABEL, tls)
112 #define PTLS_PROBE(LABEL, tls, ...)
113 #endif
114
115 /**
116 * list of supported versions in the preferred order
117 */
118 static const uint16_t supported_versions[] = {PTLS_PROTOCOL_VERSION_TLS13_FINAL, PTLS_PROTOCOL_VERSION_TLS13_DRAFT28,
119 PTLS_PROTOCOL_VERSION_TLS13_DRAFT27, PTLS_PROTOCOL_VERSION_TLS13_DRAFT26};
120
121 static const uint8_t hello_retry_random[PTLS_HELLO_RANDOM_SIZE] = {0xCF, 0x21, 0xAD, 0x74, 0xE5, 0x9A, 0x61, 0x11, 0xBE, 0x1D, 0x8C,
122 0x02, 0x1E, 0x65, 0xB8, 0x91, 0xC2, 0xA2, 0x11, 0x16, 0x7A, 0xBB,
123 0x8C, 0x5E, 0x07, 0x9E, 0x09, 0xE2, 0xC8, 0xA8, 0x33, 0x9C};
124
125 struct st_ptls_traffic_protection_t {
126 uint8_t secret[PTLS_MAX_DIGEST_SIZE];
127 size_t epoch;
128 /* the following fields are not used if the key_change callback is set */
129 ptls_aead_context_t *aead;
130 uint64_t seq;
131 };
132
133 struct st_ptls_record_message_emitter_t {
134 ptls_message_emitter_t super;
135 size_t rec_start;
136 };
137
138 struct st_ptls_signature_algorithms_t {
139 uint16_t list[16]; /* expand? */
140 size_t count;
141 };
142
143 struct st_ptls_certificate_request_t {
144 /**
145 * context.base becomes non-NULL when a CertificateRequest is pending for processing
146 */
147 ptls_iovec_t context;
148 struct st_ptls_signature_algorithms_t signature_algorithms;
149 };
150
151 struct st_ptls_t {
152 /**
153 * the context
154 */
155 ptls_context_t *ctx;
156 /**
157 * the state
158 */
159 enum en_ptls_state_t {
160 PTLS_STATE_CLIENT_HANDSHAKE_START,
161 PTLS_STATE_CLIENT_EXPECT_SERVER_HELLO,
162 PTLS_STATE_CLIENT_EXPECT_SECOND_SERVER_HELLO,
163 PTLS_STATE_CLIENT_EXPECT_ENCRYPTED_EXTENSIONS,
164 PTLS_STATE_CLIENT_EXPECT_CERTIFICATE_REQUEST_OR_CERTIFICATE,
165 PTLS_STATE_CLIENT_EXPECT_CERTIFICATE,
166 PTLS_STATE_CLIENT_EXPECT_CERTIFICATE_VERIFY,
167 PTLS_STATE_CLIENT_EXPECT_FINISHED,
168 PTLS_STATE_SERVER_EXPECT_CLIENT_HELLO,
169 PTLS_STATE_SERVER_EXPECT_SECOND_CLIENT_HELLO,
170 PTLS_STATE_SERVER_EXPECT_CERTIFICATE,
171 PTLS_STATE_SERVER_EXPECT_CERTIFICATE_VERIFY,
172 /* ptls_send can be called if the state is below here */
173 PTLS_STATE_SERVER_EXPECT_END_OF_EARLY_DATA,
174 PTLS_STATE_SERVER_EXPECT_FINISHED,
175 PTLS_STATE_POST_HANDSHAKE_MIN,
176 PTLS_STATE_CLIENT_POST_HANDSHAKE = PTLS_STATE_POST_HANDSHAKE_MIN,
177 PTLS_STATE_SERVER_POST_HANDSHAKE
178 } state;
179 /**
180 * receive buffers
181 */
182 struct {
183 ptls_buffer_t rec;
184 ptls_buffer_t mess;
185 } recvbuf;
186 /**
187 * key schedule
188 */
189 ptls_key_schedule_t *key_schedule;
190 /**
191 * values used for record protection
192 */
193 struct {
194 struct st_ptls_traffic_protection_t dec;
195 struct st_ptls_traffic_protection_t enc;
196 } traffic_protection;
197 /**
198 * server-name passed using SNI
199 */
200 char *server_name;
201 /**
202 * result of ALPN
203 */
204 char *negotiated_protocol;
205 /**
206 * selected key-exchange
207 */
208 ptls_key_exchange_algorithm_t *key_share;
209 /**
210 * selected cipher-suite
211 */
212 ptls_cipher_suite_t *cipher_suite;
213 /**
214 * clienthello.random
215 */
216 uint8_t client_random[PTLS_HELLO_RANDOM_SIZE];
217 /**
218 * esni
219 */
220 ptls_esni_secret_t *esni;
221 /**
222 * exporter master secret (either 0rtt or 1rtt)
223 */
224 struct {
225 uint8_t *early;
226 uint8_t *one_rtt;
227 } exporter_master_secret;
228 /* flags */
229 unsigned is_server : 1;
230 unsigned is_psk_handshake : 1;
231 unsigned send_change_cipher_spec : 1;
232 unsigned needs_key_update : 1;
233 unsigned key_update_send_request : 1;
234 unsigned skip_tracing : 1;
235 /**
236 * misc.
237 */
238 union {
239 struct {
240 ptls_iovec_t legacy_session_id;
241 uint8_t legacy_session_id_buf[32];
242 ptls_key_exchange_context_t *key_share_ctx;
243 unsigned offered_psk : 1;
244 /**
245 * if 1-RTT write key is active
246 */
247 unsigned using_early_data : 1;
248 struct st_ptls_certificate_request_t certificate_request;
249 } client;
250 struct {
251 uint8_t pending_traffic_secret[PTLS_MAX_DIGEST_SIZE];
252 uint32_t early_data_skipped_bytes; /* if not UINT32_MAX, the server is skipping early data */
253 } server;
254 };
255 /**
256 * certificate verify
257 * will be used by the client and the server (if require_client_authentication is set).
258 */
259 struct {
260 int (*cb)(void *verify_ctx, uint16_t algo, ptls_iovec_t data, ptls_iovec_t signature);
261 void *verify_ctx;
262 } certificate_verify;
263 /**
264 * handshake traffic secret to be commisioned (an array of `uint8_t [PTLS_MAX_DIGEST_SIZE]` or NULL)
265 */
266 uint8_t *pending_handshake_secret;
267 /**
268 * user data
269 */
270 void *data_ptr;
271 };
272
273 struct st_ptls_record_t {
274 uint8_t type;
275 uint16_t version;
276 size_t length;
277 const uint8_t *fragment;
278 };
279
280 struct st_ptls_client_hello_psk_t {
281 ptls_iovec_t identity;
282 uint32_t obfuscated_ticket_age;
283 ptls_iovec_t binder;
284 };
285
286 #define MAX_UNKNOWN_EXTENSIONS 16
287 #define MAX_CLIENT_CIPHERS 32
288 #define MAX_CERTIFICATE_TYPES 8
289
290 struct st_ptls_client_hello_t {
291 uint16_t legacy_version;
292 const uint8_t *random_bytes;
293 ptls_iovec_t legacy_session_id;
294 struct {
295 const uint8_t *ids;
296 size_t count;
297 } compression_methods;
298 uint16_t selected_version;
299 ptls_iovec_t cipher_suites;
300 ptls_iovec_t negotiated_groups;
301 ptls_iovec_t key_shares;
302 struct st_ptls_signature_algorithms_t signature_algorithms;
303 ptls_iovec_t server_name;
304 struct {
305 ptls_cipher_suite_t *cipher; /* selected cipher-suite, or NULL if esni extension is not used */
306 ptls_key_exchange_algorithm_t *key_share;
307 ptls_iovec_t peer_key;
308 const uint8_t *record_digest;
309 ptls_iovec_t encrypted_sni;
310 } esni;
311 struct {
312 ptls_iovec_t list[16];
313 size_t count;
314 } alpn;
315 struct {
316 uint16_t list[16];
317 size_t count;
318 } cert_compression_algos;
319 struct {
320 uint16_t list[MAX_CLIENT_CIPHERS];
321 size_t count;
322 } client_ciphers;
323 struct {
324 ptls_iovec_t all;
325 ptls_iovec_t tbs;
326 ptls_iovec_t ch1_hash;
327 ptls_iovec_t signature;
328 unsigned sent_key_share : 1;
329 } cookie;
330 struct {
331 const uint8_t *hash_end;
332 struct {
333 struct st_ptls_client_hello_psk_t list[4];
334 size_t count;
335 } identities;
336 unsigned ke_modes;
337 unsigned early_data_indication : 1;
338 unsigned is_last_extension : 1;
339 } psk;
340 struct {
341 uint8_t list[MAX_CERTIFICATE_TYPES];
342 size_t count;
343 } server_certificate_types;
344 ptls_raw_extension_t unknown_extensions[MAX_UNKNOWN_EXTENSIONS + 1];
345 unsigned status_request : 1;
346 };
347
348 struct st_ptls_server_hello_t {
349 uint8_t random_[PTLS_HELLO_RANDOM_SIZE];
350 ptls_iovec_t legacy_session_id;
351 int is_retry_request;
352 union {
353 ptls_iovec_t peerkey;
354 struct {
355 uint16_t selected_group;
356 ptls_iovec_t cookie;
357 } retry_request;
358 };
359 };
360
361 struct st_ptls_key_schedule_t {
362 unsigned generation; /* early secret (1), hanshake secret (2), master secret (3) */
363 const char *hkdf_label_prefix;
364 uint8_t secret[PTLS_MAX_DIGEST_SIZE];
365 size_t num_hashes;
366 struct {
367 ptls_hash_algorithm_t *algo;
368 ptls_hash_context_t *ctx;
369 } hashes[1];
370 };
371
372 struct st_ptls_extension_decoder_t {
373 uint16_t type;
374 int (*cb)(ptls_t *tls, void *arg, const uint8_t *src, const uint8_t *const end);
375 };
376
377 struct st_ptls_extension_bitmap_t {
378 uint8_t bits[8]; /* only ids below 64 is tracked */
379 };
380
381 static const uint8_t zeroes_of_max_digest_size[PTLS_MAX_DIGEST_SIZE] = {0};
382
383 static int hkdf_expand_label(ptls_hash_algorithm_t *algo, void *output, size_t outlen, ptls_iovec_t secret, const char *label,
384 ptls_iovec_t hash_value, const char *label_prefix);
385 static ptls_aead_context_t *new_aead(ptls_aead_algorithm_t *aead, ptls_hash_algorithm_t *hash, int is_enc, const void *secret,
386 ptls_iovec_t hash_value, const char *label_prefix);
387
is_supported_version(uint16_t v)388 static int is_supported_version(uint16_t v)
389 {
390 size_t i;
391 for (i = 0; i != PTLS_ELEMENTSOF(supported_versions); ++i)
392 if (supported_versions[i] == v)
393 return 1;
394 return 0;
395 }
396
extension_bitmap_is_set(struct st_ptls_extension_bitmap_t * bitmap,uint16_t id)397 static inline int extension_bitmap_is_set(struct st_ptls_extension_bitmap_t *bitmap, uint16_t id)
398 {
399 if (id < sizeof(bitmap->bits) * 8)
400 return (bitmap->bits[id / 8] & (1 << (id % 8))) != 0;
401 return 0;
402 }
403
extension_bitmap_set(struct st_ptls_extension_bitmap_t * bitmap,uint16_t id)404 static inline void extension_bitmap_set(struct st_ptls_extension_bitmap_t *bitmap, uint16_t id)
405 {
406 if (id < sizeof(bitmap->bits) * 8)
407 bitmap->bits[id / 8] |= 1 << (id % 8);
408 }
409
init_extension_bitmap(struct st_ptls_extension_bitmap_t * bitmap,uint8_t hstype)410 static inline void init_extension_bitmap(struct st_ptls_extension_bitmap_t *bitmap, uint8_t hstype)
411 {
412 *bitmap = (struct st_ptls_extension_bitmap_t){{0}};
413
414 #define EXT(extid, proc) \
415 do { \
416 int _found = 0; \
417 do { \
418 proc \
419 } while (0); \
420 if (!_found) \
421 extension_bitmap_set(bitmap, PTLS_EXTENSION_TYPE_##extid); \
422 } while (0)
423 #define ALLOW(allowed_hstype) _found = _found || hstype == PTLS_HANDSHAKE_TYPE_##allowed_hstype
424
425 /* Implements the table found in section 4.2 of draft-19; "If an implementation receives an extension which it recognizes and
426 * which is not specified for the message in which it appears it MUST abort the handshake with an “illegal_parameter” alert."
427 */
428 EXT(SERVER_NAME, {
429 ALLOW(CLIENT_HELLO);
430 ALLOW(ENCRYPTED_EXTENSIONS);
431 });
432 EXT(STATUS_REQUEST, {
433 ALLOW(CLIENT_HELLO);
434 ALLOW(CERTIFICATE);
435 ALLOW(CERTIFICATE_REQUEST);
436 });
437 EXT(SUPPORTED_GROUPS, {
438 ALLOW(CLIENT_HELLO);
439 ALLOW(ENCRYPTED_EXTENSIONS);
440 });
441 EXT(SIGNATURE_ALGORITHMS, {
442 ALLOW(CLIENT_HELLO);
443 ALLOW(CERTIFICATE_REQUEST);
444 });
445 EXT(ALPN, {
446 ALLOW(CLIENT_HELLO);
447 ALLOW(ENCRYPTED_EXTENSIONS);
448 });
449 EXT(KEY_SHARE, {
450 ALLOW(CLIENT_HELLO);
451 ALLOW(SERVER_HELLO);
452 });
453 EXT(PRE_SHARED_KEY, {
454 ALLOW(CLIENT_HELLO);
455 ALLOW(SERVER_HELLO);
456 });
457 EXT(PSK_KEY_EXCHANGE_MODES, { ALLOW(CLIENT_HELLO); });
458 EXT(EARLY_DATA, {
459 ALLOW(CLIENT_HELLO);
460 ALLOW(ENCRYPTED_EXTENSIONS);
461 ALLOW(NEW_SESSION_TICKET);
462 });
463 EXT(COOKIE, {
464 ALLOW(CLIENT_HELLO);
465 ALLOW(SERVER_HELLO);
466 });
467 EXT(SUPPORTED_VERSIONS, {
468 ALLOW(CLIENT_HELLO);
469 ALLOW(SERVER_HELLO);
470 });
471 EXT(SERVER_CERTIFICATE_TYPE, {
472 ALLOW(CLIENT_HELLO);
473 ALLOW(ENCRYPTED_EXTENSIONS);
474 });
475
476 #undef ALLOW
477 #undef EXT
478 }
479
480 #ifndef ntoh16
ntoh16(const uint8_t * src)481 static uint16_t ntoh16(const uint8_t *src)
482 {
483 return (uint16_t)src[0] << 8 | src[1];
484 }
485 #endif
486
487 #ifndef ntoh24
ntoh24(const uint8_t * src)488 static uint32_t ntoh24(const uint8_t *src)
489 {
490 return (uint32_t)src[0] << 16 | (uint32_t)src[1] << 8 | src[2];
491 }
492 #endif
493
494 #ifndef ntoh32
ntoh32(const uint8_t * src)495 static uint32_t ntoh32(const uint8_t *src)
496 {
497 return (uint32_t)src[0] << 24 | (uint32_t)src[1] << 16 | (uint32_t)src[2] << 8 | src[3];
498 }
499 #endif
500
501 #ifndef ntoh64
ntoh64(const uint8_t * src)502 static uint64_t ntoh64(const uint8_t *src)
503 {
504 return (uint64_t)src[0] << 56 | (uint64_t)src[1] << 48 | (uint64_t)src[2] << 40 | (uint64_t)src[3] << 32 |
505 (uint64_t)src[4] << 24 | (uint64_t)src[5] << 16 | (uint64_t)src[6] << 8 | src[7];
506 }
507 #endif
508
ptls_buffer__release_memory(ptls_buffer_t * buf)509 void ptls_buffer__release_memory(ptls_buffer_t *buf)
510 {
511 ptls_clear_memory(buf->base, buf->off);
512 if (buf->is_allocated)
513 free(buf->base);
514 }
515
ptls_buffer_reserve(ptls_buffer_t * buf,size_t delta)516 int ptls_buffer_reserve(ptls_buffer_t *buf, size_t delta)
517 {
518 if (buf->base == NULL)
519 return PTLS_ERROR_NO_MEMORY;
520
521 if (PTLS_MEMORY_DEBUG || buf->capacity < buf->off + delta) {
522 uint8_t *newp;
523 size_t new_capacity = buf->capacity;
524 if (new_capacity < 1024)
525 new_capacity = 1024;
526 while (new_capacity < buf->off + delta) {
527 new_capacity *= 2;
528 }
529 if ((newp = malloc(new_capacity)) == NULL)
530 return PTLS_ERROR_NO_MEMORY;
531 memcpy(newp, buf->base, buf->off);
532 ptls_buffer__release_memory(buf);
533 buf->base = newp;
534 buf->capacity = new_capacity;
535 buf->is_allocated = 1;
536 }
537
538 return 0;
539 }
540
ptls_buffer__do_pushv(ptls_buffer_t * buf,const void * src,size_t len)541 int ptls_buffer__do_pushv(ptls_buffer_t *buf, const void *src, size_t len)
542 {
543 int ret;
544
545 if (len == 0)
546 return 0;
547 if ((ret = ptls_buffer_reserve(buf, len)) != 0)
548 return ret;
549 memcpy(buf->base + buf->off, src, len);
550 buf->off += len;
551 return 0;
552 }
553
ptls_buffer__adjust_quic_blocksize(ptls_buffer_t * buf,size_t body_size)554 int ptls_buffer__adjust_quic_blocksize(ptls_buffer_t *buf, size_t body_size)
555 {
556 uint8_t sizebuf[PTLS_ENCODE_QUICINT_CAPACITY];
557 size_t sizelen = ptls_encode_quicint(sizebuf, body_size) - sizebuf;
558
559 /* adjust amount of space before body_size to `sizelen` bytes */
560 if (sizelen != 1) {
561 int ret;
562 if ((ret = ptls_buffer_reserve(buf, sizelen - 1)) != 0)
563 return ret;
564 memmove(buf->base + buf->off - body_size - 1 + sizelen, buf->base + buf->off - body_size, body_size);
565 buf->off += sizelen - 1;
566 }
567
568 /* write the size */
569 memcpy(buf->base + buf->off - body_size - sizelen, sizebuf, sizelen);
570
571 return 0;
572 }
573
ptls_buffer__adjust_asn1_blocksize(ptls_buffer_t * buf,size_t body_size)574 int ptls_buffer__adjust_asn1_blocksize(ptls_buffer_t *buf, size_t body_size)
575 {
576 fprintf(stderr, "unimplemented\n");
577 abort();
578 }
579
ptls_buffer_push_asn1_ubigint(ptls_buffer_t * buf,const void * bignum,size_t size)580 int ptls_buffer_push_asn1_ubigint(ptls_buffer_t *buf, const void *bignum, size_t size)
581 {
582 const uint8_t *p = bignum, *const end = p + size;
583 int ret;
584
585 /* skip zeroes */
586 for (; end - p >= 1; ++p)
587 if (*p != 0)
588 break;
589
590 /* emit */
591 ptls_buffer_push(buf, 2);
592 ptls_buffer_push_asn1_block(buf, {
593 if (*p >= 0x80)
594 ptls_buffer_push(buf, 0);
595 if (p != end) {
596 ptls_buffer_pushv(buf, p, end - p);
597 } else {
598 ptls_buffer_pushv(buf, "", 1);
599 }
600 });
601 ret = 0;
602
603 Exit:
604 return ret;
605 }
606
607 #if PTLS_FUZZ_HANDSHAKE
608
aead_encrypt(struct st_ptls_traffic_protection_t * ctx,void * output,const void * input,size_t inlen,uint8_t content_type)609 static size_t aead_encrypt(struct st_ptls_traffic_protection_t *ctx, void *output, const void *input, size_t inlen,
610 uint8_t content_type)
611 {
612 memcpy(output, input, inlen);
613 memcpy(output + inlen, &content_type, 1);
614 return inlen + 1 + 16;
615 }
616
aead_decrypt(struct st_ptls_traffic_protection_t * ctx,void * output,size_t * outlen,const void * input,size_t inlen)617 static int aead_decrypt(struct st_ptls_traffic_protection_t *ctx, void *output, size_t *outlen, const void *input, size_t inlen)
618 {
619 if (inlen < 16) {
620 return PTLS_ALERT_BAD_RECORD_MAC;
621 }
622 memcpy(output, input, inlen - 16);
623 *outlen = inlen - 16; /* removing the 16 bytes of tag */
624 return 0;
625 }
626
627 #else
628
build_aad(uint8_t aad[5],size_t reclen)629 static void build_aad(uint8_t aad[5], size_t reclen)
630 {
631 aad[0] = PTLS_CONTENT_TYPE_APPDATA;
632 aad[1] = PTLS_RECORD_VERSION_MAJOR;
633 aad[2] = PTLS_RECORD_VERSION_MINOR;
634 aad[3] = (uint8_t)(reclen >> 8);
635 aad[4] = (uint8_t)reclen;
636 }
637
aead_encrypt(struct st_ptls_traffic_protection_t * ctx,void * output,const void * input,size_t inlen,uint8_t content_type)638 static size_t aead_encrypt(struct st_ptls_traffic_protection_t *ctx, void *output, const void *input, size_t inlen,
639 uint8_t content_type)
640 {
641 uint8_t aad[5];
642 size_t off = 0;
643
644 build_aad(aad, inlen + 1 + ctx->aead->algo->tag_size);
645 ptls_aead_encrypt_init(ctx->aead, ctx->seq++, aad, sizeof(aad));
646 off += ptls_aead_encrypt_update(ctx->aead, ((uint8_t *)output) + off, input, inlen);
647 off += ptls_aead_encrypt_update(ctx->aead, ((uint8_t *)output) + off, &content_type, 1);
648 off += ptls_aead_encrypt_final(ctx->aead, ((uint8_t *)output) + off);
649
650 return off;
651 }
652
aead_decrypt(struct st_ptls_traffic_protection_t * ctx,void * output,size_t * outlen,const void * input,size_t inlen)653 static int aead_decrypt(struct st_ptls_traffic_protection_t *ctx, void *output, size_t *outlen, const void *input, size_t inlen)
654 {
655 uint8_t aad[5];
656
657 build_aad(aad, inlen);
658 if ((*outlen = ptls_aead_decrypt(ctx->aead, output, input, inlen, ctx->seq, aad, sizeof(aad))) == SIZE_MAX)
659 return PTLS_ALERT_BAD_RECORD_MAC;
660 ++ctx->seq;
661 return 0;
662 }
663
664 #endif /* #if PTLS_FUZZ_HANDSHAKE */
665
666 #define buffer_push_record(buf, type, block) \
667 do { \
668 ptls_buffer_push((buf), (type), PTLS_RECORD_VERSION_MAJOR, PTLS_RECORD_VERSION_MINOR); \
669 ptls_buffer_push_block((buf), 2, block); \
670 } while (0)
671
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)672 static int buffer_push_encrypted_records(ptls_buffer_t *buf, uint8_t type, const uint8_t *src, size_t len,
673 struct st_ptls_traffic_protection_t *enc)
674 {
675 int ret = 0;
676
677 while (len != 0) {
678 size_t chunk_size = len;
679 if (chunk_size > PTLS_MAX_PLAINTEXT_RECORD_SIZE)
680 chunk_size = PTLS_MAX_PLAINTEXT_RECORD_SIZE;
681 buffer_push_record(buf, PTLS_CONTENT_TYPE_APPDATA, {
682 if ((ret = ptls_buffer_reserve(buf, chunk_size + enc->aead->algo->tag_size + 1)) != 0)
683 goto Exit;
684 buf->off += aead_encrypt(enc, buf->base + buf->off, src, chunk_size, type);
685 });
686 src += chunk_size;
687 len -= chunk_size;
688 }
689
690 Exit:
691 return ret;
692 }
693
buffer_encrypt_record(ptls_buffer_t * buf,size_t rec_start,struct st_ptls_traffic_protection_t * enc)694 static int buffer_encrypt_record(ptls_buffer_t *buf, size_t rec_start, struct st_ptls_traffic_protection_t *enc)
695 {
696 size_t bodylen = buf->off - rec_start - 5;
697 uint8_t *tmpbuf, type = buf->base[rec_start];
698 int ret;
699
700 /* fast path: do in-place encryption if only one record needs to be emitted */
701 if (bodylen <= PTLS_MAX_PLAINTEXT_RECORD_SIZE) {
702 size_t overhead = 1 + enc->aead->algo->tag_size;
703 if ((ret = ptls_buffer_reserve(buf, overhead)) != 0)
704 return ret;
705 size_t encrypted_len = aead_encrypt(enc, buf->base + rec_start + 5, buf->base + rec_start + 5, bodylen, type);
706 assert(encrypted_len == bodylen + overhead);
707 buf->off += overhead;
708 buf->base[rec_start] = PTLS_CONTENT_TYPE_APPDATA;
709 buf->base[rec_start + 3] = (encrypted_len >> 8) & 0xff;
710 buf->base[rec_start + 4] = encrypted_len & 0xff;
711 return 0;
712 }
713
714 /* move plaintext to temporary buffer */
715 if ((tmpbuf = malloc(bodylen)) == NULL) {
716 ret = PTLS_ERROR_NO_MEMORY;
717 goto Exit;
718 }
719 memcpy(tmpbuf, buf->base + rec_start + 5, bodylen);
720 ptls_clear_memory(buf->base + rec_start, bodylen + 5);
721 buf->off = rec_start;
722
723 /* push encrypted records */
724 ret = buffer_push_encrypted_records(buf, type, tmpbuf, bodylen, enc);
725
726 Exit:
727 if (tmpbuf != NULL) {
728 ptls_clear_memory(tmpbuf, bodylen);
729 free(tmpbuf);
730 }
731 return ret;
732 }
733
begin_record_message(ptls_message_emitter_t * _self)734 static int begin_record_message(ptls_message_emitter_t *_self)
735 {
736 struct st_ptls_record_message_emitter_t *self = (void *)_self;
737 int ret;
738
739 self->rec_start = self->super.buf->off;
740 ptls_buffer_push(self->super.buf, PTLS_CONTENT_TYPE_HANDSHAKE, PTLS_RECORD_VERSION_MAJOR, PTLS_RECORD_VERSION_MINOR, 0, 0);
741 ret = 0;
742 Exit:
743 return ret;
744 }
745
commit_record_message(ptls_message_emitter_t * _self)746 static int commit_record_message(ptls_message_emitter_t *_self)
747 {
748 struct st_ptls_record_message_emitter_t *self = (void *)_self;
749 int ret;
750
751 if (self->super.enc->aead != NULL) {
752 ret = buffer_encrypt_record(self->super.buf, self->rec_start, self->super.enc);
753 } else {
754 /* TODO allow CH,SH,HRR above 16KB */
755 size_t sz = self->super.buf->off - self->rec_start - 5;
756 assert(sz <= PTLS_MAX_PLAINTEXT_RECORD_SIZE);
757 self->super.buf->base[self->rec_start + 3] = (uint8_t)(sz >> 8);
758 self->super.buf->base[self->rec_start + 4] = (uint8_t)(sz);
759 ret = 0;
760 }
761
762 return ret;
763 }
764
765 #define buffer_push_extension(buf, type, block) \
766 do { \
767 ptls_buffer_push16((buf), (type)); \
768 ptls_buffer_push_block((buf), 2, block); \
769 } while (0);
770
771 #define decode_open_extensions(src, end, hstype, exttype, block) \
772 do { \
773 struct st_ptls_extension_bitmap_t bitmap; \
774 init_extension_bitmap(&bitmap, (hstype)); \
775 ptls_decode_open_block((src), end, 2, { \
776 while ((src) != end) { \
777 if ((ret = ptls_decode16((exttype), &(src), end)) != 0) \
778 goto Exit; \
779 if (extension_bitmap_is_set(&bitmap, *(exttype)) != 0) { \
780 ret = PTLS_ALERT_ILLEGAL_PARAMETER; \
781 goto Exit; \
782 } \
783 extension_bitmap_set(&bitmap, *(exttype)); \
784 ptls_decode_open_block((src), end, 2, block); \
785 } \
786 }); \
787 } while (0)
788
789 #define decode_extensions(src, end, hstype, exttype, block) \
790 do { \
791 decode_open_extensions((src), end, hstype, exttype, block); \
792 ptls_decode_assert_block_close((src), end); \
793 } while (0)
794
ptls_decode16(uint16_t * value,const uint8_t ** src,const uint8_t * end)795 int ptls_decode16(uint16_t *value, const uint8_t **src, const uint8_t *end)
796 {
797 if (end - *src < 2)
798 return PTLS_ALERT_DECODE_ERROR;
799 *value = ntoh16(*src);
800 *src += 2;
801 return 0;
802 }
803
ptls_decode24(uint32_t * value,const uint8_t ** src,const uint8_t * end)804 int ptls_decode24(uint32_t *value, const uint8_t **src, const uint8_t *end)
805 {
806 if (end - *src < 3)
807 return PTLS_ALERT_DECODE_ERROR;
808 *value = ((uint32_t)(*src)[0] << 16) | ((uint32_t)(*src)[1] << 8) | (*src)[2];
809 *src += 3;
810 return 0;
811 }
812
ptls_decode32(uint32_t * value,const uint8_t ** src,const uint8_t * end)813 int ptls_decode32(uint32_t *value, const uint8_t **src, const uint8_t *end)
814 {
815 if (end - *src < 4)
816 return PTLS_ALERT_DECODE_ERROR;
817 *value = ntoh32(*src);
818 *src += 4;
819 return 0;
820 }
821
ptls_decode64(uint64_t * value,const uint8_t ** src,const uint8_t * end)822 int ptls_decode64(uint64_t *value, const uint8_t **src, const uint8_t *end)
823 {
824 if (end - *src < 8)
825 return PTLS_ALERT_DECODE_ERROR;
826 *value = ntoh64(*src);
827 *src += 8;
828 return 0;
829 }
830
ptls_decode_quicint(const uint8_t ** src,const uint8_t * end)831 uint64_t ptls_decode_quicint(const uint8_t **src, const uint8_t *end)
832 {
833 if (PTLS_UNLIKELY(*src == end))
834 return UINT64_MAX;
835
836 uint8_t b = *(*src)++;
837
838 if (PTLS_LIKELY(b <= 0x3f))
839 return b;
840
841 uint64_t v = b & 0x3f;
842 unsigned bytes_left = (1 << (b >> 6)) - 1;
843 if (PTLS_UNLIKELY((size_t)(end - *src) < bytes_left))
844 return UINT64_MAX;
845 do {
846 v = (v << 8) | *(*src)++;
847 } while (--bytes_left != 0);
848 return v;
849 }
850
log_secret(ptls_t * tls,const char * type,ptls_iovec_t secret)851 static void log_secret(ptls_t *tls, const char *type, ptls_iovec_t secret)
852 {
853 char hexbuf[PTLS_MAX_DIGEST_SIZE * 2 + 1];
854
855 PTLS_PROBE(NEW_SECRET, tls, type, ptls_hexdump(hexbuf, secret.base, secret.len));
856
857 if (tls->ctx->log_event != NULL)
858 tls->ctx->log_event->cb(tls->ctx->log_event, tls, type, "%s", ptls_hexdump(hexbuf, secret.base, secret.len));
859 }
860
key_schedule_free(ptls_key_schedule_t * sched)861 static void key_schedule_free(ptls_key_schedule_t *sched)
862 {
863 size_t i;
864 ptls_clear_memory(sched->secret, sizeof(sched->secret));
865 for (i = 0; i != sched->num_hashes; ++i)
866 sched->hashes[i].ctx->final(sched->hashes[i].ctx, NULL, PTLS_HASH_FINAL_MODE_FREE);
867 free(sched);
868 }
869
key_schedule_new(ptls_cipher_suite_t * preferred,ptls_cipher_suite_t ** offered,const char * hkdf_label_prefix)870 static ptls_key_schedule_t *key_schedule_new(ptls_cipher_suite_t *preferred, ptls_cipher_suite_t **offered,
871 const char *hkdf_label_prefix)
872 {
873 #define FOREACH_HASH(block) \
874 do { \
875 ptls_cipher_suite_t *cs; \
876 if ((cs = preferred) != NULL) { \
877 block \
878 } \
879 if (offered != NULL) { \
880 size_t i, j; \
881 for (i = 0; (cs = offered[i]) != NULL; ++i) { \
882 if (preferred == NULL || cs->hash != preferred->hash) { \
883 for (j = 0; j != i; ++j) \
884 if (cs->hash == offered[j]->hash) \
885 break; \
886 if (j == i) { \
887 block \
888 } \
889 } \
890 } \
891 } \
892 } while (0)
893
894 ptls_key_schedule_t *sched;
895
896 if (hkdf_label_prefix == NULL)
897 hkdf_label_prefix = PTLS_HKDF_EXPAND_LABEL_PREFIX;
898
899 { /* allocate */
900 size_t num_hashes = 0;
901 FOREACH_HASH({ ++num_hashes; });
902 if ((sched = malloc(offsetof(ptls_key_schedule_t, hashes) + sizeof(sched->hashes[0]) * num_hashes)) == NULL)
903 return NULL;
904 *sched = (ptls_key_schedule_t){0, hkdf_label_prefix};
905 }
906
907 /* setup the hash algos and contexts */
908 FOREACH_HASH({
909 sched->hashes[sched->num_hashes].algo = cs->hash;
910 if ((sched->hashes[sched->num_hashes].ctx = cs->hash->create()) == NULL)
911 goto Fail;
912 ++sched->num_hashes;
913 });
914
915 return sched;
916 Fail:
917 key_schedule_free(sched);
918 return NULL;
919
920 #undef FOREACH_HASH
921 }
922
key_schedule_extract(ptls_key_schedule_t * sched,ptls_iovec_t ikm)923 static int key_schedule_extract(ptls_key_schedule_t *sched, ptls_iovec_t ikm)
924 {
925 int ret;
926
927 if (ikm.base == NULL)
928 ikm = ptls_iovec_init(zeroes_of_max_digest_size, sched->hashes[0].algo->digest_size);
929
930 if (sched->generation != 0 &&
931 (ret = hkdf_expand_label(sched->hashes[0].algo, sched->secret, sched->hashes[0].algo->digest_size,
932 ptls_iovec_init(sched->secret, sched->hashes[0].algo->digest_size), "derived",
933 ptls_iovec_init(sched->hashes[0].algo->empty_digest, sched->hashes[0].algo->digest_size),
934 sched->hkdf_label_prefix)) != 0)
935 return ret;
936
937 ++sched->generation;
938 ret = ptls_hkdf_extract(sched->hashes[0].algo, sched->secret,
939 ptls_iovec_init(sched->secret, sched->hashes[0].algo->digest_size), ikm);
940 PTLS_DEBUGF("%s: %u, %02x%02x\n", __FUNCTION__, sched->generation, (int)sched->secret[0], (int)sched->secret[1]);
941 return ret;
942 }
943
key_schedule_select_one(ptls_key_schedule_t * sched,ptls_cipher_suite_t * cs,int reset)944 static int key_schedule_select_one(ptls_key_schedule_t *sched, ptls_cipher_suite_t *cs, int reset)
945 {
946 size_t found_slot = SIZE_MAX, i;
947 int ret;
948
949 assert(sched->generation == 1);
950
951 /* find the one, while freeing others */
952 for (i = 0; i != sched->num_hashes; ++i) {
953 if (sched->hashes[i].algo == cs->hash) {
954 assert(found_slot == SIZE_MAX);
955 found_slot = i;
956 } else {
957 sched->hashes[i].ctx->final(sched->hashes[i].ctx, NULL, PTLS_HASH_FINAL_MODE_FREE);
958 }
959 }
960 if (found_slot != 0) {
961 sched->hashes[0] = sched->hashes[found_slot];
962 reset = 1;
963 }
964 sched->num_hashes = 1;
965
966 /* recalculate the hash if a different hash as been selected than the one we used for calculating the early secrets */
967 if (reset) {
968 --sched->generation;
969 memset(sched->secret, 0, sizeof(sched->secret));
970 if ((ret = key_schedule_extract(sched, ptls_iovec_init(NULL, 0))) != 0)
971 goto Exit;
972 }
973
974 ret = 0;
975 Exit:
976 return ret;
977 }
978
ptls__key_schedule_update_hash(ptls_key_schedule_t * sched,const uint8_t * msg,size_t msglen)979 void ptls__key_schedule_update_hash(ptls_key_schedule_t *sched, const uint8_t *msg, size_t msglen)
980 {
981 size_t i;
982
983 PTLS_DEBUGF("%s:%zu\n", __FUNCTION__, msglen);
984 for (i = 0; i != sched->num_hashes; ++i)
985 sched->hashes[i].ctx->update(sched->hashes[i].ctx, msg, msglen);
986 }
987
key_schedule_update_ch1hash_prefix(ptls_key_schedule_t * sched)988 static void key_schedule_update_ch1hash_prefix(ptls_key_schedule_t *sched)
989 {
990 uint8_t prefix[4] = {PTLS_HANDSHAKE_TYPE_MESSAGE_HASH, 0, 0, (uint8_t)sched->hashes[0].algo->digest_size};
991 ptls__key_schedule_update_hash(sched, prefix, sizeof(prefix));
992 }
993
key_schedule_extract_ch1hash(ptls_key_schedule_t * sched,uint8_t * hash)994 static void key_schedule_extract_ch1hash(ptls_key_schedule_t *sched, uint8_t *hash)
995 {
996 sched->hashes[0].ctx->final(sched->hashes[0].ctx, hash, PTLS_HASH_FINAL_MODE_RESET);
997 }
998
key_schedule_transform_post_ch1hash(ptls_key_schedule_t * sched)999 static void key_schedule_transform_post_ch1hash(ptls_key_schedule_t *sched)
1000 {
1001 uint8_t ch1hash[PTLS_MAX_DIGEST_SIZE];
1002
1003 key_schedule_extract_ch1hash(sched, ch1hash);
1004
1005 key_schedule_update_ch1hash_prefix(sched);
1006 ptls__key_schedule_update_hash(sched, ch1hash, sched->hashes[0].algo->digest_size);
1007 }
1008
derive_secret_with_hash(ptls_key_schedule_t * sched,void * secret,const char * label,const uint8_t * hash)1009 static int derive_secret_with_hash(ptls_key_schedule_t *sched, void *secret, const char *label, const uint8_t *hash)
1010 {
1011 int ret = hkdf_expand_label(sched->hashes[0].algo, secret, sched->hashes[0].algo->digest_size,
1012 ptls_iovec_init(sched->secret, sched->hashes[0].algo->digest_size), label,
1013 ptls_iovec_init(hash, sched->hashes[0].algo->digest_size), sched->hkdf_label_prefix);
1014 PTLS_DEBUGF("%s: (label=%s, hash=%02x%02x) => %02x%02x\n", __FUNCTION__, label, hash[0], hash[1], ((uint8_t *)secret)[0],
1015 ((uint8_t *)secret)[1]);
1016 return ret;
1017 }
1018
derive_secret(ptls_key_schedule_t * sched,void * secret,const char * label)1019 static int derive_secret(ptls_key_schedule_t *sched, void *secret, const char *label)
1020 {
1021 uint8_t hash_value[PTLS_MAX_DIGEST_SIZE];
1022
1023 sched->hashes[0].ctx->final(sched->hashes[0].ctx, hash_value, PTLS_HASH_FINAL_MODE_SNAPSHOT);
1024 int ret = derive_secret_with_hash(sched, secret, label, hash_value);
1025 ptls_clear_memory(hash_value, sizeof(hash_value));
1026 return ret;
1027 }
1028
derive_secret_with_empty_digest(ptls_key_schedule_t * sched,void * secret,const char * label)1029 static int derive_secret_with_empty_digest(ptls_key_schedule_t *sched, void *secret, const char *label)
1030 {
1031 return derive_secret_with_hash(sched, secret, label, sched->hashes[0].algo->empty_digest);
1032 }
1033
derive_exporter_secret(ptls_t * tls,int is_early)1034 static int derive_exporter_secret(ptls_t *tls, int is_early)
1035 {
1036 int ret;
1037
1038 if (!tls->ctx->use_exporter)
1039 return 0;
1040
1041 uint8_t **slot = is_early ? &tls->exporter_master_secret.early : &tls->exporter_master_secret.one_rtt;
1042 assert(*slot == NULL);
1043 if ((*slot = malloc(tls->key_schedule->hashes[0].algo->digest_size)) == NULL)
1044 return PTLS_ERROR_NO_MEMORY;
1045
1046 if ((ret = derive_secret(tls->key_schedule, *slot, is_early ? "e exp master" : "exp master")) != 0)
1047 return ret;
1048
1049 log_secret(tls, is_early ? "EARLY_EXPORTER_SECRET" : "EXPORTER_SECRET",
1050 ptls_iovec_init(*slot, tls->key_schedule->hashes[0].algo->digest_size));
1051
1052 return 0;
1053 }
1054
free_exporter_master_secret(ptls_t * tls,int is_early)1055 static void free_exporter_master_secret(ptls_t *tls, int is_early)
1056 {
1057 uint8_t *slot = is_early ? tls->exporter_master_secret.early : tls->exporter_master_secret.one_rtt;
1058 if (slot == NULL)
1059 return;
1060 assert(tls->key_schedule != NULL);
1061 ptls_clear_memory(slot, tls->key_schedule->hashes[0].algo->digest_size);
1062 free(slot);
1063 }
1064
derive_resumption_secret(ptls_key_schedule_t * sched,uint8_t * secret,ptls_iovec_t nonce)1065 static int derive_resumption_secret(ptls_key_schedule_t *sched, uint8_t *secret, ptls_iovec_t nonce)
1066 {
1067 int ret;
1068
1069 if ((ret = derive_secret(sched, secret, "res master")) != 0)
1070 goto Exit;
1071 if ((ret = hkdf_expand_label(sched->hashes[0].algo, secret, sched->hashes[0].algo->digest_size,
1072 ptls_iovec_init(secret, sched->hashes[0].algo->digest_size), "resumption", nonce,
1073 sched->hkdf_label_prefix)) != 0)
1074 goto Exit;
1075
1076 Exit:
1077 if (ret != 0)
1078 ptls_clear_memory(secret, sched->hashes[0].algo->digest_size);
1079 return ret;
1080 }
1081
decode_new_session_ticket(ptls_t * tls,uint32_t * lifetime,uint32_t * age_add,ptls_iovec_t * nonce,ptls_iovec_t * ticket,uint32_t * max_early_data_size,const uint8_t * src,const uint8_t * const end)1082 static int decode_new_session_ticket(ptls_t *tls, uint32_t *lifetime, uint32_t *age_add, ptls_iovec_t *nonce, ptls_iovec_t *ticket,
1083 uint32_t *max_early_data_size, const uint8_t *src, const uint8_t *const end)
1084 {
1085 uint16_t exttype;
1086 int ret;
1087
1088 if ((ret = ptls_decode32(lifetime, &src, end)) != 0)
1089 goto Exit;
1090 if ((ret = ptls_decode32(age_add, &src, end)) != 0)
1091 goto Exit;
1092 ptls_decode_open_block(src, end, 1, {
1093 *nonce = ptls_iovec_init(src, end - src);
1094 src = end;
1095 });
1096 ptls_decode_open_block(src, end, 2, {
1097 if (src == end) {
1098 ret = PTLS_ALERT_DECODE_ERROR;
1099 goto Exit;
1100 }
1101 *ticket = ptls_iovec_init(src, end - src);
1102 src = end;
1103 });
1104
1105 *max_early_data_size = 0;
1106 decode_extensions(src, end, PTLS_HANDSHAKE_TYPE_NEW_SESSION_TICKET, &exttype, {
1107 if (tls->ctx->on_extension != NULL &&
1108 (ret = tls->ctx->on_extension->cb(tls->ctx->on_extension, tls, PTLS_HANDSHAKE_TYPE_NEW_SESSION_TICKET, exttype,
1109 ptls_iovec_init(src, end - src)) != 0))
1110 goto Exit;
1111 switch (exttype) {
1112 case PTLS_EXTENSION_TYPE_EARLY_DATA:
1113 if ((ret = ptls_decode32(max_early_data_size, &src, end)) != 0)
1114 goto Exit;
1115 break;
1116 default:
1117 src = end;
1118 break;
1119 }
1120 });
1121
1122 ret = 0;
1123 Exit:
1124 return ret;
1125 }
1126
decode_stored_session_ticket(ptls_t * tls,ptls_key_exchange_algorithm_t ** key_share,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 * const end)1127 static int decode_stored_session_ticket(ptls_t *tls, ptls_key_exchange_algorithm_t **key_share, ptls_cipher_suite_t **cs,
1128 ptls_iovec_t *secret, uint32_t *obfuscated_ticket_age, ptls_iovec_t *ticket,
1129 uint32_t *max_early_data_size, const uint8_t *src, const uint8_t *const end)
1130 {
1131 uint16_t kxid, csid;
1132 uint32_t lifetime, age_add;
1133 uint64_t obtained_at, now;
1134 ptls_iovec_t nonce;
1135 int ret;
1136
1137 /* decode */
1138 if ((ret = ptls_decode64(&obtained_at, &src, end)) != 0)
1139 goto Exit;
1140 if ((ret = ptls_decode16(&kxid, &src, end)) != 0)
1141 goto Exit;
1142 if ((ret = ptls_decode16(&csid, &src, end)) != 0)
1143 goto Exit;
1144 ptls_decode_open_block(src, end, 3, {
1145 if ((ret = decode_new_session_ticket(tls, &lifetime, &age_add, &nonce, ticket, max_early_data_size, src, end)) != 0)
1146 goto Exit;
1147 src = end;
1148 });
1149 ptls_decode_block(src, end, 2, {
1150 *secret = ptls_iovec_init(src, end - src);
1151 src = end;
1152 });
1153
1154 { /* determine the key-exchange */
1155 ptls_key_exchange_algorithm_t **cand;
1156 for (cand = tls->ctx->key_exchanges; *cand != NULL; ++cand)
1157 if ((*cand)->id == kxid)
1158 break;
1159 if (*cand == NULL) {
1160 ret = PTLS_ERROR_LIBRARY;
1161 goto Exit;
1162 }
1163 *key_share = *cand;
1164 }
1165
1166 { /* determine the cipher-suite */
1167 ptls_cipher_suite_t **cand;
1168 for (cand = tls->ctx->cipher_suites; *cand != NULL; ++cand)
1169 if ((*cand)->id == csid)
1170 break;
1171 if (*cand == NULL) {
1172 ret = PTLS_ERROR_LIBRARY;
1173 goto Exit;
1174 }
1175 *cs = *cand;
1176 }
1177
1178 /* calculate obfuscated_ticket_age */
1179 now = tls->ctx->get_time->cb(tls->ctx->get_time);
1180 if (!(obtained_at <= now && now - obtained_at < 7 * 86400 * 1000)) {
1181 ret = PTLS_ERROR_LIBRARY;
1182 goto Exit;
1183 }
1184 *obfuscated_ticket_age = (uint32_t)(now - obtained_at) + age_add;
1185
1186 ret = 0;
1187 Exit:
1188 return ret;
1189 }
1190
get_traffic_key(ptls_hash_algorithm_t * algo,void * key,size_t key_size,int is_iv,const void * secret,ptls_iovec_t hash_value,const char * label_prefix)1191 static int get_traffic_key(ptls_hash_algorithm_t *algo, void *key, size_t key_size, int is_iv, const void *secret,
1192 ptls_iovec_t hash_value, const char *label_prefix)
1193 {
1194 return ptls_hkdf_expand_label(algo, key, key_size, ptls_iovec_init(secret, algo->digest_size), is_iv ? "iv" : "key", hash_value,
1195 label_prefix);
1196 }
1197
setup_traffic_protection(ptls_t * tls,int is_enc,const char * secret_label,size_t epoch,int skip_notify)1198 static int setup_traffic_protection(ptls_t *tls, int is_enc, const char *secret_label, size_t epoch, int skip_notify)
1199 {
1200 static const char *log_labels[2][4] = {
1201 {NULL, "CLIENT_EARLY_TRAFFIC_SECRET", "CLIENT_HANDSHAKE_TRAFFIC_SECRET", "CLIENT_TRAFFIC_SECRET_0"},
1202 {NULL, NULL, "SERVER_HANDSHAKE_TRAFFIC_SECRET", "SERVER_TRAFFIC_SECRET_0"}};
1203 struct st_ptls_traffic_protection_t *ctx = is_enc ? &tls->traffic_protection.enc : &tls->traffic_protection.dec;
1204
1205 if (secret_label != NULL) {
1206 int ret;
1207 if ((ret = derive_secret(tls->key_schedule, ctx->secret, secret_label)) != 0)
1208 return ret;
1209 }
1210
1211 ctx->epoch = epoch;
1212
1213 /* special path for applications having their own record layer */
1214 if (tls->ctx->update_traffic_key != NULL) {
1215 if (skip_notify)
1216 return 0;
1217 return tls->ctx->update_traffic_key->cb(tls->ctx->update_traffic_key, tls, is_enc, epoch, ctx->secret);
1218 }
1219
1220 if (ctx->aead != NULL)
1221 ptls_aead_free(ctx->aead);
1222 if ((ctx->aead = ptls_aead_new(tls->cipher_suite->aead, tls->cipher_suite->hash, is_enc, ctx->secret,
1223 tls->ctx->hkdf_label_prefix__obsolete)) == NULL)
1224 return PTLS_ERROR_NO_MEMORY; /* TODO obtain error from ptls_aead_new */
1225 ctx->seq = 0;
1226
1227 log_secret(tls, log_labels[ptls_is_server(tls) == is_enc][epoch],
1228 ptls_iovec_init(ctx->secret, tls->key_schedule->hashes[0].algo->digest_size));
1229 PTLS_DEBUGF("[%s] %02x%02x,%02x%02x\n", log_labels[ptls_is_server(tls)][epoch], (unsigned)ctx->secret[0],
1230 (unsigned)ctx->secret[1], (unsigned)ctx->aead->static_iv[0], (unsigned)ctx->aead->static_iv[1]);
1231
1232 return 0;
1233 }
1234
commission_handshake_secret(ptls_t * tls)1235 static int commission_handshake_secret(ptls_t *tls)
1236 {
1237 int is_enc = !ptls_is_server(tls);
1238
1239 assert(tls->pending_handshake_secret != NULL);
1240 memcpy((is_enc ? &tls->traffic_protection.enc : &tls->traffic_protection.dec)->secret, tls->pending_handshake_secret,
1241 PTLS_MAX_DIGEST_SIZE);
1242 ptls_clear_memory(tls->pending_handshake_secret, PTLS_MAX_DIGEST_SIZE);
1243 free(tls->pending_handshake_secret);
1244 tls->pending_handshake_secret = NULL;
1245
1246 return setup_traffic_protection(tls, is_enc, NULL, 2, 1);
1247 }
1248
log_client_random(ptls_t * tls)1249 static void log_client_random(ptls_t *tls)
1250 {
1251 PTLS_PROBE(CLIENT_RANDOM, tls,
1252 ptls_hexdump(alloca(sizeof(tls->client_random) * 2 + 1), tls->client_random, sizeof(tls->client_random)));
1253 }
1254
1255 #define SESSION_IDENTIFIER_MAGIC "ptls0001" /* the number should be changed upon incompatible format change */
1256 #define SESSION_IDENTIFIER_MAGIC_SIZE (sizeof(SESSION_IDENTIFIER_MAGIC) - 1)
1257
encode_session_identifier(ptls_context_t * ctx,ptls_buffer_t * buf,uint32_t ticket_age_add,ptls_iovec_t ticket_nonce,ptls_key_schedule_t * sched,const char * server_name,uint16_t key_exchange_id,uint16_t csid,const char * negotiated_protocol)1258 static int encode_session_identifier(ptls_context_t *ctx, ptls_buffer_t *buf, uint32_t ticket_age_add, ptls_iovec_t ticket_nonce,
1259 ptls_key_schedule_t *sched, const char *server_name, uint16_t key_exchange_id, uint16_t csid,
1260 const char *negotiated_protocol)
1261 {
1262 int ret = 0;
1263
1264 ptls_buffer_push_block(buf, 2, {
1265 /* format id */
1266 ptls_buffer_pushv(buf, SESSION_IDENTIFIER_MAGIC, SESSION_IDENTIFIER_MAGIC_SIZE);
1267 /* date */
1268 ptls_buffer_push64(buf, ctx->get_time->cb(ctx->get_time));
1269 /* resumption master secret */
1270 ptls_buffer_push_block(buf, 2, {
1271 if ((ret = ptls_buffer_reserve(buf, sched->hashes[0].algo->digest_size)) != 0)
1272 goto Exit;
1273 if ((ret = derive_resumption_secret(sched, buf->base + buf->off, ticket_nonce)) != 0)
1274 goto Exit;
1275 buf->off += sched->hashes[0].algo->digest_size;
1276 });
1277 /* key-exchange */
1278 ptls_buffer_push16(buf, key_exchange_id);
1279 /* cipher-suite */
1280 ptls_buffer_push16(buf, csid);
1281 /* ticket_age_add */
1282 ptls_buffer_push32(buf, ticket_age_add);
1283 /* server-name */
1284 ptls_buffer_push_block(buf, 2, {
1285 if (server_name != NULL)
1286 ptls_buffer_pushv(buf, server_name, strlen(server_name));
1287 });
1288 /* alpn */
1289 ptls_buffer_push_block(buf, 1, {
1290 if (negotiated_protocol != NULL)
1291 ptls_buffer_pushv(buf, negotiated_protocol, strlen(negotiated_protocol));
1292 });
1293 });
1294
1295 Exit:
1296 return ret;
1297 }
1298
decode_session_identifier(uint64_t * issued_at,ptls_iovec_t * psk,uint32_t * ticket_age_add,ptls_iovec_t * server_name,uint16_t * key_exchange_id,uint16_t * csid,ptls_iovec_t * negotiated_protocol,const uint8_t * src,const uint8_t * const end)1299 int decode_session_identifier(uint64_t *issued_at, ptls_iovec_t *psk, uint32_t *ticket_age_add, ptls_iovec_t *server_name,
1300 uint16_t *key_exchange_id, uint16_t *csid, ptls_iovec_t *negotiated_protocol, const uint8_t *src,
1301 const uint8_t *const end)
1302 {
1303 int ret = 0;
1304
1305 ptls_decode_block(src, end, 2, {
1306 if (end - src < SESSION_IDENTIFIER_MAGIC_SIZE ||
1307 memcmp(src, SESSION_IDENTIFIER_MAGIC, SESSION_IDENTIFIER_MAGIC_SIZE) != 0) {
1308 ret = PTLS_ALERT_DECODE_ERROR;
1309 goto Exit;
1310 }
1311 src += SESSION_IDENTIFIER_MAGIC_SIZE;
1312 if ((ret = ptls_decode64(issued_at, &src, end)) != 0)
1313 goto Exit;
1314 ptls_decode_open_block(src, end, 2, {
1315 *psk = ptls_iovec_init(src, end - src);
1316 src = end;
1317 });
1318 if ((ret = ptls_decode16(key_exchange_id, &src, end)) != 0)
1319 goto Exit;
1320 if ((ret = ptls_decode16(csid, &src, end)) != 0)
1321 goto Exit;
1322 if ((ret = ptls_decode32(ticket_age_add, &src, end)) != 0)
1323 goto Exit;
1324 ptls_decode_open_block(src, end, 2, {
1325 *server_name = ptls_iovec_init(src, end - src);
1326 src = end;
1327 });
1328 ptls_decode_open_block(src, end, 1, {
1329 *negotiated_protocol = ptls_iovec_init(src, end - src);
1330 src = end;
1331 });
1332 });
1333
1334 Exit:
1335 return ret;
1336 }
1337
build_certificate_verify_signdata(uint8_t * data,ptls_key_schedule_t * sched,const char * context_string)1338 static size_t build_certificate_verify_signdata(uint8_t *data, ptls_key_schedule_t *sched, const char *context_string)
1339 {
1340 size_t datalen = 0;
1341
1342 memset(data + datalen, 32, 64);
1343 datalen += 64;
1344 memcpy(data + datalen, context_string, strlen(context_string) + 1);
1345 datalen += strlen(context_string) + 1;
1346 sched->hashes[0].ctx->final(sched->hashes[0].ctx, data + datalen, PTLS_HASH_FINAL_MODE_SNAPSHOT);
1347 datalen += sched->hashes[0].algo->digest_size;
1348 assert(datalen <= PTLS_MAX_CERTIFICATE_VERIFY_SIGNDATA_SIZE);
1349
1350 return datalen;
1351 }
1352
calc_verify_data(void * output,ptls_key_schedule_t * sched,const void * secret)1353 static int calc_verify_data(void *output, ptls_key_schedule_t *sched, const void *secret)
1354 {
1355 ptls_hash_context_t *hmac;
1356 uint8_t digest[PTLS_MAX_DIGEST_SIZE];
1357 int ret;
1358
1359 if ((ret = hkdf_expand_label(sched->hashes[0].algo, digest, sched->hashes[0].algo->digest_size,
1360 ptls_iovec_init(secret, sched->hashes[0].algo->digest_size), "finished", ptls_iovec_init(NULL, 0),
1361 sched->hkdf_label_prefix)) != 0)
1362 return ret;
1363 if ((hmac = ptls_hmac_create(sched->hashes[0].algo, digest, sched->hashes[0].algo->digest_size)) == NULL) {
1364 ptls_clear_memory(digest, sizeof(digest));
1365 return PTLS_ERROR_NO_MEMORY;
1366 }
1367
1368 sched->hashes[0].ctx->final(sched->hashes[0].ctx, digest, PTLS_HASH_FINAL_MODE_SNAPSHOT);
1369 PTLS_DEBUGF("%s: %02x%02x,%02x%02x\n", __FUNCTION__, ((uint8_t *)secret)[0], ((uint8_t *)secret)[1], digest[0], digest[1]);
1370 hmac->update(hmac, digest, sched->hashes[0].algo->digest_size);
1371 ptls_clear_memory(digest, sizeof(digest));
1372 hmac->final(hmac, output, PTLS_HASH_FINAL_MODE_FREE);
1373
1374 return 0;
1375 }
1376
verify_finished(ptls_t * tls,ptls_iovec_t message)1377 static int verify_finished(ptls_t *tls, ptls_iovec_t message)
1378 {
1379 uint8_t verify_data[PTLS_MAX_DIGEST_SIZE];
1380 int ret;
1381
1382 if (PTLS_HANDSHAKE_HEADER_SIZE + tls->key_schedule->hashes[0].algo->digest_size != message.len) {
1383 ret = PTLS_ALERT_DECODE_ERROR;
1384 goto Exit;
1385 }
1386
1387 if ((ret = calc_verify_data(verify_data, tls->key_schedule, tls->traffic_protection.dec.secret)) != 0)
1388 goto Exit;
1389 if (!ptls_mem_equal(message.base + PTLS_HANDSHAKE_HEADER_SIZE, verify_data, tls->key_schedule->hashes[0].algo->digest_size)) {
1390 ret = PTLS_ALERT_HANDSHAKE_FAILURE;
1391 goto Exit;
1392 }
1393
1394 Exit:
1395 ptls_clear_memory(verify_data, sizeof(verify_data));
1396 return ret;
1397 }
1398
send_finished(ptls_t * tls,ptls_message_emitter_t * emitter)1399 static int send_finished(ptls_t *tls, ptls_message_emitter_t *emitter)
1400 {
1401 int ret;
1402
1403 ptls_push_message(emitter, tls->key_schedule, PTLS_HANDSHAKE_TYPE_FINISHED, {
1404 if ((ret = ptls_buffer_reserve(emitter->buf, tls->key_schedule->hashes[0].algo->digest_size)) != 0)
1405 goto Exit;
1406 if ((ret = calc_verify_data(emitter->buf->base + emitter->buf->off, tls->key_schedule,
1407 tls->traffic_protection.enc.secret)) != 0)
1408 goto Exit;
1409 emitter->buf->off += tls->key_schedule->hashes[0].algo->digest_size;
1410 });
1411
1412 Exit:
1413 return ret;
1414 }
1415
send_session_ticket(ptls_t * tls,ptls_message_emitter_t * emitter)1416 static int send_session_ticket(ptls_t *tls, ptls_message_emitter_t *emitter)
1417 {
1418 ptls_hash_context_t *msghash_backup = tls->key_schedule->hashes[0].ctx->clone_(tls->key_schedule->hashes[0].ctx);
1419 ptls_buffer_t session_id;
1420 char session_id_smallbuf[128];
1421 uint32_t ticket_age_add;
1422 int ret = 0;
1423
1424 assert(tls->ctx->ticket_lifetime != 0);
1425 assert(tls->ctx->encrypt_ticket != NULL);
1426
1427 { /* calculate verify-data that will be sent by the client */
1428 size_t orig_off = emitter->buf->off;
1429 if (tls->pending_handshake_secret != NULL && !tls->ctx->omit_end_of_early_data) {
1430 assert(tls->state == PTLS_STATE_SERVER_EXPECT_END_OF_EARLY_DATA);
1431 ptls_buffer_push_message_body(emitter->buf, tls->key_schedule, PTLS_HANDSHAKE_TYPE_END_OF_EARLY_DATA, {});
1432 emitter->buf->off = orig_off;
1433 }
1434 ptls_buffer_push_message_body(emitter->buf, tls->key_schedule, PTLS_HANDSHAKE_TYPE_FINISHED, {
1435 if ((ret = ptls_buffer_reserve(emitter->buf, tls->key_schedule->hashes[0].algo->digest_size)) != 0)
1436 goto Exit;
1437 if ((ret = calc_verify_data(emitter->buf->base + emitter->buf->off, tls->key_schedule,
1438 tls->pending_handshake_secret != NULL ? tls->pending_handshake_secret
1439 : tls->traffic_protection.dec.secret)) != 0)
1440 goto Exit;
1441 emitter->buf->off += tls->key_schedule->hashes[0].algo->digest_size;
1442 });
1443 emitter->buf->off = orig_off;
1444 }
1445
1446 tls->ctx->random_bytes(&ticket_age_add, sizeof(ticket_age_add));
1447
1448 /* build the raw nsk */
1449 ptls_buffer_init(&session_id, session_id_smallbuf, sizeof(session_id_smallbuf));
1450 ret = encode_session_identifier(tls->ctx, &session_id, ticket_age_add, ptls_iovec_init(NULL, 0), tls->key_schedule,
1451 tls->server_name, tls->key_share->id, tls->cipher_suite->id, tls->negotiated_protocol);
1452 if (ret != 0)
1453 goto Exit;
1454
1455 /* encrypt and send */
1456 ptls_push_message(emitter, tls->key_schedule, PTLS_HANDSHAKE_TYPE_NEW_SESSION_TICKET, {
1457 ptls_buffer_push32(emitter->buf, tls->ctx->ticket_lifetime);
1458 ptls_buffer_push32(emitter->buf, ticket_age_add);
1459 ptls_buffer_push_block(emitter->buf, 1, {});
1460 ptls_buffer_push_block(emitter->buf, 2, {
1461 if ((ret = tls->ctx->encrypt_ticket->cb(tls->ctx->encrypt_ticket, tls, 1, emitter->buf,
1462 ptls_iovec_init(session_id.base, session_id.off))) != 0)
1463 goto Exit;
1464 });
1465 ptls_buffer_push_block(emitter->buf, 2, {
1466 if (tls->ctx->max_early_data_size != 0)
1467 buffer_push_extension(emitter->buf, PTLS_EXTENSION_TYPE_EARLY_DATA,
1468 { ptls_buffer_push32(emitter->buf, tls->ctx->max_early_data_size); });
1469 });
1470 });
1471
1472 Exit:
1473 ptls_buffer_dispose(&session_id);
1474
1475 /* restore handshake state */
1476 tls->key_schedule->hashes[0].ctx->final(tls->key_schedule->hashes[0].ctx, NULL, PTLS_HASH_FINAL_MODE_FREE);
1477 tls->key_schedule->hashes[0].ctx = msghash_backup;
1478
1479 return ret;
1480 }
1481
push_change_cipher_spec(ptls_t * tls,ptls_message_emitter_t * emitter)1482 static int push_change_cipher_spec(ptls_t *tls, ptls_message_emitter_t *emitter)
1483 {
1484 int ret;
1485
1486 /* check if we are requested to (or still need to) */
1487 if (!tls->send_change_cipher_spec) {
1488 ret = 0;
1489 goto Exit;
1490 }
1491
1492 /* CCS is a record, can only be sent when using a record-based protocol. */
1493 if (emitter->begin_message != begin_record_message) {
1494 ret = PTLS_ALERT_UNEXPECTED_MESSAGE;
1495 goto Exit;
1496 }
1497
1498 /* emit CCS */
1499 buffer_push_record(emitter->buf, PTLS_CONTENT_TYPE_CHANGE_CIPHER_SPEC, { ptls_buffer_push(emitter->buf, 1); });
1500
1501 tls->send_change_cipher_spec = 0;
1502 ret = 0;
1503 Exit:
1504 return ret;
1505 }
1506
push_additional_extensions(ptls_handshake_properties_t * properties,ptls_buffer_t * sendbuf)1507 static int push_additional_extensions(ptls_handshake_properties_t *properties, ptls_buffer_t *sendbuf)
1508 {
1509 int ret;
1510
1511 if (properties != NULL && properties->additional_extensions != NULL) {
1512 ptls_raw_extension_t *ext;
1513 for (ext = properties->additional_extensions; ext->type != UINT16_MAX; ++ext) {
1514 buffer_push_extension(sendbuf, ext->type, { ptls_buffer_pushv(sendbuf, ext->data.base, ext->data.len); });
1515 }
1516 }
1517 ret = 0;
1518 Exit:
1519 return ret;
1520 }
1521
push_signature_algorithms(ptls_verify_certificate_t * vc,ptls_buffer_t * sendbuf)1522 static int push_signature_algorithms(ptls_verify_certificate_t *vc, ptls_buffer_t *sendbuf)
1523 {
1524 /* The list sent when verify callback is not registered */
1525 static const uint16_t default_algos[] = {PTLS_SIGNATURE_RSA_PSS_RSAE_SHA256, PTLS_SIGNATURE_ECDSA_SECP256R1_SHA256,
1526 PTLS_SIGNATURE_RSA_PKCS1_SHA256, PTLS_SIGNATURE_RSA_PKCS1_SHA1, UINT16_MAX};
1527 int ret;
1528
1529 ptls_buffer_push_block(sendbuf, 2, {
1530 for (const uint16_t *p = vc != NULL ? vc->algos : default_algos; *p != UINT16_MAX; ++p)
1531 ptls_buffer_push16(sendbuf, *p);
1532 });
1533
1534 ret = 0;
1535 Exit:
1536 return ret;
1537 }
1538
decode_signature_algorithms(struct st_ptls_signature_algorithms_t * sa,const uint8_t ** src,const uint8_t * end)1539 static int decode_signature_algorithms(struct st_ptls_signature_algorithms_t *sa, const uint8_t **src, const uint8_t *end)
1540 {
1541 int ret;
1542
1543 ptls_decode_block(*src, end, 2, {
1544 do {
1545 uint16_t id;
1546 if ((ret = ptls_decode16(&id, src, end)) != 0)
1547 goto Exit;
1548 if (sa->count < PTLS_ELEMENTSOF(sa->list))
1549 sa->list[sa->count++] = id;
1550 } while (*src != end);
1551 });
1552
1553 ret = 0;
1554 Exit:
1555 return ret;
1556 }
1557
create_sha256_context(ptls_context_t * ctx)1558 static ptls_hash_context_t *create_sha256_context(ptls_context_t *ctx)
1559 {
1560 ptls_cipher_suite_t **cs;
1561
1562 for (cs = ctx->cipher_suites; *cs != NULL; ++cs) {
1563 switch ((*cs)->id) {
1564 case PTLS_CIPHER_SUITE_AES_128_GCM_SHA256:
1565 case PTLS_CIPHER_SUITE_CHACHA20_POLY1305_SHA256:
1566 return (*cs)->hash->create();
1567 }
1568 }
1569
1570 return NULL;
1571 }
1572
select_cipher(ptls_cipher_suite_t ** selected,ptls_cipher_suite_t ** candidates,const uint8_t * src,const uint8_t * const end,int server_preference)1573 static int select_cipher(ptls_cipher_suite_t **selected, ptls_cipher_suite_t **candidates, const uint8_t *src,
1574 const uint8_t *const end, int server_preference)
1575 {
1576 size_t found_index = SIZE_MAX;
1577 int ret;
1578
1579 while (src != end) {
1580 uint16_t id;
1581 if ((ret = ptls_decode16(&id, &src, end)) != 0)
1582 goto Exit;
1583 for (size_t i = 0; candidates[i] != NULL; ++i) {
1584 if (candidates[i]->id == id) {
1585 if (server_preference) {
1586 /* preserve smallest matching index, and proceed to the next input */
1587 if (i < found_index) {
1588 found_index = i;
1589 break;
1590 }
1591 } else {
1592 /* return the pointer matching to the first input that can be used */
1593 *selected = candidates[i];
1594 goto Exit;
1595 }
1596 }
1597 }
1598 }
1599 if (found_index != SIZE_MAX) {
1600 *selected = candidates[found_index];
1601 ret = 0;
1602 } else {
1603 ret = PTLS_ALERT_HANDSHAKE_FAILURE;
1604 }
1605
1606 Exit:
1607 return ret;
1608 }
1609
push_key_share_entry(ptls_buffer_t * buf,uint16_t group,ptls_iovec_t pubkey)1610 static int push_key_share_entry(ptls_buffer_t *buf, uint16_t group, ptls_iovec_t pubkey)
1611 {
1612 int ret;
1613
1614 ptls_buffer_push16(buf, group);
1615 ptls_buffer_push_block(buf, 2, { ptls_buffer_pushv(buf, pubkey.base, pubkey.len); });
1616 ret = 0;
1617 Exit:
1618 return ret;
1619 }
1620
decode_key_share_entry(uint16_t * group,ptls_iovec_t * key_exchange,const uint8_t ** src,const uint8_t * const end)1621 static int decode_key_share_entry(uint16_t *group, ptls_iovec_t *key_exchange, const uint8_t **src, const uint8_t *const end)
1622 {
1623 int ret;
1624
1625 if ((ret = ptls_decode16(group, src, end)) != 0)
1626 goto Exit;
1627 ptls_decode_open_block(*src, end, 2, {
1628 *key_exchange = ptls_iovec_init(*src, end - *src);
1629 *src = end;
1630 });
1631
1632 Exit:
1633 return ret;
1634 }
1635
select_key_share(ptls_key_exchange_algorithm_t ** selected,ptls_iovec_t * peer_key,ptls_key_exchange_algorithm_t ** candidates,const uint8_t ** src,const uint8_t * const end,int expect_one)1636 static int select_key_share(ptls_key_exchange_algorithm_t **selected, ptls_iovec_t *peer_key,
1637 ptls_key_exchange_algorithm_t **candidates, const uint8_t **src, const uint8_t *const end,
1638 int expect_one)
1639 {
1640 int ret;
1641
1642 *selected = NULL;
1643
1644 if (expect_one && *src == end) {
1645 ret = PTLS_ALERT_ILLEGAL_PARAMETER;
1646 goto Exit;
1647 }
1648
1649 while (*src != end) {
1650 uint16_t group;
1651 ptls_iovec_t key;
1652 if ((ret = decode_key_share_entry(&group, &key, src, end)) != 0)
1653 goto Exit;
1654 ptls_key_exchange_algorithm_t **c = candidates;
1655 for (; *c != NULL; ++c) {
1656 if (*selected == NULL && (*c)->id == group) {
1657 *selected = *c;
1658 *peer_key = key;
1659 }
1660 }
1661 if (expect_one) {
1662 ret = *selected != NULL ? 0 : PTLS_ALERT_ILLEGAL_PARAMETER;
1663 goto Exit;
1664 }
1665 }
1666
1667 ret = 0;
1668
1669 Exit:
1670 return ret;
1671 }
1672
emit_server_name_extension(ptls_buffer_t * buf,const char * server_name)1673 static int emit_server_name_extension(ptls_buffer_t *buf, const char *server_name)
1674 {
1675 int ret;
1676
1677 ptls_buffer_push_block(buf, 2, {
1678 ptls_buffer_push(buf, PTLS_SERVER_NAME_TYPE_HOSTNAME);
1679 ptls_buffer_push_block(buf, 2, { ptls_buffer_pushv(buf, server_name, strlen(server_name)); });
1680 });
1681
1682 ret = 0;
1683 Exit:
1684 return ret;
1685 }
1686
parse_esni_keys(ptls_context_t * ctx,uint16_t * esni_version,ptls_key_exchange_algorithm_t ** selected_key_share,ptls_cipher_suite_t ** selected_cipher,ptls_iovec_t * peer_key,uint16_t * padded_length,char ** published_sni,ptls_iovec_t input)1687 static int parse_esni_keys(ptls_context_t *ctx, uint16_t *esni_version, ptls_key_exchange_algorithm_t **selected_key_share,
1688 ptls_cipher_suite_t **selected_cipher, ptls_iovec_t *peer_key, uint16_t *padded_length,
1689 char **published_sni, ptls_iovec_t input)
1690 {
1691 const uint8_t *src = input.base, *const end = input.base + input.len;
1692 uint16_t version;
1693 uint64_t not_before, not_after, now;
1694 int ret = 0;
1695
1696 /* version */
1697 if ((ret = ptls_decode16(&version, &src, end)) != 0)
1698 goto Exit;
1699 if (version != PTLS_ESNI_VERSION_DRAFT03) {
1700 ret = PTLS_ALERT_DECODE_ERROR;
1701 goto Exit;
1702 }
1703
1704 { /* verify checksum */
1705 ptls_hash_context_t *hctx;
1706 uint8_t digest[PTLS_SHA256_DIGEST_SIZE];
1707 if (end - src < 4) {
1708 ret = PTLS_ALERT_DECODE_ERROR;
1709 goto Exit;
1710 }
1711 if ((hctx = create_sha256_context(ctx)) == NULL) {
1712 ret = PTLS_ERROR_LIBRARY;
1713 goto Exit;
1714 }
1715 hctx->update(hctx, input.base, src - input.base);
1716 hctx->update(hctx, "\0\0\0\0", 4);
1717 hctx->update(hctx, src + 4, end - (src + 4));
1718 hctx->final(hctx, digest, PTLS_HASH_FINAL_MODE_FREE);
1719 if (memcmp(src, digest, 4) != 0) {
1720 ret = PTLS_ALERT_DECODE_ERROR;
1721 goto Exit;
1722 }
1723 src += 4;
1724 }
1725 *esni_version = version;
1726 /* published sni */
1727 ptls_decode_open_block(src, end, 2, {
1728 size_t len = end - src;
1729 *published_sni = malloc(len + 1);
1730 if (*published_sni == NULL) {
1731 ret = PTLS_ERROR_NO_MEMORY;
1732 goto Exit;
1733 }
1734 if (len > 0) {
1735 memcpy(*published_sni, src, len);
1736 }
1737 (*published_sni)[len] = 0;
1738 src = end;
1739 });
1740 /* key-shares */
1741 ptls_decode_open_block(src, end, 2, {
1742 if ((ret = select_key_share(selected_key_share, peer_key, ctx->key_exchanges, &src, end, 0)) != 0)
1743 goto Exit;
1744 });
1745 /* cipher-suite */
1746 ptls_decode_open_block(src, end, 2, {
1747 if ((ret = select_cipher(selected_cipher, ctx->cipher_suites, src, end, ctx->server_cipher_preference)) != 0)
1748 goto Exit;
1749 src = end;
1750 });
1751 /* padded-length */
1752 if ((ret = ptls_decode16(padded_length, &src, end)) != 0)
1753 goto Exit;
1754 if (padded_length == 0)
1755 goto Exit;
1756 /* not-before, not_after */
1757 if ((ret = ptls_decode64(¬_before, &src, end)) != 0 || (ret = ptls_decode64(¬_after, &src, end)) != 0)
1758 goto Exit;
1759 /* extensions */
1760 ptls_decode_block(src, end, 2, {
1761 while (src != end) {
1762 uint16_t id;
1763 if ((ret = ptls_decode16(&id, &src, end)) != 0)
1764 goto Exit;
1765 ptls_decode_open_block(src, end, 2, { src = end; });
1766 }
1767 });
1768
1769 /* check validity period */
1770 now = ctx->get_time->cb(ctx->get_time);
1771 if (!(not_before * 1000 <= now && now <= not_after * 1000)) {
1772 ret = PTLS_ALERT_DECODE_ERROR;
1773 goto Exit;
1774 }
1775
1776 ret = 0;
1777 Exit:
1778 return ret;
1779 }
1780
create_esni_aead(ptls_aead_context_t ** aead_ctx,int is_enc,ptls_cipher_suite_t * cipher,ptls_iovec_t ecdh_secret,const uint8_t * esni_contents_hash)1781 static int create_esni_aead(ptls_aead_context_t **aead_ctx, int is_enc, ptls_cipher_suite_t *cipher, ptls_iovec_t ecdh_secret,
1782 const uint8_t *esni_contents_hash)
1783 {
1784 uint8_t aead_secret[PTLS_MAX_DIGEST_SIZE];
1785 int ret;
1786
1787 if ((ret = ptls_hkdf_extract(cipher->hash, aead_secret, ptls_iovec_init(NULL, 0), ecdh_secret)) != 0)
1788 goto Exit;
1789 if ((*aead_ctx = new_aead(cipher->aead, cipher->hash, is_enc, aead_secret,
1790 ptls_iovec_init(esni_contents_hash, cipher->hash->digest_size), "tls13 esni ")) == NULL) {
1791 ret = PTLS_ERROR_NO_MEMORY;
1792 goto Exit;
1793 }
1794
1795 ret = 0;
1796 Exit:
1797 ptls_clear_memory(aead_secret, sizeof(aead_secret));
1798 return ret;
1799 }
1800
build_esni_contents_hash(ptls_hash_algorithm_t * hash,uint8_t * digest,const uint8_t * record_digest,uint16_t group,ptls_iovec_t pubkey,const uint8_t * client_random)1801 static int build_esni_contents_hash(ptls_hash_algorithm_t *hash, uint8_t *digest, const uint8_t *record_digest, uint16_t group,
1802 ptls_iovec_t pubkey, const uint8_t *client_random)
1803 {
1804 ptls_buffer_t buf;
1805 uint8_t smallbuf[256];
1806 int ret;
1807
1808 /* build ESNIContents */
1809 ptls_buffer_init(&buf, smallbuf, sizeof(smallbuf));
1810 ptls_buffer_push_block(&buf, 2, { ptls_buffer_pushv(&buf, record_digest, hash->digest_size); });
1811 if ((ret = push_key_share_entry(&buf, group, pubkey)) != 0)
1812 goto Exit;
1813 ptls_buffer_pushv(&buf, client_random, PTLS_HELLO_RANDOM_SIZE);
1814
1815 /* calculate digest */
1816 if ((ret = ptls_calc_hash(hash, digest, buf.base, buf.off)) != 0)
1817 goto Exit;
1818
1819 ret = 0;
1820 Exit:
1821 ptls_buffer_dispose(&buf);
1822 return ret;
1823 }
1824
free_esni_secret(ptls_esni_secret_t ** esni,int is_server)1825 static void free_esni_secret(ptls_esni_secret_t **esni, int is_server)
1826 {
1827 assert(*esni != NULL);
1828 if ((*esni)->secret.base != NULL) {
1829 ptls_clear_memory((*esni)->secret.base, (*esni)->secret.len);
1830 free((*esni)->secret.base);
1831 }
1832 if (!is_server)
1833 free((*esni)->client.pubkey.base);
1834 ptls_clear_memory((*esni), sizeof(**esni));
1835 free(*esni);
1836 *esni = NULL;
1837 }
1838
client_setup_esni(ptls_context_t * ctx,ptls_esni_secret_t ** esni,ptls_iovec_t esni_keys,char ** published_sni,const uint8_t * client_random)1839 static int client_setup_esni(ptls_context_t *ctx, ptls_esni_secret_t **esni, ptls_iovec_t esni_keys, char **published_sni,
1840 const uint8_t *client_random)
1841 {
1842 ptls_iovec_t peer_key;
1843 int ret;
1844
1845 if ((*esni = malloc(sizeof(**esni))) == NULL)
1846 return PTLS_ERROR_NO_MEMORY;
1847 memset(*esni, 0, sizeof(**esni));
1848
1849 /* parse ESNI_Keys (and return success while keeping *esni NULL) */
1850 if (parse_esni_keys(ctx, &(*esni)->version, &(*esni)->client.key_share, &(*esni)->client.cipher, &peer_key,
1851 &(*esni)->client.padded_length, published_sni, esni_keys) != 0) {
1852 free(*esni);
1853 *esni = NULL;
1854 return 0;
1855 }
1856
1857 ctx->random_bytes((*esni)->nonce, sizeof((*esni)->nonce));
1858
1859 /* calc record digest */
1860 if ((ret = ptls_calc_hash((*esni)->client.cipher->hash, (*esni)->client.record_digest, esni_keys.base, esni_keys.len)) != 0)
1861 goto Exit;
1862 /* derive ECDH secret */
1863 if ((ret = (*esni)->client.key_share->exchange((*esni)->client.key_share, &(*esni)->client.pubkey, &(*esni)->secret,
1864 peer_key)) != 0)
1865 goto Exit;
1866 /* calc H(ESNIContents) */
1867 if ((ret = build_esni_contents_hash((*esni)->client.cipher->hash, (*esni)->esni_contents_hash, (*esni)->client.record_digest,
1868 (*esni)->client.key_share->id, (*esni)->client.pubkey, client_random)) != 0)
1869 goto Exit;
1870
1871 ret = 0;
1872 Exit:
1873 if (ret != 0)
1874 free_esni_secret(esni, 0);
1875 return ret;
1876 }
1877
emit_esni_extension(ptls_esni_secret_t * esni,ptls_buffer_t * buf,ptls_iovec_t esni_keys,const char * server_name,size_t key_share_ch_off,size_t key_share_ch_len)1878 static int emit_esni_extension(ptls_esni_secret_t *esni, ptls_buffer_t *buf, ptls_iovec_t esni_keys, const char *server_name,
1879 size_t key_share_ch_off, size_t key_share_ch_len)
1880 {
1881 ptls_aead_context_t *aead = NULL;
1882 int ret;
1883
1884 if ((ret = create_esni_aead(&aead, 1, esni->client.cipher, esni->secret, esni->esni_contents_hash)) != 0)
1885 goto Exit;
1886
1887 /* cipher-suite id */
1888 ptls_buffer_push16(buf, esni->client.cipher->id);
1889 /* key-share */
1890 if ((ret = push_key_share_entry(buf, esni->client.key_share->id, esni->client.pubkey)) != 0)
1891 goto Exit;
1892 /* record-digest */
1893 ptls_buffer_push_block(buf, 2, { ptls_buffer_pushv(buf, esni->client.record_digest, esni->client.cipher->hash->digest_size); });
1894 /* encrypted sni */
1895 ptls_buffer_push_block(buf, 2, {
1896 size_t start_off = buf->off;
1897 /* nonce */
1898 ptls_buffer_pushv(buf, esni->nonce, PTLS_ESNI_NONCE_SIZE);
1899 /* emit server-name extension */
1900 if ((ret = emit_server_name_extension(buf, server_name)) != 0)
1901 goto Exit;
1902 /* pad */
1903 if (buf->off - start_off < (size_t)(esni->client.padded_length + PTLS_ESNI_NONCE_SIZE)) {
1904 size_t bytes_to_pad = esni->client.padded_length + PTLS_ESNI_NONCE_SIZE - (buf->off - start_off);
1905 if ((ret = ptls_buffer_reserve(buf, bytes_to_pad)) != 0)
1906 goto Exit;
1907 memset(buf->base + buf->off, 0, bytes_to_pad);
1908 buf->off += bytes_to_pad;
1909 }
1910 /* encrypt */
1911 if ((ret = ptls_buffer_reserve(buf, aead->algo->tag_size)) != 0)
1912 goto Exit;
1913 ptls_aead_encrypt(aead, buf->base + start_off, buf->base + start_off, buf->off - start_off, 0, buf->base + key_share_ch_off,
1914 key_share_ch_len);
1915 buf->off += aead->algo->tag_size;
1916 });
1917
1918 ret = 0;
1919 Exit:
1920 if (aead != NULL)
1921 ptls_aead_free(aead);
1922 return ret;
1923 }
1924
send_client_hello(ptls_t * tls,ptls_message_emitter_t * emitter,ptls_handshake_properties_t * properties,ptls_iovec_t * cookie)1925 static int send_client_hello(ptls_t *tls, ptls_message_emitter_t *emitter, ptls_handshake_properties_t *properties,
1926 ptls_iovec_t *cookie)
1927 {
1928 ptls_iovec_t resumption_secret = {NULL}, resumption_ticket;
1929 char *published_sni = NULL;
1930 uint32_t obfuscated_ticket_age = 0;
1931 size_t msghash_off;
1932 uint8_t binder_key[PTLS_MAX_DIGEST_SIZE];
1933 int ret, is_second_flight = tls->key_schedule != NULL,
1934 send_sni = tls->server_name != NULL && !ptls_server_name_is_ipaddr(tls->server_name);
1935
1936 if (properties != NULL) {
1937 /* try to use ESNI */
1938 if (!is_second_flight && send_sni && properties->client.esni_keys.base != NULL) {
1939 if ((ret = client_setup_esni(tls->ctx, &tls->esni, properties->client.esni_keys, &published_sni, tls->client_random)) !=
1940 0) {
1941 goto Exit;
1942 }
1943 if (tls->ctx->update_esni_key != NULL) {
1944 if ((ret = tls->ctx->update_esni_key->cb(tls->ctx->update_esni_key, tls, tls->esni->secret,
1945 tls->esni->client.cipher->hash, tls->esni->esni_contents_hash)) != 0)
1946 goto Exit;
1947 }
1948 }
1949 /* setup resumption-related data. If successful, resumption_secret becomes a non-zero value. */
1950 if (properties->client.session_ticket.base != NULL) {
1951 ptls_key_exchange_algorithm_t *key_share = NULL;
1952 ptls_cipher_suite_t *cipher_suite = NULL;
1953 uint32_t max_early_data_size;
1954 if (decode_stored_session_ticket(tls, &key_share, &cipher_suite, &resumption_secret, &obfuscated_ticket_age,
1955 &resumption_ticket, &max_early_data_size, properties->client.session_ticket.base,
1956 properties->client.session_ticket.base + properties->client.session_ticket.len) == 0) {
1957 tls->client.offered_psk = 1;
1958 /* key-share selected by HRR should not be overridden */
1959 if (tls->key_share == NULL)
1960 tls->key_share = key_share;
1961 tls->cipher_suite = cipher_suite;
1962 if (!is_second_flight && max_early_data_size != 0 && properties->client.max_early_data_size != NULL) {
1963 tls->client.using_early_data = 1;
1964 *properties->client.max_early_data_size = max_early_data_size;
1965 }
1966 } else {
1967 resumption_secret = ptls_iovec_init(NULL, 0);
1968 }
1969 }
1970 if (tls->client.using_early_data) {
1971 properties->client.early_data_acceptance = PTLS_EARLY_DATA_ACCEPTANCE_UNKNOWN;
1972 } else {
1973 if (properties->client.max_early_data_size != NULL)
1974 *properties->client.max_early_data_size = 0;
1975 properties->client.early_data_acceptance = PTLS_EARLY_DATA_REJECTED;
1976 }
1977 }
1978
1979 /* use the default key share if still not undetermined */
1980 if (tls->key_share == NULL && !(properties != NULL && properties->client.negotiate_before_key_exchange))
1981 tls->key_share = tls->ctx->key_exchanges[0];
1982
1983 if (!is_second_flight) {
1984 tls->key_schedule = key_schedule_new(tls->cipher_suite, tls->ctx->cipher_suites, tls->ctx->hkdf_label_prefix__obsolete);
1985 if ((ret = key_schedule_extract(tls->key_schedule, resumption_secret)) != 0)
1986 goto Exit;
1987 }
1988
1989 msghash_off = emitter->buf->off + emitter->record_header_length;
1990 ptls_push_message(emitter, NULL, PTLS_HANDSHAKE_TYPE_CLIENT_HELLO, {
1991 ptls_buffer_t *sendbuf = emitter->buf;
1992 /* legacy_version */
1993 ptls_buffer_push16(sendbuf, 0x0303);
1994 /* random_bytes */
1995 ptls_buffer_pushv(sendbuf, tls->client_random, sizeof(tls->client_random));
1996 /* lecagy_session_id */
1997 ptls_buffer_push_block(
1998 sendbuf, 1, { ptls_buffer_pushv(sendbuf, tls->client.legacy_session_id.base, tls->client.legacy_session_id.len); });
1999 /* cipher_suites */
2000 ptls_buffer_push_block(sendbuf, 2, {
2001 ptls_cipher_suite_t **cs = tls->ctx->cipher_suites;
2002 for (; *cs != NULL; ++cs)
2003 ptls_buffer_push16(sendbuf, (*cs)->id);
2004 });
2005 /* legacy_compression_methods */
2006 ptls_buffer_push_block(sendbuf, 1, { ptls_buffer_push(sendbuf, 0); });
2007 /* extensions */
2008 ptls_buffer_push_block(sendbuf, 2, {
2009 struct {
2010 size_t off;
2011 size_t len;
2012 } key_share_client_hello;
2013 buffer_push_extension(sendbuf, PTLS_EXTENSION_TYPE_KEY_SHARE, {
2014 key_share_client_hello.off = sendbuf->off;
2015 ptls_buffer_push_block(sendbuf, 2, {
2016 if (tls->key_share != NULL) {
2017 if ((ret = tls->key_share->create(tls->key_share, &tls->client.key_share_ctx)) != 0)
2018 goto Exit;
2019 if ((ret = push_key_share_entry(sendbuf, tls->key_share->id, tls->client.key_share_ctx->pubkey)) != 0)
2020 goto Exit;
2021 }
2022 });
2023 key_share_client_hello.len = sendbuf->off - key_share_client_hello.off;
2024 });
2025 if (send_sni) {
2026 if (tls->esni != NULL) {
2027 if (published_sni != NULL) {
2028 buffer_push_extension(sendbuf, PTLS_EXTENSION_TYPE_SERVER_NAME, {
2029 if ((ret = emit_server_name_extension(sendbuf, published_sni)) != 0)
2030 goto Exit;
2031 });
2032 }
2033 buffer_push_extension(sendbuf, PTLS_EXTENSION_TYPE_ENCRYPTED_SERVER_NAME, {
2034 if ((ret = emit_esni_extension(tls->esni, sendbuf, properties->client.esni_keys, tls->server_name,
2035 key_share_client_hello.off, key_share_client_hello.len)) != 0)
2036 goto Exit;
2037 });
2038 } else {
2039 buffer_push_extension(sendbuf, PTLS_EXTENSION_TYPE_SERVER_NAME, {
2040 if ((ret = emit_server_name_extension(sendbuf, tls->server_name)) != 0)
2041 goto Exit;
2042 });
2043 }
2044 }
2045 if (properties != NULL && properties->client.negotiated_protocols.count != 0) {
2046 buffer_push_extension(sendbuf, PTLS_EXTENSION_TYPE_ALPN, {
2047 ptls_buffer_push_block(sendbuf, 2, {
2048 size_t i;
2049 for (i = 0; i != properties->client.negotiated_protocols.count; ++i) {
2050 ptls_buffer_push_block(sendbuf, 1, {
2051 ptls_iovec_t p = properties->client.negotiated_protocols.list[i];
2052 ptls_buffer_pushv(sendbuf, p.base, p.len);
2053 });
2054 }
2055 });
2056 });
2057 }
2058 if (tls->ctx->decompress_certificate != NULL) {
2059 buffer_push_extension(sendbuf, PTLS_EXTENSION_TYPE_COMPRESS_CERTIFICATE, {
2060 ptls_buffer_push_block(sendbuf, 1, {
2061 const uint16_t *algo = tls->ctx->decompress_certificate->supported_algorithms;
2062 assert(*algo != UINT16_MAX);
2063 for (; *algo != UINT16_MAX; ++algo)
2064 ptls_buffer_push16(sendbuf, *algo);
2065 });
2066 });
2067 }
2068 buffer_push_extension(sendbuf, PTLS_EXTENSION_TYPE_SUPPORTED_VERSIONS, {
2069 ptls_buffer_push_block(sendbuf, 1, {
2070 size_t i;
2071 for (i = 0; i != PTLS_ELEMENTSOF(supported_versions); ++i)
2072 ptls_buffer_push16(sendbuf, supported_versions[i]);
2073 });
2074 });
2075 buffer_push_extension(sendbuf, PTLS_EXTENSION_TYPE_SIGNATURE_ALGORITHMS, {
2076 if ((ret = push_signature_algorithms(tls->ctx->verify_certificate, sendbuf)) != 0)
2077 goto Exit;
2078 });
2079 buffer_push_extension(sendbuf, PTLS_EXTENSION_TYPE_SUPPORTED_GROUPS, {
2080 ptls_key_exchange_algorithm_t **algo = tls->ctx->key_exchanges;
2081 ptls_buffer_push_block(sendbuf, 2, {
2082 for (; *algo != NULL; ++algo)
2083 ptls_buffer_push16(sendbuf, (*algo)->id);
2084 });
2085 });
2086 if (cookie != NULL && cookie->base != NULL) {
2087 buffer_push_extension(sendbuf, PTLS_EXTENSION_TYPE_COOKIE, {
2088 ptls_buffer_push_block(sendbuf, 2, { ptls_buffer_pushv(sendbuf, cookie->base, cookie->len); });
2089 });
2090 }
2091 if (tls->ctx->use_raw_public_keys) {
2092 buffer_push_extension(sendbuf, PTLS_EXTENSION_TYPE_SERVER_CERTIFICATE_TYPE, {
2093 ptls_buffer_push_block(sendbuf, 1, { ptls_buffer_push(sendbuf, PTLS_CERTIFICATE_TYPE_RAW_PUBLIC_KEY); });
2094 });
2095 }
2096 if ((ret = push_additional_extensions(properties, sendbuf)) != 0)
2097 goto Exit;
2098 if (tls->ctx->save_ticket != NULL || resumption_secret.base != NULL) {
2099 buffer_push_extension(sendbuf, PTLS_EXTENSION_TYPE_PSK_KEY_EXCHANGE_MODES, {
2100 ptls_buffer_push_block(sendbuf, 1, {
2101 if (!tls->ctx->require_dhe_on_psk)
2102 ptls_buffer_push(sendbuf, PTLS_PSK_KE_MODE_PSK);
2103 ptls_buffer_push(sendbuf, PTLS_PSK_KE_MODE_PSK_DHE);
2104 });
2105 });
2106 }
2107 if (resumption_secret.base != NULL) {
2108 if (tls->client.using_early_data && !is_second_flight)
2109 buffer_push_extension(sendbuf, PTLS_EXTENSION_TYPE_EARLY_DATA, {});
2110 /* pre-shared key "MUST be the last extension in the ClientHello" (draft-17 section 4.2.6) */
2111 buffer_push_extension(sendbuf, PTLS_EXTENSION_TYPE_PRE_SHARED_KEY, {
2112 ptls_buffer_push_block(sendbuf, 2, {
2113 ptls_buffer_push_block(sendbuf, 2,
2114 { ptls_buffer_pushv(sendbuf, resumption_ticket.base, resumption_ticket.len); });
2115 ptls_buffer_push32(sendbuf, obfuscated_ticket_age);
2116 });
2117 /* allocate space for PSK binder. the space is filled at the bottom of the function */
2118 ptls_buffer_push_block(sendbuf, 2, {
2119 ptls_buffer_push_block(sendbuf, 1, {
2120 if ((ret = ptls_buffer_reserve(sendbuf, tls->key_schedule->hashes[0].algo->digest_size)) != 0)
2121 goto Exit;
2122 sendbuf->off += tls->key_schedule->hashes[0].algo->digest_size;
2123 });
2124 });
2125 });
2126 }
2127 });
2128 });
2129
2130 /* update the message hash, filling in the PSK binder HMAC if necessary */
2131 if (resumption_secret.base != NULL) {
2132 size_t psk_binder_off = emitter->buf->off - (3 + tls->key_schedule->hashes[0].algo->digest_size);
2133 if ((ret = derive_secret_with_empty_digest(tls->key_schedule, binder_key, "res binder")) != 0)
2134 goto Exit;
2135 ptls__key_schedule_update_hash(tls->key_schedule, emitter->buf->base + msghash_off, psk_binder_off - msghash_off);
2136 msghash_off = psk_binder_off;
2137 if ((ret = calc_verify_data(emitter->buf->base + psk_binder_off + 3, tls->key_schedule, binder_key)) != 0)
2138 goto Exit;
2139 }
2140 ptls__key_schedule_update_hash(tls->key_schedule, emitter->buf->base + msghash_off, emitter->buf->off - msghash_off);
2141
2142 if (tls->client.using_early_data) {
2143 assert(!is_second_flight);
2144 if ((ret = setup_traffic_protection(tls, 1, "c e traffic", 1, 0)) != 0)
2145 goto Exit;
2146 if ((ret = push_change_cipher_spec(tls, emitter)) != 0)
2147 goto Exit;
2148 }
2149 if (resumption_secret.base != NULL && !is_second_flight) {
2150 if ((ret = derive_exporter_secret(tls, 1)) != 0)
2151 goto Exit;
2152 }
2153 tls->state = cookie == NULL ? PTLS_STATE_CLIENT_EXPECT_SERVER_HELLO : PTLS_STATE_CLIENT_EXPECT_SECOND_SERVER_HELLO;
2154 ret = PTLS_ERROR_IN_PROGRESS;
2155
2156 Exit:
2157 if (published_sni != NULL) {
2158 free(published_sni);
2159 }
2160 ptls_clear_memory(binder_key, sizeof(binder_key));
2161 return ret;
2162 }
2163
find_cipher_suite(ptls_context_t * ctx,uint16_t id)2164 static ptls_cipher_suite_t *find_cipher_suite(ptls_context_t *ctx, uint16_t id)
2165 {
2166 ptls_cipher_suite_t **cs;
2167
2168 for (cs = ctx->cipher_suites; *cs != NULL && (*cs)->id != id; ++cs)
2169 ;
2170 return *cs;
2171 }
2172
decode_server_hello(ptls_t * tls,struct st_ptls_server_hello_t * sh,const uint8_t * src,const uint8_t * const end)2173 static int decode_server_hello(ptls_t *tls, struct st_ptls_server_hello_t *sh, const uint8_t *src, const uint8_t *const end)
2174 {
2175 int ret;
2176
2177 *sh = (struct st_ptls_server_hello_t){{0}};
2178
2179 /* ignore legacy-version */
2180 if (end - src < 2) {
2181 ret = PTLS_ALERT_DECODE_ERROR;
2182 goto Exit;
2183 }
2184 src += 2;
2185
2186 /* random */
2187 if (end - src < PTLS_HELLO_RANDOM_SIZE) {
2188 ret = PTLS_ALERT_DECODE_ERROR;
2189 goto Exit;
2190 }
2191 sh->is_retry_request = memcmp(src, hello_retry_random, PTLS_HELLO_RANDOM_SIZE) == 0;
2192 src += PTLS_HELLO_RANDOM_SIZE;
2193
2194 /* legacy_session_id */
2195 ptls_decode_open_block(src, end, 1, {
2196 if (end - src > 32) {
2197 ret = PTLS_ALERT_DECODE_ERROR;
2198 goto Exit;
2199 }
2200 sh->legacy_session_id = ptls_iovec_init(src, end - src);
2201 src = end;
2202 });
2203
2204 { /* select cipher_suite */
2205 uint16_t csid;
2206 if ((ret = ptls_decode16(&csid, &src, end)) != 0)
2207 goto Exit;
2208 if ((tls->cipher_suite = find_cipher_suite(tls->ctx, csid)) == NULL) {
2209 ret = PTLS_ALERT_ILLEGAL_PARAMETER;
2210 goto Exit;
2211 }
2212 }
2213
2214 /* legacy_compression_method */
2215 if (src == end || *src++ != 0) {
2216 ret = PTLS_ALERT_ILLEGAL_PARAMETER;
2217 goto Exit;
2218 }
2219
2220 if (sh->is_retry_request)
2221 sh->retry_request.selected_group = UINT16_MAX;
2222
2223 uint16_t exttype, found_version = UINT16_MAX, selected_psk_identity = UINT16_MAX;
2224 decode_extensions(src, end, PTLS_HANDSHAKE_TYPE_SERVER_HELLO, &exttype, {
2225 if (tls->ctx->on_extension != NULL &&
2226 (ret = tls->ctx->on_extension->cb(tls->ctx->on_extension, tls, PTLS_HANDSHAKE_TYPE_SERVER_HELLO, exttype,
2227 ptls_iovec_init(src, end - src)) != 0))
2228 goto Exit;
2229 switch (exttype) {
2230 case PTLS_EXTENSION_TYPE_SUPPORTED_VERSIONS:
2231 if ((ret = ptls_decode16(&found_version, &src, end)) != 0)
2232 goto Exit;
2233 break;
2234 case PTLS_EXTENSION_TYPE_KEY_SHARE:
2235 if (sh->is_retry_request) {
2236 if ((ret = ptls_decode16(&sh->retry_request.selected_group, &src, end)) != 0)
2237 goto Exit;
2238 } else {
2239 uint16_t group;
2240 if ((ret = decode_key_share_entry(&group, &sh->peerkey, &src, end)) != 0)
2241 goto Exit;
2242 if (src != end) {
2243 ret = PTLS_ALERT_DECODE_ERROR;
2244 goto Exit;
2245 }
2246 if (tls->key_share == NULL || tls->key_share->id != group) {
2247 ret = PTLS_ALERT_ILLEGAL_PARAMETER;
2248 goto Exit;
2249 }
2250 }
2251 break;
2252 case PTLS_EXTENSION_TYPE_COOKIE:
2253 if (sh->is_retry_request) {
2254 ptls_decode_block(src, end, 2, {
2255 if (src == end) {
2256 ret = PTLS_ALERT_DECODE_ERROR;
2257 goto Exit;
2258 }
2259 sh->retry_request.cookie = ptls_iovec_init(src, end - src);
2260 src = end;
2261 });
2262 } else {
2263 ret = PTLS_ALERT_ILLEGAL_PARAMETER;
2264 goto Exit;
2265 }
2266 break;
2267 case PTLS_EXTENSION_TYPE_PRE_SHARED_KEY:
2268 if (sh->is_retry_request) {
2269 ret = PTLS_ALERT_ILLEGAL_PARAMETER;
2270 goto Exit;
2271 } else {
2272 if ((ret = ptls_decode16(&selected_psk_identity, &src, end)) != 0)
2273 goto Exit;
2274 }
2275 break;
2276 default:
2277 src = end;
2278 break;
2279 }
2280 });
2281
2282 if (!is_supported_version(found_version)) {
2283 ret = PTLS_ALERT_ILLEGAL_PARAMETER;
2284 goto Exit;
2285 }
2286 if (!sh->is_retry_request) {
2287 if (selected_psk_identity != UINT16_MAX) {
2288 if (!tls->client.offered_psk) {
2289 ret = PTLS_ALERT_ILLEGAL_PARAMETER;
2290 goto Exit;
2291 }
2292 if (selected_psk_identity != 0) {
2293 ret = PTLS_ALERT_ILLEGAL_PARAMETER;
2294 goto Exit;
2295 }
2296 tls->is_psk_handshake = 1;
2297 }
2298 if (sh->peerkey.base == NULL && !tls->is_psk_handshake) {
2299 ret = PTLS_ALERT_ILLEGAL_PARAMETER;
2300 goto Exit;
2301 }
2302 }
2303
2304 ret = 0;
2305 Exit:
2306 return ret;
2307 }
2308
handle_hello_retry_request(ptls_t * tls,ptls_message_emitter_t * emitter,struct st_ptls_server_hello_t * sh,ptls_iovec_t message,ptls_handshake_properties_t * properties)2309 static int handle_hello_retry_request(ptls_t *tls, ptls_message_emitter_t *emitter, struct st_ptls_server_hello_t *sh,
2310 ptls_iovec_t message, ptls_handshake_properties_t *properties)
2311 {
2312 int ret;
2313
2314 if (tls->client.key_share_ctx != NULL) {
2315 tls->client.key_share_ctx->on_exchange(&tls->client.key_share_ctx, 1, NULL, ptls_iovec_init(NULL, 0));
2316 tls->client.key_share_ctx = NULL;
2317 }
2318 if (tls->client.using_early_data) {
2319 /* release traffic encryption key so that 2nd CH goes out in cleartext, but keep the epoch at 1 since we've already
2320 * called derive-secret */
2321 if (tls->ctx->update_traffic_key == NULL) {
2322 assert(tls->traffic_protection.enc.aead != NULL);
2323 ptls_aead_free(tls->traffic_protection.enc.aead);
2324 tls->traffic_protection.enc.aead = NULL;
2325 }
2326 tls->client.using_early_data = 0;
2327 }
2328
2329 if (sh->retry_request.selected_group != UINT16_MAX) {
2330 /* we offer the first key_exchanges[0] as KEY_SHARE unless client.negotiate_before_key_exchange is set */
2331 ptls_key_exchange_algorithm_t **cand;
2332 for (cand = tls->ctx->key_exchanges; *cand != NULL; ++cand)
2333 if ((*cand)->id == sh->retry_request.selected_group)
2334 break;
2335 if (*cand == NULL) {
2336 ret = PTLS_ALERT_ILLEGAL_PARAMETER;
2337 goto Exit;
2338 }
2339 tls->key_share = *cand;
2340 } else if (tls->key_share != NULL) {
2341 /* retain the key-share using in first CH, if server does not specify one */
2342 } else {
2343 ret = PTLS_ALERT_ILLEGAL_PARAMETER;
2344 goto Exit;
2345 }
2346
2347 key_schedule_transform_post_ch1hash(tls->key_schedule);
2348 ptls__key_schedule_update_hash(tls->key_schedule, message.base, message.len);
2349 ret = send_client_hello(tls, emitter, properties, &sh->retry_request.cookie);
2350
2351 Exit:
2352 return ret;
2353 }
2354
client_handle_hello(ptls_t * tls,ptls_message_emitter_t * emitter,ptls_iovec_t message,ptls_handshake_properties_t * properties)2355 static int client_handle_hello(ptls_t *tls, ptls_message_emitter_t *emitter, ptls_iovec_t message,
2356 ptls_handshake_properties_t *properties)
2357 {
2358 struct st_ptls_server_hello_t sh;
2359 ptls_iovec_t ecdh_secret = {NULL};
2360 int ret;
2361
2362 if ((ret = decode_server_hello(tls, &sh, message.base + PTLS_HANDSHAKE_HEADER_SIZE, message.base + message.len)) != 0)
2363 goto Exit;
2364 if (!(sh.legacy_session_id.len == tls->client.legacy_session_id.len &&
2365 ptls_mem_equal(sh.legacy_session_id.base, tls->client.legacy_session_id.base, tls->client.legacy_session_id.len))) {
2366 ret = PTLS_ALERT_ILLEGAL_PARAMETER;
2367 goto Exit;
2368 }
2369
2370 if (sh.is_retry_request) {
2371 if ((ret = key_schedule_select_one(tls->key_schedule, tls->cipher_suite, 0)) != 0)
2372 goto Exit;
2373 return handle_hello_retry_request(tls, emitter, &sh, message, properties);
2374 }
2375
2376 if ((ret = key_schedule_select_one(tls->key_schedule, tls->cipher_suite, tls->client.offered_psk && !tls->is_psk_handshake)) !=
2377 0)
2378 goto Exit;
2379
2380 if (sh.peerkey.base != NULL) {
2381 if ((ret = tls->client.key_share_ctx->on_exchange(&tls->client.key_share_ctx, 1, &ecdh_secret, sh.peerkey)) != 0)
2382 goto Exit;
2383 }
2384
2385 ptls__key_schedule_update_hash(tls->key_schedule, message.base, message.len);
2386
2387 if ((ret = key_schedule_extract(tls->key_schedule, ecdh_secret)) != 0)
2388 goto Exit;
2389 if ((ret = setup_traffic_protection(tls, 0, "s hs traffic", 2, 0)) != 0)
2390 goto Exit;
2391 if (tls->client.using_early_data) {
2392 if ((tls->pending_handshake_secret = malloc(PTLS_MAX_DIGEST_SIZE)) == NULL) {
2393 ret = PTLS_ERROR_NO_MEMORY;
2394 goto Exit;
2395 }
2396 if ((ret = derive_secret(tls->key_schedule, tls->pending_handshake_secret, "c hs traffic")) != 0)
2397 goto Exit;
2398 if (tls->ctx->update_traffic_key != NULL &&
2399 (ret = tls->ctx->update_traffic_key->cb(tls->ctx->update_traffic_key, tls, 1, 2, tls->pending_handshake_secret)) != 0)
2400 goto Exit;
2401 } else {
2402 if ((ret = setup_traffic_protection(tls, 1, "c hs traffic", 2, 0)) != 0)
2403 goto Exit;
2404 }
2405
2406 tls->state = PTLS_STATE_CLIENT_EXPECT_ENCRYPTED_EXTENSIONS;
2407 ret = PTLS_ERROR_IN_PROGRESS;
2408
2409 Exit:
2410 if (ecdh_secret.base != NULL) {
2411 ptls_clear_memory(ecdh_secret.base, ecdh_secret.len);
2412 free(ecdh_secret.base);
2413 }
2414 return ret;
2415 }
2416
should_collect_unknown_extension(ptls_t * tls,ptls_handshake_properties_t * properties,uint16_t type)2417 static int should_collect_unknown_extension(ptls_t *tls, ptls_handshake_properties_t *properties, uint16_t type)
2418 {
2419 return properties != NULL && properties->collect_extension != NULL && properties->collect_extension(tls, properties, type);
2420 }
2421
collect_unknown_extension(ptls_t * tls,uint16_t type,const uint8_t * src,const uint8_t * const end,ptls_raw_extension_t * slots)2422 static int collect_unknown_extension(ptls_t *tls, uint16_t type, const uint8_t *src, const uint8_t *const end,
2423 ptls_raw_extension_t *slots)
2424 {
2425 size_t i;
2426 for (i = 0; slots[i].type != UINT16_MAX; ++i) {
2427 assert(i < MAX_UNKNOWN_EXTENSIONS);
2428 if (slots[i].type == type)
2429 return PTLS_ALERT_ILLEGAL_PARAMETER;
2430 }
2431 if (i < MAX_UNKNOWN_EXTENSIONS) {
2432 slots[i].type = type;
2433 slots[i].data = ptls_iovec_init(src, end - src);
2434 slots[i + 1].type = UINT16_MAX;
2435 }
2436 return 0;
2437 }
2438
report_unknown_extensions(ptls_t * tls,ptls_handshake_properties_t * properties,ptls_raw_extension_t * slots)2439 static int report_unknown_extensions(ptls_t *tls, ptls_handshake_properties_t *properties, ptls_raw_extension_t *slots)
2440 {
2441 if (properties != NULL && properties->collect_extension != NULL) {
2442 assert(properties->collected_extensions != NULL);
2443 return properties->collected_extensions(tls, properties, slots);
2444 } else {
2445 return 0;
2446 }
2447 }
2448
client_handle_encrypted_extensions(ptls_t * tls,ptls_iovec_t message,ptls_handshake_properties_t * properties)2449 static int client_handle_encrypted_extensions(ptls_t *tls, ptls_iovec_t message, ptls_handshake_properties_t *properties)
2450 {
2451 const uint8_t *src = message.base + PTLS_HANDSHAKE_HEADER_SIZE, *const end = message.base + message.len, *esni_nonce = NULL;
2452 uint16_t type;
2453 static const ptls_raw_extension_t no_unknown_extensions = {UINT16_MAX};
2454 ptls_raw_extension_t *unknown_extensions = (ptls_raw_extension_t *)&no_unknown_extensions;
2455 int ret, skip_early_data = 1;
2456 uint8_t server_offered_cert_type = PTLS_CERTIFICATE_TYPE_X509;
2457
2458 decode_extensions(src, end, PTLS_HANDSHAKE_TYPE_ENCRYPTED_EXTENSIONS, &type, {
2459 if (tls->ctx->on_extension != NULL &&
2460 (ret = tls->ctx->on_extension->cb(tls->ctx->on_extension, tls, PTLS_HANDSHAKE_TYPE_ENCRYPTED_EXTENSIONS, type,
2461 ptls_iovec_init(src, end - src)) != 0))
2462 goto Exit;
2463 switch (type) {
2464 case PTLS_EXTENSION_TYPE_SERVER_NAME:
2465 if (src != end) {
2466 ret = PTLS_ALERT_DECODE_ERROR;
2467 goto Exit;
2468 }
2469 if (!(tls->server_name != NULL && !ptls_server_name_is_ipaddr(tls->server_name))) {
2470 ret = PTLS_ALERT_ILLEGAL_PARAMETER;
2471 goto Exit;
2472 }
2473 break;
2474 case PTLS_EXTENSION_TYPE_ENCRYPTED_SERVER_NAME:
2475 if (*src == PTLS_ESNI_RESPONSE_TYPE_ACCEPT) {
2476 if (end - src != PTLS_ESNI_NONCE_SIZE + 1) {
2477 ret = PTLS_ALERT_ILLEGAL_PARAMETER;
2478 goto Exit;
2479 }
2480 esni_nonce = src + 1;
2481 } else {
2482 /* TODO: provide API to parse the RETRY REQUEST response */
2483 ret = PTLS_ERROR_ESNI_RETRY;
2484 goto Exit;
2485 }
2486 break;
2487 case PTLS_EXTENSION_TYPE_ALPN:
2488 ptls_decode_block(src, end, 2, {
2489 ptls_decode_open_block(src, end, 1, {
2490 if (src == end) {
2491 ret = PTLS_ALERT_DECODE_ERROR;
2492 goto Exit;
2493 }
2494 if ((ret = ptls_set_negotiated_protocol(tls, (const char *)src, end - src)) != 0)
2495 goto Exit;
2496 src = end;
2497 });
2498 if (src != end) {
2499 ret = PTLS_ALERT_HANDSHAKE_FAILURE;
2500 goto Exit;
2501 }
2502 });
2503 break;
2504 case PTLS_EXTENSION_TYPE_EARLY_DATA:
2505 if (!tls->client.using_early_data) {
2506 ret = PTLS_ALERT_ILLEGAL_PARAMETER;
2507 goto Exit;
2508 }
2509 skip_early_data = 0;
2510 break;
2511 case PTLS_EXTENSION_TYPE_SERVER_CERTIFICATE_TYPE:
2512 if (end - src != 1) {
2513 ret = PTLS_ALERT_DECODE_ERROR;
2514 goto Exit;
2515 }
2516 server_offered_cert_type = *src;
2517 src = end;
2518 break;
2519 default:
2520 if (should_collect_unknown_extension(tls, properties, type)) {
2521 if (unknown_extensions == &no_unknown_extensions) {
2522 if ((unknown_extensions = malloc(sizeof(*unknown_extensions) * (MAX_UNKNOWN_EXTENSIONS + 1))) == NULL) {
2523 ret = PTLS_ERROR_NO_MEMORY;
2524 goto Exit;
2525 }
2526 unknown_extensions[0].type = UINT16_MAX;
2527 }
2528 if ((ret = collect_unknown_extension(tls, type, src, end, unknown_extensions)) != 0)
2529 goto Exit;
2530 }
2531 break;
2532 }
2533 src = end;
2534 });
2535
2536 if (server_offered_cert_type !=
2537 (tls->ctx->use_raw_public_keys ? PTLS_CERTIFICATE_TYPE_RAW_PUBLIC_KEY : PTLS_CERTIFICATE_TYPE_X509)) {
2538 ret = PTLS_ALERT_UNSUPPORTED_CERTIFICATE;
2539 goto Exit;
2540 }
2541
2542 if (tls->esni != NULL) {
2543 if (esni_nonce == NULL || !ptls_mem_equal(esni_nonce, tls->esni->nonce, PTLS_ESNI_NONCE_SIZE)) {
2544 ret = PTLS_ALERT_ILLEGAL_PARAMETER;
2545 goto Exit;
2546 }
2547 free_esni_secret(&tls->esni, 0);
2548 } else {
2549 if (esni_nonce != NULL) {
2550 ret = PTLS_ALERT_ILLEGAL_PARAMETER;
2551 goto Exit;
2552 }
2553 }
2554
2555 if (tls->client.using_early_data) {
2556 if (skip_early_data)
2557 tls->client.using_early_data = 0;
2558 if (properties != NULL)
2559 properties->client.early_data_acceptance = skip_early_data ? PTLS_EARLY_DATA_REJECTED : PTLS_EARLY_DATA_ACCEPTED;
2560 }
2561 if ((ret = report_unknown_extensions(tls, properties, unknown_extensions)) != 0)
2562 goto Exit;
2563
2564 ptls__key_schedule_update_hash(tls->key_schedule, message.base, message.len);
2565 tls->state =
2566 tls->is_psk_handshake ? PTLS_STATE_CLIENT_EXPECT_FINISHED : PTLS_STATE_CLIENT_EXPECT_CERTIFICATE_REQUEST_OR_CERTIFICATE;
2567 ret = PTLS_ERROR_IN_PROGRESS;
2568
2569 Exit:
2570 if (unknown_extensions != &no_unknown_extensions)
2571 free(unknown_extensions);
2572 return ret;
2573 }
2574
decode_certificate_request(ptls_t * tls,struct st_ptls_certificate_request_t * cr,const uint8_t * src,const uint8_t * const end)2575 static int decode_certificate_request(ptls_t *tls, struct st_ptls_certificate_request_t *cr, const uint8_t *src,
2576 const uint8_t *const end)
2577 {
2578 int ret;
2579 uint16_t exttype = 0;
2580
2581 /* certificate request context */
2582 ptls_decode_open_block(src, end, 1, {
2583 size_t len = end - src;
2584 if (len > 255) {
2585 ret = PTLS_ALERT_DECODE_ERROR;
2586 goto Exit;
2587 }
2588 if ((cr->context.base = malloc(len != 0 ? len : 1)) == NULL) {
2589 ret = PTLS_ERROR_NO_MEMORY;
2590 goto Exit;
2591 }
2592 cr->context.len = len;
2593 memcpy(cr->context.base, src, len);
2594 src = end;
2595 });
2596
2597 /* decode extensions */
2598 decode_extensions(src, end, PTLS_HANDSHAKE_TYPE_CERTIFICATE_REQUEST, &exttype, {
2599 if (tls->ctx->on_extension != NULL &&
2600 (ret = tls->ctx->on_extension->cb(tls->ctx->on_extension, tls, PTLS_HANDSHAKE_TYPE_CERTIFICATE_REQUEST, exttype,
2601 ptls_iovec_init(src, end - src)) != 0))
2602 goto Exit;
2603 switch (exttype) {
2604 case PTLS_EXTENSION_TYPE_SIGNATURE_ALGORITHMS:
2605 if ((ret = decode_signature_algorithms(&cr->signature_algorithms, &src, end)) != 0)
2606 goto Exit;
2607 break;
2608 }
2609 src = end;
2610 });
2611
2612 if (cr->signature_algorithms.count == 0) {
2613 ret = PTLS_ALERT_MISSING_EXTENSION;
2614 goto Exit;
2615 }
2616
2617 ret = 0;
2618 Exit:
2619 return ret;
2620 }
2621
ptls_build_certificate_message(ptls_buffer_t * buf,ptls_iovec_t context,ptls_iovec_t * certificates,size_t num_certificates,ptls_iovec_t ocsp_status)2622 int ptls_build_certificate_message(ptls_buffer_t *buf, ptls_iovec_t context, ptls_iovec_t *certificates, size_t num_certificates,
2623 ptls_iovec_t ocsp_status)
2624 {
2625 int ret;
2626
2627 ptls_buffer_push_block(buf, 1, { ptls_buffer_pushv(buf, context.base, context.len); });
2628 ptls_buffer_push_block(buf, 3, {
2629 size_t i;
2630 for (i = 0; i != num_certificates; ++i) {
2631 ptls_buffer_push_block(buf, 3, { ptls_buffer_pushv(buf, certificates[i].base, certificates[i].len); });
2632 ptls_buffer_push_block(buf, 2, {
2633 if (i == 0 && ocsp_status.len != 0) {
2634 buffer_push_extension(buf, PTLS_EXTENSION_TYPE_STATUS_REQUEST, {
2635 ptls_buffer_push(buf, 1); /* status_type == ocsp */
2636 ptls_buffer_push_block(buf, 3, { ptls_buffer_pushv(buf, ocsp_status.base, ocsp_status.len); });
2637 });
2638 }
2639 });
2640 }
2641 });
2642
2643 ret = 0;
2644 Exit:
2645 return ret;
2646 }
2647
default_emit_certificate_cb(ptls_emit_certificate_t * _self,ptls_t * tls,ptls_message_emitter_t * emitter,ptls_key_schedule_t * key_sched,ptls_iovec_t context,int push_status_request,const uint16_t * compress_algos,size_t num_compress_algos)2648 static int default_emit_certificate_cb(ptls_emit_certificate_t *_self, ptls_t *tls, ptls_message_emitter_t *emitter,
2649 ptls_key_schedule_t *key_sched, ptls_iovec_t context, int push_status_request,
2650 const uint16_t *compress_algos, size_t num_compress_algos)
2651 {
2652 int ret;
2653
2654 ptls_push_message(emitter, key_sched, PTLS_HANDSHAKE_TYPE_CERTIFICATE, {
2655 if ((ret = ptls_build_certificate_message(emitter->buf, context, tls->ctx->certificates.list, tls->ctx->certificates.count,
2656 ptls_iovec_init(NULL, 0))) != 0)
2657 goto Exit;
2658 });
2659
2660 ret = 0;
2661 Exit:
2662 return ret;
2663 }
2664
send_certificate_and_certificate_verify(ptls_t * tls,ptls_message_emitter_t * emitter,struct st_ptls_signature_algorithms_t * signature_algorithms,ptls_iovec_t context,const char * context_string,int push_status_request,const uint16_t * compress_algos,size_t num_compress_algos)2665 static int send_certificate_and_certificate_verify(ptls_t *tls, ptls_message_emitter_t *emitter,
2666 struct st_ptls_signature_algorithms_t *signature_algorithms,
2667 ptls_iovec_t context, const char *context_string, int push_status_request,
2668 const uint16_t *compress_algos, size_t num_compress_algos)
2669 {
2670 int ret;
2671
2672 if (signature_algorithms->count == 0) {
2673 ret = PTLS_ALERT_MISSING_EXTENSION;
2674 goto Exit;
2675 }
2676
2677 { /* send Certificate (or the equivalent) */
2678 static ptls_emit_certificate_t default_emit_certificate = {default_emit_certificate_cb};
2679 ptls_emit_certificate_t *emit_certificate =
2680 tls->ctx->emit_certificate != NULL ? tls->ctx->emit_certificate : &default_emit_certificate;
2681 Redo:
2682 if ((ret = emit_certificate->cb(emit_certificate, tls, emitter, tls->key_schedule, context, push_status_request,
2683 compress_algos, num_compress_algos)) != 0) {
2684 if (ret == PTLS_ERROR_DELEGATE) {
2685 assert(emit_certificate != &default_emit_certificate);
2686 emit_certificate = &default_emit_certificate;
2687 goto Redo;
2688 }
2689 goto Exit;
2690 }
2691 }
2692
2693 /* build and send CertificateVerify */
2694 if (tls->ctx->sign_certificate != NULL) {
2695 ptls_push_message(emitter, tls->key_schedule, PTLS_HANDSHAKE_TYPE_CERTIFICATE_VERIFY, {
2696 ptls_buffer_t *sendbuf = emitter->buf;
2697 size_t algo_off = sendbuf->off;
2698 ptls_buffer_push16(sendbuf, 0); /* filled in later */
2699 ptls_buffer_push_block(sendbuf, 2, {
2700 uint16_t algo;
2701 uint8_t data[PTLS_MAX_CERTIFICATE_VERIFY_SIGNDATA_SIZE];
2702 size_t datalen = build_certificate_verify_signdata(data, tls->key_schedule, context_string);
2703 if ((ret = tls->ctx->sign_certificate->cb(tls->ctx->sign_certificate, tls, &algo, sendbuf,
2704 ptls_iovec_init(data, datalen), signature_algorithms->list,
2705 signature_algorithms->count)) != 0) {
2706 goto Exit;
2707 }
2708 sendbuf->base[algo_off] = (uint8_t)(algo >> 8);
2709 sendbuf->base[algo_off + 1] = (uint8_t)algo;
2710 });
2711 });
2712 }
2713
2714 Exit:
2715 return ret;
2716 }
2717
client_handle_certificate_request(ptls_t * tls,ptls_iovec_t message,ptls_handshake_properties_t * properties)2718 static int client_handle_certificate_request(ptls_t *tls, ptls_iovec_t message, ptls_handshake_properties_t *properties)
2719 {
2720 const uint8_t *src = message.base + PTLS_HANDSHAKE_HEADER_SIZE, *const end = message.base + message.len;
2721 int ret = 0;
2722
2723 if ((ret = decode_certificate_request(tls, &tls->client.certificate_request, src, end)) != 0)
2724 return ret;
2725
2726 /* This field SHALL be zero length unless used for the post-handshake authentication exchanges (section 4.3.2) */
2727 if (tls->client.certificate_request.context.len != 0)
2728 return PTLS_ALERT_ILLEGAL_PARAMETER;
2729
2730 tls->state = PTLS_STATE_CLIENT_EXPECT_CERTIFICATE;
2731 ptls__key_schedule_update_hash(tls->key_schedule, message.base, message.len);
2732
2733 return PTLS_ERROR_IN_PROGRESS;
2734 }
2735
handle_certificate(ptls_t * tls,const uint8_t * src,const uint8_t * end,int * got_certs)2736 static int handle_certificate(ptls_t *tls, const uint8_t *src, const uint8_t *end, int *got_certs)
2737 {
2738 ptls_iovec_t certs[16];
2739 size_t num_certs = 0;
2740 int ret = 0;
2741
2742 /* certificate request context */
2743 ptls_decode_open_block(src, end, 1, {
2744 if (src != end) {
2745 ret = PTLS_ALERT_ILLEGAL_PARAMETER;
2746 goto Exit;
2747 }
2748 });
2749 /* certificate_list */
2750 ptls_decode_block(src, end, 3, {
2751 while (src != end) {
2752 ptls_decode_open_block(src, end, 3, {
2753 if (num_certs < PTLS_ELEMENTSOF(certs))
2754 certs[num_certs++] = ptls_iovec_init(src, end - src);
2755 src = end;
2756 });
2757 uint16_t type;
2758 decode_open_extensions(src, end, PTLS_HANDSHAKE_TYPE_CERTIFICATE, &type, {
2759 if (tls->ctx->on_extension != NULL &&
2760 (ret = tls->ctx->on_extension->cb(tls->ctx->on_extension, tls, PTLS_HANDSHAKE_TYPE_CERTIFICATE, type,
2761 ptls_iovec_init(src, end - src)) != 0))
2762 goto Exit;
2763 src = end;
2764 });
2765 }
2766 });
2767
2768 if (num_certs != 0 && tls->ctx->verify_certificate != NULL) {
2769 if ((ret = tls->ctx->verify_certificate->cb(tls->ctx->verify_certificate, tls, &tls->certificate_verify.cb,
2770 &tls->certificate_verify.verify_ctx, certs, num_certs)) != 0)
2771 goto Exit;
2772 }
2773
2774 *got_certs = num_certs != 0;
2775
2776 Exit:
2777 return ret;
2778 }
2779
client_do_handle_certificate(ptls_t * tls,const uint8_t * src,const uint8_t * end)2780 static int client_do_handle_certificate(ptls_t *tls, const uint8_t *src, const uint8_t *end)
2781 {
2782 int got_certs, ret;
2783
2784 if ((ret = handle_certificate(tls, src, end, &got_certs)) != 0)
2785 return ret;
2786 if (!got_certs)
2787 return PTLS_ALERT_ILLEGAL_PARAMETER;
2788
2789 return 0;
2790 }
2791
client_handle_certificate(ptls_t * tls,ptls_iovec_t message)2792 static int client_handle_certificate(ptls_t *tls, ptls_iovec_t message)
2793 {
2794 int ret;
2795
2796 if ((ret = client_do_handle_certificate(tls, message.base + PTLS_HANDSHAKE_HEADER_SIZE, message.base + message.len)) != 0)
2797 return ret;
2798
2799 ptls__key_schedule_update_hash(tls->key_schedule, message.base, message.len);
2800
2801 tls->state = PTLS_STATE_CLIENT_EXPECT_CERTIFICATE_VERIFY;
2802 return PTLS_ERROR_IN_PROGRESS;
2803 }
2804
client_handle_compressed_certificate(ptls_t * tls,ptls_iovec_t message)2805 static int client_handle_compressed_certificate(ptls_t *tls, ptls_iovec_t message)
2806 {
2807 const uint8_t *src = message.base + PTLS_HANDSHAKE_HEADER_SIZE, *const end = message.base + message.len;
2808 uint16_t algo;
2809 uint32_t uncompressed_size;
2810 uint8_t *uncompressed = NULL;
2811 int ret;
2812
2813 if (tls->ctx->decompress_certificate == NULL) {
2814 ret = PTLS_ALERT_UNEXPECTED_MESSAGE;
2815 goto Exit;
2816 }
2817
2818 /* decode */
2819 if ((ret = ptls_decode16(&algo, &src, end)) != 0)
2820 goto Exit;
2821 if ((ret = ptls_decode24(&uncompressed_size, &src, end)) != 0)
2822 goto Exit;
2823 if (uncompressed_size > 65536) { /* TODO find a sensible number */
2824 ret = PTLS_ALERT_BAD_CERTIFICATE;
2825 goto Exit;
2826 }
2827 if ((uncompressed = malloc(uncompressed_size)) == NULL) {
2828 ret = PTLS_ERROR_NO_MEMORY;
2829 goto Exit;
2830 }
2831 ptls_decode_block(src, end, 3, {
2832 if ((ret = tls->ctx->decompress_certificate->cb(tls->ctx->decompress_certificate, tls, algo,
2833 ptls_iovec_init(uncompressed, uncompressed_size),
2834 ptls_iovec_init(src, end - src))) != 0)
2835 goto Exit;
2836 src = end;
2837 });
2838
2839 /* handle */
2840 if ((ret = client_do_handle_certificate(tls, uncompressed, uncompressed + uncompressed_size)) != 0)
2841 goto Exit;
2842
2843 ptls__key_schedule_update_hash(tls->key_schedule, message.base, message.len);
2844 tls->state = PTLS_STATE_CLIENT_EXPECT_CERTIFICATE_VERIFY;
2845 ret = PTLS_ERROR_IN_PROGRESS;
2846
2847 Exit:
2848 free(uncompressed);
2849 return ret;
2850 }
2851
server_handle_certificate(ptls_t * tls,ptls_iovec_t message)2852 static int server_handle_certificate(ptls_t *tls, ptls_iovec_t message)
2853 {
2854 int got_certs, ret;
2855
2856 if ((ret = handle_certificate(tls, message.base + PTLS_HANDSHAKE_HEADER_SIZE, message.base + message.len, &got_certs)) != 0)
2857 return ret;
2858 if (!got_certs)
2859 return PTLS_ALERT_CERTIFICATE_REQUIRED;
2860
2861 ptls__key_schedule_update_hash(tls->key_schedule, message.base, message.len);
2862
2863 tls->state = PTLS_STATE_SERVER_EXPECT_CERTIFICATE_VERIFY;
2864 return PTLS_ERROR_IN_PROGRESS;
2865 }
2866
handle_certificate_verify(ptls_t * tls,ptls_iovec_t message,const char * context_string)2867 static int handle_certificate_verify(ptls_t *tls, ptls_iovec_t message, const char *context_string)
2868 {
2869 const uint8_t *src = message.base + PTLS_HANDSHAKE_HEADER_SIZE, *const end = message.base + message.len;
2870 uint16_t algo;
2871 ptls_iovec_t signature;
2872 uint8_t signdata[PTLS_MAX_CERTIFICATE_VERIFY_SIGNDATA_SIZE];
2873 size_t signdata_size;
2874 int ret;
2875
2876 /* decode */
2877 if ((ret = ptls_decode16(&algo, &src, end)) != 0)
2878 goto Exit;
2879 ptls_decode_block(src, end, 2, {
2880 signature = ptls_iovec_init(src, end - src);
2881 src = end;
2882 });
2883
2884 signdata_size = build_certificate_verify_signdata(signdata, tls->key_schedule, context_string);
2885 if (tls->certificate_verify.cb != NULL) {
2886 ret = tls->certificate_verify.cb(tls->certificate_verify.verify_ctx, algo, ptls_iovec_init(signdata, signdata_size),
2887 signature);
2888 } else {
2889 ret = 0;
2890 }
2891 ptls_clear_memory(signdata, signdata_size);
2892 tls->certificate_verify.cb = NULL;
2893 if (ret != 0) {
2894 goto Exit;
2895 }
2896
2897 ptls__key_schedule_update_hash(tls->key_schedule, message.base, message.len);
2898
2899 Exit:
2900 return ret;
2901 }
2902
client_handle_certificate_verify(ptls_t * tls,ptls_iovec_t message)2903 static int client_handle_certificate_verify(ptls_t *tls, ptls_iovec_t message)
2904 {
2905 int ret = handle_certificate_verify(tls, message, PTLS_SERVER_CERTIFICATE_VERIFY_CONTEXT_STRING);
2906
2907 if (ret == 0) {
2908 tls->state = PTLS_STATE_CLIENT_EXPECT_FINISHED;
2909 ret = PTLS_ERROR_IN_PROGRESS;
2910 }
2911
2912 return ret;
2913 }
2914
server_handle_certificate_verify(ptls_t * tls,ptls_iovec_t message)2915 static int server_handle_certificate_verify(ptls_t *tls, ptls_iovec_t message)
2916 {
2917 int ret = handle_certificate_verify(tls, message, PTLS_CLIENT_CERTIFICATE_VERIFY_CONTEXT_STRING);
2918
2919 if (ret == 0) {
2920 tls->state = PTLS_STATE_SERVER_EXPECT_FINISHED;
2921 ret = PTLS_ERROR_IN_PROGRESS;
2922 }
2923
2924 return ret;
2925 }
2926
client_handle_finished(ptls_t * tls,ptls_message_emitter_t * emitter,ptls_iovec_t message)2927 static int client_handle_finished(ptls_t *tls, ptls_message_emitter_t *emitter, ptls_iovec_t message)
2928 {
2929 uint8_t send_secret[PTLS_MAX_DIGEST_SIZE];
2930 int ret;
2931
2932 if ((ret = verify_finished(tls, message)) != 0)
2933 goto Exit;
2934 ptls__key_schedule_update_hash(tls->key_schedule, message.base, message.len);
2935
2936 /* update traffic keys by using messages upto ServerFinished, but commission them after sending ClientFinished */
2937 if ((ret = key_schedule_extract(tls->key_schedule, ptls_iovec_init(NULL, 0))) != 0)
2938 goto Exit;
2939 if ((ret = setup_traffic_protection(tls, 0, "s ap traffic", 3, 0)) != 0)
2940 goto Exit;
2941 if ((ret = derive_secret(tls->key_schedule, send_secret, "c ap traffic")) != 0)
2942 goto Exit;
2943 if ((ret = derive_exporter_secret(tls, 0)) != 0)
2944 goto Exit;
2945
2946 /* if sending early data, emit EOED and commision the client handshake traffic secret */
2947 if (tls->pending_handshake_secret != NULL) {
2948 assert(tls->traffic_protection.enc.aead != NULL || tls->ctx->update_traffic_key != NULL);
2949 if (tls->client.using_early_data && !tls->ctx->omit_end_of_early_data)
2950 ptls_push_message(emitter, tls->key_schedule, PTLS_HANDSHAKE_TYPE_END_OF_EARLY_DATA, {});
2951 tls->client.using_early_data = 0;
2952 if ((ret = commission_handshake_secret(tls)) != 0)
2953 goto Exit;
2954 }
2955
2956 if ((ret = push_change_cipher_spec(tls, emitter)) != 0)
2957 goto Exit;
2958
2959 if (tls->client.certificate_request.context.base != NULL) {
2960 /* If this is a resumed session, the server must not send the certificate request in the handshake */
2961 if (tls->is_psk_handshake) {
2962 ret = PTLS_ALERT_ILLEGAL_PARAMETER;
2963 goto Exit;
2964 }
2965 ret = send_certificate_and_certificate_verify(tls, emitter, &tls->client.certificate_request.signature_algorithms,
2966 tls->client.certificate_request.context,
2967 PTLS_CLIENT_CERTIFICATE_VERIFY_CONTEXT_STRING, 0, NULL, 0);
2968 free(tls->client.certificate_request.context.base);
2969 tls->client.certificate_request.context = ptls_iovec_init(NULL, 0);
2970 if (ret != 0)
2971 goto Exit;
2972 }
2973
2974 ret = send_finished(tls, emitter);
2975
2976 memcpy(tls->traffic_protection.enc.secret, send_secret, sizeof(send_secret));
2977 if ((ret = setup_traffic_protection(tls, 1, NULL, 3, 0)) != 0)
2978 goto Exit;
2979
2980 tls->state = PTLS_STATE_CLIENT_POST_HANDSHAKE;
2981
2982 Exit:
2983 ptls_clear_memory(send_secret, sizeof(send_secret));
2984 return ret;
2985 }
2986
client_handle_new_session_ticket(ptls_t * tls,ptls_iovec_t message)2987 static int client_handle_new_session_ticket(ptls_t *tls, ptls_iovec_t message)
2988 {
2989 const uint8_t *src = message.base + PTLS_HANDSHAKE_HEADER_SIZE, *const end = message.base + message.len;
2990 ptls_iovec_t ticket_nonce;
2991 int ret;
2992
2993 { /* verify the format */
2994 uint32_t ticket_lifetime, ticket_age_add, max_early_data_size;
2995 ptls_iovec_t ticket;
2996 if ((ret = decode_new_session_ticket(tls, &ticket_lifetime, &ticket_age_add, &ticket_nonce, &ticket, &max_early_data_size,
2997 src, end)) != 0)
2998 return ret;
2999 }
3000
3001 /* do nothing if use of session ticket is disabled */
3002 if (tls->ctx->save_ticket == NULL)
3003 return 0;
3004
3005 /* save the extension, along with the key of myself */
3006 ptls_buffer_t ticket_buf;
3007 ptls_buffer_init(&ticket_buf, "", 0);
3008 ptls_buffer_push64(&ticket_buf, tls->ctx->get_time->cb(tls->ctx->get_time));
3009 ptls_buffer_push16(&ticket_buf, tls->key_share->id);
3010 ptls_buffer_push16(&ticket_buf, tls->cipher_suite->id);
3011 ptls_buffer_push_block(&ticket_buf, 3, { ptls_buffer_pushv(&ticket_buf, src, end - src); });
3012 ptls_buffer_push_block(&ticket_buf, 2, {
3013 if ((ret = ptls_buffer_reserve(&ticket_buf, tls->key_schedule->hashes[0].algo->digest_size)) != 0)
3014 goto Exit;
3015 if ((ret = derive_resumption_secret(tls->key_schedule, ticket_buf.base + ticket_buf.off, ticket_nonce)) != 0)
3016 goto Exit;
3017 ticket_buf.off += tls->key_schedule->hashes[0].algo->digest_size;
3018 });
3019
3020 if ((ret = tls->ctx->save_ticket->cb(tls->ctx->save_ticket, tls, ptls_iovec_init(ticket_buf.base, ticket_buf.off))) != 0)
3021 goto Exit;
3022
3023 ret = 0;
3024 Exit:
3025 ptls_buffer_dispose(&ticket_buf);
3026 return ret;
3027 }
3028
client_hello_decode_server_name(ptls_iovec_t * name,const uint8_t ** src,const uint8_t * const end)3029 static int client_hello_decode_server_name(ptls_iovec_t *name, const uint8_t **src, const uint8_t *const end)
3030 {
3031 int ret = 0;
3032
3033 ptls_decode_open_block(*src, end, 2, {
3034 if (*src == end) {
3035 ret = PTLS_ALERT_DECODE_ERROR;
3036 goto Exit;
3037 }
3038 do {
3039 uint8_t type = *(*src)++;
3040 ptls_decode_open_block(*src, end, 2, {
3041 switch (type) {
3042 case PTLS_SERVER_NAME_TYPE_HOSTNAME:
3043 if (memchr(*src, '\0', end - *src) != 0) {
3044 ret = PTLS_ALERT_ILLEGAL_PARAMETER;
3045 goto Exit;
3046 }
3047 *name = ptls_iovec_init(*src, end - *src);
3048 break;
3049 default:
3050 break;
3051 }
3052 *src = end;
3053 });
3054 } while (*src != end);
3055 });
3056
3057 Exit:
3058 return ret;
3059 }
3060
client_hello_decrypt_esni(ptls_context_t * ctx,ptls_iovec_t * server_name,ptls_esni_secret_t ** secret,struct st_ptls_client_hello_t * ch)3061 static int client_hello_decrypt_esni(ptls_context_t *ctx, ptls_iovec_t *server_name, ptls_esni_secret_t **secret,
3062 struct st_ptls_client_hello_t *ch)
3063 {
3064 ptls_esni_context_t **esni;
3065 ptls_key_exchange_context_t **key_share_ctx;
3066 uint8_t *decrypted = NULL;
3067 ptls_aead_context_t *aead = NULL;
3068 int ret;
3069
3070 /* allocate secret */
3071 assert(*secret == NULL);
3072 if ((*secret = malloc(sizeof(**secret))) == NULL)
3073 return PTLS_ERROR_NO_MEMORY;
3074 memset(*secret, 0, sizeof(**secret));
3075
3076 /* find the matching esni structure */
3077 for (esni = ctx->esni; *esni != NULL; ++esni) {
3078 size_t i;
3079 for (i = 0; (*esni)->cipher_suites[i].cipher_suite != NULL; ++i)
3080 if ((*esni)->cipher_suites[i].cipher_suite->id == ch->esni.cipher->id)
3081 break;
3082 if ((*esni)->cipher_suites[i].cipher_suite == NULL) {
3083 ret = PTLS_ALERT_ILLEGAL_PARAMETER;
3084 goto Exit;
3085 }
3086 if (memcmp((*esni)->cipher_suites[i].record_digest, ch->esni.record_digest, ch->esni.cipher->hash->digest_size) == 0) {
3087 (*secret)->version = (*esni)->version;
3088 break;
3089 }
3090 }
3091 if (*esni == NULL) {
3092 ret = PTLS_ALERT_ILLEGAL_PARAMETER;
3093 goto Exit;
3094 }
3095
3096 /* find the matching private key for ESNI decryption */
3097 for (key_share_ctx = (*esni)->key_exchanges; *key_share_ctx != NULL; ++key_share_ctx)
3098 if ((*key_share_ctx)->algo->id == ch->esni.key_share->id)
3099 break;
3100 if (*key_share_ctx == NULL) {
3101 ret = PTLS_ALERT_ILLEGAL_PARAMETER;
3102 goto Exit;
3103 }
3104
3105 /* calculate ESNIContents */
3106 if ((ret = build_esni_contents_hash(ch->esni.cipher->hash, (*secret)->esni_contents_hash, ch->esni.record_digest,
3107 ch->esni.key_share->id, ch->esni.peer_key, ch->random_bytes)) != 0)
3108 goto Exit;
3109 /* derive the shared secret */
3110 if ((ret = (*key_share_ctx)->on_exchange(key_share_ctx, 0, &(*secret)->secret, ch->esni.peer_key)) != 0)
3111 goto Exit;
3112 /* decrypt */
3113 if (ch->esni.encrypted_sni.len - ch->esni.cipher->aead->tag_size != (*esni)->padded_length + PTLS_ESNI_NONCE_SIZE) {
3114 ret = PTLS_ALERT_ILLEGAL_PARAMETER;
3115 goto Exit;
3116 }
3117 if ((decrypted = malloc((*esni)->padded_length + PTLS_ESNI_NONCE_SIZE)) == NULL) {
3118 ret = PTLS_ERROR_NO_MEMORY;
3119 goto Exit;
3120 }
3121 if ((ret = create_esni_aead(&aead, 0, ch->esni.cipher, (*secret)->secret, (*secret)->esni_contents_hash)) != 0)
3122 goto Exit;
3123 if (ptls_aead_decrypt(aead, decrypted, ch->esni.encrypted_sni.base, ch->esni.encrypted_sni.len, 0, ch->key_shares.base,
3124 ch->key_shares.len) != (*esni)->padded_length + PTLS_ESNI_NONCE_SIZE) {
3125 ret = PTLS_ALERT_DECRYPT_ERROR;
3126 goto Exit;
3127 }
3128 ptls_aead_free(aead);
3129 aead = NULL;
3130
3131 { /* decode sni */
3132 const uint8_t *src = decrypted, *const end = src + (*esni)->padded_length;
3133 ptls_iovec_t found_name;
3134 if (end - src < PTLS_ESNI_NONCE_SIZE) {
3135 ret = PTLS_ALERT_ILLEGAL_PARAMETER;
3136 goto Exit;
3137 }
3138 memcpy((*secret)->nonce, src, PTLS_ESNI_NONCE_SIZE);
3139 src += PTLS_ESNI_NONCE_SIZE;
3140 if ((ret = client_hello_decode_server_name(&found_name, &src, end)) != 0)
3141 goto Exit;
3142 for (; src != end; ++src) {
3143 if (*src != '\0') {
3144 ret = PTLS_ALERT_ILLEGAL_PARAMETER;
3145 goto Exit;
3146 }
3147 }
3148 /* if successful, reuse memory allocated for padded_server_name for storing the found name (freed by the caller) */
3149 memmove(decrypted, found_name.base, found_name.len);
3150 *server_name = ptls_iovec_init(decrypted, found_name.len);
3151 decrypted = NULL;
3152 }
3153
3154 ret = 0;
3155 Exit:
3156 if (decrypted != NULL)
3157 free(decrypted);
3158 if (aead != NULL)
3159 ptls_aead_free(aead);
3160 if (ret != 0 && *secret != NULL)
3161 free_esni_secret(secret, 1);
3162 return ret;
3163 }
3164
select_negotiated_group(ptls_key_exchange_algorithm_t ** selected,ptls_key_exchange_algorithm_t ** candidates,const uint8_t * src,const uint8_t * const end)3165 static int select_negotiated_group(ptls_key_exchange_algorithm_t **selected, ptls_key_exchange_algorithm_t **candidates,
3166 const uint8_t *src, const uint8_t *const end)
3167 {
3168 int ret;
3169
3170 ptls_decode_block(src, end, 2, {
3171 while (src != end) {
3172 uint16_t group;
3173 if ((ret = ptls_decode16(&group, &src, end)) != 0)
3174 goto Exit;
3175 ptls_key_exchange_algorithm_t **c = candidates;
3176 for (; *c != NULL; ++c) {
3177 if ((*c)->id == group) {
3178 *selected = *c;
3179 return 0;
3180 }
3181 }
3182 }
3183 });
3184
3185 ret = PTLS_ALERT_HANDSHAKE_FAILURE;
3186
3187 Exit:
3188 return ret;
3189 }
3190
decode_client_hello(ptls_t * tls,struct st_ptls_client_hello_t * ch,const uint8_t * src,const uint8_t * const end,ptls_handshake_properties_t * properties)3191 static int decode_client_hello(ptls_t *tls, struct st_ptls_client_hello_t *ch, const uint8_t *src, const uint8_t *const end,
3192 ptls_handshake_properties_t *properties)
3193 {
3194 uint16_t exttype = 0;
3195 int ret;
3196
3197 /* decode protocol version (do not bare to decode something older than TLS 1.0) */
3198 if ((ret = ptls_decode16(&ch->legacy_version, &src, end)) != 0)
3199 goto Exit;
3200 if (ch->legacy_version < 0x0301) {
3201 ret = PTLS_ALERT_PROTOCOL_VERSION;
3202 goto Exit;
3203 }
3204
3205 /* skip random */
3206 if (end - src < PTLS_HELLO_RANDOM_SIZE) {
3207 ret = PTLS_ALERT_DECODE_ERROR;
3208 goto Exit;
3209 }
3210 ch->random_bytes = src;
3211 src += PTLS_HELLO_RANDOM_SIZE;
3212
3213 /* skip legacy_session_id */
3214 ptls_decode_open_block(src, end, 1, {
3215 if (end - src > 32) {
3216 ret = PTLS_ALERT_DECODE_ERROR;
3217 goto Exit;
3218 }
3219 ch->legacy_session_id = ptls_iovec_init(src, end - src);
3220 src = end;
3221 });
3222
3223 /* decode and select from ciphersuites */
3224 ptls_decode_open_block(src, end, 2, {
3225 ch->cipher_suites = ptls_iovec_init(src, end - src);
3226 uint16_t *id = ch->client_ciphers.list;
3227 do {
3228 if ((ret = ptls_decode16(id, &src, end)) != 0)
3229 goto Exit;
3230 id++;
3231 ch->client_ciphers.count++;
3232 if (id >= ch->client_ciphers.list + MAX_CLIENT_CIPHERS) {
3233 src = end;
3234 break;
3235 }
3236 } while (src != end);
3237 });
3238
3239 /* decode legacy_compression_methods */
3240 ptls_decode_open_block(src, end, 1, {
3241 if (src == end) {
3242 ret = PTLS_ALERT_DECODE_ERROR;
3243 goto Exit;
3244 }
3245 ch->compression_methods.ids = src;
3246 ch->compression_methods.count = end - src;
3247 src = end;
3248 });
3249
3250 /* decode extensions */
3251 decode_extensions(src, end, PTLS_HANDSHAKE_TYPE_CLIENT_HELLO, &exttype, {
3252 ch->psk.is_last_extension = 0;
3253 if (tls->ctx->on_extension != NULL &&
3254 (ret = tls->ctx->on_extension->cb(tls->ctx->on_extension, tls, PTLS_HANDSHAKE_TYPE_CLIENT_HELLO, exttype,
3255 ptls_iovec_init(src, end - src)) != 0))
3256 goto Exit;
3257 switch (exttype) {
3258 case PTLS_EXTENSION_TYPE_SERVER_NAME:
3259 if ((ret = client_hello_decode_server_name(&ch->server_name, &src, end)) != 0)
3260 goto Exit;
3261 if (src != end) {
3262 ret = PTLS_ALERT_DECODE_ERROR;
3263 goto Exit;
3264 }
3265 break;
3266 case PTLS_EXTENSION_TYPE_ENCRYPTED_SERVER_NAME: {
3267 ptls_cipher_suite_t **cipher;
3268 if (ch->esni.cipher != NULL) {
3269 ret = PTLS_ALERT_ILLEGAL_PARAMETER;
3270 goto Exit;
3271 }
3272 { /* cipher-suite */
3273 uint16_t csid;
3274 if ((ret = ptls_decode16(&csid, &src, end)) != 0)
3275 goto Exit;
3276 for (cipher = tls->ctx->cipher_suites; *cipher != NULL; ++cipher)
3277 if ((*cipher)->id == csid)
3278 break;
3279 if (*cipher == NULL) {
3280 ret = PTLS_ALERT_ILLEGAL_PARAMETER;
3281 goto Exit;
3282 }
3283 }
3284 /* key-share (including peer-key) */
3285 if ((ret = select_key_share(&ch->esni.key_share, &ch->esni.peer_key, tls->ctx->key_exchanges, &src, end, 1)) != 0)
3286 goto Exit;
3287 ptls_decode_open_block(src, end, 2, {
3288 size_t len = end - src;
3289 if (len != (*cipher)->hash->digest_size) {
3290 ret = PTLS_ALERT_ILLEGAL_PARAMETER;
3291 goto Exit;
3292 }
3293 ch->esni.record_digest = src;
3294 src += len;
3295 });
3296 ptls_decode_block(src, end, 2, {
3297 size_t len = end - src;
3298 if (len < (*cipher)->aead->tag_size) {
3299 ret = PTLS_ALERT_ILLEGAL_PARAMETER;
3300 goto Exit;
3301 }
3302 ch->esni.encrypted_sni = ptls_iovec_init(src, len);
3303 src += len;
3304 });
3305 ch->esni.cipher = *cipher; /* set only after successful parsing */
3306 } break;
3307 case PTLS_EXTENSION_TYPE_ALPN:
3308 ptls_decode_block(src, end, 2, {
3309 do {
3310 ptls_decode_open_block(src, end, 1, {
3311 /* rfc7301 3.1: empty strings MUST NOT be included */
3312 if (src == end) {
3313 ret = PTLS_ALERT_DECODE_ERROR;
3314 goto Exit;
3315 }
3316 if (ch->alpn.count < PTLS_ELEMENTSOF(ch->alpn.list))
3317 ch->alpn.list[ch->alpn.count++] = ptls_iovec_init(src, end - src);
3318 src = end;
3319 });
3320 } while (src != end);
3321 });
3322 break;
3323 case PTLS_EXTENSION_TYPE_SERVER_CERTIFICATE_TYPE:
3324 ptls_decode_block(src, end, 1, {
3325 size_t list_size = end - src;
3326
3327 /* RFC7250 4.1: No empty list, no list with single x509 element */
3328 if (list_size == 0 || (list_size == 1 && *src == PTLS_CERTIFICATE_TYPE_X509)) {
3329 ret = PTLS_ALERT_DECODE_ERROR;
3330 goto Exit;
3331 }
3332
3333 do {
3334 if (ch->server_certificate_types.count < PTLS_ELEMENTSOF(ch->server_certificate_types.list))
3335 ch->server_certificate_types.list[ch->server_certificate_types.count++] = *src;
3336 src++;
3337 } while (src != end);
3338 });
3339 break;
3340 case PTLS_EXTENSION_TYPE_COMPRESS_CERTIFICATE:
3341 ptls_decode_block(src, end, 1, {
3342 do {
3343 uint16_t id;
3344 if ((ret = ptls_decode16(&id, &src, end)) != 0)
3345 goto Exit;
3346 if (ch->cert_compression_algos.count < PTLS_ELEMENTSOF(ch->cert_compression_algos.list))
3347 ch->cert_compression_algos.list[ch->cert_compression_algos.count++] = id;
3348 } while (src != end);
3349 });
3350 break;
3351 case PTLS_EXTENSION_TYPE_SUPPORTED_GROUPS:
3352 ch->negotiated_groups = ptls_iovec_init(src, end - src);
3353 break;
3354 case PTLS_EXTENSION_TYPE_SIGNATURE_ALGORITHMS:
3355 if ((ret = decode_signature_algorithms(&ch->signature_algorithms, &src, end)) != 0)
3356 goto Exit;
3357 break;
3358 case PTLS_EXTENSION_TYPE_KEY_SHARE:
3359 ch->key_shares = ptls_iovec_init(src, end - src);
3360 break;
3361 case PTLS_EXTENSION_TYPE_SUPPORTED_VERSIONS:
3362 ptls_decode_block(src, end, 1, {
3363 size_t selected_index = PTLS_ELEMENTSOF(supported_versions);
3364 do {
3365 size_t i;
3366 uint16_t v;
3367 if ((ret = ptls_decode16(&v, &src, end)) != 0)
3368 goto Exit;
3369 for (i = 0; i != selected_index; ++i) {
3370 if (supported_versions[i] == v) {
3371 selected_index = i;
3372 break;
3373 }
3374 }
3375 } while (src != end);
3376 if (selected_index != PTLS_ELEMENTSOF(supported_versions))
3377 ch->selected_version = supported_versions[selected_index];
3378 });
3379 break;
3380 case PTLS_EXTENSION_TYPE_COOKIE:
3381 if (properties == NULL || properties->server.cookie.key == NULL) {
3382 ret = PTLS_ALERT_ILLEGAL_PARAMETER;
3383 goto Exit;
3384 }
3385 ch->cookie.all = ptls_iovec_init(src, end - src);
3386 ptls_decode_block(src, end, 2, {
3387 ch->cookie.tbs.base = (void *)src;
3388 ptls_decode_open_block(src, end, 2, {
3389 ptls_decode_open_block(src, end, 1, {
3390 ch->cookie.ch1_hash = ptls_iovec_init(src, end - src);
3391 src = end;
3392 });
3393 if (src == end) {
3394 ret = PTLS_ALERT_DECODE_ERROR;
3395 goto Exit;
3396 }
3397 switch (*src++) {
3398 case 0:
3399 assert(!ch->cookie.sent_key_share);
3400 break;
3401 case 1:
3402 ch->cookie.sent_key_share = 1;
3403 break;
3404 default:
3405 ret = PTLS_ALERT_DECODE_ERROR;
3406 goto Exit;
3407 }
3408 });
3409 ch->cookie.tbs.len = src - ch->cookie.tbs.base;
3410 ptls_decode_block(src, end, 1, {
3411 ch->cookie.signature = ptls_iovec_init(src, end - src);
3412 src = end;
3413 });
3414 });
3415 break;
3416 case PTLS_EXTENSION_TYPE_PRE_SHARED_KEY: {
3417 size_t num_identities = 0;
3418 ptls_decode_open_block(src, end, 2, {
3419 do {
3420 struct st_ptls_client_hello_psk_t psk = {{NULL}};
3421 ptls_decode_open_block(src, end, 2, {
3422 psk.identity = ptls_iovec_init(src, end - src);
3423 src = end;
3424 });
3425 if ((ret = ptls_decode32(&psk.obfuscated_ticket_age, &src, end)) != 0)
3426 goto Exit;
3427 if (ch->psk.identities.count < PTLS_ELEMENTSOF(ch->psk.identities.list))
3428 ch->psk.identities.list[ch->psk.identities.count++] = psk;
3429 ++num_identities;
3430 } while (src != end);
3431 });
3432 ch->psk.hash_end = src;
3433 ptls_decode_block(src, end, 2, {
3434 size_t num_binders = 0;
3435 do {
3436 ptls_decode_open_block(src, end, 1, {
3437 if (num_binders < ch->psk.identities.count)
3438 ch->psk.identities.list[num_binders].binder = ptls_iovec_init(src, end - src);
3439 src = end;
3440 });
3441 ++num_binders;
3442 } while (src != end);
3443 if (num_identities != num_binders) {
3444 ret = PTLS_ALERT_ILLEGAL_PARAMETER;
3445 goto Exit;
3446 }
3447 });
3448 ch->psk.is_last_extension = 1;
3449 } break;
3450 case PTLS_EXTENSION_TYPE_PSK_KEY_EXCHANGE_MODES:
3451 ptls_decode_block(src, end, 1, {
3452 if (src == end) {
3453 ret = PTLS_ALERT_DECODE_ERROR;
3454 goto Exit;
3455 }
3456 for (; src != end; ++src) {
3457 if (*src < sizeof(ch->psk.ke_modes) * 8)
3458 ch->psk.ke_modes |= 1u << *src;
3459 }
3460 });
3461 break;
3462 case PTLS_EXTENSION_TYPE_EARLY_DATA:
3463 ch->psk.early_data_indication = 1;
3464 break;
3465 case PTLS_EXTENSION_TYPE_STATUS_REQUEST:
3466 ch->status_request = 1;
3467 break;
3468 default:
3469 if (should_collect_unknown_extension(tls, properties, exttype)) {
3470 if ((ret = collect_unknown_extension(tls, exttype, src, end, ch->unknown_extensions)) != 0)
3471 goto Exit;
3472 }
3473 break;
3474 }
3475 src = end;
3476 });
3477
3478 ret = 0;
3479 Exit:
3480 return ret;
3481 }
3482
vec_is_string(ptls_iovec_t x,const char * y)3483 static int vec_is_string(ptls_iovec_t x, const char *y)
3484 {
3485 return strncmp((const char *)x.base, y, x.len) == 0 && y[x.len] == '\0';
3486 }
3487
try_psk_handshake(ptls_t * tls,size_t * psk_index,int * accept_early_data,struct st_ptls_client_hello_t * ch,ptls_iovec_t ch_trunc)3488 static int try_psk_handshake(ptls_t *tls, size_t *psk_index, int *accept_early_data, struct st_ptls_client_hello_t *ch,
3489 ptls_iovec_t ch_trunc)
3490 {
3491 ptls_buffer_t decbuf;
3492 ptls_iovec_t ticket_psk, ticket_server_name, ticket_negotiated_protocol;
3493 uint64_t issue_at, now = tls->ctx->get_time->cb(tls->ctx->get_time);
3494 uint32_t age_add;
3495 uint16_t ticket_key_exchange_id, ticket_csid;
3496 uint8_t binder_key[PTLS_MAX_DIGEST_SIZE];
3497 int ret;
3498
3499 ptls_buffer_init(&decbuf, "", 0);
3500
3501 for (*psk_index = 0; *psk_index < ch->psk.identities.count; ++*psk_index) {
3502 struct st_ptls_client_hello_psk_t *identity = ch->psk.identities.list + *psk_index;
3503 /* decrypt and decode */
3504 int can_accept_early_data = 1;
3505 decbuf.off = 0;
3506 switch (tls->ctx->encrypt_ticket->cb(tls->ctx->encrypt_ticket, tls, 0, &decbuf, identity->identity)) {
3507 case 0: /* decrypted */
3508 break;
3509 case PTLS_ERROR_REJECT_EARLY_DATA: /* decrypted, but early data is rejected */
3510 can_accept_early_data = 0;
3511 break;
3512 default: /* decryption failure */
3513 continue;
3514 }
3515 if (decode_session_identifier(&issue_at, &ticket_psk, &age_add, &ticket_server_name, &ticket_key_exchange_id, &ticket_csid,
3516 &ticket_negotiated_protocol, decbuf.base, decbuf.base + decbuf.off) != 0)
3517 continue;
3518 /* check age */
3519 if (now < issue_at)
3520 continue;
3521 if (now - issue_at > (uint64_t)tls->ctx->ticket_lifetime * 1000)
3522 continue;
3523 *accept_early_data = 0;
3524 if (ch->psk.early_data_indication && can_accept_early_data) {
3525 /* accept early-data if abs(diff) between the reported age and the actual age is within += 10 seconds */
3526 int64_t delta = (now - issue_at) - (identity->obfuscated_ticket_age - age_add);
3527 if (delta < 0)
3528 delta = -delta;
3529 if (tls->ctx->max_early_data_size != 0 && delta <= PTLS_EARLY_DATA_MAX_DELAY)
3530 *accept_early_data = 1;
3531 }
3532 /* check server-name */
3533 if (ticket_server_name.len != 0) {
3534 if (tls->server_name == NULL)
3535 continue;
3536 if (!vec_is_string(ticket_server_name, tls->server_name))
3537 continue;
3538 } else {
3539 if (tls->server_name != NULL)
3540 continue;
3541 }
3542 { /* check key-exchange */
3543 ptls_key_exchange_algorithm_t **a;
3544 for (a = tls->ctx->key_exchanges; *a != NULL && (*a)->id != ticket_key_exchange_id; ++a)
3545 ;
3546 if (*a == NULL)
3547 continue;
3548 tls->key_share = *a;
3549 }
3550 /* check cipher-suite */
3551 if (ticket_csid != tls->cipher_suite->id)
3552 continue;
3553 /* check negotiated-protocol */
3554 if (ticket_negotiated_protocol.len != 0) {
3555 if (tls->negotiated_protocol == NULL)
3556 continue;
3557 if (!vec_is_string(ticket_negotiated_protocol, tls->negotiated_protocol))
3558 continue;
3559 }
3560 /* check the length of the decrypted psk and the PSK binder */
3561 if (ticket_psk.len != tls->key_schedule->hashes[0].algo->digest_size)
3562 continue;
3563 if (ch->psk.identities.list[*psk_index].binder.len != tls->key_schedule->hashes[0].algo->digest_size)
3564 continue;
3565
3566 /* found */
3567 goto Found;
3568 }
3569
3570 /* not found */
3571 *psk_index = SIZE_MAX;
3572 *accept_early_data = 0;
3573 tls->key_share = NULL;
3574 ret = 0;
3575 goto Exit;
3576
3577 Found:
3578 if ((ret = key_schedule_extract(tls->key_schedule, ticket_psk)) != 0)
3579 goto Exit;
3580 if ((ret = derive_secret(tls->key_schedule, binder_key, "res binder")) != 0)
3581 goto Exit;
3582 ptls__key_schedule_update_hash(tls->key_schedule, ch_trunc.base, ch_trunc.len);
3583 if ((ret = calc_verify_data(binder_key /* to conserve space, reuse binder_key for storing verify_data */, tls->key_schedule,
3584 binder_key)) != 0)
3585 goto Exit;
3586 if (!ptls_mem_equal(ch->psk.identities.list[*psk_index].binder.base, binder_key,
3587 tls->key_schedule->hashes[0].algo->digest_size)) {
3588 ret = PTLS_ALERT_DECRYPT_ERROR;
3589 goto Exit;
3590 }
3591 ret = 0;
3592
3593 Exit:
3594 ptls_buffer_dispose(&decbuf);
3595 ptls_clear_memory(binder_key, sizeof(binder_key));
3596 return ret;
3597 }
3598
calc_cookie_signature(ptls_t * tls,ptls_handshake_properties_t * properties,ptls_key_exchange_algorithm_t * negotiated_group,ptls_iovec_t tbs,uint8_t * sig)3599 static int calc_cookie_signature(ptls_t *tls, ptls_handshake_properties_t *properties,
3600 ptls_key_exchange_algorithm_t *negotiated_group, ptls_iovec_t tbs, uint8_t *sig)
3601 {
3602 ptls_hash_algorithm_t *algo = tls->ctx->cipher_suites[0]->hash;
3603 ptls_hash_context_t *hctx;
3604
3605 if ((hctx = ptls_hmac_create(algo, properties->server.cookie.key, algo->digest_size)) == NULL)
3606 return PTLS_ERROR_NO_MEMORY;
3607
3608 #define UPDATE_BLOCK(p, _len) \
3609 do { \
3610 size_t len = (_len); \
3611 assert(len < UINT8_MAX); \
3612 uint8_t len8 = (uint8_t)len; \
3613 hctx->update(hctx, &len8, 1); \
3614 hctx->update(hctx, (p), len); \
3615 } while (0)
3616 #define UPDATE16(_v) \
3617 do { \
3618 uint16_t v = (_v); \
3619 uint8_t b[2] = {v >> 8, v & 0xff}; \
3620 hctx->update(hctx, b, 2); \
3621 } while (0)
3622
3623 UPDATE_BLOCK(tls->client_random, sizeof(tls->client_random));
3624 UPDATE_BLOCK(tls->server_name, tls->server_name != NULL ? strlen(tls->server_name) : 0);
3625 UPDATE16(tls->cipher_suite->id);
3626 UPDATE16(negotiated_group->id);
3627 UPDATE_BLOCK(properties->server.cookie.additional_data.base, properties->server.cookie.additional_data.len);
3628
3629 UPDATE_BLOCK(tbs.base, tbs.len);
3630
3631 #undef UPDATE_BLOCK
3632 #undef UPDATE16
3633
3634 hctx->final(hctx, sig, PTLS_HASH_FINAL_MODE_FREE);
3635 return 0;
3636 }
3637
certificate_type_exists(uint8_t * list,size_t count,uint8_t desired_type)3638 static int certificate_type_exists(uint8_t *list, size_t count, uint8_t desired_type)
3639 {
3640 /* empty type list means that we default to x509 */
3641 if (desired_type == PTLS_CERTIFICATE_TYPE_X509 && count == 0)
3642 return 1;
3643 for (size_t i = 0; i < count; i++) {
3644 if (list[i] == desired_type)
3645 return 1;
3646 }
3647 return 0;
3648 }
3649
server_handle_hello(ptls_t * tls,ptls_message_emitter_t * emitter,ptls_iovec_t message,ptls_handshake_properties_t * properties)3650 static int server_handle_hello(ptls_t *tls, ptls_message_emitter_t *emitter, ptls_iovec_t message,
3651 ptls_handshake_properties_t *properties)
3652 {
3653 #define EMIT_SERVER_HELLO(sched, fill_rand, extensions) \
3654 ptls_push_message(emitter, (sched), PTLS_HANDSHAKE_TYPE_SERVER_HELLO, { \
3655 ptls_buffer_push16(emitter->buf, 0x0303 /* legacy version */); \
3656 if ((ret = ptls_buffer_reserve(emitter->buf, PTLS_HELLO_RANDOM_SIZE)) != 0) \
3657 goto Exit; \
3658 do { \
3659 fill_rand \
3660 } while (0); \
3661 emitter->buf->off += PTLS_HELLO_RANDOM_SIZE; \
3662 ptls_buffer_push_block(emitter->buf, 1, \
3663 { ptls_buffer_pushv(emitter->buf, ch->legacy_session_id.base, ch->legacy_session_id.len); }); \
3664 ptls_buffer_push16(emitter->buf, tls->cipher_suite->id); \
3665 ptls_buffer_push(emitter->buf, 0); \
3666 ptls_buffer_push_block(emitter->buf, 2, { \
3667 buffer_push_extension(emitter->buf, PTLS_EXTENSION_TYPE_SUPPORTED_VERSIONS, \
3668 { ptls_buffer_push16(emitter->buf, ch->selected_version); }); \
3669 do { \
3670 extensions \
3671 } while (0); \
3672 }); \
3673 });
3674
3675 #define EMIT_HELLO_RETRY_REQUEST(sched, negotiated_group, additional_extensions) \
3676 EMIT_SERVER_HELLO((sched), { memcpy(emitter->buf->base + emitter->buf->off, hello_retry_random, PTLS_HELLO_RANDOM_SIZE); }, \
3677 { \
3678 ptls_key_exchange_algorithm_t *_negotiated_group = (negotiated_group); \
3679 if (_negotiated_group != NULL) { \
3680 buffer_push_extension(emitter->buf, PTLS_EXTENSION_TYPE_KEY_SHARE, \
3681 { ptls_buffer_push16(emitter->buf, _negotiated_group->id); }); \
3682 } \
3683 do { \
3684 additional_extensions \
3685 } while (0); \
3686 })
3687 struct st_ptls_client_hello_t *ch;
3688 struct {
3689 ptls_key_exchange_algorithm_t *algorithm;
3690 ptls_iovec_t peer_key;
3691 } key_share = {NULL};
3692 enum { HANDSHAKE_MODE_FULL, HANDSHAKE_MODE_PSK, HANDSHAKE_MODE_PSK_DHE } mode;
3693 size_t psk_index = SIZE_MAX;
3694 ptls_iovec_t pubkey = {0}, ecdh_secret = {0};
3695 int accept_early_data = 0, is_second_flight = tls->state == PTLS_STATE_SERVER_EXPECT_SECOND_CLIENT_HELLO, ret;
3696
3697 if ((ch = malloc(sizeof(*ch))) == NULL) {
3698 ret = PTLS_ERROR_NO_MEMORY;
3699 goto Exit;
3700 }
3701
3702 *ch = (struct st_ptls_client_hello_t){0, NULL, {NULL}, {NULL}, 0, {NULL}, {NULL}, {NULL}, {{0}},
3703 {NULL}, {NULL}, {{{NULL}}}, {{0}}, {{0}}, {{NULL}}, {NULL}, {{0}}, {{UINT16_MAX}}};
3704
3705 /* decode ClientHello */
3706 if ((ret = decode_client_hello(tls, ch, message.base + PTLS_HANDSHAKE_HEADER_SIZE, message.base + message.len, properties)) !=
3707 0)
3708 goto Exit;
3709
3710 /* bail out if CH cannot be handled as TLS 1.3, providing the application the raw CH and SNI, to help them fallback */
3711 if (!is_supported_version(ch->selected_version)) {
3712 if (!is_second_flight && tls->ctx->on_client_hello != NULL) {
3713 ptls_on_client_hello_parameters_t params = {
3714 .server_name = ch->server_name,
3715 .raw_message = message,
3716 .negotiated_protocols = {ch->alpn.list, ch->alpn.count},
3717 .incompatible_version = 1,
3718 };
3719 if ((ret = tls->ctx->on_client_hello->cb(tls->ctx->on_client_hello, tls, ¶ms)) != 0)
3720 goto Exit;
3721 }
3722 ret = PTLS_ALERT_PROTOCOL_VERSION;
3723 goto Exit;
3724 }
3725
3726 /* Check TLS 1.3-specific constraints. Hereafter, we might exit without calling on_client_hello. That's fine because this CH is
3727 * ought to be rejected. */
3728 if (ch->legacy_version <= 0x0300) {
3729 /* RFC 8446 Appendix D.5: any endpoint receiving a Hello message with legacy_version set to 0x0300 MUST abort the handshake
3730 * with a "protocol_version" alert. */
3731 ret = PTLS_ALERT_PROTOCOL_VERSION;
3732 goto Exit;
3733 }
3734 if (!(ch->compression_methods.count == 1 && ch->compression_methods.ids[0] == 0)) {
3735 ret = PTLS_ALERT_ILLEGAL_PARAMETER;
3736 goto Exit;
3737 }
3738 /* esni */
3739 if (ch->esni.cipher != NULL) {
3740 if (ch->key_shares.base == NULL) {
3741 ret = PTLS_ALERT_ILLEGAL_PARAMETER;
3742 goto Exit;
3743 }
3744 }
3745 /* pre-shared key */
3746 if (ch->psk.hash_end != NULL) {
3747 /* PSK must be the last extension */
3748 if (!ch->psk.is_last_extension) {
3749 ret = PTLS_ALERT_ILLEGAL_PARAMETER;
3750 goto Exit;
3751 }
3752 } else {
3753 if (ch->psk.early_data_indication) {
3754 ret = PTLS_ALERT_ILLEGAL_PARAMETER;
3755 goto Exit;
3756 }
3757 }
3758
3759 if (tls->ctx->require_dhe_on_psk)
3760 ch->psk.ke_modes &= ~(1u << PTLS_PSK_KE_MODE_PSK);
3761
3762 /* handle client_random, legacy_session_id, SNI, ESNI */
3763 if (!is_second_flight) {
3764 memcpy(tls->client_random, ch->random_bytes, sizeof(tls->client_random));
3765 log_client_random(tls);
3766 if (ch->legacy_session_id.len != 0)
3767 tls->send_change_cipher_spec = 1;
3768 ptls_iovec_t server_name = {NULL};
3769 int is_esni = 0;
3770 if (ch->esni.cipher != NULL && tls->ctx->esni != NULL) {
3771 if ((ret = client_hello_decrypt_esni(tls->ctx, &server_name, &tls->esni, ch)) != 0)
3772 goto Exit;
3773 if (tls->ctx->update_esni_key != NULL) {
3774 if ((ret = tls->ctx->update_esni_key->cb(tls->ctx->update_esni_key, tls, tls->esni->secret, ch->esni.cipher->hash,
3775 tls->esni->esni_contents_hash)) != 0)
3776 goto Exit;
3777 }
3778 is_esni = 1;
3779 } else if (ch->server_name.base != NULL) {
3780 server_name = ch->server_name;
3781 }
3782 if (tls->ctx->on_client_hello != NULL) {
3783 ptls_on_client_hello_parameters_t params = {server_name,
3784 message,
3785 {ch->alpn.list, ch->alpn.count},
3786 {ch->signature_algorithms.list, ch->signature_algorithms.count},
3787 {ch->cert_compression_algos.list, ch->cert_compression_algos.count},
3788 {ch->client_ciphers.list, ch->client_ciphers.count},
3789 {ch->server_certificate_types.list, ch->server_certificate_types.count},
3790 is_esni};
3791 ret = tls->ctx->on_client_hello->cb(tls->ctx->on_client_hello, tls, ¶ms);
3792 } else {
3793 ret = 0;
3794 }
3795
3796 if (is_esni)
3797 free(server_name.base);
3798 if (ret != 0)
3799 goto Exit;
3800
3801 if (!certificate_type_exists(ch->server_certificate_types.list, ch->server_certificate_types.count,
3802 tls->ctx->use_raw_public_keys ? PTLS_CERTIFICATE_TYPE_RAW_PUBLIC_KEY
3803 : PTLS_CERTIFICATE_TYPE_X509)) {
3804 ret = PTLS_ALERT_UNSUPPORTED_CERTIFICATE;
3805 goto Exit;
3806 }
3807 } else {
3808 if (ch->psk.early_data_indication) {
3809 ret = PTLS_ALERT_DECODE_ERROR;
3810 goto Exit;
3811 }
3812 /* the following check is necessary so that we would be able to track the connection in SSLKEYLOGFILE, even though it
3813 * might not be for the safety of the protocol */
3814 if (!ptls_mem_equal(tls->client_random, ch->random_bytes, sizeof(tls->client_random))) {
3815 ret = PTLS_ALERT_HANDSHAKE_FAILURE;
3816 goto Exit;
3817 }
3818 /* We compare SNI only when the value is saved by the on_client_hello callback. This should be OK because we are
3819 * ignoring the value unless the callback saves the server-name. */
3820 if (tls->server_name != NULL) {
3821 size_t l = strlen(tls->server_name);
3822 if (!(ch->server_name.len == l && memcmp(ch->server_name.base, tls->server_name, l) == 0)) {
3823 ret = PTLS_ALERT_HANDSHAKE_FAILURE;
3824 goto Exit;
3825 }
3826 }
3827 }
3828
3829 { /* select (or check) cipher-suite, create key_schedule */
3830 ptls_cipher_suite_t *cs;
3831 if ((ret = select_cipher(&cs, tls->ctx->cipher_suites, ch->cipher_suites.base,
3832 ch->cipher_suites.base + ch->cipher_suites.len, tls->ctx->server_cipher_preference)) != 0)
3833 goto Exit;
3834 if (!is_second_flight) {
3835 tls->cipher_suite = cs;
3836 tls->key_schedule = key_schedule_new(cs, NULL, tls->ctx->hkdf_label_prefix__obsolete);
3837 } else {
3838 if (tls->cipher_suite != cs) {
3839 ret = PTLS_ALERT_HANDSHAKE_FAILURE;
3840 goto Exit;
3841 }
3842 }
3843 }
3844
3845 /* select key_share */
3846 if (key_share.algorithm == NULL && ch->key_shares.base != NULL) {
3847 const uint8_t *src = ch->key_shares.base, *const end = src + ch->key_shares.len;
3848 ptls_decode_block(src, end, 2, {
3849 if ((ret = select_key_share(&key_share.algorithm, &key_share.peer_key, tls->ctx->key_exchanges, &src, end, 0)) != 0)
3850 goto Exit;
3851 });
3852 }
3853
3854 if (!is_second_flight) {
3855 if (ch->cookie.all.len != 0 && key_share.algorithm != NULL) {
3856
3857 /* use cookie to check the integrity of the handshake, and update the context */
3858 size_t sigsize = tls->ctx->cipher_suites[0]->hash->digest_size;
3859 uint8_t *sig = alloca(sigsize);
3860 if ((ret = calc_cookie_signature(tls, properties, key_share.algorithm, ch->cookie.tbs, sig)) != 0)
3861 goto Exit;
3862 if (!(ch->cookie.signature.len == sigsize && ptls_mem_equal(ch->cookie.signature.base, sig, sigsize))) {
3863 ret = PTLS_ALERT_HANDSHAKE_FAILURE;
3864 goto Exit;
3865 }
3866 /* integrity check passed; update states */
3867 key_schedule_update_ch1hash_prefix(tls->key_schedule);
3868 ptls__key_schedule_update_hash(tls->key_schedule, ch->cookie.ch1_hash.base, ch->cookie.ch1_hash.len);
3869 key_schedule_extract(tls->key_schedule, ptls_iovec_init(NULL, 0));
3870 /* ... reusing sendbuf to rebuild HRR for hash calculation */
3871 size_t hrr_start = emitter->buf->off;
3872 EMIT_HELLO_RETRY_REQUEST(tls->key_schedule, ch->cookie.sent_key_share ? key_share.algorithm : NULL, {
3873 buffer_push_extension(emitter->buf, PTLS_EXTENSION_TYPE_COOKIE,
3874 { ptls_buffer_pushv(emitter->buf, ch->cookie.all.base, ch->cookie.all.len); });
3875 });
3876 emitter->buf->off = hrr_start;
3877 is_second_flight = 1;
3878
3879 } else if (key_share.algorithm == NULL || (properties != NULL && properties->server.enforce_retry)) {
3880
3881 /* send HelloRetryRequest */
3882 if (ch->negotiated_groups.base == NULL) {
3883 ret = PTLS_ALERT_MISSING_EXTENSION;
3884 goto Exit;
3885 }
3886 ptls_key_exchange_algorithm_t *negotiated_group;
3887 if ((ret = select_negotiated_group(&negotiated_group, tls->ctx->key_exchanges, ch->negotiated_groups.base,
3888 ch->negotiated_groups.base + ch->negotiated_groups.len)) != 0)
3889 goto Exit;
3890 ptls__key_schedule_update_hash(tls->key_schedule, message.base, message.len);
3891 assert(tls->key_schedule->generation == 0);
3892 if (properties != NULL && properties->server.retry_uses_cookie) {
3893 /* emit HRR with cookie (note: we MUST omit KeyShare if the client has specified the correct one; see 46554f0)
3894 */
3895 EMIT_HELLO_RETRY_REQUEST(NULL, key_share.algorithm != NULL ? NULL : negotiated_group, {
3896 ptls_buffer_t *sendbuf = emitter->buf;
3897 buffer_push_extension(sendbuf, PTLS_EXTENSION_TYPE_COOKIE, {
3898 ptls_buffer_push_block(sendbuf, 2, {
3899 /* push to-be-signed data */
3900 size_t tbs_start = sendbuf->off;
3901 ptls_buffer_push_block(sendbuf, 2, {
3902 /* first block of the cookie data is the hash(ch1) */
3903 ptls_buffer_push_block(sendbuf, 1, {
3904 size_t sz = tls->cipher_suite->hash->digest_size;
3905 if ((ret = ptls_buffer_reserve(sendbuf, sz)) != 0)
3906 goto Exit;
3907 key_schedule_extract_ch1hash(tls->key_schedule, sendbuf->base + sendbuf->off);
3908 sendbuf->off += sz;
3909 });
3910 /* second is if we have sent key_share extension */
3911 ptls_buffer_push(sendbuf, key_share.algorithm == NULL);
3912 /* we can add more data here */
3913 });
3914 size_t tbs_len = sendbuf->off - tbs_start;
3915 /* push the signature */
3916 ptls_buffer_push_block(sendbuf, 1, {
3917 size_t sz = tls->ctx->cipher_suites[0]->hash->digest_size;
3918 if ((ret = ptls_buffer_reserve(sendbuf, sz)) != 0)
3919 goto Exit;
3920 if ((ret = calc_cookie_signature(tls, properties, negotiated_group,
3921 ptls_iovec_init(sendbuf->base + tbs_start, tbs_len),
3922 sendbuf->base + sendbuf->off)) != 0)
3923 goto Exit;
3924 sendbuf->off += sz;
3925 });
3926 });
3927 });
3928 });
3929 if ((ret = push_change_cipher_spec(tls, emitter)) != 0)
3930 goto Exit;
3931 ret = PTLS_ERROR_STATELESS_RETRY;
3932 } else {
3933 /* invoking stateful retry; roll the key schedule and emit HRR */
3934 key_schedule_transform_post_ch1hash(tls->key_schedule);
3935 key_schedule_extract(tls->key_schedule, ptls_iovec_init(NULL, 0));
3936 EMIT_HELLO_RETRY_REQUEST(tls->key_schedule, key_share.algorithm != NULL ? NULL : negotiated_group, {});
3937 if ((ret = push_change_cipher_spec(tls, emitter)) != 0)
3938 goto Exit;
3939 tls->state = PTLS_STATE_SERVER_EXPECT_SECOND_CLIENT_HELLO;
3940 if (ch->psk.early_data_indication)
3941 tls->server.early_data_skipped_bytes = 0;
3942 ret = PTLS_ERROR_IN_PROGRESS;
3943 }
3944 goto Exit;
3945 }
3946 }
3947
3948 /* handle unknown extensions */
3949 if ((ret = report_unknown_extensions(tls, properties, ch->unknown_extensions)) != 0)
3950 goto Exit;
3951
3952 /* try psk handshake */
3953 if (!is_second_flight && ch->psk.hash_end != 0 &&
3954 (ch->psk.ke_modes & ((1u << PTLS_PSK_KE_MODE_PSK) | (1u << PTLS_PSK_KE_MODE_PSK_DHE))) != 0 &&
3955 tls->ctx->encrypt_ticket != NULL && !tls->ctx->require_client_authentication) {
3956 if ((ret = try_psk_handshake(tls, &psk_index, &accept_early_data, ch,
3957 ptls_iovec_init(message.base, ch->psk.hash_end - message.base))) != 0) {
3958 goto Exit;
3959 }
3960 }
3961
3962 /* If client authentication is enabled, we always force a full handshake.
3963 * TODO: Check for `post_handshake_auth` extension and if that is present, do not force full handshake!
3964 * Remove also the check `!require_client_authentication` above.
3965 *
3966 * adjust key_schedule, determine handshake mode
3967 */
3968 if (psk_index == SIZE_MAX || tls->ctx->require_client_authentication) {
3969 ptls__key_schedule_update_hash(tls->key_schedule, message.base, message.len);
3970 if (!is_second_flight) {
3971 assert(tls->key_schedule->generation == 0);
3972 key_schedule_extract(tls->key_schedule, ptls_iovec_init(NULL, 0));
3973 }
3974 mode = HANDSHAKE_MODE_FULL;
3975 if (properties != NULL)
3976 properties->server.selected_psk_binder.len = 0;
3977 } else {
3978 ptls__key_schedule_update_hash(tls->key_schedule, ch->psk.hash_end, message.base + message.len - ch->psk.hash_end);
3979 if ((ch->psk.ke_modes & (1u << PTLS_PSK_KE_MODE_PSK)) != 0) {
3980 mode = HANDSHAKE_MODE_PSK;
3981 } else {
3982 assert((ch->psk.ke_modes & (1u << PTLS_PSK_KE_MODE_PSK_DHE)) != 0);
3983 mode = HANDSHAKE_MODE_PSK_DHE;
3984 }
3985 tls->is_psk_handshake = 1;
3986 if (properties != NULL) {
3987 ptls_iovec_t *selected = &ch->psk.identities.list[psk_index].binder;
3988 memcpy(properties->server.selected_psk_binder.base, selected->base, selected->len);
3989 properties->server.selected_psk_binder.len = selected->len;
3990 }
3991 }
3992
3993 if (accept_early_data && tls->ctx->max_early_data_size != 0 && psk_index == 0) {
3994 if ((tls->pending_handshake_secret = malloc(PTLS_MAX_DIGEST_SIZE)) == NULL) {
3995 ret = PTLS_ERROR_NO_MEMORY;
3996 goto Exit;
3997 }
3998 if ((ret = derive_exporter_secret(tls, 1)) != 0)
3999 goto Exit;
4000 if ((ret = setup_traffic_protection(tls, 0, "c e traffic", 1, 0)) != 0)
4001 goto Exit;
4002 }
4003
4004 /* run key-exchange, to obtain pubkey and secret */
4005 if (mode != HANDSHAKE_MODE_PSK) {
4006 if (key_share.algorithm == NULL) {
4007 ret = ch->key_shares.base != NULL ? PTLS_ALERT_HANDSHAKE_FAILURE : PTLS_ALERT_MISSING_EXTENSION;
4008 goto Exit;
4009 }
4010 if ((ret = key_share.algorithm->exchange(key_share.algorithm, &pubkey, &ecdh_secret, key_share.peer_key)) != 0)
4011 goto Exit;
4012 tls->key_share = key_share.algorithm;
4013 }
4014
4015 /* send ServerHello */
4016 EMIT_SERVER_HELLO(
4017 tls->key_schedule, { tls->ctx->random_bytes(emitter->buf->base + emitter->buf->off, PTLS_HELLO_RANDOM_SIZE); },
4018 {
4019 ptls_buffer_t *sendbuf = emitter->buf;
4020 if (mode != HANDSHAKE_MODE_PSK) {
4021 buffer_push_extension(sendbuf, PTLS_EXTENSION_TYPE_KEY_SHARE, {
4022 ptls_buffer_push16(sendbuf, key_share.algorithm->id);
4023 ptls_buffer_push_block(sendbuf, 2, { ptls_buffer_pushv(sendbuf, pubkey.base, pubkey.len); });
4024 });
4025 }
4026 if (mode != HANDSHAKE_MODE_FULL) {
4027 buffer_push_extension(sendbuf, PTLS_EXTENSION_TYPE_PRE_SHARED_KEY,
4028 { ptls_buffer_push16(sendbuf, (uint16_t)psk_index); });
4029 }
4030 });
4031 if ((ret = push_change_cipher_spec(tls, emitter)) != 0)
4032 goto Exit;
4033
4034 /* create protection contexts for the handshake */
4035 assert(tls->key_schedule->generation == 1);
4036 key_schedule_extract(tls->key_schedule, ecdh_secret);
4037 if ((ret = setup_traffic_protection(tls, 1, "s hs traffic", 2, 0)) != 0)
4038 goto Exit;
4039 if (tls->pending_handshake_secret != NULL) {
4040 if ((ret = derive_secret(tls->key_schedule, tls->pending_handshake_secret, "c hs traffic")) != 0)
4041 goto Exit;
4042 if (tls->ctx->update_traffic_key != NULL &&
4043 (ret = tls->ctx->update_traffic_key->cb(tls->ctx->update_traffic_key, tls, 0, 2, tls->pending_handshake_secret)) != 0)
4044 goto Exit;
4045 } else {
4046 if ((ret = setup_traffic_protection(tls, 0, "c hs traffic", 2, 0)) != 0)
4047 goto Exit;
4048 if (ch->psk.early_data_indication)
4049 tls->server.early_data_skipped_bytes = 0;
4050 }
4051
4052 /* send EncryptedExtensions */
4053 ptls_push_message(emitter, tls->key_schedule, PTLS_HANDSHAKE_TYPE_ENCRYPTED_EXTENSIONS, {
4054 ptls_buffer_t *sendbuf = emitter->buf;
4055 ptls_buffer_push_block(sendbuf, 2, {
4056 if (tls->esni != NULL) {
4057 /* the extension is sent even if the application does not handle server name, because otherwise the handshake
4058 * would fail (FIXME ch->esni.nonce will be zero on HRR) */
4059 buffer_push_extension(sendbuf, PTLS_EXTENSION_TYPE_ENCRYPTED_SERVER_NAME, {
4060 uint8_t response_type = PTLS_ESNI_RESPONSE_TYPE_ACCEPT;
4061 ptls_buffer_pushv(sendbuf, &response_type, 1);
4062 ptls_buffer_pushv(sendbuf, tls->esni->nonce, PTLS_ESNI_NONCE_SIZE);
4063 });
4064 free_esni_secret(&tls->esni, 1);
4065 } else if (tls->server_name != NULL) {
4066 /* In this event, the server SHALL include an extension of type "server_name" in the (extended) server hello.
4067 * The "extension_data" field of this extension SHALL be empty. (RFC 6066 section 3) */
4068 buffer_push_extension(sendbuf, PTLS_EXTENSION_TYPE_SERVER_NAME, {});
4069 }
4070 if (tls->ctx->use_raw_public_keys) {
4071 buffer_push_extension(sendbuf, PTLS_EXTENSION_TYPE_SERVER_CERTIFICATE_TYPE,
4072 { ptls_buffer_push(sendbuf, PTLS_CERTIFICATE_TYPE_RAW_PUBLIC_KEY); });
4073 }
4074 if (tls->negotiated_protocol != NULL) {
4075 buffer_push_extension(sendbuf, PTLS_EXTENSION_TYPE_ALPN, {
4076 ptls_buffer_push_block(sendbuf, 2, {
4077 ptls_buffer_push_block(sendbuf, 1, {
4078 ptls_buffer_pushv(sendbuf, tls->negotiated_protocol, strlen(tls->negotiated_protocol));
4079 });
4080 });
4081 });
4082 }
4083 if (tls->pending_handshake_secret != NULL)
4084 buffer_push_extension(sendbuf, PTLS_EXTENSION_TYPE_EARLY_DATA, {});
4085 if ((ret = push_additional_extensions(properties, sendbuf)) != 0)
4086 goto Exit;
4087 });
4088 });
4089
4090 if (mode == HANDSHAKE_MODE_FULL) {
4091 /* send certificate request if client authentication is activated */
4092 if (tls->ctx->require_client_authentication) {
4093 ptls_push_message(emitter, tls->key_schedule, PTLS_HANDSHAKE_TYPE_CERTIFICATE_REQUEST, {
4094 /* certificate_request_context, this field SHALL be zero length, unless the certificate
4095 * request is used for post-handshake authentication.
4096 */
4097 ptls_buffer_t *sendbuf = emitter->buf;
4098 ptls_buffer_push(sendbuf, 0);
4099 /* extensions */
4100 ptls_buffer_push_block(sendbuf, 2, {
4101 buffer_push_extension(sendbuf, PTLS_EXTENSION_TYPE_SIGNATURE_ALGORITHMS, {
4102 if ((ret = push_signature_algorithms(tls->ctx->verify_certificate, sendbuf)) != 0)
4103 goto Exit;
4104 });
4105 });
4106 });
4107
4108 if (ret != 0) {
4109 goto Exit;
4110 }
4111 }
4112
4113 ret = send_certificate_and_certificate_verify(tls, emitter, &ch->signature_algorithms, ptls_iovec_init(NULL, 0),
4114 PTLS_SERVER_CERTIFICATE_VERIFY_CONTEXT_STRING, ch->status_request,
4115 ch->cert_compression_algos.list, ch->cert_compression_algos.count);
4116
4117 if (ret != 0) {
4118 goto Exit;
4119 }
4120 }
4121
4122 if ((ret = send_finished(tls, emitter)) != 0)
4123 goto Exit;
4124
4125 assert(tls->key_schedule->generation == 2);
4126 if ((ret = key_schedule_extract(tls->key_schedule, ptls_iovec_init(NULL, 0))) != 0)
4127 goto Exit;
4128 if ((ret = setup_traffic_protection(tls, 1, "s ap traffic", 3, 0)) != 0)
4129 goto Exit;
4130 if ((ret = derive_secret(tls->key_schedule, tls->server.pending_traffic_secret, "c ap traffic")) != 0)
4131 goto Exit;
4132 if ((ret = derive_exporter_secret(tls, 0)) != 0)
4133 goto Exit;
4134
4135 if (tls->pending_handshake_secret != NULL) {
4136 if (tls->ctx->omit_end_of_early_data) {
4137 if ((ret = commission_handshake_secret(tls)) != 0)
4138 goto Exit;
4139 tls->state = PTLS_STATE_SERVER_EXPECT_FINISHED;
4140 } else {
4141 tls->state = PTLS_STATE_SERVER_EXPECT_END_OF_EARLY_DATA;
4142 }
4143 } else if (tls->ctx->require_client_authentication) {
4144 tls->state = PTLS_STATE_SERVER_EXPECT_CERTIFICATE;
4145 } else {
4146 tls->state = PTLS_STATE_SERVER_EXPECT_FINISHED;
4147 }
4148
4149 /* send session ticket if necessary */
4150 if (ch->psk.ke_modes != 0 && tls->ctx->ticket_lifetime != 0) {
4151 if ((ret = send_session_ticket(tls, emitter)) != 0)
4152 goto Exit;
4153 }
4154
4155 if (tls->ctx->require_client_authentication) {
4156 ret = PTLS_ERROR_IN_PROGRESS;
4157 } else {
4158 ret = 0;
4159 }
4160
4161 Exit:
4162 free(pubkey.base);
4163 if (ecdh_secret.base != NULL) {
4164 ptls_clear_memory(ecdh_secret.base, ecdh_secret.len);
4165 free(ecdh_secret.base);
4166 }
4167 free(ch);
4168 return ret;
4169
4170 #undef EMIT_SERVER_HELLO
4171 #undef EMIT_HELLO_RETRY_REQUEST
4172 }
4173
server_handle_end_of_early_data(ptls_t * tls,ptls_iovec_t message)4174 static int server_handle_end_of_early_data(ptls_t *tls, ptls_iovec_t message)
4175 {
4176 int ret;
4177
4178 if ((ret = commission_handshake_secret(tls)) != 0)
4179 goto Exit;
4180
4181 ptls__key_schedule_update_hash(tls->key_schedule, message.base, message.len);
4182 tls->state = PTLS_STATE_SERVER_EXPECT_FINISHED;
4183 ret = PTLS_ERROR_IN_PROGRESS;
4184
4185 Exit:
4186 return ret;
4187 }
4188
server_handle_finished(ptls_t * tls,ptls_iovec_t message)4189 static int server_handle_finished(ptls_t *tls, ptls_iovec_t message)
4190 {
4191 int ret;
4192
4193 if ((ret = verify_finished(tls, message)) != 0)
4194 return ret;
4195
4196 memcpy(tls->traffic_protection.dec.secret, tls->server.pending_traffic_secret, sizeof(tls->server.pending_traffic_secret));
4197 ptls_clear_memory(tls->server.pending_traffic_secret, sizeof(tls->server.pending_traffic_secret));
4198 if ((ret = setup_traffic_protection(tls, 0, NULL, 3, 0)) != 0)
4199 return ret;
4200
4201 ptls__key_schedule_update_hash(tls->key_schedule, message.base, message.len);
4202
4203 tls->state = PTLS_STATE_SERVER_POST_HANDSHAKE;
4204 return 0;
4205 }
4206
update_traffic_key(ptls_t * tls,int is_enc)4207 static int update_traffic_key(ptls_t *tls, int is_enc)
4208 {
4209 struct st_ptls_traffic_protection_t *tp = is_enc ? &tls->traffic_protection.enc : &tls->traffic_protection.dec;
4210 uint8_t secret[PTLS_MAX_DIGEST_SIZE];
4211 int ret;
4212
4213 ptls_hash_algorithm_t *hash = tls->key_schedule->hashes[0].algo;
4214 if ((ret = hkdf_expand_label(hash, secret, hash->digest_size, ptls_iovec_init(tp->secret, hash->digest_size), "traffic upd",
4215 ptls_iovec_init(NULL, 0), tls->key_schedule->hkdf_label_prefix)) != 0)
4216 goto Exit;
4217 memcpy(tp->secret, secret, sizeof(secret));
4218 ret = setup_traffic_protection(tls, is_enc, NULL, 3, 1);
4219
4220 Exit:
4221 ptls_clear_memory(secret, sizeof(secret));
4222 return ret;
4223 }
4224
handle_key_update(ptls_t * tls,ptls_message_emitter_t * emitter,ptls_iovec_t message)4225 static int handle_key_update(ptls_t *tls, ptls_message_emitter_t *emitter, ptls_iovec_t message)
4226 {
4227 const uint8_t *src = message.base + PTLS_HANDSHAKE_HEADER_SIZE, *const end = message.base + message.len;
4228 int ret;
4229
4230 /* validate */
4231 if (end - src != 1 || *src > 1)
4232 return PTLS_ALERT_DECODE_ERROR;
4233
4234 /* update receive key */
4235 if ((ret = update_traffic_key(tls, 0)) != 0)
4236 return ret;
4237
4238 if (*src) {
4239 if (tls->ctx->update_traffic_key != NULL)
4240 return PTLS_ALERT_UNEXPECTED_MESSAGE;
4241 tls->needs_key_update = 1;
4242 }
4243
4244 return 0;
4245 }
4246
parse_record_header(struct st_ptls_record_t * rec,const uint8_t * src)4247 static int parse_record_header(struct st_ptls_record_t *rec, const uint8_t *src)
4248 {
4249 rec->type = src[0];
4250 rec->version = ntoh16(src + 1);
4251 rec->length = ntoh16(src + 3);
4252
4253 if (rec->length >
4254 (size_t)(rec->type == PTLS_CONTENT_TYPE_APPDATA ? PTLS_MAX_ENCRYPTED_RECORD_SIZE : PTLS_MAX_PLAINTEXT_RECORD_SIZE))
4255 return PTLS_ALERT_DECODE_ERROR;
4256
4257 return 0;
4258 }
4259
parse_record(ptls_t * tls,struct st_ptls_record_t * rec,const uint8_t * src,size_t * len)4260 static int parse_record(ptls_t *tls, struct st_ptls_record_t *rec, const uint8_t *src, size_t *len)
4261 {
4262 int ret;
4263
4264 if (tls->recvbuf.rec.base == NULL && *len >= 5) {
4265 /* fast path */
4266 if ((ret = parse_record_header(rec, src)) != 0)
4267 return ret;
4268 if (5 + rec->length <= *len) {
4269 rec->fragment = src + 5;
4270 *len = rec->length + 5;
4271 return 0;
4272 }
4273 }
4274
4275 /* slow path */
4276 const uint8_t *const end = src + *len;
4277 *rec = (struct st_ptls_record_t){0};
4278
4279 if (tls->recvbuf.rec.base == NULL) {
4280 ptls_buffer_init(&tls->recvbuf.rec, "", 0);
4281 if ((ret = ptls_buffer_reserve(&tls->recvbuf.rec, 5)) != 0)
4282 return ret;
4283 }
4284
4285 /* fill and parse the header */
4286 while (tls->recvbuf.rec.off < 5) {
4287 if (src == end)
4288 return PTLS_ERROR_IN_PROGRESS;
4289 tls->recvbuf.rec.base[tls->recvbuf.rec.off++] = *src++;
4290 }
4291 if ((ret = parse_record_header(rec, tls->recvbuf.rec.base)) != 0)
4292 return ret;
4293
4294 /* fill the fragment */
4295 size_t addlen = rec->length + 5 - tls->recvbuf.rec.off;
4296 if (addlen != 0) {
4297 if ((ret = ptls_buffer_reserve(&tls->recvbuf.rec, addlen)) != 0)
4298 return ret;
4299 if (addlen > (size_t)(end - src))
4300 addlen = end - src;
4301 if (addlen != 0) {
4302 memcpy(tls->recvbuf.rec.base + tls->recvbuf.rec.off, src, addlen);
4303 tls->recvbuf.rec.off += addlen;
4304 src += addlen;
4305 }
4306 }
4307
4308 /* set rec->fragment if a complete record has been parsed */
4309 if (tls->recvbuf.rec.off == rec->length + 5) {
4310 rec->fragment = tls->recvbuf.rec.base + 5;
4311 ret = 0;
4312 } else {
4313 ret = PTLS_ERROR_IN_PROGRESS;
4314 }
4315
4316 *len -= end - src;
4317 return ret;
4318 }
4319
update_open_count(ptls_context_t * ctx,ssize_t delta)4320 static void update_open_count(ptls_context_t *ctx, ssize_t delta)
4321 {
4322 if (ctx->update_open_count != NULL)
4323 ctx->update_open_count->cb(ctx->update_open_count, delta);
4324 }
4325
new_instance(ptls_context_t * ctx,int is_server)4326 static ptls_t *new_instance(ptls_context_t *ctx, int is_server)
4327 {
4328 ptls_t *tls;
4329
4330 assert(ctx->get_time != NULL && "please set ctx->get_time to `&ptls_get_time`; see #92");
4331
4332 if ((tls = malloc(sizeof(*tls))) == NULL)
4333 return NULL;
4334
4335 update_open_count(ctx, 1);
4336 *tls = (ptls_t){ctx};
4337 tls->is_server = is_server;
4338 tls->send_change_cipher_spec = ctx->send_change_cipher_spec;
4339 tls->skip_tracing = ptls_default_skip_tracing;
4340 return tls;
4341 }
4342
ptls_client_new(ptls_context_t * ctx)4343 ptls_t *ptls_client_new(ptls_context_t *ctx)
4344 {
4345 ptls_t *tls = new_instance(ctx, 0);
4346 tls->state = PTLS_STATE_CLIENT_HANDSHAKE_START;
4347 tls->ctx->random_bytes(tls->client_random, sizeof(tls->client_random));
4348 log_client_random(tls);
4349 if (tls->send_change_cipher_spec) {
4350 tls->client.legacy_session_id =
4351 ptls_iovec_init(tls->client.legacy_session_id_buf, sizeof(tls->client.legacy_session_id_buf));
4352 tls->ctx->random_bytes(tls->client.legacy_session_id.base, tls->client.legacy_session_id.len);
4353 }
4354
4355 PTLS_PROBE(NEW, tls, 0);
4356 return tls;
4357 }
4358
ptls_server_new(ptls_context_t * ctx)4359 ptls_t *ptls_server_new(ptls_context_t *ctx)
4360 {
4361 ptls_t *tls = new_instance(ctx, 1);
4362 tls->state = PTLS_STATE_SERVER_EXPECT_CLIENT_HELLO;
4363 tls->server.early_data_skipped_bytes = UINT32_MAX;
4364
4365 PTLS_PROBE(NEW, tls, 1);
4366 return tls;
4367 }
4368
ptls_free(ptls_t * tls)4369 void ptls_free(ptls_t *tls)
4370 {
4371 PTLS_PROBE0(FREE, tls);
4372 ptls_buffer_dispose(&tls->recvbuf.rec);
4373 ptls_buffer_dispose(&tls->recvbuf.mess);
4374 free_exporter_master_secret(tls, 1);
4375 free_exporter_master_secret(tls, 0);
4376 if (tls->esni != NULL)
4377 free_esni_secret(&tls->esni, tls->is_server);
4378 if (tls->key_schedule != NULL)
4379 key_schedule_free(tls->key_schedule);
4380 if (tls->traffic_protection.dec.aead != NULL)
4381 ptls_aead_free(tls->traffic_protection.dec.aead);
4382 if (tls->traffic_protection.enc.aead != NULL)
4383 ptls_aead_free(tls->traffic_protection.enc.aead);
4384 free(tls->server_name);
4385 free(tls->negotiated_protocol);
4386 if (tls->is_server) {
4387 /* nothing to do */
4388 } else {
4389 if (tls->client.key_share_ctx != NULL)
4390 tls->client.key_share_ctx->on_exchange(&tls->client.key_share_ctx, 1, NULL, ptls_iovec_init(NULL, 0));
4391 if (tls->client.certificate_request.context.base != NULL)
4392 free(tls->client.certificate_request.context.base);
4393 }
4394 if (tls->certificate_verify.cb != NULL) {
4395 tls->certificate_verify.cb(tls->certificate_verify.verify_ctx, 0, ptls_iovec_init(NULL, 0), ptls_iovec_init(NULL, 0));
4396 }
4397 if (tls->pending_handshake_secret != NULL) {
4398 ptls_clear_memory(tls->pending_handshake_secret, PTLS_MAX_DIGEST_SIZE);
4399 free(tls->pending_handshake_secret);
4400 }
4401 update_open_count(tls->ctx, -1);
4402 ptls_clear_memory(tls, sizeof(*tls));
4403 free(tls);
4404 }
4405
ptls_get_context(ptls_t * tls)4406 ptls_context_t *ptls_get_context(ptls_t *tls)
4407 {
4408 return tls->ctx;
4409 }
4410
ptls_set_context(ptls_t * tls,ptls_context_t * ctx)4411 void ptls_set_context(ptls_t *tls, ptls_context_t *ctx)
4412 {
4413 update_open_count(ctx, 1);
4414 update_open_count(tls->ctx, -1);
4415 tls->ctx = ctx;
4416 }
4417
ptls_get_client_random(ptls_t * tls)4418 ptls_iovec_t ptls_get_client_random(ptls_t *tls)
4419 {
4420 return ptls_iovec_init(tls->client_random, PTLS_HELLO_RANDOM_SIZE);
4421 }
4422
ptls_get_cipher(ptls_t * tls)4423 ptls_cipher_suite_t *ptls_get_cipher(ptls_t *tls)
4424 {
4425 return tls->cipher_suite;
4426 }
4427
ptls_get_server_name(ptls_t * tls)4428 const char *ptls_get_server_name(ptls_t *tls)
4429 {
4430 return tls->server_name;
4431 }
4432
ptls_set_server_name(ptls_t * tls,const char * server_name,size_t server_name_len)4433 int ptls_set_server_name(ptls_t *tls, const char *server_name, size_t server_name_len)
4434 {
4435 char *duped = NULL;
4436
4437 if (server_name != NULL) {
4438 if (server_name_len == 0)
4439 server_name_len = strlen(server_name);
4440 if ((duped = malloc(server_name_len + 1)) == NULL)
4441 return PTLS_ERROR_NO_MEMORY;
4442 memcpy(duped, server_name, server_name_len);
4443 duped[server_name_len] = '\0';
4444 }
4445
4446 free(tls->server_name);
4447 tls->server_name = duped;
4448
4449 return 0;
4450 }
4451
ptls_get_negotiated_protocol(ptls_t * tls)4452 const char *ptls_get_negotiated_protocol(ptls_t *tls)
4453 {
4454 return tls->negotiated_protocol;
4455 }
4456
ptls_set_negotiated_protocol(ptls_t * tls,const char * protocol,size_t protocol_len)4457 int ptls_set_negotiated_protocol(ptls_t *tls, const char *protocol, size_t protocol_len)
4458 {
4459 char *duped = NULL;
4460
4461 if (protocol != NULL) {
4462 if (protocol_len == 0)
4463 protocol_len = strlen(protocol);
4464 if ((duped = malloc(protocol_len + 1)) == NULL)
4465 return PTLS_ERROR_NO_MEMORY;
4466 memcpy(duped, protocol, protocol_len);
4467 duped[protocol_len] = '\0';
4468 }
4469
4470 free(tls->negotiated_protocol);
4471 tls->negotiated_protocol = duped;
4472
4473 return 0;
4474 }
4475
ptls_handshake_is_complete(ptls_t * tls)4476 int ptls_handshake_is_complete(ptls_t *tls)
4477 {
4478 return tls->state >= PTLS_STATE_POST_HANDSHAKE_MIN;
4479 }
4480
ptls_is_psk_handshake(ptls_t * tls)4481 int ptls_is_psk_handshake(ptls_t *tls)
4482 {
4483 return tls->is_psk_handshake;
4484 }
4485
ptls_get_data_ptr(ptls_t * tls)4486 void **ptls_get_data_ptr(ptls_t *tls)
4487 {
4488 return &tls->data_ptr;
4489 }
4490
ptls_skip_tracing(ptls_t * tls)4491 int ptls_skip_tracing(ptls_t *tls)
4492 {
4493 return tls->skip_tracing;
4494 }
4495
ptls_set_skip_tracing(ptls_t * tls,int skip_tracing)4496 void ptls_set_skip_tracing(ptls_t *tls, int skip_tracing)
4497 {
4498 tls->skip_tracing = skip_tracing;
4499 }
4500
handle_client_handshake_message(ptls_t * tls,ptls_message_emitter_t * emitter,ptls_iovec_t message,int is_end_of_record,ptls_handshake_properties_t * properties)4501 static int handle_client_handshake_message(ptls_t *tls, ptls_message_emitter_t *emitter, ptls_iovec_t message, int is_end_of_record,
4502 ptls_handshake_properties_t *properties)
4503 {
4504 uint8_t type = message.base[0];
4505 int ret;
4506
4507 switch (tls->state) {
4508 case PTLS_STATE_CLIENT_EXPECT_SERVER_HELLO:
4509 case PTLS_STATE_CLIENT_EXPECT_SECOND_SERVER_HELLO:
4510 if (type == PTLS_HANDSHAKE_TYPE_SERVER_HELLO && is_end_of_record) {
4511 ret = client_handle_hello(tls, emitter, message, properties);
4512 } else {
4513 ret = PTLS_ALERT_UNEXPECTED_MESSAGE;
4514 }
4515 break;
4516 case PTLS_STATE_CLIENT_EXPECT_ENCRYPTED_EXTENSIONS:
4517 if (type == PTLS_HANDSHAKE_TYPE_ENCRYPTED_EXTENSIONS) {
4518 ret = client_handle_encrypted_extensions(tls, message, properties);
4519 } else {
4520 ret = PTLS_ALERT_UNEXPECTED_MESSAGE;
4521 }
4522 break;
4523 case PTLS_STATE_CLIENT_EXPECT_CERTIFICATE_REQUEST_OR_CERTIFICATE:
4524 if (type == PTLS_HANDSHAKE_TYPE_CERTIFICATE_REQUEST) {
4525 ret = client_handle_certificate_request(tls, message, properties);
4526 break;
4527 }
4528 /* fall through */
4529 case PTLS_STATE_CLIENT_EXPECT_CERTIFICATE:
4530 switch (type) {
4531 case PTLS_HANDSHAKE_TYPE_CERTIFICATE:
4532 ret = client_handle_certificate(tls, message);
4533 break;
4534 case PTLS_HANDSHAKE_TYPE_COMPRESSED_CERTIFICATE:
4535 ret = client_handle_compressed_certificate(tls, message);
4536 break;
4537 default:
4538 ret = PTLS_ALERT_UNEXPECTED_MESSAGE;
4539 break;
4540 }
4541 break;
4542 case PTLS_STATE_CLIENT_EXPECT_CERTIFICATE_VERIFY:
4543 if (type == PTLS_HANDSHAKE_TYPE_CERTIFICATE_VERIFY) {
4544 ret = client_handle_certificate_verify(tls, message);
4545 } else {
4546 ret = PTLS_ALERT_UNEXPECTED_MESSAGE;
4547 }
4548 break;
4549 case PTLS_STATE_CLIENT_EXPECT_FINISHED:
4550 if (type == PTLS_HANDSHAKE_TYPE_FINISHED && is_end_of_record) {
4551 ret = client_handle_finished(tls, emitter, message);
4552 } else {
4553 ret = PTLS_ALERT_UNEXPECTED_MESSAGE;
4554 }
4555 break;
4556 case PTLS_STATE_CLIENT_POST_HANDSHAKE:
4557 switch (type) {
4558 case PTLS_HANDSHAKE_TYPE_NEW_SESSION_TICKET:
4559 ret = client_handle_new_session_ticket(tls, message);
4560 break;
4561 case PTLS_HANDSHAKE_TYPE_KEY_UPDATE:
4562 ret = handle_key_update(tls, emitter, message);
4563 break;
4564 default:
4565 ret = PTLS_ALERT_UNEXPECTED_MESSAGE;
4566 break;
4567 }
4568 break;
4569 default:
4570 assert(!"unexpected state");
4571 ret = PTLS_ALERT_INTERNAL_ERROR;
4572 break;
4573 }
4574
4575 PTLS_PROBE(RECEIVE_MESSAGE, tls, message.base[0], message.base + PTLS_HANDSHAKE_HEADER_SIZE,
4576 message.len - PTLS_HANDSHAKE_HEADER_SIZE, ret);
4577
4578 return ret;
4579 }
4580
handle_server_handshake_message(ptls_t * tls,ptls_message_emitter_t * emitter,ptls_iovec_t message,int is_end_of_record,ptls_handshake_properties_t * properties)4581 static int handle_server_handshake_message(ptls_t *tls, ptls_message_emitter_t *emitter, ptls_iovec_t message, int is_end_of_record,
4582 ptls_handshake_properties_t *properties)
4583 {
4584 uint8_t type = message.base[0];
4585 int ret;
4586
4587 switch (tls->state) {
4588 case PTLS_STATE_SERVER_EXPECT_CLIENT_HELLO:
4589 case PTLS_STATE_SERVER_EXPECT_SECOND_CLIENT_HELLO:
4590 if (type == PTLS_HANDSHAKE_TYPE_CLIENT_HELLO && is_end_of_record) {
4591 ret = server_handle_hello(tls, emitter, message, properties);
4592 } else {
4593 ret = PTLS_ALERT_HANDSHAKE_FAILURE;
4594 }
4595 break;
4596 case PTLS_STATE_SERVER_EXPECT_CERTIFICATE:
4597 if (type == PTLS_HANDSHAKE_TYPE_CERTIFICATE) {
4598 ret = server_handle_certificate(tls, message);
4599 } else {
4600 ret = PTLS_ALERT_UNEXPECTED_MESSAGE;
4601 }
4602 break;
4603 case PTLS_STATE_SERVER_EXPECT_CERTIFICATE_VERIFY:
4604 if (type == PTLS_HANDSHAKE_TYPE_CERTIFICATE_VERIFY) {
4605 ret = server_handle_certificate_verify(tls, message);
4606 } else {
4607 ret = PTLS_ALERT_UNEXPECTED_MESSAGE;
4608 }
4609 break;
4610 case PTLS_STATE_SERVER_EXPECT_END_OF_EARLY_DATA:
4611 assert(!tls->ctx->omit_end_of_early_data);
4612 if (type == PTLS_HANDSHAKE_TYPE_END_OF_EARLY_DATA) {
4613 ret = server_handle_end_of_early_data(tls, message);
4614 } else {
4615 ret = PTLS_ALERT_UNEXPECTED_MESSAGE;
4616 }
4617 break;
4618 case PTLS_STATE_SERVER_EXPECT_FINISHED:
4619 if (type == PTLS_HANDSHAKE_TYPE_FINISHED && is_end_of_record) {
4620 ret = server_handle_finished(tls, message);
4621 } else {
4622 ret = PTLS_ALERT_HANDSHAKE_FAILURE;
4623 }
4624 break;
4625 case PTLS_STATE_SERVER_POST_HANDSHAKE:
4626 switch (type) {
4627 case PTLS_HANDSHAKE_TYPE_KEY_UPDATE:
4628 ret = handle_key_update(tls, emitter, message);
4629 break;
4630 default:
4631 ret = PTLS_ALERT_UNEXPECTED_MESSAGE;
4632 break;
4633 }
4634 break;
4635 default:
4636 assert(!"unexpected state");
4637 ret = PTLS_ALERT_INTERNAL_ERROR;
4638 break;
4639 }
4640
4641 PTLS_PROBE(RECEIVE_MESSAGE, tls, message.base[0], message.base + PTLS_HANDSHAKE_HEADER_SIZE,
4642 message.len - PTLS_HANDSHAKE_HEADER_SIZE, ret);
4643
4644 return ret;
4645 }
4646
handle_alert(ptls_t * tls,const uint8_t * src,size_t len)4647 static int handle_alert(ptls_t *tls, const uint8_t *src, size_t len)
4648 {
4649 if (len != 2)
4650 return PTLS_ALERT_DECODE_ERROR;
4651
4652 uint8_t desc = src[1];
4653
4654 /* all fatal alerts and USER_CANCELLED warning tears down the connection immediately, regardless of the transmitted level */
4655 return PTLS_ALERT_TO_PEER_ERROR(desc);
4656 }
4657
message_buffer_is_overflow(ptls_context_t * ctx,size_t size)4658 static int message_buffer_is_overflow(ptls_context_t *ctx, size_t size)
4659 {
4660 if (ctx->max_buffer_size == 0)
4661 return 0;
4662 if (size <= ctx->max_buffer_size)
4663 return 0;
4664 return 1;
4665 }
4666
handle_handshake_record(ptls_t * tls,int (* cb)(ptls_t * tls,ptls_message_emitter_t * emitter,ptls_iovec_t message,int is_end_of_record,ptls_handshake_properties_t * properties),ptls_message_emitter_t * emitter,struct st_ptls_record_t * rec,ptls_handshake_properties_t * properties)4667 static int handle_handshake_record(ptls_t *tls,
4668 int (*cb)(ptls_t *tls, ptls_message_emitter_t *emitter, ptls_iovec_t message,
4669 int is_end_of_record, ptls_handshake_properties_t *properties),
4670 ptls_message_emitter_t *emitter, struct st_ptls_record_t *rec,
4671 ptls_handshake_properties_t *properties)
4672 {
4673 int ret;
4674
4675 /* handshake */
4676 if (rec->type != PTLS_CONTENT_TYPE_HANDSHAKE)
4677 return PTLS_ALERT_DECODE_ERROR;
4678
4679 /* flatten the unhandled messages */
4680 const uint8_t *src, *src_end;
4681 if (tls->recvbuf.mess.base == NULL) {
4682 src = rec->fragment;
4683 src_end = src + rec->length;
4684 } else {
4685 if (message_buffer_is_overflow(tls->ctx, tls->recvbuf.mess.off + rec->length))
4686 return PTLS_ALERT_HANDSHAKE_FAILURE;
4687 if ((ret = ptls_buffer_reserve(&tls->recvbuf.mess, rec->length)) != 0)
4688 return ret;
4689 memcpy(tls->recvbuf.mess.base + tls->recvbuf.mess.off, rec->fragment, rec->length);
4690 tls->recvbuf.mess.off += rec->length;
4691 src = tls->recvbuf.mess.base;
4692 src_end = src + tls->recvbuf.mess.off;
4693 }
4694
4695 /* handle the messages */
4696 ret = PTLS_ERROR_IN_PROGRESS;
4697 while (src_end - src >= 4) {
4698 size_t mess_len = 4 + ntoh24(src + 1);
4699 if (src_end - src < (int)mess_len)
4700 break;
4701 ret = cb(tls, emitter, ptls_iovec_init(src, mess_len), src_end - src == mess_len, properties);
4702 switch (ret) {
4703 case 0:
4704 case PTLS_ERROR_IN_PROGRESS:
4705 break;
4706 default:
4707 ptls_buffer_dispose(&tls->recvbuf.mess);
4708 return ret;
4709 }
4710 src += mess_len;
4711 }
4712
4713 /* keep last partial message in buffer */
4714 if (src != src_end) {
4715 size_t new_size = src_end - src;
4716 if (message_buffer_is_overflow(tls->ctx, new_size))
4717 return PTLS_ALERT_HANDSHAKE_FAILURE;
4718 if (tls->recvbuf.mess.base == NULL) {
4719 ptls_buffer_init(&tls->recvbuf.mess, "", 0);
4720 if ((ret = ptls_buffer_reserve(&tls->recvbuf.mess, new_size)) != 0)
4721 return ret;
4722 memcpy(tls->recvbuf.mess.base, src, new_size);
4723 } else {
4724 memmove(tls->recvbuf.mess.base, src, new_size);
4725 }
4726 tls->recvbuf.mess.off = new_size;
4727 ret = PTLS_ERROR_IN_PROGRESS;
4728 } else {
4729 ptls_buffer_dispose(&tls->recvbuf.mess);
4730 }
4731
4732 return ret;
4733 }
4734
handle_input(ptls_t * tls,ptls_message_emitter_t * emitter,ptls_buffer_t * decryptbuf,const void * input,size_t * inlen,ptls_handshake_properties_t * properties)4735 static int handle_input(ptls_t *tls, ptls_message_emitter_t *emitter, ptls_buffer_t *decryptbuf, const void *input, size_t *inlen,
4736 ptls_handshake_properties_t *properties)
4737 {
4738 struct st_ptls_record_t rec;
4739 int ret;
4740
4741 /* extract the record */
4742 if ((ret = parse_record(tls, &rec, input, inlen)) != 0)
4743 return ret;
4744 assert(rec.fragment != NULL);
4745
4746 /* decrypt the record */
4747 if (rec.type == PTLS_CONTENT_TYPE_CHANGE_CIPHER_SPEC) {
4748 if (tls->state < PTLS_STATE_POST_HANDSHAKE_MIN) {
4749 if (!(rec.length == 1 && rec.fragment[0] == 0x01))
4750 return PTLS_ALERT_ILLEGAL_PARAMETER;
4751 } else {
4752 return PTLS_ALERT_HANDSHAKE_FAILURE;
4753 }
4754 ret = PTLS_ERROR_IN_PROGRESS;
4755 goto NextRecord;
4756 }
4757 if (tls->traffic_protection.dec.aead != NULL && rec.type != PTLS_CONTENT_TYPE_ALERT) {
4758 size_t decrypted_length;
4759 if (rec.type != PTLS_CONTENT_TYPE_APPDATA)
4760 return PTLS_ALERT_HANDSHAKE_FAILURE;
4761 if ((ret = ptls_buffer_reserve(decryptbuf, 5 + rec.length)) != 0)
4762 return ret;
4763 if ((ret = aead_decrypt(&tls->traffic_protection.dec, decryptbuf->base + decryptbuf->off, &decrypted_length, rec.fragment,
4764 rec.length)) != 0) {
4765 if (tls->is_server && tls->server.early_data_skipped_bytes != UINT32_MAX)
4766 goto ServerSkipEarlyData;
4767 return ret;
4768 }
4769 rec.length = decrypted_length;
4770 rec.fragment = decryptbuf->base + decryptbuf->off;
4771 /* skip padding */
4772 for (; rec.length != 0; --rec.length)
4773 if (rec.fragment[rec.length - 1] != 0)
4774 break;
4775 if (rec.length == 0)
4776 return PTLS_ALERT_UNEXPECTED_MESSAGE;
4777 rec.type = rec.fragment[--rec.length];
4778 } else if (rec.type == PTLS_CONTENT_TYPE_APPDATA && tls->is_server && tls->server.early_data_skipped_bytes != UINT32_MAX) {
4779 goto ServerSkipEarlyData;
4780 }
4781
4782 if (tls->recvbuf.mess.base != NULL || rec.type == PTLS_CONTENT_TYPE_HANDSHAKE) {
4783 /* handshake record */
4784 ret = handle_handshake_record(tls, tls->is_server ? handle_server_handshake_message : handle_client_handshake_message,
4785 emitter, &rec, properties);
4786 } else {
4787 /* handling of an alert or an application record */
4788 switch (rec.type) {
4789 case PTLS_CONTENT_TYPE_APPDATA:
4790 if (tls->state >= PTLS_STATE_POST_HANDSHAKE_MIN) {
4791 decryptbuf->off += rec.length;
4792 ret = 0;
4793 } else if (tls->state == PTLS_STATE_SERVER_EXPECT_END_OF_EARLY_DATA) {
4794 if (tls->traffic_protection.dec.aead != NULL)
4795 decryptbuf->off += rec.length;
4796 ret = 0;
4797 } else {
4798 ret = PTLS_ALERT_UNEXPECTED_MESSAGE;
4799 }
4800 break;
4801 case PTLS_CONTENT_TYPE_ALERT:
4802 ret = handle_alert(tls, rec.fragment, rec.length);
4803 break;
4804 default:
4805 ret = PTLS_ALERT_UNEXPECTED_MESSAGE;
4806 break;
4807 }
4808 }
4809
4810 NextRecord:
4811 ptls_buffer_dispose(&tls->recvbuf.rec);
4812 return ret;
4813
4814 ServerSkipEarlyData:
4815 tls->server.early_data_skipped_bytes += (uint32_t)rec.length;
4816 if (tls->server.early_data_skipped_bytes > PTLS_MAX_EARLY_DATA_SKIP_SIZE)
4817 return PTLS_ALERT_HANDSHAKE_FAILURE;
4818 ret = PTLS_ERROR_IN_PROGRESS;
4819 goto NextRecord;
4820 }
4821
init_record_message_emitter(ptls_t * tls,struct st_ptls_record_message_emitter_t * emitter,ptls_buffer_t * sendbuf)4822 static void init_record_message_emitter(ptls_t *tls, struct st_ptls_record_message_emitter_t *emitter, ptls_buffer_t *sendbuf)
4823 {
4824 *emitter = (struct st_ptls_record_message_emitter_t){
4825 {sendbuf, &tls->traffic_protection.enc, 5, begin_record_message, commit_record_message}};
4826 }
4827
ptls_handshake(ptls_t * tls,ptls_buffer_t * _sendbuf,const void * input,size_t * inlen,ptls_handshake_properties_t * properties)4828 int ptls_handshake(ptls_t *tls, ptls_buffer_t *_sendbuf, const void *input, size_t *inlen, ptls_handshake_properties_t *properties)
4829 {
4830 struct st_ptls_record_message_emitter_t emitter;
4831 int ret;
4832
4833 assert(tls->state < PTLS_STATE_POST_HANDSHAKE_MIN);
4834
4835 init_record_message_emitter(tls, &emitter, _sendbuf);
4836 size_t sendbuf_orig_off = emitter.super.buf->off;
4837
4838 /* special handlings */
4839 switch (tls->state) {
4840 case PTLS_STATE_CLIENT_HANDSHAKE_START: {
4841 assert(input == NULL || *inlen == 0);
4842 assert(tls->ctx->key_exchanges[0] != NULL);
4843 return send_client_hello(tls, &emitter.super, properties, NULL);
4844 }
4845 default:
4846 break;
4847 }
4848
4849 const uint8_t *src = input, *const src_end = src + *inlen;
4850 ptls_buffer_t decryptbuf;
4851
4852 ptls_buffer_init(&decryptbuf, "", 0);
4853
4854 /* perform handhake until completion or until all the input has been swallowed */
4855 ret = PTLS_ERROR_IN_PROGRESS;
4856 while (ret == PTLS_ERROR_IN_PROGRESS && src != src_end) {
4857 size_t consumed = src_end - src;
4858 ret = handle_input(tls, &emitter.super, &decryptbuf, src, &consumed, properties);
4859 src += consumed;
4860 assert(decryptbuf.off == 0);
4861 }
4862
4863 ptls_buffer_dispose(&decryptbuf);
4864
4865 switch (ret) {
4866 case 0:
4867 case PTLS_ERROR_IN_PROGRESS:
4868 case PTLS_ERROR_STATELESS_RETRY:
4869 break;
4870 default:
4871 /* flush partially written response */
4872 ptls_clear_memory(emitter.super.buf->base + sendbuf_orig_off, emitter.super.buf->off - sendbuf_orig_off);
4873 emitter.super.buf->off = sendbuf_orig_off;
4874 /* send alert immediately */
4875 if (PTLS_ERROR_GET_CLASS(ret) != PTLS_ERROR_CLASS_PEER_ALERT)
4876 if (ptls_send_alert(tls, emitter.super.buf, PTLS_ALERT_LEVEL_FATAL,
4877 PTLS_ERROR_GET_CLASS(ret) == PTLS_ERROR_CLASS_SELF_ALERT ? ret : PTLS_ALERT_INTERNAL_ERROR) != 0)
4878 emitter.super.buf->off = sendbuf_orig_off;
4879 break;
4880 }
4881
4882 *inlen -= src_end - src;
4883 return ret;
4884 }
4885
ptls_receive(ptls_t * tls,ptls_buffer_t * decryptbuf,const void * _input,size_t * inlen)4886 int ptls_receive(ptls_t *tls, ptls_buffer_t *decryptbuf, const void *_input, size_t *inlen)
4887 {
4888 const uint8_t *input = (const uint8_t *)_input, *const end = input + *inlen;
4889 size_t decryptbuf_orig_size = decryptbuf->off;
4890 int ret = 0;
4891
4892 assert(tls->state >= PTLS_STATE_SERVER_EXPECT_END_OF_EARLY_DATA);
4893
4894 /* loop until we decrypt some application data (or an error) */
4895 while (ret == 0 && input != end && decryptbuf_orig_size == decryptbuf->off) {
4896 size_t consumed = end - input;
4897 ret = handle_input(tls, NULL, decryptbuf, input, &consumed, NULL);
4898 input += consumed;
4899
4900 switch (ret) {
4901 case 0:
4902 break;
4903 case PTLS_ERROR_IN_PROGRESS:
4904 ret = 0;
4905 break;
4906 case PTLS_ERROR_CLASS_PEER_ALERT + PTLS_ALERT_CLOSE_NOTIFY:
4907 /* TODO send close alert */
4908 break;
4909 default:
4910 if (PTLS_ERROR_GET_CLASS(ret) == PTLS_ERROR_CLASS_SELF_ALERT) {
4911 /* TODO send alert */
4912 }
4913 break;
4914 }
4915 }
4916
4917 *inlen -= end - input;
4918
4919 return ret;
4920 }
4921
update_send_key(ptls_t * tls,ptls_buffer_t * _sendbuf,int request_update)4922 static int update_send_key(ptls_t *tls, ptls_buffer_t *_sendbuf, int request_update)
4923 {
4924 struct st_ptls_record_message_emitter_t emitter;
4925 int ret;
4926
4927 init_record_message_emitter(tls, &emitter, _sendbuf);
4928 size_t sendbuf_orig_off = emitter.super.buf->off;
4929
4930 ptls_push_message(&emitter.super, NULL, PTLS_HANDSHAKE_TYPE_KEY_UPDATE,
4931 { ptls_buffer_push(emitter.super.buf, !!request_update); });
4932 if ((ret = update_traffic_key(tls, 1)) != 0)
4933 goto Exit;
4934 ret = 0;
4935
4936 Exit:
4937 if (ret != 0)
4938 emitter.super.buf->off = sendbuf_orig_off;
4939 return ret;
4940 }
4941
ptls_send(ptls_t * tls,ptls_buffer_t * sendbuf,const void * input,size_t inlen)4942 int ptls_send(ptls_t *tls, ptls_buffer_t *sendbuf, const void *input, size_t inlen)
4943 {
4944 assert(tls->traffic_protection.enc.aead != NULL);
4945
4946 /* "For AES-GCM, up to 2^24.5 full-size records (about 24 million) may be encrypted on a given connection while keeping a
4947 * safety margin of approximately 2^-57 for Authenticated Encryption (AE) security." (RFC 8446 section 5.5)
4948 */
4949 if (tls->traffic_protection.enc.seq >= 16777216)
4950 tls->needs_key_update = 1;
4951
4952 if (tls->needs_key_update) {
4953 int ret;
4954 if ((ret = update_send_key(tls, sendbuf, tls->key_update_send_request)) != 0)
4955 return ret;
4956 tls->needs_key_update = 0;
4957 tls->key_update_send_request = 0;
4958 }
4959
4960 return buffer_push_encrypted_records(sendbuf, PTLS_CONTENT_TYPE_APPDATA, input, inlen, &tls->traffic_protection.enc);
4961 }
4962
ptls_update_key(ptls_t * tls,int request_update)4963 int ptls_update_key(ptls_t *tls, int request_update)
4964 {
4965 assert(tls->ctx->update_traffic_key == NULL);
4966 tls->needs_key_update = 1;
4967 tls->key_update_send_request = request_update;
4968 return 0;
4969 }
4970
ptls_get_record_overhead(ptls_t * tls)4971 size_t ptls_get_record_overhead(ptls_t *tls)
4972 {
4973 return 6 + tls->traffic_protection.enc.aead->algo->tag_size;
4974 }
4975
ptls_send_alert(ptls_t * tls,ptls_buffer_t * sendbuf,uint8_t level,uint8_t description)4976 int ptls_send_alert(ptls_t *tls, ptls_buffer_t *sendbuf, uint8_t level, uint8_t description)
4977 {
4978 size_t rec_start = sendbuf->off;
4979 int ret = 0;
4980
4981 buffer_push_record(sendbuf, PTLS_CONTENT_TYPE_ALERT, { ptls_buffer_push(sendbuf, level, description); });
4982 /* encrypt the alert if we have the encryption keys, unless when it is the early data key */
4983 if (tls->traffic_protection.enc.aead != NULL && !(tls->state <= PTLS_STATE_CLIENT_EXPECT_FINISHED)) {
4984 if ((ret = buffer_encrypt_record(sendbuf, rec_start, &tls->traffic_protection.enc)) != 0)
4985 goto Exit;
4986 }
4987
4988 Exit:
4989 return ret;
4990 }
4991
ptls_export_secret(ptls_t * tls,void * output,size_t outlen,const char * label,ptls_iovec_t context_value,int is_early)4992 int ptls_export_secret(ptls_t *tls, void *output, size_t outlen, const char *label, ptls_iovec_t context_value, int is_early)
4993 {
4994 ptls_hash_algorithm_t *algo = tls->key_schedule->hashes[0].algo;
4995 uint8_t *master_secret = is_early ? tls->exporter_master_secret.early : tls->exporter_master_secret.one_rtt,
4996 derived_secret[PTLS_MAX_DIGEST_SIZE], context_value_hash[PTLS_MAX_DIGEST_SIZE];
4997 int ret;
4998
4999 if (master_secret == NULL) {
5000 if (is_early) {
5001 switch (tls->state) {
5002 case PTLS_STATE_CLIENT_HANDSHAKE_START:
5003 case PTLS_STATE_SERVER_EXPECT_CLIENT_HELLO:
5004 ret = PTLS_ERROR_IN_PROGRESS;
5005 break;
5006 default:
5007 ret = PTLS_ERROR_NOT_AVAILABLE;
5008 break;
5009 }
5010 } else {
5011 ret = PTLS_ERROR_IN_PROGRESS;
5012 }
5013 return ret;
5014 }
5015
5016 if ((ret = ptls_calc_hash(algo, context_value_hash, context_value.base, context_value.len)) != 0)
5017 return ret;
5018
5019 if ((ret = hkdf_expand_label(algo, derived_secret, algo->digest_size, ptls_iovec_init(master_secret, algo->digest_size), label,
5020 ptls_iovec_init(algo->empty_digest, algo->digest_size), tls->key_schedule->hkdf_label_prefix)) !=
5021 0)
5022 goto Exit;
5023 ret = hkdf_expand_label(algo, output, outlen, ptls_iovec_init(derived_secret, algo->digest_size), "exporter",
5024 ptls_iovec_init(context_value_hash, algo->digest_size), tls->key_schedule->hkdf_label_prefix);
5025
5026 Exit:
5027 ptls_clear_memory(derived_secret, sizeof(derived_secret));
5028 ptls_clear_memory(context_value_hash, sizeof(context_value_hash));
5029 return ret;
5030 }
5031
5032 struct st_picotls_hmac_context_t {
5033 ptls_hash_context_t super;
5034 ptls_hash_algorithm_t *algo;
5035 ptls_hash_context_t *hash;
5036 uint8_t key[1];
5037 };
5038
hmac_update(ptls_hash_context_t * _ctx,const void * src,size_t len)5039 static void hmac_update(ptls_hash_context_t *_ctx, const void *src, size_t len)
5040 {
5041 struct st_picotls_hmac_context_t *ctx = (struct st_picotls_hmac_context_t *)_ctx;
5042 ctx->hash->update(ctx->hash, src, len);
5043 }
5044
hmac_apply_key(struct st_picotls_hmac_context_t * ctx,uint8_t pad)5045 static void hmac_apply_key(struct st_picotls_hmac_context_t *ctx, uint8_t pad)
5046 {
5047 size_t i;
5048
5049 for (i = 0; i != ctx->algo->block_size; ++i)
5050 ctx->key[i] ^= pad;
5051 ctx->hash->update(ctx->hash, ctx->key, ctx->algo->block_size);
5052 for (i = 0; i != ctx->algo->block_size; ++i)
5053 ctx->key[i] ^= pad;
5054 }
5055
hmac_final(ptls_hash_context_t * _ctx,void * md,ptls_hash_final_mode_t mode)5056 static void hmac_final(ptls_hash_context_t *_ctx, void *md, ptls_hash_final_mode_t mode)
5057 {
5058 struct st_picotls_hmac_context_t *ctx = (struct st_picotls_hmac_context_t *)_ctx;
5059
5060 assert(mode != PTLS_HASH_FINAL_MODE_SNAPSHOT || !"not supported");
5061
5062 if (md != NULL) {
5063 ctx->hash->final(ctx->hash, md, PTLS_HASH_FINAL_MODE_RESET);
5064 hmac_apply_key(ctx, 0x5c);
5065 ctx->hash->update(ctx->hash, md, ctx->algo->digest_size);
5066 }
5067 ctx->hash->final(ctx->hash, md, mode);
5068
5069 switch (mode) {
5070 case PTLS_HASH_FINAL_MODE_FREE:
5071 ptls_clear_memory(ctx->key, ctx->algo->block_size);
5072 free(ctx);
5073 break;
5074 case PTLS_HASH_FINAL_MODE_RESET:
5075 hmac_apply_key(ctx, 0x36);
5076 break;
5077 default:
5078 assert(!"FIXME");
5079 break;
5080 }
5081 }
5082
ptls_calc_hash(ptls_hash_algorithm_t * algo,void * output,const void * src,size_t len)5083 int ptls_calc_hash(ptls_hash_algorithm_t *algo, void *output, const void *src, size_t len)
5084 {
5085 ptls_hash_context_t *ctx;
5086
5087 if ((ctx = algo->create()) == NULL)
5088 return PTLS_ERROR_NO_MEMORY;
5089 ctx->update(ctx, src, len);
5090 ctx->final(ctx, output, PTLS_HASH_FINAL_MODE_FREE);
5091 return 0;
5092 }
5093
ptls_hmac_create(ptls_hash_algorithm_t * algo,const void * key,size_t key_size)5094 ptls_hash_context_t *ptls_hmac_create(ptls_hash_algorithm_t *algo, const void *key, size_t key_size)
5095 {
5096 struct st_picotls_hmac_context_t *ctx;
5097
5098 assert(key_size <= algo->block_size);
5099
5100 if ((ctx = malloc(offsetof(struct st_picotls_hmac_context_t, key) + algo->block_size)) == NULL)
5101 return NULL;
5102
5103 *ctx = (struct st_picotls_hmac_context_t){{hmac_update, hmac_final}, algo};
5104 if ((ctx->hash = algo->create()) == NULL) {
5105 free(ctx);
5106 return NULL;
5107 }
5108 memset(ctx->key, 0, algo->block_size);
5109 memcpy(ctx->key, key, key_size);
5110
5111 hmac_apply_key(ctx, 0x36);
5112
5113 return &ctx->super;
5114 }
5115
ptls_hkdf_extract(ptls_hash_algorithm_t * algo,void * output,ptls_iovec_t salt,ptls_iovec_t ikm)5116 int ptls_hkdf_extract(ptls_hash_algorithm_t *algo, void *output, ptls_iovec_t salt, ptls_iovec_t ikm)
5117 {
5118 ptls_hash_context_t *hash;
5119
5120 if (salt.len == 0)
5121 salt = ptls_iovec_init(zeroes_of_max_digest_size, algo->digest_size);
5122
5123 if ((hash = ptls_hmac_create(algo, salt.base, salt.len)) == NULL)
5124 return PTLS_ERROR_NO_MEMORY;
5125 hash->update(hash, ikm.base, ikm.len);
5126 hash->final(hash, output, PTLS_HASH_FINAL_MODE_FREE);
5127 return 0;
5128 }
5129
ptls_hkdf_expand(ptls_hash_algorithm_t * algo,void * output,size_t outlen,ptls_iovec_t prk,ptls_iovec_t info)5130 int ptls_hkdf_expand(ptls_hash_algorithm_t *algo, void *output, size_t outlen, ptls_iovec_t prk, ptls_iovec_t info)
5131 {
5132 ptls_hash_context_t *hmac = NULL;
5133 size_t i;
5134 uint8_t digest[PTLS_MAX_DIGEST_SIZE];
5135
5136 for (i = 0; (i * algo->digest_size) < outlen; ++i) {
5137 if (hmac == NULL) {
5138 if ((hmac = ptls_hmac_create(algo, prk.base, prk.len)) == NULL)
5139 return PTLS_ERROR_NO_MEMORY;
5140 } else {
5141 hmac->update(hmac, digest, algo->digest_size);
5142 }
5143 hmac->update(hmac, info.base, info.len);
5144 uint8_t gen = (uint8_t)(i + 1);
5145 hmac->update(hmac, &gen, 1);
5146 hmac->final(hmac, digest, 1);
5147
5148 size_t off_start = i * algo->digest_size, off_end = off_start + algo->digest_size;
5149 if (off_end > outlen)
5150 off_end = outlen;
5151 memcpy((uint8_t *)output + off_start, digest, off_end - off_start);
5152 }
5153
5154 if (hmac != NULL)
5155 hmac->final(hmac, NULL, PTLS_HASH_FINAL_MODE_FREE);
5156
5157 ptls_clear_memory(digest, algo->digest_size);
5158
5159 return 0;
5160 }
5161
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,const char * label_prefix)5162 int hkdf_expand_label(ptls_hash_algorithm_t *algo, void *output, size_t outlen, ptls_iovec_t secret, const char *label,
5163 ptls_iovec_t hash_value, const char *label_prefix)
5164 {
5165 ptls_buffer_t hkdf_label;
5166 uint8_t hkdf_label_buf[80];
5167 int ret;
5168
5169 assert(label_prefix != NULL);
5170
5171 ptls_buffer_init(&hkdf_label, hkdf_label_buf, sizeof(hkdf_label_buf));
5172
5173 ptls_buffer_push16(&hkdf_label, (uint16_t)outlen);
5174 ptls_buffer_push_block(&hkdf_label, 1, {
5175 ptls_buffer_pushv(&hkdf_label, label_prefix, strlen(label_prefix));
5176 ptls_buffer_pushv(&hkdf_label, label, strlen(label));
5177 });
5178 ptls_buffer_push_block(&hkdf_label, 1, { ptls_buffer_pushv(&hkdf_label, hash_value.base, hash_value.len); });
5179
5180 ret = ptls_hkdf_expand(algo, output, outlen, secret, ptls_iovec_init(hkdf_label.base, hkdf_label.off));
5181
5182 Exit:
5183 ptls_buffer_dispose(&hkdf_label);
5184 return ret;
5185 }
5186
ptls_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,const char * label_prefix)5187 int ptls_hkdf_expand_label(ptls_hash_algorithm_t *algo, void *output, size_t outlen, ptls_iovec_t secret, const char *label,
5188 ptls_iovec_t hash_value, const char *label_prefix)
5189 {
5190 /* the handshake layer should call hkdf_expand_label directly, always setting key_schedule->hkdf_label_prefix as the
5191 * argument */
5192 if (label_prefix == NULL)
5193 label_prefix = PTLS_HKDF_EXPAND_LABEL_PREFIX;
5194 return hkdf_expand_label(algo, output, outlen, secret, label, hash_value, label_prefix);
5195 }
5196
ptls_cipher_new(ptls_cipher_algorithm_t * algo,int is_enc,const void * key)5197 ptls_cipher_context_t *ptls_cipher_new(ptls_cipher_algorithm_t *algo, int is_enc, const void *key)
5198 {
5199 ptls_cipher_context_t *ctx;
5200
5201 if ((ctx = (ptls_cipher_context_t *)malloc(algo->context_size)) == NULL)
5202 return NULL;
5203 *ctx = (ptls_cipher_context_t){algo};
5204 if (algo->setup_crypto(ctx, is_enc, key) != 0) {
5205 free(ctx);
5206 ctx = NULL;
5207 }
5208 return ctx;
5209 }
5210
ptls_cipher_free(ptls_cipher_context_t * ctx)5211 void ptls_cipher_free(ptls_cipher_context_t *ctx)
5212 {
5213 ctx->do_dispose(ctx);
5214 free(ctx);
5215 }
5216
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)5217 ptls_aead_context_t *new_aead(ptls_aead_algorithm_t *aead, ptls_hash_algorithm_t *hash, int is_enc, const void *secret,
5218 ptls_iovec_t hash_value, const char *label_prefix)
5219 {
5220 ptls_aead_context_t *ctx = NULL;
5221 uint8_t key_iv[PTLS_MAX_SECRET_SIZE + PTLS_MAX_IV_SIZE];
5222 int ret;
5223
5224 if ((ret = get_traffic_key(hash, key_iv, aead->key_size, 0, secret, hash_value, label_prefix)) != 0)
5225 goto Exit;
5226 if ((ret = get_traffic_key(hash, key_iv + aead->key_size, aead->iv_size, 1, secret, hash_value, label_prefix)) != 0)
5227 goto Exit;
5228 ctx = ptls_aead_new_direct(aead, is_enc, key_iv, key_iv + aead->key_size);
5229
5230 Exit:
5231 ptls_clear_memory(key_iv, sizeof(key_iv));
5232 return ctx;
5233 }
5234
ptls_aead_new(ptls_aead_algorithm_t * aead,ptls_hash_algorithm_t * hash,int is_enc,const void * secret,const char * label_prefix)5235 ptls_aead_context_t *ptls_aead_new(ptls_aead_algorithm_t *aead, ptls_hash_algorithm_t *hash, int is_enc, const void *secret,
5236 const char *label_prefix)
5237 {
5238 return new_aead(aead, hash, is_enc, secret, ptls_iovec_init(NULL, 0), label_prefix);
5239 }
5240
ptls_aead_new_direct(ptls_aead_algorithm_t * aead,int is_enc,const void * key,const void * iv)5241 ptls_aead_context_t *ptls_aead_new_direct(ptls_aead_algorithm_t *aead, int is_enc, const void *key, const void *iv)
5242 {
5243 ptls_aead_context_t *ctx;
5244
5245 if ((ctx = (ptls_aead_context_t *)malloc(aead->context_size)) == NULL)
5246 return NULL;
5247
5248 *ctx = (ptls_aead_context_t){aead};
5249
5250 if (aead->setup_crypto(ctx, is_enc, key, iv) != 0) {
5251 free(ctx);
5252 return NULL;
5253 }
5254
5255 return ctx;
5256 }
5257
ptls_aead_free(ptls_aead_context_t * ctx)5258 void ptls_aead_free(ptls_aead_context_t *ctx)
5259 {
5260 ctx->dispose_crypto(ctx);
5261 free(ctx);
5262 }
5263
ptls_aead__build_iv(ptls_aead_algorithm_t * algo,uint8_t * iv,const uint8_t * static_iv,uint64_t seq)5264 void ptls_aead__build_iv(ptls_aead_algorithm_t *algo, uint8_t *iv, const uint8_t *static_iv, uint64_t seq)
5265 {
5266 size_t iv_size = algo->iv_size, i;
5267 const uint8_t *s = static_iv;
5268 uint8_t *d = iv;
5269
5270 /* build iv */
5271 for (i = iv_size - 8; i != 0; --i)
5272 *d++ = *s++;
5273 i = 64;
5274 do {
5275 i -= 8;
5276 *d++ = *s++ ^ (uint8_t)(seq >> i);
5277 } while (i != 0);
5278 }
5279
clear_memory(void * p,size_t len)5280 static void clear_memory(void *p, size_t len)
5281 {
5282 if (len != 0)
5283 memset(p, 0, len);
5284 }
5285
5286 void (*volatile ptls_clear_memory)(void *p, size_t len) = clear_memory;
5287
mem_equal(const void * _x,const void * _y,size_t len)5288 static int mem_equal(const void *_x, const void *_y, size_t len)
5289 {
5290 const volatile uint8_t *x = _x, *y = _y;
5291 uint8_t t = 0;
5292
5293 for (; len != 0; --len)
5294 t |= *x++ ^ *y++;
5295
5296 return t == 0;
5297 }
5298
5299 int (*volatile ptls_mem_equal)(const void *x, const void *y, size_t len) = mem_equal;
5300
get_time(ptls_get_time_t * self)5301 static uint64_t get_time(ptls_get_time_t *self)
5302 {
5303 struct timeval tv;
5304 gettimeofday(&tv, NULL);
5305 return (uint64_t)tv.tv_sec * 1000 + tv.tv_usec / 1000;
5306 }
5307
5308 ptls_get_time_t ptls_get_time = {get_time};
5309 #if PICOTLS_USE_DTRACE
5310 PTLS_THREADLOCAL unsigned ptls_default_skip_tracing = 0;
5311 #endif
5312
ptls_is_server(ptls_t * tls)5313 int ptls_is_server(ptls_t *tls)
5314 {
5315 return tls->is_server;
5316 }
5317
5318 struct st_ptls_raw_message_emitter_t {
5319 ptls_message_emitter_t super;
5320 size_t start_off;
5321 size_t *epoch_offsets;
5322 };
5323
begin_raw_message(ptls_message_emitter_t * _self)5324 static int begin_raw_message(ptls_message_emitter_t *_self)
5325 {
5326 struct st_ptls_raw_message_emitter_t *self = (void *)_self;
5327
5328 self->start_off = self->super.buf->off;
5329 return 0;
5330 }
5331
commit_raw_message(ptls_message_emitter_t * _self)5332 static int commit_raw_message(ptls_message_emitter_t *_self)
5333 {
5334 struct st_ptls_raw_message_emitter_t *self = (void *)_self;
5335 size_t epoch;
5336
5337 /* epoch is the key epoch, with the only exception being 2nd CH generated after 0-RTT key */
5338 epoch = self->super.enc->epoch;
5339 if (epoch == 1 && self->super.buf->base[self->start_off] == PTLS_HANDSHAKE_TYPE_CLIENT_HELLO)
5340 epoch = 0;
5341
5342 for (++epoch; epoch < 5; ++epoch) {
5343 assert(self->epoch_offsets[epoch] == self->start_off);
5344 self->epoch_offsets[epoch] = self->super.buf->off;
5345 }
5346
5347 self->start_off = SIZE_MAX;
5348
5349 return 0;
5350 }
5351
ptls_get_read_epoch(ptls_t * tls)5352 size_t ptls_get_read_epoch(ptls_t *tls)
5353 {
5354 switch (tls->state) {
5355 case PTLS_STATE_CLIENT_HANDSHAKE_START:
5356 case PTLS_STATE_CLIENT_EXPECT_SERVER_HELLO:
5357 case PTLS_STATE_CLIENT_EXPECT_SECOND_SERVER_HELLO:
5358 case PTLS_STATE_SERVER_EXPECT_CLIENT_HELLO:
5359 case PTLS_STATE_SERVER_EXPECT_SECOND_CLIENT_HELLO:
5360 return 0; /* plaintext */
5361 case PTLS_STATE_SERVER_EXPECT_END_OF_EARLY_DATA:
5362 assert(!tls->ctx->omit_end_of_early_data);
5363 return 1; /* 0-rtt */
5364 case PTLS_STATE_CLIENT_EXPECT_ENCRYPTED_EXTENSIONS:
5365 case PTLS_STATE_CLIENT_EXPECT_CERTIFICATE_REQUEST_OR_CERTIFICATE:
5366 case PTLS_STATE_CLIENT_EXPECT_CERTIFICATE:
5367 case PTLS_STATE_CLIENT_EXPECT_CERTIFICATE_VERIFY:
5368 case PTLS_STATE_CLIENT_EXPECT_FINISHED:
5369 case PTLS_STATE_SERVER_EXPECT_CERTIFICATE:
5370 case PTLS_STATE_SERVER_EXPECT_CERTIFICATE_VERIFY:
5371 case PTLS_STATE_SERVER_EXPECT_FINISHED:
5372 return 2; /* handshake */
5373 case PTLS_STATE_CLIENT_POST_HANDSHAKE:
5374 case PTLS_STATE_SERVER_POST_HANDSHAKE:
5375 return 3; /* 1-rtt */
5376 default:
5377 assert(!"invalid state");
5378 return SIZE_MAX;
5379 }
5380 }
5381
ptls_handle_message(ptls_t * tls,ptls_buffer_t * sendbuf,size_t epoch_offsets[5],size_t in_epoch,const void * input,size_t inlen,ptls_handshake_properties_t * properties)5382 int ptls_handle_message(ptls_t *tls, ptls_buffer_t *sendbuf, size_t epoch_offsets[5], size_t in_epoch, const void *input,
5383 size_t inlen, ptls_handshake_properties_t *properties)
5384 {
5385 return tls->is_server ? ptls_server_handle_message(tls, sendbuf, epoch_offsets, in_epoch, input, inlen, properties)
5386 : ptls_client_handle_message(tls, sendbuf, epoch_offsets, in_epoch, input, inlen, properties);
5387 }
5388
ptls_client_handle_message(ptls_t * tls,ptls_buffer_t * sendbuf,size_t epoch_offsets[5],size_t in_epoch,const void * input,size_t inlen,ptls_handshake_properties_t * properties)5389 int ptls_client_handle_message(ptls_t *tls, ptls_buffer_t *sendbuf, size_t epoch_offsets[5], size_t in_epoch, const void *input,
5390 size_t inlen, ptls_handshake_properties_t *properties)
5391 {
5392 assert(!tls->is_server);
5393
5394 struct st_ptls_raw_message_emitter_t emitter = {
5395 {sendbuf, &tls->traffic_protection.enc, 0, begin_raw_message, commit_raw_message}, SIZE_MAX, epoch_offsets};
5396 struct st_ptls_record_t rec = {PTLS_CONTENT_TYPE_HANDSHAKE, 0, inlen, input};
5397
5398 if (input == NULL)
5399 return send_client_hello(tls, &emitter.super, properties, NULL);
5400
5401 if (ptls_get_read_epoch(tls) != in_epoch)
5402 return PTLS_ALERT_UNEXPECTED_MESSAGE;
5403
5404 return handle_handshake_record(tls, handle_client_handshake_message, &emitter.super, &rec, properties);
5405 }
5406
ptls_server_handle_message(ptls_t * tls,ptls_buffer_t * sendbuf,size_t epoch_offsets[5],size_t in_epoch,const void * input,size_t inlen,ptls_handshake_properties_t * properties)5407 int ptls_server_handle_message(ptls_t *tls, ptls_buffer_t *sendbuf, size_t epoch_offsets[5], size_t in_epoch, const void *input,
5408 size_t inlen, ptls_handshake_properties_t *properties)
5409 {
5410 assert(tls->is_server);
5411
5412 struct st_ptls_raw_message_emitter_t emitter = {
5413 {sendbuf, &tls->traffic_protection.enc, 0, begin_raw_message, commit_raw_message}, SIZE_MAX, epoch_offsets};
5414 struct st_ptls_record_t rec = {PTLS_CONTENT_TYPE_HANDSHAKE, 0, inlen, input};
5415
5416 assert(input);
5417
5418 if (ptls_get_read_epoch(tls) != in_epoch)
5419 return PTLS_ALERT_UNEXPECTED_MESSAGE;
5420
5421 return handle_handshake_record(tls, handle_server_handshake_message, &emitter.super, &rec, properties);
5422 }
5423
ptls_esni_init_context(ptls_context_t * ctx,ptls_esni_context_t * esni,ptls_iovec_t esni_keys,ptls_key_exchange_context_t ** key_exchanges)5424 int ptls_esni_init_context(ptls_context_t *ctx, ptls_esni_context_t *esni, ptls_iovec_t esni_keys,
5425 ptls_key_exchange_context_t **key_exchanges)
5426 {
5427 const uint8_t *src = esni_keys.base, *const end = src + esni_keys.len;
5428 size_t num_key_exchanges, num_cipher_suites = 0;
5429 int ret;
5430
5431 for (num_key_exchanges = 0; key_exchanges[num_key_exchanges] != NULL; ++num_key_exchanges)
5432 ;
5433
5434 memset(esni, 0, sizeof(*esni));
5435 if ((esni->key_exchanges = malloc(sizeof(*esni->key_exchanges) * (num_key_exchanges + 1))) == NULL) {
5436 ret = PTLS_ERROR_NO_MEMORY;
5437 goto Exit;
5438 }
5439 memcpy(esni->key_exchanges, key_exchanges, sizeof(*esni->key_exchanges) * (num_key_exchanges + 1));
5440
5441 /* ESNIKeys */
5442 if ((ret = ptls_decode16(&esni->version, &src, end)) != 0)
5443 goto Exit;
5444 /* Skip checksum fields */
5445 if (end - src < 4) {
5446 ret = PTLS_ALERT_DECRYPT_ERROR;
5447 goto Exit;
5448 }
5449 src += 4;
5450 /* Published SNI field */
5451 ptls_decode_open_block(src, end, 2, { src = end; });
5452
5453 /* Process the list of KeyShareEntries, verify for each of them that the ciphersuite is supported. */
5454 ptls_decode_open_block(src, end, 2, {
5455 do {
5456 /* parse */
5457 uint16_t id;
5458 if ((ret = ptls_decode16(&id, &src, end)) != 0)
5459 goto Exit;
5460 ptls_decode_open_block(src, end, 2, { src = end; });
5461 /* check that matching key-share exists */
5462 ptls_key_exchange_context_t **found;
5463 for (found = key_exchanges; *found != NULL; ++found)
5464 if ((*found)->algo->id == id)
5465 break;
5466 if (found == NULL) {
5467 ret = PTLS_ERROR_INCOMPATIBLE_KEY;
5468 goto Exit;
5469 }
5470 } while (src != end);
5471 });
5472 /* Process the list of cipher_suites. If they are supported, store in esni context */
5473 ptls_decode_open_block(src, end, 2, {
5474 void *newp;
5475 do {
5476 uint16_t id;
5477 if ((ret = ptls_decode16(&id, &src, end)) != 0)
5478 goto Exit;
5479 size_t i;
5480 for (i = 0; ctx->cipher_suites[i] != NULL; ++i)
5481 if (ctx->cipher_suites[i]->id == id)
5482 break;
5483 if (ctx->cipher_suites[i] != NULL) {
5484 if ((newp = realloc(esni->cipher_suites, sizeof(*esni->cipher_suites) * (num_cipher_suites + 1))) == NULL) {
5485 ret = PTLS_ERROR_NO_MEMORY;
5486 goto Exit;
5487 }
5488 esni->cipher_suites = newp;
5489 esni->cipher_suites[num_cipher_suites++].cipher_suite = ctx->cipher_suites[i];
5490 }
5491 } while (src != end);
5492 if ((newp = realloc(esni->cipher_suites, sizeof(*esni->cipher_suites) * (num_cipher_suites + 1))) == NULL) {
5493 ret = PTLS_ERROR_NO_MEMORY;
5494 goto Exit;
5495 }
5496 esni->cipher_suites = newp;
5497 esni->cipher_suites[num_cipher_suites].cipher_suite = NULL;
5498 });
5499 /* Parse the padded length, not before, not after parameters */
5500 if ((ret = ptls_decode16(&esni->padded_length, &src, end)) != 0)
5501 goto Exit;
5502 if ((ret = ptls_decode64(&esni->not_before, &src, end)) != 0)
5503 goto Exit;
5504 if ((ret = ptls_decode64(&esni->not_after, &src, end)) != 0)
5505 goto Exit;
5506 /* Skip the extension fields */
5507 ptls_decode_block(src, end, 2, {
5508 while (src != end) {
5509 uint16_t ext_type;
5510 if ((ret = ptls_decode16(&ext_type, &src, end)) != 0)
5511 goto Exit;
5512 ptls_decode_open_block(src, end, 2, { src = end; });
5513 }
5514 });
5515
5516 { /* calculate digests for every cipher-suite */
5517 size_t i;
5518 for (i = 0; esni->cipher_suites[i].cipher_suite != NULL; ++i) {
5519 if ((ret = ptls_calc_hash(esni->cipher_suites[i].cipher_suite->hash, esni->cipher_suites[i].record_digest,
5520 esni_keys.base, esni_keys.len)) != 0)
5521 goto Exit;
5522 }
5523 }
5524
5525 ret = 0;
5526 Exit:
5527 if (ret != 0)
5528 ptls_esni_dispose_context(esni);
5529 return ret;
5530 }
5531
ptls_esni_dispose_context(ptls_esni_context_t * esni)5532 void ptls_esni_dispose_context(ptls_esni_context_t *esni)
5533 {
5534 size_t i;
5535
5536 if (esni->key_exchanges != NULL) {
5537 for (i = 0; esni->key_exchanges[i] != NULL; ++i)
5538 esni->key_exchanges[i]->on_exchange(esni->key_exchanges + i, 1, NULL, ptls_iovec_init(NULL, 0));
5539 free(esni->key_exchanges);
5540 }
5541 free(esni->cipher_suites);
5542 }
5543
5544 /**
5545 * Obtain the ESNI secrets negotiated during the handshake.
5546 */
ptls_get_esni_secret(ptls_t * ctx)5547 ptls_esni_secret_t *ptls_get_esni_secret(ptls_t *ctx)
5548 {
5549 return ctx->esni;
5550 }
5551
5552 /**
5553 * checks if given name looks like an IP address
5554 */
ptls_server_name_is_ipaddr(const char * name)5555 int ptls_server_name_is_ipaddr(const char *name)
5556 {
5557 #ifdef AF_INET
5558 struct sockaddr_in sin;
5559 if (inet_pton(AF_INET, name, &sin) == 1)
5560 return 1;
5561 #endif
5562 #ifdef AF_INET6
5563 struct sockaddr_in6 sin6;
5564 if (inet_pton(AF_INET6, name, &sin6) == 1)
5565 return 1;
5566 #endif
5567 return 0;
5568 }
5569
ptls_hexdump(char * buf,const void * _src,size_t len)5570 char *ptls_hexdump(char *buf, const void *_src, size_t len)
5571 {
5572 char *dst = buf;
5573 const uint8_t *src = _src;
5574 size_t i;
5575
5576 for (i = 0; i != len; ++i) {
5577 *dst++ = "0123456789abcdef"[src[i] >> 4];
5578 *dst++ = "0123456789abcdef"[src[i] & 0xf];
5579 }
5580 *dst++ = '\0';
5581 return buf;
5582 }
5583