Coverage Report

Created: 2026-08-13 07:17

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/h2o/deps/picotls/lib/picotls.c
Line
Count
Source
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
#ifdef _WINDOWS
23
#include "wincompat.h"
24
#endif
25
#include <assert.h>
26
#include <stdarg.h>
27
#include <stddef.h>
28
#include <stdio.h>
29
#include <stdlib.h>
30
#include <string.h>
31
#ifndef _WINDOWS
32
#include <errno.h>
33
#include <pthread.h>
34
#include <unistd.h>
35
#include <sys/socket.h>
36
#include <arpa/inet.h>
37
#include <netinet/in.h>
38
#include <sys/time.h>
39
#include <sys/types.h>
40
#endif
41
#ifdef __linux__
42
#include <sys/syscall.h>
43
#endif
44
#ifdef __APPLE__
45
#include <AvailabilityMacros.h>
46
#endif
47
#include "picotls.h"
48
#if PICOTLS_USE_DTRACE
49
#include "picotls-probes.h"
50
#endif
51
52
0
#define PTLS_MAX_PLAINTEXT_RECORD_SIZE 16384
53
0
#define PTLS_MAX_ENCRYPTED_RECORD_SIZE (16384 + 256)
54
55
0
#define PTLS_RECORD_VERSION_MAJOR 3
56
0
#define PTLS_RECORD_VERSION_MINOR 3
57
58
0
#define PTLS_CONTENT_TYPE_CHANGE_CIPHER_SPEC 20
59
0
#define PTLS_CONTENT_TYPE_ALERT 21
60
0
#define PTLS_CONTENT_TYPE_HANDSHAKE 22
61
0
#define PTLS_CONTENT_TYPE_APPDATA 23
62
63
0
#define PTLS_PSK_KE_MODE_PSK 0
64
0
#define PTLS_PSK_KE_MODE_PSK_DHE 1
65
66
0
#define PTLS_HANDSHAKE_HEADER_SIZE 4
67
68
#define PTLS_EXTENSION_TYPE_SERVER_NAME 0
69
#define PTLS_EXTENSION_TYPE_STATUS_REQUEST 5
70
#define PTLS_EXTENSION_TYPE_SUPPORTED_GROUPS 10
71
#define PTLS_EXTENSION_TYPE_SIGNATURE_ALGORITHMS 13
72
#define PTLS_EXTENSION_TYPE_ALPN 16
73
#define PTLS_EXTENSION_TYPE_SERVER_CERTIFICATE_TYPE 20
74
#define PTLS_EXTENSION_TYPE_COMPRESS_CERTIFICATE 27
75
#define PTLS_EXTENSION_TYPE_PRE_SHARED_KEY 41
76
#define PTLS_EXTENSION_TYPE_EARLY_DATA 42
77
#define PTLS_EXTENSION_TYPE_SUPPORTED_VERSIONS 43
78
#define PTLS_EXTENSION_TYPE_COOKIE 44
79
#define PTLS_EXTENSION_TYPE_PSK_KEY_EXCHANGE_MODES 45
80
#define PTLS_EXTENSION_TYPE_CERTIFICATE_AUTHORITIES 47
81
#define PTLS_EXTENSION_TYPE_KEY_SHARE 51
82
#define PTLS_EXTENSION_TYPE_TICKET_REQUEST 58
83
#define PTLS_EXTENSION_TYPE_ECH_OUTER_EXTENSIONS 0xfd00
84
#define PTLS_EXTENSION_TYPE_ENCRYPTED_CLIENT_HELLO 0xfe0d
85
86
#define PTLS_SERVER_NAME_TYPE_HOSTNAME 0
87
88
#define PTLS_ECH_CONFIG_VERSION 0xfe0d
89
0
#define PTLS_ECH_CLIENT_HELLO_TYPE_OUTER 0
90
0
#define PTLS_ECH_CLIENT_HELLO_TYPE_INNER 1
91
92
0
#define PTLS_ECH_CONFIRM_LENGTH 8
93
94
static const char ech_info_prefix[8] = "tls ech";
95
96
0
#define PTLS_SERVER_CERTIFICATE_VERIFY_CONTEXT_STRING "TLS 1.3, server CertificateVerify"
97
0
#define PTLS_CLIENT_CERTIFICATE_VERIFY_CONTEXT_STRING "TLS 1.3, client CertificateVerify"
98
#define PTLS_MAX_CERTIFICATE_VERIFY_SIGNDATA_SIZE                                                                                  \
99
    (64 + sizeof(PTLS_SERVER_CERTIFICATE_VERIFY_CONTEXT_STRING) + PTLS_MAX_DIGEST_SIZE * 2)
100
101
0
#define PTLS_EARLY_DATA_MAX_DELAY 10000 /* max. RTT (in msec) to permit early data */
102
103
#ifndef PTLS_MAX_EARLY_DATA_SKIP_SIZE
104
0
#define PTLS_MAX_EARLY_DATA_SKIP_SIZE 65536
105
#endif
106
#if defined(PTLS_DEBUG) && PTLS_DEBUG
107
#define PTLS_DEBUGF(...) fprintf(stderr, __VA_ARGS__)
108
#else
109
#define PTLS_DEBUGF(...)
110
#endif
111
112
#ifndef PTLS_MEMORY_DEBUG
113
113k
#define PTLS_MEMORY_DEBUG 0
114
#endif
115
116
#if PICOTLS_USE_DTRACE
117
#define PTLS_PROBE0(LABEL, tls)                                                                                                    \
118
    do {                                                                                                                           \
119
        if (PTLS_UNLIKELY(PICOTLS_##LABEL##_ENABLED()))                                                                            \
120
            PICOTLS_##LABEL(tls);                                                                                                  \
121
    } while (0)
122
#define PTLS_PROBE(LABEL, tls, ...)                                                                                                \
123
    do {                                                                                                                           \
124
        if (PTLS_UNLIKELY(PICOTLS_##LABEL##_ENABLED()))                                                                            \
125
            PICOTLS_##LABEL((tls), __VA_ARGS__);                                                                                   \
126
    } while (0)
127
#else
128
#define PTLS_PROBE0(LABEL, tls)
129
#define PTLS_PROBE(LABEL, tls, ...)
130
#endif
131
132
/**
133
 * list of supported versions in the preferred order
134
 */
135
static const uint16_t supported_versions[] = {PTLS_PROTOCOL_VERSION_TLS13};
136
137
static const uint8_t hello_retry_random[PTLS_HELLO_RANDOM_SIZE] = {0xCF, 0x21, 0xAD, 0x74, 0xE5, 0x9A, 0x61, 0x11, 0xBE, 0x1D, 0x8C,
138
                                                                   0x02, 0x1E, 0x65, 0xB8, 0x91, 0xC2, 0xA2, 0x11, 0x16, 0x7A, 0xBB,
139
                                                                   0x8C, 0x5E, 0x07, 0x9E, 0x09, 0xE2, 0xC8, 0xA8, 0x33, 0x9C};
140
141
struct st_ptls_traffic_protection_t {
142
    uint8_t secret[PTLS_MAX_DIGEST_SIZE];
143
    size_t epoch;
144
    /* the following fields are not used if the key_change callback is set */
145
    ptls_aead_context_t *aead;
146
    uint64_t seq;
147
    unsigned tls12 : 1;
148
    uint64_t tls12_enc_record_iv;
149
};
150
151
struct st_ptls_record_message_emitter_t {
152
    ptls_message_emitter_t super;
153
    size_t rec_start;
154
};
155
156
struct st_ptls_signature_algorithms_t {
157
    uint16_t list[PTLS_MAX_SIGNATURE_ALGORITHMS];
158
    size_t count;
159
};
160
161
struct st_ptls_certificate_request_t {
162
    /**
163
     * context.base becomes non-NULL when a CertificateRequest is pending for processing
164
     */
165
    ptls_iovec_t context;
166
    struct st_ptls_signature_algorithms_t signature_algorithms;
167
};
168
169
struct st_decoded_ech_config_t {
170
    uint8_t id;
171
    ptls_hpke_kem_t *kem;
172
    ptls_iovec_t public_key;
173
    ptls_hpke_cipher_suite_t *cipher;
174
    uint8_t max_name_length;
175
    ptls_iovec_t public_name;
176
    ptls_iovec_t bytes;
177
};
178
179
/**
180
 * Properties for ECH. Iff ECH is used and not rejected, `aead` is non-NULL.
181
 */
182
struct st_ptls_ech_t {
183
    /**
184
     * ECH state for this connection. `OFFERED` and `ACCEPTED` are used on both client and server; `GREASE` is client-only (server
185
     * cannot distinguish GREASE from a config mismatch, both are simply ECH that fails to decrypt).
186
     */
187
    enum en_ptls_ech_state_t {
188
        PTLS_ECH_STATE_NONE = 0,
189
        PTLS_ECH_STATE_OFFERED,
190
        PTLS_ECH_STATE_ACCEPTED,
191
        PTLS_ECH_STATE_GREASE
192
    } state;
193
    uint8_t config_id;
194
    ptls_hpke_kem_t *kem;
195
    ptls_hpke_cipher_suite_t *cipher;
196
    ptls_aead_context_t *aead;
197
    uint8_t inner_client_random[PTLS_HELLO_RANDOM_SIZE];
198
    struct {
199
        ptls_iovec_t enc;
200
        uint8_t max_name_length;
201
        char *public_name;
202
        /**
203
         * retains a copy of entire ECH extension so that it can be replayed in the 2nd CH when ECH is rejected via HRR
204
         */
205
        ptls_iovec_t first_ech;
206
    } client;
207
};
208
209
struct st_ptls_t {
210
    /**
211
     * the context
212
     */
213
    ptls_context_t *ctx;
214
    /**
215
     * the state
216
     */
217
    enum en_ptls_state_t {
218
        PTLS_STATE_CLIENT_HANDSHAKE_START,
219
        PTLS_STATE_CLIENT_EXPECT_SERVER_HELLO,
220
        PTLS_STATE_CLIENT_EXPECT_SECOND_SERVER_HELLO,
221
        PTLS_STATE_CLIENT_EXPECT_ENCRYPTED_EXTENSIONS,
222
        PTLS_STATE_CLIENT_EXPECT_CERTIFICATE_REQUEST_OR_CERTIFICATE,
223
        PTLS_STATE_CLIENT_EXPECT_CERTIFICATE,
224
        PTLS_STATE_CLIENT_EXPECT_CERTIFICATE_VERIFY,
225
        PTLS_STATE_CLIENT_EXPECT_FINISHED,
226
        PTLS_STATE_SERVER_EXPECT_CLIENT_HELLO,
227
        PTLS_STATE_SERVER_EXPECT_SECOND_CLIENT_HELLO,
228
        PTLS_STATE_SERVER_GENERATING_CERTIFICATE_VERIFY,
229
        PTLS_STATE_SERVER_EXPECT_CERTIFICATE,
230
        PTLS_STATE_SERVER_EXPECT_CERTIFICATE_VERIFY,
231
        /* ptls_send can be called if the state is below here */
232
        PTLS_STATE_SERVER_EXPECT_END_OF_EARLY_DATA,
233
        PTLS_STATE_SERVER_EXPECT_FINISHED,
234
        PTLS_STATE_POST_HANDSHAKE_MIN,
235
        PTLS_STATE_CLIENT_POST_HANDSHAKE = PTLS_STATE_POST_HANDSHAKE_MIN,
236
        PTLS_STATE_SERVER_POST_HANDSHAKE
237
    } state;
238
    /**
239
     * receive buffers
240
     */
241
    struct {
242
        ptls_buffer_t rec;
243
        ptls_buffer_t mess;
244
    } recvbuf;
245
    /**
246
     * key schedule
247
     */
248
    ptls_key_schedule_t *key_schedule;
249
    /**
250
     * values used for record protection
251
     */
252
    struct {
253
        struct st_ptls_traffic_protection_t dec;
254
        struct st_ptls_traffic_protection_t enc;
255
    } traffic_protection;
256
    /**
257
     * server-name passed using SNI
258
     */
259
    char *server_name;
260
    /**
261
     * result of ALPN
262
     */
263
    char *negotiated_protocol;
264
    /**
265
     * selected key-exchange
266
     */
267
    ptls_key_exchange_algorithm_t *key_share;
268
    /**
269
     * selected cipher-suite
270
     */
271
    ptls_cipher_suite_t *cipher_suite;
272
    /**
273
     * ClientHello.random that appears on the wire. When ECH is used, that of inner CH is retained separately.
274
     */
275
    uint8_t client_random[PTLS_HELLO_RANDOM_SIZE];
276
    /**
277
     * exporter master secret (either 0rtt or 1rtt)
278
     */
279
    struct {
280
        uint8_t *early;
281
        uint8_t *one_rtt;
282
    } exporter_master_secret;
283
    /**
284
     * ECH
285
     */
286
    struct st_ptls_ech_t ech;
287
    /* flags */
288
    unsigned is_server : 1;
289
    unsigned is_psk_handshake : 1;
290
    unsigned send_change_cipher_spec : 1;
291
    unsigned needs_key_update : 1;
292
    unsigned key_update_send_request : 1;
293
#if PTLS_HAVE_LOG
294
    /**
295
     * see ptls_log
296
     */
297
    ptls_log_conn_state_t log_state;
298
#endif
299
    struct {
300
        uint32_t active_conns;
301
        uint32_t generation;
302
    } log_sni;
303
    /**
304
     * misc.
305
     */
306
    union {
307
        struct {
308
            ptls_iovec_t legacy_session_id;
309
            uint8_t legacy_session_id_buf[32];
310
            ptls_key_exchange_context_t *key_share_ctx;
311
            unsigned offered_psk : 1;
312
            /**
313
             * if 1-RTT write key is active
314
             */
315
            unsigned using_early_data : 1;
316
            struct st_ptls_certificate_request_t certificate_request;
317
        } client;
318
        struct {
319
            uint8_t pending_traffic_secret[PTLS_MAX_DIGEST_SIZE];
320
            uint32_t early_data_skipped_bytes; /* if not UINT32_MAX, the server is skipping early data */
321
            uint8_t num_tickets_to_send;
322
            ptls_async_job_t *async_job;
323
        } server;
324
    };
325
    /**
326
     * certificate verify; will be used by the client and the server (if require_client_authentication is set)
327
     */
328
    struct {
329
        int (*cb)(void *verify_ctx, uint16_t algo, ptls_iovec_t data, ptls_iovec_t signature);
330
        void *verify_ctx;
331
    } certificate_verify;
332
    /**
333
     * handshake traffic secret to be commisioned (an array of `uint8_t [PTLS_MAX_DIGEST_SIZE]` or NULL)
334
     */
335
    uint8_t *pending_handshake_secret;
336
    /**
337
     * user data
338
     */
339
    void *data_ptr;
340
};
341
342
struct st_ptls_record_t {
343
    uint8_t type;
344
    uint16_t version;
345
    size_t length;
346
    const uint8_t *fragment;
347
};
348
349
0
#define MAX_UNKNOWN_EXTENSIONS 16
350
#define MAX_CERTIFICATE_TYPES 8
351
352
struct st_ptls_client_hello_t {
353
    uint16_t legacy_version;
354
    const uint8_t *random_bytes;
355
    ptls_iovec_t legacy_session_id;
356
    struct {
357
        const uint8_t *ids;
358
        size_t count;
359
    } compression_methods;
360
    uint16_t selected_version;
361
    ptls_iovec_t cipher_suites;
362
    ptls_iovec_t negotiated_groups;
363
    ptls_iovec_t key_shares;
364
    struct st_ptls_signature_algorithms_t signature_algorithms;
365
    ptls_iovec_t server_name;
366
    struct {
367
        ptls_iovec_t list[16];
368
        size_t count;
369
    } alpn;
370
    struct {
371
        uint16_t list[16];
372
        size_t count;
373
    } cert_compression_algos;
374
    struct {
375
        ptls_iovec_t all;
376
        ptls_iovec_t tbs;
377
        ptls_iovec_t ch1_hash;
378
        ptls_iovec_t signature;
379
        unsigned sent_key_share : 1;
380
    } cookie;
381
    struct {
382
        uint8_t list[MAX_CERTIFICATE_TYPES];
383
        size_t count;
384
    } server_certificate_types;
385
    unsigned status_request : 1;
386
    struct {
387
        uint8_t new_session_count;
388
        uint8_t resumption_count;
389
    } ticket_request;
390
    /**
391
     * ECH: payload.base != NULL indicates that the extension was received
392
     */
393
    struct {
394
        uint8_t type;
395
        uint8_t config_id;
396
        ptls_hpke_cipher_suite_id_t cipher_suite;
397
        ptls_iovec_t enc;
398
        ptls_iovec_t payload;
399
    } ech;
400
    struct {
401
        const uint8_t *hash_end;
402
        struct {
403
            ptls_client_hello_psk_identity_t list[4];
404
            size_t count;
405
        } identities;
406
        unsigned ke_modes;
407
        unsigned early_data_indication : 1;
408
        unsigned is_last_extension : 1;
409
    } psk;
410
    ptls_raw_extension_t unknown_extensions[MAX_UNKNOWN_EXTENSIONS + 1];
411
    size_t first_extension_at;
412
};
413
414
struct st_ptls_server_hello_t {
415
    uint8_t random_[PTLS_HELLO_RANDOM_SIZE];
416
    ptls_iovec_t legacy_session_id;
417
    int is_retry_request;
418
    union {
419
        ptls_iovec_t peerkey;
420
        struct {
421
            uint16_t selected_group;
422
            ptls_iovec_t cookie;
423
            const uint8_t *ech;
424
        } retry_request;
425
    };
426
};
427
428
struct st_ptls_key_schedule_t {
429
    unsigned generation; /* early secret (1), hanshake secret (2), master secret (3) */
430
    uint8_t secret[PTLS_MAX_DIGEST_SIZE];
431
    size_t num_hashes;
432
    struct {
433
        ptls_hash_algorithm_t *algo;
434
        ptls_hash_context_t *ctx, *ctx_outer;
435
    } hashes[1];
436
};
437
438
struct st_ptls_extension_decoder_t {
439
    uint16_t type;
440
    int (*cb)(ptls_t *tls, void *arg, const uint8_t *src, const uint8_t *const end);
441
};
442
443
struct st_ptls_extension_bitmap_t {
444
    uint64_t bits;
445
};
446
447
static const uint8_t zeroes_of_max_digest_size[PTLS_MAX_DIGEST_SIZE] = {0};
448
449
static ptls_aead_context_t *new_aead(ptls_aead_algorithm_t *aead, ptls_hash_algorithm_t *hash, int is_enc, const void *secret,
450
                                     ptls_iovec_t hash_value, const char *label_prefix);
451
static int server_finish_handshake(ptls_t *tls, ptls_message_emitter_t *emitter, int send_cert_verify,
452
                                   struct st_ptls_signature_algorithms_t *signature_algorithms);
453
454
static int is_supported_version(uint16_t v)
455
0
{
456
0
    size_t i;
457
0
    for (i = 0; i != PTLS_ELEMENTSOF(supported_versions); ++i)
458
0
        if (supported_versions[i] == v)
459
0
            return 1;
460
0
    return 0;
461
0
}
462
463
static int extension_bitmap_testandset(struct st_ptls_extension_bitmap_t *bitmap, int hstype, uint16_t extid)
464
0
{
465
0
#define HSTYPE_TO_BIT(hstype) ((uint64_t)1 << ((hstype) + 1)) /* min(hstype) is -1 (PSEUDO_HRR) */
466
0
#define DEFINE_BIT(abbrev, hstype) static const uint64_t abbrev = HSTYPE_TO_BIT(PTLS_HANDSHAKE_TYPE_##hstype)
467
0
#define EXT(candext, allowed_bits)                                                                                                 \
468
0
    do {                                                                                                                           \
469
0
        if (PTLS_UNLIKELY(extid == PTLS_EXTENSION_TYPE_##candext)) {                                                               \
470
0
            allowed_hs_bits = allowed_bits;                                                                                        \
471
0
            goto Found;                                                                                                            \
472
0
        }                                                                                                                          \
473
0
        ext_bitmap_mask <<= 1;                                                                                                     \
474
0
    } while (0)
475
476
0
    DEFINE_BIT(CH, CLIENT_HELLO);
477
0
    DEFINE_BIT(SH, SERVER_HELLO);
478
0
    DEFINE_BIT(HRR, PSEUDO_HRR);
479
0
    DEFINE_BIT(EE, ENCRYPTED_EXTENSIONS);
480
0
    DEFINE_BIT(CR, CERTIFICATE_REQUEST);
481
0
    DEFINE_BIT(CT, CERTIFICATE);
482
0
    DEFINE_BIT(NST, NEW_SESSION_TICKET);
483
484
0
    uint64_t allowed_hs_bits, ext_bitmap_mask = 1;
485
486
    /* clang-format off */
487
    /* RFC 8446 section 4.2: "The table below indicates the messages where a given extension may appear... If an implementation
488
     * receives an extension which it recognizes and which is not specified for the message in which it appears, it MUST abort the
489
     * handshake with an "illegal_parameter" alert.
490
     *
491
     * +-------------------------+---------------+
492
     * +        Extension        |    Allowed    |
493
     * +-------------------------+---------------+ */
494
0
    EXT( SERVER_NAME             , CH + EE       );
495
0
    EXT( STATUS_REQUEST          , CH + CR + CT  );
496
0
    EXT( SUPPORTED_GROUPS        , CH + EE       );
497
0
    EXT( SIGNATURE_ALGORITHMS    , CH + CR       );
498
0
    EXT( ALPN                    , CH + EE       );
499
0
    EXT( SERVER_CERTIFICATE_TYPE , CH + EE       );
500
0
    EXT( KEY_SHARE               , CH + SH + HRR );
501
0
    EXT( PRE_SHARED_KEY          , CH + SH       );
502
0
    EXT( PSK_KEY_EXCHANGE_MODES  , CH            );
503
0
    EXT( EARLY_DATA              , CH + EE + NST );
504
0
    EXT( COOKIE                  , CH + HRR      );
505
0
    EXT( SUPPORTED_VERSIONS      , CH + SH + HRR );
506
0
    EXT( COMPRESS_CERTIFICATE    , CH + CR       ); /* from RFC 8879 */
507
0
    EXT( ENCRYPTED_CLIENT_HELLO  , CH + HRR + EE ); /* from draft-ietf-tls-esni-15 */
508
0
    EXT( ECH_OUTER_EXTENSIONS    , 0             );
509
    /* +-----------------------------------------+ */
510
    /* clang-format on */
511
512
0
    return 1;
513
514
0
Found:
515
0
    if ((allowed_hs_bits & HSTYPE_TO_BIT(hstype)) == 0)
516
0
        return 0;
517
0
    if ((bitmap->bits & ext_bitmap_mask) != 0)
518
0
        return 0;
519
0
    bitmap->bits |= ext_bitmap_mask;
520
0
    return 1;
521
522
0
#undef HSTYPE_TO_BIT
523
0
#undef DEFINE_ABBREV
524
0
#undef EXT
525
0
}
526
527
#ifndef ntoh16
528
static uint16_t ntoh16(const uint8_t *src)
529
0
{
530
0
    return (uint16_t)src[0] << 8 | src[1];
531
0
}
532
#endif
533
534
#ifndef ntoh24
535
static uint32_t ntoh24(const uint8_t *src)
536
0
{
537
0
    return (uint32_t)src[0] << 16 | (uint32_t)src[1] << 8 | src[2];
538
0
}
539
#endif
540
541
#ifndef ntoh32
542
static uint32_t ntoh32(const uint8_t *src)
543
0
{
544
0
    return (uint32_t)src[0] << 24 | (uint32_t)src[1] << 16 | (uint32_t)src[2] << 8 | src[3];
545
0
}
546
#endif
547
548
#ifndef ntoh64
549
static uint64_t ntoh64(const uint8_t *src)
550
0
{
551
0
    return (uint64_t)src[0] << 56 | (uint64_t)src[1] << 48 | (uint64_t)src[2] << 40 | (uint64_t)src[3] << 32 |
552
0
           (uint64_t)src[4] << 24 | (uint64_t)src[5] << 16 | (uint64_t)src[6] << 8 | src[7];
553
0
}
554
#endif
555
556
static void encode64(uint8_t *dst, uint64_t v)
557
0
{
558
0
    for (size_t i = 0; i < 8; ++i)
559
0
        dst[i] = (uint8_t)(v >> (56 - 8 * i));
560
0
}
561
562
static char *duplicate_as_str(const void *src, size_t len)
563
0
{
564
0
    char *dst;
565
566
0
    if ((dst = malloc(len + 1)) == NULL)
567
0
        return NULL;
568
0
    memcpy(dst, src, len);
569
0
    dst[len] = '\0';
570
0
    return dst;
571
0
}
572
573
void ptls_buffer__release_memory(ptls_buffer_t *buf)
574
0
{
575
0
    ptls_clear_memory(buf->base, buf->off);
576
0
    if (buf->is_allocated) {
577
#ifdef _WINDOWS
578
        if (buf->align_bits != 0) {
579
            _aligned_free(buf->base);
580
        } else {
581
            free(buf->base);
582
        }
583
#else
584
0
        free(buf->base);
585
0
#endif
586
0
    }
587
0
}
588
589
int ptls_buffer_reserve(ptls_buffer_t *buf, size_t delta)
590
56.6k
{
591
56.6k
    return ptls_buffer_reserve_aligned(buf, delta, 0);
592
56.6k
}
593
594
int ptls_buffer_reserve_aligned(ptls_buffer_t *buf, size_t delta, uint8_t align_bits)
595
56.6k
{
596
56.6k
    if (buf->base == NULL)
597
0
        return PTLS_ERROR_NO_MEMORY;
598
599
56.6k
    if (PTLS_MEMORY_DEBUG || buf->capacity < buf->off + delta ||
600
56.6k
        (buf->align_bits < align_bits && ((uintptr_t)buf->base & (((uintptr_t)1 << align_bits) - 1)) != 0)) {
601
0
        void *newp;
602
0
        size_t new_capacity = buf->capacity;
603
0
        if (new_capacity < 1024)
604
0
            new_capacity = 1024;
605
0
        while (new_capacity < buf->off + delta) {
606
0
            new_capacity *= 2;
607
0
        }
608
0
        if (align_bits != 0) {
609
#ifdef _WINDOWS
610
            if ((newp = _aligned_malloc(new_capacity, (size_t)1 << align_bits)) == NULL)
611
                return PTLS_ERROR_NO_MEMORY;
612
#else
613
0
            if (posix_memalign(&newp, 1 << align_bits, new_capacity) != 0)
614
0
                return PTLS_ERROR_NO_MEMORY;
615
0
#endif
616
0
        } else {
617
0
            if ((newp = malloc(new_capacity)) == NULL)
618
0
                return PTLS_ERROR_NO_MEMORY;
619
0
        }
620
0
        memcpy(newp, buf->base, buf->off);
621
0
        ptls_buffer__release_memory(buf);
622
0
        buf->base = newp;
623
0
        buf->capacity = new_capacity;
624
0
        buf->is_allocated = 1;
625
0
        buf->align_bits = align_bits;
626
0
    }
627
628
56.6k
    return 0;
629
56.6k
}
630
631
int ptls_buffer__do_pushv(ptls_buffer_t *buf, const void *src, size_t len)
632
6.28k
{
633
6.28k
    int ret;
634
635
6.28k
    if (len == 0)
636
0
        return 0;
637
6.28k
    if ((ret = ptls_buffer_reserve(buf, len)) != 0)
638
0
        return ret;
639
6.28k
    memcpy(buf->base + buf->off, src, len);
640
6.28k
    buf->off += len;
641
6.28k
    return 0;
642
6.28k
}
643
644
int ptls_buffer__adjust_quic_blocksize(ptls_buffer_t *buf, size_t body_size)
645
6.28k
{
646
6.28k
    uint8_t sizebuf[PTLS_ENCODE_QUICINT_CAPACITY];
647
6.28k
    size_t sizelen = ptls_encode_quicint(sizebuf, body_size) - sizebuf;
648
649
    /* adjust amount of space before body_size to `sizelen` bytes */
650
6.28k
    if (sizelen != 1) {
651
0
        int ret;
652
0
        if ((ret = ptls_buffer_reserve(buf, sizelen - 1)) != 0)
653
0
            return ret;
654
0
        memmove(buf->base + buf->off - body_size - 1 + sizelen, buf->base + buf->off - body_size, body_size);
655
0
        buf->off += sizelen - 1;
656
0
    }
657
658
    /* write the size */
659
6.28k
    memcpy(buf->base + buf->off - body_size - sizelen, sizebuf, sizelen);
660
661
6.28k
    return 0;
662
6.28k
}
663
664
int ptls_buffer__adjust_asn1_blocksize(ptls_buffer_t *buf, size_t body_size)
665
0
{
666
0
    fprintf(stderr, "unimplemented\n");
667
0
    abort();
668
0
}
669
670
int ptls_buffer_push_asn1_ubigint(ptls_buffer_t *buf, const void *bignum, size_t size)
671
0
{
672
0
    const uint8_t *p = bignum, *const end = p + size;
673
0
    int ret;
674
675
    /* skip zeroes */
676
0
    for (; end - p >= 1; ++p)
677
0
        if (*p != 0)
678
0
            break;
679
680
    /* emit */
681
0
    ptls_buffer_push(buf, 2);
682
0
    ptls_buffer_push_asn1_block(buf, {
683
0
        if (*p >= 0x80)
684
0
            ptls_buffer_push(buf, 0);
685
0
        if (p != end) {
686
0
            ptls_buffer_pushv(buf, p, end - p);
687
0
        } else {
688
0
            ptls_buffer_pushv(buf, "", 1);
689
0
        }
690
0
    });
691
0
    ret = 0;
692
693
0
Exit:
694
0
    return ret;
695
0
}
696
697
#if PTLS_FUZZ_HANDSHAKE
698
699
static size_t aead_encrypt(struct st_ptls_traffic_protection_t *ctx, void *output, const void *input, size_t inlen,
700
                           uint8_t content_type)
701
{
702
    memcpy(output, input, inlen);
703
    memcpy(output + inlen, &content_type, 1);
704
    return inlen + 1 + 16;
705
}
706
707
static int aead_decrypt(struct st_ptls_traffic_protection_t *ctx, void *output, size_t *outlen, const void *input, size_t inlen)
708
{
709
    if (inlen < 16) {
710
        return PTLS_ALERT_BAD_RECORD_MAC;
711
    }
712
    memcpy(output, input, inlen - 16);
713
    *outlen = inlen - 16; /* removing the 16 bytes of tag */
714
    return 0;
715
}
716
717
#else
718
719
static void build_aad(uint8_t aad[5], size_t reclen)
720
0
{
721
0
    aad[0] = PTLS_CONTENT_TYPE_APPDATA;
722
0
    aad[1] = PTLS_RECORD_VERSION_MAJOR;
723
0
    aad[2] = PTLS_RECORD_VERSION_MINOR;
724
0
    aad[3] = (uint8_t)(reclen >> 8);
725
0
    aad[4] = (uint8_t)reclen;
726
0
}
727
728
static size_t aead_encrypt(struct st_ptls_traffic_protection_t *ctx, void *output, const void *input, size_t inlen,
729
                           uint8_t content_type)
730
0
{
731
0
    ptls_iovec_t invec[2] = {ptls_iovec_init(input, inlen), ptls_iovec_init(&content_type, 1)};
732
0
    uint8_t aad[5];
733
734
0
    build_aad(aad, inlen + 1 + ctx->aead->algo->tag_size);
735
0
    ptls_aead_encrypt_v(ctx->aead, output, invec, PTLS_ELEMENTSOF(invec), ctx->seq++, aad, sizeof(aad));
736
737
0
    return inlen + 1 + ctx->aead->algo->tag_size;
738
0
}
739
740
static int aead_decrypt(struct st_ptls_traffic_protection_t *ctx, void *output, size_t *outlen, const void *input, size_t inlen)
741
0
{
742
0
    uint8_t aad[5];
743
744
0
    build_aad(aad, inlen);
745
0
    if ((*outlen = ptls_aead_decrypt(ctx->aead, output, input, inlen, ctx->seq, aad, sizeof(aad))) == SIZE_MAX)
746
0
        return PTLS_ALERT_BAD_RECORD_MAC;
747
0
    ++ctx->seq;
748
0
    return 0;
749
0
}
750
751
#endif /* #if PTLS_FUZZ_HANDSHAKE */
752
753
static void build_tls12_aad(uint8_t *aad, uint8_t type, uint64_t seq, uint16_t length)
754
0
{
755
0
    for (size_t i = 0; i < 8; ++i)
756
0
        aad[i] = (uint8_t)(seq >> (56 - i * 8));
757
0
    aad[8] = type;
758
0
    aad[9] = PTLS_RECORD_VERSION_MAJOR;
759
0
    aad[10] = PTLS_RECORD_VERSION_MINOR;
760
0
    aad[11] = length >> 8;
761
0
    aad[12] = (uint8_t)length;
762
0
}
763
764
#define buffer_push_record(buf, type, block)                                                                                       \
765
0
    do {                                                                                                                           \
766
0
        ptls_buffer_push((buf), (type), PTLS_RECORD_VERSION_MAJOR, PTLS_RECORD_VERSION_MINOR);                                     \
767
0
        ptls_buffer_push_block((buf), 2, block);                                                                                   \
768
0
    } while (0)
769
770
static int buffer_push_encrypted_records(ptls_buffer_t *buf, uint8_t type, const uint8_t *src, size_t len,
771
                                         struct st_ptls_traffic_protection_t *enc)
772
0
{
773
0
    int ret = 0;
774
775
0
    while (len != 0) {
776
0
        size_t chunk_size = len;
777
0
        if (chunk_size > PTLS_MAX_PLAINTEXT_RECORD_SIZE)
778
0
            chunk_size = PTLS_MAX_PLAINTEXT_RECORD_SIZE;
779
0
        if (enc->tls12) {
780
0
            buffer_push_record(buf, type, {
781
                /* reserve memory */
782
0
                if ((ret = ptls_buffer_reserve_aligned(
783
0
                         buf, enc->aead->algo->tls12.record_iv_size + chunk_size + enc->aead->algo->tag_size,
784
0
                         enc->aead->algo->align_bits)) != 0)
785
0
                    goto Exit;
786
                /* determine nonce, as well as prepending that walue as the record IV (AES-GCM) */
787
0
                uint64_t nonce;
788
0
                if (enc->aead->algo->tls12.record_iv_size != 0) {
789
0
                    assert(enc->aead->algo->tls12.record_iv_size == 8);
790
0
                    nonce = enc->tls12_enc_record_iv++;
791
0
                    encode64(buf->base + buf->off, nonce);
792
0
                    buf->off += 8;
793
0
                } else {
794
0
                    nonce = enc->seq;
795
0
                }
796
                /* build AAD */
797
0
                uint8_t aad[PTLS_TLS12_AAD_SIZE];
798
0
                build_tls12_aad(aad, type, enc->seq, (uint16_t)chunk_size);
799
                /* encrypt */
800
0
                buf->off += ptls_aead_encrypt(enc->aead, buf->base + buf->off, src, chunk_size, nonce, aad, sizeof(aad));
801
0
                ++enc->seq;
802
0
            });
803
0
        } else {
804
0
            buffer_push_record(buf, PTLS_CONTENT_TYPE_APPDATA, {
805
0
                if ((ret = ptls_buffer_reserve_aligned(buf, chunk_size + enc->aead->algo->tag_size + 1,
806
0
                                                       enc->aead->algo->align_bits)) != 0)
807
0
                    goto Exit;
808
0
                buf->off += aead_encrypt(enc, buf->base + buf->off, src, chunk_size, type);
809
0
            });
810
0
        }
811
0
        src += chunk_size;
812
0
        len -= chunk_size;
813
0
    }
814
815
0
Exit:
816
0
    return ret;
817
0
}
818
819
static int buffer_encrypt_record(ptls_buffer_t *buf, size_t rec_start, struct st_ptls_traffic_protection_t *enc)
820
0
{
821
0
    size_t bodylen = buf->off - rec_start - 5;
822
0
    uint8_t *tmpbuf, type = buf->base[rec_start];
823
0
    int ret;
824
825
    /* Fast path: do in-place encryption if only one record needs to be emitted. (For simplicity, do not take this path if TLS 1.2
826
     * is used, as this function will be called no more than once per connection, for encrypting an alert.) */
827
0
    if (!enc->tls12 && bodylen <= PTLS_MAX_PLAINTEXT_RECORD_SIZE) {
828
0
        size_t overhead = 1 + enc->aead->algo->tag_size;
829
0
        if ((ret = ptls_buffer_reserve_aligned(buf, overhead, enc->aead->algo->align_bits)) != 0)
830
0
            return ret;
831
0
        size_t encrypted_len = aead_encrypt(enc, buf->base + rec_start + 5, buf->base + rec_start + 5, bodylen, type);
832
0
        assert(encrypted_len == bodylen + overhead);
833
0
        buf->off += overhead;
834
0
        buf->base[rec_start] = PTLS_CONTENT_TYPE_APPDATA;
835
0
        buf->base[rec_start + 3] = (encrypted_len >> 8) & 0xff;
836
0
        buf->base[rec_start + 4] = encrypted_len & 0xff;
837
0
        return 0;
838
0
    }
839
840
    /* move plaintext to temporary buffer */
841
0
    if ((tmpbuf = malloc(bodylen)) == NULL) {
842
0
        ret = PTLS_ERROR_NO_MEMORY;
843
0
        goto Exit;
844
0
    }
845
0
    memcpy(tmpbuf, buf->base + rec_start + 5, bodylen);
846
0
    ptls_clear_memory(buf->base + rec_start, bodylen + 5);
847
0
    buf->off = rec_start;
848
849
    /* push encrypted records */
850
0
    ret = buffer_push_encrypted_records(buf, type, tmpbuf, bodylen, enc);
851
852
0
Exit:
853
0
    if (tmpbuf != NULL) {
854
0
        ptls_clear_memory(tmpbuf, bodylen);
855
0
        free(tmpbuf);
856
0
    }
857
0
    return ret;
858
0
}
859
860
static int begin_record_message(ptls_message_emitter_t *_self)
861
0
{
862
0
    struct st_ptls_record_message_emitter_t *self = (void *)_self;
863
0
    int ret;
864
865
0
    self->rec_start = self->super.buf->off;
866
0
    ptls_buffer_push(self->super.buf, PTLS_CONTENT_TYPE_HANDSHAKE, PTLS_RECORD_VERSION_MAJOR, PTLS_RECORD_VERSION_MINOR, 0, 0);
867
0
    ret = 0;
868
0
Exit:
869
0
    return ret;
870
0
}
871
872
static int commit_record_message(ptls_message_emitter_t *_self)
873
0
{
874
0
    struct st_ptls_record_message_emitter_t *self = (void *)_self;
875
0
    int ret;
876
877
0
    if (self->super.enc->aead != NULL) {
878
0
        ret = buffer_encrypt_record(self->super.buf, self->rec_start, self->super.enc);
879
0
    } else {
880
        /* TODO allow CH,SH,HRR above 16KB */
881
0
        size_t sz = self->super.buf->off - self->rec_start - 5;
882
0
        assert(sz <= PTLS_MAX_PLAINTEXT_RECORD_SIZE);
883
0
        self->super.buf->base[self->rec_start + 3] = (uint8_t)(sz >> 8);
884
0
        self->super.buf->base[self->rec_start + 4] = (uint8_t)(sz);
885
0
        ret = 0;
886
0
    }
887
888
0
    return ret;
889
0
}
890
891
#define buffer_push_extension(buf, type, block)                                                                                    \
892
0
    do {                                                                                                                           \
893
0
        ptls_buffer_push16((buf), (type));                                                                                         \
894
0
        ptls_buffer_push_block((buf), 2, block);                                                                                   \
895
0
    } while (0);
896
897
#define decode_open_extensions(src, end, hstype, exttype, block)                                                                   \
898
0
    do {                                                                                                                           \
899
0
        struct st_ptls_extension_bitmap_t bitmap = {0};                                                                            \
900
0
        ptls_decode_open_block((src), end, 2, {                                                                                    \
901
0
            while ((src) != end) {                                                                                                 \
902
0
                if ((ret = ptls_decode16((exttype), &(src), end)) != 0)                                                            \
903
0
                    goto Exit;                                                                                                     \
904
0
                if (!extension_bitmap_testandset(&bitmap, (hstype), *(exttype))) {                                                 \
905
0
                    ret = PTLS_ALERT_ILLEGAL_PARAMETER;                                                                            \
906
0
                    goto Exit;                                                                                                     \
907
0
                }                                                                                                                  \
908
0
                ptls_decode_open_block((src), end, 2, block);                                                                      \
909
0
            }                                                                                                                      \
910
0
        });                                                                                                                        \
911
0
    } while (0)
912
913
#define decode_extensions(src, end, hstype, exttype, block)                                                                        \
914
0
    do {                                                                                                                           \
915
0
        decode_open_extensions((src), end, hstype, exttype, block);                                                                \
916
0
        ptls_decode_assert_block_close((src), end);                                                                                \
917
0
    } while (0)
918
919
int ptls_decode8(uint8_t *value, const uint8_t **src, const uint8_t *end)
920
0
{
921
0
    if (*src == end)
922
0
        return PTLS_ALERT_DECODE_ERROR;
923
0
    *value = *(*src)++;
924
0
    return 0;
925
0
}
926
927
int ptls_decode16(uint16_t *value, const uint8_t **src, const uint8_t *end)
928
0
{
929
0
    if (end - *src < 2)
930
0
        return PTLS_ALERT_DECODE_ERROR;
931
0
    *value = ntoh16(*src);
932
0
    *src += 2;
933
0
    return 0;
934
0
}
935
936
int ptls_decode24(uint32_t *value, const uint8_t **src, const uint8_t *end)
937
0
{
938
0
    if (end - *src < 3)
939
0
        return PTLS_ALERT_DECODE_ERROR;
940
0
    *value = ((uint32_t)(*src)[0] << 16) | ((uint32_t)(*src)[1] << 8) | (*src)[2];
941
0
    *src += 3;
942
0
    return 0;
943
0
}
944
945
int ptls_decode32(uint32_t *value, const uint8_t **src, const uint8_t *end)
946
0
{
947
0
    if (end - *src < 4)
948
0
        return PTLS_ALERT_DECODE_ERROR;
949
0
    *value = ntoh32(*src);
950
0
    *src += 4;
951
0
    return 0;
952
0
}
953
954
int ptls_decode64(uint64_t *value, const uint8_t **src, const uint8_t *end)
955
0
{
956
0
    if (end - *src < 8)
957
0
        return PTLS_ALERT_DECODE_ERROR;
958
0
    *value = ntoh64(*src);
959
0
    *src += 8;
960
0
    return 0;
961
0
}
962
963
uint64_t ptls_decode_quicint(const uint8_t **src, const uint8_t *end)
964
45.5k
{
965
45.5k
    if (PTLS_UNLIKELY(*src == end))
966
97
        return UINT64_MAX;
967
968
45.4k
    uint8_t b = *(*src)++;
969
970
45.4k
    if (PTLS_LIKELY(b <= 0x3f))
971
42.7k
        return b;
972
973
2.73k
    uint64_t v = b & 0x3f;
974
2.73k
    unsigned bytes_left = (1 << (b >> 6)) - 1;
975
2.73k
    if (PTLS_UNLIKELY((size_t)(end - *src) < bytes_left))
976
41
        return UINT64_MAX;
977
7.09k
    do {
978
7.09k
        v = (v << 8) | *(*src)++;
979
7.09k
    } while (--bytes_left != 0);
980
2.69k
    return v;
981
2.73k
}
982
983
static void log_secret(ptls_t *tls, const char *type, ptls_iovec_t secret)
984
0
{
985
0
    char hexbuf[PTLS_MAX_DIGEST_SIZE * 2 + 1];
986
987
0
    PTLS_PROBE(NEW_SECRET, tls, type, ptls_hexdump(hexbuf, secret.base, secret.len));
988
0
    PTLS_LOG_CONN(new_secret, tls, { PTLS_LOG_ELEMENT_SAFESTR(label, type); });
989
990
0
    if (tls->ctx->log_event != NULL)
991
0
        tls->ctx->log_event->cb(tls->ctx->log_event, tls, type, "%s", ptls_hexdump(hexbuf, secret.base, secret.len));
992
0
}
993
994
/**
995
 * This function preserves the flags and  modes (e.g., `offered`, `accepted`, `cipher`), they can be used afterwards.
996
 */
997
static void clear_ech(struct st_ptls_ech_t *ech, int is_server)
998
0
{
999
0
    if (ech->aead != NULL) {
1000
0
        ptls_aead_free(ech->aead);
1001
0
        ech->aead = NULL;
1002
0
    }
1003
0
    ptls_clear_memory(ech->inner_client_random, PTLS_HELLO_RANDOM_SIZE);
1004
0
    if (!is_server) {
1005
0
        free(ech->client.enc.base);
1006
0
        ech->client.enc = ptls_iovec_init(NULL, 0);
1007
0
        if (ech->client.public_name != NULL) {
1008
0
            free(ech->client.public_name);
1009
0
            ech->client.public_name = NULL;
1010
0
        }
1011
0
        free(ech->client.first_ech.base);
1012
0
        ech->client.first_ech = ptls_iovec_init(NULL, 0);
1013
0
    }
1014
0
}
1015
1016
/**
1017
 * Decodes one ECHConfigContents (tls-esni-15 section 4). `decoded->kem` and `cipher` may be NULL even when the function returns
1018
 * zero, if the corresponding entries are not found.
1019
 */
1020
static int decode_one_ech_config(ptls_hpke_kem_t **kems, ptls_hpke_cipher_suite_t **ciphers,
1021
                                 struct st_decoded_ech_config_t *decoded, const uint8_t **src, const uint8_t *const end)
1022
0
{
1023
0
    char *public_name_buf = NULL;
1024
0
    int ret;
1025
1026
0
    *decoded = (struct st_decoded_ech_config_t){0};
1027
1028
0
    if ((ret = ptls_decode8(&decoded->id, src, end)) != 0)
1029
0
        goto Exit;
1030
0
    uint16_t kem_id;
1031
0
    if ((ret = ptls_decode16(&kem_id, src, end)) != 0)
1032
0
        goto Exit;
1033
0
    for (size_t i = 0; kems[i] != NULL; ++i) {
1034
0
        if (kems[i]->id == kem_id) {
1035
0
            decoded->kem = kems[i];
1036
0
            break;
1037
0
        }
1038
0
    }
1039
0
    ptls_decode_open_block(*src, end, 2, {
1040
0
        if (*src == end) {
1041
0
            ret = PTLS_ALERT_DECODE_ERROR;
1042
0
            goto Exit;
1043
0
        }
1044
0
        decoded->public_key = ptls_iovec_init(*src, end - *src);
1045
0
        *src = end;
1046
0
    });
1047
0
    ptls_decode_open_block(*src, end, 2, {
1048
0
        do {
1049
0
            uint16_t kdf_id;
1050
0
            uint16_t aead_id;
1051
0
            if ((ret = ptls_decode16(&kdf_id, src, end)) != 0)
1052
0
                goto Exit;
1053
0
            if ((ret = ptls_decode16(&aead_id, src, end)) != 0)
1054
0
                goto Exit;
1055
0
            if (decoded->cipher == NULL) {
1056
0
                for (size_t i = 0; ciphers[i] != NULL; ++i) {
1057
0
                    if (ciphers[i]->id.kdf == kdf_id && ciphers[i]->id.aead == aead_id) {
1058
0
                        decoded->cipher = ciphers[i];
1059
0
                        break;
1060
0
                    }
1061
0
                }
1062
0
            }
1063
0
        } while (*src != end);
1064
0
    });
1065
0
    if ((ret = ptls_decode8(&decoded->max_name_length, src, end)) != 0)
1066
0
        goto Exit;
1067
1068
0
#define SKIP_DECODED()                                                                                                             \
1069
0
    do {                                                                                                                           \
1070
0
        decoded->kem = NULL;                                                                                                       \
1071
0
        decoded->cipher = NULL;                                                                                                    \
1072
0
    } while (0)
1073
1074
    /* Decode public_name. The specification requires clients to ignore (upon parsing ESNIConfigList) or reject (upon handshake)
1075
     * public names that are not DNS names or IPv4 addresses. We ignore IPv4 and v6 addresses during parsing (IPv6 addresses never
1076
     * looks like DNS names), and delegate the responsibility of rejecting non-DNS names to the certificate verify callback. */
1077
0
    ptls_decode_open_block(*src, end, 1, {
1078
0
        if (*src == end) {
1079
0
            ret = PTLS_ALERT_DECODE_ERROR;
1080
0
            goto Exit;
1081
0
        }
1082
0
        if ((public_name_buf = duplicate_as_str(*src, end - *src)) == NULL) {
1083
0
            ret = PTLS_ERROR_NO_MEMORY;
1084
0
            goto Exit;
1085
0
        }
1086
0
        if (ptls_server_name_is_ipaddr(public_name_buf)) {
1087
0
            SKIP_DECODED();
1088
0
        } else {
1089
0
            decoded->public_name = ptls_iovec_init(*src, end - *src);
1090
0
        }
1091
0
        *src = end;
1092
0
    });
1093
1094
0
    ptls_decode_block(*src, end, 2, {
1095
0
        while (*src < end) {
1096
0
            uint16_t type;
1097
0
            if ((ret = ptls_decode16(&type, src, end)) != 0)
1098
0
                goto Exit;
1099
0
            ptls_decode_open_block(*src, end, 2, { *src = end; });
1100
            /* if a critital extension is found, indicate that the config cannot be used */
1101
0
            if ((type & 0x8000) != 0)
1102
0
                SKIP_DECODED();
1103
0
        }
1104
0
    });
1105
1106
0
#undef SKIP_DECODED
1107
1108
0
Exit:
1109
0
    free(public_name_buf);
1110
0
    return ret;
1111
0
}
1112
1113
static int client_decode_ech_config_list(ptls_context_t *ctx, struct st_decoded_ech_config_t *decoded, ptls_iovec_t config_list)
1114
0
{
1115
0
    const uint8_t *src = config_list.base, *const end = src + config_list.len;
1116
0
    int match_found = 0, ret;
1117
1118
0
    *decoded = (struct st_decoded_ech_config_t){0};
1119
1120
0
    ptls_decode_block(src, end, 2, {
1121
0
        do {
1122
0
            const uint8_t *config_start = src;
1123
0
            uint16_t version;
1124
0
            if ((ret = ptls_decode16(&version, &src, end)) != 0)
1125
0
                goto Exit;
1126
0
            ptls_decode_open_block(src, end, 2, {
1127
                /* If the block is the one that we recognize, parse it, then adopt if if possible. Otherwise, skip. */
1128
0
                if (version == PTLS_ECH_CONFIG_VERSION) {
1129
0
                    struct st_decoded_ech_config_t thisconf;
1130
0
                    if ((ret = decode_one_ech_config(ctx->ech.client.kems, ctx->ech.client.ciphers, &thisconf, &src, end)) != 0)
1131
0
                        goto Exit;
1132
0
                    if (!match_found && thisconf.kem != NULL && thisconf.cipher != NULL) {
1133
0
                        *decoded = thisconf;
1134
0
                        decoded->bytes = ptls_iovec_init(config_start, end - config_start);
1135
0
                        match_found = 1;
1136
0
                    }
1137
0
                } else {
1138
0
                    src = end;
1139
0
                }
1140
0
            });
1141
0
        } while (src != end);
1142
0
    });
1143
0
    ret = 0;
1144
1145
0
Exit:
1146
0
    if (ret != 0)
1147
0
        *decoded = (struct st_decoded_ech_config_t){0};
1148
0
    return ret;
1149
0
}
1150
1151
static int client_setup_ech(struct st_ptls_ech_t *ech, struct st_decoded_ech_config_t *decoded,
1152
                            void (*random_bytes)(void *, size_t))
1153
0
{
1154
0
    ptls_buffer_t infobuf;
1155
0
    uint8_t infobuf_smallbuf[256];
1156
0
    int ret;
1157
1158
    /* setup `enc` and `aead` by running HPKE */
1159
0
    ptls_buffer_init(&infobuf, infobuf_smallbuf, sizeof(infobuf_smallbuf));
1160
0
    ptls_buffer_pushv(&infobuf, ech_info_prefix, sizeof(ech_info_prefix));
1161
0
    ptls_buffer_pushv(&infobuf, decoded->bytes.base, decoded->bytes.len);
1162
0
    if ((ret = ptls_hpke_setup_base_s(decoded->kem, decoded->cipher, &ech->client.enc, &ech->aead, decoded->public_key,
1163
0
                                      ptls_iovec_init(infobuf.base, infobuf.off))) != 0)
1164
0
        goto Exit;
1165
1166
    /* setup the rest */
1167
0
    ech->config_id = decoded->id;
1168
0
    ech->kem = decoded->kem;
1169
0
    ech->cipher = decoded->cipher;
1170
0
    random_bytes(ech->inner_client_random, PTLS_HELLO_RANDOM_SIZE);
1171
0
    ech->client.max_name_length = decoded->max_name_length;
1172
0
    if ((ech->client.public_name = duplicate_as_str(decoded->public_name.base, decoded->public_name.len)) == NULL) {
1173
0
        ret = PTLS_ERROR_NO_MEMORY;
1174
0
        goto Exit;
1175
0
    }
1176
1177
0
Exit:
1178
0
    if (ret != 0)
1179
0
        clear_ech(ech, 0);
1180
0
    return ret;
1181
0
}
1182
1183
static void client_setup_ech_grease(struct st_ptls_ech_t *ech, void (*random_bytes)(void *, size_t), ptls_hpke_kem_t **kems,
1184
                                    ptls_hpke_cipher_suite_t **ciphers, const char *sni_name)
1185
0
{
1186
0
    static const size_t x25519_key_size = 32;
1187
0
    uint8_t random_secret[PTLS_AES128_KEY_SIZE + PTLS_AES_IV_SIZE];
1188
1189
    /* pick up X25519, AES-128-GCM or bail out */
1190
0
    for (size_t i = 0; kems[i] != NULL; ++i) {
1191
0
        if (kems[i]->id == PTLS_HPKE_KEM_X25519_SHA256) {
1192
0
            ech->kem = kems[i];
1193
0
            break;
1194
0
        }
1195
0
    }
1196
0
    for (size_t i = 0; ciphers[i] != NULL; ++i) {
1197
0
        if (ciphers[i]->id.kdf == PTLS_HPKE_HKDF_SHA256 && ciphers[i]->id.aead == PTLS_HPKE_AEAD_AES_128_GCM) {
1198
0
            ech->cipher = ciphers[i];
1199
0
            break;
1200
0
        }
1201
0
    }
1202
0
    if (ech->kem == NULL || ech->cipher == NULL)
1203
0
        goto Fail;
1204
1205
    /* aead is generated from random */
1206
0
    random_bytes(random_secret, sizeof(random_secret));
1207
0
    ech->aead = ptls_aead_new_direct(ech->cipher->aead, 1, random_secret, random_secret + PTLS_AES128_KEY_SIZE);
1208
1209
    /* `enc` is random bytes */
1210
0
    if ((ech->client.enc.base = malloc(x25519_key_size)) == NULL)
1211
0
        goto Fail;
1212
0
    ech->client.enc.len = x25519_key_size;
1213
0
    random_bytes(ech->client.enc.base, ech->client.enc.len);
1214
1215
    /* setup the rest (inner_client_random is left zeros) */
1216
0
    random_bytes(&ech->config_id, sizeof(ech->config_id));
1217
0
    ech->client.max_name_length = 64;
1218
0
    if ((ech->client.public_name = duplicate_as_str(sni_name, strlen(sni_name))) == NULL)
1219
0
        goto Fail;
1220
1221
0
    return;
1222
1223
0
Fail:
1224
0
    clear_ech(ech, 0);
1225
0
}
1226
1227
0
#define ECH_CONFIRMATION_SERVER_HELLO "ech accept confirmation"
1228
0
#define ECH_CONFIRMATION_HRR "hrr ech accept confirmation"
1229
static int ech_calc_confirmation(ptls_key_schedule_t *sched, void *dst, const uint8_t *inner_random, const char *label,
1230
                                 ptls_iovec_t message)
1231
0
{
1232
0
    ptls_hash_context_t *hash = NULL;
1233
0
    uint8_t secret[PTLS_MAX_DIGEST_SIZE], transcript_hash[PTLS_MAX_DIGEST_SIZE];
1234
0
    int ret;
1235
1236
    /* calc transcript hash using the modified ServerHello / HRR */
1237
0
    if ((hash = sched->hashes[0].ctx->clone_(sched->hashes[0].ctx)) == NULL) {
1238
0
        ret = PTLS_ERROR_NO_MEMORY;
1239
0
        goto Exit;
1240
0
    }
1241
0
    hash->update(hash, message.base, message.len);
1242
0
    hash->final(hash, transcript_hash, PTLS_HASH_FINAL_MODE_FREE);
1243
0
    hash = NULL;
1244
1245
    /* HKDF extract and expand */
1246
0
    if ((ret = ptls_hkdf_extract(sched->hashes[0].algo, secret, ptls_iovec_init(NULL, 0),
1247
0
                                 ptls_iovec_init(inner_random, PTLS_HELLO_RANDOM_SIZE))) != 0)
1248
0
        goto Exit;
1249
0
    if ((ret = ptls_hkdf_expand_label(sched->hashes[0].algo, dst, 8, ptls_iovec_init(secret, sched->hashes[0].algo->digest_size),
1250
0
                                      label, ptls_iovec_init(transcript_hash, sched->hashes[0].algo->digest_size), NULL)) != 0)
1251
0
        goto Exit;
1252
1253
0
Exit:
1254
0
    ptls_clear_memory(secret, sizeof(secret));
1255
0
    ptls_clear_memory(transcript_hash, sizeof(transcript_hash));
1256
0
    if (hash != NULL)
1257
0
        hash->final(hash, NULL, PTLS_HASH_FINAL_MODE_FREE);
1258
0
    return ret;
1259
0
}
1260
1261
static void key_schedule_free(ptls_key_schedule_t *sched)
1262
0
{
1263
0
    size_t i;
1264
0
    ptls_clear_memory(sched->secret, sizeof(sched->secret));
1265
0
    for (i = 0; i != sched->num_hashes; ++i) {
1266
0
        sched->hashes[i].ctx->final(sched->hashes[i].ctx, NULL, PTLS_HASH_FINAL_MODE_FREE);
1267
0
        if (sched->hashes[i].ctx_outer != NULL)
1268
0
            sched->hashes[i].ctx_outer->final(sched->hashes[i].ctx_outer, NULL, PTLS_HASH_FINAL_MODE_FREE);
1269
0
    }
1270
0
    free(sched);
1271
0
}
1272
1273
static ptls_key_schedule_t *key_schedule_new(ptls_cipher_suite_t *preferred, ptls_cipher_suite_t **offered, int use_outer)
1274
0
{
1275
0
#define FOREACH_HASH(block)                                                                                                        \
1276
0
    do {                                                                                                                           \
1277
0
        ptls_cipher_suite_t *cs;                                                                                                   \
1278
0
        if ((cs = preferred) != NULL) {                                                                                            \
1279
0
            block                                                                                                                  \
1280
0
        }                                                                                                                          \
1281
0
        if (offered != NULL) {                                                                                                     \
1282
0
            size_t i, j;                                                                                                           \
1283
0
            for (i = 0; (cs = offered[i]) != NULL; ++i) {                                                                          \
1284
0
                if (preferred == NULL || cs->hash != preferred->hash) {                                                            \
1285
0
                    for (j = 0; j != i; ++j)                                                                                       \
1286
0
                        if (cs->hash == offered[j]->hash)                                                                          \
1287
0
                            break;                                                                                                 \
1288
0
                    if (j == i) {                                                                                                  \
1289
0
                        block                                                                                                      \
1290
0
                    }                                                                                                              \
1291
0
                }                                                                                                                  \
1292
0
            }                                                                                                                      \
1293
0
        }                                                                                                                          \
1294
0
    } while (0)
1295
1296
0
    ptls_key_schedule_t *sched;
1297
1298
0
    { /* allocate */
1299
0
        size_t num_hashes = 0;
1300
0
        FOREACH_HASH({ ++num_hashes; });
1301
0
        if ((sched = malloc(offsetof(ptls_key_schedule_t, hashes) + sizeof(sched->hashes[0]) * num_hashes)) == NULL)
1302
0
            return NULL;
1303
0
        *sched = (ptls_key_schedule_t){0};
1304
0
    }
1305
1306
    /* setup the hash algos and contexts */
1307
0
    FOREACH_HASH({
1308
0
        sched->hashes[sched->num_hashes].algo = cs->hash;
1309
0
        if ((sched->hashes[sched->num_hashes].ctx = cs->hash->create()) == NULL)
1310
0
            goto Fail;
1311
0
        if (use_outer) {
1312
0
            if ((sched->hashes[sched->num_hashes].ctx_outer = cs->hash->create()) == NULL)
1313
0
                goto Fail;
1314
0
        } else {
1315
0
            sched->hashes[sched->num_hashes].ctx_outer = NULL;
1316
0
        }
1317
0
        ++sched->num_hashes;
1318
0
    });
1319
1320
0
    return sched;
1321
0
Fail:
1322
0
    key_schedule_free(sched);
1323
0
    return NULL;
1324
1325
0
#undef FOREACH_HASH
1326
0
}
1327
1328
static int key_schedule_extract(ptls_key_schedule_t *sched, ptls_iovec_t ikm)
1329
0
{
1330
0
    int ret;
1331
1332
0
    if (ikm.base == NULL)
1333
0
        ikm = ptls_iovec_init(zeroes_of_max_digest_size, sched->hashes[0].algo->digest_size);
1334
1335
0
    if (sched->generation != 0 &&
1336
0
        (ret = ptls_hkdf_expand_label(sched->hashes[0].algo, sched->secret, sched->hashes[0].algo->digest_size,
1337
0
                                      ptls_iovec_init(sched->secret, sched->hashes[0].algo->digest_size), "derived",
1338
0
                                      ptls_iovec_init(sched->hashes[0].algo->empty_digest, sched->hashes[0].algo->digest_size),
1339
0
                                      NULL)) != 0)
1340
0
        return ret;
1341
1342
0
    ++sched->generation;
1343
0
    ret = ptls_hkdf_extract(sched->hashes[0].algo, sched->secret,
1344
0
                            ptls_iovec_init(sched->secret, sched->hashes[0].algo->digest_size), ikm);
1345
0
    PTLS_DEBUGF("%s: %u, %02x%02x\n", __FUNCTION__, sched->generation, (int)sched->secret[0], (int)sched->secret[1]);
1346
0
    return ret;
1347
0
}
1348
1349
static int key_schedule_select_cipher(ptls_key_schedule_t *sched, ptls_cipher_suite_t *cs, int reset, ptls_iovec_t reset_ikm)
1350
0
{
1351
0
    size_t found_slot = SIZE_MAX, i;
1352
0
    int ret;
1353
1354
0
    assert(sched->generation == 1);
1355
1356
    /* find the one, while freeing others */
1357
0
    for (i = 0; i != sched->num_hashes; ++i) {
1358
0
        if (sched->hashes[i].algo == cs->hash) {
1359
0
            assert(found_slot == SIZE_MAX);
1360
0
            found_slot = i;
1361
0
        } else {
1362
0
            sched->hashes[i].ctx->final(sched->hashes[i].ctx, NULL, PTLS_HASH_FINAL_MODE_FREE);
1363
0
            if (sched->hashes[i].ctx_outer != NULL)
1364
0
                sched->hashes[i].ctx_outer->final(sched->hashes[i].ctx_outer, NULL, PTLS_HASH_FINAL_MODE_FREE);
1365
0
        }
1366
0
    }
1367
0
    if (found_slot != 0) {
1368
0
        sched->hashes[0] = sched->hashes[found_slot];
1369
0
        reset = 1;
1370
0
    }
1371
0
    sched->num_hashes = 1;
1372
1373
    /* recalculate the hash if a different hash as been selected than the one we used for calculating the early secrets */
1374
0
    if (reset) {
1375
0
        --sched->generation;
1376
0
        memset(sched->secret, 0, sizeof(sched->secret));
1377
0
        if ((ret = key_schedule_extract(sched, reset_ikm)) != 0)
1378
0
            goto Exit;
1379
0
    }
1380
1381
0
    ret = 0;
1382
0
Exit:
1383
0
    return ret;
1384
0
}
1385
1386
static void key_schedule_select_outer(ptls_key_schedule_t *sched)
1387
0
{
1388
    /* This function is called when receiving a cleartext message (Server Hello), after the cipher-suite is determined (and hence
1389
     * the hash also), if ECH was offered */
1390
0
    assert(sched->generation == 1);
1391
0
    assert(sched->num_hashes == 1);
1392
0
    assert(sched->hashes[0].ctx_outer != NULL);
1393
1394
0
    sched->hashes[0].ctx->final(sched->hashes[0].ctx, NULL, PTLS_HASH_FINAL_MODE_FREE);
1395
0
    sched->hashes[0].ctx = sched->hashes[0].ctx_outer;
1396
0
    sched->hashes[0].ctx_outer = NULL;
1397
0
}
1398
1399
void ptls__key_schedule_update_hash(ptls_key_schedule_t *sched, const uint8_t *msg, size_t msglen, int use_outer)
1400
0
{
1401
0
    size_t i;
1402
1403
0
    PTLS_DEBUGF("%s:%p:len=%zu\n", __FUNCTION__, sched, msglen);
1404
0
    for (i = 0; i != sched->num_hashes; ++i) {
1405
0
        ptls_hash_context_t *ctx = use_outer ? sched->hashes[i].ctx_outer : sched->hashes[i].ctx;
1406
0
        ctx->update(ctx, msg, msglen);
1407
#if defined(PTLS_DEBUG) && PTLS_DEBUG
1408
        {
1409
            uint8_t digest[PTLS_MAX_DIGEST_SIZE];
1410
            ctx->final(ctx, digest, PTLS_HASH_FINAL_MODE_SNAPSHOT);
1411
            PTLS_DEBUGF("  %zu: %02x%02x%02x%02x\n", i, digest[0], digest[1], digest[2], digest[3]);
1412
        }
1413
#endif
1414
0
    }
1415
0
}
1416
1417
static void key_schedule_update_ch1hash_prefix(ptls_key_schedule_t *sched)
1418
0
{
1419
0
    uint8_t prefix[4] = {PTLS_HANDSHAKE_TYPE_MESSAGE_HASH, 0, 0, (uint8_t)sched->hashes[0].algo->digest_size};
1420
0
    ptls__key_schedule_update_hash(sched, prefix, sizeof(prefix), 0);
1421
0
}
1422
1423
static void key_schedule_extract_ch1hash(ptls_key_schedule_t *sched, uint8_t *hash)
1424
0
{
1425
0
    assert(sched->hashes[0].ctx_outer == NULL);
1426
0
    sched->hashes[0].ctx->final(sched->hashes[0].ctx, hash, PTLS_HASH_FINAL_MODE_RESET);
1427
0
}
1428
1429
static void key_schedule_transform_post_ch1hash(ptls_key_schedule_t *sched)
1430
0
{
1431
0
    size_t digest_size = sched->hashes[0].algo->digest_size;
1432
0
    ptls_hash_context_t *hashes[3] = {sched->hashes[0].ctx, sched->hashes[0].ctx_outer, NULL};
1433
0
    uint8_t ch1hash[PTLS_MAX_DIGEST_SIZE];
1434
0
    uint8_t prefix[4] = {PTLS_HANDSHAKE_TYPE_MESSAGE_HASH, 0, 0, (uint8_t)digest_size};
1435
1436
0
    for (size_t i = 0; hashes[i] != NULL; ++i) {
1437
0
        hashes[i]->final(hashes[i], ch1hash, PTLS_HASH_FINAL_MODE_RESET);
1438
0
        hashes[i]->update(hashes[i], prefix, sizeof(prefix));
1439
0
        hashes[i]->update(hashes[i], ch1hash, digest_size);
1440
0
    }
1441
1442
0
    ptls_clear_memory(ch1hash, sizeof(ch1hash));
1443
0
}
1444
1445
static int derive_secret_with_hash(ptls_key_schedule_t *sched, void *secret, const char *label, const uint8_t *hash)
1446
0
{
1447
0
    int ret = ptls_hkdf_expand_label(sched->hashes[0].algo, secret, sched->hashes[0].algo->digest_size,
1448
0
                                     ptls_iovec_init(sched->secret, sched->hashes[0].algo->digest_size), label,
1449
0
                                     ptls_iovec_init(hash, sched->hashes[0].algo->digest_size), NULL);
1450
0
    PTLS_DEBUGF("%s: (label=%s, hash=%02x%02x) => %02x%02x\n", __FUNCTION__, label, hash[0], hash[1], ((uint8_t *)secret)[0],
1451
0
                ((uint8_t *)secret)[1]);
1452
0
    return ret;
1453
0
}
1454
1455
static int derive_secret(ptls_key_schedule_t *sched, void *secret, const char *label)
1456
0
{
1457
0
    uint8_t hash_value[PTLS_MAX_DIGEST_SIZE];
1458
1459
0
    sched->hashes[0].ctx->final(sched->hashes[0].ctx, hash_value, PTLS_HASH_FINAL_MODE_SNAPSHOT);
1460
0
    int ret = derive_secret_with_hash(sched, secret, label, hash_value);
1461
0
    ptls_clear_memory(hash_value, sizeof(hash_value));
1462
0
    return ret;
1463
0
}
1464
1465
static int derive_secret_with_empty_digest(ptls_key_schedule_t *sched, void *secret, const char *label)
1466
0
{
1467
0
    return derive_secret_with_hash(sched, secret, label, sched->hashes[0].algo->empty_digest);
1468
0
}
1469
1470
static int derive_exporter_secret(ptls_t *tls, int is_early)
1471
0
{
1472
0
    int ret;
1473
1474
0
    if (!tls->ctx->use_exporter)
1475
0
        return 0;
1476
1477
0
    uint8_t **slot = is_early ? &tls->exporter_master_secret.early : &tls->exporter_master_secret.one_rtt;
1478
0
    assert(*slot == NULL);
1479
0
    if ((*slot = malloc(tls->key_schedule->hashes[0].algo->digest_size)) == NULL)
1480
0
        return PTLS_ERROR_NO_MEMORY;
1481
1482
0
    if ((ret = derive_secret(tls->key_schedule, *slot, is_early ? "e exp master" : "exp master")) != 0)
1483
0
        return ret;
1484
1485
0
    log_secret(tls, is_early ? "EARLY_EXPORTER_SECRET" : "EXPORTER_SECRET",
1486
0
               ptls_iovec_init(*slot, tls->key_schedule->hashes[0].algo->digest_size));
1487
1488
0
    return 0;
1489
0
}
1490
1491
static void free_exporter_master_secret(ptls_t *tls, int is_early)
1492
0
{
1493
0
    uint8_t *slot = is_early ? tls->exporter_master_secret.early : tls->exporter_master_secret.one_rtt;
1494
0
    if (slot == NULL)
1495
0
        return;
1496
0
    assert(tls->key_schedule != NULL);
1497
0
    ptls_clear_memory(slot, tls->key_schedule->hashes[0].algo->digest_size);
1498
0
    free(slot);
1499
0
}
1500
1501
static int derive_resumption_secret(ptls_key_schedule_t *sched, uint8_t *secret, ptls_iovec_t nonce)
1502
0
{
1503
0
    int ret;
1504
1505
0
    if ((ret = derive_secret(sched, secret, "res master")) != 0)
1506
0
        goto Exit;
1507
0
    if ((ret = ptls_hkdf_expand_label(sched->hashes[0].algo, secret, sched->hashes[0].algo->digest_size,
1508
0
                                      ptls_iovec_init(secret, sched->hashes[0].algo->digest_size), "resumption", nonce, NULL)) != 0)
1509
0
        goto Exit;
1510
1511
0
Exit:
1512
0
    if (ret != 0)
1513
0
        ptls_clear_memory(secret, sched->hashes[0].algo->digest_size);
1514
0
    return ret;
1515
0
}
1516
1517
static int decode_new_session_ticket(ptls_t *tls, uint32_t *lifetime, uint32_t *age_add, ptls_iovec_t *nonce, ptls_iovec_t *ticket,
1518
                                     uint32_t *max_early_data_size, const uint8_t *src, const uint8_t *const end)
1519
0
{
1520
0
    uint16_t exttype;
1521
0
    int ret;
1522
1523
0
    if ((ret = ptls_decode32(lifetime, &src, end)) != 0)
1524
0
        goto Exit;
1525
0
    if ((ret = ptls_decode32(age_add, &src, end)) != 0)
1526
0
        goto Exit;
1527
0
    ptls_decode_open_block(src, end, 1, {
1528
0
        *nonce = ptls_iovec_init(src, end - src);
1529
0
        src = end;
1530
0
    });
1531
0
    ptls_decode_open_block(src, end, 2, {
1532
0
        if (src == end) {
1533
0
            ret = PTLS_ALERT_DECODE_ERROR;
1534
0
            goto Exit;
1535
0
        }
1536
0
        *ticket = ptls_iovec_init(src, end - src);
1537
0
        src = end;
1538
0
    });
1539
1540
0
    *max_early_data_size = 0;
1541
0
    decode_extensions(src, end, PTLS_HANDSHAKE_TYPE_NEW_SESSION_TICKET, &exttype, {
1542
0
        if (tls->ctx->on_extension != NULL &&
1543
0
            (ret = tls->ctx->on_extension->cb(tls->ctx->on_extension, tls, PTLS_HANDSHAKE_TYPE_NEW_SESSION_TICKET, exttype,
1544
0
                                              ptls_iovec_init(src, end - src)) != 0))
1545
0
            goto Exit;
1546
0
        switch (exttype) {
1547
0
        case PTLS_EXTENSION_TYPE_EARLY_DATA:
1548
0
            if ((ret = ptls_decode32(max_early_data_size, &src, end)) != 0)
1549
0
                goto Exit;
1550
0
            break;
1551
0
        default:
1552
0
            src = end;
1553
0
            break;
1554
0
        }
1555
0
    });
1556
1557
0
    ret = 0;
1558
0
Exit:
1559
0
    return ret;
1560
0
}
1561
1562
static int decode_stored_session_ticket(ptls_t *tls, ptls_key_exchange_algorithm_t **key_share, ptls_cipher_suite_t **cs,
1563
                                        ptls_iovec_t *secret, uint32_t *obfuscated_ticket_age, ptls_iovec_t *ticket,
1564
                                        uint32_t *max_early_data_size, const uint8_t *src, const uint8_t *const end)
1565
0
{
1566
0
    uint16_t kxid, csid;
1567
0
    uint32_t lifetime, age_add;
1568
0
    uint64_t obtained_at, now;
1569
0
    ptls_iovec_t nonce;
1570
0
    int ret;
1571
1572
    /* decode */
1573
0
    if ((ret = ptls_decode64(&obtained_at, &src, end)) != 0)
1574
0
        goto Exit;
1575
0
    if ((ret = ptls_decode16(&kxid, &src, end)) != 0)
1576
0
        goto Exit;
1577
0
    if ((ret = ptls_decode16(&csid, &src, end)) != 0)
1578
0
        goto Exit;
1579
0
    ptls_decode_open_block(src, end, 3, {
1580
0
        if ((ret = decode_new_session_ticket(tls, &lifetime, &age_add, &nonce, ticket, max_early_data_size, src, end)) != 0)
1581
0
            goto Exit;
1582
0
        src = end;
1583
0
    });
1584
0
    ptls_decode_block(src, end, 2, {
1585
0
        *secret = ptls_iovec_init(src, end - src);
1586
0
        src = end;
1587
0
    });
1588
1589
0
    { /* determine the key-exchange */
1590
0
        ptls_key_exchange_algorithm_t **cand;
1591
0
        for (cand = tls->ctx->key_exchanges; *cand != NULL; ++cand)
1592
0
            if ((*cand)->id == kxid)
1593
0
                break;
1594
0
        if (*cand == NULL) {
1595
0
            ret = PTLS_ERROR_LIBRARY;
1596
0
            goto Exit;
1597
0
        }
1598
0
        *key_share = *cand;
1599
0
    }
1600
1601
0
    { /* determine the cipher-suite */
1602
0
        ptls_cipher_suite_t **cand;
1603
0
        for (cand = tls->ctx->cipher_suites; *cand != NULL; ++cand)
1604
0
            if ((*cand)->id == csid)
1605
0
                break;
1606
0
        if (*cand == NULL) {
1607
0
            ret = PTLS_ERROR_LIBRARY;
1608
0
            goto Exit;
1609
0
        }
1610
0
        *cs = *cand;
1611
0
    }
1612
1613
    /* calculate obfuscated_ticket_age */
1614
0
    now = tls->ctx->get_time->cb(tls->ctx->get_time);
1615
0
    if (!(obtained_at <= now && now - obtained_at < 7 * 86400 * 1000)) {
1616
0
        ret = PTLS_ERROR_LIBRARY;
1617
0
        goto Exit;
1618
0
    }
1619
0
    *obfuscated_ticket_age = (uint32_t)(now - obtained_at) + age_add;
1620
1621
0
    ret = 0;
1622
0
Exit:
1623
0
    return ret;
1624
0
}
1625
1626
static int get_traffic_key(ptls_hash_algorithm_t *algo, void *key, size_t key_size, int is_iv, const void *secret,
1627
                           ptls_iovec_t hash_value, const char *label_prefix)
1628
0
{
1629
0
    return ptls_hkdf_expand_label(algo, key, key_size, ptls_iovec_init(secret, algo->digest_size), is_iv ? "iv" : "key", hash_value,
1630
0
                                  label_prefix);
1631
0
}
1632
1633
static int get_traffic_keys(ptls_aead_algorithm_t *aead, ptls_hash_algorithm_t *hash, void *key, void *iv, const void *secret,
1634
                            ptls_iovec_t hash_value, const char *label_prefix)
1635
0
{
1636
0
    int ret;
1637
1638
0
    if ((ret = get_traffic_key(hash, key, aead->key_size, 0, secret, hash_value, label_prefix)) != 0 ||
1639
0
        (ret = get_traffic_key(hash, iv, aead->iv_size, 1, secret, hash_value, label_prefix)) != 0) {
1640
0
        ptls_clear_memory(key, aead->key_size);
1641
0
        ptls_clear_memory(iv, aead->iv_size);
1642
0
    }
1643
1644
0
    return ret;
1645
0
}
1646
1647
static int setup_traffic_protection(ptls_t *tls, int is_enc, const char *secret_label, size_t epoch, uint64_t seq, int skip_notify)
1648
0
{
1649
0
    static const char *log_labels[2][4] = {
1650
0
        {NULL, "CLIENT_EARLY_TRAFFIC_SECRET", "CLIENT_HANDSHAKE_TRAFFIC_SECRET", "CLIENT_TRAFFIC_SECRET_0"},
1651
0
        {NULL, NULL, "SERVER_HANDSHAKE_TRAFFIC_SECRET", "SERVER_TRAFFIC_SECRET_0"}};
1652
0
    struct st_ptls_traffic_protection_t *ctx = is_enc ? &tls->traffic_protection.enc : &tls->traffic_protection.dec;
1653
1654
0
    if (secret_label != NULL) {
1655
0
        int ret;
1656
0
        if ((ret = derive_secret(tls->key_schedule, ctx->secret, secret_label)) != 0)
1657
0
            return ret;
1658
0
    }
1659
1660
0
    ctx->epoch = epoch;
1661
1662
0
    log_secret(tls, log_labels[ptls_is_server(tls) == is_enc][epoch],
1663
0
               ptls_iovec_init(ctx->secret, tls->key_schedule->hashes[0].algo->digest_size));
1664
1665
    /* special path for applications having their own record layer */
1666
0
    if (tls->ctx->update_traffic_key != NULL) {
1667
0
        if (skip_notify)
1668
0
            return 0;
1669
0
        return tls->ctx->update_traffic_key->cb(tls->ctx->update_traffic_key, tls, is_enc, epoch, ctx->secret);
1670
0
    }
1671
1672
0
    if (ctx->aead != NULL)
1673
0
        ptls_aead_free(ctx->aead);
1674
0
    if ((ctx->aead = ptls_aead_new(tls->cipher_suite->aead, tls->cipher_suite->hash, is_enc, ctx->secret,
1675
0
                                   tls->ctx->hkdf_label_prefix__obsolete)) == NULL)
1676
0
        return PTLS_ERROR_NO_MEMORY; /* TODO obtain error from ptls_aead_new */
1677
0
    ctx->seq = seq;
1678
1679
#if defined(PTLS_DEBUG) && PTLS_DEBUG
1680
    {
1681
        uint8_t static_iv[PTLS_MAX_IV_SIZE];
1682
        ptls_aead_get_iv(ctx->aead, static_iv);
1683
        PTLS_DEBUGF("[%s] %02x%02x,%02x%02x\n", log_labels[ptls_is_server(tls)][epoch], (unsigned)ctx->secret[0],
1684
                    (unsigned)ctx->secret[1], static_iv[0], static_iv[1]);
1685
    }
1686
#endif
1687
1688
0
    return 0;
1689
0
}
1690
1691
static int commission_handshake_secret(ptls_t *tls)
1692
0
{
1693
0
    int is_enc = !ptls_is_server(tls);
1694
1695
0
    assert(tls->pending_handshake_secret != NULL);
1696
0
    memcpy((is_enc ? &tls->traffic_protection.enc : &tls->traffic_protection.dec)->secret, tls->pending_handshake_secret,
1697
0
           PTLS_MAX_DIGEST_SIZE);
1698
0
    ptls_clear_memory(tls->pending_handshake_secret, PTLS_MAX_DIGEST_SIZE);
1699
0
    free(tls->pending_handshake_secret);
1700
0
    tls->pending_handshake_secret = NULL;
1701
1702
0
    return setup_traffic_protection(tls, is_enc, NULL, 2, 0, 1);
1703
0
}
1704
1705
static void log_client_random(ptls_t *tls)
1706
0
{
1707
#if PICOTLS_USE_DTRACE
1708
    char buf[sizeof(tls->client_random) * 2 + 1];
1709
#endif
1710
1711
0
    PTLS_PROBE(CLIENT_RANDOM, tls, ptls_hexdump(buf, tls->client_random, sizeof(tls->client_random)));
1712
0
    PTLS_LOG_CONN(client_random, tls, { PTLS_LOG_ELEMENT_HEXDUMP(bytes, tls->client_random, sizeof(tls->client_random)); });
1713
0
}
1714
1715
#define SESSION_IDENTIFIER_MAGIC "ptls0001" /* the number should be changed upon incompatible format change */
1716
#define SESSION_IDENTIFIER_MAGIC_SIZE (sizeof(SESSION_IDENTIFIER_MAGIC) - 1)
1717
1718
static int encode_session_identifier(ptls_context_t *ctx, ptls_buffer_t *buf, uint32_t ticket_age_add, ptls_iovec_t ticket_nonce,
1719
                                     ptls_key_schedule_t *sched, const char *server_name, uint16_t key_exchange_id, uint16_t csid,
1720
                                     const char *negotiated_protocol)
1721
0
{
1722
0
    int ret = 0;
1723
1724
0
    ptls_buffer_push_block(buf, 2, {
1725
        /* format id */
1726
0
        ptls_buffer_pushv(buf, SESSION_IDENTIFIER_MAGIC, SESSION_IDENTIFIER_MAGIC_SIZE);
1727
        /* date */
1728
0
        ptls_buffer_push64(buf, ctx->get_time->cb(ctx->get_time));
1729
        /* resumption master secret */
1730
0
        ptls_buffer_push_block(buf, 2, {
1731
0
            if ((ret = ptls_buffer_reserve(buf, sched->hashes[0].algo->digest_size)) != 0)
1732
0
                goto Exit;
1733
0
            if ((ret = derive_resumption_secret(sched, buf->base + buf->off, ticket_nonce)) != 0)
1734
0
                goto Exit;
1735
0
            buf->off += sched->hashes[0].algo->digest_size;
1736
0
        });
1737
        /* key-exchange */
1738
0
        ptls_buffer_push16(buf, key_exchange_id);
1739
        /* cipher-suite */
1740
0
        ptls_buffer_push16(buf, csid);
1741
        /* ticket_age_add */
1742
0
        ptls_buffer_push32(buf, ticket_age_add);
1743
        /* session ID context */
1744
0
        ptls_buffer_push_block(buf, 2, {
1745
0
            if (ctx->ticket_context.is_set) {
1746
0
                ptls_buffer_pushv(buf, ctx->ticket_context.bytes, sizeof(ctx->ticket_context.bytes));
1747
0
            } else if (server_name != NULL) {
1748
0
                ptls_buffer_pushv(buf, server_name, strlen(server_name));
1749
0
            }
1750
0
        });
1751
        /* alpn */
1752
0
        ptls_buffer_push_block(buf, 1, {
1753
0
            if (negotiated_protocol != NULL)
1754
0
                ptls_buffer_pushv(buf, negotiated_protocol, strlen(negotiated_protocol));
1755
0
        });
1756
0
    });
1757
1758
0
Exit:
1759
0
    return ret;
1760
0
}
1761
1762
int decode_session_identifier(uint64_t *issued_at, ptls_iovec_t *psk, uint32_t *ticket_age_add, ptls_iovec_t *ticket_ctx,
1763
                              uint16_t *key_exchange_id, uint16_t *csid, ptls_iovec_t *negotiated_protocol, const uint8_t *src,
1764
                              const uint8_t *const end)
1765
0
{
1766
0
    int ret = 0;
1767
1768
0
    ptls_decode_block(src, end, 2, {
1769
0
        if (end - src < SESSION_IDENTIFIER_MAGIC_SIZE ||
1770
0
            memcmp(src, SESSION_IDENTIFIER_MAGIC, SESSION_IDENTIFIER_MAGIC_SIZE) != 0) {
1771
0
            ret = PTLS_ALERT_DECODE_ERROR;
1772
0
            goto Exit;
1773
0
        }
1774
0
        src += SESSION_IDENTIFIER_MAGIC_SIZE;
1775
0
        if ((ret = ptls_decode64(issued_at, &src, end)) != 0)
1776
0
            goto Exit;
1777
0
        ptls_decode_open_block(src, end, 2, {
1778
0
            *psk = ptls_iovec_init(src, end - src);
1779
0
            src = end;
1780
0
        });
1781
0
        if ((ret = ptls_decode16(key_exchange_id, &src, end)) != 0)
1782
0
            goto Exit;
1783
0
        if ((ret = ptls_decode16(csid, &src, end)) != 0)
1784
0
            goto Exit;
1785
0
        if ((ret = ptls_decode32(ticket_age_add, &src, end)) != 0)
1786
0
            goto Exit;
1787
0
        ptls_decode_open_block(src, end, 2, {
1788
0
            *ticket_ctx = ptls_iovec_init(src, end - src);
1789
0
            src = end;
1790
0
        });
1791
0
        ptls_decode_open_block(src, end, 1, {
1792
0
            *negotiated_protocol = ptls_iovec_init(src, end - src);
1793
0
            src = end;
1794
0
        });
1795
0
    });
1796
1797
0
Exit:
1798
0
    return ret;
1799
0
}
1800
1801
static size_t build_certificate_verify_signdata(uint8_t *data, ptls_key_schedule_t *sched, const char *context_string)
1802
0
{
1803
0
    size_t datalen = 0;
1804
1805
0
    memset(data + datalen, 32, 64);
1806
0
    datalen += 64;
1807
0
    memcpy(data + datalen, context_string, strlen(context_string) + 1);
1808
0
    datalen += strlen(context_string) + 1;
1809
0
    sched->hashes[0].ctx->final(sched->hashes[0].ctx, data + datalen, PTLS_HASH_FINAL_MODE_SNAPSHOT);
1810
0
    datalen += sched->hashes[0].algo->digest_size;
1811
0
    assert(datalen <= PTLS_MAX_CERTIFICATE_VERIFY_SIGNDATA_SIZE);
1812
1813
0
    return datalen;
1814
0
}
1815
1816
static int calc_verify_data(void *output, ptls_key_schedule_t *sched, const void *secret)
1817
0
{
1818
0
    ptls_hash_context_t *hmac;
1819
0
    uint8_t digest[PTLS_MAX_DIGEST_SIZE];
1820
0
    int ret;
1821
1822
0
    if ((ret = ptls_hkdf_expand_label(sched->hashes[0].algo, digest, sched->hashes[0].algo->digest_size,
1823
0
                                      ptls_iovec_init(secret, sched->hashes[0].algo->digest_size), "finished",
1824
0
                                      ptls_iovec_init(NULL, 0), NULL)) != 0)
1825
0
        return ret;
1826
0
    if ((hmac = ptls_hmac_create(sched->hashes[0].algo, digest, sched->hashes[0].algo->digest_size)) == NULL) {
1827
0
        ptls_clear_memory(digest, sizeof(digest));
1828
0
        return PTLS_ERROR_NO_MEMORY;
1829
0
    }
1830
1831
0
    sched->hashes[0].ctx->final(sched->hashes[0].ctx, digest, PTLS_HASH_FINAL_MODE_SNAPSHOT);
1832
0
    PTLS_DEBUGF("%s: %02x%02x,%02x%02x\n", __FUNCTION__, ((uint8_t *)secret)[0], ((uint8_t *)secret)[1], digest[0], digest[1]);
1833
0
    hmac->update(hmac, digest, sched->hashes[0].algo->digest_size);
1834
0
    ptls_clear_memory(digest, sizeof(digest));
1835
0
    hmac->final(hmac, output, PTLS_HASH_FINAL_MODE_FREE);
1836
1837
0
    return 0;
1838
0
}
1839
1840
static int verify_finished(ptls_t *tls, ptls_iovec_t message)
1841
0
{
1842
0
    uint8_t verify_data[PTLS_MAX_DIGEST_SIZE];
1843
0
    int ret;
1844
1845
0
    if (PTLS_HANDSHAKE_HEADER_SIZE + tls->key_schedule->hashes[0].algo->digest_size != message.len) {
1846
0
        ret = PTLS_ALERT_DECODE_ERROR;
1847
0
        goto Exit;
1848
0
    }
1849
1850
0
    if ((ret = calc_verify_data(verify_data, tls->key_schedule, tls->traffic_protection.dec.secret)) != 0)
1851
0
        goto Exit;
1852
0
    if (!ptls_mem_equal(message.base + PTLS_HANDSHAKE_HEADER_SIZE, verify_data, tls->key_schedule->hashes[0].algo->digest_size)) {
1853
0
        ret = PTLS_ALERT_HANDSHAKE_FAILURE;
1854
0
        goto Exit;
1855
0
    }
1856
1857
0
Exit:
1858
0
    ptls_clear_memory(verify_data, sizeof(verify_data));
1859
0
    return ret;
1860
0
}
1861
1862
static int send_finished(ptls_t *tls, ptls_message_emitter_t *emitter)
1863
0
{
1864
0
    int ret;
1865
1866
0
    ptls_push_message(emitter, tls->key_schedule, PTLS_HANDSHAKE_TYPE_FINISHED, {
1867
0
        if ((ret = ptls_buffer_reserve(emitter->buf, tls->key_schedule->hashes[0].algo->digest_size)) != 0)
1868
0
            goto Exit;
1869
0
        if ((ret = calc_verify_data(emitter->buf->base + emitter->buf->off, tls->key_schedule,
1870
0
                                    tls->traffic_protection.enc.secret)) != 0)
1871
0
            goto Exit;
1872
0
        emitter->buf->off += tls->key_schedule->hashes[0].algo->digest_size;
1873
0
    });
1874
1875
0
Exit:
1876
0
    return ret;
1877
0
}
1878
1879
static int send_session_ticket(ptls_t *tls, ptls_message_emitter_t *emitter)
1880
0
{
1881
0
    ptls_hash_context_t *msghash_backup = tls->key_schedule->hashes[0].ctx->clone_(tls->key_schedule->hashes[0].ctx);
1882
0
    ptls_buffer_t session_id;
1883
0
    char session_id_smallbuf[128];
1884
0
    uint32_t ticket_age_add;
1885
0
    int ret = 0;
1886
1887
0
    assert(tls->ctx->ticket_lifetime != 0);
1888
0
    assert(tls->ctx->encrypt_ticket != NULL);
1889
1890
0
    ptls_buffer_init(&session_id, session_id_smallbuf, sizeof(session_id_smallbuf));
1891
1892
0
    { /* calculate verify-data that will be sent by the client */
1893
0
        size_t orig_off = emitter->buf->off;
1894
0
        if (tls->pending_handshake_secret != NULL && !tls->ctx->omit_end_of_early_data) {
1895
0
            assert(tls->state == PTLS_STATE_SERVER_EXPECT_END_OF_EARLY_DATA);
1896
0
            ptls_buffer_push_message_body(emitter->buf, tls->key_schedule, PTLS_HANDSHAKE_TYPE_END_OF_EARLY_DATA, {});
1897
0
            emitter->buf->off = orig_off;
1898
0
        }
1899
0
        ptls_buffer_push_message_body(emitter->buf, tls->key_schedule, PTLS_HANDSHAKE_TYPE_FINISHED, {
1900
0
            if ((ret = ptls_buffer_reserve(emitter->buf, tls->key_schedule->hashes[0].algo->digest_size)) != 0)
1901
0
                goto Exit;
1902
0
            if ((ret = calc_verify_data(emitter->buf->base + emitter->buf->off, tls->key_schedule,
1903
0
                                        tls->pending_handshake_secret != NULL ? tls->pending_handshake_secret
1904
0
                                                                              : tls->traffic_protection.dec.secret)) != 0)
1905
0
                goto Exit;
1906
0
            emitter->buf->off += tls->key_schedule->hashes[0].algo->digest_size;
1907
0
        });
1908
0
        emitter->buf->off = orig_off;
1909
0
    }
1910
1911
0
    tls->ctx->random_bytes(&ticket_age_add, sizeof(ticket_age_add));
1912
1913
    /* build the raw nsk */
1914
0
    if (tls->key_share != NULL && (ret = encode_session_identifier(tls->ctx, &session_id, ticket_age_add, ptls_iovec_init(NULL, 0),
1915
0
                                                                   tls->key_schedule, tls->server_name, tls->key_share->id,
1916
0
                                                                   tls->cipher_suite->id, tls->negotiated_protocol)) != 0)
1917
0
        goto Exit;
1918
1919
    /* encrypt and send */
1920
0
    ptls_push_message(emitter, tls->key_schedule, PTLS_HANDSHAKE_TYPE_NEW_SESSION_TICKET, {
1921
0
        ptls_buffer_push32(emitter->buf, tls->ctx->ticket_lifetime);
1922
0
        ptls_buffer_push32(emitter->buf, ticket_age_add);
1923
0
        ptls_buffer_push_block(emitter->buf, 1, {});
1924
0
        ptls_buffer_push_block(emitter->buf, 2, {
1925
0
            if ((ret = tls->ctx->encrypt_ticket->cb(tls->ctx->encrypt_ticket, tls, 1, emitter->buf,
1926
0
                                                    ptls_iovec_init(session_id.base, session_id.off))) != 0)
1927
0
                goto Exit;
1928
0
        });
1929
0
        ptls_buffer_push_block(emitter->buf, 2, {
1930
0
            if (tls->ctx->max_early_data_size != 0)
1931
0
                buffer_push_extension(emitter->buf, PTLS_EXTENSION_TYPE_EARLY_DATA,
1932
0
                                      { ptls_buffer_push32(emitter->buf, tls->ctx->max_early_data_size); });
1933
0
        });
1934
0
    });
1935
1936
0
Exit:
1937
0
    ptls_buffer_dispose(&session_id);
1938
1939
    /* restore handshake state */
1940
0
    tls->key_schedule->hashes[0].ctx->final(tls->key_schedule->hashes[0].ctx, NULL, PTLS_HASH_FINAL_MODE_FREE);
1941
0
    tls->key_schedule->hashes[0].ctx = msghash_backup;
1942
1943
0
    return ret;
1944
0
}
1945
1946
static int push_change_cipher_spec(ptls_t *tls, ptls_message_emitter_t *emitter)
1947
0
{
1948
0
    int ret;
1949
1950
    /* check if we are requested to (or still need to) */
1951
0
    if (!tls->send_change_cipher_spec) {
1952
0
        ret = 0;
1953
0
        goto Exit;
1954
0
    }
1955
1956
    /* CCS is a record, can only be sent when using a record-based protocol. */
1957
0
    if (emitter->begin_message != begin_record_message) {
1958
0
        ret = PTLS_ALERT_UNEXPECTED_MESSAGE;
1959
0
        goto Exit;
1960
0
    }
1961
1962
    /* emit CCS */
1963
0
    buffer_push_record(emitter->buf, PTLS_CONTENT_TYPE_CHANGE_CIPHER_SPEC, { ptls_buffer_push(emitter->buf, 1); });
1964
1965
0
    tls->send_change_cipher_spec = 0;
1966
0
    ret = 0;
1967
0
Exit:
1968
0
    return ret;
1969
0
}
1970
1971
static int push_additional_extensions(ptls_handshake_properties_t *properties, ptls_buffer_t *sendbuf)
1972
0
{
1973
0
    int ret;
1974
1975
0
    if (properties != NULL && properties->additional_extensions != NULL) {
1976
0
        ptls_raw_extension_t *ext;
1977
0
        for (ext = properties->additional_extensions; ext->type != UINT16_MAX; ++ext) {
1978
0
            buffer_push_extension(sendbuf, ext->type, { ptls_buffer_pushv(sendbuf, ext->data.base, ext->data.len); });
1979
0
        }
1980
0
    }
1981
0
    ret = 0;
1982
0
Exit:
1983
0
    return ret;
1984
0
}
1985
1986
static int push_signature_algorithms(ptls_verify_certificate_t *vc, ptls_buffer_t *sendbuf)
1987
0
{
1988
    /* The list sent when verify callback is not registered */
1989
0
    static const uint16_t default_algos[] = {PTLS_SIGNATURE_RSA_PSS_RSAE_SHA384, PTLS_SIGNATURE_RSA_PSS_RSAE_SHA256,
1990
0
                                             PTLS_SIGNATURE_ECDSA_SECP384R1_SHA384, PTLS_SIGNATURE_ECDSA_SECP256R1_SHA256,
1991
0
                                             PTLS_SIGNATURE_RSA_PKCS1_SHA256, PTLS_SIGNATURE_RSA_PKCS1_SHA1, UINT16_MAX};
1992
0
    int ret;
1993
1994
0
    ptls_buffer_push_block(sendbuf, 2, {
1995
0
        for (const uint16_t *p = vc != NULL ? vc->algos : default_algos; *p != UINT16_MAX; ++p)
1996
0
            ptls_buffer_push16(sendbuf, *p);
1997
0
    });
1998
1999
0
    ret = 0;
2000
0
Exit:
2001
0
    return ret;
2002
0
}
2003
2004
static int decode_signature_algorithms(struct st_ptls_signature_algorithms_t *sa, const uint8_t **src, const uint8_t *end)
2005
0
{
2006
0
    int ret;
2007
2008
0
    ptls_decode_block(*src, end, 2, {
2009
0
        do {
2010
0
            uint16_t id;
2011
0
            if ((ret = ptls_decode16(&id, src, end)) != 0)
2012
0
                goto Exit;
2013
0
            if (sa->count < PTLS_ELEMENTSOF(sa->list))
2014
0
                sa->list[sa->count++] = id;
2015
0
        } while (*src != end);
2016
0
    });
2017
2018
0
    ret = 0;
2019
0
Exit:
2020
0
    return ret;
2021
0
}
2022
2023
/**
2024
 * @param hash optional argument for restricting the underlying hash algorithm
2025
 */
2026
static int select_cipher(ptls_cipher_suite_t **selected, ptls_cipher_suite_t **candidates, const uint8_t *src,
2027
                         const uint8_t *const end, int server_preference, int server_chacha_priority, ptls_hash_algorithm_t *hash)
2028
0
{
2029
0
    size_t found_index = SIZE_MAX;
2030
0
    int ret;
2031
2032
0
    while (src != end) {
2033
0
        uint16_t id;
2034
0
        if ((ret = ptls_decode16(&id, &src, end)) != 0)
2035
0
            goto Exit;
2036
0
        for (size_t i = 0; candidates[i] != NULL; ++i) {
2037
0
            if (candidates[i]->id == id && (hash == NULL || candidates[i]->hash == hash)) {
2038
0
                if (server_preference && !(server_chacha_priority && id == PTLS_CIPHER_SUITE_CHACHA20_POLY1305_SHA256)) {
2039
                    /* preserve smallest matching index, and proceed to the next input */
2040
0
                    if (i < found_index) {
2041
0
                        found_index = i;
2042
0
                        break;
2043
0
                    }
2044
0
                } else {
2045
                    /* return the pointer matching to the first input that can be used */
2046
0
                    *selected = candidates[i];
2047
0
                    goto Exit;
2048
0
                }
2049
0
            }
2050
0
        }
2051
        /* first position of the server list matched (server_preference) */
2052
0
        if (found_index == 0)
2053
0
            break;
2054
        /* server preference is overridden only if the first entry of client-provided list is chachapoly */
2055
0
        server_chacha_priority = 0;
2056
0
    }
2057
0
    if (found_index != SIZE_MAX) {
2058
0
        *selected = candidates[found_index];
2059
0
        ret = 0;
2060
0
    } else {
2061
0
        ret = PTLS_ALERT_HANDSHAKE_FAILURE;
2062
0
    }
2063
2064
0
Exit:
2065
0
    return ret;
2066
0
}
2067
2068
static int push_key_share_entry(ptls_buffer_t *buf, uint16_t group, ptls_iovec_t pubkey)
2069
0
{
2070
0
    int ret;
2071
2072
0
    ptls_buffer_push16(buf, group);
2073
0
    ptls_buffer_push_block(buf, 2, { ptls_buffer_pushv(buf, pubkey.base, pubkey.len); });
2074
0
    ret = 0;
2075
0
Exit:
2076
0
    return ret;
2077
0
}
2078
2079
static int decode_key_share_entry(uint16_t *group, ptls_iovec_t *key_exchange, const uint8_t **src, const uint8_t *const end)
2080
0
{
2081
0
    int ret;
2082
2083
0
    if ((ret = ptls_decode16(group, src, end)) != 0)
2084
0
        goto Exit;
2085
0
    ptls_decode_open_block(*src, end, 2, {
2086
0
        *key_exchange = ptls_iovec_init(*src, end - *src);
2087
0
        *src = end;
2088
0
    });
2089
2090
0
Exit:
2091
0
    return ret;
2092
0
}
2093
2094
static int select_key_share(ptls_key_exchange_algorithm_t **selected, ptls_iovec_t *peer_key,
2095
                            ptls_key_exchange_algorithm_t **candidates, const uint8_t **src, const uint8_t *const end,
2096
                            int expect_one)
2097
0
{
2098
0
    int ret;
2099
2100
0
    *selected = NULL;
2101
2102
0
    if (expect_one && *src == end) {
2103
0
        ret = PTLS_ALERT_ILLEGAL_PARAMETER;
2104
0
        goto Exit;
2105
0
    }
2106
2107
0
    while (*src != end) {
2108
0
        uint16_t group;
2109
0
        ptls_iovec_t key;
2110
0
        if ((ret = decode_key_share_entry(&group, &key, src, end)) != 0)
2111
0
            goto Exit;
2112
0
        ptls_key_exchange_algorithm_t **c = candidates;
2113
0
        for (; *c != NULL; ++c) {
2114
0
            if (*selected == NULL && (*c)->id == group) {
2115
0
                *selected = *c;
2116
0
                *peer_key = key;
2117
0
            }
2118
0
        }
2119
0
        if (expect_one) {
2120
0
            ret = *selected != NULL ? 0 : PTLS_ALERT_ILLEGAL_PARAMETER;
2121
0
            goto Exit;
2122
0
        }
2123
0
    }
2124
2125
0
    ret = 0;
2126
2127
0
Exit:
2128
0
    return ret;
2129
0
}
2130
2131
static int emit_server_name_extension(ptls_buffer_t *buf, const char *server_name)
2132
0
{
2133
0
    int ret;
2134
2135
0
    ptls_buffer_push_block(buf, 2, {
2136
0
        ptls_buffer_push(buf, PTLS_SERVER_NAME_TYPE_HOSTNAME);
2137
0
        ptls_buffer_push_block(buf, 2, { ptls_buffer_pushv(buf, server_name, strlen(server_name)); });
2138
0
    });
2139
2140
0
    ret = 0;
2141
0
Exit:
2142
0
    return ret;
2143
0
}
2144
2145
/**
2146
 * Within the outer ECH extension, returns the number of bytes that preceeds the AEAD-encrypted payload.
2147
 */
2148
static inline size_t outer_ech_header_size(size_t enc_size)
2149
0
{
2150
0
    return 10 + enc_size;
2151
0
}
2152
2153
/**
2154
 * Flag to indicate which of ClientHelloInner, EncodedClientHelloInner, ClientHelloOuter is to be generated. When ECH is inactive,
2155
 * only ClientHelloInner is used.
2156
 */
2157
enum encode_ch_mode { ENCODE_CH_MODE_INNER, ENCODE_CH_MODE_ENCODED_INNER, ENCODE_CH_MODE_OUTER };
2158
2159
static int encode_client_hello(ptls_context_t *ctx, ptls_buffer_t *sendbuf, enum encode_ch_mode mode, int is_second_flight,
2160
                               ptls_handshake_properties_t *properties, const void *client_random,
2161
                               ptls_key_exchange_context_t *key_share_ctx, const char *sni_name, ptls_iovec_t legacy_session_id,
2162
                               struct st_ptls_ech_t *ech, size_t *ech_size_offset, ptls_iovec_t ech_replay, ptls_iovec_t psk_secret,
2163
                               ptls_iovec_t psk_identity, uint32_t obfuscated_ticket_age, size_t psk_binder_size,
2164
                               ptls_iovec_t *cookie, int using_early_data)
2165
0
{
2166
0
    int ret;
2167
2168
0
    assert(mode == ENCODE_CH_MODE_INNER || ech != NULL);
2169
2170
0
    ptls_buffer_push_message_body(sendbuf, NULL, PTLS_HANDSHAKE_TYPE_CLIENT_HELLO, {
2171
        /* legacy_version */
2172
0
        ptls_buffer_push16(sendbuf, 0x0303);
2173
        /* random_bytes */
2174
0
        ptls_buffer_pushv(sendbuf, client_random, PTLS_HELLO_RANDOM_SIZE);
2175
        /* lecagy_session_id */
2176
0
        ptls_buffer_push_block(sendbuf, 1, {
2177
0
            if (mode != ENCODE_CH_MODE_ENCODED_INNER)
2178
0
                ptls_buffer_pushv(sendbuf, legacy_session_id.base, legacy_session_id.len);
2179
0
        });
2180
        /* cipher_suites */
2181
0
        ptls_buffer_push_block(sendbuf, 2, {
2182
0
            ptls_cipher_suite_t **cs = ctx->cipher_suites;
2183
0
            for (; *cs != NULL; ++cs)
2184
0
                ptls_buffer_push16(sendbuf, (*cs)->id);
2185
0
        });
2186
        /* legacy_compression_methods */
2187
0
        ptls_buffer_push_block(sendbuf, 1, { ptls_buffer_push(sendbuf, 0); });
2188
        /* extensions */
2189
0
        ptls_buffer_push_block(sendbuf, 2, {
2190
0
            if (mode == ENCODE_CH_MODE_OUTER) {
2191
0
                buffer_push_extension(sendbuf, PTLS_EXTENSION_TYPE_ENCRYPTED_CLIENT_HELLO, {
2192
0
                    size_t ext_payload_from = sendbuf->off;
2193
0
                    ptls_buffer_push(sendbuf, PTLS_ECH_CLIENT_HELLO_TYPE_OUTER);
2194
0
                    ptls_buffer_push16(sendbuf, ech->cipher->id.kdf);
2195
0
                    ptls_buffer_push16(sendbuf, ech->cipher->id.aead);
2196
0
                    ptls_buffer_push(sendbuf, ech->config_id);
2197
0
                    ptls_buffer_push_block(sendbuf, 2, {
2198
0
                        if (!is_second_flight)
2199
0
                            ptls_buffer_pushv(sendbuf, ech->client.enc.base, ech->client.enc.len);
2200
0
                    });
2201
0
                    ptls_buffer_push_block(sendbuf, 2, {
2202
0
                        assert(sendbuf->off - ext_payload_from ==
2203
0
                               outer_ech_header_size(is_second_flight ? 0 : ech->client.enc.len));
2204
0
                        if ((ret = ptls_buffer_reserve(sendbuf, *ech_size_offset)) != 0)
2205
0
                            goto Exit;
2206
0
                        memset(sendbuf->base + sendbuf->off, 0, *ech_size_offset);
2207
0
                        sendbuf->off += *ech_size_offset;
2208
0
                        *ech_size_offset = sendbuf->off - *ech_size_offset;
2209
0
                    });
2210
0
                });
2211
0
            } else if (ech->aead != NULL) {
2212
0
                buffer_push_extension(sendbuf, PTLS_EXTENSION_TYPE_ENCRYPTED_CLIENT_HELLO,
2213
0
                                      { ptls_buffer_push(sendbuf, PTLS_ECH_CLIENT_HELLO_TYPE_INNER); });
2214
0
            } else if (ech_replay.base != NULL) {
2215
0
                buffer_push_extension(sendbuf, PTLS_EXTENSION_TYPE_ENCRYPTED_CLIENT_HELLO,
2216
0
                                      { ptls_buffer_pushv(sendbuf, ech_replay.base, ech_replay.len); });
2217
0
            }
2218
0
            if (mode == ENCODE_CH_MODE_ENCODED_INNER) {
2219
0
                buffer_push_extension(sendbuf, PTLS_EXTENSION_TYPE_ECH_OUTER_EXTENSIONS, {
2220
0
                    ptls_buffer_push_block(sendbuf, 1, { ptls_buffer_push16(sendbuf, PTLS_EXTENSION_TYPE_KEY_SHARE); });
2221
0
                });
2222
0
            } else {
2223
0
                buffer_push_extension(sendbuf, PTLS_EXTENSION_TYPE_KEY_SHARE, {
2224
0
                    ptls_buffer_push_block(sendbuf, 2, {
2225
0
                        if (key_share_ctx != NULL &&
2226
0
                            (ret = push_key_share_entry(sendbuf, key_share_ctx->algo->id, key_share_ctx->pubkey)) != 0)
2227
0
                            goto Exit;
2228
0
                    });
2229
0
                });
2230
0
            }
2231
0
            if (sni_name != NULL) {
2232
0
                buffer_push_extension(sendbuf, PTLS_EXTENSION_TYPE_SERVER_NAME, {
2233
0
                    if ((ret = emit_server_name_extension(sendbuf, sni_name)) != 0)
2234
0
                        goto Exit;
2235
0
                });
2236
0
            }
2237
0
            if (properties != NULL && properties->client.negotiated_protocols.count != 0) {
2238
0
                buffer_push_extension(sendbuf, PTLS_EXTENSION_TYPE_ALPN, {
2239
0
                    ptls_buffer_push_block(sendbuf, 2, {
2240
0
                        size_t i;
2241
0
                        for (i = 0; i != properties->client.negotiated_protocols.count; ++i) {
2242
0
                            ptls_buffer_push_block(sendbuf, 1, {
2243
0
                                ptls_iovec_t p = properties->client.negotiated_protocols.list[i];
2244
0
                                ptls_buffer_pushv(sendbuf, p.base, p.len);
2245
0
                            });
2246
0
                        }
2247
0
                    });
2248
0
                });
2249
0
            }
2250
0
            if (ctx->decompress_certificate != NULL) {
2251
0
                buffer_push_extension(sendbuf, PTLS_EXTENSION_TYPE_COMPRESS_CERTIFICATE, {
2252
0
                    ptls_buffer_push_block(sendbuf, 1, {
2253
0
                        const uint16_t *algo = ctx->decompress_certificate->supported_algorithms;
2254
0
                        assert(*algo != UINT16_MAX);
2255
0
                        for (; *algo != UINT16_MAX; ++algo)
2256
0
                            ptls_buffer_push16(sendbuf, *algo);
2257
0
                    });
2258
0
                });
2259
0
            }
2260
0
            buffer_push_extension(sendbuf, PTLS_EXTENSION_TYPE_SUPPORTED_VERSIONS, {
2261
0
                ptls_buffer_push_block(sendbuf, 1, {
2262
0
                    size_t i;
2263
0
                    for (i = 0; i != PTLS_ELEMENTSOF(supported_versions); ++i)
2264
0
                        ptls_buffer_push16(sendbuf, supported_versions[i]);
2265
0
                });
2266
0
            });
2267
0
            buffer_push_extension(sendbuf, PTLS_EXTENSION_TYPE_SIGNATURE_ALGORITHMS, {
2268
0
                if ((ret = push_signature_algorithms(ctx->verify_certificate, sendbuf)) != 0)
2269
0
                    goto Exit;
2270
0
            });
2271
0
            if (ctx->key_exchanges != NULL) {
2272
0
                buffer_push_extension(sendbuf, PTLS_EXTENSION_TYPE_SUPPORTED_GROUPS, {
2273
0
                    ptls_key_exchange_algorithm_t **algo = ctx->key_exchanges;
2274
0
                    ptls_buffer_push_block(sendbuf, 2, {
2275
0
                        for (; *algo != NULL; ++algo)
2276
0
                            ptls_buffer_push16(sendbuf, (*algo)->id);
2277
0
                    });
2278
0
                });
2279
0
            }
2280
0
            if (cookie != NULL && cookie->base != NULL) {
2281
0
                buffer_push_extension(sendbuf, PTLS_EXTENSION_TYPE_COOKIE, {
2282
0
                    ptls_buffer_push_block(sendbuf, 2, { ptls_buffer_pushv(sendbuf, cookie->base, cookie->len); });
2283
0
                });
2284
0
            }
2285
0
            if (ctx->use_raw_public_keys) {
2286
0
                buffer_push_extension(sendbuf, PTLS_EXTENSION_TYPE_SERVER_CERTIFICATE_TYPE, {
2287
0
                    ptls_buffer_push_block(sendbuf, 1, { ptls_buffer_push(sendbuf, PTLS_CERTIFICATE_TYPE_RAW_PUBLIC_KEY); });
2288
0
                });
2289
0
            }
2290
0
            if (ctx->save_ticket != NULL &&
2291
0
                (ctx->ticket_requests.client.new_session_count != 0 || ctx->ticket_requests.client.resumption_count != 0)) {
2292
0
                buffer_push_extension(sendbuf, PTLS_EXTENSION_TYPE_TICKET_REQUEST, {
2293
0
                    ptls_buffer_push(sendbuf, ctx->ticket_requests.client.new_session_count,
2294
0
                                     ctx->ticket_requests.client.resumption_count);
2295
0
                });
2296
0
            }
2297
0
            if ((ret = push_additional_extensions(properties, sendbuf)) != 0)
2298
0
                goto Exit;
2299
0
            if (ctx->save_ticket != NULL || psk_secret.base != NULL) {
2300
0
                buffer_push_extension(sendbuf, PTLS_EXTENSION_TYPE_PSK_KEY_EXCHANGE_MODES, {
2301
0
                    ptls_buffer_push_block(sendbuf, 1, {
2302
0
                        if (!ctx->require_dhe_on_psk)
2303
0
                            ptls_buffer_push(sendbuf, PTLS_PSK_KE_MODE_PSK);
2304
0
                        ptls_buffer_push(sendbuf, PTLS_PSK_KE_MODE_PSK_DHE);
2305
0
                    });
2306
0
                });
2307
0
            }
2308
0
            if (psk_secret.base != NULL) {
2309
0
                if (using_early_data && !is_second_flight)
2310
0
                    buffer_push_extension(sendbuf, PTLS_EXTENSION_TYPE_EARLY_DATA, {});
2311
                /* pre-shared key "MUST be the last extension in the ClientHello" (draft-17 section 4.2.6) */
2312
0
                buffer_push_extension(sendbuf, PTLS_EXTENSION_TYPE_PRE_SHARED_KEY, {
2313
0
                    ptls_buffer_push_block(sendbuf, 2, {
2314
0
                        ptls_buffer_push_block(sendbuf, 2, {
2315
0
                            if (mode == ENCODE_CH_MODE_OUTER && ech->state != PTLS_ECH_STATE_GREASE) {
2316
0
                                if ((ret = ptls_buffer_reserve(sendbuf, psk_identity.len)) != 0)
2317
0
                                    goto Exit;
2318
0
                                ctx->random_bytes(sendbuf->base + sendbuf->off, psk_identity.len);
2319
0
                                sendbuf->off += psk_identity.len;
2320
0
                            } else {
2321
0
                                ptls_buffer_pushv(sendbuf, psk_identity.base, psk_identity.len);
2322
0
                            }
2323
0
                        });
2324
0
                        uint32_t age;
2325
0
                        if (mode == ENCODE_CH_MODE_OUTER && ech->state != PTLS_ECH_STATE_GREASE) {
2326
0
                            ctx->random_bytes(&age, sizeof(age));
2327
0
                        } else {
2328
0
                            age = obfuscated_ticket_age;
2329
0
                        }
2330
0
                        ptls_buffer_push32(sendbuf, age);
2331
0
                    });
2332
                    /* allocate space for PSK binder. The space is filled initially filled by a random value (meeting the
2333
                     * requirement of ClientHelloOuter), and later gets filled with the correct binder value if necessary. */
2334
0
                    ptls_buffer_push_block(sendbuf, 2, {
2335
0
                        ptls_buffer_push_block(sendbuf, 1, {
2336
0
                            if ((ret = ptls_buffer_reserve(sendbuf, psk_binder_size)) != 0)
2337
0
                                goto Exit;
2338
0
                            ctx->random_bytes(sendbuf->base + sendbuf->off, psk_binder_size);
2339
0
                            sendbuf->off += psk_binder_size;
2340
0
                        });
2341
0
                    });
2342
0
                });
2343
0
            }
2344
0
        });
2345
0
    });
2346
2347
0
Exit:
2348
0
    return ret;
2349
0
}
2350
2351
/**
2352
 * Feeds the CH message into the hash, computing the PSK binder if necessary. `binder_key` must be derived before calling this
2353
 * function.
2354
 */
2355
static int update_ch_hash_and_binder(ptls_key_schedule_t *ks, uint8_t *ch, size_t ch_start, size_t ch_end, int has_psk,
2356
                                     uint8_t *binder_key, int is_outer)
2357
0
{
2358
0
    int ret = 0;
2359
0
    size_t hash_off = ch_start;
2360
2361
0
    if (has_psk) {
2362
0
        size_t psk_binder_off = ch_end - (3 + ks->hashes[0].algo->digest_size);
2363
0
        ptls__key_schedule_update_hash(ks, ch + hash_off, psk_binder_off - hash_off, is_outer);
2364
0
        hash_off = psk_binder_off;
2365
0
        if ((ret = calc_verify_data(ch + psk_binder_off + 3, ks, binder_key)) != 0)
2366
0
            return ret;
2367
0
    }
2368
0
    ptls__key_schedule_update_hash(ks, ch + hash_off, ch_end - hash_off, is_outer);
2369
2370
0
    return ret;
2371
0
}
2372
2373
static int send_client_hello(ptls_t *tls, ptls_message_emitter_t *emitter, ptls_handshake_properties_t *properties,
2374
                             ptls_iovec_t *cookie)
2375
0
{
2376
0
    struct {
2377
0
        ptls_iovec_t secret;
2378
0
        ptls_iovec_t identity;
2379
0
        const char *label;
2380
0
    } psk = {{NULL}};
2381
0
    uint32_t obfuscated_ticket_age = 0;
2382
0
    const char *sni_name = NULL;
2383
0
    size_t mess_start;
2384
0
    uint8_t binder_key[PTLS_MAX_DIGEST_SIZE];
2385
0
    ptls_buffer_t encoded_ch_inner;
2386
0
    int ret, is_second_flight = tls->key_schedule != NULL;
2387
2388
0
    ptls_buffer_init(&encoded_ch_inner, "", 0);
2389
2390
0
    if (tls->server_name != NULL && !ptls_server_name_is_ipaddr(tls->server_name))
2391
0
        sni_name = tls->server_name;
2392
2393
    /* try to use ECH (ignore broken ECHConfigList; it is delivered insecurely) */
2394
0
    if (properties != NULL) {
2395
0
        if (!is_second_flight && sni_name != NULL && tls->ctx->ech.client.ciphers != NULL) {
2396
0
            if (properties->client.ech.configs.len != 0) {
2397
0
                struct st_decoded_ech_config_t decoded;
2398
0
                client_decode_ech_config_list(tls->ctx, &decoded, properties->client.ech.configs);
2399
0
                if (decoded.kem != NULL && decoded.cipher != NULL) {
2400
0
                    if ((ret = client_setup_ech(&tls->ech, &decoded, tls->ctx->random_bytes)) != 0)
2401
0
                        goto Exit;
2402
0
                }
2403
0
            } else if (properties->client.ech.configs.base != NULL) {
2404
                /* zero-length config with non-NULL base indicates ECH greasing; NULL base means no ECH */
2405
0
                client_setup_ech_grease(&tls->ech, tls->ctx->random_bytes, tls->ctx->ech.client.kems, tls->ctx->ech.client.ciphers,
2406
0
                                        sni_name);
2407
0
                tls->ech.state = PTLS_ECH_STATE_GREASE;
2408
0
            }
2409
0
        }
2410
0
    }
2411
2412
    /* use external PSK if provided */
2413
0
    if (tls->ctx->pre_shared_key.identity.base != NULL) {
2414
0
        if (!is_second_flight) {
2415
0
            tls->client.offered_psk = 1;
2416
0
            for (size_t i = 0; tls->ctx->cipher_suites[i] != NULL; ++i) {
2417
0
                if (tls->ctx->cipher_suites[i]->hash == tls->ctx->pre_shared_key.hash) {
2418
0
                    tls->cipher_suite = tls->ctx->cipher_suites[i];
2419
0
                    break;
2420
0
                }
2421
0
            }
2422
0
            assert(tls->cipher_suite != NULL && "no compatible cipher-suite provided that matches psk.hash");
2423
0
            if (properties != NULL && properties->client.max_early_data_size != NULL) {
2424
0
                tls->client.using_early_data = 1;
2425
0
                *properties->client.max_early_data_size = SIZE_MAX;
2426
0
            }
2427
0
        } else {
2428
0
            assert(tls->cipher_suite != NULL && tls->cipher_suite->hash == tls->ctx->pre_shared_key.hash);
2429
0
        }
2430
0
        psk.secret = tls->ctx->pre_shared_key.secret;
2431
0
        psk.identity = tls->ctx->pre_shared_key.identity;
2432
0
        psk.label = "ext binder";
2433
0
    }
2434
2435
    /* try to setup resumption-related data, unless external PSK is used */
2436
0
    if (psk.secret.base == NULL && properties != NULL && properties->client.session_ticket.base != NULL &&
2437
0
        tls->ctx->key_exchanges != NULL) {
2438
0
        ptls_key_exchange_algorithm_t *key_share = NULL;
2439
0
        ptls_cipher_suite_t *cipher_suite = NULL;
2440
0
        uint32_t max_early_data_size;
2441
0
        if (decode_stored_session_ticket(tls, &key_share, &cipher_suite, &psk.secret, &obfuscated_ticket_age, &psk.identity,
2442
0
                                         &max_early_data_size, properties->client.session_ticket.base,
2443
0
                                         properties->client.session_ticket.base + properties->client.session_ticket.len) == 0) {
2444
0
            psk.label = "res binder";
2445
0
            tls->client.offered_psk = 1;
2446
            /* key-share selected by HRR should not be overridden */
2447
0
            if (tls->key_share == NULL)
2448
0
                tls->key_share = key_share;
2449
0
            tls->cipher_suite = cipher_suite;
2450
0
            if (!is_second_flight && max_early_data_size != 0 && properties->client.max_early_data_size != NULL) {
2451
0
                tls->client.using_early_data = 1;
2452
0
                *properties->client.max_early_data_size = max_early_data_size;
2453
0
            }
2454
0
        } else {
2455
0
            psk.secret = ptls_iovec_init(NULL, 0);
2456
0
        }
2457
0
    }
2458
2459
    /* send 0-RTT related signals back to the client */
2460
0
    if (properties != NULL) {
2461
0
        if (tls->client.using_early_data) {
2462
0
            properties->client.early_data_acceptance = PTLS_EARLY_DATA_ACCEPTANCE_UNKNOWN;
2463
0
        } else {
2464
0
            if (properties->client.max_early_data_size != NULL)
2465
0
                *properties->client.max_early_data_size = 0;
2466
0
            properties->client.early_data_acceptance = PTLS_EARLY_DATA_REJECTED;
2467
0
        }
2468
0
    }
2469
2470
    /* use the default key share if still not undetermined */
2471
0
    if (tls->key_share == NULL && tls->ctx->key_exchanges != NULL &&
2472
0
        !(properties != NULL && properties->client.negotiate_before_key_exchange))
2473
0
        tls->key_share = tls->ctx->key_exchanges[0];
2474
2475
    /* instantiate key share context */
2476
0
    assert(tls->client.key_share_ctx == NULL);
2477
0
    if (tls->key_share != NULL) {
2478
0
        if ((ret = tls->key_share->create(tls->key_share, &tls->client.key_share_ctx)) != 0)
2479
0
            goto Exit;
2480
0
    }
2481
2482
    /* initialize key schedule */
2483
0
    if (!is_second_flight) {
2484
0
        if ((tls->key_schedule = key_schedule_new(tls->cipher_suite, tls->ctx->cipher_suites, tls->ech.aead != NULL)) == NULL) {
2485
0
            ret = PTLS_ERROR_NO_MEMORY;
2486
0
            goto Exit;
2487
0
        }
2488
0
        if ((ret = key_schedule_extract(tls->key_schedule, psk.secret)) != 0)
2489
0
            goto Exit;
2490
0
    }
2491
2492
    /* start generating CH */
2493
0
    if ((ret = emitter->begin_message(emitter)) != 0)
2494
0
        goto Exit;
2495
0
    mess_start = emitter->buf->off;
2496
2497
    /* generate true (inner) CH */
2498
0
    if ((ret = encode_client_hello(tls->ctx, emitter->buf, ENCODE_CH_MODE_INNER, is_second_flight, properties,
2499
0
                                   tls->ech.aead != NULL ? tls->ech.inner_client_random : tls->client_random,
2500
0
                                   tls->client.key_share_ctx, sni_name, tls->client.legacy_session_id, &tls->ech, NULL,
2501
0
                                   tls->ech.client.first_ech, psk.secret, psk.identity, obfuscated_ticket_age,
2502
0
                                   tls->key_schedule->hashes[0].algo->digest_size, cookie, tls->client.using_early_data)) != 0)
2503
0
        goto Exit;
2504
2505
    /* update the message hash, filling in the PSK binder HMAC if necessary */
2506
0
    if (psk.secret.base != NULL) {
2507
0
        if ((ret = derive_secret_with_empty_digest(tls->key_schedule, binder_key, psk.label)) != 0)
2508
0
            goto Exit;
2509
0
    }
2510
0
    if ((ret = update_ch_hash_and_binder(tls->key_schedule, emitter->buf->base, mess_start, emitter->buf->off,
2511
0
                                         psk.secret.base != NULL, binder_key, 0)) != 0)
2512
0
        goto Exit;
2513
2514
    /* ECH */
2515
0
    if (tls->ech.aead != NULL) {
2516
        /* build EncodedCHInner */
2517
0
        if ((ret = encode_client_hello(tls->ctx, &encoded_ch_inner, ENCODE_CH_MODE_ENCODED_INNER, is_second_flight, properties,
2518
0
                                       tls->ech.inner_client_random, tls->client.key_share_ctx, sni_name,
2519
0
                                       tls->client.legacy_session_id, &tls->ech, NULL, ptls_iovec_init(NULL, 0), psk.secret,
2520
0
                                       psk.identity, obfuscated_ticket_age, tls->key_schedule->hashes[0].algo->digest_size, cookie,
2521
0
                                       tls->client.using_early_data)) != 0)
2522
0
            goto Exit;
2523
0
        if (psk.secret.base != NULL)
2524
0
            memcpy(encoded_ch_inner.base + encoded_ch_inner.off - tls->key_schedule->hashes[0].algo->digest_size,
2525
0
                   emitter->buf->base + emitter->buf->off - tls->key_schedule->hashes[0].algo->digest_size,
2526
0
                   tls->key_schedule->hashes[0].algo->digest_size);
2527
0
        { /* pad EncodedCHInner (following draft-ietf-tls-esni-15 6.1.3) */
2528
0
            size_t padding_len;
2529
0
            if (sni_name != NULL) {
2530
0
                padding_len = strlen(sni_name);
2531
0
                if (padding_len < tls->ech.client.max_name_length)
2532
0
                    padding_len = tls->ech.client.max_name_length;
2533
0
            } else {
2534
0
                padding_len = tls->ech.client.max_name_length + 9;
2535
0
            }
2536
0
            size_t final_len = encoded_ch_inner.off - PTLS_HANDSHAKE_HEADER_SIZE + padding_len;
2537
0
            final_len = (final_len + 31) / 32 * 32;
2538
0
            padding_len = final_len - (encoded_ch_inner.off - PTLS_HANDSHAKE_HEADER_SIZE);
2539
0
            if (padding_len != 0) {
2540
0
                if ((ret = ptls_buffer_reserve(&encoded_ch_inner, padding_len)) != 0)
2541
0
                    goto Exit;
2542
0
                memset(encoded_ch_inner.base + encoded_ch_inner.off, 0, padding_len);
2543
0
                encoded_ch_inner.off += padding_len;
2544
0
            }
2545
0
        }
2546
        /* flush CHInner, build CHOuterAAD */
2547
0
        emitter->buf->off = mess_start;
2548
0
        size_t ech_payload_size = encoded_ch_inner.off - PTLS_HANDSHAKE_HEADER_SIZE + tls->ech.aead->algo->tag_size,
2549
0
               ech_size_offset = ech_payload_size;
2550
0
        if ((ret = encode_client_hello(tls->ctx, emitter->buf, ENCODE_CH_MODE_OUTER, is_second_flight, properties,
2551
0
                                       tls->client_random, tls->client.key_share_ctx, tls->ech.client.public_name,
2552
0
                                       tls->client.legacy_session_id, &tls->ech, &ech_size_offset, ptls_iovec_init(NULL, 0),
2553
0
                                       psk.secret, psk.identity, obfuscated_ticket_age,
2554
0
                                       tls->key_schedule->hashes[0].algo->digest_size, cookie, tls->client.using_early_data)) != 0)
2555
0
            goto Exit;
2556
        /* overwrite ECH payload */
2557
0
        ptls_aead_encrypt(tls->ech.aead, emitter->buf->base + ech_size_offset, encoded_ch_inner.base + PTLS_HANDSHAKE_HEADER_SIZE,
2558
0
                          encoded_ch_inner.off - PTLS_HANDSHAKE_HEADER_SIZE, is_second_flight,
2559
0
                          emitter->buf->base + mess_start + PTLS_HANDSHAKE_HEADER_SIZE,
2560
0
                          emitter->buf->off - (mess_start + PTLS_HANDSHAKE_HEADER_SIZE));
2561
        /* keep the copy of the 1st ECH extension so that we can send it again in 2nd CH in response to rejection with HRR */
2562
0
        if (!is_second_flight) {
2563
0
            size_t len = outer_ech_header_size(tls->ech.client.enc.len) + ech_payload_size;
2564
0
            if ((tls->ech.client.first_ech.base = malloc(len)) == NULL) {
2565
0
                ret = PTLS_ERROR_NO_MEMORY;
2566
0
                goto Exit;
2567
0
            }
2568
0
            memcpy(tls->ech.client.first_ech.base,
2569
0
                   emitter->buf->base + ech_size_offset - outer_ech_header_size(tls->ech.client.enc.len), len);
2570
0
            tls->ech.client.first_ech.len = len;
2571
0
            if (tls->ech.state != PTLS_ECH_STATE_GREASE)
2572
0
                tls->ech.state = PTLS_ECH_STATE_OFFERED;
2573
0
        }
2574
0
        if (tls->ech.state == PTLS_ECH_STATE_GREASE) {
2575
            /* For grease ECH, the server sees the outer CH. Discard the inner state and adopt the outer, then compute the PSK
2576
             * binder over the outer CH using the standard flow. */
2577
0
            for (size_t i = 0; i < tls->key_schedule->num_hashes; ++i) {
2578
0
                tls->key_schedule->hashes[i].ctx->final(tls->key_schedule->hashes[i].ctx, NULL, PTLS_HASH_FINAL_MODE_FREE);
2579
0
                tls->key_schedule->hashes[i].ctx = tls->key_schedule->hashes[i].ctx_outer;
2580
0
                tls->key_schedule->hashes[i].ctx_outer = NULL;
2581
0
            }
2582
0
            ptls_aead_free(tls->ech.aead);
2583
0
            tls->ech.aead = NULL;
2584
0
            if ((ret = update_ch_hash_and_binder(tls->key_schedule, emitter->buf->base, mess_start, emitter->buf->off,
2585
0
                                                     psk.secret.base != NULL, binder_key, 0)) != 0)
2586
0
                goto Exit;
2587
0
        } else {
2588
            /* update outer hash */
2589
0
            ptls__key_schedule_update_hash(tls->key_schedule, emitter->buf->base + mess_start, emitter->buf->off - mess_start, 1);
2590
0
        }
2591
0
    }
2592
2593
    /* commit CH to the record layer */
2594
0
    if ((ret = emitter->commit_message(emitter)) != 0)
2595
0
        goto Exit;
2596
2597
0
    if (tls->client.using_early_data) {
2598
0
        assert(!is_second_flight);
2599
0
        if ((ret = setup_traffic_protection(tls, 1, "c e traffic", 1, 0, 0)) != 0)
2600
0
            goto Exit;
2601
0
        if ((ret = push_change_cipher_spec(tls, emitter)) != 0)
2602
0
            goto Exit;
2603
0
    }
2604
0
    if (psk.secret.base != NULL && !is_second_flight) {
2605
0
        if ((ret = derive_exporter_secret(tls, 1)) != 0)
2606
0
            goto Exit;
2607
0
    }
2608
0
    tls->state = cookie == NULL ? PTLS_STATE_CLIENT_EXPECT_SERVER_HELLO : PTLS_STATE_CLIENT_EXPECT_SECOND_SERVER_HELLO;
2609
0
    ret = PTLS_ERROR_IN_PROGRESS;
2610
2611
0
Exit:
2612
0
    ptls_buffer_dispose(&encoded_ch_inner);
2613
0
    ptls_clear_memory(binder_key, sizeof(binder_key));
2614
0
    return ret;
2615
0
}
2616
2617
ptls_cipher_suite_t *ptls_find_cipher_suite(ptls_cipher_suite_t **cipher_suites, uint16_t id)
2618
0
{
2619
0
    ptls_cipher_suite_t **cs;
2620
0
    if (cipher_suites == NULL)
2621
0
        return NULL;
2622
0
    for (cs = cipher_suites; *cs != NULL && (*cs)->id != id; ++cs)
2623
0
        ;
2624
0
    return *cs;
2625
0
}
2626
2627
static int decode_server_hello(ptls_t *tls, struct st_ptls_server_hello_t *sh, const uint8_t *src, const uint8_t *const end)
2628
0
{
2629
0
    int ret;
2630
2631
0
    *sh = (struct st_ptls_server_hello_t){{0}};
2632
2633
    /* ignore legacy-version */
2634
0
    if (end - src < 2) {
2635
0
        ret = PTLS_ALERT_DECODE_ERROR;
2636
0
        goto Exit;
2637
0
    }
2638
0
    src += 2;
2639
2640
    /* random */
2641
0
    if (end - src < PTLS_HELLO_RANDOM_SIZE) {
2642
0
        ret = PTLS_ALERT_DECODE_ERROR;
2643
0
        goto Exit;
2644
0
    }
2645
0
    sh->is_retry_request = memcmp(src, hello_retry_random, PTLS_HELLO_RANDOM_SIZE) == 0;
2646
0
    src += PTLS_HELLO_RANDOM_SIZE;
2647
2648
    /* legacy_session_id */
2649
0
    ptls_decode_open_block(src, end, 1, {
2650
0
        if (end - src > 32) {
2651
0
            ret = PTLS_ALERT_DECODE_ERROR;
2652
0
            goto Exit;
2653
0
        }
2654
0
        sh->legacy_session_id = ptls_iovec_init(src, end - src);
2655
0
        src = end;
2656
0
    });
2657
2658
0
    { /* select cipher_suite */
2659
0
        uint16_t csid;
2660
0
        if ((ret = ptls_decode16(&csid, &src, end)) != 0)
2661
0
            goto Exit;
2662
0
        if ((tls->cipher_suite = ptls_find_cipher_suite(tls->ctx->cipher_suites, csid)) == NULL) {
2663
0
            ret = PTLS_ALERT_ILLEGAL_PARAMETER;
2664
0
            goto Exit;
2665
0
        }
2666
0
    }
2667
2668
0
    { /* legacy_compression_method */
2669
0
        uint8_t method;
2670
0
        if ((ret = ptls_decode8(&method, &src, end)) != 0)
2671
0
            goto Exit;
2672
0
        if (method != 0) {
2673
0
            ret = PTLS_ALERT_ILLEGAL_PARAMETER;
2674
0
            goto Exit;
2675
0
        }
2676
0
    }
2677
2678
0
    if (sh->is_retry_request)
2679
0
        sh->retry_request.selected_group = UINT16_MAX;
2680
2681
0
    uint16_t exttype, found_version = UINT16_MAX, selected_psk_identity = UINT16_MAX;
2682
0
    decode_extensions(src, end, sh->is_retry_request ? PTLS_HANDSHAKE_TYPE_PSEUDO_HRR : PTLS_HANDSHAKE_TYPE_SERVER_HELLO, &exttype,
2683
0
                      {
2684
0
                          if (tls->ctx->on_extension != NULL &&
2685
0
                              (ret = tls->ctx->on_extension->cb(tls->ctx->on_extension, tls, PTLS_HANDSHAKE_TYPE_SERVER_HELLO,
2686
0
                                                                exttype, ptls_iovec_init(src, end - src)) != 0))
2687
0
                              goto Exit;
2688
0
                          switch (exttype) {
2689
0
                          case PTLS_EXTENSION_TYPE_SUPPORTED_VERSIONS:
2690
0
                              if ((ret = ptls_decode16(&found_version, &src, end)) != 0)
2691
0
                                  goto Exit;
2692
0
                              break;
2693
0
                          case PTLS_EXTENSION_TYPE_KEY_SHARE:
2694
0
                              if (tls->ctx->key_exchanges == NULL) {
2695
0
                                  ret = PTLS_ALERT_HANDSHAKE_FAILURE;
2696
0
                                  goto Exit;
2697
0
                              }
2698
0
                              if (sh->is_retry_request) {
2699
0
                                  if ((ret = ptls_decode16(&sh->retry_request.selected_group, &src, end)) != 0)
2700
0
                                      goto Exit;
2701
0
                              } else {
2702
0
                                  uint16_t group;
2703
0
                                  if ((ret = decode_key_share_entry(&group, &sh->peerkey, &src, end)) != 0)
2704
0
                                      goto Exit;
2705
0
                                  if (src != end) {
2706
0
                                      ret = PTLS_ALERT_DECODE_ERROR;
2707
0
                                      goto Exit;
2708
0
                                  }
2709
0
                                  if (tls->key_share == NULL || tls->key_share->id != group) {
2710
0
                                      ret = PTLS_ALERT_ILLEGAL_PARAMETER;
2711
0
                                      goto Exit;
2712
0
                                  }
2713
0
                              }
2714
0
                              break;
2715
0
                          case PTLS_EXTENSION_TYPE_COOKIE:
2716
0
                              assert(sh->is_retry_request);
2717
0
                              ptls_decode_block(src, end, 2, {
2718
0
                                  if (src == end) {
2719
0
                                      ret = PTLS_ALERT_DECODE_ERROR;
2720
0
                                      goto Exit;
2721
0
                                  }
2722
0
                                  sh->retry_request.cookie = ptls_iovec_init(src, end - src);
2723
0
                                  src = end;
2724
0
                              });
2725
0
                              break;
2726
0
                          case PTLS_EXTENSION_TYPE_PRE_SHARED_KEY:
2727
0
                              assert(!sh->is_retry_request);
2728
0
                              if ((ret = ptls_decode16(&selected_psk_identity, &src, end)) != 0)
2729
0
                                  goto Exit;
2730
0
                              break;
2731
0
                          case PTLS_EXTENSION_TYPE_ENCRYPTED_CLIENT_HELLO:
2732
0
                              assert(sh->is_retry_request);
2733
0
                              if (tls->ech.state == PTLS_ECH_STATE_NONE) {
2734
0
                                  ret = PTLS_ALERT_UNSUPPORTED_EXTENSION;
2735
0
                                  goto Exit;
2736
0
                              }
2737
0
                              if (end - src != PTLS_ECH_CONFIRM_LENGTH) {
2738
0
                                  ret = PTLS_ALERT_DECODE_ERROR;
2739
0
                                  goto Exit;
2740
0
                              }
2741
0
                              sh->retry_request.ech = src;
2742
0
                              src = end;
2743
0
                              break;
2744
0
                          default:
2745
0
                              src = end;
2746
0
                              break;
2747
0
                          }
2748
0
                      });
2749
2750
0
    if (!is_supported_version(found_version)) {
2751
0
        ret = PTLS_ALERT_ILLEGAL_PARAMETER;
2752
0
        goto Exit;
2753
0
    }
2754
0
    if (!sh->is_retry_request) {
2755
0
        if (selected_psk_identity != UINT16_MAX) {
2756
0
            if (!tls->client.offered_psk) {
2757
0
                ret = PTLS_ALERT_ILLEGAL_PARAMETER;
2758
0
                goto Exit;
2759
0
            }
2760
0
            if (selected_psk_identity != 0) {
2761
0
                ret = PTLS_ALERT_ILLEGAL_PARAMETER;
2762
0
                goto Exit;
2763
0
            }
2764
0
            tls->is_psk_handshake = 1;
2765
0
        }
2766
0
        if (sh->peerkey.base == NULL && !tls->is_psk_handshake) {
2767
0
            ret = PTLS_ALERT_ILLEGAL_PARAMETER;
2768
0
            goto Exit;
2769
0
        }
2770
0
    }
2771
2772
0
    ret = 0;
2773
0
Exit:
2774
0
    return ret;
2775
0
}
2776
2777
static int handle_hello_retry_request(ptls_t *tls, ptls_message_emitter_t *emitter, struct st_ptls_server_hello_t *sh,
2778
                                      ptls_iovec_t message, ptls_handshake_properties_t *properties)
2779
0
{
2780
0
    int ret;
2781
2782
0
    if (tls->client.key_share_ctx != NULL) {
2783
0
        tls->client.key_share_ctx->on_exchange(&tls->client.key_share_ctx, 1, NULL, ptls_iovec_init(NULL, 0));
2784
0
        tls->client.key_share_ctx = NULL;
2785
0
    }
2786
0
    if (tls->client.using_early_data) {
2787
        /* release traffic encryption key so that 2nd CH goes out in cleartext, but keep the epoch at 1 since we've already
2788
         * called derive-secret */
2789
0
        if (tls->ctx->update_traffic_key == NULL) {
2790
0
            assert(tls->traffic_protection.enc.aead != NULL);
2791
0
            ptls_aead_free(tls->traffic_protection.enc.aead);
2792
0
            tls->traffic_protection.enc.aead = NULL;
2793
0
        }
2794
0
        tls->client.using_early_data = 0;
2795
0
    }
2796
2797
0
    if (sh->retry_request.selected_group != UINT16_MAX) {
2798
        /* we offer the first key_exchanges[0] as KEY_SHARE unless client.negotiate_before_key_exchange is set */
2799
0
        ptls_key_exchange_algorithm_t **cand;
2800
0
        for (cand = tls->ctx->key_exchanges; *cand != NULL; ++cand)
2801
0
            if ((*cand)->id == sh->retry_request.selected_group)
2802
0
                break;
2803
0
        if (*cand == NULL) {
2804
0
            ret = PTLS_ALERT_ILLEGAL_PARAMETER;
2805
0
            goto Exit;
2806
0
        }
2807
0
        tls->key_share = *cand;
2808
0
    } else if (tls->key_share != NULL) {
2809
        /* retain the key-share using in first CH, if server does not specify one */
2810
0
    } else {
2811
0
        ret = PTLS_ALERT_ILLEGAL_PARAMETER;
2812
0
        goto Exit;
2813
0
    }
2814
2815
0
    ret = send_client_hello(tls, emitter, properties, &sh->retry_request.cookie);
2816
2817
0
Exit:
2818
0
    return ret;
2819
0
}
2820
2821
static int client_ech_select_hello(ptls_t *tls, ptls_iovec_t message, size_t confirm_hash_off, const char *label)
2822
0
{
2823
0
    uint8_t confirm_hash_delivered[PTLS_ECH_CONFIRM_LENGTH], confirm_hash_expected[PTLS_ECH_CONFIRM_LENGTH];
2824
0
    int ret = 0;
2825
2826
    /* Determine if ECH has been accepted by checking the confirmation hash. `confirm_hash_off` set to zero indicates that HRR was
2827
     * received wo. ECH extension, which is an indication that ECH was rejected. */
2828
0
    if (confirm_hash_off != 0) {
2829
0
        memcpy(confirm_hash_delivered, message.base + confirm_hash_off, sizeof(confirm_hash_delivered));
2830
0
        memset(message.base + confirm_hash_off, 0, sizeof(confirm_hash_delivered));
2831
0
        if ((ret = ech_calc_confirmation(tls->key_schedule, confirm_hash_expected, tls->ech.inner_client_random, label, message)) !=
2832
0
            0)
2833
0
            goto Exit;
2834
0
        int accepted = ptls_mem_equal(confirm_hash_delivered, confirm_hash_expected, sizeof(confirm_hash_delivered));
2835
0
        memcpy(message.base + confirm_hash_off, confirm_hash_delivered, sizeof(confirm_hash_delivered));
2836
0
        if (accepted) {
2837
0
            tls->ech.state = PTLS_ECH_STATE_ACCEPTED;
2838
0
            goto Exit;
2839
0
        } else if (tls->ech.state == PTLS_ECH_STATE_ACCEPTED) {
2840
            /* Per RFC 9849 Section 6.1.5: if HRR confirmed ECH acceptance, ServerHello MUST also confirm it. */
2841
0
            ret = PTLS_ALERT_ILLEGAL_PARAMETER;
2842
0
            goto Exit;
2843
0
        }
2844
0
    }
2845
2846
    /* dispose ECH AEAD state to indicate rejection, adopting outer CH for the rest of the handshake */
2847
0
    ptls_aead_free(tls->ech.aead);
2848
0
    tls->ech.aead = NULL;
2849
0
    key_schedule_select_outer(tls->key_schedule);
2850
2851
0
Exit:
2852
0
    PTLS_PROBE(ECH_SELECTION, tls, tls->ech.state == PTLS_ECH_STATE_ACCEPTED);
2853
0
    PTLS_LOG_CONN(ech_selection, tls, { PTLS_LOG_ELEMENT_BOOL(is_ech, tls->ech.state == PTLS_ECH_STATE_ACCEPTED); });
2854
0
    ptls_clear_memory(confirm_hash_expected, sizeof(confirm_hash_expected));
2855
0
    return ret;
2856
0
}
2857
2858
static int client_handle_hello(ptls_t *tls, ptls_message_emitter_t *emitter, ptls_iovec_t message,
2859
                               ptls_handshake_properties_t *properties)
2860
0
{
2861
0
    struct st_ptls_server_hello_t sh;
2862
0
    ptls_iovec_t ecdh_secret = {NULL};
2863
0
    int ret;
2864
2865
0
    if ((ret = decode_server_hello(tls, &sh, message.base + PTLS_HANDSHAKE_HEADER_SIZE, message.base + message.len)) != 0)
2866
0
        goto Exit;
2867
0
    if (!(sh.legacy_session_id.len == tls->client.legacy_session_id.len &&
2868
0
          ptls_mem_equal(sh.legacy_session_id.base, tls->client.legacy_session_id.base, tls->client.legacy_session_id.len))) {
2869
0
        ret = PTLS_ALERT_ILLEGAL_PARAMETER;
2870
0
        goto Exit;
2871
0
    }
2872
2873
0
    if (sh.is_retry_request) {
2874
0
        if ((ret = key_schedule_select_cipher(tls->key_schedule, tls->cipher_suite, 0, tls->ctx->pre_shared_key.secret)) != 0)
2875
0
            goto Exit;
2876
0
        key_schedule_transform_post_ch1hash(tls->key_schedule);
2877
0
        if (tls->ech.aead != NULL) {
2878
0
            size_t confirm_hash_off = 0;
2879
0
            if (tls->ech.state != PTLS_ECH_STATE_GREASE) {
2880
0
                if (sh.retry_request.ech != NULL)
2881
0
                    confirm_hash_off = sh.retry_request.ech - message.base;
2882
0
            }
2883
0
            if ((ret = client_ech_select_hello(tls, message, confirm_hash_off, ECH_CONFIRMATION_HRR)) != 0)
2884
0
                goto Exit;
2885
0
        }
2886
0
        ptls__key_schedule_update_hash(tls->key_schedule, message.base, message.len, 0);
2887
0
        return handle_hello_retry_request(tls, emitter, &sh, message, properties);
2888
0
    }
2889
2890
0
    if ((ret = key_schedule_select_cipher(tls->key_schedule, tls->cipher_suite, tls->client.offered_psk && !tls->is_psk_handshake,
2891
0
                                          ptls_iovec_init(NULL, 0))) != 0)
2892
0
        goto Exit;
2893
2894
    /* check if ECH is accepted */
2895
0
    if (tls->ech.aead != NULL) {
2896
0
        size_t confirm_hash_off = 0;
2897
0
        if (tls->ech.state != PTLS_ECH_STATE_GREASE) {
2898
0
            confirm_hash_off =
2899
0
                PTLS_HANDSHAKE_HEADER_SIZE + 2 /* legacy_version */ + PTLS_HELLO_RANDOM_SIZE - PTLS_ECH_CONFIRM_LENGTH;
2900
0
        }
2901
0
        if ((ret = client_ech_select_hello(tls, message, confirm_hash_off, ECH_CONFIRMATION_SERVER_HELLO)) != 0)
2902
0
            goto Exit;
2903
0
    }
2904
2905
    /* clear sensitive and space-consuming ECH state, now that are done with handling sending and decoding Hellos */
2906
0
    clear_ech(&tls->ech, 0);
2907
0
    if (tls->key_schedule->hashes[0].ctx_outer != NULL) {
2908
0
        tls->key_schedule->hashes[0].ctx_outer->final(tls->key_schedule->hashes[0].ctx_outer, NULL, PTLS_HASH_FINAL_MODE_FREE);
2909
0
        tls->key_schedule->hashes[0].ctx_outer = NULL;
2910
0
    }
2911
2912
    /* if the client offered external PSK but the server did not use that, we call it a handshake failure */
2913
0
    if (tls->ctx->pre_shared_key.identity.base != NULL && !tls->is_psk_handshake) {
2914
0
        ret = PTLS_ALERT_HANDSHAKE_FAILURE;
2915
0
        goto Exit;
2916
0
    }
2917
2918
0
    ptls__key_schedule_update_hash(tls->key_schedule, message.base, message.len, 0);
2919
2920
0
    if (sh.peerkey.base != NULL) {
2921
0
        if ((ret = tls->client.key_share_ctx->on_exchange(&tls->client.key_share_ctx, 1, &ecdh_secret, sh.peerkey)) != 0) {
2922
0
            assert(ecdh_secret.base == NULL);
2923
0
            goto Exit;
2924
0
        }
2925
0
    }
2926
2927
0
    if ((ret = key_schedule_extract(tls->key_schedule, ecdh_secret)) != 0)
2928
0
        goto Exit;
2929
0
    if ((ret = setup_traffic_protection(tls, 0, "s hs traffic", 2, 0, 0)) != 0)
2930
0
        goto Exit;
2931
0
    if (tls->client.using_early_data) {
2932
0
        if ((tls->pending_handshake_secret = malloc(PTLS_MAX_DIGEST_SIZE)) == NULL) {
2933
0
            ret = PTLS_ERROR_NO_MEMORY;
2934
0
            goto Exit;
2935
0
        }
2936
0
        if ((ret = derive_secret(tls->key_schedule, tls->pending_handshake_secret, "c hs traffic")) != 0)
2937
0
            goto Exit;
2938
0
        if (tls->ctx->update_traffic_key != NULL &&
2939
0
            (ret = tls->ctx->update_traffic_key->cb(tls->ctx->update_traffic_key, tls, 1, 2, tls->pending_handshake_secret)) != 0)
2940
0
            goto Exit;
2941
0
    } else {
2942
0
        if ((ret = setup_traffic_protection(tls, 1, "c hs traffic", 2, 0, 0)) != 0)
2943
0
            goto Exit;
2944
0
    }
2945
2946
0
    tls->state = PTLS_STATE_CLIENT_EXPECT_ENCRYPTED_EXTENSIONS;
2947
0
    ret = PTLS_ERROR_IN_PROGRESS;
2948
2949
0
Exit:
2950
0
    if (ecdh_secret.base != NULL) {
2951
0
        ptls_clear_memory(ecdh_secret.base, ecdh_secret.len);
2952
0
        free(ecdh_secret.base);
2953
0
    }
2954
0
    return ret;
2955
0
}
2956
2957
static int should_collect_unknown_extension(ptls_t *tls, ptls_handshake_properties_t *properties, uint16_t type)
2958
0
{
2959
0
    return properties != NULL && properties->collect_extension != NULL && properties->collect_extension(tls, properties, type);
2960
0
}
2961
2962
static int collect_unknown_extension(ptls_t *tls, uint16_t type, const uint8_t *src, const uint8_t *const end,
2963
                                     ptls_raw_extension_t *slots)
2964
0
{
2965
0
    size_t i;
2966
0
    for (i = 0; slots[i].type != UINT16_MAX; ++i) {
2967
0
        assert(i < MAX_UNKNOWN_EXTENSIONS);
2968
0
        if (slots[i].type == type)
2969
0
            return PTLS_ALERT_ILLEGAL_PARAMETER;
2970
0
    }
2971
0
    if (i < MAX_UNKNOWN_EXTENSIONS) {
2972
0
        slots[i].type = type;
2973
0
        slots[i].data = ptls_iovec_init(src, end - src);
2974
0
        slots[i + 1].type = UINT16_MAX;
2975
0
    }
2976
0
    return 0;
2977
0
}
2978
2979
static int report_unknown_extensions(ptls_t *tls, ptls_handshake_properties_t *properties, ptls_raw_extension_t *slots)
2980
0
{
2981
0
    if (properties != NULL && properties->collect_extension != NULL) {
2982
0
        assert(properties->collected_extensions != NULL);
2983
0
        return properties->collected_extensions(tls, properties, slots);
2984
0
    } else {
2985
0
        return 0;
2986
0
    }
2987
0
}
2988
2989
static int client_handle_encrypted_extensions(ptls_t *tls, ptls_iovec_t message, ptls_handshake_properties_t *properties)
2990
0
{
2991
0
    const uint8_t *src = message.base + PTLS_HANDSHAKE_HEADER_SIZE, *const end = message.base + message.len;
2992
0
    uint16_t type;
2993
0
    static const ptls_raw_extension_t no_unknown_extensions = {UINT16_MAX};
2994
0
    ptls_raw_extension_t *unknown_extensions = (ptls_raw_extension_t *)&no_unknown_extensions;
2995
0
    int ret, skip_early_data = 1;
2996
0
    uint8_t server_offered_cert_type = PTLS_CERTIFICATE_TYPE_X509;
2997
2998
0
    decode_extensions(src, end, PTLS_HANDSHAKE_TYPE_ENCRYPTED_EXTENSIONS, &type, {
2999
0
        if (tls->ctx->on_extension != NULL &&
3000
0
            (ret = tls->ctx->on_extension->cb(tls->ctx->on_extension, tls, PTLS_HANDSHAKE_TYPE_ENCRYPTED_EXTENSIONS, type,
3001
0
                                              ptls_iovec_init(src, end - src)) != 0))
3002
0
            goto Exit;
3003
0
        switch (type) {
3004
0
        case PTLS_EXTENSION_TYPE_SERVER_NAME:
3005
0
            if (src != end) {
3006
0
                ret = PTLS_ALERT_DECODE_ERROR;
3007
0
                goto Exit;
3008
0
            }
3009
0
            if (!(tls->server_name != NULL && !ptls_server_name_is_ipaddr(tls->server_name))) {
3010
0
                ret = PTLS_ALERT_ILLEGAL_PARAMETER;
3011
0
                goto Exit;
3012
0
            }
3013
0
            break;
3014
0
        case PTLS_EXTENSION_TYPE_ALPN:
3015
0
            ptls_decode_block(src, end, 2, {
3016
0
                ptls_decode_open_block(src, end, 1, {
3017
0
                    if (src == end) {
3018
0
                        ret = PTLS_ALERT_DECODE_ERROR;
3019
0
                        goto Exit;
3020
0
                    }
3021
0
                    if ((ret = ptls_set_negotiated_protocol(tls, (const char *)src, end - src)) != 0)
3022
0
                        goto Exit;
3023
0
                    src = end;
3024
0
                });
3025
0
                if (src != end) {
3026
0
                    ret = PTLS_ALERT_HANDSHAKE_FAILURE;
3027
0
                    goto Exit;
3028
0
                }
3029
0
            });
3030
0
            break;
3031
0
        case PTLS_EXTENSION_TYPE_EARLY_DATA:
3032
0
            if (!tls->client.using_early_data) {
3033
0
                ret = PTLS_ALERT_ILLEGAL_PARAMETER;
3034
0
                goto Exit;
3035
0
            }
3036
0
            skip_early_data = 0;
3037
0
            break;
3038
0
        case PTLS_EXTENSION_TYPE_SERVER_CERTIFICATE_TYPE:
3039
0
            if (end - src != 1) {
3040
0
                ret = PTLS_ALERT_DECODE_ERROR;
3041
0
                goto Exit;
3042
0
            }
3043
0
            server_offered_cert_type = *src;
3044
0
            src = end;
3045
0
            break;
3046
0
        case PTLS_EXTENSION_TYPE_ENCRYPTED_CLIENT_HELLO: {
3047
            /* accept retry_configs only if we offered ECH (or grease) but rejected */
3048
0
            if (!(tls->ech.state == PTLS_ECH_STATE_OFFERED || tls->ech.state == PTLS_ECH_STATE_GREASE)) {
3049
0
                ret = PTLS_ALERT_UNSUPPORTED_EXTENSION;
3050
0
                goto Exit;
3051
0
            }
3052
            /* parse retry_config, and if it is applicable, provide that to the application (grease clients just verify syntax) */
3053
0
            struct st_decoded_ech_config_t decoded;
3054
0
            if ((ret = client_decode_ech_config_list(tls->ctx, &decoded, ptls_iovec_init(src, end - src))) != 0)
3055
0
                goto Exit;
3056
0
            if (tls->ech.state == PTLS_ECH_STATE_GREASE) {
3057
                /* GREASE clients ignore retry_configs after verifying the syntax */
3058
0
            } else if (decoded.kem != NULL && decoded.cipher != NULL && properties != NULL &&
3059
0
                       properties->client.ech.retry_configs != NULL) {
3060
0
                if ((properties->client.ech.retry_configs->base = malloc(end - src)) == NULL) {
3061
0
                    ret = PTLS_ERROR_NO_MEMORY;
3062
0
                    goto Exit;
3063
0
                }
3064
0
                memcpy(properties->client.ech.retry_configs->base, src, end - src);
3065
0
                properties->client.ech.retry_configs->len = end - src;
3066
0
            }
3067
0
            src = end;
3068
0
        } break;
3069
0
        default:
3070
0
            if (should_collect_unknown_extension(tls, properties, type)) {
3071
0
                if (unknown_extensions == &no_unknown_extensions) {
3072
0
                    if ((unknown_extensions = malloc(sizeof(*unknown_extensions) * (MAX_UNKNOWN_EXTENSIONS + 1))) == NULL) {
3073
0
                        ret = PTLS_ERROR_NO_MEMORY;
3074
0
                        goto Exit;
3075
0
                    }
3076
0
                    unknown_extensions[0].type = UINT16_MAX;
3077
0
                }
3078
0
                if ((ret = collect_unknown_extension(tls, type, src, end, unknown_extensions)) != 0)
3079
0
                    goto Exit;
3080
0
            }
3081
0
            break;
3082
0
        }
3083
0
        src = end;
3084
0
    });
3085
3086
0
    if (server_offered_cert_type !=
3087
0
        (tls->ctx->use_raw_public_keys ? PTLS_CERTIFICATE_TYPE_RAW_PUBLIC_KEY : PTLS_CERTIFICATE_TYPE_X509)) {
3088
0
        ret = PTLS_ALERT_UNSUPPORTED_CERTIFICATE;
3089
0
        goto Exit;
3090
0
    }
3091
3092
0
    if (tls->client.using_early_data) {
3093
0
        if (skip_early_data)
3094
0
            tls->client.using_early_data = 0;
3095
0
        if (properties != NULL)
3096
0
            properties->client.early_data_acceptance = skip_early_data ? PTLS_EARLY_DATA_REJECTED : PTLS_EARLY_DATA_ACCEPTED;
3097
0
    }
3098
0
    if ((ret = report_unknown_extensions(tls, properties, unknown_extensions)) != 0)
3099
0
        goto Exit;
3100
3101
0
    ptls__key_schedule_update_hash(tls->key_schedule, message.base, message.len, 0);
3102
0
    tls->state =
3103
0
        tls->is_psk_handshake ? PTLS_STATE_CLIENT_EXPECT_FINISHED : PTLS_STATE_CLIENT_EXPECT_CERTIFICATE_REQUEST_OR_CERTIFICATE;
3104
0
    ret = PTLS_ERROR_IN_PROGRESS;
3105
3106
0
Exit:
3107
0
    if (unknown_extensions != &no_unknown_extensions)
3108
0
        free(unknown_extensions);
3109
0
    return ret;
3110
0
}
3111
3112
static int decode_certificate_request(ptls_t *tls, struct st_ptls_certificate_request_t *cr, const uint8_t *src,
3113
                                      const uint8_t *const end)
3114
0
{
3115
0
    int ret;
3116
0
    uint16_t exttype = 0;
3117
3118
    /* certificate request context */
3119
0
    ptls_decode_open_block(src, end, 1, {
3120
0
        size_t len = end - src;
3121
0
        if (len > 255) {
3122
0
            ret = PTLS_ALERT_DECODE_ERROR;
3123
0
            goto Exit;
3124
0
        }
3125
0
        if ((cr->context.base = malloc(len != 0 ? len : 1)) == NULL) {
3126
0
            ret = PTLS_ERROR_NO_MEMORY;
3127
0
            goto Exit;
3128
0
        }
3129
0
        cr->context.len = len;
3130
0
        memcpy(cr->context.base, src, len);
3131
0
        src = end;
3132
0
    });
3133
3134
    /* decode extensions */
3135
0
    decode_extensions(src, end, PTLS_HANDSHAKE_TYPE_CERTIFICATE_REQUEST, &exttype, {
3136
0
        if (tls->ctx->on_extension != NULL &&
3137
0
            (ret = tls->ctx->on_extension->cb(tls->ctx->on_extension, tls, PTLS_HANDSHAKE_TYPE_CERTIFICATE_REQUEST, exttype,
3138
0
                                              ptls_iovec_init(src, end - src)) != 0))
3139
0
            goto Exit;
3140
0
        switch (exttype) {
3141
0
        case PTLS_EXTENSION_TYPE_SIGNATURE_ALGORITHMS:
3142
0
            if ((ret = decode_signature_algorithms(&cr->signature_algorithms, &src, end)) != 0)
3143
0
                goto Exit;
3144
0
            break;
3145
0
        }
3146
0
        src = end;
3147
0
    });
3148
3149
0
    if (cr->signature_algorithms.count == 0) {
3150
0
        ret = PTLS_ALERT_MISSING_EXTENSION;
3151
0
        goto Exit;
3152
0
    }
3153
3154
0
    ret = 0;
3155
0
Exit:
3156
0
    return ret;
3157
0
}
3158
3159
int ptls_build_certificate_message(ptls_buffer_t *buf, ptls_iovec_t context, ptls_iovec_t *certificates, size_t num_certificates,
3160
                                   ptls_iovec_t ocsp_status)
3161
0
{
3162
0
    int ret;
3163
3164
0
    ptls_buffer_push_block(buf, 1, { ptls_buffer_pushv(buf, context.base, context.len); });
3165
0
    ptls_buffer_push_block(buf, 3, {
3166
0
        size_t i;
3167
0
        for (i = 0; i != num_certificates; ++i) {
3168
0
            ptls_buffer_push_block(buf, 3, { ptls_buffer_pushv(buf, certificates[i].base, certificates[i].len); });
3169
0
            ptls_buffer_push_block(buf, 2, {
3170
0
                if (i == 0 && ocsp_status.len != 0) {
3171
0
                    buffer_push_extension(buf, PTLS_EXTENSION_TYPE_STATUS_REQUEST, {
3172
0
                        ptls_buffer_push(buf, 1); /* status_type == ocsp */
3173
0
                        ptls_buffer_push_block(buf, 3, { ptls_buffer_pushv(buf, ocsp_status.base, ocsp_status.len); });
3174
0
                    });
3175
0
                }
3176
0
            });
3177
0
        }
3178
0
    });
3179
3180
0
    ret = 0;
3181
0
Exit:
3182
0
    return ret;
3183
0
}
3184
3185
static int default_emit_certificate_cb(ptls_emit_certificate_t *_self, ptls_t *tls, ptls_message_emitter_t *emitter,
3186
                                       ptls_key_schedule_t *key_sched, ptls_iovec_t context, int push_status_request,
3187
                                       const uint16_t *compress_algos, size_t num_compress_algos)
3188
0
{
3189
0
    int ret;
3190
3191
0
    ptls_push_message(emitter, key_sched, PTLS_HANDSHAKE_TYPE_CERTIFICATE, {
3192
0
        if ((ret = ptls_build_certificate_message(emitter->buf, context, tls->ctx->certificates.list, tls->ctx->certificates.count,
3193
0
                                                  ptls_iovec_init(NULL, 0))) != 0)
3194
0
            goto Exit;
3195
0
    });
3196
3197
0
    ret = 0;
3198
0
Exit:
3199
0
    return ret;
3200
0
}
3201
3202
static int send_certificate(ptls_t *tls, ptls_message_emitter_t *emitter,
3203
                            struct st_ptls_signature_algorithms_t *signature_algorithms, ptls_iovec_t context,
3204
                            int push_status_request, const uint16_t *compress_algos, size_t num_compress_algos)
3205
0
{
3206
0
    int ret;
3207
3208
0
    if (signature_algorithms->count == 0) {
3209
0
        ret = PTLS_ALERT_MISSING_EXTENSION;
3210
0
        goto Exit;
3211
0
    }
3212
3213
0
    { /* send Certificate (or the equivalent) */
3214
0
        static ptls_emit_certificate_t default_emit_certificate = {default_emit_certificate_cb};
3215
0
        ptls_emit_certificate_t *emit_certificate =
3216
0
            tls->ctx->emit_certificate != NULL ? tls->ctx->emit_certificate : &default_emit_certificate;
3217
0
    Redo:
3218
0
        if ((ret = emit_certificate->cb(emit_certificate, tls, emitter, tls->key_schedule, context, push_status_request,
3219
0
                                        compress_algos, num_compress_algos)) != 0) {
3220
0
            if (ret == PTLS_ERROR_DELEGATE) {
3221
0
                assert(emit_certificate != &default_emit_certificate);
3222
0
                emit_certificate = &default_emit_certificate;
3223
0
                goto Redo;
3224
0
            }
3225
0
            goto Exit;
3226
0
        }
3227
0
    }
3228
3229
0
Exit:
3230
0
    return ret;
3231
0
}
3232
3233
static int send_certificate_verify(ptls_t *tls, ptls_message_emitter_t *emitter,
3234
                                   struct st_ptls_signature_algorithms_t *signature_algorithms, const char *context_string)
3235
0
{
3236
0
    size_t start_off = emitter->buf->off;
3237
0
    int ret;
3238
3239
0
    if (tls->ctx->sign_certificate == NULL)
3240
0
        return 0;
3241
    /* build and send CertificateVerify */
3242
0
    ptls_push_message(emitter, tls->key_schedule, PTLS_HANDSHAKE_TYPE_CERTIFICATE_VERIFY, {
3243
0
        ptls_buffer_t *sendbuf = emitter->buf;
3244
0
        size_t algo_off = sendbuf->off;
3245
0
        ptls_buffer_push16(sendbuf, 0); /* filled in later */
3246
0
        ptls_buffer_push_block(sendbuf, 2, {
3247
0
            uint16_t algo;
3248
0
            uint8_t data[PTLS_MAX_CERTIFICATE_VERIFY_SIGNDATA_SIZE];
3249
0
            size_t datalen = build_certificate_verify_signdata(data, tls->key_schedule, context_string);
3250
0
            if ((ret = tls->ctx->sign_certificate->cb(
3251
0
                     tls->ctx->sign_certificate, tls, tls->is_server ? &tls->server.async_job : NULL, &algo, sendbuf,
3252
0
                     ptls_iovec_init(data, datalen), signature_algorithms != NULL ? signature_algorithms->list : NULL,
3253
0
                     signature_algorithms != NULL ? signature_algorithms->count : 0)) == PTLS_ERROR_ASYNC_OPERATION) {
3254
0
                assert(tls->is_server || !"async operation only supported on the server-side");
3255
0
                assert(tls->server.async_job != NULL);
3256
                /* Reset the output to the end of the previous handshake message. CertificateVerify will be rebuilt when the async
3257
                 * operation completes. */
3258
0
                emitter->buf->off = start_off;
3259
0
                goto Exit;
3260
0
            }
3261
0
            assert(!tls->is_server || tls->server.async_job == NULL);
3262
0
            if (ret != 0)
3263
0
                goto Exit;
3264
0
            sendbuf->base[algo_off] = (uint8_t)(algo >> 8);
3265
0
            sendbuf->base[algo_off + 1] = (uint8_t)algo;
3266
0
        });
3267
0
    });
3268
0
Exit:
3269
0
    return ret;
3270
0
}
3271
3272
static int client_handle_certificate_request(ptls_t *tls, ptls_iovec_t message, ptls_handshake_properties_t *properties)
3273
0
{
3274
0
    const uint8_t *src = message.base + PTLS_HANDSHAKE_HEADER_SIZE, *const end = message.base + message.len;
3275
0
    int ret = 0;
3276
3277
0
    assert(!tls->is_psk_handshake && "state machine asserts that this message is never delivered when PSK is used");
3278
3279
0
    if ((ret = decode_certificate_request(tls, &tls->client.certificate_request, src, end)) != 0)
3280
0
        return ret;
3281
3282
    /* This field SHALL be zero length unless used for the post-handshake authentication exchanges (section 4.3.2) */
3283
0
    if (tls->client.certificate_request.context.len != 0)
3284
0
        return PTLS_ALERT_ILLEGAL_PARAMETER;
3285
3286
0
    tls->state = PTLS_STATE_CLIENT_EXPECT_CERTIFICATE;
3287
0
    ptls__key_schedule_update_hash(tls->key_schedule, message.base, message.len, 0);
3288
3289
0
    return PTLS_ERROR_IN_PROGRESS;
3290
0
}
3291
3292
static int handle_certificate(ptls_t *tls, const uint8_t *src, const uint8_t *end, int *got_certs)
3293
0
{
3294
0
    ptls_iovec_t certs[16];
3295
0
    size_t num_certs = 0;
3296
0
    int ret = 0;
3297
3298
    /* certificate request context */
3299
0
    ptls_decode_open_block(src, end, 1, {
3300
0
        if (src != end) {
3301
0
            ret = PTLS_ALERT_ILLEGAL_PARAMETER;
3302
0
            goto Exit;
3303
0
        }
3304
0
    });
3305
    /* certificate_list */
3306
0
    ptls_decode_block(src, end, 3, {
3307
0
        while (src != end) {
3308
0
            ptls_decode_open_block(src, end, 3, {
3309
0
                if (num_certs < PTLS_ELEMENTSOF(certs))
3310
0
                    certs[num_certs++] = ptls_iovec_init(src, end - src);
3311
0
                src = end;
3312
0
            });
3313
0
            uint16_t type;
3314
0
            decode_open_extensions(src, end, PTLS_HANDSHAKE_TYPE_CERTIFICATE, &type, {
3315
0
                if (tls->ctx->on_extension != NULL &&
3316
0
                    (ret = tls->ctx->on_extension->cb(tls->ctx->on_extension, tls, PTLS_HANDSHAKE_TYPE_CERTIFICATE, type,
3317
0
                                                      ptls_iovec_init(src, end - src)) != 0))
3318
0
                    goto Exit;
3319
0
                src = end;
3320
0
            });
3321
0
        }
3322
0
    });
3323
3324
0
    if (tls->ctx->verify_certificate != NULL) {
3325
0
        const char *server_name = NULL;
3326
0
        if (!ptls_is_server(tls)) {
3327
0
            if (tls->ech.state == PTLS_ECH_STATE_OFFERED) {
3328
0
                server_name = tls->ech.client.public_name;
3329
0
            } else {
3330
0
                server_name = tls->server_name;
3331
0
            }
3332
0
        }
3333
0
        if ((ret = tls->ctx->verify_certificate->cb(tls->ctx->verify_certificate, tls, server_name, &tls->certificate_verify.cb,
3334
0
                                                    &tls->certificate_verify.verify_ctx, certs, num_certs)) != 0)
3335
0
            goto Exit;
3336
0
    }
3337
3338
0
    *got_certs = num_certs != 0;
3339
3340
0
Exit:
3341
0
    return ret;
3342
0
}
3343
3344
static int client_do_handle_certificate(ptls_t *tls, const uint8_t *src, const uint8_t *end)
3345
0
{
3346
0
    int got_certs, ret;
3347
3348
0
    if ((ret = handle_certificate(tls, src, end, &got_certs)) != 0)
3349
0
        return ret;
3350
0
    if (!got_certs)
3351
0
        return PTLS_ALERT_ILLEGAL_PARAMETER;
3352
3353
0
    return 0;
3354
0
}
3355
3356
static int client_handle_certificate(ptls_t *tls, ptls_iovec_t message)
3357
0
{
3358
0
    int ret;
3359
3360
0
    if ((ret = client_do_handle_certificate(tls, message.base + PTLS_HANDSHAKE_HEADER_SIZE, message.base + message.len)) != 0)
3361
0
        return ret;
3362
3363
0
    ptls__key_schedule_update_hash(tls->key_schedule, message.base, message.len, 0);
3364
3365
0
    tls->state = PTLS_STATE_CLIENT_EXPECT_CERTIFICATE_VERIFY;
3366
0
    return PTLS_ERROR_IN_PROGRESS;
3367
0
}
3368
3369
static int client_handle_compressed_certificate(ptls_t *tls, ptls_iovec_t message)
3370
0
{
3371
0
    const uint8_t *src = message.base + PTLS_HANDSHAKE_HEADER_SIZE, *const end = message.base + message.len;
3372
0
    uint16_t algo;
3373
0
    uint32_t uncompressed_size;
3374
0
    uint8_t *uncompressed = NULL;
3375
0
    int ret;
3376
3377
0
    if (tls->ctx->decompress_certificate == NULL) {
3378
0
        ret = PTLS_ALERT_UNEXPECTED_MESSAGE;
3379
0
        goto Exit;
3380
0
    }
3381
3382
    /* decode */
3383
0
    if ((ret = ptls_decode16(&algo, &src, end)) != 0)
3384
0
        goto Exit;
3385
0
    if ((ret = ptls_decode24(&uncompressed_size, &src, end)) != 0)
3386
0
        goto Exit;
3387
0
    if (uncompressed_size > 65536) { /* TODO find a sensible number */
3388
0
        ret = PTLS_ALERT_BAD_CERTIFICATE;
3389
0
        goto Exit;
3390
0
    }
3391
0
    if ((uncompressed = malloc(uncompressed_size)) == NULL) {
3392
0
        ret = PTLS_ERROR_NO_MEMORY;
3393
0
        goto Exit;
3394
0
    }
3395
0
    ptls_decode_block(src, end, 3, {
3396
0
        if ((ret = tls->ctx->decompress_certificate->cb(tls->ctx->decompress_certificate, tls, algo,
3397
0
                                                        ptls_iovec_init(uncompressed, uncompressed_size),
3398
0
                                                        ptls_iovec_init(src, end - src))) != 0)
3399
0
            goto Exit;
3400
0
        src = end;
3401
0
    });
3402
3403
    /* handle */
3404
0
    if ((ret = client_do_handle_certificate(tls, uncompressed, uncompressed + uncompressed_size)) != 0)
3405
0
        goto Exit;
3406
3407
0
    ptls__key_schedule_update_hash(tls->key_schedule, message.base, message.len, 0);
3408
0
    tls->state = PTLS_STATE_CLIENT_EXPECT_CERTIFICATE_VERIFY;
3409
0
    ret = PTLS_ERROR_IN_PROGRESS;
3410
3411
0
Exit:
3412
0
    free(uncompressed);
3413
0
    return ret;
3414
0
}
3415
3416
static int server_handle_certificate(ptls_t *tls, ptls_iovec_t message)
3417
0
{
3418
0
    int got_certs, ret;
3419
3420
0
    if ((ret = handle_certificate(tls, message.base + PTLS_HANDSHAKE_HEADER_SIZE, message.base + message.len, &got_certs)) != 0)
3421
0
        return ret;
3422
3423
0
    ptls__key_schedule_update_hash(tls->key_schedule, message.base, message.len, 0);
3424
3425
0
    if (got_certs) {
3426
0
        tls->state = PTLS_STATE_SERVER_EXPECT_CERTIFICATE_VERIFY;
3427
0
    } else {
3428
        /* Client did not provide certificate, and the verifier says we can fail open. Therefore, the next message is Finished. */
3429
0
        tls->state = PTLS_STATE_SERVER_EXPECT_FINISHED;
3430
0
    }
3431
3432
0
    return PTLS_ERROR_IN_PROGRESS;
3433
0
}
3434
3435
static int handle_certificate_verify(ptls_t *tls, ptls_iovec_t message, const char *context_string)
3436
0
{
3437
0
    const uint8_t *src = message.base + PTLS_HANDSHAKE_HEADER_SIZE, *const end = message.base + message.len;
3438
0
    uint16_t algo;
3439
0
    ptls_iovec_t signature;
3440
0
    uint8_t signdata[PTLS_MAX_CERTIFICATE_VERIFY_SIGNDATA_SIZE];
3441
0
    size_t signdata_size;
3442
0
    int ret;
3443
3444
    /* decode */
3445
0
    if ((ret = ptls_decode16(&algo, &src, end)) != 0)
3446
0
        goto Exit;
3447
0
    ptls_decode_block(src, end, 2, {
3448
0
        signature = ptls_iovec_init(src, end - src);
3449
0
        src = end;
3450
0
    });
3451
3452
0
    signdata_size = build_certificate_verify_signdata(signdata, tls->key_schedule, context_string);
3453
0
    if (tls->certificate_verify.cb != NULL) {
3454
0
        ret = tls->certificate_verify.cb(tls->certificate_verify.verify_ctx, algo, ptls_iovec_init(signdata, signdata_size),
3455
0
                                         signature);
3456
0
    } else {
3457
0
        ret = 0;
3458
0
    }
3459
0
    ptls_clear_memory(signdata, signdata_size);
3460
0
    tls->certificate_verify.cb = NULL;
3461
0
    if (ret != 0) {
3462
0
        goto Exit;
3463
0
    }
3464
3465
0
    ptls__key_schedule_update_hash(tls->key_schedule, message.base, message.len, 0);
3466
3467
0
Exit:
3468
0
    return ret;
3469
0
}
3470
3471
static int client_handle_certificate_verify(ptls_t *tls, ptls_iovec_t message)
3472
0
{
3473
0
    int ret = handle_certificate_verify(tls, message, PTLS_SERVER_CERTIFICATE_VERIFY_CONTEXT_STRING);
3474
3475
0
    if (ret == 0) {
3476
0
        tls->state = PTLS_STATE_CLIENT_EXPECT_FINISHED;
3477
0
        ret = PTLS_ERROR_IN_PROGRESS;
3478
0
    }
3479
3480
0
    return ret;
3481
0
}
3482
3483
static int server_handle_certificate_verify(ptls_t *tls, ptls_iovec_t message)
3484
0
{
3485
0
    int ret = handle_certificate_verify(tls, message, PTLS_CLIENT_CERTIFICATE_VERIFY_CONTEXT_STRING);
3486
3487
0
    if (ret == 0) {
3488
0
        tls->state = PTLS_STATE_SERVER_EXPECT_FINISHED;
3489
0
        ret = PTLS_ERROR_IN_PROGRESS;
3490
0
    }
3491
3492
0
    return ret;
3493
0
}
3494
3495
static int client_handle_finished(ptls_t *tls, ptls_message_emitter_t *emitter, ptls_iovec_t message)
3496
0
{
3497
0
    uint8_t send_secret[PTLS_MAX_DIGEST_SIZE];
3498
0
    int alert_ech_required = tls->ech.state == PTLS_ECH_STATE_OFFERED, ret;
3499
3500
0
    if ((ret = verify_finished(tls, message)) != 0)
3501
0
        goto Exit;
3502
0
    ptls__key_schedule_update_hash(tls->key_schedule, message.base, message.len, 0);
3503
3504
    /* update traffic keys by using messages upto ServerFinished, but commission them after sending ClientFinished */
3505
0
    if ((ret = key_schedule_extract(tls->key_schedule, ptls_iovec_init(NULL, 0))) != 0)
3506
0
        goto Exit;
3507
0
    if ((ret = setup_traffic_protection(tls, 0, "s ap traffic", 3, 0, 0)) != 0)
3508
0
        goto Exit;
3509
0
    if ((ret = derive_secret(tls->key_schedule, send_secret, "c ap traffic")) != 0)
3510
0
        goto Exit;
3511
0
    if ((ret = derive_exporter_secret(tls, 0)) != 0)
3512
0
        goto Exit;
3513
3514
    /* if sending early data, emit EOED and commision the client handshake traffic secret */
3515
0
    if (tls->pending_handshake_secret != NULL) {
3516
0
        assert(tls->traffic_protection.enc.aead != NULL || tls->ctx->update_traffic_key != NULL);
3517
0
        if (tls->client.using_early_data && !tls->ctx->omit_end_of_early_data)
3518
0
            ptls_push_message(emitter, tls->key_schedule, PTLS_HANDSHAKE_TYPE_END_OF_EARLY_DATA, {});
3519
0
        tls->client.using_early_data = 0;
3520
0
        if ((ret = commission_handshake_secret(tls)) != 0)
3521
0
            goto Exit;
3522
0
    }
3523
3524
0
    if ((ret = push_change_cipher_spec(tls, emitter)) != 0)
3525
0
        goto Exit;
3526
3527
0
    if (!alert_ech_required && tls->client.certificate_request.context.base != NULL) {
3528
0
        if ((ret = send_certificate(tls, emitter, &tls->client.certificate_request.signature_algorithms,
3529
0
                                    tls->client.certificate_request.context, 0, NULL, 0)) == 0)
3530
0
            ret = send_certificate_verify(tls, emitter, &tls->client.certificate_request.signature_algorithms,
3531
0
                                          PTLS_CLIENT_CERTIFICATE_VERIFY_CONTEXT_STRING);
3532
0
        free(tls->client.certificate_request.context.base);
3533
0
        tls->client.certificate_request.context = ptls_iovec_init(NULL, 0);
3534
0
        if (ret != 0)
3535
0
            goto Exit;
3536
0
    }
3537
3538
0
    ret = send_finished(tls, emitter);
3539
3540
0
    memcpy(tls->traffic_protection.enc.secret, send_secret, sizeof(send_secret));
3541
0
    if ((ret = setup_traffic_protection(tls, 1, NULL, 3, 0, 0)) != 0)
3542
0
        goto Exit;
3543
3544
0
    tls->state = PTLS_STATE_CLIENT_POST_HANDSHAKE;
3545
3546
    /* if ECH was rejected, close the connection with ECH_REQUIRED alert after verifying messages up to Finished */
3547
0
    if (alert_ech_required)
3548
0
        ret = PTLS_ALERT_ECH_REQUIRED;
3549
3550
0
Exit:
3551
0
    ptls_clear_memory(send_secret, sizeof(send_secret));
3552
0
    return ret;
3553
0
}
3554
3555
static int client_handle_new_session_ticket(ptls_t *tls, ptls_iovec_t message)
3556
0
{
3557
0
    const uint8_t *src = message.base + PTLS_HANDSHAKE_HEADER_SIZE, *const end = message.base + message.len;
3558
0
    ptls_iovec_t ticket_nonce;
3559
0
    int ret;
3560
3561
0
    { /* verify the format */
3562
0
        uint32_t ticket_lifetime, ticket_age_add, max_early_data_size;
3563
0
        ptls_iovec_t ticket;
3564
0
        if ((ret = decode_new_session_ticket(tls, &ticket_lifetime, &ticket_age_add, &ticket_nonce, &ticket, &max_early_data_size,
3565
0
                                             src, end)) != 0)
3566
0
            return ret;
3567
0
    }
3568
3569
    /* do nothing if use of session ticket is disabled */
3570
0
    if (tls->ctx->save_ticket == NULL)
3571
0
        return 0;
3572
3573
    /* save the extension, along with the key of myself */
3574
0
    ptls_buffer_t ticket_buf;
3575
0
    ptls_buffer_init(&ticket_buf, "", 0);
3576
0
    ptls_buffer_push64(&ticket_buf, tls->ctx->get_time->cb(tls->ctx->get_time));
3577
0
    ptls_buffer_push16(&ticket_buf, tls->key_share->id);
3578
0
    ptls_buffer_push16(&ticket_buf, tls->cipher_suite->id);
3579
0
    ptls_buffer_push_block(&ticket_buf, 3, { ptls_buffer_pushv(&ticket_buf, src, end - src); });
3580
0
    ptls_buffer_push_block(&ticket_buf, 2, {
3581
0
        if ((ret = ptls_buffer_reserve(&ticket_buf, tls->key_schedule->hashes[0].algo->digest_size)) != 0)
3582
0
            goto Exit;
3583
0
        if ((ret = derive_resumption_secret(tls->key_schedule, ticket_buf.base + ticket_buf.off, ticket_nonce)) != 0)
3584
0
            goto Exit;
3585
0
        ticket_buf.off += tls->key_schedule->hashes[0].algo->digest_size;
3586
0
    });
3587
3588
0
    if ((ret = tls->ctx->save_ticket->cb(tls->ctx->save_ticket, tls, ptls_iovec_init(ticket_buf.base, ticket_buf.off))) != 0)
3589
0
        goto Exit;
3590
3591
0
    ret = 0;
3592
0
Exit:
3593
0
    ptls_buffer_dispose(&ticket_buf);
3594
0
    return ret;
3595
0
}
3596
3597
static int client_hello_decode_server_name(ptls_iovec_t *name, const uint8_t **src, const uint8_t *const end)
3598
0
{
3599
0
    int ret = 0;
3600
3601
0
    ptls_decode_open_block(*src, end, 2, {
3602
0
        do {
3603
0
            uint8_t type;
3604
0
            if ((ret = ptls_decode8(&type, src, end)) != 0)
3605
0
                goto Exit;
3606
0
            ptls_decode_open_block(*src, end, 2, {
3607
0
                switch (type) {
3608
0
                case PTLS_SERVER_NAME_TYPE_HOSTNAME:
3609
0
                    if (end - *src == 0) {
3610
0
                        ret = PTLS_ALERT_DECODE_ERROR;
3611
0
                        goto Exit;
3612
0
                    }
3613
0
                    if (memchr(*src, '\0', end - *src) != 0) {
3614
0
                        ret = PTLS_ALERT_ILLEGAL_PARAMETER;
3615
0
                        goto Exit;
3616
0
                    }
3617
0
                    *name = ptls_iovec_init(*src, end - *src);
3618
0
                    break;
3619
0
                default:
3620
0
                    break;
3621
0
                }
3622
0
                *src = end;
3623
0
            });
3624
0
        } while (*src != end);
3625
0
    });
3626
3627
0
Exit:
3628
0
    return ret;
3629
0
}
3630
3631
static int select_negotiated_group(ptls_key_exchange_algorithm_t **selected, ptls_key_exchange_algorithm_t **candidates,
3632
                                   const uint8_t *src, const uint8_t *const end)
3633
0
{
3634
0
    int ret;
3635
3636
0
    ptls_decode_block(src, end, 2, {
3637
0
        while (src != end) {
3638
0
            uint16_t group;
3639
0
            if ((ret = ptls_decode16(&group, &src, end)) != 0)
3640
0
                goto Exit;
3641
0
            ptls_key_exchange_algorithm_t **c = candidates;
3642
0
            for (; *c != NULL; ++c) {
3643
0
                if ((*c)->id == group) {
3644
0
                    *selected = *c;
3645
0
                    return 0;
3646
0
                }
3647
0
            }
3648
0
        }
3649
0
    });
3650
3651
0
    ret = PTLS_ALERT_HANDSHAKE_FAILURE;
3652
3653
0
Exit:
3654
0
    return ret;
3655
0
}
3656
3657
static int decode_client_hello(ptls_context_t *ctx, struct st_ptls_client_hello_t *ch, const uint8_t *src, const uint8_t *const end,
3658
                               ptls_handshake_properties_t *properties, ptls_t *tls_cbarg)
3659
0
{
3660
0
    const uint8_t *start = src;
3661
0
    uint16_t exttype = 0;
3662
0
    int ret;
3663
3664
    /* decode protocol version (do not bare to decode something older than TLS 1.0) */
3665
0
    if ((ret = ptls_decode16(&ch->legacy_version, &src, end)) != 0)
3666
0
        goto Exit;
3667
0
    if (ch->legacy_version < 0x0301) {
3668
0
        ret = PTLS_ALERT_PROTOCOL_VERSION;
3669
0
        goto Exit;
3670
0
    }
3671
3672
    /* skip random */
3673
0
    if (end - src < PTLS_HELLO_RANDOM_SIZE) {
3674
0
        ret = PTLS_ALERT_DECODE_ERROR;
3675
0
        goto Exit;
3676
0
    }
3677
0
    ch->random_bytes = src;
3678
0
    src += PTLS_HELLO_RANDOM_SIZE;
3679
3680
    /* skip legacy_session_id */
3681
0
    ptls_decode_open_block(src, end, 1, {
3682
0
        if (end - src > 32) {
3683
0
            ret = PTLS_ALERT_DECODE_ERROR;
3684
0
            goto Exit;
3685
0
        }
3686
0
        ch->legacy_session_id = ptls_iovec_init(src, end - src);
3687
0
        src = end;
3688
0
    });
3689
3690
    /* decode and select from ciphersuites */
3691
0
    ptls_decode_open_block(src, end, 2, {
3692
0
        if ((end - src) % 2 != 0) {
3693
0
            ret = PTLS_ALERT_DECODE_ERROR;
3694
0
            goto Exit;
3695
0
        }
3696
0
        ch->cipher_suites = ptls_iovec_init(src, end - src);
3697
0
        src = end;
3698
0
    });
3699
3700
    /* decode legacy_compression_methods */
3701
0
    ptls_decode_open_block(src, end, 1, {
3702
0
        if (src == end) {
3703
0
            ret = PTLS_ALERT_DECODE_ERROR;
3704
0
            goto Exit;
3705
0
        }
3706
0
        ch->compression_methods.ids = src;
3707
0
        ch->compression_methods.count = end - src;
3708
0
        src = end;
3709
0
    });
3710
3711
    /* In TLS versions 1.2 and earlier CH might not have an extensions block (or they might, see what OpenSSL 1.0.0 sends); so bail
3712
     * out if that is the case after parsing the main variables. Zero is returned as it is a valid ClientHello. However
3713
     * `ptls_t::selected_version` remains zero indicating that no compatible version were found. */
3714
0
    if (src == end) {
3715
0
        ret = 0;
3716
0
        goto Exit;
3717
0
    }
3718
3719
    /* decode extensions */
3720
0
    ch->first_extension_at = src - start + 2;
3721
0
    decode_extensions(src, end, PTLS_HANDSHAKE_TYPE_CLIENT_HELLO, &exttype, {
3722
0
        ch->psk.is_last_extension = 0;
3723
0
        if (ctx->on_extension != NULL && tls_cbarg != NULL &&
3724
0
            (ret = ctx->on_extension->cb(ctx->on_extension, tls_cbarg, PTLS_HANDSHAKE_TYPE_CLIENT_HELLO, exttype,
3725
0
                                         ptls_iovec_init(src, end - src)) != 0))
3726
0
            goto Exit;
3727
0
        switch (exttype) {
3728
0
        case PTLS_EXTENSION_TYPE_SERVER_NAME:
3729
0
            if ((ret = client_hello_decode_server_name(&ch->server_name, &src, end)) != 0)
3730
0
                goto Exit;
3731
0
            if (src != end) {
3732
0
                ret = PTLS_ALERT_DECODE_ERROR;
3733
0
                goto Exit;
3734
0
            }
3735
0
            break;
3736
0
        case PTLS_EXTENSION_TYPE_ALPN:
3737
0
            ptls_decode_block(src, end, 2, {
3738
0
                do {
3739
0
                    ptls_decode_open_block(src, end, 1, {
3740
                        /* rfc7301 3.1: empty strings MUST NOT be included */
3741
0
                        if (src == end) {
3742
0
                            ret = PTLS_ALERT_DECODE_ERROR;
3743
0
                            goto Exit;
3744
0
                        }
3745
0
                        if (ch->alpn.count < PTLS_ELEMENTSOF(ch->alpn.list))
3746
0
                            ch->alpn.list[ch->alpn.count++] = ptls_iovec_init(src, end - src);
3747
0
                        src = end;
3748
0
                    });
3749
0
                } while (src != end);
3750
0
            });
3751
0
            break;
3752
0
        case PTLS_EXTENSION_TYPE_SERVER_CERTIFICATE_TYPE:
3753
0
            ptls_decode_block(src, end, 1, {
3754
0
                size_t list_size = end - src;
3755
3756
                /* RFC7250 4.1: No empty list, no list with single x509 element */
3757
0
                if (list_size == 0 || (list_size == 1 && *src == PTLS_CERTIFICATE_TYPE_X509)) {
3758
0
                    ret = PTLS_ALERT_DECODE_ERROR;
3759
0
                    goto Exit;
3760
0
                }
3761
3762
0
                do {
3763
0
                    if (ch->server_certificate_types.count < PTLS_ELEMENTSOF(ch->server_certificate_types.list))
3764
0
                        ch->server_certificate_types.list[ch->server_certificate_types.count++] = *src;
3765
0
                    src++;
3766
0
                } while (src != end);
3767
0
            });
3768
0
            break;
3769
0
        case PTLS_EXTENSION_TYPE_COMPRESS_CERTIFICATE:
3770
0
            ptls_decode_block(src, end, 1, {
3771
0
                do {
3772
0
                    uint16_t id;
3773
0
                    if ((ret = ptls_decode16(&id, &src, end)) != 0)
3774
0
                        goto Exit;
3775
0
                    if (ch->cert_compression_algos.count < PTLS_ELEMENTSOF(ch->cert_compression_algos.list))
3776
0
                        ch->cert_compression_algos.list[ch->cert_compression_algos.count++] = id;
3777
0
                } while (src != end);
3778
0
            });
3779
0
            break;
3780
0
        case PTLS_EXTENSION_TYPE_SUPPORTED_GROUPS:
3781
0
            ch->negotiated_groups = ptls_iovec_init(src, end - src);
3782
0
            break;
3783
0
        case PTLS_EXTENSION_TYPE_SIGNATURE_ALGORITHMS:
3784
0
            if ((ret = decode_signature_algorithms(&ch->signature_algorithms, &src, end)) != 0)
3785
0
                goto Exit;
3786
0
            break;
3787
0
        case PTLS_EXTENSION_TYPE_KEY_SHARE:
3788
0
            ch->key_shares = ptls_iovec_init(src, end - src);
3789
0
            break;
3790
0
        case PTLS_EXTENSION_TYPE_SUPPORTED_VERSIONS:
3791
0
            ptls_decode_block(src, end, 1, {
3792
0
                size_t selected_index = PTLS_ELEMENTSOF(supported_versions);
3793
0
                do {
3794
0
                    size_t i;
3795
0
                    uint16_t v;
3796
0
                    if ((ret = ptls_decode16(&v, &src, end)) != 0)
3797
0
                        goto Exit;
3798
0
                    for (i = 0; i != selected_index; ++i) {
3799
0
                        if (supported_versions[i] == v) {
3800
0
                            selected_index = i;
3801
0
                            break;
3802
0
                        }
3803
0
                    }
3804
0
                } while (src != end);
3805
0
                if (selected_index != PTLS_ELEMENTSOF(supported_versions))
3806
0
                    ch->selected_version = supported_versions[selected_index];
3807
0
            });
3808
0
            break;
3809
0
        case PTLS_EXTENSION_TYPE_COOKIE:
3810
0
            if (properties == NULL || properties->server.cookie.key == NULL) {
3811
0
                ret = PTLS_ALERT_ILLEGAL_PARAMETER;
3812
0
                goto Exit;
3813
0
            }
3814
0
            ch->cookie.all = ptls_iovec_init(src, end - src);
3815
0
            ptls_decode_block(src, end, 2, {
3816
0
                ch->cookie.tbs.base = (void *)src;
3817
0
                ptls_decode_open_block(src, end, 2, {
3818
0
                    ptls_decode_open_block(src, end, 1, {
3819
0
                        ch->cookie.ch1_hash = ptls_iovec_init(src, end - src);
3820
0
                        src = end;
3821
0
                    });
3822
0
                    uint8_t sent_key_share;
3823
0
                    if ((ret = ptls_decode8(&sent_key_share, &src, end)) != 0)
3824
0
                        goto Exit;
3825
0
                    switch (sent_key_share) {
3826
0
                    case 0:
3827
0
                        assert(!ch->cookie.sent_key_share);
3828
0
                        break;
3829
0
                    case 1:
3830
0
                        ch->cookie.sent_key_share = 1;
3831
0
                        break;
3832
0
                    default:
3833
0
                        ret = PTLS_ALERT_DECODE_ERROR;
3834
0
                        goto Exit;
3835
0
                    }
3836
0
                });
3837
0
                ch->cookie.tbs.len = src - ch->cookie.tbs.base;
3838
0
                ptls_decode_block(src, end, 1, {
3839
0
                    ch->cookie.signature = ptls_iovec_init(src, end - src);
3840
0
                    src = end;
3841
0
                });
3842
0
            });
3843
0
            break;
3844
0
        case PTLS_EXTENSION_TYPE_PRE_SHARED_KEY: {
3845
0
            size_t num_identities = 0;
3846
0
            ptls_decode_open_block(src, end, 2, {
3847
0
                do {
3848
0
                    ptls_client_hello_psk_identity_t psk = {{NULL}};
3849
0
                    ptls_decode_open_block(src, end, 2, {
3850
0
                        if (end - src < 1) {
3851
0
                            ret = PTLS_ALERT_DECODE_ERROR;
3852
0
                            goto Exit;
3853
0
                        }
3854
0
                        psk.identity = ptls_iovec_init(src, end - src);
3855
0
                        src = end;
3856
0
                    });
3857
0
                    if ((ret = ptls_decode32(&psk.obfuscated_ticket_age, &src, end)) != 0)
3858
0
                        goto Exit;
3859
0
                    if (ch->psk.identities.count < PTLS_ELEMENTSOF(ch->psk.identities.list))
3860
0
                        ch->psk.identities.list[ch->psk.identities.count++] = psk;
3861
0
                    ++num_identities;
3862
0
                } while (src != end);
3863
0
            });
3864
0
            ch->psk.hash_end = src;
3865
0
            ptls_decode_block(src, end, 2, {
3866
0
                size_t num_binders = 0;
3867
0
                do {
3868
0
                    ptls_decode_open_block(src, end, 1, {
3869
0
                        if (num_binders < ch->psk.identities.count)
3870
0
                            ch->psk.identities.list[num_binders].binder = ptls_iovec_init(src, end - src);
3871
0
                        src = end;
3872
0
                    });
3873
0
                    ++num_binders;
3874
0
                } while (src != end);
3875
0
                if (num_identities != num_binders) {
3876
0
                    ret = PTLS_ALERT_ILLEGAL_PARAMETER;
3877
0
                    goto Exit;
3878
0
                }
3879
0
            });
3880
0
            ch->psk.is_last_extension = 1;
3881
0
        } break;
3882
0
        case PTLS_EXTENSION_TYPE_PSK_KEY_EXCHANGE_MODES:
3883
0
            ptls_decode_block(src, end, 1, {
3884
0
                do {
3885
0
                    uint8_t mode;
3886
0
                    if ((ret = ptls_decode8(&mode, &src, end)) != 0)
3887
0
                        goto Exit;
3888
0
                    if (mode < sizeof(ch->psk.ke_modes) * 8)
3889
0
                        ch->psk.ke_modes |= 1u << mode;
3890
0
                } while (src != end);
3891
0
            });
3892
0
            break;
3893
0
        case PTLS_EXTENSION_TYPE_EARLY_DATA:
3894
0
            ch->psk.early_data_indication = 1;
3895
0
            break;
3896
0
        case PTLS_EXTENSION_TYPE_STATUS_REQUEST:
3897
0
            ch->status_request = 1;
3898
0
            break;
3899
0
        case PTLS_EXTENSION_TYPE_TICKET_REQUEST:
3900
0
            if (end - src != 2) {
3901
0
                ret = PTLS_ALERT_DECODE_ERROR;
3902
0
                goto Exit;
3903
0
            }
3904
0
            ch->ticket_request.new_session_count = *src++;
3905
0
            ch->ticket_request.resumption_count = *src++;
3906
0
            break;
3907
0
        case PTLS_EXTENSION_TYPE_ENCRYPTED_CLIENT_HELLO:
3908
0
            if ((ret = ptls_decode8(&ch->ech.type, &src, end)) != 0)
3909
0
                goto Exit;
3910
0
            switch (ch->ech.type) {
3911
0
            case PTLS_ECH_CLIENT_HELLO_TYPE_OUTER:
3912
0
                if ((ret = ptls_decode16(&ch->ech.cipher_suite.kdf, &src, end)) != 0 ||
3913
0
                    (ret = ptls_decode16(&ch->ech.cipher_suite.aead, &src, end)) != 0)
3914
0
                    goto Exit;
3915
0
                if ((ret = ptls_decode8(&ch->ech.config_id, &src, end)) != 0)
3916
0
                    goto Exit;
3917
0
                ptls_decode_open_block(src, end, 2, {
3918
0
                    ch->ech.enc = ptls_iovec_init(src, end - src);
3919
0
                    src = end;
3920
0
                });
3921
0
                ptls_decode_open_block(src, end, 2, {
3922
0
                    if (src == end) {
3923
0
                        ret = PTLS_ALERT_DECODE_ERROR;
3924
0
                        goto Exit;
3925
0
                    }
3926
0
                    ch->ech.payload = ptls_iovec_init(src, end - src);
3927
0
                    src = end;
3928
0
                });
3929
0
                break;
3930
0
            case PTLS_ECH_CLIENT_HELLO_TYPE_INNER:
3931
0
                if (src != end) {
3932
0
                    ret = PTLS_ALERT_DECODE_ERROR;
3933
0
                    goto Exit;
3934
0
                }
3935
0
                ch->ech.payload = ptls_iovec_init("", 0); /* non-zero base indicates that the extension was received */
3936
0
                break;
3937
0
            default:
3938
0
                ret = PTLS_ALERT_ILLEGAL_PARAMETER;
3939
0
                goto Exit;
3940
0
            }
3941
0
            src = end;
3942
0
            break;
3943
0
        default:
3944
0
            if (tls_cbarg != NULL && should_collect_unknown_extension(tls_cbarg, properties, exttype)) {
3945
0
                if ((ret = collect_unknown_extension(tls_cbarg, exttype, src, end, ch->unknown_extensions)) != 0)
3946
0
                    goto Exit;
3947
0
            }
3948
0
            break;
3949
0
        }
3950
0
        src = end;
3951
0
    });
3952
3953
0
    ret = 0;
3954
0
Exit:
3955
0
    return ret;
3956
0
}
3957
3958
static int rebuild_ch_inner_extensions(ptls_buffer_t *buf, const uint8_t **src, const uint8_t *const end, const uint8_t *outer_ext,
3959
                                       const uint8_t *outer_ext_end)
3960
0
{
3961
0
    int ret;
3962
3963
0
    ptls_buffer_push_block(buf, 2, {
3964
0
        ptls_decode_open_block(*src, end, 2, {
3965
0
            while (*src != end) {
3966
0
                uint16_t exttype;
3967
0
                if ((ret = ptls_decode16(&exttype, src, end)) != 0)
3968
0
                    goto Exit;
3969
0
                ptls_decode_open_block(*src, end, 2, {
3970
0
                    if (exttype == PTLS_EXTENSION_TYPE_ECH_OUTER_EXTENSIONS) {
3971
0
                        ptls_decode_open_block(*src, end, 1, {
3972
0
                            do {
3973
0
                                uint16_t reftype;
3974
0
                                uint16_t outertype;
3975
0
                                uint16_t outersize;
3976
0
                                if ((ret = ptls_decode16(&reftype, src, end)) != 0)
3977
0
                                    goto Exit;
3978
0
                                if (reftype == PTLS_EXTENSION_TYPE_ENCRYPTED_CLIENT_HELLO) {
3979
0
                                    ret = PTLS_ALERT_ILLEGAL_PARAMETER;
3980
0
                                    goto Exit;
3981
0
                                }
3982
0
                                while (1) {
3983
0
                                    if (ptls_decode16(&outertype, &outer_ext, outer_ext_end) != 0 ||
3984
0
                                        ptls_decode16(&outersize, &outer_ext, outer_ext_end) != 0) {
3985
0
                                        ret = PTLS_ALERT_ILLEGAL_PARAMETER;
3986
0
                                        goto Exit;
3987
0
                                    }
3988
0
                                    assert(outer_ext_end - outer_ext >= outersize);
3989
0
                                    if (outertype == reftype)
3990
0
                                        break;
3991
0
                                    outer_ext += outersize;
3992
0
                                }
3993
0
                                buffer_push_extension(buf, reftype, {
3994
0
                                    ptls_buffer_pushv(buf, outer_ext, outersize);
3995
0
                                    outer_ext += outersize;
3996
0
                                });
3997
0
                            } while (*src != end);
3998
0
                        });
3999
0
                    } else {
4000
0
                        buffer_push_extension(buf, exttype, {
4001
0
                            ptls_buffer_pushv(buf, *src, end - *src);
4002
0
                            *src = end;
4003
0
                        });
4004
0
                    }
4005
0
                });
4006
0
            }
4007
0
        });
4008
0
    });
4009
4010
0
Exit:
4011
0
    return ret;
4012
0
}
4013
4014
static int rebuild_ch_inner(ptls_buffer_t *buf, const uint8_t *src, const uint8_t *const end,
4015
                            struct st_ptls_client_hello_t *outer_ch, const uint8_t *outer_ext, const uint8_t *outer_ext_end)
4016
0
{
4017
0
#define COPY_BLOCK(capacity)                                                                                                       \
4018
0
    do {                                                                                                                           \
4019
0
        ptls_decode_open_block(src, end, (capacity), {                                                                             \
4020
0
            ptls_buffer_push_block(buf, (capacity), { ptls_buffer_pushv(buf, src, end - src); });                                  \
4021
0
            src = end;                                                                                                             \
4022
0
        });                                                                                                                        \
4023
0
    } while (0)
4024
4025
0
    int ret;
4026
4027
0
    ptls_buffer_push_message_body(buf, NULL, PTLS_HANDSHAKE_TYPE_CLIENT_HELLO, {
4028
0
        { /* legacy_version */
4029
0
            uint16_t legacy_version;
4030
0
            if ((ret = ptls_decode16(&legacy_version, &src, end)) != 0)
4031
0
                goto Exit;
4032
0
            ptls_buffer_push16(buf, legacy_version);
4033
0
        }
4034
4035
        /* hello random */
4036
0
        if (end - src < PTLS_HELLO_RANDOM_SIZE) {
4037
0
            ret = PTLS_ALERT_DECODE_ERROR;
4038
0
            goto Exit;
4039
0
        }
4040
0
        ptls_buffer_pushv(buf, src, PTLS_HELLO_RANDOM_SIZE);
4041
0
        src += PTLS_HELLO_RANDOM_SIZE;
4042
4043
0
        ptls_decode_open_block(src, end, 1, {
4044
0
            if (src != end) {
4045
0
                ret = PTLS_ALERT_ILLEGAL_PARAMETER;
4046
0
                goto Exit;
4047
0
            }
4048
0
        });
4049
0
        ptls_buffer_push_block(buf, 1,
4050
0
                               { ptls_buffer_pushv(buf, outer_ch->legacy_session_id.base, outer_ch->legacy_session_id.len); });
4051
4052
        /* cipher-suites and legacy-compression-methods */
4053
0
        COPY_BLOCK(2);
4054
0
        COPY_BLOCK(1);
4055
4056
        /* extensions */
4057
0
        if ((ret = rebuild_ch_inner_extensions(buf, &src, end, outer_ext, outer_ext_end)) != 0)
4058
0
            goto Exit;
4059
0
    });
4060
4061
    /* padding must be all zero */
4062
0
    for (; src != end; ++src) {
4063
0
        if (*src != '\0') {
4064
0
            ret = PTLS_ALERT_ILLEGAL_PARAMETER;
4065
0
            goto Exit;
4066
0
        }
4067
0
    }
4068
4069
0
Exit:
4070
0
    return ret;
4071
4072
0
#undef COPY_BLOCK
4073
0
}
4074
4075
/* Wrapper function for invoking the on_client_hello callback, taking an exhaustive list of parameters as arguments. The intention
4076
 * is to not miss setting them as we add new parameters to the struct. */
4077
static inline int call_on_client_hello_cb(ptls_t *tls, ptls_iovec_t server_name, ptls_iovec_t raw_message,
4078
                                          ptls_iovec_t cipher_suites, ptls_iovec_t *alpns, size_t num_alpns,
4079
                                          const uint16_t *sig_algos, size_t num_sig_algos, const uint16_t *cert_comp_algos,
4080
                                          size_t num_cert_comp_algos, const uint8_t *server_cert_types,
4081
                                          size_t num_server_cert_types, const ptls_client_hello_psk_identity_t *psk_identities,
4082
                                          size_t num_psk_identities, int incompatible_version)
4083
0
{
4084
0
    if (tls->ctx->on_client_hello == NULL)
4085
0
        return 0;
4086
4087
0
    ptls_on_client_hello_parameters_t params = {server_name,
4088
0
                                                raw_message,
4089
0
                                                cipher_suites,
4090
0
                                                {alpns, num_alpns},
4091
0
                                                {sig_algos, num_sig_algos},
4092
0
                                                {cert_comp_algos, num_cert_comp_algos},
4093
0
                                                {server_cert_types, num_server_cert_types},
4094
0
                                                {psk_identities, num_psk_identities},
4095
0
                                                incompatible_version};
4096
0
    return tls->ctx->on_client_hello->cb(tls->ctx->on_client_hello, tls, &params);
4097
0
}
4098
4099
static int check_client_hello_constraints(ptls_context_t *ctx, struct st_ptls_client_hello_t *ch, const void *prev_random,
4100
                                          int ech_is_inner_ch, ptls_iovec_t raw_message, ptls_t *tls_cbarg)
4101
0
{
4102
0
    int is_second_flight = prev_random != 0;
4103
4104
    /* The following check is necessary so that we would be able to track the connection in SSLKEYLOGFILE, even though it might not
4105
     * be for the safety of the protocol. */
4106
0
    if (is_second_flight && !ptls_mem_equal(ch->random_bytes, prev_random, PTLS_HELLO_RANDOM_SIZE))
4107
0
        return PTLS_ALERT_HANDSHAKE_FAILURE;
4108
4109
    /* bail out if CH cannot be handled as TLS 1.3 */
4110
0
    if (!is_supported_version(ch->selected_version)) {
4111
        /* ECH: server MUST abort with an "illegal_parameter" alert if the client offers TLS 1.2 or below (draft-15 7.1) */
4112
0
        if (ech_is_inner_ch)
4113
0
            return PTLS_ALERT_ILLEGAL_PARAMETER;
4114
        /* fail with PROTOCOL_VERSION alert, after providing the applications the raw CH and SNI to help them fallback */
4115
0
        if (!is_second_flight) {
4116
0
            int ret;
4117
0
            if ((ret = call_on_client_hello_cb(tls_cbarg, ch->server_name, raw_message, ch->cipher_suites, ch->alpn.list,
4118
0
                                               ch->alpn.count, NULL, 0, NULL, 0, NULL, 0, NULL, 0, 1)) != 0)
4119
0
                return ret;
4120
0
        }
4121
0
        return PTLS_ALERT_PROTOCOL_VERSION;
4122
0
    }
4123
4124
    /* Check TLS 1.3-specific constraints. Hereafter, we might exit without calling on_client_hello. That's fine because this CH is
4125
     * ought to be rejected. */
4126
0
    if (ch->legacy_version <= 0x0300) {
4127
        /* RFC 8446 Appendix D.5: any endpoint receiving a Hello message with legacy_version set to 0x0300 MUST abort the handshake
4128
         * with a "protocol_version" alert. */
4129
0
        return PTLS_ALERT_PROTOCOL_VERSION;
4130
0
    }
4131
0
    if (!(ch->compression_methods.count == 1 && ch->compression_methods.ids[0] == 0))
4132
0
        return PTLS_ALERT_ILLEGAL_PARAMETER;
4133
    /* pre-shared key */
4134
0
    if (ch->psk.hash_end != NULL) {
4135
        /* PSK must be the last extension */
4136
0
        if (!ch->psk.is_last_extension)
4137
0
            return PTLS_ALERT_ILLEGAL_PARAMETER;
4138
0
    } else {
4139
0
        if (ch->psk.early_data_indication)
4140
0
            return PTLS_ALERT_ILLEGAL_PARAMETER;
4141
0
    }
4142
4143
0
    if (ech_is_inner_ch && ch->ech.payload.base == NULL)
4144
0
        return PTLS_ALERT_ILLEGAL_PARAMETER;
4145
0
    if (ch->ech.payload.base != NULL &&
4146
0
        ch->ech.type != (ech_is_inner_ch ? PTLS_ECH_CLIENT_HELLO_TYPE_INNER : PTLS_ECH_CLIENT_HELLO_TYPE_OUTER))
4147
0
        return PTLS_ALERT_ILLEGAL_PARAMETER;
4148
4149
0
    return 0;
4150
0
}
4151
4152
static int vec_is_string(ptls_iovec_t x, const char *y)
4153
0
{
4154
0
    return strncmp((const char *)x.base, y, x.len) == 0 && y[x.len] == '\0';
4155
0
}
4156
4157
/**
4158
 * Looks for a PSK identity that can be used, and if found, updates the handshake state and returns the necessary variables. If
4159
 * `ptls_context_t::pre_shared_key` is set, only tries handshake using those keys provided. Otherwise, tries resumption.
4160
 */
4161
static int try_psk_handshake(ptls_t *tls, size_t *psk_index, int *accept_early_data, struct st_ptls_client_hello_t *ch,
4162
                             ptls_iovec_t ch_trunc, int is_second_flight)
4163
0
{
4164
0
    ptls_buffer_t decbuf;
4165
0
    ptls_iovec_t secret, ticket_ctx, ticket_negotiated_protocol;
4166
0
    uint64_t issue_at, now = tls->ctx->get_time->cb(tls->ctx->get_time);
4167
0
    uint32_t age_add;
4168
0
    uint16_t ticket_key_exchange_id, ticket_csid;
4169
0
    uint8_t binder_key[PTLS_MAX_DIGEST_SIZE];
4170
0
    int ret;
4171
4172
0
    ptls_buffer_init(&decbuf, "", 0);
4173
4174
0
    for (*psk_index = 0; *psk_index < ch->psk.identities.count; ++*psk_index) {
4175
0
        ptls_client_hello_psk_identity_t *identity = ch->psk.identities.list + *psk_index;
4176
4177
        /* negotiate using fixed pre-shared key */
4178
0
        if (tls->ctx->pre_shared_key.identity.base != NULL) {
4179
0
            if (identity->identity.len == tls->ctx->pre_shared_key.identity.len &&
4180
0
                memcmp(identity->identity.base, tls->ctx->pre_shared_key.identity.base, identity->identity.len) == 0) {
4181
0
                *accept_early_data = ch->psk.early_data_indication && *psk_index == 0;
4182
0
                tls->key_share = NULL;
4183
0
                secret = tls->ctx->pre_shared_key.secret;
4184
0
                goto Found;
4185
0
            }
4186
0
            continue;
4187
0
        }
4188
4189
        /* decrypt ticket and decode */
4190
0
        if (tls->ctx->encrypt_ticket == NULL || tls->ctx->key_exchanges == NULL)
4191
0
            continue;
4192
0
        int can_accept_early_data = *psk_index == 0;
4193
0
        decbuf.off = 0;
4194
0
        switch (tls->ctx->encrypt_ticket->cb(tls->ctx->encrypt_ticket, tls, 0, &decbuf, identity->identity)) {
4195
0
        case 0: /* decrypted */
4196
0
            break;
4197
0
        case PTLS_ERROR_REJECT_EARLY_DATA: /* decrypted, but early data is rejected */
4198
0
            can_accept_early_data = 0;
4199
0
            break;
4200
0
        default: /* decryption failure */
4201
0
            continue;
4202
0
        }
4203
0
        if (decode_session_identifier(&issue_at, &secret, &age_add, &ticket_ctx, &ticket_key_exchange_id, &ticket_csid,
4204
0
                                      &ticket_negotiated_protocol, decbuf.base, decbuf.base + decbuf.off) != 0)
4205
0
            continue;
4206
        /* check age */
4207
0
        if (now < issue_at)
4208
0
            continue;
4209
0
        if (now - issue_at > (uint64_t)tls->ctx->ticket_lifetime * 1000)
4210
0
            continue;
4211
0
        *accept_early_data = 0;
4212
0
        if (ch->psk.early_data_indication && can_accept_early_data) {
4213
            /* accept early-data if abs(diff) between the reported age and the actual age is within += 10 seconds */
4214
0
            int64_t delta = (now - issue_at) - (identity->obfuscated_ticket_age - age_add);
4215
0
            if (delta < 0)
4216
0
                delta = -delta;
4217
0
            if (tls->ctx->max_early_data_size != 0 && delta <= PTLS_EARLY_DATA_MAX_DELAY)
4218
0
                *accept_early_data = 1;
4219
0
        }
4220
        /* check ticket context */
4221
0
        if (tls->ctx->ticket_context.is_set) {
4222
0
            if (!(ticket_ctx.len == sizeof(tls->ctx->ticket_context.bytes) &&
4223
0
                  memcmp(ticket_ctx.base, tls->ctx->ticket_context.bytes, ticket_ctx.len) == 0))
4224
0
                continue;
4225
0
        } else {
4226
            /* check server-name */
4227
0
            if (ticket_ctx.len != 0) {
4228
0
                if (tls->server_name == NULL)
4229
0
                    continue;
4230
0
                if (!vec_is_string(ticket_ctx, tls->server_name))
4231
0
                    continue;
4232
0
            } else {
4233
0
                if (tls->server_name != NULL)
4234
0
                    continue;
4235
0
            }
4236
0
        }
4237
0
        { /* check key-exchange */
4238
0
            ptls_key_exchange_algorithm_t **a;
4239
0
            for (a = tls->ctx->key_exchanges; *a != NULL && (*a)->id != ticket_key_exchange_id; ++a)
4240
0
                ;
4241
0
            if (*a == NULL)
4242
0
                continue;
4243
0
            tls->key_share = *a;
4244
0
        }
4245
        /* check cipher-suite */
4246
0
        if (ticket_csid != tls->cipher_suite->id)
4247
0
            continue;
4248
        /* check negotiated-protocol */
4249
0
        if (ticket_negotiated_protocol.len != 0) {
4250
0
            if (tls->negotiated_protocol == NULL)
4251
0
                continue;
4252
0
            if (!vec_is_string(ticket_negotiated_protocol, tls->negotiated_protocol))
4253
0
                continue;
4254
0
        }
4255
        /* check the length of the decrypted psk and the PSK binder */
4256
0
        if (secret.len != tls->key_schedule->hashes[0].algo->digest_size)
4257
0
            continue;
4258
0
        if (ch->psk.identities.list[*psk_index].binder.len != tls->key_schedule->hashes[0].algo->digest_size)
4259
0
            continue;
4260
4261
        /* found */
4262
0
        goto Found;
4263
0
    }
4264
4265
    /* not found */
4266
0
    *psk_index = SIZE_MAX;
4267
0
    *accept_early_data = 0;
4268
0
    tls->key_share = NULL;
4269
0
    ret = 0;
4270
0
    goto Exit;
4271
4272
0
Found:
4273
0
    if (!is_second_flight && (ret = key_schedule_extract(tls->key_schedule, secret)) != 0)
4274
0
        goto Exit;
4275
0
    if ((ret = derive_secret_with_empty_digest(tls->key_schedule, binder_key,
4276
0
                                               tls->ctx->pre_shared_key.secret.base != NULL ? "ext binder" : "res binder")) != 0)
4277
0
        goto Exit;
4278
0
    ptls__key_schedule_update_hash(tls->key_schedule, ch_trunc.base, ch_trunc.len, 0);
4279
0
    if ((ret = calc_verify_data(binder_key /* to conserve space, reuse binder_key for storing verify_data */, tls->key_schedule,
4280
0
                                binder_key)) != 0)
4281
0
        goto Exit;
4282
0
    if (!ptls_mem_equal(ch->psk.identities.list[*psk_index].binder.base, binder_key,
4283
0
                        tls->key_schedule->hashes[0].algo->digest_size)) {
4284
0
        ret = PTLS_ALERT_DECRYPT_ERROR;
4285
0
        goto Exit;
4286
0
    }
4287
0
    ret = 0;
4288
4289
0
Exit:
4290
0
    ptls_buffer_dispose(&decbuf);
4291
0
    ptls_clear_memory(binder_key, sizeof(binder_key));
4292
0
    return ret;
4293
0
}
4294
4295
static int calc_cookie_signature(ptls_t *tls, ptls_handshake_properties_t *properties,
4296
                                 ptls_key_exchange_algorithm_t *negotiated_group, ptls_iovec_t tbs, uint8_t *sig)
4297
0
{
4298
0
    ptls_hash_algorithm_t *algo = tls->ctx->cipher_suites[0]->hash;
4299
0
    ptls_hash_context_t *hctx;
4300
4301
0
    if ((hctx = ptls_hmac_create(algo, properties->server.cookie.key, algo->digest_size)) == NULL)
4302
0
        return PTLS_ERROR_NO_MEMORY;
4303
4304
0
#define UPDATE_BLOCK(p, _len)                                                                                                      \
4305
0
    do {                                                                                                                           \
4306
0
        size_t len = (_len);                                                                                                       \
4307
0
        assert(len < UINT8_MAX);                                                                                                   \
4308
0
        uint8_t len8 = (uint8_t)len;                                                                                               \
4309
0
        hctx->update(hctx, &len8, 1);                                                                                              \
4310
0
        hctx->update(hctx, (p), len);                                                                                              \
4311
0
    } while (0)
4312
0
#define UPDATE16(_v)                                                                                                               \
4313
0
    do {                                                                                                                           \
4314
0
        uint16_t v = (_v);                                                                                                         \
4315
0
        uint8_t b[2] = {v >> 8, v & 0xff};                                                                                         \
4316
0
        hctx->update(hctx, b, 2);                                                                                                  \
4317
0
    } while (0)
4318
4319
0
    UPDATE_BLOCK(tls->client_random, sizeof(tls->client_random));
4320
0
    UPDATE_BLOCK(tls->server_name, tls->server_name != NULL ? strlen(tls->server_name) : 0);
4321
0
    UPDATE16(tls->cipher_suite->id);
4322
0
    UPDATE16(negotiated_group != NULL ? negotiated_group->id : 0);
4323
0
    UPDATE_BLOCK(properties->server.cookie.additional_data.base, properties->server.cookie.additional_data.len);
4324
4325
0
    UPDATE_BLOCK(tbs.base, tbs.len);
4326
4327
0
#undef UPDATE_BLOCK
4328
0
#undef UPDATE16
4329
4330
0
    hctx->final(hctx, sig, PTLS_HASH_FINAL_MODE_FREE);
4331
0
    return 0;
4332
0
}
4333
4334
static int certificate_type_exists(uint8_t *list, size_t count, uint8_t desired_type)
4335
0
{
4336
    /* empty type list means that we default to x509 */
4337
0
    if (desired_type == PTLS_CERTIFICATE_TYPE_X509 && count == 0)
4338
0
        return 1;
4339
0
    for (size_t i = 0; i < count; i++) {
4340
0
        if (list[i] == desired_type)
4341
0
            return 1;
4342
0
    }
4343
0
    return 0;
4344
0
}
4345
4346
static int server_handle_hello(ptls_t *tls, ptls_message_emitter_t *emitter, ptls_iovec_t message,
4347
                               ptls_handshake_properties_t *properties)
4348
0
{
4349
0
#define EMIT_SERVER_HELLO(sched, fill_rand, extensions, post_action)                                                               \
4350
0
    do {                                                                                                                           \
4351
0
        size_t sh_start_off;                                                                                                       \
4352
0
        ptls_push_message(emitter, NULL, PTLS_HANDSHAKE_TYPE_SERVER_HELLO, {                                                       \
4353
0
            sh_start_off = emitter->buf->off - PTLS_HANDSHAKE_HEADER_SIZE;                                                         \
4354
0
            ptls_buffer_push16(emitter->buf, 0x0303 /* legacy version */);                                                         \
4355
0
            if ((ret = ptls_buffer_reserve(emitter->buf, PTLS_HELLO_RANDOM_SIZE)) != 0)                                            \
4356
0
                goto Exit;                                                                                                         \
4357
0
            do {                                                                                                                   \
4358
0
                fill_rand                                                                                                          \
4359
0
            } while (0);                                                                                                           \
4360
0
            emitter->buf->off += PTLS_HELLO_RANDOM_SIZE;                                                                           \
4361
0
            ptls_buffer_push_block(emitter->buf, 1,                                                                                \
4362
0
                                   { ptls_buffer_pushv(emitter->buf, ch->legacy_session_id.base, ch->legacy_session_id.len); });   \
4363
0
            ptls_buffer_push16(emitter->buf, tls->cipher_suite->id);                                                               \
4364
0
            ptls_buffer_push(emitter->buf, 0);                                                                                     \
4365
0
            ptls_buffer_push_block(emitter->buf, 2, {                                                                              \
4366
0
                buffer_push_extension(emitter->buf, PTLS_EXTENSION_TYPE_SUPPORTED_VERSIONS,                                        \
4367
0
                                      { ptls_buffer_push16(emitter->buf, ch->selected_version); });                                \
4368
0
                do {                                                                                                               \
4369
0
                    extensions                                                                                                     \
4370
0
                } while (0);                                                                                                       \
4371
0
            });                                                                                                                    \
4372
0
        });                                                                                                                        \
4373
0
        do {                                                                                                                       \
4374
0
            post_action                                                                                                            \
4375
0
        } while (0);                                                                                                               \
4376
0
        ptls__key_schedule_update_hash((sched), emitter->buf->base + sh_start_off, emitter->buf->off - sh_start_off, 0);           \
4377
0
    } while (0)
4378
4379
0
#define EMIT_HELLO_RETRY_REQUEST(sched, negotiated_group, additional_extensions, post_action)                                      \
4380
0
    EMIT_SERVER_HELLO((sched), { memcpy(emitter->buf->base + emitter->buf->off, hello_retry_random, PTLS_HELLO_RANDOM_SIZE); },    \
4381
0
                      {                                                                                                            \
4382
0
                          ptls_key_exchange_algorithm_t *_negotiated_group = (negotiated_group);                                   \
4383
0
                          if (_negotiated_group != NULL) {                                                                         \
4384
0
                              buffer_push_extension(emitter->buf, PTLS_EXTENSION_TYPE_KEY_SHARE,                                   \
4385
0
                                                    { ptls_buffer_push16(emitter->buf, _negotiated_group->id); });                 \
4386
0
                          }                                                                                                        \
4387
0
                          do {                                                                                                     \
4388
0
                              additional_extensions                                                                                \
4389
0
                          } while (0);                                                                                             \
4390
0
                      },                                                                                                           \
4391
0
                      post_action)
4392
0
    struct st_ptls_client_hello_t *ch;
4393
0
    struct {
4394
0
        ptls_key_exchange_algorithm_t *algorithm;
4395
0
        ptls_iovec_t peer_key;
4396
0
    } key_share = {NULL};
4397
0
    struct {
4398
0
        uint8_t *encoded_ch_inner;
4399
0
        uint8_t *ch_outer_aad;
4400
0
        ptls_buffer_t ch_inner;
4401
0
    } ech = {NULL};
4402
0
    enum { HANDSHAKE_MODE_FULL, HANDSHAKE_MODE_PSK, HANDSHAKE_MODE_PSK_DHE } mode;
4403
0
    size_t psk_index = SIZE_MAX;
4404
0
    ptls_iovec_t pubkey = {0}, ecdh_secret = {0};
4405
0
    int accept_early_data = 0, is_second_flight = tls->state == PTLS_STATE_SERVER_EXPECT_SECOND_CLIENT_HELLO, ret;
4406
4407
0
    ptls_buffer_init(&ech.ch_inner, "", 0);
4408
4409
0
    if ((ch = malloc(sizeof(*ch))) == NULL) {
4410
0
        ret = PTLS_ERROR_NO_MEMORY;
4411
0
        goto Exit;
4412
0
    }
4413
4414
0
    *ch = (struct st_ptls_client_hello_t){.unknown_extensions = {{UINT16_MAX}}};
4415
4416
    /* decode ClientHello */
4417
0
    if ((ret = decode_client_hello(tls->ctx, ch, message.base + PTLS_HANDSHAKE_HEADER_SIZE, message.base + message.len, properties,
4418
0
                                   tls)) != 0)
4419
0
        goto Exit;
4420
0
    if ((ret = check_client_hello_constraints(tls->ctx, ch, is_second_flight ? tls->client_random : NULL, 0, message, tls)) != 0)
4421
0
        goto Exit;
4422
0
    if (!is_second_flight) {
4423
0
        memcpy(tls->client_random, ch->random_bytes, PTLS_HELLO_RANDOM_SIZE);
4424
0
        log_client_random(tls);
4425
0
    } else {
4426
        /* consistency check for ECH extension in response to HRR */
4427
0
        if (tls->ech.aead != NULL) {
4428
0
            if (ch->ech.payload.base == NULL) {
4429
0
                ret = PTLS_ALERT_MISSING_EXTENSION;
4430
0
                goto Exit;
4431
0
            }
4432
0
            if (!(ch->ech.config_id == tls->ech.config_id && ch->ech.cipher_suite.kdf == tls->ech.cipher->id.kdf &&
4433
0
                  ch->ech.cipher_suite.aead == tls->ech.cipher->id.aead && ch->ech.enc.len == 0)) {
4434
0
                ret = PTLS_ALERT_ILLEGAL_PARAMETER;
4435
0
                goto Exit;
4436
0
            }
4437
0
        }
4438
0
    }
4439
4440
    /* ECH */
4441
0
    if (ch->ech.payload.base != NULL) {
4442
0
        if (ch->ech.type != PTLS_ECH_CLIENT_HELLO_TYPE_OUTER) {
4443
0
            ret = PTLS_ALERT_ILLEGAL_PARAMETER;
4444
0
            goto Exit;
4445
0
        }
4446
0
        if (!is_second_flight)
4447
0
            tls->ech.state = PTLS_ECH_STATE_OFFERED;
4448
        /* obtain AEAD context for opening inner CH */
4449
0
        if (!is_second_flight && ch->ech.payload.base != NULL && tls->ctx->ech.server.create_opener != NULL) {
4450
0
            if ((tls->ech.aead = tls->ctx->ech.server.create_opener->cb(
4451
0
                     tls->ctx->ech.server.create_opener, &tls->ech.kem, &tls->ech.cipher, tls, ch->ech.config_id,
4452
0
                     ch->ech.cipher_suite, ch->ech.enc, ptls_iovec_init(ech_info_prefix, sizeof(ech_info_prefix)))) != NULL)
4453
0
                tls->ech.config_id = ch->ech.config_id;
4454
0
        }
4455
0
        if (!is_second_flight) {
4456
0
            PTLS_PROBE(ECH_SELECTION, tls, tls->ech.aead != NULL);
4457
0
            PTLS_LOG_CONN(ech_selection, tls, { PTLS_LOG_ELEMENT_BOOL(is_ech, tls->ech.aead != NULL); });
4458
0
        }
4459
0
        if (tls->ech.aead != NULL) {
4460
            /* now that AEAD context is available, create AAD and decrypt inner CH */
4461
0
            if ((ech.encoded_ch_inner = malloc(ch->ech.payload.len - tls->ech.aead->algo->tag_size)) == NULL ||
4462
0
                (ech.ch_outer_aad = malloc(message.len - PTLS_HANDSHAKE_HEADER_SIZE)) == NULL) {
4463
0
                ret = PTLS_ERROR_NO_MEMORY;
4464
0
                goto Exit;
4465
0
            }
4466
0
            memcpy(ech.ch_outer_aad, message.base + PTLS_HANDSHAKE_HEADER_SIZE, message.len - PTLS_HANDSHAKE_HEADER_SIZE);
4467
0
            memset(ech.ch_outer_aad + (ch->ech.payload.base - (message.base + PTLS_HANDSHAKE_HEADER_SIZE)), 0, ch->ech.payload.len);
4468
0
            if (ptls_aead_decrypt(tls->ech.aead, ech.encoded_ch_inner, ch->ech.payload.base, ch->ech.payload.len, is_second_flight,
4469
0
                                  ech.ch_outer_aad, message.len - PTLS_HANDSHAKE_HEADER_SIZE) != SIZE_MAX) {
4470
0
                tls->ech.state = PTLS_ECH_STATE_ACCEPTED;
4471
                /* successfully decrypted EncodedCHInner, build CHInner */
4472
0
                if ((ret = rebuild_ch_inner(&ech.ch_inner, ech.encoded_ch_inner,
4473
0
                                            ech.encoded_ch_inner + ch->ech.payload.len - tls->ech.aead->algo->tag_size, ch,
4474
0
                                            message.base + PTLS_HANDSHAKE_HEADER_SIZE + ch->first_extension_at,
4475
0
                                            message.base + message.len)) != 0)
4476
0
                    goto Exit;
4477
                /* treat inner ch as the message being received, re-decode it */
4478
0
                message = ptls_iovec_init(ech.ch_inner.base, ech.ch_inner.off);
4479
0
                *ch = (struct st_ptls_client_hello_t){.unknown_extensions = {{UINT16_MAX}}};
4480
0
                if ((ret = decode_client_hello(tls->ctx, ch, ech.ch_inner.base + PTLS_HANDSHAKE_HEADER_SIZE,
4481
0
                                               ech.ch_inner.base + ech.ch_inner.off, properties, tls)) != 0)
4482
0
                    goto Exit;
4483
0
                if ((ret = check_client_hello_constraints(tls->ctx, ch, is_second_flight ? tls->ech.inner_client_random : NULL, 1,
4484
0
                                                          message, tls)) != 0)
4485
0
                    goto Exit;
4486
0
                if (!is_second_flight)
4487
0
                    memcpy(tls->ech.inner_client_random, ch->random_bytes, PTLS_HELLO_RANDOM_SIZE);
4488
0
            } else if (is_second_flight) {
4489
                /* decryption failure of inner CH in 2nd CH is fatal */
4490
0
                ret = PTLS_ALERT_DECRYPT_ERROR;
4491
0
                goto Exit;
4492
0
            } else {
4493
                /* decryption failure of 1st CH indicates key mismatch; dispose of AEAD context to indicate adoption of outerCH */
4494
0
                ptls_aead_free(tls->ech.aead);
4495
0
                tls->ech.aead = NULL;
4496
0
            }
4497
0
        }
4498
0
    } else if (tls->ech.state != PTLS_ECH_STATE_NONE) {
4499
0
        assert(is_second_flight);
4500
0
        ret = PTLS_ALERT_ILLEGAL_PARAMETER;
4501
0
        goto Exit;
4502
0
    }
4503
4504
0
    if (tls->ctx->require_dhe_on_psk)
4505
0
        ch->psk.ke_modes &= ~(1u << PTLS_PSK_KE_MODE_PSK);
4506
4507
    /* handle client_random, legacy_session_id, SNI, ESNI */
4508
0
    if (!is_second_flight) {
4509
0
        if (ch->legacy_session_id.len != 0)
4510
0
            tls->send_change_cipher_spec = 1;
4511
0
        ptls_iovec_t server_name = {NULL};
4512
0
        if (ch->server_name.base != NULL)
4513
0
            server_name = ch->server_name;
4514
0
        if ((ret = call_on_client_hello_cb(tls, server_name, message, ch->cipher_suites, ch->alpn.list, ch->alpn.count,
4515
0
                                           ch->signature_algorithms.list, ch->signature_algorithms.count,
4516
0
                                           ch->cert_compression_algos.list, ch->cert_compression_algos.count,
4517
0
                                           ch->server_certificate_types.list, ch->server_certificate_types.count,
4518
0
                                           ch->psk.identities.list, ch->psk.identities.count, 0)) != 0)
4519
0
            goto Exit;
4520
0
        if (!certificate_type_exists(ch->server_certificate_types.list, ch->server_certificate_types.count,
4521
0
                                     tls->ctx->use_raw_public_keys ? PTLS_CERTIFICATE_TYPE_RAW_PUBLIC_KEY
4522
0
                                                                   : PTLS_CERTIFICATE_TYPE_X509)) {
4523
0
            ret = PTLS_ALERT_UNSUPPORTED_CERTIFICATE;
4524
0
            goto Exit;
4525
0
        }
4526
0
    } else {
4527
0
        if (ch->psk.early_data_indication) {
4528
0
            ret = PTLS_ALERT_DECODE_ERROR;
4529
0
            goto Exit;
4530
0
        }
4531
        /* We compare SNI only when the value is saved by the on_client_hello callback. This should be OK because we are
4532
         * ignoring the value unless the callback saves the server-name. */
4533
0
        if (tls->server_name != NULL) {
4534
0
            size_t l = strlen(tls->server_name);
4535
0
            if (!(ch->server_name.len == l && memcmp(ch->server_name.base, tls->server_name, l) == 0)) {
4536
0
                ret = PTLS_ALERT_HANDSHAKE_FAILURE;
4537
0
                goto Exit;
4538
0
            }
4539
0
        }
4540
0
    }
4541
4542
0
    { /* select (or check) cipher-suite, create key_schedule */
4543
0
        ptls_cipher_suite_t *cs;
4544
0
        if ((ret = select_cipher(&cs, tls->ctx->cipher_suites, ch->cipher_suites.base,
4545
0
                                 ch->cipher_suites.base + ch->cipher_suites.len, tls->ctx->server_cipher_preference,
4546
0
                                 tls->ctx->server_cipher_chacha_priority, tls->ctx->pre_shared_key.hash)) != 0)
4547
0
            goto Exit;
4548
0
        if (!is_second_flight) {
4549
0
            tls->cipher_suite = cs;
4550
0
            if ((tls->key_schedule = key_schedule_new(cs, NULL, 0)) == NULL) {
4551
0
                ret = PTLS_ERROR_NO_MEMORY;
4552
0
                goto Exit;
4553
0
            }
4554
0
        } else {
4555
0
            if (tls->cipher_suite != cs) {
4556
0
                ret = PTLS_ALERT_HANDSHAKE_FAILURE;
4557
0
                goto Exit;
4558
0
            }
4559
0
        }
4560
0
    }
4561
4562
    /* select key_share */
4563
0
    if (key_share.algorithm == NULL && ch->key_shares.base != NULL && tls->ctx->key_exchanges != NULL) {
4564
0
        const uint8_t *src = ch->key_shares.base, *const end = src + ch->key_shares.len;
4565
0
        ptls_decode_block(src, end, 2, {
4566
0
            if ((ret = select_key_share(&key_share.algorithm, &key_share.peer_key, tls->ctx->key_exchanges, &src, end, 0)) != 0)
4567
0
                goto Exit;
4568
0
        });
4569
0
    }
4570
4571
0
    if (!is_second_flight) {
4572
0
        if (ch->cookie.all.len != 0 && key_share.algorithm != NULL) {
4573
4574
0
            { /* use cookie to check the integrity of the handshake, and update the context */
4575
0
                uint8_t sig[PTLS_MAX_DIGEST_SIZE];
4576
0
                size_t sigsize = tls->ctx->cipher_suites[0]->hash->digest_size;
4577
0
                if ((ret = calc_cookie_signature(tls, properties, key_share.algorithm, ch->cookie.tbs, sig)) != 0)
4578
0
                    goto Exit;
4579
0
                if (!(ch->cookie.signature.len == sigsize && ptls_mem_equal(ch->cookie.signature.base, sig, sigsize))) {
4580
0
                    ret = PTLS_ALERT_HANDSHAKE_FAILURE;
4581
0
                    goto Exit;
4582
0
                }
4583
0
            }
4584
            /* integrity check passed; update states */
4585
0
            key_schedule_update_ch1hash_prefix(tls->key_schedule);
4586
0
            ptls__key_schedule_update_hash(tls->key_schedule, ch->cookie.ch1_hash.base, ch->cookie.ch1_hash.len, 0);
4587
0
            key_schedule_extract(tls->key_schedule,
4588
0
                                 tls->ctx->pre_shared_key.secret /* this argument will be a zero-length vector unless external PSK
4589
0
                                                                  is used, and that's fine; we never resume when sending HRR */);
4590
            /* ... reusing sendbuf to rebuild HRR for hash calculation */
4591
0
            size_t hrr_start = emitter->buf->off;
4592
0
            EMIT_HELLO_RETRY_REQUEST(tls->key_schedule, ch->cookie.sent_key_share ? key_share.algorithm : NULL,
4593
0
                                     {
4594
0
                                         buffer_push_extension(emitter->buf, PTLS_EXTENSION_TYPE_COOKIE, {
4595
0
                                             ptls_buffer_pushv(emitter->buf, ch->cookie.all.base, ch->cookie.all.len);
4596
0
                                         });
4597
0
                                     },
4598
0
                                     {});
4599
0
            emitter->buf->off = hrr_start;
4600
0
            is_second_flight = 1;
4601
4602
0
        } else if (ch->key_shares.base != NULL && tls->ctx->key_exchanges != NULL &&
4603
0
                   (key_share.algorithm == NULL || (properties != NULL && properties->server.enforce_retry))) {
4604
            /* send HelloRetryRequest, when trying to negotiate the key share but enforced by config or upon key-share mismatch */
4605
0
            if (ch->negotiated_groups.base == NULL) {
4606
0
                ret = PTLS_ALERT_MISSING_EXTENSION;
4607
0
                goto Exit;
4608
0
            }
4609
0
            ptls_key_exchange_algorithm_t *negotiated_group;
4610
0
            if ((ret = select_negotiated_group(&negotiated_group, tls->ctx->key_exchanges, ch->negotiated_groups.base,
4611
0
                                               ch->negotiated_groups.base + ch->negotiated_groups.len)) != 0)
4612
0
                goto Exit;
4613
0
            ptls__key_schedule_update_hash(tls->key_schedule, message.base, message.len, 0);
4614
0
            assert(tls->key_schedule->generation == 0);
4615
4616
            /* Either send a stateless retry (w. cookies) or a stateful one. When sending the latter, run the state machine. At the
4617
             * moment, stateless retry is disabled when ECH is used (do we need to support it?). */
4618
0
            int retry_uses_cookie =
4619
0
                properties != NULL && properties->server.retry_uses_cookie && !ptls_is_ech_handshake(tls, NULL, NULL, NULL);
4620
0
            if (!retry_uses_cookie) {
4621
0
                key_schedule_transform_post_ch1hash(tls->key_schedule);
4622
0
                key_schedule_extract(tls->key_schedule, tls->ctx->pre_shared_key.secret /* see comment above */);
4623
0
            }
4624
0
            size_t ech_confirm_off = 0;
4625
0
            EMIT_HELLO_RETRY_REQUEST(
4626
0
                tls->key_schedule, key_share.algorithm != NULL ? NULL : negotiated_group,
4627
0
                {
4628
0
                    ptls_buffer_t *sendbuf = emitter->buf;
4629
0
                    if (ptls_is_ech_handshake(tls, NULL, NULL, NULL)) {
4630
0
                        buffer_push_extension(sendbuf, PTLS_EXTENSION_TYPE_ENCRYPTED_CLIENT_HELLO, {
4631
0
                            if ((ret = ptls_buffer_reserve(sendbuf, PTLS_ECH_CONFIRM_LENGTH)) != 0)
4632
0
                                goto Exit;
4633
0
                            memset(sendbuf->base + sendbuf->off, 0, PTLS_ECH_CONFIRM_LENGTH);
4634
0
                            ech_confirm_off = sendbuf->off;
4635
0
                            sendbuf->off += PTLS_ECH_CONFIRM_LENGTH;
4636
0
                        });
4637
0
                    }
4638
0
                    if (retry_uses_cookie) {
4639
0
                        buffer_push_extension(sendbuf, PTLS_EXTENSION_TYPE_COOKIE, {
4640
0
                            ptls_buffer_push_block(sendbuf, 2, {
4641
                                /* push to-be-signed data */
4642
0
                                size_t tbs_start = sendbuf->off;
4643
0
                                ptls_buffer_push_block(sendbuf, 2, {
4644
                                    /* first block of the cookie data is the hash(ch1) */
4645
0
                                    ptls_buffer_push_block(sendbuf, 1, {
4646
0
                                        size_t sz = tls->cipher_suite->hash->digest_size;
4647
0
                                        if ((ret = ptls_buffer_reserve(sendbuf, sz)) != 0)
4648
0
                                            goto Exit;
4649
0
                                        key_schedule_extract_ch1hash(tls->key_schedule, sendbuf->base + sendbuf->off);
4650
0
                                        sendbuf->off += sz;
4651
0
                                    });
4652
                                    /* second is if we have sent key_share extension */
4653
0
                                    ptls_buffer_push(sendbuf, key_share.algorithm == NULL);
4654
                                    /* we can add more data here */
4655
0
                                });
4656
0
                                size_t tbs_len = sendbuf->off - tbs_start;
4657
                                /* push the signature */
4658
0
                                ptls_buffer_push_block(sendbuf, 1, {
4659
0
                                    size_t sz = tls->ctx->cipher_suites[0]->hash->digest_size;
4660
0
                                    if ((ret = ptls_buffer_reserve(sendbuf, sz)) != 0)
4661
0
                                        goto Exit;
4662
0
                                    if ((ret = calc_cookie_signature(tls, properties, negotiated_group,
4663
0
                                                                     ptls_iovec_init(sendbuf->base + tbs_start, tbs_len),
4664
0
                                                                     sendbuf->base + sendbuf->off)) != 0)
4665
0
                                        goto Exit;
4666
0
                                    sendbuf->off += sz;
4667
0
                                });
4668
0
                            });
4669
0
                        });
4670
0
                    }
4671
0
                },
4672
0
                {
4673
0
                    if (ech_confirm_off != 0 &&
4674
0
                        (ret = ech_calc_confirmation(
4675
0
                             tls->key_schedule, emitter->buf->base + ech_confirm_off, tls->ech.inner_client_random,
4676
0
                             ECH_CONFIRMATION_HRR,
4677
0
                             ptls_iovec_init(emitter->buf->base + sh_start_off, emitter->buf->off - sh_start_off))) != 0)
4678
0
                        goto Exit;
4679
0
                });
4680
0
            if (retry_uses_cookie) {
4681
0
                if ((ret = push_change_cipher_spec(tls, emitter)) != 0)
4682
0
                    goto Exit;
4683
0
                ret = PTLS_ERROR_STATELESS_RETRY;
4684
0
            } else {
4685
0
                tls->state = PTLS_STATE_SERVER_EXPECT_SECOND_CLIENT_HELLO;
4686
0
                if (ch->psk.early_data_indication)
4687
0
                    tls->server.early_data_skipped_bytes = 0;
4688
0
                ret = PTLS_ERROR_IN_PROGRESS;
4689
0
            }
4690
0
            goto Exit;
4691
0
        }
4692
0
    }
4693
4694
    /* handle unknown extensions */
4695
0
    if ((ret = report_unknown_extensions(tls, properties, ch->unknown_extensions)) != 0)
4696
0
        goto Exit;
4697
4698
    /* try psk handshake */
4699
0
    if (ch->psk.hash_end != 0 && (ch->psk.ke_modes & ((1u << PTLS_PSK_KE_MODE_PSK) | (1u << PTLS_PSK_KE_MODE_PSK_DHE))) != 0 &&
4700
0
        !tls->ctx->require_client_authentication &&
4701
0
        ((!is_second_flight && tls->ctx->encrypt_ticket != NULL) || tls->ctx->pre_shared_key.identity.base != NULL)) {
4702
0
        if ((ret = try_psk_handshake(tls, &psk_index, &accept_early_data, ch,
4703
0
                                     ptls_iovec_init(message.base, ch->psk.hash_end - message.base), is_second_flight)) != 0) {
4704
0
            goto Exit;
4705
0
        }
4706
0
    }
4707
4708
    /* If the server was setup to use an external PSK but failed to agree, abort the handshake. Because external PSK is a form of
4709
     * mutual authentication, it makes sense to abort (at least as the default). */
4710
0
    if (tls->ctx->pre_shared_key.identity.base != NULL && psk_index == SIZE_MAX) {
4711
0
        ret = PTLS_ALERT_UNKNOWN_PSK_IDENTITY;
4712
0
        goto Exit;
4713
0
    }
4714
4715
    /* If client authentication is enabled, we always force a full handshake.
4716
     * TODO: Check for `post_handshake_auth` extension and if that is present, do not force full handshake!
4717
     *       Remove also the check `!require_client_authentication` above.
4718
     *
4719
     * adjust key_schedule, determine handshake mode
4720
     */
4721
0
    if (psk_index == SIZE_MAX || tls->ctx->require_client_authentication) {
4722
0
        ptls__key_schedule_update_hash(tls->key_schedule, message.base, message.len, 0);
4723
0
        if (!is_second_flight) {
4724
0
            assert(tls->key_schedule->generation == 0);
4725
0
            key_schedule_extract(tls->key_schedule, ptls_iovec_init(NULL, 0));
4726
0
        }
4727
0
        mode = HANDSHAKE_MODE_FULL;
4728
0
        if (properties != NULL)
4729
0
            properties->server.selected_psk_binder.len = 0;
4730
0
    } else {
4731
0
        ptls__key_schedule_update_hash(tls->key_schedule, ch->psk.hash_end, message.base + message.len - ch->psk.hash_end, 0);
4732
0
        if ((ch->psk.ke_modes & (1u << PTLS_PSK_KE_MODE_PSK)) != 0) {
4733
0
            mode = HANDSHAKE_MODE_PSK;
4734
0
        } else {
4735
0
            assert((ch->psk.ke_modes & (1u << PTLS_PSK_KE_MODE_PSK_DHE)) != 0);
4736
0
            mode = HANDSHAKE_MODE_PSK_DHE;
4737
0
        }
4738
0
        tls->is_psk_handshake = 1;
4739
0
        if (properties != NULL) {
4740
0
            ptls_iovec_t *selected = &ch->psk.identities.list[psk_index].binder;
4741
0
            memcpy(properties->server.selected_psk_binder.base, selected->base, selected->len);
4742
0
            properties->server.selected_psk_binder.len = selected->len;
4743
0
        }
4744
0
    }
4745
4746
    /* determine number of tickets to send */
4747
0
    if (ch->psk.ke_modes != 0 && tls->ctx->ticket_lifetime != 0) {
4748
0
        if (ch->ticket_request.new_session_count != 0) {
4749
0
            tls->server.num_tickets_to_send =
4750
0
                tls->is_psk_handshake ? ch->ticket_request.resumption_count : ch->ticket_request.new_session_count;
4751
0
        } else {
4752
0
            tls->server.num_tickets_to_send = 1;
4753
0
        }
4754
0
        uint8_t max_tickets = tls->ctx->ticket_requests.server.max_count;
4755
0
        if (max_tickets == 0)
4756
0
            max_tickets = PTLS_DEFAULT_MAX_TICKETS_TO_SERVE;
4757
0
        if (tls->server.num_tickets_to_send > max_tickets)
4758
0
            tls->server.num_tickets_to_send = max_tickets;
4759
0
    } else {
4760
0
        tls->server.num_tickets_to_send = 0;
4761
0
    }
4762
4763
0
    if (accept_early_data && tls->ctx->max_early_data_size != 0 && psk_index == 0) {
4764
0
        if ((tls->pending_handshake_secret = malloc(PTLS_MAX_DIGEST_SIZE)) == NULL) {
4765
0
            ret = PTLS_ERROR_NO_MEMORY;
4766
0
            goto Exit;
4767
0
        }
4768
0
        if ((ret = derive_exporter_secret(tls, 1)) != 0)
4769
0
            goto Exit;
4770
0
        if ((ret = setup_traffic_protection(tls, 0, "c e traffic", 1, 0, 0)) != 0)
4771
0
            goto Exit;
4772
0
    }
4773
4774
    /* run key-exchange, to obtain pubkey and secret */
4775
0
    if (mode != HANDSHAKE_MODE_PSK) {
4776
0
        if (key_share.algorithm == NULL) {
4777
0
            ret = ch->key_shares.base != NULL ? PTLS_ALERT_HANDSHAKE_FAILURE : PTLS_ALERT_MISSING_EXTENSION;
4778
0
            goto Exit;
4779
0
        }
4780
0
        if ((ret = key_share.algorithm->exchange(key_share.algorithm, &pubkey, &ecdh_secret, key_share.peer_key)) != 0) {
4781
0
            assert(pubkey.base == NULL);
4782
0
            assert(ecdh_secret.base == NULL);
4783
0
            goto Exit;
4784
0
        }
4785
0
        tls->key_share = key_share.algorithm;
4786
0
    }
4787
4788
0
    { /* send ServerHello */
4789
0
        size_t ech_confirm_off = 0;
4790
0
        EMIT_SERVER_HELLO(
4791
0
            tls->key_schedule,
4792
0
            {
4793
0
                tls->ctx->random_bytes(emitter->buf->base + emitter->buf->off, PTLS_HELLO_RANDOM_SIZE);
4794
                /* when accepting CHInner, last 8 byte of SH.random is zero for the handshake transcript */
4795
0
                if (ptls_is_ech_handshake(tls, NULL, NULL, NULL)) {
4796
0
                    ech_confirm_off = emitter->buf->off + PTLS_HELLO_RANDOM_SIZE - PTLS_ECH_CONFIRM_LENGTH;
4797
0
                    memset(emitter->buf->base + ech_confirm_off, 0, PTLS_ECH_CONFIRM_LENGTH);
4798
0
                }
4799
0
            },
4800
0
            {
4801
0
                ptls_buffer_t *sendbuf = emitter->buf;
4802
0
                if (mode != HANDSHAKE_MODE_PSK) {
4803
0
                    buffer_push_extension(sendbuf, PTLS_EXTENSION_TYPE_KEY_SHARE, {
4804
0
                        ptls_buffer_push16(sendbuf, key_share.algorithm->id);
4805
0
                        ptls_buffer_push_block(sendbuf, 2, { ptls_buffer_pushv(sendbuf, pubkey.base, pubkey.len); });
4806
0
                    });
4807
0
                }
4808
0
                if (mode != HANDSHAKE_MODE_FULL) {
4809
0
                    buffer_push_extension(sendbuf, PTLS_EXTENSION_TYPE_PRE_SHARED_KEY,
4810
0
                                          { ptls_buffer_push16(sendbuf, (uint16_t)psk_index); });
4811
0
                }
4812
0
            },
4813
0
            {
4814
0
                if (ech_confirm_off != 0 &&
4815
0
                    (ret = ech_calc_confirmation(
4816
0
                         tls->key_schedule, emitter->buf->base + ech_confirm_off, tls->ech.inner_client_random,
4817
0
                         ECH_CONFIRMATION_SERVER_HELLO,
4818
0
                         ptls_iovec_init(emitter->buf->base + sh_start_off, emitter->buf->off - sh_start_off))) != 0)
4819
0
                    goto Exit;
4820
0
            });
4821
0
    }
4822
4823
    /* processing of ECH is complete; dispose state */
4824
0
    clear_ech(&tls->ech, 1);
4825
4826
0
    if ((ret = push_change_cipher_spec(tls, emitter)) != 0)
4827
0
        goto Exit;
4828
4829
    /* create protection contexts for the handshake */
4830
0
    assert(tls->key_schedule->generation == 1);
4831
0
    key_schedule_extract(tls->key_schedule, ecdh_secret);
4832
0
    if ((ret = setup_traffic_protection(tls, 1, "s hs traffic", 2, 0, 0)) != 0)
4833
0
        goto Exit;
4834
0
    if (tls->pending_handshake_secret != NULL) {
4835
0
        if ((ret = derive_secret(tls->key_schedule, tls->pending_handshake_secret, "c hs traffic")) != 0)
4836
0
            goto Exit;
4837
0
        if (tls->ctx->update_traffic_key != NULL &&
4838
0
            (ret = tls->ctx->update_traffic_key->cb(tls->ctx->update_traffic_key, tls, 0, 2, tls->pending_handshake_secret)) != 0)
4839
0
            goto Exit;
4840
0
    } else {
4841
0
        if ((ret = setup_traffic_protection(tls, 0, "c hs traffic", 2, 0, 0)) != 0)
4842
0
            goto Exit;
4843
0
        if (ch->psk.early_data_indication)
4844
0
            tls->server.early_data_skipped_bytes = 0;
4845
0
    }
4846
4847
    /* send EncryptedExtensions */
4848
0
    ptls_push_message(emitter, tls->key_schedule, PTLS_HANDSHAKE_TYPE_ENCRYPTED_EXTENSIONS, {
4849
0
        ptls_buffer_t *sendbuf = emitter->buf;
4850
0
        ptls_buffer_push_block(sendbuf, 2, {
4851
0
            if (tls->server_name != NULL) {
4852
                /* In this event, the server SHALL include an extension of type "server_name" in the (extended) server hello.
4853
                 * The "extension_data" field of this extension SHALL be empty. (RFC 6066 section 3) */
4854
0
                buffer_push_extension(sendbuf, PTLS_EXTENSION_TYPE_SERVER_NAME, {});
4855
0
            }
4856
0
            if (tls->ctx->use_raw_public_keys) {
4857
0
                buffer_push_extension(sendbuf, PTLS_EXTENSION_TYPE_SERVER_CERTIFICATE_TYPE,
4858
0
                                      { ptls_buffer_push(sendbuf, PTLS_CERTIFICATE_TYPE_RAW_PUBLIC_KEY); });
4859
0
            }
4860
0
            if (tls->negotiated_protocol != NULL) {
4861
0
                buffer_push_extension(sendbuf, PTLS_EXTENSION_TYPE_ALPN, {
4862
0
                    ptls_buffer_push_block(sendbuf, 2, {
4863
0
                        ptls_buffer_push_block(sendbuf, 1, {
4864
0
                            ptls_buffer_pushv(sendbuf, tls->negotiated_protocol, strlen(tls->negotiated_protocol));
4865
0
                        });
4866
0
                    });
4867
0
                });
4868
0
            }
4869
0
            if (tls->pending_handshake_secret != NULL)
4870
0
                buffer_push_extension(sendbuf, PTLS_EXTENSION_TYPE_EARLY_DATA, {});
4871
            /* send ECH retry_configs, if ECH was offered by rejected, even though we (the server) could have accepted ECH */
4872
0
            if (tls->ech.state == PTLS_ECH_STATE_OFFERED && tls->ctx->ech.server.create_opener != NULL &&
4873
0
                tls->ctx->ech.server.retry_configs.len != 0)
4874
0
                buffer_push_extension(sendbuf, PTLS_EXTENSION_TYPE_ENCRYPTED_CLIENT_HELLO, {
4875
0
                    ptls_buffer_pushv(sendbuf, tls->ctx->ech.server.retry_configs.base, tls->ctx->ech.server.retry_configs.len);
4876
0
                });
4877
0
            if (ch->ticket_request.new_session_count != 0 && tls->server.num_tickets_to_send != 0)
4878
0
                buffer_push_extension(sendbuf, PTLS_EXTENSION_TYPE_TICKET_REQUEST,
4879
0
                                      { ptls_buffer_push(sendbuf, tls->server.num_tickets_to_send); });
4880
0
            if ((ret = push_additional_extensions(properties, sendbuf)) != 0)
4881
0
                goto Exit;
4882
0
        });
4883
0
    });
4884
4885
0
    if (mode == HANDSHAKE_MODE_FULL) {
4886
        /* send certificate request if client authentication is activated */
4887
0
        if (tls->ctx->require_client_authentication) {
4888
0
            ptls_push_message(emitter, tls->key_schedule, PTLS_HANDSHAKE_TYPE_CERTIFICATE_REQUEST, {
4889
0
                ptls_buffer_t *sendbuf = emitter->buf;
4890
                /* certificate_request_context: this field SHALL be zero length, unless the certificate request is used for post-
4891
                 * handshake authentication. */
4892
0
                ptls_buffer_push(sendbuf, 0);
4893
                /* extensions */
4894
0
                ptls_buffer_push_block(sendbuf, 2, {
4895
0
                    buffer_push_extension(sendbuf, PTLS_EXTENSION_TYPE_SIGNATURE_ALGORITHMS, {
4896
0
                        if ((ret = push_signature_algorithms(tls->ctx->verify_certificate, sendbuf)) != 0)
4897
0
                            goto Exit;
4898
0
                    });
4899
                    /* certificate authorities entension */
4900
0
                    if (tls->ctx->client_ca_names.count > 0) {
4901
0
                        buffer_push_extension(sendbuf, PTLS_EXTENSION_TYPE_CERTIFICATE_AUTHORITIES, {
4902
0
                            ptls_buffer_push_block(sendbuf, 2, {
4903
0
                                for (size_t i = 0; i != tls->ctx->client_ca_names.count; ++i) {
4904
0
                                    ptls_buffer_push_block(sendbuf, 2, {
4905
0
                                        ptls_iovec_t name = tls->ctx->client_ca_names.list[i];
4906
0
                                        ptls_buffer_pushv(sendbuf, name.base, name.len);
4907
0
                                    });
4908
0
                                }
4909
0
                            });
4910
0
                        });
4911
0
                    }
4912
0
                });
4913
0
            });
4914
4915
0
            if (ret != 0) {
4916
0
                goto Exit;
4917
0
            }
4918
0
        }
4919
4920
        /* send certificate */
4921
0
        if ((ret = send_certificate(tls, emitter, &ch->signature_algorithms, ptls_iovec_init(NULL, 0), ch->status_request,
4922
0
                                    ch->cert_compression_algos.list, ch->cert_compression_algos.count)) != 0)
4923
0
            goto Exit;
4924
        /* send certificateverify, finished, and complete the handshake */
4925
0
        if ((ret = server_finish_handshake(tls, emitter, 1, &ch->signature_algorithms)) != 0)
4926
0
            goto Exit;
4927
0
    } else {
4928
        /* send finished, and complete the handshake */
4929
0
        if ((ret = server_finish_handshake(tls, emitter, 0, NULL)) != 0)
4930
0
            goto Exit;
4931
0
    }
4932
4933
0
Exit:
4934
0
    free(pubkey.base);
4935
0
    if (ecdh_secret.base != NULL) {
4936
0
        ptls_clear_memory(ecdh_secret.base, ecdh_secret.len);
4937
0
        free(ecdh_secret.base);
4938
0
    }
4939
0
    free(ech.encoded_ch_inner);
4940
0
    free(ech.ch_outer_aad);
4941
0
    ptls_buffer_dispose(&ech.ch_inner);
4942
0
    free(ch);
4943
0
    return ret;
4944
4945
0
#undef EMIT_SERVER_HELLO
4946
0
#undef EMIT_HELLO_RETRY_REQUEST
4947
0
}
4948
4949
static int server_finish_handshake(ptls_t *tls, ptls_message_emitter_t *emitter, int send_cert_verify,
4950
                                   struct st_ptls_signature_algorithms_t *signature_algorithms)
4951
0
{
4952
0
    int ret;
4953
4954
0
    if (send_cert_verify) {
4955
0
        if ((ret = send_certificate_verify(tls, emitter, signature_algorithms, PTLS_SERVER_CERTIFICATE_VERIFY_CONTEXT_STRING)) !=
4956
0
            0) {
4957
0
            if (ret == PTLS_ERROR_ASYNC_OPERATION) {
4958
0
                tls->state = PTLS_STATE_SERVER_GENERATING_CERTIFICATE_VERIFY;
4959
0
            }
4960
0
            goto Exit;
4961
0
        }
4962
0
    }
4963
4964
0
    if ((ret = send_finished(tls, emitter)) != 0)
4965
0
        goto Exit;
4966
4967
0
    assert(tls->key_schedule->generation == 2);
4968
0
    if ((ret = key_schedule_extract(tls->key_schedule, ptls_iovec_init(NULL, 0))) != 0)
4969
0
        goto Exit;
4970
0
    if ((ret = setup_traffic_protection(tls, 1, "s ap traffic", 3, 0, 0)) != 0)
4971
0
        goto Exit;
4972
0
    if ((ret = derive_secret(tls->key_schedule, tls->server.pending_traffic_secret, "c ap traffic")) != 0)
4973
0
        goto Exit;
4974
0
    if ((ret = derive_exporter_secret(tls, 0)) != 0)
4975
0
        goto Exit;
4976
4977
0
    if (tls->pending_handshake_secret != NULL) {
4978
0
        if (tls->ctx->omit_end_of_early_data) {
4979
0
            if ((ret = commission_handshake_secret(tls)) != 0)
4980
0
                goto Exit;
4981
0
            tls->state = PTLS_STATE_SERVER_EXPECT_FINISHED;
4982
0
        } else {
4983
0
            tls->state = PTLS_STATE_SERVER_EXPECT_END_OF_EARLY_DATA;
4984
0
        }
4985
0
    } else if (tls->ctx->require_client_authentication) {
4986
0
        tls->state = PTLS_STATE_SERVER_EXPECT_CERTIFICATE;
4987
0
    } else {
4988
0
        tls->state = PTLS_STATE_SERVER_EXPECT_FINISHED;
4989
0
    }
4990
4991
    /* send session ticket if necessary */
4992
0
    if (tls->server.num_tickets_to_send != 0) {
4993
0
        assert(tls->ctx->ticket_lifetime != 0);
4994
0
        for (uint8_t i = 0; i < tls->server.num_tickets_to_send; ++i)
4995
0
            if ((ret = send_session_ticket(tls, emitter)) != 0)
4996
0
                goto Exit;
4997
0
    }
4998
4999
0
    if (tls->ctx->require_client_authentication) {
5000
0
        ret = PTLS_ERROR_IN_PROGRESS;
5001
0
    } else {
5002
0
        ret = 0;
5003
0
    }
5004
5005
0
Exit:
5006
0
    return ret;
5007
0
}
5008
5009
static int server_handle_end_of_early_data(ptls_t *tls, ptls_iovec_t message)
5010
0
{
5011
0
    int ret;
5012
5013
0
    if ((ret = commission_handshake_secret(tls)) != 0)
5014
0
        goto Exit;
5015
5016
0
    ptls__key_schedule_update_hash(tls->key_schedule, message.base, message.len, 0);
5017
0
    tls->state = PTLS_STATE_SERVER_EXPECT_FINISHED;
5018
0
    ret = PTLS_ERROR_IN_PROGRESS;
5019
5020
0
Exit:
5021
0
    return ret;
5022
0
}
5023
5024
static int server_handle_finished(ptls_t *tls, ptls_iovec_t message)
5025
0
{
5026
0
    int ret;
5027
5028
0
    if ((ret = verify_finished(tls, message)) != 0)
5029
0
        return ret;
5030
5031
0
    memcpy(tls->traffic_protection.dec.secret, tls->server.pending_traffic_secret, sizeof(tls->server.pending_traffic_secret));
5032
0
    ptls_clear_memory(tls->server.pending_traffic_secret, sizeof(tls->server.pending_traffic_secret));
5033
0
    if ((ret = setup_traffic_protection(tls, 0, NULL, 3, 0, 0)) != 0)
5034
0
        return ret;
5035
5036
0
    ptls__key_schedule_update_hash(tls->key_schedule, message.base, message.len, 0);
5037
5038
0
    tls->state = PTLS_STATE_SERVER_POST_HANDSHAKE;
5039
0
    return 0;
5040
0
}
5041
5042
static int update_traffic_key(ptls_t *tls, int is_enc)
5043
0
{
5044
0
    struct st_ptls_traffic_protection_t *tp = is_enc ? &tls->traffic_protection.enc : &tls->traffic_protection.dec;
5045
0
    uint8_t secret[PTLS_MAX_DIGEST_SIZE];
5046
0
    int ret;
5047
5048
0
    ptls_hash_algorithm_t *hash = tls->key_schedule->hashes[0].algo;
5049
0
    if ((ret = ptls_hkdf_expand_label(hash, secret, hash->digest_size, ptls_iovec_init(tp->secret, hash->digest_size),
5050
0
                                      "traffic upd", ptls_iovec_init(NULL, 0), NULL)) != 0)
5051
0
        goto Exit;
5052
0
    memcpy(tp->secret, secret, sizeof(secret));
5053
0
    ret = setup_traffic_protection(tls, is_enc, NULL, 3, 0, 1);
5054
5055
0
Exit:
5056
0
    ptls_clear_memory(secret, sizeof(secret));
5057
0
    return ret;
5058
0
}
5059
5060
static int handle_key_update(ptls_t *tls, ptls_message_emitter_t *emitter, ptls_iovec_t message)
5061
0
{
5062
0
    const uint8_t *src = message.base + PTLS_HANDSHAKE_HEADER_SIZE, *const end = message.base + message.len;
5063
0
    int ret;
5064
5065
    /* validate */
5066
0
    if (end - src != 1 || *src > 1)
5067
0
        return PTLS_ALERT_DECODE_ERROR;
5068
5069
    /* update receive key */
5070
0
    if ((ret = update_traffic_key(tls, 0)) != 0)
5071
0
        return ret;
5072
5073
0
    if (*src) {
5074
0
        if (tls->ctx->update_traffic_key != NULL)
5075
0
            return PTLS_ALERT_UNEXPECTED_MESSAGE;
5076
0
        tls->needs_key_update = 1;
5077
0
    }
5078
5079
0
    return 0;
5080
0
}
5081
5082
static int parse_record_header(struct st_ptls_record_t *rec, const uint8_t *src)
5083
0
{
5084
0
    rec->type = src[0];
5085
0
    rec->version = ntoh16(src + 1);
5086
0
    rec->length = ntoh16(src + 3);
5087
5088
0
    if (rec->length >
5089
0
        (size_t)(rec->type == PTLS_CONTENT_TYPE_APPDATA ? PTLS_MAX_ENCRYPTED_RECORD_SIZE : PTLS_MAX_PLAINTEXT_RECORD_SIZE))
5090
0
        return PTLS_ALERT_DECODE_ERROR;
5091
5092
0
    return 0;
5093
0
}
5094
5095
static int parse_record(ptls_t *tls, struct st_ptls_record_t *rec, const uint8_t *src, size_t *len)
5096
0
{
5097
0
    int ret;
5098
5099
0
    assert(*len != 0);
5100
5101
    /* Check if the first byte is something that we can handle, otherwise do not bother parsing / buffering the entire record as it
5102
     * is obviously broken. SSL 2.0 handshakes fall into this path as well. */
5103
0
    if (tls->recvbuf.rec.base == NULL) {
5104
0
        uint8_t type = src[0];
5105
0
        switch (type) {
5106
0
        case PTLS_CONTENT_TYPE_CHANGE_CIPHER_SPEC:
5107
0
        case PTLS_CONTENT_TYPE_ALERT:
5108
0
        case PTLS_CONTENT_TYPE_HANDSHAKE:
5109
0
        case PTLS_CONTENT_TYPE_APPDATA:
5110
0
            break;
5111
0
        default:
5112
0
            return PTLS_ALERT_DECODE_ERROR;
5113
0
        }
5114
0
    }
5115
5116
0
    if (tls->recvbuf.rec.base == NULL && *len >= 5) {
5117
        /* fast path */
5118
0
        if ((ret = parse_record_header(rec, src)) != 0)
5119
0
            return ret;
5120
0
        if (5 + rec->length <= *len) {
5121
0
            rec->fragment = src + 5;
5122
0
            *len = rec->length + 5;
5123
0
            return 0;
5124
0
        }
5125
0
    }
5126
5127
    /* slow path */
5128
0
    const uint8_t *const end = src + *len;
5129
0
    *rec = (struct st_ptls_record_t){0};
5130
5131
0
    if (tls->recvbuf.rec.base == NULL) {
5132
0
        ptls_buffer_init(&tls->recvbuf.rec, "", 0);
5133
0
        if ((ret = ptls_buffer_reserve(&tls->recvbuf.rec, 5)) != 0)
5134
0
            return ret;
5135
0
    }
5136
5137
    /* fill and parse the header */
5138
0
    while (tls->recvbuf.rec.off < 5) {
5139
0
        if (src == end)
5140
0
            return PTLS_ERROR_IN_PROGRESS;
5141
0
        tls->recvbuf.rec.base[tls->recvbuf.rec.off++] = *src++;
5142
0
    }
5143
0
    if ((ret = parse_record_header(rec, tls->recvbuf.rec.base)) != 0)
5144
0
        return ret;
5145
5146
    /* fill the fragment */
5147
0
    size_t addlen = rec->length + 5 - tls->recvbuf.rec.off;
5148
0
    if (addlen != 0) {
5149
0
        if ((ret = ptls_buffer_reserve(&tls->recvbuf.rec, addlen)) != 0)
5150
0
            return ret;
5151
0
        if (addlen > (size_t)(end - src))
5152
0
            addlen = end - src;
5153
0
        if (addlen != 0) {
5154
0
            memcpy(tls->recvbuf.rec.base + tls->recvbuf.rec.off, src, addlen);
5155
0
            tls->recvbuf.rec.off += addlen;
5156
0
            src += addlen;
5157
0
        }
5158
0
    }
5159
5160
    /* set rec->fragment if a complete record has been parsed */
5161
0
    if (tls->recvbuf.rec.off == rec->length + 5) {
5162
0
        rec->fragment = tls->recvbuf.rec.base + 5;
5163
0
        ret = 0;
5164
0
    } else {
5165
0
        ret = PTLS_ERROR_IN_PROGRESS;
5166
0
    }
5167
5168
0
    *len -= end - src;
5169
0
    return ret;
5170
0
}
5171
5172
static void update_open_count(ptls_context_t *ctx, ssize_t delta)
5173
0
{
5174
0
    if (ctx->update_open_count != NULL)
5175
0
        ctx->update_open_count->cb(ctx->update_open_count, delta);
5176
0
}
5177
5178
static ptls_t *new_instance(ptls_context_t *ctx, int is_server)
5179
0
{
5180
0
    ptls_t *tls;
5181
5182
    /* check consistency of `ptls_context_t` before instantiating a connection object */
5183
0
    assert(ctx->get_time != NULL && "please set ctx->get_time to `&ptls_get_time`; see #92");
5184
0
    if (ctx->pre_shared_key.identity.base != NULL) {
5185
0
        assert(ctx->pre_shared_key.identity.len != 0 && ctx->pre_shared_key.secret.base != NULL &&
5186
0
               ctx->pre_shared_key.secret.len != 0 && ctx->pre_shared_key.hash != NULL &&
5187
0
               "`ptls_context_t::pre_shared_key` in incosistent state");
5188
0
    } else {
5189
0
        assert(ctx->pre_shared_key.identity.len == 0 && ctx->pre_shared_key.secret.base == NULL &&
5190
0
               ctx->pre_shared_key.secret.len == 0 && ctx->pre_shared_key.hash == NULL &&
5191
0
               "`ptls_context_t::pre_shared_key` in inconsitent state");
5192
0
    }
5193
5194
0
    if ((tls = malloc(sizeof(*tls))) == NULL)
5195
0
        return NULL;
5196
5197
0
    update_open_count(ctx, 1);
5198
0
    *tls = (ptls_t){ctx};
5199
0
    tls->is_server = is_server;
5200
0
    tls->send_change_cipher_spec = ctx->send_change_cipher_spec;
5201
5202
0
#if PTLS_HAVE_LOG
5203
0
    if (ptls_log_conn_state_override != NULL) {
5204
0
        tls->log_state = *ptls_log_conn_state_override;
5205
0
    } else {
5206
0
        ptls_log_init_conn_state(&tls->log_state, ctx->random_bytes, 0, NULL);
5207
0
    }
5208
0
#endif
5209
5210
0
    return tls;
5211
0
}
5212
5213
ptls_t *ptls_client_new(ptls_context_t *ctx)
5214
0
{
5215
0
    ptls_t *tls = new_instance(ctx, 0);
5216
0
    tls->state = PTLS_STATE_CLIENT_HANDSHAKE_START;
5217
0
    tls->ctx->random_bytes(tls->client_random, sizeof(tls->client_random));
5218
0
    log_client_random(tls);
5219
0
    if (tls->send_change_cipher_spec) {
5220
0
        tls->client.legacy_session_id =
5221
0
            ptls_iovec_init(tls->client.legacy_session_id_buf, sizeof(tls->client.legacy_session_id_buf));
5222
0
        tls->ctx->random_bytes(tls->client.legacy_session_id.base, tls->client.legacy_session_id.len);
5223
0
    }
5224
5225
0
    PTLS_PROBE(NEW, tls, 0);
5226
0
    PTLS_LOG_CONN(new, tls, { PTLS_LOG_ELEMENT_BOOL(is_server, 0); });
5227
0
    return tls;
5228
0
}
5229
5230
ptls_t *ptls_server_new(ptls_context_t *ctx)
5231
0
{
5232
0
    ptls_t *tls = new_instance(ctx, 1);
5233
0
    tls->state = PTLS_STATE_SERVER_EXPECT_CLIENT_HELLO;
5234
0
    tls->server.early_data_skipped_bytes = UINT32_MAX;
5235
5236
0
    PTLS_PROBE(NEW, tls, 1);
5237
0
    PTLS_LOG_CONN(new, tls, { PTLS_LOG_ELEMENT_BOOL(is_server, 1); });
5238
0
    return tls;
5239
0
}
5240
5241
#define export_tls_params(output, is_server, session_reused, protocol_version, cipher, client_random, server_name,                 \
5242
                          negotiated_protocol, ver_block)                                                                          \
5243
0
    do {                                                                                                                           \
5244
0
        const char *_server_name = (server_name);                                                                                  \
5245
0
        ptls_iovec_t _negotiated_protocol = (negotiated_protocol);                                                                 \
5246
0
        ptls_buffer_push_block((output), 2, {                                                                                      \
5247
0
            ptls_buffer_push((output), (is_server));                                                                               \
5248
0
            ptls_buffer_push((output), (session_reused));                                                                          \
5249
0
            ptls_buffer_push16((output), (protocol_version));                                                                      \
5250
0
            ptls_buffer_push16((output), (cipher)->id);                                                                            \
5251
0
            ptls_buffer_pushv((output), (client_random), PTLS_HELLO_RANDOM_SIZE);                                                  \
5252
0
            ptls_buffer_push_block((output), 2, {                                                                                  \
5253
0
                size_t len = _server_name != NULL ? strlen(_server_name) : 0;                                                      \
5254
0
                ptls_buffer_pushv((output), _server_name, len);                                                                    \
5255
0
            });                                                                                                                    \
5256
0
            ptls_buffer_push_block((output), 2,                                                                                    \
5257
0
                                   { ptls_buffer_pushv((output), _negotiated_protocol.base, _negotiated_protocol.len); });         \
5258
0
            ptls_buffer_push_block((output), 2, {ver_block}); /* version-specific block */                                         \
5259
0
            ptls_buffer_push_block((output), 2, {});          /* for future extensions */                                          \
5260
0
        });                                                                                                                        \
5261
0
    } while (0)
5262
5263
static int export_tls12_params(ptls_buffer_t *output, int is_server, int session_reused, ptls_cipher_suite_t *cipher,
5264
                               const void *client_random, const char *server_name, ptls_iovec_t negotiated_protocol,
5265
                               const void *enc_key, const void *enc_iv, uint64_t enc_seq, uint64_t enc_record_iv,
5266
                               const void *dec_key, const void *dec_iv, uint64_t dec_seq)
5267
0
{
5268
0
    int ret;
5269
5270
0
    export_tls_params(output, is_server, session_reused, PTLS_PROTOCOL_VERSION_TLS12, cipher, client_random, server_name,
5271
0
                      negotiated_protocol, {
5272
0
                          ptls_buffer_pushv(output, enc_key, cipher->aead->key_size);
5273
0
                          ptls_buffer_pushv(output, enc_iv, cipher->aead->tls12.fixed_iv_size);
5274
0
                          ptls_buffer_push64(output, enc_seq);
5275
0
                          if (cipher->aead->tls12.record_iv_size != 0)
5276
0
                              ptls_buffer_push64(output, enc_record_iv);
5277
0
                          ptls_buffer_pushv(output, dec_key, cipher->aead->key_size);
5278
0
                          ptls_buffer_pushv(output, dec_iv, cipher->aead->tls12.fixed_iv_size);
5279
0
                          ptls_buffer_push64(output, dec_seq);
5280
0
                      });
5281
0
    ret = 0;
5282
5283
0
Exit:
5284
0
    return ret;
5285
0
}
5286
5287
int ptls_build_tls12_export_params(ptls_context_t *ctx, ptls_buffer_t *output, int is_server, int session_reused,
5288
                                   ptls_cipher_suite_t *cipher, const void *master_secret, const void *hello_randoms,
5289
                                   uint64_t next_send_record_iv, const char *server_name, ptls_iovec_t negotiated_protocol)
5290
0
{
5291
0
    assert(cipher->aead->tls12.fixed_iv_size + cipher->aead->tls12.record_iv_size != 0 || !"given cipher-suite supports TLS/1.2");
5292
5293
0
    uint8_t key_block[(PTLS_MAX_SECRET_SIZE + PTLS_MAX_IV_SIZE) * 2];
5294
0
    size_t key_block_len = (cipher->aead->key_size + cipher->aead->tls12.fixed_iv_size) * 2;
5295
0
    int ret;
5296
5297
0
    assert(key_block_len <= sizeof(key_block));
5298
5299
    /* generate key block */
5300
0
    if ((ret =
5301
0
             ptls_tls12_phash(cipher->hash, key_block, key_block_len, ptls_iovec_init(master_secret, PTLS_TLS12_MASTER_SECRET_SIZE),
5302
0
                              "key expansion", ptls_iovec_init(hello_randoms, PTLS_HELLO_RANDOM_SIZE * 2))) != 0)
5303
0
        goto Exit;
5304
5305
    /* determine key locations */
5306
0
    struct {
5307
0
        const void *key;
5308
0
        const void *iv;
5309
0
    } client_secret, server_secret, *enc_secret = is_server ? &server_secret : &client_secret,
5310
0
                                    *dec_secret = is_server ? &client_secret : &server_secret;
5311
0
    client_secret.key = key_block;
5312
0
    server_secret.key = key_block + cipher->aead->key_size;
5313
0
    client_secret.iv = key_block + cipher->aead->key_size * 2;
5314
0
    server_secret.iv = key_block + cipher->aead->key_size * 2 + cipher->aead->tls12.fixed_iv_size;
5315
5316
    /* Serialize prams. Sequence number of the first application record is 1, because Finished is the only message sent after
5317
     * ChangeCipherSpec. */
5318
0
    ret = export_tls12_params(output, is_server, session_reused, cipher, (uint8_t *)hello_randoms + PTLS_HELLO_RANDOM_SIZE,
5319
0
                              server_name, negotiated_protocol, enc_secret->key, enc_secret->iv, 1, next_send_record_iv,
5320
0
                              dec_secret->key, dec_secret->iv, 1);
5321
5322
0
Exit:
5323
0
    ptls_clear_memory(key_block, sizeof(key_block));
5324
0
    return ret;
5325
0
}
5326
5327
int ptls_export(ptls_t *tls, ptls_buffer_t *output)
5328
0
{
5329
0
    ptls_iovec_t negotiated_protocol =
5330
0
        ptls_iovec_init(tls->negotiated_protocol, tls->negotiated_protocol != NULL ? strlen(tls->negotiated_protocol) : 0);
5331
0
    int ret;
5332
5333
0
    if (tls->state != PTLS_STATE_SERVER_POST_HANDSHAKE) {
5334
0
        ret = PTLS_ERROR_LIBRARY;
5335
0
        goto Exit;
5336
0
    }
5337
5338
0
    if (ptls_get_protocol_version(tls) == PTLS_PROTOCOL_VERSION_TLS13) {
5339
0
        export_tls_params(output, tls->is_server, tls->is_psk_handshake, PTLS_PROTOCOL_VERSION_TLS13, tls->cipher_suite,
5340
0
                          tls->client_random, tls->server_name, negotiated_protocol, {
5341
0
                              ptls_buffer_pushv(output, tls->traffic_protection.enc.secret, tls->cipher_suite->hash->digest_size);
5342
0
                              ptls_buffer_push64(output, tls->traffic_protection.enc.seq);
5343
0
                              ptls_buffer_pushv(output, tls->traffic_protection.dec.secret, tls->cipher_suite->hash->digest_size);
5344
0
                              ptls_buffer_push64(output, tls->traffic_protection.dec.seq);
5345
0
                          });
5346
0
        ret = 0;
5347
0
    } else {
5348
0
        if ((ret = export_tls12_params(output, tls->is_server, tls->is_psk_handshake, tls->cipher_suite, tls->client_random,
5349
0
                                       tls->server_name, negotiated_protocol, tls->traffic_protection.enc.secret,
5350
0
                                       tls->traffic_protection.enc.secret + PTLS_MAX_SECRET_SIZE, tls->traffic_protection.enc.seq,
5351
0
                                       tls->traffic_protection.enc.tls12_enc_record_iv, tls->traffic_protection.dec.secret,
5352
0
                                       tls->traffic_protection.dec.secret + PTLS_MAX_SECRET_SIZE,
5353
0
                                       tls->traffic_protection.dec.seq)) != 0)
5354
0
            goto Exit;
5355
0
    }
5356
5357
0
Exit:
5358
0
    return ret;
5359
0
}
5360
5361
static int import_tls12_traffic_protection(ptls_t *tls, int is_enc, const uint8_t **src, const uint8_t *const end)
5362
0
{
5363
0
    struct st_ptls_traffic_protection_t *tp = is_enc ? &tls->traffic_protection.enc : &tls->traffic_protection.dec;
5364
5365
0
    if ((size_t)(end - *src) < tls->cipher_suite->aead->key_size + tls->cipher_suite->aead->tls12.fixed_iv_size + sizeof(uint64_t))
5366
0
        return PTLS_ALERT_DECODE_ERROR;
5367
5368
    /* set properties */
5369
0
    memcpy(tp->secret, *src, tls->cipher_suite->aead->key_size);
5370
0
    *src += tls->cipher_suite->aead->key_size;
5371
0
    memcpy(tp->secret + PTLS_MAX_SECRET_SIZE, *src, tls->cipher_suite->aead->tls12.fixed_iv_size);
5372
0
    *src += tls->cipher_suite->aead->tls12.fixed_iv_size;
5373
0
    if (ptls_decode64(&tp->seq, src, end) != 0)
5374
0
        return PTLS_ALERT_DECODE_ERROR;
5375
0
    if (is_enc && tls->cipher_suite->aead->tls12.record_iv_size != 0) {
5376
0
        if (ptls_decode64(&tp->tls12_enc_record_iv, src, end) != 0)
5377
0
            return PTLS_ALERT_DECODE_ERROR;
5378
0
    }
5379
0
    tp->tls12 = 1;
5380
5381
    /* instantiate aead */
5382
0
    if ((tp->aead = ptls_aead_new_direct(tls->cipher_suite->aead, is_enc, tp->secret, tp->secret + PTLS_MAX_SECRET_SIZE)) == NULL)
5383
0
        return PTLS_ERROR_NO_MEMORY;
5384
5385
0
    return 0;
5386
0
}
5387
5388
static int import_tls13_traffic_protection(ptls_t *tls, int is_enc, const uint8_t **src, const uint8_t *const end)
5389
0
{
5390
0
    struct st_ptls_traffic_protection_t *tp = is_enc ? &tls->traffic_protection.enc : &tls->traffic_protection.dec;
5391
5392
    /* set properties */
5393
0
    memcpy(tp->secret, *src, tls->cipher_suite->hash->digest_size);
5394
0
    *src += tls->cipher_suite->hash->digest_size;
5395
0
    if (ptls_decode64(&tp->seq, src, end) != 0)
5396
0
        return PTLS_ALERT_DECODE_ERROR;
5397
5398
0
    if (setup_traffic_protection(tls, is_enc, NULL, 3, tp->seq, 0) != 0)
5399
0
        return PTLS_ERROR_INCOMPATIBLE_KEY;
5400
5401
0
    return 0;
5402
0
}
5403
5404
int ptls_import(ptls_context_t *ctx, ptls_t **tls, ptls_iovec_t params)
5405
0
{
5406
0
    const uint8_t *src = params.base, *const end = src + params.len;
5407
0
    uint16_t protocol_version, csid;
5408
0
    int ret;
5409
5410
0
    *tls = NULL;
5411
5412
    /* TODO handle flags like psk_handshake, ech_handshake as we add support for TLS/1.3 import */
5413
0
    ptls_decode_block(src, end, 2, {
5414
        /* instantiate, based on the is_server flag */
5415
0
        if (end - src < 2) {
5416
0
            ret = PTLS_ALERT_DECODE_ERROR;
5417
0
            goto Exit;
5418
0
        }
5419
0
        if ((*tls = new_instance(ctx, *src++)) == NULL) {
5420
0
            ret = PTLS_ERROR_NO_MEMORY;
5421
0
            goto Exit;
5422
0
        }
5423
0
        (*tls)->is_psk_handshake = *src++;
5424
        /* determine protocol version and cipher suite */
5425
0
        if ((ret = ptls_decode16(&protocol_version, &src, end)) != 0)
5426
0
            goto Exit;
5427
0
        if ((ret = ptls_decode16(&csid, &src, end)) != 0)
5428
0
            goto Exit;
5429
        /* other version-independent stuff */
5430
0
        if (end - src < PTLS_HELLO_RANDOM_SIZE) {
5431
0
            ret = PTLS_ALERT_DECODE_ERROR;
5432
0
            goto Exit;
5433
0
        }
5434
0
        memcpy((*tls)->client_random, src, PTLS_HELLO_RANDOM_SIZE);
5435
0
        src += PTLS_HELLO_RANDOM_SIZE;
5436
0
        ptls_decode_open_block(src, end, 2, {
5437
0
            if (src != end) {
5438
0
                if ((ret = ptls_set_server_name(*tls, (const char *)src, end - src)) != 0)
5439
0
                    goto Exit;
5440
0
                src = end;
5441
0
            }
5442
0
        });
5443
0
        ptls_decode_open_block(src, end, 2, {
5444
0
            if (src != end) {
5445
0
                if ((ret = ptls_set_negotiated_protocol(*tls, (const char *)src, end - src)) != 0)
5446
0
                    goto Exit;
5447
0
                src = end;
5448
0
            }
5449
0
        });
5450
        /* version-dependent stuff */
5451
0
        ptls_decode_open_block(src, end, 2, {
5452
0
            switch (protocol_version) {
5453
0
            case PTLS_PROTOCOL_VERSION_TLS12:
5454
0
                (*tls)->cipher_suite = ptls_find_cipher_suite(ctx->tls12_cipher_suites, csid);
5455
0
                if ((*tls)->cipher_suite == NULL) {
5456
0
                    ret = PTLS_ALERT_HANDSHAKE_FAILURE;
5457
0
                    goto Exit;
5458
0
                }
5459
                /* setup AEAD keys */
5460
0
                if ((ret = import_tls12_traffic_protection(*tls, 1, &src, end)) != 0)
5461
0
                    goto Exit;
5462
0
                if ((ret = import_tls12_traffic_protection(*tls, 0, &src, end)) != 0)
5463
0
                    goto Exit;
5464
0
                break;
5465
0
            case PTLS_PROTOCOL_VERSION_TLS13:
5466
0
                (*tls)->cipher_suite = ptls_find_cipher_suite(ctx->cipher_suites, csid);
5467
0
                if ((*tls)->cipher_suite == NULL) {
5468
0
                    ret = PTLS_ALERT_HANDSHAKE_FAILURE;
5469
0
                    goto Exit;
5470
0
                }
5471
                /* setup AEAD keys */
5472
0
                if (((*tls)->key_schedule = key_schedule_new((*tls)->cipher_suite, NULL, (*tls)->ech.aead != NULL)) == NULL) {
5473
0
                    ret = PTLS_ERROR_NO_MEMORY;
5474
0
                    goto Exit;
5475
0
                }
5476
0
                if ((ret = import_tls13_traffic_protection(*tls, 1, &src, end)) != 0)
5477
0
                    goto Exit;
5478
0
                if ((ret = import_tls13_traffic_protection(*tls, 0, &src, end)) != 0)
5479
0
                    goto Exit;
5480
0
                break;
5481
0
            default:
5482
0
                ret = PTLS_ALERT_ILLEGAL_PARAMETER;
5483
0
                goto Exit;
5484
0
            }
5485
0
        });
5486
        /* extensions */
5487
0
        ptls_decode_open_block(src, end, 2, {
5488
0
            src = end; /* unused */
5489
0
        });
5490
0
    });
5491
5492
0
    (*tls)->state = ptls_is_server(*tls) ? PTLS_STATE_SERVER_POST_HANDSHAKE : PTLS_STATE_CLIENT_POST_HANDSHAKE;
5493
5494
0
Exit:
5495
0
    if (ret != 0) {
5496
0
        if (*tls != NULL) {
5497
0
            ptls_free(*tls);
5498
0
            *tls = NULL;
5499
0
        }
5500
0
    }
5501
0
    return ret;
5502
0
}
5503
5504
void ptls_free(ptls_t *tls)
5505
0
{
5506
0
    PTLS_PROBE0(FREE, tls);
5507
0
    PTLS_LOG_CONN(free, tls, {});
5508
5509
0
    ptls_buffer_dispose(&tls->recvbuf.rec);
5510
0
    ptls_buffer_dispose(&tls->recvbuf.mess);
5511
0
    free_exporter_master_secret(tls, 1);
5512
0
    free_exporter_master_secret(tls, 0);
5513
0
    if (tls->key_schedule != NULL)
5514
0
        key_schedule_free(tls->key_schedule);
5515
0
    if (tls->traffic_protection.dec.aead != NULL)
5516
0
        ptls_aead_free(tls->traffic_protection.dec.aead);
5517
0
    if (tls->traffic_protection.enc.aead != NULL)
5518
0
        ptls_aead_free(tls->traffic_protection.enc.aead);
5519
0
    free(tls->server_name);
5520
0
    free(tls->negotiated_protocol);
5521
0
    clear_ech(&tls->ech, tls->is_server);
5522
0
    if (tls->is_server) {
5523
0
        if (tls->server.async_job != NULL)
5524
0
            tls->server.async_job->destroy_(tls->server.async_job);
5525
0
    } else {
5526
0
        if (tls->client.key_share_ctx != NULL)
5527
0
            tls->client.key_share_ctx->on_exchange(&tls->client.key_share_ctx, 1, NULL, ptls_iovec_init(NULL, 0));
5528
0
        if (tls->client.certificate_request.context.base != NULL)
5529
0
            free(tls->client.certificate_request.context.base);
5530
0
    }
5531
0
    if (tls->certificate_verify.cb != NULL)
5532
0
        tls->certificate_verify.cb(tls->certificate_verify.verify_ctx, 0, ptls_iovec_init(NULL, 0), ptls_iovec_init(NULL, 0));
5533
0
    if (tls->pending_handshake_secret != NULL) {
5534
0
        ptls_clear_memory(tls->pending_handshake_secret, PTLS_MAX_DIGEST_SIZE);
5535
0
        free(tls->pending_handshake_secret);
5536
0
    }
5537
0
    update_open_count(tls->ctx, -1);
5538
0
    ptls_clear_memory(tls, sizeof(*tls));
5539
0
    free(tls);
5540
0
}
5541
5542
ptls_context_t *ptls_get_context(ptls_t *tls)
5543
0
{
5544
0
    return tls->ctx;
5545
0
}
5546
5547
void ptls_set_context(ptls_t *tls, ptls_context_t *ctx)
5548
0
{
5549
0
    update_open_count(ctx, 1);
5550
0
    update_open_count(tls->ctx, -1);
5551
0
    tls->ctx = ctx;
5552
0
}
5553
5554
ptls_async_job_t *ptls_get_async_job(ptls_t *tls)
5555
0
{
5556
0
    return tls->server.async_job;
5557
0
}
5558
5559
ptls_iovec_t ptls_get_client_random(ptls_t *tls)
5560
0
{
5561
0
    return ptls_iovec_init(tls->client_random, PTLS_HELLO_RANDOM_SIZE);
5562
0
}
5563
5564
ptls_cipher_suite_t *ptls_get_cipher(ptls_t *tls)
5565
0
{
5566
0
    return tls->cipher_suite;
5567
0
}
5568
5569
uint16_t ptls_get_protocol_version(ptls_t *tls)
5570
0
{
5571
0
    if (tls->traffic_protection.enc.tls12)
5572
0
        return PTLS_PROTOCOL_VERSION_TLS12;
5573
5574
0
    return PTLS_PROTOCOL_VERSION_TLS13;
5575
0
}
5576
5577
int ptls_get_traffic_keys(ptls_t *tls, int is_enc, uint8_t *key, uint8_t *iv, uint64_t *seq)
5578
0
{
5579
0
    struct st_ptls_traffic_protection_t *ctx = is_enc ? &tls->traffic_protection.enc : &tls->traffic_protection.dec;
5580
0
    int ret;
5581
5582
0
    if ((ret = get_traffic_keys(tls->cipher_suite->aead, tls->cipher_suite->hash, key, iv, ctx->secret, ptls_iovec_init(NULL, 0),
5583
0
                                NULL)) != 0)
5584
0
        return ret;
5585
0
    *seq = ctx->seq;
5586
0
    return 0;
5587
0
}
5588
5589
const char *ptls_get_server_name(ptls_t *tls)
5590
0
{
5591
0
    return tls->server_name;
5592
0
}
5593
5594
int ptls_set_server_name(ptls_t *tls, const char *server_name, size_t server_name_len)
5595
0
{
5596
0
    char *duped = NULL;
5597
5598
0
    if (server_name != NULL &&
5599
0
        (duped = duplicate_as_str(server_name, server_name_len != 0 ? server_name_len : strlen(server_name))) == NULL)
5600
0
        return PTLS_ERROR_NO_MEMORY;
5601
5602
0
    free(tls->server_name);
5603
0
    tls->server_name = duped;
5604
5605
0
    return 0;
5606
0
}
5607
5608
const char *ptls_get_negotiated_protocol(ptls_t *tls)
5609
0
{
5610
0
    return tls->negotiated_protocol;
5611
0
}
5612
5613
int ptls_set_negotiated_protocol(ptls_t *tls, const char *protocol, size_t protocol_len)
5614
0
{
5615
0
    char *duped = NULL;
5616
5617
0
    if (protocol != NULL && (duped = duplicate_as_str(protocol, protocol_len != 0 ? protocol_len : strlen(protocol))) == NULL)
5618
0
        return PTLS_ERROR_NO_MEMORY;
5619
5620
0
    free(tls->negotiated_protocol);
5621
0
    tls->negotiated_protocol = duped;
5622
5623
0
    return 0;
5624
0
}
5625
5626
int ptls_handshake_is_complete(ptls_t *tls)
5627
0
{
5628
0
    return tls->state >= PTLS_STATE_POST_HANDSHAKE_MIN;
5629
0
}
5630
5631
int ptls_is_psk_handshake(ptls_t *tls)
5632
0
{
5633
0
    return tls->is_psk_handshake;
5634
0
}
5635
5636
int ptls_is_ech_handshake(ptls_t *tls, uint8_t *config_id, ptls_hpke_kem_t **kem, ptls_hpke_cipher_suite_t **cipher)
5637
0
{
5638
0
    if (tls->ech.state == PTLS_ECH_STATE_ACCEPTED) {
5639
0
        if (config_id != NULL)
5640
0
            *config_id = tls->ech.config_id;
5641
0
        if (kem != NULL)
5642
0
            *kem = tls->ech.kem;
5643
0
        if (cipher != NULL)
5644
0
            *cipher = tls->ech.cipher;
5645
0
        return 1;
5646
0
    }
5647
0
    return 0;
5648
0
}
5649
5650
void **ptls_get_data_ptr(ptls_t *tls)
5651
0
{
5652
0
    return &tls->data_ptr;
5653
0
}
5654
5655
ptls_log_conn_state_t *ptls_get_log_state(ptls_t *tls)
5656
0
{
5657
0
#if PTLS_HAVE_LOG
5658
0
    return &tls->log_state;
5659
#else
5660
    return &ptls_log.dummy_conn_state;
5661
#endif
5662
0
}
5663
5664
static int handle_client_handshake_message(ptls_t *tls, ptls_message_emitter_t *emitter, ptls_iovec_t message, int is_end_of_record,
5665
                                           ptls_handshake_properties_t *properties)
5666
0
{
5667
0
    uint8_t type = message.base[0];
5668
0
    int ret;
5669
5670
0
    switch (tls->state) {
5671
0
    case PTLS_STATE_CLIENT_EXPECT_SERVER_HELLO:
5672
0
    case PTLS_STATE_CLIENT_EXPECT_SECOND_SERVER_HELLO:
5673
0
        if (type == PTLS_HANDSHAKE_TYPE_SERVER_HELLO && is_end_of_record) {
5674
0
            ret = client_handle_hello(tls, emitter, message, properties);
5675
0
        } else {
5676
0
            ret = PTLS_ALERT_UNEXPECTED_MESSAGE;
5677
0
        }
5678
0
        break;
5679
0
    case PTLS_STATE_CLIENT_EXPECT_ENCRYPTED_EXTENSIONS:
5680
0
        if (type == PTLS_HANDSHAKE_TYPE_ENCRYPTED_EXTENSIONS) {
5681
0
            ret = client_handle_encrypted_extensions(tls, message, properties);
5682
0
        } else {
5683
0
            ret = PTLS_ALERT_UNEXPECTED_MESSAGE;
5684
0
        }
5685
0
        break;
5686
0
    case PTLS_STATE_CLIENT_EXPECT_CERTIFICATE_REQUEST_OR_CERTIFICATE:
5687
0
        if (type == PTLS_HANDSHAKE_TYPE_CERTIFICATE_REQUEST) {
5688
0
            ret = client_handle_certificate_request(tls, message, properties);
5689
0
            break;
5690
0
        }
5691
    /* fall through */
5692
0
    case PTLS_STATE_CLIENT_EXPECT_CERTIFICATE:
5693
0
        switch (type) {
5694
0
        case PTLS_HANDSHAKE_TYPE_CERTIFICATE:
5695
0
            ret = client_handle_certificate(tls, message);
5696
0
            break;
5697
0
        case PTLS_HANDSHAKE_TYPE_COMPRESSED_CERTIFICATE:
5698
0
            ret = client_handle_compressed_certificate(tls, message);
5699
0
            break;
5700
0
        default:
5701
0
            ret = PTLS_ALERT_UNEXPECTED_MESSAGE;
5702
0
            break;
5703
0
        }
5704
0
        break;
5705
0
    case PTLS_STATE_CLIENT_EXPECT_CERTIFICATE_VERIFY:
5706
0
        if (type == PTLS_HANDSHAKE_TYPE_CERTIFICATE_VERIFY) {
5707
0
            ret = client_handle_certificate_verify(tls, message);
5708
0
        } else {
5709
0
            ret = PTLS_ALERT_UNEXPECTED_MESSAGE;
5710
0
        }
5711
0
        break;
5712
0
    case PTLS_STATE_CLIENT_EXPECT_FINISHED:
5713
0
        if (type == PTLS_HANDSHAKE_TYPE_FINISHED && is_end_of_record) {
5714
0
            ret = client_handle_finished(tls, emitter, message);
5715
0
        } else {
5716
0
            ret = PTLS_ALERT_UNEXPECTED_MESSAGE;
5717
0
        }
5718
0
        break;
5719
0
    case PTLS_STATE_CLIENT_POST_HANDSHAKE:
5720
0
        switch (type) {
5721
0
        case PTLS_HANDSHAKE_TYPE_NEW_SESSION_TICKET:
5722
0
            ret = client_handle_new_session_ticket(tls, message);
5723
0
            break;
5724
0
        case PTLS_HANDSHAKE_TYPE_KEY_UPDATE:
5725
0
            ret = handle_key_update(tls, emitter, message);
5726
0
            break;
5727
0
        default:
5728
0
            ret = PTLS_ALERT_UNEXPECTED_MESSAGE;
5729
0
            break;
5730
0
        }
5731
0
        break;
5732
0
    default:
5733
0
        assert(!"unexpected state");
5734
0
        ret = PTLS_ALERT_INTERNAL_ERROR;
5735
0
        break;
5736
0
    }
5737
5738
0
    PTLS_PROBE(RECEIVE_MESSAGE, tls, message.base[0], message.base + PTLS_HANDSHAKE_HEADER_SIZE,
5739
0
               message.len - PTLS_HANDSHAKE_HEADER_SIZE, ret);
5740
0
    PTLS_LOG_CONN(receive_message, tls, {
5741
0
        PTLS_LOG_ELEMENT_UNSIGNED(message, message.base[0]);
5742
0
        PTLS_LOG_ELEMENT_UNSIGNED(len, message.len - PTLS_HANDSHAKE_HEADER_SIZE);
5743
0
        PTLS_LOG_ELEMENT_SIGNED(result, ret);
5744
0
    });
5745
5746
0
    return ret;
5747
0
}
5748
5749
static int handle_server_handshake_message(ptls_t *tls, ptls_message_emitter_t *emitter, ptls_iovec_t message, int is_end_of_record,
5750
                                           ptls_handshake_properties_t *properties)
5751
0
{
5752
0
    uint8_t type = message.base[0];
5753
0
    int ret;
5754
5755
0
    switch (tls->state) {
5756
0
    case PTLS_STATE_SERVER_EXPECT_CLIENT_HELLO:
5757
0
    case PTLS_STATE_SERVER_EXPECT_SECOND_CLIENT_HELLO:
5758
0
        if (type == PTLS_HANDSHAKE_TYPE_CLIENT_HELLO && is_end_of_record) {
5759
0
            ret = server_handle_hello(tls, emitter, message, properties);
5760
0
        } else {
5761
0
            ret = PTLS_ALERT_HANDSHAKE_FAILURE;
5762
0
        }
5763
0
        break;
5764
0
    case PTLS_STATE_SERVER_EXPECT_CERTIFICATE:
5765
0
        if (type == PTLS_HANDSHAKE_TYPE_CERTIFICATE) {
5766
0
            ret = server_handle_certificate(tls, message);
5767
0
        } else {
5768
0
            ret = PTLS_ALERT_UNEXPECTED_MESSAGE;
5769
0
        }
5770
0
        break;
5771
0
    case PTLS_STATE_SERVER_EXPECT_CERTIFICATE_VERIFY:
5772
0
        if (type == PTLS_HANDSHAKE_TYPE_CERTIFICATE_VERIFY) {
5773
0
            ret = server_handle_certificate_verify(tls, message);
5774
0
        } else {
5775
0
            ret = PTLS_ALERT_UNEXPECTED_MESSAGE;
5776
0
        }
5777
0
        break;
5778
0
    case PTLS_STATE_SERVER_EXPECT_END_OF_EARLY_DATA:
5779
0
        assert(!tls->ctx->omit_end_of_early_data);
5780
0
        if (type == PTLS_HANDSHAKE_TYPE_END_OF_EARLY_DATA) {
5781
0
            ret = server_handle_end_of_early_data(tls, message);
5782
0
        } else {
5783
0
            ret = PTLS_ALERT_UNEXPECTED_MESSAGE;
5784
0
        }
5785
0
        break;
5786
0
    case PTLS_STATE_SERVER_EXPECT_FINISHED:
5787
0
        if (type == PTLS_HANDSHAKE_TYPE_FINISHED && is_end_of_record) {
5788
0
            ret = server_handle_finished(tls, message);
5789
0
        } else {
5790
0
            ret = PTLS_ALERT_HANDSHAKE_FAILURE;
5791
0
        }
5792
0
        break;
5793
0
    case PTLS_STATE_SERVER_POST_HANDSHAKE:
5794
0
        switch (type) {
5795
0
        case PTLS_HANDSHAKE_TYPE_KEY_UPDATE:
5796
0
            ret = handle_key_update(tls, emitter, message);
5797
0
            break;
5798
0
        default:
5799
0
            ret = PTLS_ALERT_UNEXPECTED_MESSAGE;
5800
0
            break;
5801
0
        }
5802
0
        break;
5803
0
    default:
5804
0
        assert(!"unexpected state");
5805
0
        ret = PTLS_ALERT_INTERNAL_ERROR;
5806
0
        break;
5807
0
    }
5808
5809
0
    PTLS_PROBE(RECEIVE_MESSAGE, tls, message.base[0], message.base + PTLS_HANDSHAKE_HEADER_SIZE,
5810
0
               message.len - PTLS_HANDSHAKE_HEADER_SIZE, ret);
5811
0
    PTLS_LOG_CONN(receive_message, tls, {
5812
0
        PTLS_LOG_ELEMENT_UNSIGNED(message, message.base[0]);
5813
0
        PTLS_LOG_ELEMENT_UNSIGNED(len, message.len - PTLS_HANDSHAKE_HEADER_SIZE);
5814
0
        PTLS_LOG_ELEMENT_SIGNED(result, ret);
5815
0
    });
5816
5817
0
    return ret;
5818
0
}
5819
5820
static int handle_alert(ptls_t *tls, const uint8_t *src, size_t len)
5821
0
{
5822
0
    if (len != 2)
5823
0
        return PTLS_ALERT_DECODE_ERROR;
5824
5825
0
    uint8_t desc = src[1];
5826
5827
    /* all fatal alerts and USER_CANCELLED warning tears down the connection immediately, regardless of the transmitted level */
5828
0
    return PTLS_ALERT_TO_PEER_ERROR(desc);
5829
0
}
5830
5831
static int message_buffer_is_overflow(ptls_context_t *ctx, size_t size)
5832
0
{
5833
0
    if (ctx->max_buffer_size == 0)
5834
0
        return 0;
5835
0
    if (size <= ctx->max_buffer_size)
5836
0
        return 0;
5837
0
    return 1;
5838
0
}
5839
5840
static int handle_handshake_record(ptls_t *tls,
5841
                                   int (*cb)(ptls_t *tls, ptls_message_emitter_t *emitter, ptls_iovec_t message,
5842
                                             int is_end_of_record, ptls_handshake_properties_t *properties),
5843
                                   ptls_message_emitter_t *emitter, struct st_ptls_record_t *rec,
5844
                                   ptls_handshake_properties_t *properties)
5845
0
{
5846
0
    int ret;
5847
5848
    /* handshake */
5849
0
    if (rec->type != PTLS_CONTENT_TYPE_HANDSHAKE)
5850
0
        return PTLS_ALERT_DECODE_ERROR;
5851
5852
    /* flatten the unhandled messages */
5853
0
    const uint8_t *src, *src_end;
5854
0
    if (tls->recvbuf.mess.base == NULL) {
5855
0
        src = rec->fragment;
5856
0
        src_end = src + rec->length;
5857
0
    } else {
5858
0
        if (message_buffer_is_overflow(tls->ctx, tls->recvbuf.mess.off + rec->length))
5859
0
            return PTLS_ALERT_HANDSHAKE_FAILURE;
5860
0
        if ((ret = ptls_buffer_reserve(&tls->recvbuf.mess, rec->length)) != 0)
5861
0
            return ret;
5862
0
        memcpy(tls->recvbuf.mess.base + tls->recvbuf.mess.off, rec->fragment, rec->length);
5863
0
        tls->recvbuf.mess.off += rec->length;
5864
0
        src = tls->recvbuf.mess.base;
5865
0
        src_end = src + tls->recvbuf.mess.off;
5866
0
    }
5867
5868
    /* handle the messages */
5869
0
    ret = PTLS_ERROR_IN_PROGRESS;
5870
0
    while (src_end - src >= 4) {
5871
0
        size_t mess_len = 4 + ntoh24(src + 1);
5872
0
        if (src_end - src < (int)mess_len)
5873
0
            break;
5874
0
        ret = cb(tls, emitter, ptls_iovec_init(src, mess_len), src_end - src == mess_len, properties);
5875
0
        switch (ret) {
5876
0
        case 0:
5877
0
        case PTLS_ERROR_ASYNC_OPERATION:
5878
0
        case PTLS_ERROR_IN_PROGRESS:
5879
0
            break;
5880
0
        default:
5881
0
            ptls_buffer_dispose(&tls->recvbuf.mess);
5882
0
            return ret;
5883
0
        }
5884
0
        src += mess_len;
5885
0
    }
5886
5887
    /* keep last partial message in buffer */
5888
0
    if (src != src_end) {
5889
0
        size_t new_size = src_end - src;
5890
0
        if (message_buffer_is_overflow(tls->ctx, new_size))
5891
0
            return PTLS_ALERT_HANDSHAKE_FAILURE;
5892
0
        if (tls->recvbuf.mess.base == NULL) {
5893
0
            ptls_buffer_init(&tls->recvbuf.mess, "", 0);
5894
0
            if ((ret = ptls_buffer_reserve(&tls->recvbuf.mess, new_size)) != 0)
5895
0
                return ret;
5896
0
            memcpy(tls->recvbuf.mess.base, src, new_size);
5897
0
        } else {
5898
0
            memmove(tls->recvbuf.mess.base, src, new_size);
5899
0
        }
5900
0
        tls->recvbuf.mess.off = new_size;
5901
0
        ret = PTLS_ERROR_IN_PROGRESS;
5902
0
    } else {
5903
0
        ptls_buffer_dispose(&tls->recvbuf.mess);
5904
0
    }
5905
5906
0
    return ret;
5907
0
}
5908
5909
static int handle_input(ptls_t *tls, ptls_message_emitter_t *emitter, ptls_buffer_t *decryptbuf, const void *input, size_t *inlen,
5910
                        ptls_handshake_properties_t *properties)
5911
0
{
5912
0
    struct st_ptls_record_t rec;
5913
0
    int ret;
5914
5915
    /* extract the record */
5916
0
    if ((ret = parse_record(tls, &rec, input, inlen)) != 0)
5917
0
        return ret;
5918
0
    assert(rec.fragment != NULL);
5919
5920
    /* decrypt the record */
5921
0
    if (rec.type == PTLS_CONTENT_TYPE_CHANGE_CIPHER_SPEC) {
5922
0
        if (tls->state < PTLS_STATE_POST_HANDSHAKE_MIN) {
5923
0
            if (!(rec.length == 1 && rec.fragment[0] == 0x01))
5924
0
                return PTLS_ALERT_UNEXPECTED_MESSAGE;
5925
0
        } else {
5926
0
            return PTLS_ALERT_UNEXPECTED_MESSAGE;
5927
0
        }
5928
0
        ret = PTLS_ERROR_IN_PROGRESS;
5929
0
        goto NextRecord;
5930
0
    }
5931
0
    if (tls->traffic_protection.dec.aead != NULL && rec.type != PTLS_CONTENT_TYPE_ALERT) {
5932
0
        size_t decrypted_length;
5933
0
        if (rec.type != PTLS_CONTENT_TYPE_APPDATA)
5934
0
            return PTLS_ALERT_HANDSHAKE_FAILURE;
5935
0
        if ((ret = ptls_buffer_reserve(decryptbuf, 5 + rec.length)) != 0)
5936
0
            return ret;
5937
0
        if ((ret = aead_decrypt(&tls->traffic_protection.dec, decryptbuf->base + decryptbuf->off, &decrypted_length, rec.fragment,
5938
0
                                rec.length)) != 0) {
5939
0
            if (tls->is_server && tls->server.early_data_skipped_bytes != UINT32_MAX)
5940
0
                goto ServerSkipEarlyData;
5941
0
            return ret;
5942
0
        }
5943
0
        rec.length = decrypted_length;
5944
0
        rec.fragment = decryptbuf->base + decryptbuf->off;
5945
        /* skip padding */
5946
0
        for (; rec.length != 0; --rec.length)
5947
0
            if (rec.fragment[rec.length - 1] != 0)
5948
0
                break;
5949
0
        if (rec.length == 0)
5950
0
            return PTLS_ALERT_UNEXPECTED_MESSAGE;
5951
0
        rec.type = rec.fragment[--rec.length];
5952
0
    } else if (rec.type == PTLS_CONTENT_TYPE_APPDATA && tls->is_server && tls->server.early_data_skipped_bytes != UINT32_MAX) {
5953
0
        goto ServerSkipEarlyData;
5954
0
    }
5955
5956
0
    if (tls->recvbuf.mess.base != NULL || rec.type == PTLS_CONTENT_TYPE_HANDSHAKE) {
5957
        /* handshake record */
5958
0
        ret = handle_handshake_record(tls, tls->is_server ? handle_server_handshake_message : handle_client_handshake_message,
5959
0
                                      emitter, &rec, properties);
5960
0
    } else {
5961
        /* handling of an alert or an application record */
5962
0
        switch (rec.type) {
5963
0
        case PTLS_CONTENT_TYPE_APPDATA:
5964
0
            if (tls->state >= PTLS_STATE_POST_HANDSHAKE_MIN) {
5965
0
                decryptbuf->off += rec.length;
5966
0
                ret = 0;
5967
0
            } else if (tls->state == PTLS_STATE_SERVER_EXPECT_END_OF_EARLY_DATA) {
5968
0
                if (tls->traffic_protection.dec.aead != NULL)
5969
0
                    decryptbuf->off += rec.length;
5970
0
                ret = 0;
5971
0
            } else {
5972
0
                ret = PTLS_ALERT_UNEXPECTED_MESSAGE;
5973
0
            }
5974
0
            break;
5975
0
        case PTLS_CONTENT_TYPE_ALERT:
5976
0
            ret = handle_alert(tls, rec.fragment, rec.length);
5977
0
            break;
5978
0
        default:
5979
0
            ret = PTLS_ALERT_UNEXPECTED_MESSAGE;
5980
0
            break;
5981
0
        }
5982
0
    }
5983
5984
0
NextRecord:
5985
0
    ptls_buffer_dispose(&tls->recvbuf.rec);
5986
0
    return ret;
5987
5988
0
ServerSkipEarlyData:
5989
0
    tls->server.early_data_skipped_bytes += (uint32_t)rec.length;
5990
0
    if (tls->server.early_data_skipped_bytes > PTLS_MAX_EARLY_DATA_SKIP_SIZE)
5991
0
        return PTLS_ALERT_HANDSHAKE_FAILURE;
5992
0
    ret = PTLS_ERROR_IN_PROGRESS;
5993
0
    goto NextRecord;
5994
0
}
5995
5996
static int handle_input_tls12(ptls_t *tls, ptls_buffer_t *decryptbuf, const void *input, size_t *inlen)
5997
0
{
5998
0
    struct st_ptls_record_t rec;
5999
0
    int ret;
6000
6001
    /* extract the record, or bail out */
6002
0
    if ((ret = parse_record(tls, &rec, input, inlen)) != 0)
6003
0
        return ret;
6004
0
    assert(rec.fragment != NULL);
6005
6006
0
    const uint8_t *src = rec.fragment, *end = src + rec.length;
6007
0
    uint64_t nonce;
6008
0
    uint8_t aad[PTLS_TLS12_AAD_SIZE];
6009
6010
    /* determine the nonce */
6011
0
    if (tls->traffic_protection.dec.aead->algo->tls12.record_iv_size != 0) {
6012
0
        assert(tls->traffic_protection.dec.aead->algo->tls12.record_iv_size == 8);
6013
0
        if ((ret = ptls_decode64(&nonce, &src, end)) != 0)
6014
0
            goto Exit;
6015
0
    } else {
6016
0
        nonce = tls->traffic_protection.dec.seq;
6017
0
    }
6018
6019
    /* determine cleartext length */
6020
0
    size_t textlen = end - src;
6021
0
    if (textlen < tls->traffic_protection.dec.aead->algo->tag_size) {
6022
0
        ret = PTLS_ALERT_BAD_RECORD_MAC;
6023
0
        goto Exit;
6024
0
    }
6025
0
    textlen -= tls->traffic_protection.dec.aead->algo->tag_size;
6026
6027
    /* build aad */
6028
0
    build_tls12_aad(aad, rec.type, tls->traffic_protection.dec.seq, (uint16_t)textlen);
6029
6030
    /* decrypt input to decryptbuf */
6031
0
    if ((ret = ptls_buffer_reserve(decryptbuf, textlen)) != 0)
6032
0
        goto Exit;
6033
0
    if (ptls_aead_decrypt(tls->traffic_protection.dec.aead, decryptbuf->base + decryptbuf->off, src, end - src, nonce, aad,
6034
0
                          sizeof(aad)) != textlen) {
6035
0
        ret = PTLS_ALERT_BAD_RECORD_MAC;
6036
0
        goto Exit;
6037
0
    }
6038
0
    ++tls->traffic_protection.dec.seq;
6039
6040
    /* record-type specific action */
6041
0
    switch (rec.type) {
6042
0
    case PTLS_CONTENT_TYPE_APPDATA:
6043
        /* if application data, retain the bytes being decrypted */
6044
0
        decryptbuf->off += textlen;
6045
0
        break;
6046
0
    case PTLS_CONTENT_TYPE_ALERT:
6047
        /* submit alert without adjusting decryptbuf, so that the decrypted data would be dropped after handling the alert */
6048
0
        ret = handle_alert(tls, decryptbuf->base + decryptbuf->off, textlen);
6049
0
        break;
6050
0
    default:
6051
0
        ret = PTLS_ALERT_UNEXPECTED_MESSAGE;
6052
0
        break;
6053
0
    }
6054
6055
0
Exit:
6056
0
    ptls_buffer_dispose(&tls->recvbuf.rec);
6057
0
    ptls_clear_memory(aad, sizeof(aad));
6058
0
    return ret;
6059
0
}
6060
6061
static void init_record_message_emitter(ptls_t *tls, struct st_ptls_record_message_emitter_t *emitter, ptls_buffer_t *sendbuf)
6062
0
{
6063
0
    *emitter = (struct st_ptls_record_message_emitter_t){
6064
0
        {sendbuf, &tls->traffic_protection.enc, 5, begin_record_message, commit_record_message}};
6065
0
}
6066
6067
int ptls_handshake(ptls_t *tls, ptls_buffer_t *_sendbuf, const void *input, size_t *inlen, ptls_handshake_properties_t *properties)
6068
0
{
6069
0
    struct st_ptls_record_message_emitter_t emitter;
6070
0
    int ret;
6071
6072
0
    assert(tls->state < PTLS_STATE_POST_HANDSHAKE_MIN);
6073
6074
0
    init_record_message_emitter(tls, &emitter, _sendbuf);
6075
0
    size_t sendbuf_orig_off = emitter.super.buf->off;
6076
6077
    /* special handlings */
6078
0
    switch (tls->state) {
6079
0
    case PTLS_STATE_CLIENT_HANDSHAKE_START: {
6080
0
        assert(input == NULL || *inlen == 0);
6081
0
        return send_client_hello(tls, &emitter.super, properties, NULL);
6082
0
    }
6083
0
    case PTLS_STATE_SERVER_GENERATING_CERTIFICATE_VERIFY:
6084
0
        return server_finish_handshake(tls, &emitter.super, 1, NULL);
6085
0
    default:
6086
0
        break;
6087
0
    }
6088
6089
0
    const uint8_t *src = input, *const src_end = src + *inlen;
6090
0
    ptls_buffer_t decryptbuf;
6091
6092
0
    ptls_buffer_init(&decryptbuf, "", 0);
6093
6094
    /* perform handhake until completion or until all the input has been swallowed */
6095
0
    ret = PTLS_ERROR_IN_PROGRESS;
6096
0
    while (ret == PTLS_ERROR_IN_PROGRESS && src != src_end) {
6097
0
        size_t consumed = src_end - src;
6098
0
        ret = handle_input(tls, &emitter.super, &decryptbuf, src, &consumed, properties);
6099
0
        src += consumed;
6100
0
        assert(decryptbuf.off == 0);
6101
0
    }
6102
6103
0
    ptls_buffer_dispose(&decryptbuf);
6104
6105
0
    switch (ret) {
6106
0
    case 0:
6107
0
    case PTLS_ERROR_IN_PROGRESS:
6108
0
    case PTLS_ERROR_STATELESS_RETRY:
6109
0
    case PTLS_ERROR_ASYNC_OPERATION:
6110
0
        break;
6111
0
    default:
6112
        /* Flush handshake messages that have been written partially. ECH_REQUIRED sticks out because it is a message sent
6113
         * post-handshake compared to other alerts that are generating *during* the handshake. */
6114
0
        if (ret != PTLS_ALERT_ECH_REQUIRED) {
6115
0
            ptls_clear_memory(emitter.super.buf->base + sendbuf_orig_off, emitter.super.buf->off - sendbuf_orig_off);
6116
0
            emitter.super.buf->off = sendbuf_orig_off;
6117
0
        }
6118
        /* send alert immediately */
6119
0
        if (PTLS_ERROR_GET_CLASS(ret) != PTLS_ERROR_CLASS_PEER_ALERT)
6120
0
            if (ptls_send_alert(tls, emitter.super.buf, PTLS_ALERT_LEVEL_FATAL,
6121
0
                                PTLS_ERROR_GET_CLASS(ret) == PTLS_ERROR_CLASS_SELF_ALERT ? ret : PTLS_ALERT_INTERNAL_ERROR) != 0)
6122
0
                emitter.super.buf->off = sendbuf_orig_off;
6123
0
        break;
6124
0
    }
6125
6126
0
    *inlen -= src_end - src;
6127
0
    return ret;
6128
0
}
6129
6130
int ptls_receive(ptls_t *tls, ptls_buffer_t *decryptbuf, const void *_input, size_t *inlen)
6131
0
{
6132
0
    const uint8_t *input = (const uint8_t *)_input, *const end = input + *inlen;
6133
0
    size_t decryptbuf_orig_size = decryptbuf->off;
6134
0
    int ret = 0;
6135
6136
0
    assert(tls->state >= PTLS_STATE_SERVER_EXPECT_END_OF_EARLY_DATA);
6137
6138
    /* loop until we decrypt some application data (or an error) */
6139
0
    while (ret == 0 && input != end && decryptbuf_orig_size == decryptbuf->off) {
6140
0
        size_t consumed = end - input;
6141
0
        if (tls->traffic_protection.dec.tls12) {
6142
0
            ret = handle_input_tls12(tls, decryptbuf, input, &consumed);
6143
0
        } else {
6144
0
            ret = handle_input(tls, NULL, decryptbuf, input, &consumed, NULL);
6145
0
        }
6146
0
        input += consumed;
6147
6148
0
        switch (ret) {
6149
0
        case 0:
6150
0
            break;
6151
0
        case PTLS_ERROR_IN_PROGRESS:
6152
0
            ret = 0;
6153
0
            break;
6154
0
        case PTLS_ERROR_CLASS_PEER_ALERT + PTLS_ALERT_CLOSE_NOTIFY:
6155
            /* TODO send close alert */
6156
0
            break;
6157
0
        default:
6158
0
            if (PTLS_ERROR_GET_CLASS(ret) == PTLS_ERROR_CLASS_SELF_ALERT) {
6159
                /* TODO send alert */
6160
0
            }
6161
0
            break;
6162
0
        }
6163
0
    }
6164
6165
0
    *inlen -= end - input;
6166
6167
0
    return ret;
6168
0
}
6169
6170
static int update_send_key(ptls_t *tls, ptls_buffer_t *_sendbuf, int request_update)
6171
0
{
6172
0
    struct st_ptls_record_message_emitter_t emitter;
6173
0
    int ret;
6174
6175
0
    init_record_message_emitter(tls, &emitter, _sendbuf);
6176
0
    size_t sendbuf_orig_off = emitter.super.buf->off;
6177
6178
0
    ptls_push_message(&emitter.super, NULL, PTLS_HANDSHAKE_TYPE_KEY_UPDATE,
6179
0
                      { ptls_buffer_push(emitter.super.buf, !!request_update); });
6180
0
    if ((ret = update_traffic_key(tls, 1)) != 0)
6181
0
        goto Exit;
6182
0
    ret = 0;
6183
6184
0
Exit:
6185
0
    if (ret != 0)
6186
0
        emitter.super.buf->off = sendbuf_orig_off;
6187
0
    return ret;
6188
0
}
6189
6190
int ptls_send(ptls_t *tls, ptls_buffer_t *sendbuf, const void *input, size_t inlen)
6191
0
{
6192
0
    assert(tls->traffic_protection.enc.aead != NULL);
6193
6194
    /* "For AES-GCM, up to 2^24.5 full-size records (about 24 million) may be encrypted on a given connection while keeping a
6195
     * safety margin of approximately 2^-57 for Authenticated Encryption (AE) security." (RFC 8446 section 5.5).
6196
     *
6197
     * Key updates do not happen with tls 1.2, check `key_schedule` to see if we are using tls/1.3
6198
     */
6199
0
    if (tls->traffic_protection.enc.seq >= 16777216 && tls->key_schedule != NULL)
6200
0
        tls->needs_key_update = 1;
6201
6202
0
    if (tls->needs_key_update) {
6203
0
        int ret;
6204
0
        if ((ret = update_send_key(tls, sendbuf, tls->key_update_send_request)) != 0)
6205
0
            return ret;
6206
0
        tls->needs_key_update = 0;
6207
0
        tls->key_update_send_request = 0;
6208
0
    }
6209
6210
0
    return buffer_push_encrypted_records(sendbuf, PTLS_CONTENT_TYPE_APPDATA, input, inlen, &tls->traffic_protection.enc);
6211
0
}
6212
6213
int ptls_update_key(ptls_t *tls, int request_update)
6214
0
{
6215
0
    assert(tls->ctx->update_traffic_key == NULL);
6216
0
    tls->needs_key_update = 1;
6217
0
    tls->key_update_send_request = request_update;
6218
0
    return 0;
6219
0
}
6220
6221
size_t ptls_get_record_overhead(ptls_t *tls)
6222
0
{
6223
0
    ptls_aead_algorithm_t *algo = tls->traffic_protection.enc.aead->algo;
6224
6225
0
    if (tls->traffic_protection.enc.tls12) {
6226
0
        return 5 + algo->tls12.record_iv_size + algo->tag_size;
6227
0
    } else {
6228
0
        return 6 + algo->tag_size;
6229
0
    }
6230
0
}
6231
6232
int ptls_send_alert(ptls_t *tls, ptls_buffer_t *sendbuf, uint8_t level, uint8_t description)
6233
0
{
6234
0
    size_t rec_start = sendbuf->off;
6235
0
    int ret = 0;
6236
6237
0
    buffer_push_record(sendbuf, PTLS_CONTENT_TYPE_ALERT, { ptls_buffer_push(sendbuf, level, description); });
6238
    /* encrypt the alert if we have the encryption keys, unless when it is the early data key */
6239
0
    if (tls->traffic_protection.enc.aead != NULL && !(tls->state <= PTLS_STATE_CLIENT_EXPECT_FINISHED)) {
6240
0
        if ((ret = buffer_encrypt_record(sendbuf, rec_start, &tls->traffic_protection.enc)) != 0)
6241
0
            goto Exit;
6242
0
    }
6243
6244
0
Exit:
6245
0
    return ret;
6246
0
}
6247
6248
int ptls_export_secret(ptls_t *tls, void *output, size_t outlen, const char *label, ptls_iovec_t context_value, int is_early)
6249
0
{
6250
0
    ptls_hash_algorithm_t *algo = tls->key_schedule->hashes[0].algo;
6251
0
    uint8_t *master_secret = is_early ? tls->exporter_master_secret.early : tls->exporter_master_secret.one_rtt,
6252
0
            derived_secret[PTLS_MAX_DIGEST_SIZE], context_value_hash[PTLS_MAX_DIGEST_SIZE];
6253
0
    int ret;
6254
6255
0
    if (master_secret == NULL) {
6256
0
        if (is_early) {
6257
0
            switch (tls->state) {
6258
0
            case PTLS_STATE_CLIENT_HANDSHAKE_START:
6259
0
            case PTLS_STATE_SERVER_EXPECT_CLIENT_HELLO:
6260
0
                ret = PTLS_ERROR_IN_PROGRESS;
6261
0
                break;
6262
0
            default:
6263
0
                ret = PTLS_ERROR_NOT_AVAILABLE;
6264
0
                break;
6265
0
            }
6266
0
        } else {
6267
0
            ret = PTLS_ERROR_IN_PROGRESS;
6268
0
        }
6269
0
        return ret;
6270
0
    }
6271
6272
0
    if ((ret = ptls_calc_hash(algo, context_value_hash, context_value.base, context_value.len)) != 0)
6273
0
        return ret;
6274
6275
0
    if ((ret = ptls_hkdf_expand_label(algo, derived_secret, algo->digest_size, ptls_iovec_init(master_secret, algo->digest_size),
6276
0
                                      label, ptls_iovec_init(algo->empty_digest, algo->digest_size), NULL)) != 0)
6277
0
        goto Exit;
6278
0
    ret = ptls_hkdf_expand_label(algo, output, outlen, ptls_iovec_init(derived_secret, algo->digest_size), "exporter",
6279
0
                                 ptls_iovec_init(context_value_hash, algo->digest_size), NULL);
6280
6281
0
Exit:
6282
0
    ptls_clear_memory(derived_secret, sizeof(derived_secret));
6283
0
    ptls_clear_memory(context_value_hash, sizeof(context_value_hash));
6284
0
    return ret;
6285
0
}
6286
6287
struct st_picotls_hmac_context_t {
6288
    ptls_hash_context_t super;
6289
    ptls_hash_algorithm_t *algo;
6290
    ptls_hash_context_t *hash;
6291
    uint8_t key[1];
6292
};
6293
6294
static void hmac_update(ptls_hash_context_t *_ctx, const void *src, size_t len)
6295
0
{
6296
0
    struct st_picotls_hmac_context_t *ctx = (struct st_picotls_hmac_context_t *)_ctx;
6297
0
    ctx->hash->update(ctx->hash, src, len);
6298
0
}
6299
6300
static void hmac_apply_key(struct st_picotls_hmac_context_t *ctx, uint8_t pad)
6301
0
{
6302
0
    size_t i;
6303
6304
0
    for (i = 0; i != ctx->algo->block_size; ++i)
6305
0
        ctx->key[i] ^= pad;
6306
0
    ctx->hash->update(ctx->hash, ctx->key, ctx->algo->block_size);
6307
0
    for (i = 0; i != ctx->algo->block_size; ++i)
6308
0
        ctx->key[i] ^= pad;
6309
0
}
6310
6311
static void hmac_final(ptls_hash_context_t *_ctx, void *md, ptls_hash_final_mode_t mode)
6312
0
{
6313
0
    struct st_picotls_hmac_context_t *ctx = (struct st_picotls_hmac_context_t *)_ctx;
6314
6315
0
    assert(mode != PTLS_HASH_FINAL_MODE_SNAPSHOT || !"not supported");
6316
6317
0
    if (md != NULL) {
6318
0
        ctx->hash->final(ctx->hash, md, PTLS_HASH_FINAL_MODE_RESET);
6319
0
        hmac_apply_key(ctx, 0x5c);
6320
0
        ctx->hash->update(ctx->hash, md, ctx->algo->digest_size);
6321
0
    }
6322
0
    ctx->hash->final(ctx->hash, md, mode);
6323
6324
0
    switch (mode) {
6325
0
    case PTLS_HASH_FINAL_MODE_FREE:
6326
0
        ptls_clear_memory(ctx->key, ctx->algo->block_size);
6327
0
        free(ctx);
6328
0
        break;
6329
0
    case PTLS_HASH_FINAL_MODE_RESET:
6330
0
        hmac_apply_key(ctx, 0x36);
6331
0
        break;
6332
0
    default:
6333
0
        assert(!"FIXME");
6334
0
        break;
6335
0
    }
6336
0
}
6337
6338
int ptls_calc_hash(ptls_hash_algorithm_t *algo, void *output, const void *src, size_t len)
6339
0
{
6340
0
    ptls_hash_context_t *ctx;
6341
6342
0
    if ((ctx = algo->create()) == NULL)
6343
0
        return PTLS_ERROR_NO_MEMORY;
6344
0
    ctx->update(ctx, src, len);
6345
0
    ctx->final(ctx, output, PTLS_HASH_FINAL_MODE_FREE);
6346
0
    return 0;
6347
0
}
6348
6349
ptls_hash_context_t *ptls_hmac_create(ptls_hash_algorithm_t *algo, const void *key, size_t key_size)
6350
0
{
6351
0
    struct st_picotls_hmac_context_t *ctx;
6352
6353
0
    assert(key_size <= algo->block_size);
6354
6355
0
    if ((ctx = malloc(offsetof(struct st_picotls_hmac_context_t, key) + algo->block_size)) == NULL)
6356
0
        return NULL;
6357
6358
0
    *ctx = (struct st_picotls_hmac_context_t){{hmac_update, hmac_final}, algo};
6359
0
    if ((ctx->hash = algo->create()) == NULL) {
6360
0
        free(ctx);
6361
0
        return NULL;
6362
0
    }
6363
0
    memset(ctx->key, 0, algo->block_size);
6364
0
    memcpy(ctx->key, key, key_size);
6365
6366
0
    hmac_apply_key(ctx, 0x36);
6367
6368
0
    return &ctx->super;
6369
0
}
6370
6371
int ptls_hkdf_extract(ptls_hash_algorithm_t *algo, void *output, ptls_iovec_t salt, ptls_iovec_t ikm)
6372
0
{
6373
0
    ptls_hash_context_t *hash;
6374
6375
0
    if (salt.len == 0)
6376
0
        salt = ptls_iovec_init(zeroes_of_max_digest_size, algo->digest_size);
6377
6378
0
    if ((hash = ptls_hmac_create(algo, salt.base, salt.len)) == NULL)
6379
0
        return PTLS_ERROR_NO_MEMORY;
6380
0
    hash->update(hash, ikm.base, ikm.len);
6381
0
    hash->final(hash, output, PTLS_HASH_FINAL_MODE_FREE);
6382
0
    return 0;
6383
0
}
6384
6385
int ptls_hkdf_expand(ptls_hash_algorithm_t *algo, void *output, size_t outlen, ptls_iovec_t prk, ptls_iovec_t info)
6386
0
{
6387
0
    ptls_hash_context_t *hmac = NULL;
6388
0
    size_t i;
6389
0
    uint8_t digest[PTLS_MAX_DIGEST_SIZE];
6390
6391
0
    for (i = 0; (i * algo->digest_size) < outlen; ++i) {
6392
0
        if (hmac == NULL) {
6393
0
            if ((hmac = ptls_hmac_create(algo, prk.base, prk.len)) == NULL)
6394
0
                return PTLS_ERROR_NO_MEMORY;
6395
0
        } else {
6396
0
            hmac->update(hmac, digest, algo->digest_size);
6397
0
        }
6398
0
        hmac->update(hmac, info.base, info.len);
6399
0
        uint8_t gen = (uint8_t)(i + 1);
6400
0
        hmac->update(hmac, &gen, 1);
6401
0
        hmac->final(hmac, digest, 1);
6402
6403
0
        size_t off_start = i * algo->digest_size, off_end = off_start + algo->digest_size;
6404
0
        if (off_end > outlen)
6405
0
            off_end = outlen;
6406
0
        memcpy((uint8_t *)output + off_start, digest, off_end - off_start);
6407
0
    }
6408
6409
0
    if (hmac != NULL)
6410
0
        hmac->final(hmac, NULL, PTLS_HASH_FINAL_MODE_FREE);
6411
6412
0
    ptls_clear_memory(digest, algo->digest_size);
6413
6414
0
    return 0;
6415
0
}
6416
6417
int ptls_hkdf_expand_label(ptls_hash_algorithm_t *algo, void *output, size_t outlen, ptls_iovec_t secret, const char *label,
6418
                           ptls_iovec_t hash_value, const char *label_prefix)
6419
0
{
6420
0
    ptls_buffer_t hkdf_label;
6421
0
    uint8_t hkdf_label_buf[80];
6422
0
    int ret;
6423
6424
0
    ptls_buffer_init(&hkdf_label, hkdf_label_buf, sizeof(hkdf_label_buf));
6425
6426
0
    ptls_buffer_push16(&hkdf_label, (uint16_t)outlen);
6427
0
    ptls_buffer_push_block(&hkdf_label, 1, {
6428
0
        if (label_prefix == NULL)
6429
0
            label_prefix = PTLS_HKDF_EXPAND_LABEL_PREFIX;
6430
0
        ptls_buffer_pushv(&hkdf_label, label_prefix, strlen(label_prefix));
6431
0
        ptls_buffer_pushv(&hkdf_label, label, strlen(label));
6432
0
    });
6433
0
    ptls_buffer_push_block(&hkdf_label, 1, { ptls_buffer_pushv(&hkdf_label, hash_value.base, hash_value.len); });
6434
6435
0
    ret = ptls_hkdf_expand(algo, output, outlen, secret, ptls_iovec_init(hkdf_label.base, hkdf_label.off));
6436
6437
0
Exit:
6438
0
    ptls_buffer_dispose(&hkdf_label);
6439
0
    return ret;
6440
0
}
6441
6442
int ptls_tls12_phash(ptls_hash_algorithm_t *algo, void *output, size_t outlen, ptls_iovec_t secret, const char *label,
6443
                     ptls_iovec_t seed)
6444
0
{
6445
0
    ptls_hash_context_t *hmac;
6446
0
    uint8_t An[PTLS_MAX_DIGEST_SIZE];
6447
0
    size_t output_off = 0;
6448
6449
0
    if ((hmac = ptls_hmac_create(algo, secret.base, secret.len)) == NULL)
6450
0
        return PTLS_ERROR_NO_MEMORY;
6451
6452
    /* A(1) = HMAC_hash(secret, label + seed) */
6453
0
    if (label != NULL)
6454
0
        hmac->update(hmac, label, strlen(label));
6455
0
    hmac->update(hmac, seed.base, seed.len);
6456
0
    hmac->final(hmac, An, PTLS_HASH_FINAL_MODE_RESET);
6457
6458
0
    while (1) {
6459
        /* output += HMAC_hash(secret, A(i) + label + seed) */
6460
0
        hmac->update(hmac, An, algo->digest_size);
6461
0
        if (label != NULL)
6462
0
            hmac->update(hmac, label, strlen(label));
6463
0
        hmac->update(hmac, seed.base, seed.len);
6464
0
        if (outlen - output_off <= algo->digest_size) {
6465
            /* digest of last chunk is at first written to An then the necessary bytes are copied to output */
6466
0
            hmac->final(hmac, An, PTLS_HASH_FINAL_MODE_FREE);
6467
0
            memcpy((uint8_t *)output + output_off, An, outlen - output_off);
6468
0
            break;
6469
0
        }
6470
0
        hmac->final(hmac, (uint8_t *)output + output_off, PTLS_HASH_FINAL_MODE_RESET);
6471
0
        output_off += algo->digest_size;
6472
6473
        /* A(i) = HMAC_hash(secret, A(i-1)) */
6474
0
        hmac->update(hmac, An, algo->digest_size);
6475
0
        hmac->final(hmac, An, PTLS_HASH_FINAL_MODE_RESET);
6476
0
    }
6477
6478
0
    ptls_clear_memory(An, algo->digest_size);
6479
6480
0
    return 0;
6481
0
}
6482
6483
ptls_cipher_context_t *ptls_cipher_new(ptls_cipher_algorithm_t *algo, int is_enc, const void *key)
6484
0
{
6485
0
    ptls_cipher_context_t *ctx;
6486
6487
0
    if ((ctx = (ptls_cipher_context_t *)malloc(algo->context_size)) == NULL)
6488
0
        return NULL;
6489
0
    *ctx = (ptls_cipher_context_t){algo};
6490
0
    if (algo->setup_crypto(ctx, is_enc, key) != 0) {
6491
0
        free(ctx);
6492
0
        ctx = NULL;
6493
0
    }
6494
0
    return ctx;
6495
0
}
6496
6497
void ptls_cipher_free(ptls_cipher_context_t *ctx)
6498
0
{
6499
0
    ctx->do_dispose(ctx);
6500
0
    free(ctx);
6501
0
}
6502
6503
ptls_aead_context_t *new_aead(ptls_aead_algorithm_t *aead, ptls_hash_algorithm_t *hash, int is_enc, const void *secret,
6504
                              ptls_iovec_t hash_value, const char *label_prefix)
6505
0
{
6506
0
    ptls_aead_context_t *ctx = NULL;
6507
0
    struct {
6508
0
        uint8_t key[PTLS_MAX_SECRET_SIZE];
6509
0
        uint8_t iv[PTLS_MAX_IV_SIZE];
6510
0
    } key_iv;
6511
0
    int ret;
6512
6513
0
    if ((ret = get_traffic_keys(aead, hash, key_iv.key, key_iv.iv, secret, hash_value, label_prefix)) != 0)
6514
0
        goto Exit;
6515
0
    ctx = ptls_aead_new_direct(aead, is_enc, key_iv.key, key_iv.iv);
6516
0
Exit:
6517
0
    ptls_clear_memory(&key_iv, sizeof(key_iv));
6518
0
    return ctx;
6519
0
}
6520
6521
ptls_aead_context_t *ptls_aead_new(ptls_aead_algorithm_t *aead, ptls_hash_algorithm_t *hash, int is_enc, const void *secret,
6522
                                   const char *label_prefix)
6523
0
{
6524
0
    return new_aead(aead, hash, is_enc, secret, ptls_iovec_init(NULL, 0), label_prefix);
6525
0
}
6526
6527
ptls_aead_context_t *ptls_aead_new_direct(ptls_aead_algorithm_t *aead, int is_enc, const void *key, const void *iv)
6528
0
{
6529
0
    ptls_aead_context_t *ctx;
6530
6531
0
    if ((ctx = (ptls_aead_context_t *)malloc(aead->context_size)) == NULL)
6532
0
        return NULL;
6533
6534
0
    *ctx = (ptls_aead_context_t){aead};
6535
6536
0
    if (aead->setup_crypto(ctx, is_enc, key, iv) != 0) {
6537
0
        free(ctx);
6538
0
        return NULL;
6539
0
    }
6540
6541
0
    return ctx;
6542
0
}
6543
6544
void ptls_aead_free(ptls_aead_context_t *ctx)
6545
0
{
6546
0
    ctx->dispose_crypto(ctx);
6547
0
    free(ctx);
6548
0
}
6549
6550
void ptls_aead_xor_iv(ptls_aead_context_t *ctx, const void *_bytes, size_t len)
6551
0
{
6552
0
    const uint8_t *bytes = _bytes;
6553
0
    uint8_t iv[PTLS_MAX_IV_SIZE];
6554
6555
0
    ptls_aead_get_iv(ctx, iv);
6556
0
    for (size_t i = 0; i < len; ++i)
6557
0
        iv[i] ^= bytes[i];
6558
0
    ptls_aead_set_iv(ctx, iv);
6559
0
}
6560
6561
void ptls_aead__build_iv(ptls_aead_algorithm_t *algo, uint8_t *iv, const uint8_t *static_iv, uint64_t seq)
6562
0
{
6563
0
    size_t iv_size = algo->iv_size, i;
6564
0
    const uint8_t *s = static_iv;
6565
0
    uint8_t *d = iv;
6566
6567
    /* build iv */
6568
0
    for (i = iv_size - 8; i != 0; --i)
6569
0
        *d++ = *s++;
6570
0
    i = 64;
6571
0
    do {
6572
0
        i -= 8;
6573
0
        *d++ = *s++ ^ (uint8_t)(seq >> i);
6574
0
    } while (i != 0);
6575
0
}
6576
6577
static void clear_memory(void *p, size_t len)
6578
0
{
6579
0
    if (len != 0)
6580
0
        memset(p, 0, len);
6581
0
}
6582
6583
void (*volatile ptls_clear_memory)(void *p, size_t len) = clear_memory;
6584
6585
static int mem_equal(const void *_x, const void *_y, size_t len)
6586
0
{
6587
0
    const volatile uint8_t *x = _x, *y = _y;
6588
0
    uint8_t t = 0;
6589
6590
0
    for (; len != 0; --len)
6591
0
        t |= *x++ ^ *y++;
6592
6593
0
    return t == 0;
6594
0
}
6595
6596
int (*volatile ptls_mem_equal)(const void *x, const void *y, size_t len) = mem_equal;
6597
6598
static uint64_t get_time(ptls_get_time_t *self)
6599
0
{
6600
0
    struct timeval tv;
6601
0
    gettimeofday(&tv, NULL);
6602
0
    return (uint64_t)tv.tv_sec * 1000 + tv.tv_usec / 1000;
6603
0
}
6604
6605
ptls_get_time_t ptls_get_time = {get_time};
6606
6607
int ptls_is_server(ptls_t *tls)
6608
0
{
6609
0
    return tls->is_server;
6610
0
}
6611
6612
struct st_ptls_raw_message_emitter_t {
6613
    ptls_message_emitter_t super;
6614
    size_t start_off;
6615
    size_t *epoch_offsets;
6616
};
6617
6618
static int begin_raw_message(ptls_message_emitter_t *_self)
6619
0
{
6620
0
    struct st_ptls_raw_message_emitter_t *self = (void *)_self;
6621
6622
0
    self->start_off = self->super.buf->off;
6623
0
    return 0;
6624
0
}
6625
6626
static int commit_raw_message(ptls_message_emitter_t *_self)
6627
0
{
6628
0
    struct st_ptls_raw_message_emitter_t *self = (void *)_self;
6629
0
    size_t epoch;
6630
6631
    /* epoch is the key epoch, with the only exception being 2nd CH generated after 0-RTT key */
6632
0
    epoch = self->super.enc->epoch;
6633
0
    if (epoch == 1 && self->super.buf->base[self->start_off] == PTLS_HANDSHAKE_TYPE_CLIENT_HELLO)
6634
0
        epoch = 0;
6635
6636
0
    for (++epoch; epoch < 5; ++epoch) {
6637
0
        assert(self->epoch_offsets[epoch] == self->start_off);
6638
0
        self->epoch_offsets[epoch] = self->super.buf->off;
6639
0
    }
6640
6641
0
    self->start_off = SIZE_MAX;
6642
6643
0
    return 0;
6644
0
}
6645
6646
size_t ptls_get_read_epoch(ptls_t *tls)
6647
0
{
6648
0
    switch (tls->state) {
6649
0
    case PTLS_STATE_CLIENT_HANDSHAKE_START:
6650
0
    case PTLS_STATE_CLIENT_EXPECT_SERVER_HELLO:
6651
0
    case PTLS_STATE_CLIENT_EXPECT_SECOND_SERVER_HELLO:
6652
0
    case PTLS_STATE_SERVER_EXPECT_CLIENT_HELLO:
6653
0
    case PTLS_STATE_SERVER_EXPECT_SECOND_CLIENT_HELLO:
6654
0
        return 0; /* plaintext */
6655
0
    case PTLS_STATE_SERVER_EXPECT_END_OF_EARLY_DATA:
6656
0
        assert(!tls->ctx->omit_end_of_early_data);
6657
0
        return 1; /* 0-rtt */
6658
0
    case PTLS_STATE_CLIENT_EXPECT_ENCRYPTED_EXTENSIONS:
6659
0
    case PTLS_STATE_CLIENT_EXPECT_CERTIFICATE_REQUEST_OR_CERTIFICATE:
6660
0
    case PTLS_STATE_CLIENT_EXPECT_CERTIFICATE:
6661
0
    case PTLS_STATE_CLIENT_EXPECT_CERTIFICATE_VERIFY:
6662
0
    case PTLS_STATE_CLIENT_EXPECT_FINISHED:
6663
0
    case PTLS_STATE_SERVER_GENERATING_CERTIFICATE_VERIFY:
6664
0
    case PTLS_STATE_SERVER_EXPECT_CERTIFICATE:
6665
0
    case PTLS_STATE_SERVER_EXPECT_CERTIFICATE_VERIFY:
6666
0
    case PTLS_STATE_SERVER_EXPECT_FINISHED:
6667
0
        return 2; /* handshake */
6668
0
    case PTLS_STATE_CLIENT_POST_HANDSHAKE:
6669
0
    case PTLS_STATE_SERVER_POST_HANDSHAKE:
6670
0
        return 3; /* 1-rtt */
6671
0
    default:
6672
0
        assert(!"invalid state");
6673
0
        return SIZE_MAX;
6674
0
    }
6675
0
}
6676
6677
int ptls_handle_message(ptls_t *tls, ptls_buffer_t *sendbuf, size_t epoch_offsets[5], size_t in_epoch, const void *input,
6678
                        size_t inlen, ptls_handshake_properties_t *properties)
6679
0
{
6680
0
    return tls->is_server ? ptls_server_handle_message(tls, sendbuf, epoch_offsets, in_epoch, input, inlen, properties)
6681
0
                          : ptls_client_handle_message(tls, sendbuf, epoch_offsets, in_epoch, input, inlen, properties);
6682
0
}
6683
6684
int ptls_client_handle_message(ptls_t *tls, ptls_buffer_t *sendbuf, size_t epoch_offsets[5], size_t in_epoch, const void *input,
6685
                               size_t inlen, ptls_handshake_properties_t *properties)
6686
0
{
6687
0
    assert(!tls->is_server);
6688
6689
0
    struct st_ptls_raw_message_emitter_t emitter = {
6690
0
        {sendbuf, &tls->traffic_protection.enc, 0, begin_raw_message, commit_raw_message}, SIZE_MAX, epoch_offsets};
6691
0
    struct st_ptls_record_t rec = {PTLS_CONTENT_TYPE_HANDSHAKE, 0, inlen, input};
6692
6693
0
    if (input == NULL)
6694
0
        return send_client_hello(tls, &emitter.super, properties, NULL);
6695
6696
0
    if (ptls_get_read_epoch(tls) != in_epoch)
6697
0
        return PTLS_ALERT_UNEXPECTED_MESSAGE;
6698
6699
0
    return handle_handshake_record(tls, handle_client_handshake_message, &emitter.super, &rec, properties);
6700
0
}
6701
6702
int ptls_server_handle_message(ptls_t *tls, ptls_buffer_t *sendbuf, size_t epoch_offsets[5], size_t in_epoch, const void *input,
6703
                               size_t inlen, ptls_handshake_properties_t *properties)
6704
0
{
6705
0
    assert(tls->is_server);
6706
6707
0
    struct st_ptls_raw_message_emitter_t emitter = {
6708
0
        {sendbuf, &tls->traffic_protection.enc, 0, begin_raw_message, commit_raw_message}, SIZE_MAX, epoch_offsets};
6709
0
    struct st_ptls_record_t rec = {PTLS_CONTENT_TYPE_HANDSHAKE, 0, inlen, input};
6710
6711
0
    if (tls->state == PTLS_STATE_SERVER_GENERATING_CERTIFICATE_VERIFY) {
6712
0
        assert(input == NULL || inlen == 0);
6713
0
        return server_finish_handshake(tls, &emitter.super, 1, NULL);
6714
0
    }
6715
6716
0
    assert(input != NULL);
6717
6718
0
    if (ptls_get_read_epoch(tls) != in_epoch)
6719
0
        return PTLS_ALERT_UNEXPECTED_MESSAGE;
6720
6721
0
    return handle_handshake_record(tls, handle_server_handshake_message, &emitter.super, &rec, properties);
6722
0
}
6723
6724
/**
6725
 * checks if given name looks like an IP address
6726
 */
6727
int ptls_server_name_is_ipaddr(const char *name)
6728
0
{
6729
0
#ifdef AF_INET
6730
0
    struct sockaddr_in sin;
6731
0
    if (inet_pton(AF_INET, name, &sin) == 1)
6732
0
        return 1;
6733
0
#endif
6734
0
#ifdef AF_INET6
6735
0
    struct sockaddr_in6 sin6;
6736
0
    if (inet_pton(AF_INET6, name, &sin6) == 1)
6737
0
        return 1;
6738
0
#endif
6739
0
    return 0;
6740
0
}
6741
6742
int ptls_ech_encode_config(ptls_buffer_t *buf, uint8_t config_id, ptls_hpke_kem_t *kem, ptls_iovec_t public_key,
6743
                           ptls_hpke_cipher_suite_t **ciphers, uint8_t max_name_length, const char *public_name)
6744
0
{
6745
0
    int ret;
6746
6747
0
    ptls_buffer_push16(buf, PTLS_ECH_CONFIG_VERSION);
6748
0
    ptls_buffer_push_block(buf, 2, {
6749
0
        ptls_buffer_push(buf, config_id);
6750
0
        ptls_buffer_push16(buf, kem->id);
6751
0
        ptls_buffer_push_block(buf, 2, { ptls_buffer_pushv(buf, public_key.base, public_key.len); });
6752
0
        ptls_buffer_push_block(buf, 2, {
6753
0
            for (size_t i = 0; ciphers[i] != NULL; ++i) {
6754
0
                ptls_buffer_push16(buf, ciphers[i]->id.kdf);
6755
0
                ptls_buffer_push16(buf, ciphers[i]->id.aead);
6756
0
            }
6757
0
        });
6758
0
        ptls_buffer_push(buf, max_name_length);
6759
0
        ptls_buffer_push_block(buf, 1, { ptls_buffer_pushv(buf, public_name, strlen(public_name)); });
6760
0
        ptls_buffer_push_block(buf, 2, {/* extensions */});
6761
0
    });
6762
6763
0
Exit:
6764
0
    return ret;
6765
0
}
6766
6767
static char *byte_to_hex(char *dst, uint8_t v)
6768
0
{
6769
0
    *dst++ = "0123456789abcdef"[v >> 4];
6770
0
    *dst++ = "0123456789abcdef"[v & 0xf];
6771
0
    return dst;
6772
0
}
6773
6774
char *ptls_hexdump(char *dst, const void *_src, size_t len)
6775
0
{
6776
0
    char *buf = dst;
6777
0
    const uint8_t *src = _src;
6778
6779
0
    for (size_t i = 0; i != len; ++i)
6780
0
        dst = byte_to_hex(dst, src[i]);
6781
0
    *dst = '\0';
6782
0
    return buf;
6783
0
}
6784
6785
char *ptls_jsonescape(char *buf, const char *unsafe_str, size_t len)
6786
0
{
6787
0
    char *dst = buf;
6788
0
    const uint8_t *src = (const uint8_t *)unsafe_str, *end = src + len;
6789
6790
0
    for (; src != end; ++src) {
6791
0
        switch (*src) {
6792
0
#define MAP(ch, escaped)                                                                                                           \
6793
0
    case ch:                                                                                                                       \
6794
0
        memcpy(dst, (escaped), sizeof(escaped) - 1);                                                                               \
6795
0
        dst += sizeof(escaped) - 1;                                                                                                \
6796
0
        break
6797
0
            MAP('"', "\\\"");
6798
0
            MAP('\\', "\\\\");
6799
0
            MAP('/', "\\/");
6800
0
            MAP('\b', "\\b");
6801
0
            MAP('\f', "\\f");
6802
0
            MAP('\n', "\\n");
6803
0
            MAP('\r', "\\r");
6804
0
            MAP('\t', "\\t");
6805
0
#undef MAP
6806
0
        default:
6807
0
            if (*src < 0x20 || *src == 0x7f) {
6808
0
                *dst++ = '\\';
6809
0
                *dst++ = 'u';
6810
0
                *dst++ = '0';
6811
0
                *dst++ = '0';
6812
0
                dst = byte_to_hex(dst, *src);
6813
0
            } else {
6814
0
                *dst++ = *src;
6815
0
            }
6816
0
            break;
6817
0
        }
6818
0
    }
6819
0
    *dst = '\0';
6820
6821
0
    return dst;
6822
0
}
6823
6824
void ptls_build_v4_mapped_v6_address(void *v6, const void *v4)
6825
6.28k
{
6826
6.28k
    memset(v6, 0, 10);
6827
6.28k
    memset((uint8_t *)v6 + 10, 0xff, 2);
6828
6.28k
    memcpy((uint8_t *)v6 + 12, v4, 4);
6829
6.28k
}
6830
6831
struct st_ptls_log_t ptls_log = {
6832
    .dummy_conn_state = {.random_ = 1 /* never log */},
6833
    ._generation = 1, /* starts from 1 so that recalc can be forced by setting to zero (i.e., the initial) */
6834
};
6835
PTLS_THREADLOCAL ptls_log_conn_state_t *ptls_log_conn_state_override = NULL;
6836
6837
#if PTLS_HAVE_LOG
6838
6839
static struct {
6840
    /**
6841
     * list of connections; the slot is connected if points != NULL
6842
     */
6843
    struct {
6844
        /**
6845
         * file descriptor
6846
         */
6847
        int fd;
6848
        /**
6849
         * see `ptls_log_add_fd`
6850
         */
6851
        char *points;
6852
        /**
6853
         *
6854
         */
6855
        char *snis;
6856
        /**
6857
         * list of addresses terminated by ip6addr_any
6858
         */
6859
        struct in6_addr *addresses;
6860
        /**
6861
         *
6862
         */
6863
        float sample_ratio;
6864
        /**
6865
         *
6866
         */
6867
        unsigned appdata : 1;
6868
    } conns[sizeof(((struct st_ptls_log_state_t *)NULL)->active_conns) * 8];
6869
    /**
6870
     * counts the number of writes that failed
6871
     */
6872
    size_t num_lost;
6873
    /**
6874
     * anchor of the single-linked list of log points; the tail refers to itself (i.e., point->next == point)
6875
     */
6876
    struct st_ptls_log_point_t *points;
6877
    /**
6878
     *
6879
     */
6880
    pthread_mutex_t mutex;
6881
} logctx = {.mutex = PTHREAD_MUTEX_INITIALIZER};
6882
6883
static PTLS_THREADLOCAL struct {
6884
    ptls_buffer_t buf; /* buf.base == NULL upon failre */
6885
    char smallbuf[128];
6886
    struct {
6887
        char buf[sizeof(",\"tid\":-9223372036854775808")];
6888
        size_t len;
6889
    } tid;
6890
} logbuf;
6891
6892
static void close_log_fd(size_t slot)
6893
0
{
6894
0
    assert(logctx.conns[slot].fd >= 0 && logctx.conns[slot].points != NULL);
6895
6896
0
    close(logctx.conns[slot].fd);
6897
6898
    /* clear the connection information */
6899
0
    logctx.conns[slot].fd = -1;
6900
0
    logctx.conns[slot].sample_ratio = 0;
6901
0
    free(logctx.conns[slot].points);
6902
0
    logctx.conns[slot].points = NULL;
6903
0
    free(logctx.conns[slot].snis);
6904
0
    logctx.conns[slot].snis = NULL;
6905
0
    free(logctx.conns[slot].addresses);
6906
0
    logctx.conns[slot].addresses = NULL;
6907
0
    logctx.conns[slot].appdata = 0;
6908
0
    ++ptls_log._generation;
6909
0
}
6910
6911
static char *duplicate_stringlist(const char *input)
6912
0
{
6913
0
    if (input == NULL)
6914
0
        return strdup("");
6915
6916
0
    char *result;
6917
0
    const char *in_tail;
6918
6919
0
    for (in_tail = input; in_tail[0] != '\0'; in_tail += strlen(in_tail) + 1)
6920
0
        ;
6921
0
    ++in_tail;
6922
0
    if ((result = malloc(in_tail - input)) == NULL)
6923
0
        return NULL;
6924
0
    memcpy(result, input, in_tail - input);
6925
0
    return result;
6926
0
}
6927
6928
static int is_in_stringlist(const char *list, const char *search_for)
6929
0
{
6930
0
    if (list[0] == '\0')
6931
0
        return 1;
6932
6933
0
    if (search_for == NULL)
6934
0
        return 0;
6935
6936
0
    for (const char *element = list; element[0] != '\0'; element += strlen(element) + 1)
6937
0
        if (strcmp(element, search_for) == 0)
6938
0
            return 1;
6939
0
    return 0;
6940
0
}
6941
6942
static int is_in_addresslist(const struct in6_addr *list, const struct in6_addr *search_for)
6943
0
{
6944
0
#define IS_EQUAL(x, y) (memcmp((x), (y), sizeof(struct in6_addr)) == 0)
6945
6946
0
    if (IS_EQUAL(&list[0], &in6addr_any))
6947
0
        return 1;
6948
6949
0
    if (IS_EQUAL(search_for, &in6addr_any))
6950
0
        return 0;
6951
6952
0
    for (const struct in6_addr *element = list; !IS_EQUAL(element, &in6addr_any); ++element)
6953
0
        if (IS_EQUAL(element, search_for))
6954
0
            return 1;
6955
0
    return 0;
6956
6957
0
#undef IS_EQUAL
6958
0
}
6959
6960
void ptls_log__recalc_point(int caller_locked, struct st_ptls_log_point_t *point)
6961
20
{
6962
20
    if (!caller_locked)
6963
20
        pthread_mutex_lock(&logctx.mutex);
6964
6965
20
    if (point->state.generation != ptls_log._generation) {
6966
        /* update active bitmap */
6967
20
        uint32_t new_active = 0;
6968
660
        for (size_t slot = 0; slot < PTLS_ELEMENTSOF(logctx.conns); ++slot)
6969
640
            if (logctx.conns[slot].points != NULL && is_in_stringlist(logctx.conns[slot].points, point->name))
6970
0
                new_active |= (uint32_t)1 << slot;
6971
20
        point->state.active_conns = new_active;
6972
20
        point->state.generation = ptls_log._generation;
6973
20
    }
6974
6975
20
    if (!caller_locked)
6976
20
        pthread_mutex_unlock(&logctx.mutex);
6977
20
}
6978
6979
void ptls_log__recalc_conn(int caller_locked, struct st_ptls_log_conn_state_t *conn, ptls_log_getsni_t getsni)
6980
0
{
6981
0
    if (!caller_locked)
6982
0
        pthread_mutex_lock(&logctx.mutex);
6983
6984
0
    if (conn->state.generation != ptls_log._generation) {
6985
        /* update active bitmap */
6986
0
        uint32_t new_active = 0;
6987
0
        const char *sni = getsni.cb != NULL ? getsni.cb(getsni.arg) : NULL;
6988
0
        for (size_t slot = 0; slot < PTLS_ELEMENTSOF(logctx.conns); ++slot) {
6989
0
            if (logctx.conns[slot].points != NULL && conn->random_ < logctx.conns[slot].sample_ratio &&
6990
0
                is_in_stringlist(logctx.conns[slot].snis, sni) &&
6991
0
                is_in_addresslist(logctx.conns[slot].addresses, (struct in6_addr *)&conn->address)) {
6992
0
                new_active |= (uint32_t)1 << slot;
6993
0
            }
6994
0
        }
6995
0
        conn->state.active_conns = new_active;
6996
0
        conn->state.generation = ptls_log._generation;
6997
0
    }
6998
6999
0
    if (!caller_locked)
7000
0
        pthread_mutex_unlock(&logctx.mutex);
7001
0
}
7002
7003
static int expand_logbuf_or_invalidate(const char *prefix, size_t prefix_len, size_t capacity)
7004
0
{
7005
0
    if (logbuf.buf.base == NULL)
7006
0
        return 0;
7007
7008
0
    if (ptls_buffer_reserve(&logbuf.buf, prefix_len + capacity) != 0) {
7009
0
        ptls_buffer_dispose(&logbuf.buf);
7010
0
        assert(logbuf.buf.base == NULL);
7011
0
        return 0;
7012
0
    }
7013
7014
0
    memcpy(logbuf.buf.base + logbuf.buf.off, prefix, prefix_len);
7015
0
    logbuf.buf.off += prefix_len;
7016
7017
0
    return 1;
7018
0
}
7019
7020
__attribute__((format(printf, 4, 5))) static void pushf_logbuf_or_invalidate(const char *prefix, size_t prefix_len, size_t capacity,
7021
                                                                             const char *fmt, ...)
7022
0
{
7023
0
    if (!expand_logbuf_or_invalidate(prefix, prefix_len, capacity))
7024
0
        return;
7025
7026
0
    va_list args;
7027
0
    va_start(args, fmt);
7028
0
    int l = vsnprintf((char *)logbuf.buf.base + logbuf.buf.off, logbuf.buf.capacity - logbuf.buf.off, fmt, args);
7029
0
    va_end(args);
7030
7031
0
    assert(l < logbuf.buf.capacity - logbuf.buf.off && "insufficent capacity");
7032
0
    logbuf.buf.off += l;
7033
0
}
7034
7035
void ptls_log__do_push_element_safestr(const char *prefix, size_t prefix_len, const char *s, size_t l)
7036
0
{
7037
0
    if (expand_logbuf_or_invalidate(prefix, prefix_len, l + 2)) {
7038
0
        logbuf.buf.base[logbuf.buf.off++] = '"';
7039
0
        memcpy(logbuf.buf.base + logbuf.buf.off, s, l);
7040
0
        logbuf.buf.off += l;
7041
0
        logbuf.buf.base[logbuf.buf.off++] = '"';
7042
0
    }
7043
0
}
7044
7045
void ptls_log__do_push_element_unsafestr(const char *prefix, size_t prefix_len, const char *s, size_t l)
7046
0
{
7047
0
    if (expand_logbuf_or_invalidate(prefix, prefix_len, l * (sizeof("\\uXXXX") - 1) + 2)) {
7048
0
        logbuf.buf.base[logbuf.buf.off++] = '"';
7049
0
        logbuf.buf.off = (uint8_t *)ptls_jsonescape((char *)logbuf.buf.base + logbuf.buf.off, s, l) - logbuf.buf.base;
7050
0
        logbuf.buf.base[logbuf.buf.off++] = '"';
7051
0
    }
7052
0
}
7053
7054
void ptls_log__do_push_element_hexdump(const char *prefix, size_t prefix_len, const void *s, size_t l)
7055
0
{
7056
0
    if (expand_logbuf_or_invalidate(prefix, prefix_len, l * 2 + 2)) {
7057
0
        logbuf.buf.base[logbuf.buf.off++] = '"';
7058
0
        ptls_hexdump((char *)logbuf.buf.base + logbuf.buf.off, s, l);
7059
0
        logbuf.buf.off += l * 2;
7060
0
        logbuf.buf.base[logbuf.buf.off++] = '"';
7061
0
    }
7062
0
}
7063
7064
void ptls_log__do_push_element_signed32(const char *prefix, size_t prefix_len, int32_t v)
7065
0
{
7066
0
    pushf_logbuf_or_invalidate(prefix, prefix_len, sizeof("-2147483648"), "%" PRId32, v);
7067
0
}
7068
7069
void ptls_log__do_push_element_signed64(const char *prefix, size_t prefix_len, int64_t v)
7070
0
{
7071
0
    pushf_logbuf_or_invalidate(prefix, prefix_len, sizeof("-9223372036854775808"), "%" PRId64, v);
7072
0
}
7073
7074
void ptls_log__do_push_element_unsigned32(const char *prefix, size_t prefix_len, uint32_t v)
7075
0
{
7076
0
    pushf_logbuf_or_invalidate(prefix, prefix_len, sizeof("4294967295"), "%" PRIu32, v);
7077
0
}
7078
7079
void ptls_log__do_push_element_unsigned64(const char *prefix, size_t prefix_len, uint64_t v)
7080
0
{
7081
0
    pushf_logbuf_or_invalidate(prefix, prefix_len, sizeof("18446744073709551615"), "%" PRIu64, v);
7082
0
}
7083
7084
void ptls_log__do_push_element_bool(const char *prefix, size_t prefix_len, int v)
7085
0
{
7086
0
    if (expand_logbuf_or_invalidate(prefix, prefix_len, 5)) {
7087
0
        if (v) {
7088
0
            memcpy(logbuf.buf.base + logbuf.buf.off, "true", 4);
7089
0
            logbuf.buf.off += 4;
7090
0
        } else {
7091
0
            memcpy(logbuf.buf.base + logbuf.buf.off, "false", 5);
7092
0
            logbuf.buf.off += 5;
7093
0
        }
7094
0
    }
7095
0
}
7096
7097
void ptls_log__do_write_start(struct st_ptls_log_point_t *point, int add_time)
7098
0
{
7099
0
    assert(logbuf.buf.base == NULL);
7100
0
    ptls_buffer_init(&logbuf.buf, logbuf.smallbuf, sizeof(logbuf.smallbuf));
7101
7102
    /* add module and type name */
7103
0
    const char *colon_at = strchr(point->name, ':');
7104
0
    int written = snprintf((char *)logbuf.buf.base, logbuf.buf.capacity, "{\"module\":\"%.*s\",\"type\":\"%s\"",
7105
0
                           (int)(colon_at - point->name), point->name, colon_at + 1);
7106
7107
    /* obtain and stringify thread id once */
7108
0
    if (logbuf.tid.len == 0) {
7109
0
#if defined(__linux__)
7110
0
        logbuf.tid.len = sprintf(logbuf.tid.buf, ",\"tid\":%" PRId64, (int64_t)syscall(SYS_gettid));
7111
#elif defined(__APPLE__)
7112
        uint64_t t = 0;
7113
#if MAC_OS_X_VERSION_MAX_ALLOWED < 1060 || defined(__POWERPC__)
7114
        t = pthread_mach_thread_np(pthread_self());
7115
#else
7116
        (void)pthread_threadid_np(NULL, &t);
7117
#endif
7118
        logbuf.tid.len = sprintf(logbuf.tid.buf, ",\"tid\":%" PRIu64, t);
7119
#else
7120
        /* other platforms: skip emitting tid, by keeping logbuf.tid.len == 0 */
7121
#endif
7122
0
    }
7123
    /* append tid */
7124
0
    assert(written > 0 && written + logbuf.tid.len < logbuf.buf.capacity);
7125
0
    memcpy((char *)logbuf.buf.base + written, logbuf.tid.buf, logbuf.tid.len + 1);
7126
0
    written += logbuf.tid.len;
7127
7128
    /* append time if requested */
7129
0
    if (add_time) {
7130
0
        struct timeval tv;
7131
0
        gettimeofday(&tv, NULL);
7132
0
        written += snprintf((char *)logbuf.buf.base + written, logbuf.buf.capacity - written, ",\"time\":%" PRIu64,
7133
0
                            (uint64_t)tv.tv_sec * 1000 + tv.tv_usec / 1000);
7134
0
    }
7135
0
    assert(written > 0 && written < logbuf.buf.capacity && "caller MUST provide smallbuf suffient to emit the prefix");
7136
7137
0
    logbuf.buf.off = (size_t)written;
7138
0
}
7139
7140
int ptls_log__do_write_end(struct st_ptls_log_point_t *point, struct st_ptls_log_conn_state_t *conn, ptls_log_getsni_t getsni,
7141
                           int includes_appdata)
7142
0
{
7143
0
    if (!expand_logbuf_or_invalidate("}\n", 2, 0))
7144
0
        return 0;
7145
7146
0
    int needs_appdata = 0;
7147
7148
0
    pthread_mutex_lock(&logctx.mutex);
7149
7150
    /* calc the active conn bits, updating stale information if necessary */
7151
0
    if (point->state.generation != ptls_log._generation)
7152
0
        ptls_log__recalc_point(1, point);
7153
0
    uint32_t active = point->state.active_conns;
7154
0
    if (conn != NULL && conn->state.generation != ptls_log._generation) {
7155
0
        ptls_log__recalc_conn(1, conn, getsni);
7156
0
        active &= conn->state.active_conns;
7157
0
    }
7158
7159
    /* iterate through the active connctions */
7160
0
    for (size_t slot = 0; active != 0; ++slot, active >>= 1) {
7161
0
        if ((active & 1) == 0)
7162
0
            continue;
7163
7164
0
        assert(logctx.conns[slot].points != NULL);
7165
7166
0
        if (logctx.conns[slot].appdata != includes_appdata) {
7167
0
            if (!includes_appdata && ptls_log.may_include_appdata)
7168
0
                needs_appdata = 1;
7169
0
            continue;
7170
0
        }
7171
7172
        /* write */
7173
0
        ssize_t wret;
7174
0
        while ((wret = write(logctx.conns[slot].fd, logbuf.buf.base, logbuf.buf.off)) == -1 && errno == EINTR)
7175
0
            ;
7176
0
        if (wret == logbuf.buf.off) {
7177
            /* success */
7178
0
        } else if (wret > 0 || (wret == -1 && (errno == EAGAIN || errno == EWOULDBLOCK))) {
7179
            /* partial write or buffer full */
7180
0
            ++logctx.num_lost;
7181
0
        } else {
7182
            /* write error; close and unregister the connection */
7183
0
            close_log_fd(slot);
7184
0
        }
7185
0
    }
7186
7187
0
    pthread_mutex_unlock(&logctx.mutex);
7188
7189
0
    if (includes_appdata)
7190
0
        assert(!needs_appdata);
7191
7192
0
    ptls_buffer_dispose(&logbuf.buf);
7193
0
    assert(logbuf.buf.base == NULL);
7194
0
    return needs_appdata;
7195
0
}
7196
7197
#endif
7198
7199
void ptls_log_init_conn_state(ptls_log_conn_state_t *state, void (*random_bytes)(void *, size_t), uint64_t conn_id, void *_peeraddr)
7200
6.28k
{
7201
6.28k
    struct sockaddr *peeraddr = _peeraddr;
7202
6.28k
    uint32_t r;
7203
6.28k
    random_bytes(&r, sizeof(r));
7204
7205
6.28k
    *state = (ptls_log_conn_state_t){
7206
6.28k
        .random_ = (float)r / ((uint64_t)UINT32_MAX + 1), /* [0..1), so that any(r) < sample_ratio where sample_ratio is [0..1] */
7207
6.28k
        .address = {0}, /* inaddr6_any */
7208
6.28k
        .conn_id = conn_id,
7209
6.28k
    };
7210
6.28k
    if (peeraddr != NULL) {
7211
6.28k
        switch (peeraddr->sa_family) {
7212
6.28k
        case AF_INET: /* store as v6-mapped v4 address */
7213
6.28k
            ptls_build_v4_mapped_v6_address(state->address, &((struct sockaddr_in *)peeraddr)->sin_addr);
7214
6.28k
            break;
7215
0
        case AF_INET6:
7216
0
            memcpy(state->address, ((struct sockaddr_in6 *)peeraddr)->sin6_addr.s6_addr, sizeof(state->address));
7217
0
            break;
7218
0
        default:
7219
0
            break;
7220
6.28k
        }
7221
6.28k
    }
7222
6.28k
}
7223
7224
size_t ptls_log_num_lost(void)
7225
0
{
7226
0
#if PTLS_HAVE_LOG
7227
0
    return logctx.num_lost;
7228
#else
7229
    return 0;
7230
#endif
7231
0
}
7232
7233
int ptls_log_add_fd(int fd, float sample_ratio, const char *_points, const char *_snis, const char *_addresses, int appdata)
7234
0
{
7235
0
#if PTLS_HAVE_LOG
7236
7237
0
    char *points = NULL, *snis = NULL;
7238
0
    struct in6_addr *addresses = NULL;
7239
0
    int ret;
7240
7241
0
    pthread_mutex_lock(&logctx.mutex);
7242
7243
0
    if ((points = duplicate_stringlist(_points)) == NULL) {
7244
0
        ret = PTLS_ERROR_NO_MEMORY;
7245
0
        goto Exit;
7246
0
    }
7247
0
    if ((snis = duplicate_stringlist(_snis)) == NULL) {
7248
0
        ret = PTLS_ERROR_NO_MEMORY;
7249
0
        goto Exit;
7250
0
    }
7251
0
    {
7252
0
        size_t num_addresses = 0;
7253
0
        for (const char *input = _addresses; input != NULL && *input != '\0'; input += strlen(input) + 1)
7254
0
            ++num_addresses;
7255
0
        if ((addresses = malloc(sizeof(*addresses) * (num_addresses + 1))) == NULL) {
7256
0
            ret = PTLS_ERROR_NO_MEMORY;
7257
0
            goto Exit;
7258
0
        }
7259
0
        size_t index = 0;
7260
0
        for (const char *input = _addresses; input != NULL && *input != '\0'; input += strlen(input) + 1) {
7261
            /* note: for consistency to the handling of points, erroneous input is ignored. V4 addresses will use the mapped form
7262
             * (::ffff:192.0.2.1) */
7263
0
            if (!inet_pton(AF_INET6, input, &addresses[index])) {
7264
0
                struct in_addr v4;
7265
0
                if (!inet_pton(AF_INET, input, &v4))
7266
0
                    continue;
7267
0
                ptls_build_v4_mapped_v6_address(&addresses[index], &v4);
7268
0
            }
7269
0
            if (memcmp(&addresses[index], &in6addr_any, sizeof(struct in6_addr)) == 0)
7270
0
                continue;
7271
0
            ++index;
7272
0
        }
7273
0
        addresses[index] = in6addr_any;
7274
0
    }
7275
7276
    /* find slot, or return if not available */
7277
0
    size_t slot_index;
7278
0
    for (slot_index = 0; slot_index < PTLS_ELEMENTSOF(logctx.conns); ++slot_index)
7279
0
        if (logctx.conns[slot_index].points == NULL)
7280
0
            break;
7281
0
    if (slot_index == PTLS_ELEMENTSOF(logctx.conns)) {
7282
0
        ret = PTLS_ERROR_NO_MEMORY;
7283
0
        goto Exit;
7284
0
    }
7285
7286
    /* setup the slot */
7287
0
    logctx.conns[slot_index].fd = fd;
7288
0
    logctx.conns[slot_index].points = points;
7289
0
    logctx.conns[slot_index].snis = snis;
7290
0
    logctx.conns[slot_index].addresses = addresses;
7291
0
    logctx.conns[slot_index].sample_ratio = sample_ratio;
7292
0
    logctx.conns[slot_index].appdata = appdata;
7293
0
    ++ptls_log._generation;
7294
7295
0
    ret = 0; /* success */
7296
7297
0
Exit:
7298
0
    pthread_mutex_unlock(&logctx.mutex);
7299
0
    if (ret != 0) {
7300
0
        free(points);
7301
0
        free(snis);
7302
0
        free(addresses);
7303
0
    }
7304
0
    return ret;
7305
7306
#else
7307
    return PTLS_ERROR_NOT_AVAILABLE;
7308
#endif
7309
0
}