1/* Copyright (c) 2017 - 2022 LiteSpeed Technologies Inc.  See LICENSE. */
2/*
3 * lsquic_enc_sess_ietf.c -- Crypto session for IETF QUIC
4 */
5
6#include <assert.h>
7#include <errno.h>
8#include <stddef.h>
9#include <stdlib.h>
10#include <string.h>
11#include <sys/queue.h>
12#if LSQUIC_PREFERRED_ADDR
13#include <arpa/inet.h>
14#endif
15
16#include <openssl/chacha.h>
17#include <openssl/hkdf.h>
18#include <openssl/rand.h>
19#include <openssl/ssl.h>
20
21#include "fiu-local.h"
22
23#include "lsquic_types.h"
24#include "lsquic_hkdf.h"
25#include "lsquic.h"
26#include "lsquic_int_types.h"
27#include "lsquic_sizes.h"
28#include "lsquic_hash.h"
29#include "lsquic_conn.h"
30#include "lsquic_enc_sess.h"
31#include "lsquic_parse.h"
32#include "lsquic_mm.h"
33#include "lsquic_engine_public.h"
34#include "lsquic_packet_common.h"
35#include "lsquic_packet_out.h"
36#include "lsquic_packet_ietf.h"
37#include "lsquic_packet_in.h"
38#include "lsquic_util.h"
39#include "lsquic_byteswap.h"
40#include "lsquic_ev_log.h"
41#include "lsquic_trans_params.h"
42#include "lsquic_version.h"
43#include "lsquic_ver_neg.h"
44#include "lsquic_frab_list.h"
45#include "lsquic_tokgen.h"
46#include "lsquic_ietf.h"
47#include "lsquic_alarmset.h"
48
49#if __GNUC__
50#   define UNLIKELY(cond) __builtin_expect(cond, 0)
51#else
52#   define UNLIKELY(cond) cond
53#endif
54
55#define MAX(a, b) ((a) > (b) ? (a) : (b))
56
57#define LSQUIC_LOGGER_MODULE LSQLM_HANDSHAKE
58#define LSQUIC_LOG_CONN_ID lsquic_conn_log_cid(enc_sess->esi_conn)
59#include "lsquic_logger.h"
60
61#define KEY_LABEL "quic key"
62#define KEY_LABEL_SZ (sizeof(KEY_LABEL) - 1)
63#define IV_LABEL "quic iv"
64#define IV_LABEL_SZ (sizeof(IV_LABEL) - 1)
65#define PN_LABEL "quic hp"
66#define PN_LABEL_SZ (sizeof(PN_LABEL) - 1)
67
68#define N_HSK_PAIRS (N_ENC_LEVS - 1)
69
70static const struct alpn_map {
71    enum lsquic_version  version;
72    const unsigned char *alpn;
73} s_h3_alpns[] = {
74    {   LSQVER_ID27, (unsigned char *) "\x05h3-27",     },
75    {   LSQVER_ID29, (unsigned char *) "\x05h3-29",     },
76    {   LSQVER_I001, (unsigned char *) "\x02h3",        },
77    {   LSQVER_VERNEG, (unsigned char *) "\x02h3",      },
78};
79
80struct enc_sess_iquic;
81struct crypto_ctx;
82struct crypto_ctx_pair;
83struct header_prot;
84
85static const int s_log_seal_and_open;
86static char s_str[0x1000];
87
88static const SSL_QUIC_METHOD cry_quic_method;
89
90static int s_idx = -1;
91
92static int
93setup_handshake_keys (struct enc_sess_iquic *, const lsquic_cid_t *);
94
95static void
96free_handshake_keys (struct enc_sess_iquic *);
97
98static struct stack_st_X509 *
99iquic_esf_get_server_cert_chain (enc_session_t *);
100
101static void
102maybe_drop_SSL (struct enc_sess_iquic *);
103
104static void
105no_sess_ticket (enum alarm_id alarm_id, void *ctx,
106                                  lsquic_time_t expiry, lsquic_time_t now);
107
108static int
109iquic_new_session_cb (SSL *, SSL_SESSION *);
110
111static enum ssl_verify_result_t
112verify_server_cert_callback (SSL *, uint8_t *out_alert);
113
114static void
115iquic_esfi_destroy (enc_session_t *);
116
117#define SAMPLE_SZ 16
118
119typedef void (*gen_hp_mask_f)(struct enc_sess_iquic *,
120    struct header_prot *, unsigned rw,
121    const unsigned char *sample, unsigned char *mask, size_t sz);
122
123#define CHACHA20_KEY_LENGTH 32
124
125struct header_prot
126{
127    gen_hp_mask_f       hp_gen_mask;
128    enum enc_level      hp_enc_level;
129    enum {
130        HP_CAN_READ  = 1 << 0,
131        HP_CAN_WRITE = 1 << 1,
132    }                   hp_flags;
133    union {
134        EVP_CIPHER_CTX      cipher_ctx[2];                  /* AES */
135        unsigned char       buf[2][CHACHA20_KEY_LENGTH];    /* ChaCha */
136    }                   hp_u;
137};
138
139#define header_prot_inited(hp_, rw_) ((hp_)->hp_flags & (1 << (rw_)))
140
141
142struct crypto_ctx
143{
144    enum {
145        YK_INITED = 1 << 0,
146    }                   yk_flags;
147    EVP_AEAD_CTX        yk_aead_ctx;
148    unsigned            yk_key_sz;
149    unsigned            yk_iv_sz;
150    unsigned char       yk_key_buf[EVP_MAX_KEY_LENGTH];
151    unsigned char       yk_iv_buf[EVP_MAX_IV_LENGTH];
152};
153
154
155struct crypto_ctx_pair
156{
157    lsquic_packno_t     ykp_thresh;
158    struct crypto_ctx   ykp_ctx[2]; /* client, server */
159};
160
161
162/* [draft-ietf-quic-tls-12] Section 5.3.6 */
163static int
164init_crypto_ctx (struct crypto_ctx *crypto_ctx, const EVP_MD *md,
165                 const EVP_AEAD *aead, const unsigned char *secret,
166                 size_t secret_sz, enum evp_aead_direction_t dir)
167{
168    crypto_ctx->yk_key_sz = EVP_AEAD_key_length(aead);
169    crypto_ctx->yk_iv_sz = EVP_AEAD_nonce_length(aead);
170
171    if (crypto_ctx->yk_key_sz > sizeof(crypto_ctx->yk_key_buf)
172        || crypto_ctx->yk_iv_sz > sizeof(crypto_ctx->yk_iv_buf))
173    {
174        return -1;
175    }
176
177    lsquic_qhkdf_expand(md, secret, secret_sz, KEY_LABEL, KEY_LABEL_SZ,
178        crypto_ctx->yk_key_buf, crypto_ctx->yk_key_sz);
179    lsquic_qhkdf_expand(md, secret, secret_sz, IV_LABEL, IV_LABEL_SZ,
180        crypto_ctx->yk_iv_buf, crypto_ctx->yk_iv_sz);
181    if (!EVP_AEAD_CTX_init_with_direction(&crypto_ctx->yk_aead_ctx, aead,
182            crypto_ctx->yk_key_buf, crypto_ctx->yk_key_sz, IQUIC_TAG_LEN, dir))
183        return -1;
184
185    crypto_ctx->yk_flags |= YK_INITED;
186
187    return 0;
188}
189
190
191static void
192cleanup_crypto_ctx (struct crypto_ctx *crypto_ctx)
193{
194    if (crypto_ctx->yk_flags & YK_INITED)
195    {
196        EVP_AEAD_CTX_cleanup(&crypto_ctx->yk_aead_ctx);
197        crypto_ctx->yk_flags &= ~YK_INITED;
198    }
199}
200
201
202#define HP_BATCH_SIZE 8
203
204struct enc_sess_iquic
205{
206    struct lsquic_engine_public
207                        *esi_enpub;
208    struct lsquic_conn  *esi_conn;
209    void               **esi_streams;
210    const struct crypto_stream_if *esi_cryst_if;
211    const struct ver_neg
212                        *esi_ver_neg;
213    SSL                 *esi_ssl;
214
215    /* These are used for forward encryption key phase 0 and 1 */
216    struct header_prot   esi_hp;
217    struct crypto_ctx_pair
218                         esi_pairs[2];
219    /* These are used during handshake.  There are three of them.
220     * esi_hsk_pairs and esi_hsk_hps are allocated and freed
221     * together.
222     */
223    struct crypto_ctx_pair *
224                         esi_hsk_pairs;
225    struct header_prot  *esi_hsk_hps;
226    lsquic_packno_t      esi_max_packno[N_PNS];
227    lsquic_cid_t         esi_odcid;
228    lsquic_cid_t         esi_rscid; /* Retry SCID */
229    lsquic_cid_t         esi_iscid; /* Initial SCID */
230    unsigned             esi_key_phase;
231    enum {
232        ESI_UNUSED0      = 1 << 0,
233        ESI_LOG_SECRETS  = 1 << 1,
234        ESI_HANDSHAKE_OK = 1 << 2,
235        ESI_ODCID        = 1 << 3,
236        ESI_ON_WRITE     = 1 << 4,
237        ESI_SERVER       = 1 << 5,
238        ESI_USE_SSL_TICKET = 1 << 6,
239        ESI_HAVE_PEER_TP = 1 << 7,
240        ESI_ALPN_CHECKED = 1 << 8,
241        ESI_CACHED_INFO  = 1 << 9,
242        ESI_HSK_CONFIRMED= 1 << 10,
243        ESI_WANT_TICKET  = 1 << 11,
244        ESI_RECV_QL_BITS = 1 << 12,
245        ESI_SEND_QL_BITS = 1 << 13,
246        ESI_RSCID        = 1 << 14,
247        ESI_ISCID        = 1 << 15,
248        ESI_RETRY        = 1 << 16, /* Connection was retried */
249        ESI_MAX_PACKNO_INIT = 1 << 17,
250        ESI_MAX_PACKNO_HSK  = ESI_MAX_PACKNO_INIT << PNS_HSK,
251        ESI_MAX_PACKNO_APP  = ESI_MAX_PACKNO_INIT << PNS_APP,
252        ESI_HAVE_0RTT_TP = 1 << 20,
253    }                    esi_flags;
254    enum enc_level       esi_last_w;
255    unsigned             esi_trasec_sz;
256#ifndef NDEBUG
257    char                *esi_sni_bypass;
258#endif
259    const unsigned char *esi_alpn;
260    /* Need MD and AEAD for key rotation */
261    const EVP_MD        *esi_md;
262    const EVP_AEAD      *esi_aead;
263    struct {
264        const char *cipher_name;
265        int         alg_bits;
266    }                    esi_cached_info;
267    /* Secrets are kept for key rotation */
268    unsigned char        esi_traffic_secrets[2][EVP_MAX_KEY_LENGTH];
269    /* We never use the first two levels, so it seems we could reduce the
270     * memory requirement here at the cost of adding some code.
271     */
272    struct frab_list     esi_frals[N_ENC_LEVS];
273    struct transport_params
274                         esi_peer_tp;
275    struct lsquic_alarmset
276                        *esi_alset;
277    unsigned             esi_max_streams_uni;
278    unsigned             esi_hp_batch_idx;
279    unsigned             esi_hp_batch_packno_len[HP_BATCH_SIZE];
280    unsigned             esi_hp_batch_packno_off[HP_BATCH_SIZE];
281    struct lsquic_packet_out *
282                         esi_hp_batch_packets[HP_BATCH_SIZE];
283    unsigned char        esi_hp_batch_samples[HP_BATCH_SIZE][SAMPLE_SZ];
284    unsigned char        esi_grease;
285    signed char          esi_have_forw;
286};
287
288
289static void
290gen_hp_mask_aes (struct enc_sess_iquic *enc_sess,
291        struct header_prot *hp, unsigned rw,
292        const unsigned char *sample, unsigned char *mask, size_t sz)
293{
294    int out_len;
295
296    if (EVP_EncryptUpdate(&hp->hp_u.cipher_ctx[rw], mask, &out_len, sample, sz))
297        assert(out_len >= (int) sz);
298    else
299    {
300        LSQ_WARN("cannot generate hp mask, error code: %"PRIu32,
301                                                            ERR_get_error());
302        enc_sess->esi_conn->cn_if->ci_internal_error(enc_sess->esi_conn,
303            "cannot generate hp mask, error code: %"PRIu32, ERR_get_error());
304    }
305}
306
307
308static void
309gen_hp_mask_chacha20 (struct enc_sess_iquic *enc_sess,
310        struct header_prot *hp, unsigned rw,
311        const unsigned char *sample, unsigned char *mask, size_t sz)
312{
313    const uint8_t *nonce;
314    uint32_t counter;
315
316#if __BYTE_ORDER == __LITTLE_ENDIAN
317    memcpy(&counter, sample, sizeof(counter));
318#else
319#error TODO: support non-little-endian machines
320#endif
321    nonce = sample + sizeof(counter);
322    CRYPTO_chacha_20(mask, (unsigned char [5]) { 0, 0, 0, 0, 0, }, 5,
323                                        hp->hp_u.buf[rw], nonce, counter);
324}
325
326
327static void
328apply_hp (struct enc_sess_iquic *enc_sess, struct header_prot *hp,
329        unsigned char *dst, const unsigned char *mask,
330        unsigned packno_off, unsigned packno_len)
331{
332    char mask_str[5 * 2 + 1];
333
334    LSQ_DEBUG("apply header protection using mask %s",
335                                                HEXSTR(mask, 5, mask_str));
336    if (enc_sess->esi_flags & ESI_SEND_QL_BITS)
337        dst[0] ^= (0x7 | ((dst[0] >> 7) << 3)) & mask[0];
338    else
339        dst[0] ^= (0xF | (((dst[0] & 0x80) == 0) << 4)) & mask[0];
340    switch (packno_len)
341    {
342    case 4:
343        dst[packno_off + 3] ^= mask[4];
344        /* fall-through */
345    case 3:
346        dst[packno_off + 2] ^= mask[3];
347        /* fall-through */
348    case 2:
349        dst[packno_off + 1] ^= mask[2];
350        /* fall-through */
351    default:
352        dst[packno_off + 0] ^= mask[1];
353    }
354}
355
356
357static void
358apply_hp_immediately (struct enc_sess_iquic *enc_sess,
359        struct header_prot *hp, struct lsquic_packet_out *packet_out,
360        unsigned packno_off, unsigned packno_len)
361{
362    unsigned char mask[SAMPLE_SZ];
363
364    hp->hp_gen_mask(enc_sess, hp, 1,
365                    packet_out->po_enc_data + packno_off + 4, mask, SAMPLE_SZ);
366    apply_hp(enc_sess, hp, packet_out->po_enc_data, mask, packno_off,
367                                                                packno_len);
368#ifndef NDEBUG
369    packet_out->po_lflags |= POL_HEADER_PROT;
370#endif
371}
372
373
374static void
375flush_hp_batch (struct enc_sess_iquic *enc_sess)
376{
377    unsigned i;
378    unsigned char mask[HP_BATCH_SIZE][SAMPLE_SZ];
379
380    enc_sess->esi_hp.hp_gen_mask(enc_sess, &enc_sess->esi_hp, 1,
381                        (unsigned char *) enc_sess->esi_hp_batch_samples,
382                        (unsigned char *) mask,
383                        enc_sess->esi_hp_batch_idx * SAMPLE_SZ);
384    for (i = 0; i < enc_sess->esi_hp_batch_idx; ++i)
385    {
386        apply_hp(enc_sess, &enc_sess->esi_hp,
387            enc_sess->esi_hp_batch_packets[i]->po_enc_data,
388            mask[i],
389            enc_sess->esi_hp_batch_packno_off[i],
390            enc_sess->esi_hp_batch_packno_len[i]);
391#ifndef NDEBUG
392            enc_sess->esi_hp_batch_packets[i]->po_lflags |= POL_HEADER_PROT;
393#endif
394    }
395    enc_sess->esi_hp_batch_idx = 0;
396}
397
398
399static void
400apply_hp_batch (struct enc_sess_iquic *enc_sess,
401        struct header_prot *hp, struct lsquic_packet_out *packet_out,
402        unsigned packno_off, unsigned packno_len)
403{
404    memcpy(enc_sess->esi_hp_batch_samples[enc_sess->esi_hp_batch_idx],
405                        packet_out->po_enc_data + packno_off + 4, SAMPLE_SZ);
406    enc_sess->esi_hp_batch_packno_off[enc_sess->esi_hp_batch_idx] = packno_off;
407    enc_sess->esi_hp_batch_packno_len[enc_sess->esi_hp_batch_idx] = packno_len;
408    enc_sess->esi_hp_batch_packets[enc_sess->esi_hp_batch_idx] = packet_out;
409    ++enc_sess->esi_hp_batch_idx;
410    if (enc_sess->esi_hp_batch_idx == HP_BATCH_SIZE)
411        flush_hp_batch(enc_sess);
412}
413
414
415static lsquic_packno_t
416decode_packno (lsquic_packno_t max_packno, lsquic_packno_t packno,
417                                                                unsigned shift)
418{
419    lsquic_packno_t candidates[3], epoch_delta;
420    int64_t diffs[3];
421    unsigned min;;
422
423    epoch_delta = 1ULL << shift;
424    candidates[1] = (max_packno & ~(epoch_delta - 1)) + packno;
425    candidates[0] = candidates[1] - epoch_delta;
426    candidates[2] = candidates[1] + epoch_delta;
427
428    diffs[0] = llabs((int64_t) candidates[0] - (int64_t) max_packno);
429    diffs[1] = llabs((int64_t) candidates[1] - (int64_t) max_packno);
430    diffs[2] = llabs((int64_t) candidates[2] - (int64_t) max_packno);
431
432    min = diffs[1] < diffs[0];
433    if (diffs[2] < diffs[min])
434        min = 2;
435
436    return candidates[min];
437}
438
439
440static lsquic_packno_t
441strip_hp (struct enc_sess_iquic *enc_sess,
442        struct header_prot *hp,
443        const unsigned char *iv, unsigned char *dst, unsigned packno_off,
444        unsigned *packno_len)
445{
446    enum packnum_space pns;
447    lsquic_packno_t packno;
448    unsigned shift;
449    unsigned char mask[SAMPLE_SZ];
450    char mask_str[5 * 2 + 1];
451
452    hp->hp_gen_mask(enc_sess, hp, 0, iv, mask, SAMPLE_SZ);
453    LSQ_DEBUG("strip header protection using mask %s",
454                                                HEXSTR(mask, 5, mask_str));
455    if (enc_sess->esi_flags & ESI_RECV_QL_BITS)
456        dst[0] ^= (0x7 | ((dst[0] >> 7) << 3)) & mask[0];
457    else
458        dst[0] ^= (0xF | (((dst[0] & 0x80) == 0) << 4)) & mask[0];
459    packno = 0;
460    shift = 0;
461    *packno_len = 1 + (dst[0] & 3);
462    switch (*packno_len)
463    {
464    case 4:
465        dst[packno_off + 3] ^= mask[4];
466        packno |= dst[packno_off + 3];
467        shift += 8;
468        /* fall-through */
469    case 3:
470        dst[packno_off + 2] ^= mask[3];
471        packno |= (unsigned) dst[packno_off + 2] << shift;
472        shift += 8;
473        /* fall-through */
474    case 2:
475        dst[packno_off + 1] ^= mask[2];
476        packno |= (unsigned) dst[packno_off + 1] << shift;
477        shift += 8;
478        /* fall-through */
479    default:
480        dst[packno_off + 0] ^= mask[1];
481        packno |= (unsigned) dst[packno_off + 0] << shift;
482        shift += 8;
483    }
484    pns = lsquic_enclev2pns[hp->hp_enc_level];
485    if (enc_sess->esi_flags & (ESI_MAX_PACKNO_INIT << pns))
486    {
487        LSQ_DEBUG("pre-decode packno: %"PRIu64, packno);
488        return decode_packno(enc_sess->esi_max_packno[pns], packno, shift);
489    }
490    else
491    {
492        LSQ_DEBUG("first packet in %s, packno: %"PRIu64, lsquic_pns2str[pns],
493                                                                        packno);
494        return packno;
495    }
496}
497
498
499static int
500gen_trans_params (struct enc_sess_iquic *enc_sess, unsigned char *buf,
501                                                                size_t bufsz)
502{
503    const struct lsquic_engine_settings *const settings =
504                                    &enc_sess->esi_enpub->enp_settings;
505    struct transport_params params;
506    const enum lsquic_version version = enc_sess->esi_conn->cn_version;
507    int len;
508
509    memset(&params, 0, sizeof(params));
510    if (version > LSQVER_ID27)
511    {
512        params.tp_initial_source_cid = *CN_SCID(enc_sess->esi_conn);
513        params.tp_set |= 1 << TPI_INITIAL_SOURCE_CID;
514    }
515    if (enc_sess->esi_flags & ESI_SERVER)
516    {
517        const struct lsquic_conn *const lconn = enc_sess->esi_conn;
518
519        params.tp_set |= 1 << TPI_STATELESS_RESET_TOKEN;
520        lsquic_tg_generate_sreset(enc_sess->esi_enpub->enp_tokgen,
521            CN_SCID(lconn), params.tp_stateless_reset_token);
522
523        if (enc_sess->esi_flags & ESI_ODCID)
524        {
525            params.tp_original_dest_cid = enc_sess->esi_odcid;
526            params.tp_set |= 1 << TPI_ORIGINAL_DEST_CID;
527        }
528#if LSQUIC_PREFERRED_ADDR
529        char addr_buf[INET6_ADDRSTRLEN + 6 /* port */ + 1];
530        const char *s, *colon;
531        struct lsquic_conn *conn;
532        struct conn_cid_elem *cce;
533        unsigned seqno;
534        s = getenv("LSQUIC_PREFERRED_ADDR4");
535        if (s && strlen(s) < sizeof(addr_buf) && (colon = strchr(s, ':')))
536        {
537            strncpy(addr_buf, s, colon - s);
538            addr_buf[colon - s] = '\0';
539            inet_pton(AF_INET, addr_buf, params.tp_preferred_address.ipv4_addr);
540            params.tp_preferred_address.ipv4_port = atoi(colon + 1);
541            params.tp_set |= 1 << TPI_PREFERRED_ADDRESS;
542        }
543        s = getenv("LSQUIC_PREFERRED_ADDR6");
544        if (s && strlen(s) < sizeof(addr_buf) && (colon = strrchr(s, ':')))
545        {
546            strncpy(addr_buf, s, colon - s);
547            addr_buf[colon - s] = '\0';
548            inet_pton(AF_INET6, addr_buf,
549                                        params.tp_preferred_address.ipv6_addr);
550            params.tp_preferred_address.ipv6_port = atoi(colon + 1);
551            params.tp_set |= 1 << TPI_PREFERRED_ADDRESS;
552        }
553        conn = enc_sess->esi_conn;
554        if ((params.tp_set & (1 << TPI_PREFERRED_ADDRESS))
555                            && (1 << conn->cn_n_cces) - 1 != conn->cn_cces_mask)
556        {
557            seqno = 0;
558            for (cce = lconn->cn_cces; cce < END_OF_CCES(lconn); ++cce)
559            {
560                if (lconn->cn_cces_mask & (1 << (cce - lconn->cn_cces)))
561                {
562                    if ((cce->cce_flags & CCE_SEQNO) && cce->cce_seqno > seqno)
563                        seqno = cce->cce_seqno;
564                }
565                else
566                    break;
567            }
568            if (cce == END_OF_CCES(lconn))
569            {
570                goto cant_use_prefaddr;
571            }
572            cce->cce_seqno = seqno + 1;
573            cce->cce_flags = CCE_SEQNO;
574
575            enc_sess->esi_enpub->enp_generate_scid(
576                enc_sess->esi_enpub->enp_gen_scid_ctx, enc_sess->esi_conn,
577                &cce->cce_cid, enc_sess->esi_enpub->enp_settings.es_scid_len);
578
579            /* Don't add to hash: migration must not start until *after*
580             * handshake is complete.
581             */
582            conn->cn_cces_mask |= 1 << (cce - conn->cn_cces);
583            params.tp_preferred_address.cid = cce->cce_cid;
584            lsquic_tg_generate_sreset(enc_sess->esi_enpub->enp_tokgen,
585                &params.tp_preferred_address.cid,
586                params.tp_preferred_address.srst);
587        }
588        else
589        {
590  cant_use_prefaddr:
591            params.tp_set &= ~(1 << TPI_PREFERRED_ADDRESS);
592        }
593#endif
594    }
595#if LSQUIC_TEST_QUANTUM_READINESS
596    {
597        const char *s = getenv("LSQUIC_TEST_QUANTUM_READINESS");
598        if (s && atoi(s))
599            params.tp_set |= 1 << TPI_QUANTUM_READINESS;
600    }
601#endif
602    params.tp_init_max_data = settings->es_init_max_data;
603    params.tp_init_max_stream_data_bidi_local
604                            = settings->es_init_max_stream_data_bidi_local;
605    params.tp_init_max_stream_data_bidi_remote
606                            = settings->es_init_max_stream_data_bidi_remote;
607    params.tp_init_max_stream_data_uni
608                            = settings->es_init_max_stream_data_uni;
609    params.tp_init_max_streams_uni
610                            = enc_sess->esi_max_streams_uni;
611    params.tp_init_max_streams_bidi
612                            = settings->es_init_max_streams_bidi;
613    params.tp_ack_delay_exponent
614                            = TP_DEF_ACK_DELAY_EXP;
615    params.tp_max_idle_timeout = settings->es_idle_timeout * 1000;
616    params.tp_max_ack_delay = TP_DEF_MAX_ACK_DELAY;
617    params.tp_active_connection_id_limit = MAX_IETF_CONN_DCIDS;
618    params.tp_set |= (1 << TPI_INIT_MAX_DATA)
619                  |  (1 << TPI_INIT_MAX_STREAM_DATA_BIDI_LOCAL)
620                  |  (1 << TPI_INIT_MAX_STREAM_DATA_BIDI_REMOTE)
621                  |  (1 << TPI_INIT_MAX_STREAM_DATA_UNI)
622                  |  (1 << TPI_INIT_MAX_STREAMS_UNI)
623                  |  (1 << TPI_INIT_MAX_STREAMS_BIDI)
624                  |  (1 << TPI_ACK_DELAY_EXPONENT)
625                  |  (1 << TPI_MAX_IDLE_TIMEOUT)
626                  |  (1 << TPI_MAX_ACK_DELAY)
627                  |  (1 << TPI_ACTIVE_CONNECTION_ID_LIMIT)
628                  ;
629    if (settings->es_max_udp_payload_size_rx)
630    {
631        params.tp_max_udp_payload_size = settings->es_max_udp_payload_size_rx;
632        params.tp_set |= 1 << TPI_MAX_UDP_PAYLOAD_SIZE;
633    }
634    if (!settings->es_allow_migration)
635        params.tp_set |= 1 << TPI_DISABLE_ACTIVE_MIGRATION;
636    if (settings->es_ql_bits)
637    {
638        params.tp_loss_bits = settings->es_ql_bits - 1;
639        params.tp_set |= 1 << TPI_LOSS_BITS;
640    }
641    if (settings->es_delayed_acks)
642    {
643        params.tp_numerics[TPI_MIN_ACK_DELAY] = TP_MIN_ACK_DELAY;
644        params.tp_set |= 1 << TPI_MIN_ACK_DELAY;
645        params.tp_numerics[TPI_MIN_ACK_DELAY_02] = TP_MIN_ACK_DELAY;
646        params.tp_set |= 1 << TPI_MIN_ACK_DELAY_02;
647    }
648    if (settings->es_timestamps)
649    {
650        params.tp_numerics[TPI_TIMESTAMPS] = TS_GENERATE_THEM;
651        params.tp_set |= 1 << TPI_TIMESTAMPS;
652    }
653    if (settings->es_datagrams)
654    {
655        if (params.tp_set & (1 << TPI_MAX_UDP_PAYLOAD_SIZE))
656            params.tp_numerics[TPI_MAX_DATAGRAM_FRAME_SIZE]
657                                            = params.tp_max_udp_payload_size;
658        else
659            params.tp_numerics[TPI_MAX_DATAGRAM_FRAME_SIZE]
660                                            = TP_DEF_MAX_UDP_PAYLOAD_SIZE;
661        params.tp_set |= 1 << TPI_MAX_DATAGRAM_FRAME_SIZE;
662    }
663
664    len = (version == LSQVER_ID27 ? lsquic_tp_encode_27 : lsquic_tp_encode)(
665                        &params, enc_sess->esi_flags & ESI_SERVER, buf, bufsz);
666    if (len >= 0)
667    {
668        char str[MAX_TP_STR_SZ];
669        LSQ_DEBUG("generated transport parameters buffer of %d bytes", len);
670        LSQ_DEBUG("%s", ((version == LSQVER_ID27 ? lsquic_tp_to_str_27
671                        : lsquic_tp_to_str)(&params, str, sizeof(str)), str));
672    }
673    else
674        LSQ_WARN("cannot generate transport parameters: %d", errno);
675    return len;
676}
677
678
679/*
680 * Format:
681 *      uint32_t    lsquic_ver_tag_t
682 *      uint32_t    encoder version
683 *      uint32_t    ticket_size
684 *      uint8_t     ticket_buf[ ticket_size ]
685 *      uint32_t    trapa_size
686 *      uint8_t     trapa_buf[ trapa_size ]
687 */
688
689#define SESS_RESUME_VERSION 1
690
691#if __BYTE_ORDER == __LITTLE_ENDIAN
692#define READ_NUM(var_, ptr_) do {                               \
693    memcpy(&var_, ptr_, sizeof(var_));                          \
694    var_ = bswap_32(var_);                                      \
695    ptr_ += sizeof(var_);                                       \
696} while (0)
697#else
698#define READ_NUM(var_, ptr_) do {                               \
699    memcpy(&var_, ptr_, sizeof(var_));                          \
700    ptr_ += sizeof(var_);                                       \
701} while (0)
702#endif
703
704static SSL_SESSION *
705maybe_create_SSL_SESSION (struct enc_sess_iquic *enc_sess,
706            const SSL_CTX *ssl_ctx, const unsigned char *sess_resume,
707                                                        size_t sess_resume_sz)
708{
709    SSL_SESSION *ssl_session;
710    lsquic_ver_tag_t ver_tag;
711    enum lsquic_version quic_ver;
712    uint32_t rtt_ver, ticket_sz, trapa_sz;
713    const unsigned char *ticket_buf, *trapa_buf, *p;
714    const unsigned char *const end = sess_resume + sess_resume_sz;
715
716    if (sess_resume_sz < sizeof(ver_tag) + sizeof(rtt_ver) + sizeof(ticket_sz))
717    {
718        LSQ_DEBUG("rtt buf too short");
719        return NULL;
720    }
721
722    p = sess_resume;
723    memcpy(&ver_tag, p, sizeof(ver_tag));
724    p += sizeof(ver_tag);
725    quic_ver = lsquic_tag2ver(ver_tag);
726    if (quic_ver != enc_sess->esi_ver_neg->vn_ver)
727    {
728        LSQ_DEBUG("negotiated version %s does not match that in the session "
729            "resumption nfo buffer",
730            lsquic_ver2str[enc_sess->esi_ver_neg->vn_ver]);
731        return NULL;
732    }
733
734    READ_NUM(rtt_ver, p);
735    if (rtt_ver != SESS_RESUME_VERSION)
736    {
737        LSQ_DEBUG("cannot use session resumption buffer: encoded using "
738                "%"PRIu32", while current version is %u",
739                rtt_ver, SESS_RESUME_VERSION);
740        return NULL;
741    }
742
743    READ_NUM(ticket_sz, p);
744    if (p + ticket_sz > end)
745    {
746        LSQ_WARN("truncated ticket buffer");
747        return NULL;
748    }
749
750    ticket_buf = p;
751    p += ticket_sz;
752
753    if (p + sizeof(trapa_sz) > end)
754    {
755        LSQ_WARN("too short to read trapa size");
756        return NULL;
757    }
758
759    READ_NUM(trapa_sz, p);
760    if (p + trapa_sz > end)
761    {
762        LSQ_WARN("truncated trapa buffer");
763        return NULL;
764    }
765    trapa_buf = p;
766    p += trapa_sz;
767    assert(p == end);
768
769    ssl_session = SSL_SESSION_from_bytes(ticket_buf, ticket_sz, ssl_ctx);
770    if (!ssl_session)
771    {
772        LSQ_WARN("SSL_SESSION could not be parsed out");
773        return NULL;
774    }
775
776    if (SSL_SESSION_early_data_capable(ssl_session))
777    {
778        if (0 > (quic_ver == LSQVER_ID27 ? lsquic_tp_decode_27
779                    : lsquic_tp_decode)(trapa_buf, trapa_sz, 1,
780                                                    &enc_sess->esi_peer_tp))
781        {
782            SSL_SESSION_free(ssl_session);
783            LSQ_WARN("cannot parse stored transport parameters");
784            return NULL;
785        }
786        LSQ_DEBUG("early data capable, will try 0-RTT");
787        enc_sess->esi_flags |= ESI_HAVE_0RTT_TP;
788    }
789    else
790        LSQ_DEBUG("early data not capable -- not trying 0-RTT");
791
792    LSQ_INFO("instantiated SSL_SESSION from serialized buffer");
793    return ssl_session;
794}
795
796
797static void
798init_frals (struct enc_sess_iquic *enc_sess)
799{
800    struct frab_list *fral;
801
802    for (fral = enc_sess->esi_frals; fral < enc_sess->esi_frals
803            + sizeof(enc_sess->esi_frals) / sizeof(enc_sess->esi_frals[0]);
804                ++fral)
805        lsquic_frab_list_init(fral, 0x100, NULL, NULL, NULL);
806}
807
808
809static enc_session_t *
810iquic_esfi_create_client (const char *hostname,
811            struct lsquic_engine_public *enpub, struct lsquic_conn *lconn,
812            const lsquic_cid_t *dcid, const struct ver_neg *ver_neg,
813            void *crypto_streams[4], const struct crypto_stream_if *cryst_if,
814            const unsigned char *sess_resume, size_t sess_resume_sz,
815            struct lsquic_alarmset *alset, unsigned max_streams_uni,
816            void* peer_ctx)
817{
818    struct enc_sess_iquic *enc_sess;
819    SSL_CTX *ssl_ctx = NULL;
820    int set_app_ctx = 0;
821    SSL_SESSION *ssl_session;
822    const struct alpn_map *am;
823    int transpa_len;
824    char errbuf[ERR_ERROR_STRING_BUF_LEN];
825    unsigned char trans_params[0x80
826#if LSQUIC_TEST_QUANTUM_READINESS
827        + 4 + lsquic_tp_get_quantum_sz()
828#endif
829    ];
830
831    fiu_return_on("enc_sess_ietf/create_client", NULL);
832
833    enc_sess = calloc(1, sizeof(*enc_sess));
834    if (!enc_sess)
835        return NULL;
836
837    enc_sess->esi_enpub = enpub;
838    enc_sess->esi_streams = crypto_streams;
839    enc_sess->esi_cryst_if = cryst_if;
840    enc_sess->esi_conn = lconn;
841    enc_sess->esi_ver_neg = ver_neg;
842
843    enc_sess->esi_odcid = *dcid;
844    enc_sess->esi_flags |= ESI_ODCID;
845    enc_sess->esi_grease = 0xFF;
846
847    LSQ_DEBUGC("created client, DCID: %"CID_FMT, CID_BITS(dcid));
848    {
849        const char *log;
850        log = getenv("LSQUIC_LOG_SECRETS");
851        if (log)
852        {
853            if (atoi(log))
854                enc_sess->esi_flags |= ESI_LOG_SECRETS;
855            LSQ_DEBUG("will %slog secrets", atoi(log) ? "" : "not ");
856        }
857    }
858
859    init_frals(enc_sess);
860
861    if (0 != setup_handshake_keys(enc_sess, dcid))
862    {
863        free(enc_sess);
864        return NULL;
865    }
866
867    enc_sess->esi_max_streams_uni = max_streams_uni;
868
869    if (enc_sess->esi_enpub->enp_alpn)
870        enc_sess->esi_alpn = enc_sess->esi_enpub->enp_alpn;
871    else if (enc_sess->esi_enpub->enp_flags & ENPUB_HTTP)
872    {
873        for (am = s_h3_alpns; am < s_h3_alpns + sizeof(s_h3_alpns)
874                                                / sizeof(s_h3_alpns[0]); ++am)
875            if (am->version == enc_sess->esi_ver_neg->vn_ver)
876                goto alpn_selected;
877        LSQ_ERROR("version %s has no matching ALPN",
878                                lsquic_ver2str[enc_sess->esi_ver_neg->vn_ver]);
879        goto err;
880  alpn_selected:
881        enc_sess->esi_alpn = am->alpn;
882        LSQ_DEBUG("for QUIC version %s, ALPN is %s",
883                        lsquic_ver2str[am->version], (char *) am->alpn + 1);
884    }
885
886    if (enc_sess->esi_enpub->enp_get_ssl_ctx)
887    {
888        struct network_path *const path =
889            enc_sess->esi_conn->cn_if->ci_get_path(enc_sess->esi_conn, NULL);
890        ssl_ctx = enc_sess->esi_enpub->enp_get_ssl_ctx(peer_ctx,
891                                                            NP_LOCAL_SA(path));
892        if (ssl_ctx)
893            set_app_ctx = 1;
894        else
895            goto create_new_ssl_ctx;
896    }
897    else
898    {
899  create_new_ssl_ctx:
900        LSQ_DEBUG("Create new SSL_CTX");
901        ssl_ctx = SSL_CTX_new(TLS_method());
902        if (!ssl_ctx)
903        {
904            LSQ_ERROR("cannot create SSL context: %s",
905                ERR_error_string(ERR_get_error(), errbuf));
906            goto err;
907        }
908        SSL_CTX_set_min_proto_version(ssl_ctx, TLS1_3_VERSION);
909        SSL_CTX_set_max_proto_version(ssl_ctx, TLS1_3_VERSION);
910        SSL_CTX_set_default_verify_paths(ssl_ctx);
911        SSL_CTX_set_session_cache_mode(ssl_ctx, SSL_SESS_CACHE_CLIENT);
912        if (enc_sess->esi_enpub->enp_stream_if->on_sess_resume_info)
913            SSL_CTX_sess_set_new_cb(ssl_ctx, iquic_new_session_cb);
914        if (enc_sess->esi_enpub->enp_verify_cert
915                || LSQ_LOG_ENABLED_EXT(LSQ_LOG_DEBUG, LSQLM_EVENT)
916                || LSQ_LOG_ENABLED_EXT(LSQ_LOG_DEBUG, LSQLM_QLOG))
917            SSL_CTX_set_custom_verify(ssl_ctx, SSL_VERIFY_PEER,
918                verify_server_cert_callback);
919        SSL_CTX_set_early_data_enabled(ssl_ctx, 1);
920    }
921
922    enc_sess->esi_ssl = SSL_new(ssl_ctx);
923    if (!enc_sess->esi_ssl)
924    {
925        LSQ_ERROR("cannot create SSL object: %s",
926            ERR_error_string(ERR_get_error(), errbuf));
927        goto err;
928    }
929#if BORINGSSL_API_VERSION >= 13
930    SSL_set_quic_use_legacy_codepoint(enc_sess->esi_ssl,
931                            enc_sess->esi_ver_neg->vn_ver < LSQVER_I001);
932#endif
933
934    transpa_len = gen_trans_params(enc_sess, trans_params,
935                                                    sizeof(trans_params));
936    if (transpa_len < 0)
937    {
938        goto err;
939    }
940    if (1 != SSL_set_quic_transport_params(enc_sess->esi_ssl, trans_params,
941                                                            transpa_len))
942    {
943        LSQ_ERROR("cannot set QUIC transport params: %s",
944            ERR_error_string(ERR_get_error(), errbuf));
945        goto err;
946    }
947
948    if (!(SSL_set_quic_method(enc_sess->esi_ssl, &cry_quic_method)))
949    {
950        LSQ_INFO("could not set stream method");
951        goto err;
952    }
953
954    if (enc_sess->esi_alpn &&
955            0 != SSL_set_alpn_protos(enc_sess->esi_ssl, enc_sess->esi_alpn,
956                                                    enc_sess->esi_alpn[0] + 1))
957    {
958        LSQ_ERROR("cannot set ALPN: %s",
959            ERR_error_string(ERR_get_error(), errbuf));
960        goto err;
961    }
962    if (1 != SSL_set_tlsext_host_name(enc_sess->esi_ssl, hostname))
963    {
964        LSQ_ERROR("cannot set hostname: %s",
965            ERR_error_string(ERR_get_error(), errbuf));
966        goto err;
967    }
968
969    if (sess_resume && sess_resume_sz)
970    {
971        ssl_session = maybe_create_SSL_SESSION(enc_sess, ssl_ctx,
972                                                sess_resume, sess_resume_sz);
973        if (ssl_session)
974        {
975            (void)  /* This only ever returns 1: */
976                SSL_set_session(enc_sess->esi_ssl, ssl_session);
977            SSL_SESSION_free(ssl_session);
978            ssl_session = NULL;
979            enc_sess->esi_flags |= ESI_USE_SSL_TICKET;
980        }
981    }
982
983    SSL_set_ex_data(enc_sess->esi_ssl, s_idx, enc_sess);
984    SSL_set_connect_state(enc_sess->esi_ssl);
985
986    if (SSL_CTX_sess_get_new_cb(ssl_ctx))
987        enc_sess->esi_flags |= ESI_WANT_TICKET;
988    enc_sess->esi_alset = alset;
989    lsquic_alarmset_init_alarm(enc_sess->esi_alset, AL_SESS_TICKET,
990                                            no_sess_ticket, enc_sess);
991
992    if( !set_app_ctx )
993        SSL_CTX_free(ssl_ctx);
994    return enc_sess;
995
996  err:
997    if (enc_sess)
998        iquic_esfi_destroy(enc_sess);
999    if (!set_app_ctx && ssl_ctx)
1000        SSL_CTX_free(ssl_ctx);
1001    return NULL;
1002}
1003
1004
1005static void
1006iquic_esfi_set_streams (enc_session_t *enc_session_p,
1007        void *(crypto_streams)[4], const struct crypto_stream_if *cryst_if)
1008{
1009    struct enc_sess_iquic *const enc_sess = enc_session_p;
1010    enc_sess->esi_streams = crypto_streams;
1011    enc_sess->esi_cryst_if = cryst_if;
1012}
1013
1014
1015static enc_session_t *
1016iquic_esfi_create_server (struct lsquic_engine_public *enpub,
1017                    struct lsquic_conn *lconn, const lsquic_cid_t *first_dcid,
1018                    void *(crypto_streams)[4],
1019                    const struct crypto_stream_if *cryst_if,
1020                    const struct lsquic_cid *odcid,
1021                    const struct lsquic_cid *iscid)
1022{
1023    struct enc_sess_iquic *enc_sess;
1024
1025    enc_sess = calloc(1, sizeof(*enc_sess));
1026    if (!enc_sess)
1027        return NULL;
1028
1029#ifndef NDEBUG
1030    enc_sess->esi_sni_bypass = getenv("LSQUIC_SNI_BYPASS");
1031#endif
1032
1033    enc_sess->esi_flags = ESI_SERVER;
1034    enc_sess->esi_streams = crypto_streams;
1035    enc_sess->esi_cryst_if = cryst_if;
1036    enc_sess->esi_enpub = enpub;
1037    enc_sess->esi_conn = lconn;
1038    enc_sess->esi_grease = 0xFF;
1039
1040    if (odcid)
1041    {
1042        enc_sess->esi_odcid = *odcid;
1043        enc_sess->esi_flags |= ESI_ODCID;
1044    }
1045    enc_sess->esi_iscid = *iscid;
1046    enc_sess->esi_flags |= ESI_ISCID;
1047
1048    init_frals(enc_sess);
1049
1050    {
1051        const char *log;
1052        log = getenv("LSQUIC_LOG_SECRETS");
1053        if (log)
1054        {
1055            if (atoi(log))
1056                enc_sess->esi_flags |= ESI_LOG_SECRETS;
1057            LSQ_DEBUG("will %slog secrets", atoi(log) ? "" : "not ");
1058        }
1059    }
1060
1061    if (0 != setup_handshake_keys(enc_sess, first_dcid))
1062    {
1063        free(enc_sess);
1064        return NULL;
1065    }
1066
1067    enc_sess->esi_max_streams_uni
1068        = enpub->enp_settings.es_init_max_streams_uni;
1069
1070    return enc_sess;
1071}
1072
1073
1074static const char *const rw2str[] = { "read", "write", };
1075
1076typedef char evp_aead_enum_has_expected_values[
1077    (int) evp_aead_open  == 0 && (int) evp_aead_seal == 1 ? 1 : -1];
1078#define rw2dir(rw_) ((enum evp_aead_direction_t) (rw_))
1079
1080
1081static void
1082log_crypto_ctx (const struct enc_sess_iquic *enc_sess,
1083                const struct crypto_ctx *ctx, const char *name, int rw)
1084{
1085    char hexbuf[EVP_MAX_MD_SIZE * 2 + 1];
1086    LSQ_DEBUG("%s %s key: %s", name, rw2str[rw],
1087        HEXSTR(ctx->yk_key_buf, ctx->yk_key_sz, hexbuf));
1088    LSQ_DEBUG("%s %s iv: %s", name, rw2str[rw],
1089        HEXSTR(ctx->yk_iv_buf, ctx->yk_iv_sz, hexbuf));
1090}
1091
1092
1093static void
1094log_crypto_pair (const struct enc_sess_iquic *enc_sess,
1095                    const struct crypto_ctx_pair *pair, const char *name)
1096{
1097    log_crypto_ctx(enc_sess, &pair->ykp_ctx[0], name, 0);
1098    log_crypto_ctx(enc_sess, &pair->ykp_ctx[1], name, 1);
1099}
1100
1101
1102/* [draft-ietf-quic-tls-12] Section 5.3.2 */
1103static int
1104setup_handshake_keys (struct enc_sess_iquic *enc_sess, const lsquic_cid_t *cid)
1105{
1106    const EVP_MD *const md = EVP_sha256();
1107    const EVP_AEAD *const aead = EVP_aead_aes_128_gcm();
1108    /* [draft-ietf-quic-tls-12] Section 5.6.1: AEAD_AES_128_GCM implies
1109     * 128-bit AES-CTR.
1110     */
1111    const EVP_CIPHER *const cipher = EVP_aes_128_ecb();
1112    struct crypto_ctx_pair *pair;
1113    struct header_prot *hp;
1114    size_t hsk_secret_sz, key_len;
1115    unsigned cliser, i;
1116    const unsigned char *salt;
1117    unsigned char hsk_secret[EVP_MAX_MD_SIZE];
1118    unsigned char secret[2][SHA256_DIGEST_LENGTH];  /* client, server */
1119    unsigned char key[2][EVP_MAX_KEY_LENGTH];
1120    char hexbuf[EVP_MAX_MD_SIZE * 2 + 1];
1121
1122    if (!enc_sess->esi_hsk_pairs)
1123    {
1124        enc_sess->esi_hsk_pairs = calloc(N_HSK_PAIRS,
1125                                            sizeof(enc_sess->esi_hsk_pairs[0]));
1126        enc_sess->esi_hsk_hps = calloc(N_HSK_PAIRS,
1127                                            sizeof(enc_sess->esi_hsk_hps[0]));
1128        if (!(enc_sess->esi_hsk_pairs && enc_sess->esi_hsk_hps))
1129        {
1130            free(enc_sess->esi_hsk_pairs);
1131            free(enc_sess->esi_hsk_hps);
1132            return -1;
1133        }
1134    }
1135    pair = &enc_sess->esi_hsk_pairs[ENC_LEV_CLEAR];
1136    pair->ykp_thresh = IQUIC_INVALID_PACKNO;
1137    hp = &enc_sess->esi_hsk_hps[ENC_LEV_CLEAR];
1138
1139    if (enc_sess->esi_conn->cn_version < LSQVER_ID29)
1140        salt = HSK_SALT_PRE29;
1141    else if (enc_sess->esi_conn->cn_version < LSQVER_I001)
1142        salt = HSK_SALT_PRE33;
1143    else
1144        salt = HSK_SALT;
1145    HKDF_extract(hsk_secret, &hsk_secret_sz, md, cid->idbuf, cid->len,
1146                    salt, HSK_SALT_SZ);
1147    if (enc_sess->esi_flags & ESI_LOG_SECRETS)
1148    {
1149        LSQ_DEBUG("handshake salt: %s", HEXSTR(salt, HSK_SALT_SZ, hexbuf));
1150        LSQ_DEBUG("handshake secret: %s", HEXSTR(hsk_secret, hsk_secret_sz,
1151                                                                    hexbuf));
1152    }
1153
1154    lsquic_qhkdf_expand(md, hsk_secret, hsk_secret_sz, CLIENT_LABEL,
1155                CLIENT_LABEL_SZ, secret[0], sizeof(secret[0]));
1156    lsquic_qhkdf_expand(md, hsk_secret, hsk_secret_sz, SERVER_LABEL,
1157                SERVER_LABEL_SZ, secret[1], sizeof(secret[1]));
1158    if (enc_sess->esi_flags & ESI_LOG_SECRETS)
1159    {
1160        LSQ_DEBUG("client handshake secret: %s",
1161            HEXSTR(secret[0], sizeof(secret[0]), hexbuf));
1162        LSQ_DEBUG("server handshake secret: %s",
1163            HEXSTR(secret[1], sizeof(secret[1]), hexbuf));
1164    }
1165
1166    cliser = !!(enc_sess->esi_flags & ESI_SERVER);
1167    if (0 != init_crypto_ctx(&pair->ykp_ctx[!cliser], md, aead, secret[0],
1168                sizeof(secret[0]), rw2dir(!cliser)))
1169        goto err;
1170    if (0 != init_crypto_ctx(&pair->ykp_ctx[cliser], md, aead, secret[1],
1171                sizeof(secret[1]), rw2dir(cliser)))
1172        goto err;
1173
1174    hp->hp_gen_mask = gen_hp_mask_aes;
1175    hp->hp_enc_level = ENC_LEV_CLEAR;
1176    key_len = EVP_AEAD_key_length(aead);
1177    lsquic_qhkdf_expand(md, secret[!cliser], sizeof(secret[0]), PN_LABEL,
1178        PN_LABEL_SZ, key[0], key_len);
1179    lsquic_qhkdf_expand(md, secret[cliser], sizeof(secret[0]), PN_LABEL,
1180        PN_LABEL_SZ, key[1], key_len);
1181    if (enc_sess->esi_flags & ESI_LOG_SECRETS)
1182    {
1183        log_crypto_pair(enc_sess, pair, "handshake");
1184        LSQ_DEBUG("read handshake hp: %s", HEXSTR(key[0], key_len, hexbuf));
1185        LSQ_DEBUG("write handshake hp: %s", HEXSTR(key[1], key_len, hexbuf));
1186    }
1187    for (i = 0; i < 2; ++i)
1188    {
1189        EVP_CIPHER_CTX_init(&hp->hp_u.cipher_ctx[i]);
1190        if (EVP_EncryptInit_ex(&hp->hp_u.cipher_ctx[i], cipher, NULL, key[i], 0))
1191            hp->hp_flags |= 1 << i;
1192        else
1193        {
1194            LSQ_ERROR("%s: cannot initialize cipher %u", __func__, i);
1195            goto err;
1196        }
1197    }
1198
1199    return 0;
1200
1201  err:
1202    cleanup_crypto_ctx(&pair->ykp_ctx[0]);
1203    cleanup_crypto_ctx(&pair->ykp_ctx[1]);
1204    return -1;
1205}
1206
1207
1208static void
1209cleanup_hp (struct header_prot *hp)
1210{
1211    unsigned rw;
1212
1213    if (hp->hp_gen_mask == gen_hp_mask_aes)
1214        for (rw = 0; rw < 2; ++rw)
1215            if (hp->hp_flags & (1 << rw))
1216                (void) EVP_CIPHER_CTX_cleanup(&hp->hp_u.cipher_ctx[rw]);
1217}
1218
1219
1220static void
1221free_handshake_keys (struct enc_sess_iquic *enc_sess)
1222{
1223    struct crypto_ctx_pair *pair;
1224    unsigned i;
1225
1226    if (enc_sess->esi_hsk_pairs)
1227    {
1228        assert(enc_sess->esi_hsk_hps);
1229        for (pair = enc_sess->esi_hsk_pairs; pair <
1230                enc_sess->esi_hsk_pairs + N_HSK_PAIRS; ++pair)
1231        {
1232            cleanup_crypto_ctx(&pair->ykp_ctx[0]);
1233            cleanup_crypto_ctx(&pair->ykp_ctx[1]);
1234        }
1235        free(enc_sess->esi_hsk_pairs);
1236        enc_sess->esi_hsk_pairs = NULL;
1237        for (i = 0; i < N_HSK_PAIRS; ++i)
1238            cleanup_hp(&enc_sess->esi_hsk_hps[i]);
1239        free(enc_sess->esi_hsk_hps);
1240        enc_sess->esi_hsk_hps = NULL;
1241    }
1242    else
1243        assert(!enc_sess->esi_hsk_hps);
1244}
1245
1246
1247static enum ssl_verify_result_t
1248verify_server_cert_callback (SSL *ssl, uint8_t *out_alert)
1249{
1250    struct enc_sess_iquic *enc_sess;
1251    struct stack_st_X509 *chain;
1252    int s;
1253
1254    enc_sess = SSL_get_ex_data(ssl, s_idx);
1255    chain = SSL_get_peer_cert_chain(ssl);
1256    if (!chain)
1257    {
1258        LSQ_ERROR("cannot get peer chain");
1259        return ssl_verify_invalid;
1260    }
1261
1262    EV_LOG_CERT_CHAIN(LSQUIC_LOG_CONN_ID, chain);
1263    if (enc_sess->esi_enpub->enp_verify_cert)
1264    {
1265        s = enc_sess->esi_enpub->enp_verify_cert(
1266                                    enc_sess->esi_enpub->enp_verify_ctx, chain);
1267        return s == 0 ? ssl_verify_ok : ssl_verify_invalid;
1268    }
1269    else
1270        return ssl_verify_ok;
1271}
1272
1273
1274static int
1275iquic_lookup_cert (SSL *ssl, void *arg)
1276{
1277    struct enc_sess_iquic *const enc_sess = arg;
1278    const struct network_path *path;
1279    const char *server_name;
1280    SSL_CTX *ssl_ctx;
1281
1282    server_name = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
1283#ifndef NDEBUG
1284    if (!server_name)
1285        server_name = enc_sess->esi_sni_bypass;
1286#endif
1287    if (!server_name)
1288    {
1289        if (enc_sess->esi_enpub->enp_flags & ENPUB_HTTP)
1290        {
1291            LSQ_DEBUG("SNI is not set, but is required in HTTP/3: "
1292                                                "fail certificate lookup");
1293            return 0;
1294        }
1295        else
1296            LSQ_DEBUG("cert lookup: server name is not set");
1297    }
1298
1299    path = enc_sess->esi_conn->cn_if->ci_get_path(enc_sess->esi_conn, NULL);
1300    ssl_ctx = enc_sess->esi_enpub->enp_lookup_cert(
1301                enc_sess->esi_enpub->enp_cert_lu_ctx, NP_LOCAL_SA(path),
1302                server_name);
1303
1304
1305    if (ssl_ctx)
1306    {
1307        if (SSL_set_SSL_CTX(enc_sess->esi_ssl, ssl_ctx))
1308        {
1309            LSQ_DEBUG("looked up cert for %s", server_name
1310                                                ? server_name : "<no SNI>");
1311            SSL_set_verify(enc_sess->esi_ssl,
1312                                    SSL_CTX_get_verify_mode(ssl_ctx), NULL);
1313            SSL_set_verify_depth(enc_sess->esi_ssl,
1314                                    SSL_CTX_get_verify_depth(ssl_ctx));
1315            SSL_clear_options(enc_sess->esi_ssl,
1316                                    SSL_get_options(enc_sess->esi_ssl));
1317            SSL_set_options(enc_sess->esi_ssl,
1318                            SSL_CTX_get_options(ssl_ctx) & ~SSL_OP_NO_TLSv1_3);
1319            return 1;
1320        }
1321        else
1322        {
1323            LSQ_WARN("cannot set SSL_CTX");
1324            return 0;
1325        }
1326    }
1327    else
1328    {
1329        LSQ_DEBUG("could not look up cert for %s", server_name
1330                                                ? server_name : "<no SNI>");
1331        return 0;
1332    }
1333}
1334
1335
1336static void
1337iquic_esf_set_conn (enc_session_t *enc_session_p, struct lsquic_conn *lconn)
1338{
1339    struct enc_sess_iquic *const enc_sess = enc_session_p;
1340    enc_sess->esi_conn = lconn;
1341    LSQ_DEBUG("updated conn reference");
1342}
1343
1344
1345static int
1346iquic_esfi_init_server (enc_session_t *enc_session_p)
1347{
1348    struct enc_sess_iquic *const enc_sess = enc_session_p;
1349    struct network_path *path;
1350    const struct alpn_map *am;
1351    unsigned quic_ctx_idx;
1352    int transpa_len;
1353    SSL_CTX *ssl_ctx = NULL;
1354    union {
1355        char errbuf[ERR_ERROR_STRING_BUF_LEN];
1356        unsigned char trans_params[sizeof(struct transport_params)
1357#if LSQUIC_TEST_QUANTUM_READINESS
1358            + 4 + lsquic_tp_get_quantum_sz()
1359#endif
1360        ];
1361    } u;
1362
1363    if (enc_sess->esi_enpub->enp_alpn)
1364        enc_sess->esi_alpn = enc_sess->esi_enpub->enp_alpn;
1365    else if (enc_sess->esi_enpub->enp_flags & ENPUB_HTTP)
1366    {
1367        for (am = s_h3_alpns; am < s_h3_alpns + sizeof(s_h3_alpns)
1368                                                / sizeof(s_h3_alpns[0]); ++am)
1369            if (am->version == enc_sess->esi_conn->cn_version)
1370                goto ok;
1371        LSQ_ERROR("version %s has no matching ALPN",
1372                                lsquic_ver2str[enc_sess->esi_conn->cn_version]);
1373        return -1;
1374  ok:   enc_sess->esi_alpn = am->alpn;
1375        LSQ_DEBUG("for QUIC version %s, ALPN is %s",
1376                        lsquic_ver2str[am->version], (char *) am->alpn + 1);
1377    }
1378
1379    path = enc_sess->esi_conn->cn_if->ci_get_path(enc_sess->esi_conn, NULL);
1380    ssl_ctx = enc_sess->esi_enpub->enp_get_ssl_ctx(path->np_peer_ctx,
1381                                                            NP_LOCAL_SA(path));
1382    if (!ssl_ctx)
1383    {
1384        LSQ_ERROR("fetching SSL context associated with peer context failed");
1385        return -1;
1386    }
1387
1388    enc_sess->esi_ssl = SSL_new(ssl_ctx);
1389    if (!enc_sess->esi_ssl)
1390    {
1391        LSQ_ERROR("cannot create SSL object: %s",
1392            ERR_error_string(ERR_get_error(), u.errbuf));
1393        return -1;
1394    }
1395#if BORINGSSL_API_VERSION >= 13
1396    SSL_set_quic_use_legacy_codepoint(enc_sess->esi_ssl,
1397                            enc_sess->esi_conn->cn_version < LSQVER_I001);
1398#endif
1399    if (!(SSL_set_quic_method(enc_sess->esi_ssl, &cry_quic_method)))
1400    {
1401        LSQ_INFO("could not set stream method");
1402        return -1;
1403    }
1404    quic_ctx_idx = enc_sess->esi_conn->cn_version == LSQVER_ID27 ? 0 : 1;
1405    if (!SSL_set_quic_early_data_context(enc_sess->esi_ssl,
1406                        enc_sess->esi_enpub->enp_quic_ctx_buf[quic_ctx_idx],
1407                        enc_sess->esi_enpub->enp_quic_ctx_sz[quic_ctx_idx]))
1408    {
1409        LSQ_INFO("could not set early data context");
1410        return -1;
1411    }
1412
1413    transpa_len = gen_trans_params(enc_sess, u.trans_params,
1414                                                    sizeof(u.trans_params));
1415    if (transpa_len < 0)
1416        return -1;
1417
1418    if (1 != SSL_set_quic_transport_params(enc_sess->esi_ssl, u.trans_params,
1419                                                            transpa_len))
1420    {
1421        LSQ_ERROR("cannot set QUIC transport params: %s",
1422            ERR_error_string(ERR_get_error(), u.errbuf));
1423        return -1;
1424    }
1425
1426    SSL_clear_options(enc_sess->esi_ssl, SSL_OP_NO_TLSv1_3);
1427    if (enc_sess->esi_enpub->enp_lookup_cert)
1428        SSL_set_cert_cb(enc_sess->esi_ssl, iquic_lookup_cert, enc_sess);
1429    SSL_set_ex_data(enc_sess->esi_ssl, s_idx, enc_sess);
1430    SSL_set_accept_state(enc_sess->esi_ssl);
1431    LSQ_DEBUG("initialized server enc session");
1432    return 0;
1433}
1434
1435
1436#if __BYTE_ORDER == __LITTLE_ENDIAN
1437#define WRITE_NUM(var_, val_, ptr_) do {                        \
1438    var_ = (val_);                                              \
1439    var_ = bswap_32(var_);                                      \
1440    memcpy((ptr_), &var_, sizeof(var_));                        \
1441    ptr_ += sizeof(var_);                                       \
1442} while (0)
1443#else
1444#define WRITE_NUM(var_, val_, ptr_) do {                        \
1445    var_ = (val_);                                              \
1446    memcpy((ptr_), &var_, sizeof(var_));                        \
1447    ptr_ += sizeof(var_);                                       \
1448} while (0)
1449#endif
1450
1451
1452/* Return 0 on success, in which case *buf is newly allocated memory and should
1453 * be freed by the caller.
1454 */
1455static int
1456iquic_ssl_sess_to_resume_info (struct enc_sess_iquic *enc_sess, SSL *ssl,
1457                SSL_SESSION *session, unsigned char **bufp, size_t *buf_szp)
1458{
1459    uint32_t num;
1460    unsigned char *p, *buf;
1461    uint8_t *ticket_buf;
1462    size_t ticket_sz;
1463    lsquic_ver_tag_t tag;
1464    const uint8_t *trapa_buf;
1465    size_t trapa_sz, buf_sz;
1466
1467    SSL_get_peer_quic_transport_params(ssl, &trapa_buf, &trapa_sz);
1468    if (!(trapa_buf + trapa_sz))
1469    {
1470        LSQ_WARN("no transport parameters: cannot generate session "
1471                                                    "resumption info");
1472        return -1;
1473    }
1474    if (trapa_sz > UINT32_MAX)
1475    {
1476        LSQ_WARN("trapa size too large: %zu", trapa_sz);
1477        return -1;
1478    }
1479
1480    if (!SSL_SESSION_to_bytes(session, &ticket_buf, &ticket_sz))
1481    {
1482        LSQ_INFO("could not serialize new session");
1483        return -1;
1484    }
1485    if (ticket_sz > UINT32_MAX)
1486    {
1487        LSQ_WARN("ticket size too large: %zu", ticket_sz);
1488        OPENSSL_free(ticket_buf);
1489        return -1;
1490    }
1491
1492    buf_sz = sizeof(tag) + sizeof(uint32_t) + sizeof(uint32_t)
1493                                + ticket_sz + sizeof(uint32_t) + trapa_sz;
1494    buf = malloc(buf_sz);
1495    if (!buf)
1496    {
1497        OPENSSL_free(ticket_buf);
1498        LSQ_INFO("%s: malloc failed", __func__);
1499        return -1;
1500    }
1501
1502    p = buf;
1503    tag = lsquic_ver2tag(enc_sess->esi_conn->cn_version);
1504    memcpy(p, &tag, sizeof(tag));
1505    p += sizeof(tag);
1506
1507    WRITE_NUM(num, SESS_RESUME_VERSION, p);
1508    WRITE_NUM(num, ticket_sz, p);
1509    memcpy(p, ticket_buf, ticket_sz);
1510    p += ticket_sz;
1511    WRITE_NUM(num, trapa_sz, p);
1512    memcpy(p, trapa_buf, trapa_sz);
1513    p += trapa_sz;
1514
1515    assert(buf + buf_sz == p);
1516    OPENSSL_free(ticket_buf);
1517
1518    LSQ_DEBUG("generated %zu bytes of session resumption buffer", buf_sz);
1519
1520    *bufp = buf;
1521    *buf_szp = buf_sz;
1522    return 0;
1523}
1524
1525
1526static int
1527iquic_new_session_cb (SSL *ssl, SSL_SESSION *session)
1528{
1529    struct enc_sess_iquic *enc_sess;
1530    unsigned char *buf;
1531    size_t buf_sz;
1532
1533    enc_sess = SSL_get_ex_data(ssl, s_idx);
1534    assert(enc_sess->esi_enpub->enp_stream_if->on_sess_resume_info);
1535
1536    if (0 == iquic_ssl_sess_to_resume_info(enc_sess, ssl, session, &buf,
1537                                                                    &buf_sz))
1538        enc_sess->esi_enpub->enp_stream_if->on_sess_resume_info(
1539                                            enc_sess->esi_conn, buf, buf_sz);
1540    free(buf);
1541    enc_sess->esi_flags &= ~ESI_WANT_TICKET;
1542    lsquic_alarmset_unset(enc_sess->esi_alset, AL_SESS_TICKET);
1543    return 0;
1544}
1545
1546
1547struct crypto_params
1548{
1549    const EVP_AEAD      *aead;
1550    const EVP_MD        *md;
1551    const EVP_CIPHER    *hp;
1552    gen_hp_mask_f        gen_hp_mask;
1553};
1554
1555
1556static int
1557get_crypto_params (const struct enc_sess_iquic *enc_sess,
1558                    const SSL_CIPHER *cipher, struct crypto_params *params)
1559{
1560    unsigned key_sz, iv_sz;
1561    uint32_t id;
1562
1563    id = SSL_CIPHER_get_id(cipher);
1564
1565    LSQ_DEBUG("Negotiated cipher ID is 0x%"PRIX32, id);
1566
1567    /* RFC 8446, Appendix B.4 */
1568    switch (id)
1569    {
1570    case 0x03000000 | 0x1301:       /* TLS_AES_128_GCM_SHA256 */
1571        params->md          = EVP_sha256();
1572        params->aead        = EVP_aead_aes_128_gcm();
1573        params->hp          = EVP_aes_128_ecb();
1574        params->gen_hp_mask = gen_hp_mask_aes;
1575        break;
1576    case 0x03000000 | 0x1302:       /* TLS_AES_256_GCM_SHA384 */
1577        params->md          = EVP_sha384();
1578        params->aead        = EVP_aead_aes_256_gcm();
1579        params->hp          = EVP_aes_256_ecb();
1580        params->gen_hp_mask = gen_hp_mask_aes;
1581        break;
1582    case 0x03000000 | 0x1303:       /* TLS_CHACHA20_POLY1305_SHA256 */
1583        params->md          = EVP_sha256();
1584        params->aead        = EVP_aead_chacha20_poly1305();
1585        params->hp          = NULL;
1586        params->gen_hp_mask = gen_hp_mask_chacha20;
1587        break;
1588    default:
1589        /* TLS_AES_128_CCM_SHA256 and TLS_AES_128_CCM_8_SHA256 are not
1590         * supported by BoringSSL (grep for \b0x130[45]\b).
1591         */
1592        LSQ_DEBUG("unsupported cipher 0x%"PRIX32, id);
1593        return -1;
1594    }
1595
1596    key_sz = EVP_AEAD_key_length(params->aead);
1597    if (key_sz > EVP_MAX_KEY_LENGTH)
1598    {
1599        LSQ_DEBUG("key size %u is too large", key_sz);
1600        return -1;
1601    }
1602
1603    iv_sz = EVP_AEAD_nonce_length(params->aead);
1604    if (iv_sz < 8)
1605        iv_sz = 8;  /* [draft-ietf-quic-tls-11], Section 5.3 */
1606    if (iv_sz > EVP_MAX_IV_LENGTH)
1607    {
1608        LSQ_DEBUG("iv size %u is too large", iv_sz);
1609        return -1;
1610    }
1611
1612    return 0;
1613}
1614
1615
1616/* [draft-ietf-quic-transport-31] Section 7.4.1:
1617 " If 0-RTT data is accepted by the server, the server MUST NOT reduce
1618 " any limits or alter any values that might be violated by the client
1619 " with its 0-RTT data.  In particular, a server that accepts 0-RTT data
1620 " MUST NOT set values for the following parameters (Section 18.2) that
1621 " are smaller than the remembered value of the parameters.
1622 "
1623 " *  active_connection_id_limit
1624 "
1625 " *  initial_max_data
1626 "
1627 " *  initial_max_stream_data_bidi_local
1628 "
1629 " *  initial_max_stream_data_bidi_remote
1630 "
1631 " *  initial_max_stream_data_uni
1632 "
1633 " *  initial_max_streams_bidi
1634 "
1635 " *  initial_max_streams_uni
1636 */
1637#define REDUCTION_PROHIBITED_TPS                                     (0 \
1638    | (1 << TPI_ACTIVE_CONNECTION_ID_LIMIT)                             \
1639    | (1 << TPI_INIT_MAX_DATA)                                          \
1640    | (1 << TPI_INIT_MAX_STREAMS_UNI)                                   \
1641    | (1 << TPI_INIT_MAX_STREAMS_BIDI)                                  \
1642    | (1 << TPI_INIT_MAX_STREAM_DATA_BIDI_LOCAL)                        \
1643    | (1 << TPI_INIT_MAX_STREAM_DATA_BIDI_REMOTE)                       \
1644    | (1 << TPI_INIT_MAX_STREAM_DATA_UNI)                               \
1645)
1646
1647
1648static int
1649check_server_tps_for_violations (const struct enc_sess_iquic *enc_sess,
1650                            const struct transport_params *params_0rtt,
1651                            const struct transport_params *new_params)
1652{
1653    enum transport_param_id tpi;
1654
1655    for (tpi = 0; tpi <= MAX_NUMERIC_TPI; ++tpi)
1656        if ((1 << tpi) & REDUCTION_PROHIBITED_TPS)
1657            if (new_params->tp_numerics[tpi] < params_0rtt->tp_numerics[tpi])
1658            {
1659                LSQ_INFO("server's new TP %s decreased in value from %"PRIu64
1660                    " to %"PRIu64, lsquic_tpi2str[tpi],
1661                        params_0rtt->tp_numerics[tpi],
1662                        new_params->tp_numerics[tpi]);
1663                return -1;
1664            }
1665
1666    LSQ_DEBUG("server's new transport parameters do not violate save 0-RTT "
1667        "parameters");
1668    return 0;
1669}
1670
1671
1672static int
1673get_peer_transport_params (struct enc_sess_iquic *enc_sess)
1674{
1675    struct transport_params *const trans_params = &enc_sess->esi_peer_tp;
1676    struct transport_params params_0rtt;
1677    const uint8_t *params_buf;
1678    size_t bufsz;
1679    char *params_str;
1680    const enum lsquic_version version = enc_sess->esi_conn->cn_version;
1681    int have_0rtt_tp;
1682
1683    SSL_get_peer_quic_transport_params(enc_sess->esi_ssl, &params_buf, &bufsz);
1684    if (!params_buf)
1685    {
1686        LSQ_DEBUG("no peer transport parameters");
1687        return -1;
1688    }
1689
1690    have_0rtt_tp = !!(enc_sess->esi_flags & ESI_HAVE_0RTT_TP);
1691    if (have_0rtt_tp)
1692    {
1693        params_0rtt = enc_sess->esi_peer_tp;
1694        enc_sess->esi_flags &= ~ESI_HAVE_0RTT_TP;
1695    }
1696
1697    LSQ_DEBUG("have peer transport parameters (%zu bytes)", bufsz);
1698    if (LSQ_LOG_ENABLED(LSQ_LOG_DEBUG))
1699    {
1700        params_str = lsquic_mm_get_4k(&enc_sess->esi_enpub->enp_mm);
1701        if (params_str)
1702        {
1703            lsquic_hexdump(params_buf, bufsz, params_str, 0x1000);
1704            LSQ_DEBUG("transport parameters (%zd bytes):\n%s", bufsz,
1705                                                            params_str);
1706            lsquic_mm_put_4k(&enc_sess->esi_enpub->enp_mm, params_str);
1707        }
1708    }
1709    if (0 > (version == LSQVER_ID27 ? lsquic_tp_decode_27
1710                : lsquic_tp_decode)(params_buf, bufsz,
1711                            !(enc_sess->esi_flags & ESI_SERVER),
1712                                                trans_params))
1713    {
1714        if (LSQ_LOG_ENABLED(LSQ_LOG_DEBUG))
1715        {
1716            params_str = lsquic_mm_get_4k(&enc_sess->esi_enpub->enp_mm);
1717            if (params_str)
1718            {
1719                lsquic_hexdump(params_buf, bufsz, params_str, 0x1000);
1720                LSQ_DEBUG("could not parse peer transport parameters "
1721                    "(%zd bytes):\n%s", bufsz, params_str);
1722                lsquic_mm_put_4k(&enc_sess->esi_enpub->enp_mm, params_str);
1723            }
1724            else
1725                LSQ_DEBUG("could not parse peer transport parameters "
1726                    "(%zd bytes)", bufsz);
1727        }
1728        return -1;
1729    }
1730
1731    if (have_0rtt_tp && 0 != check_server_tps_for_violations(enc_sess,
1732                                                &params_0rtt, trans_params))
1733        return -1;
1734
1735    const lsquic_cid_t *const cids[LAST_TPI + 1] = {
1736        [TP_CID_IDX(TPI_ORIGINAL_DEST_CID)]  = enc_sess->esi_flags & ESI_ODCID ? &enc_sess->esi_odcid : NULL,
1737        [TP_CID_IDX(TPI_RETRY_SOURCE_CID)]   = enc_sess->esi_flags & ESI_RSCID ? &enc_sess->esi_rscid : NULL,
1738        [TP_CID_IDX(TPI_INITIAL_SOURCE_CID)] = enc_sess->esi_flags & ESI_ISCID ? &enc_sess->esi_iscid : NULL,
1739    };
1740
1741    unsigned must_have, must_not_have = 0;
1742    if (version > LSQVER_ID27)
1743    {
1744        must_have = 1 << TPI_INITIAL_SOURCE_CID;
1745        if (enc_sess->esi_flags & ESI_SERVER)
1746            must_not_have |= 1 << TPI_ORIGINAL_DEST_CID;
1747        else
1748            must_have |= 1 << TPI_ORIGINAL_DEST_CID;
1749        if ((enc_sess->esi_flags & (ESI_RETRY|ESI_SERVER)) == ESI_RETRY)
1750            must_have |= 1 << TPI_RETRY_SOURCE_CID;
1751        else
1752            must_not_have |= 1 << TPI_RETRY_SOURCE_CID;
1753    }
1754    else if ((enc_sess->esi_flags & (ESI_RETRY|ESI_SERVER)) == ESI_RETRY)
1755        must_have = 1 << TPI_ORIGINAL_DEST_CID;
1756    else
1757        must_have = 0;
1758
1759    enum transport_param_id tpi;
1760    for (tpi = FIRST_TP_CID; tpi <= LAST_TP_CID; ++tpi)
1761    {
1762        if (!(must_have & (1 << tpi)))
1763            continue;
1764        if (!(trans_params->tp_set & (1 << tpi)))
1765        {
1766            LSQ_DEBUG("server did not produce %s", lsquic_tpi2str[tpi]);
1767            return -1;
1768        }
1769        if (!cids[TP_CID_IDX(tpi)])
1770        {
1771            LSQ_WARN("do not have CID %s for checking",
1772                                                    lsquic_tpi2str[tpi]);
1773            return -1;
1774        }
1775        if (LSQUIC_CIDS_EQ(cids[TP_CID_IDX(tpi)],
1776                                &trans_params->tp_cids[TP_CID_IDX(tpi)]))
1777            LSQ_DEBUG("%s values match", lsquic_tpi2str[tpi]);
1778        else
1779        {
1780            if (LSQ_LOG_ENABLED(LSQ_LOG_DEBUG))
1781            {
1782                char cidbuf[2][MAX_CID_LEN * 2 + 1];
1783                LSQ_DEBUG("server provided %s %"CID_FMT" that does not "
1784                    "match ours %"CID_FMT, lsquic_tpi2str[tpi],
1785                    CID_BITS_B(&trans_params->tp_cids[TP_CID_IDX(tpi)],
1786                                                            cidbuf[0]),
1787                    CID_BITS_B(cids[TP_CID_IDX(tpi)], cidbuf[1]));
1788            }
1789            return -1;
1790        }
1791    }
1792
1793    for (tpi = FIRST_TP_CID; tpi <= LAST_TP_CID; ++tpi)
1794        if (must_not_have & (1 << tpi) & trans_params->tp_set)
1795        {
1796            LSQ_DEBUG("server transport parameters unexpectedly contain %s",
1797                                        lsquic_tpi2str[tpi]);
1798            return -1;
1799        }
1800
1801    if ((trans_params->tp_set & (1 << TPI_LOSS_BITS))
1802                            && enc_sess->esi_enpub->enp_settings.es_ql_bits)
1803    {
1804        const unsigned our_loss_bits
1805            = enc_sess->esi_enpub->enp_settings.es_ql_bits - 1;
1806        switch ((our_loss_bits << 1) | trans_params->tp_loss_bits)
1807        {
1808        case    (0             << 1) | 0:
1809            LSQ_DEBUG("both sides only tolerate QL bits: don't enable them");
1810            break;
1811        case    (0             << 1) | 1:
1812            LSQ_DEBUG("peer sends QL bits, we receive them");
1813            enc_sess->esi_flags |= ESI_RECV_QL_BITS;
1814            break;
1815        case    (1             << 1) | 0:
1816            LSQ_DEBUG("we send QL bits, peer receives them");
1817            enc_sess->esi_flags |= ESI_SEND_QL_BITS;
1818            break;
1819        default/*1             << 1) | 1*/:
1820            LSQ_DEBUG("enable sending and receiving QL bits");
1821            enc_sess->esi_flags |= ESI_RECV_QL_BITS;
1822            enc_sess->esi_flags |= ESI_SEND_QL_BITS;
1823            break;
1824        }
1825    }
1826    else
1827        LSQ_DEBUG("no QL bits");
1828
1829    if (trans_params->tp_set & (1 << TPI_GREASE_QUIC_BIT))
1830    {
1831        if (enc_sess->esi_enpub->enp_settings.es_grease_quic_bit)
1832        {
1833            LSQ_DEBUG("will grease the QUIC bit");
1834            enc_sess->esi_grease = ~QUIC_BIT;
1835        }
1836        else
1837            LSQ_DEBUG("greasing turned off: won't grease the QUIC bit");
1838    }
1839
1840    if (enc_sess->esi_enpub->enp_settings.es_check_tp_sanity
1841        /* We only care (and know) about HTTP/3.  Other protocols may have
1842         * their own limitations.  The most generic way to do this would be
1843         * to factor out transport parameter sanity check into a callback.
1844         */
1845        && enc_sess->esi_alpn && enc_sess->esi_alpn[0] >= 2
1846        && enc_sess->esi_alpn[1] == 'h'
1847        && enc_sess->esi_alpn[2] == '3')
1848    {
1849        const enum transport_param_id stream_data = enc_sess->esi_flags
1850            & ESI_SERVER ? TPI_INIT_MAX_STREAM_DATA_BIDI_LOCAL
1851                         : TPI_INIT_MAX_STREAM_DATA_BIDI_REMOTE;
1852        if (!((trans_params->tp_set & (1 << stream_data))
1853                        && trans_params->tp_numerics[stream_data] >= 0x1000))
1854        {
1855            LSQ_INFO("peer transport parameters: %s=%"PRIu64" does not pass "
1856                "sanity check", lsquic_tpi2str[stream_data],
1857                trans_params->tp_numerics[stream_data]);
1858            return -1;
1859        }
1860        if (!((trans_params->tp_set & (1 << TPI_INIT_MAX_DATA))
1861                    && trans_params->tp_numerics[TPI_INIT_MAX_DATA] >= 0x1000))
1862        {
1863            LSQ_INFO("peer transport parameters: %s=%"PRIu64" does not pass "
1864                "sanity check", lsquic_tpi2str[TPI_INIT_MAX_DATA],
1865                trans_params->tp_numerics[TPI_INIT_MAX_DATA]);
1866            return -1;
1867        }
1868    }
1869
1870    return 0;
1871}
1872
1873
1874static int
1875maybe_get_peer_transport_params (struct enc_sess_iquic *enc_sess)
1876{
1877    int s;
1878
1879    if (enc_sess->esi_flags & ESI_HAVE_PEER_TP)
1880        return 0;
1881
1882    s = get_peer_transport_params(enc_sess);
1883    if (s == 0)
1884        enc_sess->esi_flags |= ESI_HAVE_PEER_TP;
1885
1886    return s;
1887}
1888
1889
1890enum iquic_handshake_status {
1891    IHS_WANT_READ,
1892    IHS_WANT_WRITE,
1893    IHS_WANT_RW,
1894    IHS_STOP,
1895};
1896
1897
1898static enum iquic_handshake_status
1899iquic_esfi_handshake (struct enc_sess_iquic *enc_sess)
1900{
1901    int s, err;
1902    enum lsquic_hsk_status hsk_status;
1903    char errbuf[ERR_ERROR_STRING_BUF_LEN];
1904
1905    s = SSL_do_handshake(enc_sess->esi_ssl);
1906    if (s <= 0)
1907    {
1908        err = SSL_get_error(enc_sess->esi_ssl, s);
1909        switch (err)
1910        {
1911        case SSL_ERROR_WANT_READ:
1912            LSQ_DEBUG("retry read");
1913            return IHS_WANT_READ;
1914        case SSL_ERROR_WANT_WRITE:
1915            LSQ_DEBUG("retry write");
1916            return IHS_WANT_WRITE;
1917        case SSL_ERROR_EARLY_DATA_REJECTED:
1918            LSQ_DEBUG("early data rejected: reset");
1919            SSL_reset_early_data_reject(enc_sess->esi_ssl);
1920            if (enc_sess->esi_conn->cn_if->ci_early_data_failed)
1921                enc_sess->esi_conn->cn_if->ci_early_data_failed(
1922                                                        enc_sess->esi_conn);
1923            return IHS_WANT_RW;
1924            /* fall through */
1925        default:
1926            LSQ_DEBUG("handshake: %s", ERR_error_string(err, errbuf));
1927            hsk_status = LSQ_HSK_FAIL;
1928            goto err;
1929        }
1930    }
1931
1932
1933    if (SSL_in_early_data(enc_sess->esi_ssl))
1934    {
1935        LSQ_DEBUG("in early data");
1936        if (enc_sess->esi_flags & ESI_SERVER)
1937            LSQ_DEBUG("TODO");
1938        else
1939            return IHS_WANT_READ;
1940    }
1941
1942    hsk_status = LSQ_HSK_OK;
1943    LSQ_DEBUG("handshake reported complete");
1944    EV_LOG_HSK_COMPLETED(LSQUIC_LOG_CONN_ID);
1945    /* The ESI_USE_SSL_TICKET flag indicates if the client attempted session
1946     * resumption.  If the handshake is complete, and the client attempted
1947     * session resumption, it must have succeeded.
1948     */
1949    if (enc_sess->esi_flags & ESI_USE_SSL_TICKET)
1950    {
1951        hsk_status = LSQ_HSK_RESUMED_OK;
1952        EV_LOG_SESSION_RESUMPTION(LSQUIC_LOG_CONN_ID);
1953    }
1954
1955    if (0 != maybe_get_peer_transport_params(enc_sess))
1956    {
1957        hsk_status = LSQ_HSK_FAIL;
1958        goto err;
1959    }
1960
1961    enc_sess->esi_flags |= ESI_HANDSHAKE_OK;
1962    enc_sess->esi_conn->cn_if->ci_hsk_done(enc_sess->esi_conn, hsk_status);
1963
1964    return IHS_STOP;    /* XXX: what else can come on the crypto stream? */
1965
1966  err:
1967    LSQ_DEBUG("handshake failed");
1968    enc_sess->esi_conn->cn_if->ci_hsk_done(enc_sess->esi_conn, hsk_status);
1969    return IHS_STOP;
1970}
1971
1972
1973static enum iquic_handshake_status
1974iquic_esfi_post_handshake (struct enc_sess_iquic *enc_sess)
1975{
1976    int s;
1977
1978    s = SSL_process_quic_post_handshake(enc_sess->esi_ssl);
1979    LSQ_DEBUG("SSL_process_quic_post_handshake() returned %d", s);
1980    if (s == 1)
1981        return IHS_WANT_READ;
1982    else
1983    {
1984        enc_sess->esi_conn->cn_if->ci_internal_error(enc_sess->esi_conn,
1985                                        "post-handshake error, code %d", s);
1986        return IHS_STOP;
1987    }
1988}
1989
1990
1991static struct transport_params *
1992iquic_esfi_get_peer_transport_params (enc_session_t *enc_session_p)
1993{
1994    struct enc_sess_iquic *const enc_sess = enc_session_p;
1995
1996    if (enc_sess->esi_flags & ESI_HAVE_0RTT_TP)
1997        return &enc_sess->esi_peer_tp;
1998    else if (0 == maybe_get_peer_transport_params(enc_sess))
1999        return &enc_sess->esi_peer_tp;
2000    else
2001        return NULL;
2002}
2003
2004
2005static void
2006iquic_esfi_destroy (enc_session_t *enc_session_p)
2007{
2008    struct enc_sess_iquic *const enc_sess = enc_session_p;
2009    struct frab_list *fral;
2010    LSQ_DEBUG("iquic_esfi_destroy");
2011
2012    for (fral = enc_sess->esi_frals; fral < enc_sess->esi_frals
2013            + sizeof(enc_sess->esi_frals) / sizeof(enc_sess->esi_frals[0]);
2014                ++fral)
2015        lsquic_frab_list_cleanup(fral);
2016    if (enc_sess->esi_ssl)
2017        SSL_free(enc_sess->esi_ssl);
2018
2019    free_handshake_keys(enc_sess);
2020    cleanup_hp(&enc_sess->esi_hp);
2021
2022    free(enc_sess);
2023}
2024
2025
2026/* See [draft-ietf-quic-tls-14], Section 4 */
2027static const enum enc_level hety2el[] =
2028{
2029    [HETY_NOT_SET]   = ENC_LEV_FORW,
2030    [HETY_VERNEG]    = 0,
2031    [HETY_INITIAL]   = ENC_LEV_CLEAR,
2032    [HETY_RETRY]     = 0,
2033    [HETY_HANDSHAKE] = ENC_LEV_INIT,
2034    [HETY_0RTT]      = ENC_LEV_EARLY,
2035};
2036
2037
2038static const enum enc_level pns2enc_level[2][N_PNS] =
2039{
2040    [0] = {
2041        [PNS_INIT]  = ENC_LEV_CLEAR,
2042        [PNS_HSK]   = ENC_LEV_INIT,
2043        [PNS_APP]   = ENC_LEV_EARLY,
2044    },
2045    [1] = {
2046        [PNS_INIT]  = ENC_LEV_CLEAR,
2047        [PNS_HSK]   = ENC_LEV_INIT,
2048        [PNS_APP]   = ENC_LEV_FORW,
2049    },
2050};
2051
2052
2053static enum enc_packout
2054iquic_esf_encrypt_packet (enc_session_t *enc_session_p,
2055    const struct lsquic_engine_public *enpub, struct lsquic_conn *lconn_UNUSED,
2056    struct lsquic_packet_out *packet_out)
2057{
2058    struct enc_sess_iquic *const enc_sess = enc_session_p;
2059    struct lsquic_conn *const lconn = enc_sess->esi_conn;
2060    unsigned char *dst;
2061    const struct crypto_ctx_pair *pair;
2062    const struct crypto_ctx *crypto_ctx;
2063    struct header_prot *hp;
2064    enum enc_level enc_level;
2065    unsigned char nonce_buf[ sizeof(crypto_ctx->yk_iv_buf) + 8 ];
2066    unsigned char *nonce, *begin_xor;
2067    lsquic_packno_t packno;
2068    size_t out_sz, dst_sz;
2069    int header_sz;
2070    int ipv6;
2071    unsigned packno_off, packno_len;
2072    enum packnum_space pns;
2073    char errbuf[ERR_ERROR_STRING_BUF_LEN];
2074
2075    pns = lsquic_packet_out_pns(packet_out);
2076    enc_level = pns2enc_level[ enc_sess->esi_have_forw ][ pns ];
2077
2078    if (enc_level == ENC_LEV_FORW)
2079    {
2080        pair = &enc_sess->esi_pairs[ enc_sess->esi_key_phase ];
2081        crypto_ctx = &pair->ykp_ctx[ 1 ];
2082        hp = &enc_sess->esi_hp;
2083    }
2084    else if (enc_sess->esi_hsk_pairs)
2085    {
2086        pair = &enc_sess->esi_hsk_pairs[ enc_level ];
2087        crypto_ctx = &pair->ykp_ctx[ 1 ];
2088        hp = &enc_sess->esi_hsk_hps[ enc_level ];
2089    }
2090    else
2091    {
2092        LSQ_WARN("no keys for encryption level %s",
2093                                            lsquic_enclev2str[enc_level]);
2094        return ENCPA_BADCRYPT;
2095    }
2096
2097    if (UNLIKELY(0 == (crypto_ctx->yk_flags & YK_INITED)))
2098    {
2099        LSQ_WARN("encrypt crypto context at level %s not initialized",
2100                                            lsquic_enclev2str[enc_level]);
2101        return ENCPA_BADCRYPT;
2102    }
2103
2104    if (packet_out->po_data_sz < 3)
2105    {
2106        /* [draft-ietf-quic-tls-20] Section 5.4.2 */
2107        enum packno_bits bits = lsquic_packet_out_packno_bits(packet_out);
2108        unsigned len = iquic_packno_bits2len(bits);
2109        if (packet_out->po_data_sz + len < 4)
2110        {
2111            len = 4 - packet_out->po_data_sz - len;
2112            memset(packet_out->po_data + packet_out->po_data_sz, 0, len);
2113            packet_out->po_data_sz += len;
2114            packet_out->po_frame_types |= QUIC_FTBIT_PADDING;
2115            LSQ_DEBUG("padded packet %"PRIu64" with %u bytes of PADDING",
2116                packet_out->po_packno, len);
2117        }
2118    }
2119
2120    dst_sz = lconn->cn_pf->pf_packout_size(lconn, packet_out);
2121    ipv6 = NP_IS_IPv6(packet_out->po_path);
2122    dst = enpub->enp_pmi->pmi_allocate(enpub->enp_pmi_ctx,
2123            packet_out->po_path->np_peer_ctx, lconn->cn_conn_ctx, dst_sz, ipv6);
2124    if (!dst)
2125    {
2126        LSQ_DEBUG("could not allocate memory for outgoing packet of size %zd",
2127                                                                        dst_sz);
2128        return ENCPA_NOMEM;
2129    }
2130
2131    /* Align nonce so we can perform XOR safely in one shot: */
2132    begin_xor = nonce_buf + sizeof(nonce_buf) - 8;
2133    begin_xor = (unsigned char *) ((uintptr_t) begin_xor & ~0x7);
2134    nonce = begin_xor - crypto_ctx->yk_iv_sz + 8;
2135    memcpy(nonce, crypto_ctx->yk_iv_buf, crypto_ctx->yk_iv_sz);
2136    packno = packet_out->po_packno;
2137    if (s_log_seal_and_open)
2138        LSQ_DEBUG("seal: iv: %s; packno: 0x%"PRIX64,
2139            HEXSTR(crypto_ctx->yk_iv_buf, crypto_ctx->yk_iv_sz, s_str), packno);
2140#if __BYTE_ORDER == __LITTLE_ENDIAN
2141    packno = bswap_64(packno);
2142#endif
2143    *((uint64_t *) begin_xor) ^= packno;
2144
2145    header_sz = lconn->cn_pf->pf_gen_reg_pkt_header(lconn, packet_out, dst,
2146                                            dst_sz, &packno_off, &packno_len);
2147    if (header_sz < 0)
2148        goto err;
2149    if (enc_level == ENC_LEV_FORW)
2150        dst[0] |= enc_sess->esi_key_phase << 2;
2151    dst[0] &= enc_sess->esi_grease | packet_out->po_path->np_dcid.idbuf[0];
2152
2153    if (s_log_seal_and_open)
2154    {
2155        LSQ_DEBUG("seal: nonce (%u bytes): %s", crypto_ctx->yk_iv_sz,
2156            HEXSTR(nonce, crypto_ctx->yk_iv_sz, s_str));
2157        LSQ_DEBUG("seal: ad (%u bytes): %s", header_sz,
2158            HEXSTR(dst, header_sz, s_str));
2159        LSQ_DEBUG("seal: in (%u bytes): %s", packet_out->po_data_sz,
2160            HEXSTR(packet_out->po_data, packet_out->po_data_sz, s_str));
2161    }
2162    if (!EVP_AEAD_CTX_seal(&crypto_ctx->yk_aead_ctx, dst + header_sz, &out_sz,
2163                dst_sz - header_sz, nonce, crypto_ctx->yk_iv_sz, packet_out->po_data,
2164                packet_out->po_data_sz, dst, header_sz))
2165    {
2166        LSQ_WARN("cannot seal packet #%"PRIu64": %s", packet_out->po_packno,
2167            ERR_error_string(ERR_get_error(), errbuf));
2168        goto err;
2169    }
2170    assert(out_sz == dst_sz - header_sz);
2171
2172#ifndef NDEBUG
2173    const unsigned sample_off = packno_off + 4;
2174    assert(sample_off + IQUIC_TAG_LEN <= dst_sz);
2175#endif
2176
2177    packet_out->po_enc_data    = dst;
2178    packet_out->po_enc_data_sz = dst_sz;
2179    packet_out->po_sent_sz     = dst_sz;
2180    packet_out->po_flags &= ~PO_IPv6;
2181    packet_out->po_flags |= PO_ENCRYPTED|PO_SENT_SZ|(ipv6 << POIPv6_SHIFT);
2182    packet_out->po_dcid_len = packet_out->po_path->np_dcid.len;
2183    lsquic_packet_out_set_enc_level(packet_out, enc_level);
2184    lsquic_packet_out_set_kp(packet_out, enc_sess->esi_key_phase);
2185
2186    if (enc_level == ENC_LEV_FORW && hp->hp_gen_mask != gen_hp_mask_chacha20)
2187        apply_hp_batch(enc_sess, hp, packet_out, packno_off, packno_len);
2188    else
2189        apply_hp_immediately(enc_sess, hp, packet_out, packno_off, packno_len);
2190
2191    return ENCPA_OK;
2192
2193  err:
2194    enpub->enp_pmi->pmi_return(enpub->enp_pmi_ctx,
2195                                packet_out->po_path->np_peer_ctx, dst, ipv6);
2196    return ENCPA_BADCRYPT;
2197}
2198
2199
2200static void
2201iquic_esf_flush_encryption (enc_session_t *enc_session_p)
2202{
2203    struct enc_sess_iquic *const enc_sess = enc_session_p;
2204
2205    if (enc_sess->esi_hp_batch_idx)
2206    {
2207        LSQ_DEBUG("flush header protection application, count: %u",
2208            enc_sess->esi_hp_batch_idx);
2209        flush_hp_batch(enc_sess);
2210    }
2211}
2212
2213
2214static struct ku_label
2215{
2216    const char *str;
2217    uint8_t     len;
2218}
2219
2220
2221select_ku_label (const struct enc_sess_iquic *enc_sess)
2222{
2223    return (struct ku_label) { "quic ku", 7, };
2224}
2225
2226
2227static enum dec_packin
2228iquic_esf_decrypt_packet (enc_session_t *enc_session_p,
2229        struct lsquic_engine_public *enpub, const struct lsquic_conn *lconn,
2230        struct lsquic_packet_in *packet_in)
2231{
2232    struct enc_sess_iquic *const enc_sess = enc_session_p;
2233    unsigned char *dst;
2234    struct crypto_ctx_pair *pair;
2235    struct header_prot *hp;
2236    struct crypto_ctx *crypto_ctx = NULL;
2237    unsigned char nonce_buf[ sizeof(crypto_ctx->yk_iv_buf) + 8 ];
2238    unsigned char *nonce, *begin_xor;
2239    unsigned sample_off, packno_len, key_phase;
2240    enum enc_level enc_level;
2241    enum packnum_space pns;
2242    lsquic_packno_t packno;
2243    size_t out_sz;
2244    enum dec_packin dec_packin;
2245    int s;
2246    const size_t dst_sz = packet_in->pi_data_sz;
2247    unsigned char new_secret[EVP_MAX_KEY_LENGTH];
2248    struct crypto_ctx crypto_ctx_buf;
2249    char secret_str[EVP_MAX_KEY_LENGTH * 2 + 1];
2250    char errbuf[ERR_ERROR_STRING_BUF_LEN];
2251
2252    dst = lsquic_mm_get_packet_in_buf(&enpub->enp_mm, dst_sz);
2253    if (!dst)
2254    {
2255        LSQ_WARN("cannot allocate memory to copy incoming packet data");
2256        dec_packin = DECPI_NOMEM;
2257        goto err;
2258    }
2259
2260    enc_level = hety2el[packet_in->pi_header_type];
2261    if (enc_level == ENC_LEV_FORW)
2262        hp = &enc_sess->esi_hp;
2263    else if (enc_sess->esi_hsk_pairs)
2264        hp = &enc_sess->esi_hsk_hps[ enc_level ];
2265    else
2266        hp = NULL;
2267
2268    if (UNLIKELY(!(hp && header_prot_inited(hp, 0))))
2269    {
2270        LSQ_DEBUG("header protection for level %u not initialized yet",
2271                                                                enc_level);
2272        dec_packin = DECPI_NOT_YET;
2273        goto err;
2274    }
2275
2276    /* Decrypt packet number.  After this operation, packet_in is adjusted:
2277     * the packet number becomes part of the header.
2278     */
2279    sample_off = packet_in->pi_header_sz + 4;
2280    if (sample_off + IQUIC_TAG_LEN > packet_in->pi_data_sz)
2281    {
2282        LSQ_INFO("packet data is too short: %hu bytes",
2283                                                packet_in->pi_data_sz);
2284        dec_packin = DECPI_TOO_SHORT;
2285        goto err;
2286    }
2287    memcpy(dst, packet_in->pi_data, sample_off);
2288    packet_in->pi_packno =
2289    packno = strip_hp(enc_sess, hp,
2290        packet_in->pi_data + sample_off,
2291        dst, packet_in->pi_header_sz, &packno_len);
2292
2293    if (enc_level == ENC_LEV_FORW)
2294    {
2295        key_phase = (dst[0] & 0x04) > 0;
2296        pair = &enc_sess->esi_pairs[ key_phase ];
2297        if (key_phase == enc_sess->esi_key_phase)
2298        {
2299            crypto_ctx = &pair->ykp_ctx[ 0 ];
2300            /* Checked by header_prot_inited() above */
2301            assert(crypto_ctx->yk_flags & YK_INITED);
2302        }
2303        else if (!is_valid_packno(
2304                        enc_sess->esi_pairs[enc_sess->esi_key_phase].ykp_thresh)
2305                || packet_in->pi_packno
2306                    > enc_sess->esi_pairs[enc_sess->esi_key_phase].ykp_thresh)
2307        {
2308            const struct ku_label kl = select_ku_label(enc_sess);
2309            lsquic_qhkdf_expand(enc_sess->esi_md,
2310                enc_sess->esi_traffic_secrets[0], enc_sess->esi_trasec_sz,
2311                kl.str, kl.len, new_secret, enc_sess->esi_trasec_sz);
2312            if (enc_sess->esi_flags & ESI_LOG_SECRETS)
2313                LSQ_DEBUG("key phase changed to %u, will try decrypting using "
2314                    "new secret %s", key_phase, HEXSTR(new_secret,
2315                    enc_sess->esi_trasec_sz, secret_str));
2316            else
2317                LSQ_DEBUG("key phase changed to %u, will try decrypting using "
2318                    "new secret", key_phase);
2319            crypto_ctx = &crypto_ctx_buf;
2320            crypto_ctx->yk_flags = 0;
2321            s = init_crypto_ctx(crypto_ctx, enc_sess->esi_md,
2322                        enc_sess->esi_aead, new_secret, enc_sess->esi_trasec_sz,
2323                        evp_aead_open);
2324            if (s != 0)
2325            {
2326                LSQ_ERROR("could not init open crypto ctx (key phase)");
2327                dec_packin = DECPI_BADCRYPT;
2328                goto err;
2329            }
2330        }
2331        else
2332        {
2333            crypto_ctx = &pair->ykp_ctx[ 0 ];
2334            if (UNLIKELY(0 == (crypto_ctx->yk_flags & YK_INITED)))
2335            {
2336                LSQ_DEBUG("supposedly older context is not initialized (key "
2337                    "phase: %u)", key_phase);
2338                dec_packin = DECPI_BADCRYPT;
2339                goto err;
2340            }
2341        }
2342    }
2343    else
2344    {
2345        key_phase = 0;
2346        assert(enc_sess->esi_hsk_pairs);
2347        pair = &enc_sess->esi_hsk_pairs[ enc_level ];
2348        crypto_ctx = &pair->ykp_ctx[ 0 ];
2349        if (UNLIKELY(0 == (crypto_ctx->yk_flags & YK_INITED)))
2350        {
2351            LSQ_WARN("decrypt crypto context at level %s not initialized",
2352                                                    lsquic_enclev2str[enc_level]);
2353            dec_packin = DECPI_BADCRYPT;
2354            goto err;
2355        }
2356    }
2357
2358    if (s_log_seal_and_open)
2359        LSQ_DEBUG("open: iv: %s; packno: 0x%"PRIX64,
2360            HEXSTR(crypto_ctx->yk_iv_buf, crypto_ctx->yk_iv_sz, s_str), packno);
2361    /* Align nonce so we can perform XOR safely in one shot: */
2362    begin_xor = nonce_buf + sizeof(nonce_buf) - 8;
2363    begin_xor = (unsigned char *) ((uintptr_t) begin_xor & ~0x7);
2364    nonce = begin_xor - crypto_ctx->yk_iv_sz + 8;
2365    memcpy(nonce, crypto_ctx->yk_iv_buf, crypto_ctx->yk_iv_sz);
2366#if __BYTE_ORDER == __LITTLE_ENDIAN
2367    packno = bswap_64(packno);
2368#endif
2369    *((uint64_t *) begin_xor) ^= packno;
2370
2371    packet_in->pi_header_sz += packno_len;
2372
2373    if (s_log_seal_and_open)
2374    {
2375        LSQ_DEBUG("open: nonce (%u bytes): %s", crypto_ctx->yk_iv_sz,
2376            HEXSTR(nonce, crypto_ctx->yk_iv_sz, s_str));
2377        LSQ_DEBUG("open: ad (%u bytes): %s", packet_in->pi_header_sz,
2378            HEXSTR(dst, packet_in->pi_header_sz, s_str));
2379        LSQ_DEBUG("open: in (%u bytes): %s", packet_in->pi_data_sz
2380            - packet_in->pi_header_sz, HEXSTR(packet_in->pi_data
2381            + packet_in->pi_header_sz, packet_in->pi_data_sz
2382            - packet_in->pi_header_sz, s_str));
2383    }
2384    if (!EVP_AEAD_CTX_open(&crypto_ctx->yk_aead_ctx,
2385                dst + packet_in->pi_header_sz, &out_sz,
2386                dst_sz - packet_in->pi_header_sz, nonce, crypto_ctx->yk_iv_sz,
2387                packet_in->pi_data + packet_in->pi_header_sz,
2388                packet_in->pi_data_sz - packet_in->pi_header_sz,
2389                dst, packet_in->pi_header_sz))
2390    {
2391        LSQ_INFO("cannot open packet #%"PRIu64": %s", packet_in->pi_packno,
2392            ERR_error_string(ERR_get_error(), errbuf));
2393        dec_packin = DECPI_BADCRYPT;
2394        goto err;
2395    }
2396
2397    if (enc_sess->esi_flags & ESI_SEND_QL_BITS)
2398    {
2399        packet_in->pi_flags |= PI_LOG_QL_BITS;
2400        if (dst[0] & 0x10)
2401            packet_in->pi_flags |= PI_SQUARE_BIT;
2402        if (dst[0] & 0x08)
2403            packet_in->pi_flags |= PI_LOSS_BIT;
2404    }
2405    else if (dst[0] & (0x0C << (packet_in->pi_header_type == HETY_NOT_SET)))
2406    {
2407        LSQ_DEBUG("reserved bits are not set to zero");
2408        dec_packin = DECPI_VIOLATION;
2409        goto err;
2410    }
2411
2412    if (crypto_ctx == &crypto_ctx_buf)
2413    {
2414        LSQ_DEBUG("decryption in the new key phase %u successful, rotate "
2415            "keys", key_phase);
2416        const struct ku_label kl = select_ku_label(enc_sess);
2417        pair->ykp_thresh = packet_in->pi_packno;
2418        pair->ykp_ctx[ 0 ] = crypto_ctx_buf;
2419        memcpy(enc_sess->esi_traffic_secrets[ 0 ], new_secret,
2420                                                enc_sess->esi_trasec_sz);
2421        lsquic_qhkdf_expand(enc_sess->esi_md,
2422            enc_sess->esi_traffic_secrets[1], enc_sess->esi_trasec_sz,
2423            kl.str, kl.len, new_secret, enc_sess->esi_trasec_sz);
2424        memcpy(enc_sess->esi_traffic_secrets[1], new_secret,
2425                                                enc_sess->esi_trasec_sz);
2426        s = init_crypto_ctx(&pair->ykp_ctx[1], enc_sess->esi_md,
2427                    enc_sess->esi_aead, new_secret, enc_sess->esi_trasec_sz,
2428                    evp_aead_seal);
2429        if (s != 0)
2430        {
2431            LSQ_ERROR("could not init seal crypto ctx (key phase)");
2432            cleanup_crypto_ctx(&pair->ykp_ctx[1]);
2433            /* This is a severe error, abort connection */
2434            enc_sess->esi_conn->cn_if->ci_internal_error(enc_sess->esi_conn,
2435                "crypto ctx failure during key phase shift");
2436            dec_packin = DECPI_BADCRYPT;
2437            goto err;
2438        }
2439        if (enc_sess->esi_flags & ESI_LOG_SECRETS)
2440            log_crypto_pair(enc_sess, pair, "updated");
2441        enc_sess->esi_key_phase = key_phase;
2442    }
2443
2444    packet_in->pi_data_sz = packet_in->pi_header_sz + out_sz;
2445    if (packet_in->pi_flags & PI_OWN_DATA)
2446        lsquic_mm_put_packet_in_buf(&enpub->enp_mm, packet_in->pi_data,
2447                                                        packet_in->pi_data_sz);
2448    packet_in->pi_data = dst;
2449    packet_in->pi_flags |= PI_OWN_DATA | PI_DECRYPTED
2450                        | (enc_level << PIBIT_ENC_LEV_SHIFT);
2451    EV_LOG_CONN_EVENT(LSQUIC_LOG_CONN_ID, "decrypted packet %"PRIu64,
2452                                                    packet_in->pi_packno);
2453    pns = lsquic_enclev2pns[enc_level];
2454    if (packet_in->pi_packno > enc_sess->esi_max_packno[pns]
2455            || !(enc_sess->esi_flags & (ESI_MAX_PACKNO_INIT << pns)))
2456        enc_sess->esi_max_packno[pns] = packet_in->pi_packno;
2457    enc_sess->esi_flags |= ESI_MAX_PACKNO_INIT << pns;
2458    if (is_valid_packno(pair->ykp_thresh)
2459                                && packet_in->pi_packno > pair->ykp_thresh)
2460        pair->ykp_thresh = packet_in->pi_packno;
2461    return DECPI_OK;
2462
2463  err:
2464    if (crypto_ctx == &crypto_ctx_buf)
2465        cleanup_crypto_ctx(crypto_ctx);
2466    if (dst)
2467        lsquic_mm_put_packet_in_buf(&enpub->enp_mm, dst, dst_sz);
2468    EV_LOG_CONN_EVENT(LSQUIC_LOG_CONN_ID, "could not decrypt packet (type %s, "
2469        "number %"PRIu64")", lsquic_hety2str[packet_in->pi_header_type],
2470                                                    packet_in->pi_packno);
2471    return dec_packin;
2472}
2473
2474
2475static const char *
2476iquic_esf_get_sni (enc_session_t *enc_session_p)
2477{
2478    struct enc_sess_iquic *const enc_sess = enc_session_p;
2479    const char *server_name;
2480
2481    server_name = SSL_get_servername(enc_sess->esi_ssl, TLSEXT_NAMETYPE_host_name);
2482#ifndef NDEBUG
2483    if (!server_name)
2484        server_name = enc_sess->esi_sni_bypass;
2485#endif
2486    return server_name;
2487}
2488
2489
2490static int
2491iquic_esf_global_init (int flags)
2492{
2493    s_idx = SSL_get_ex_new_index(0, NULL, NULL, NULL, NULL);
2494    if (s_idx >= 0)
2495    {
2496        LSQ_LOG1(LSQ_LOG_DEBUG, "SSL extra data index: %d", s_idx);
2497        return 0;
2498    }
2499    else
2500    {
2501        LSQ_LOG1(LSQ_LOG_ERROR, "%s: could not select index", __func__);
2502        return -1;
2503    }
2504}
2505
2506
2507static void
2508iquic_esf_global_cleanup (void)
2509{
2510}
2511
2512
2513static void *
2514copy_X509 (void *cert)
2515{
2516    X509_up_ref(cert);
2517    return cert;
2518}
2519
2520
2521static struct stack_st_X509 *
2522iquic_esf_get_server_cert_chain (enc_session_t *enc_session_p)
2523{
2524    struct enc_sess_iquic *const enc_sess = enc_session_p;
2525    STACK_OF(X509) *chain;
2526
2527    if (enc_sess->esi_ssl)
2528    {
2529        chain = SSL_get_peer_cert_chain(enc_sess->esi_ssl);
2530        return (struct stack_st_X509 *)
2531            sk_deep_copy((const _STACK *) chain, sk_X509_call_copy_func,
2532                copy_X509, sk_X509_call_free_func, (void(*)(void*))X509_free);
2533    }
2534    else
2535        return NULL;
2536}
2537
2538
2539static const char *
2540iquic_esf_cipher (enc_session_t *enc_session_p)
2541{
2542    struct enc_sess_iquic *const enc_sess = enc_session_p;
2543    const SSL_CIPHER *cipher;
2544
2545    if (enc_sess->esi_flags & ESI_CACHED_INFO)
2546        return enc_sess->esi_cached_info.cipher_name;
2547    else if (enc_sess->esi_ssl)
2548    {
2549        cipher = SSL_get_current_cipher(enc_sess->esi_ssl);
2550        return SSL_CIPHER_get_name(cipher);
2551    }
2552    else
2553    {
2554        LSQ_WARN("SSL session is not set");
2555        return "null";
2556    }
2557}
2558
2559
2560static int
2561iquic_esf_keysize (enc_session_t *enc_session_p)
2562{
2563    struct enc_sess_iquic *const enc_sess = enc_session_p;
2564    const SSL_CIPHER *cipher;
2565    uint32_t id;
2566
2567    if (enc_sess->esi_flags & ESI_CACHED_INFO)
2568        return enc_sess->esi_cached_info.alg_bits / 8;
2569    else if (enc_sess->esi_ssl)
2570    {
2571        cipher = SSL_get_current_cipher(enc_sess->esi_ssl);
2572        id = cipher ? SSL_CIPHER_get_id(cipher) : 0;
2573
2574        /* RFC 8446, Appendix B.4 */
2575        switch (id)
2576        {
2577        case 0x03000000 | 0x1301:       /* TLS_AES_128_GCM_SHA256 */
2578            return 128 / 8;
2579        case 0x03000000 | 0x1302:       /* TLS_AES_256_GCM_SHA384 */
2580            return 256 / 8;
2581        case 0x03000000 | 0x1303:       /* TLS_CHACHA20_POLY1305_SHA256 */
2582            return 256 / 8;
2583        default:
2584            return -1;
2585        }
2586    }
2587    else
2588    {
2589        LSQ_WARN("SSL session is not set");
2590        return -1;
2591    }
2592}
2593
2594
2595static int
2596iquic_esf_alg_keysize (enc_session_t *enc_session_p)
2597{
2598    /* Modeled on SslConnection::getEnv() */
2599    return iquic_esf_keysize(enc_session_p);
2600}
2601
2602
2603static int
2604iquic_esf_sess_resume_enabled (enc_session_t *enc_session_p)
2605{
2606    struct enc_sess_iquic *const enc_sess = enc_session_p;
2607    return !!(enc_sess->esi_flags & ESI_USE_SSL_TICKET);
2608}
2609
2610
2611static void
2612iquic_esfi_set_iscid (enc_session_t *enc_session_p,
2613                                    const struct lsquic_packet_in *packet_in)
2614{
2615    struct enc_sess_iquic *const enc_sess = enc_session_p;
2616
2617    if (!(enc_sess->esi_flags & ESI_ISCID))
2618    {
2619        lsquic_scid_from_packet_in(packet_in, &enc_sess->esi_iscid);
2620        enc_sess->esi_flags |= ESI_ISCID;
2621        LSQ_DEBUGC("set ISCID to %"CID_FMT, CID_BITS(&enc_sess->esi_iscid));
2622    }
2623}
2624
2625
2626static int
2627iquic_esfi_reset_dcid (enc_session_t *enc_session_p,
2628        const lsquic_cid_t *old_dcid, const lsquic_cid_t *new_dcid)
2629{
2630    struct enc_sess_iquic *const enc_sess = enc_session_p;
2631    struct crypto_ctx_pair *pair;
2632
2633    enc_sess->esi_odcid = *old_dcid;
2634    enc_sess->esi_rscid = *new_dcid;
2635    enc_sess->esi_flags |= ESI_ODCID|ESI_RSCID|ESI_RETRY;
2636
2637    /* Free previous handshake keys */
2638    assert(enc_sess->esi_hsk_pairs);
2639    pair = &enc_sess->esi_hsk_pairs[ENC_LEV_CLEAR];
2640    cleanup_crypto_ctx(&pair->ykp_ctx[0]);
2641    cleanup_crypto_ctx(&pair->ykp_ctx[1]);
2642    cleanup_hp(&enc_sess->esi_hsk_hps[ENC_LEV_CLEAR]);
2643
2644    if (0 == setup_handshake_keys(enc_sess, new_dcid))
2645    {
2646        LSQ_INFOC("reset DCID to %"CID_FMT, CID_BITS(new_dcid));
2647        return 0;
2648    }
2649    else
2650        return -1;
2651}
2652
2653
2654static void
2655iquic_esfi_handshake_confirmed (enc_session_t *sess)
2656{
2657    struct enc_sess_iquic *enc_sess = (struct enc_sess_iquic *) sess;
2658
2659    if (!(enc_sess->esi_flags & ESI_HSK_CONFIRMED))
2660    {
2661        LSQ_DEBUG("handshake has been confirmed");
2662        enc_sess->esi_flags |= ESI_HSK_CONFIRMED;
2663        maybe_drop_SSL(enc_sess);
2664    }
2665}
2666
2667
2668static int
2669iquic_esfi_in_init (enc_session_t *sess)
2670{
2671    struct enc_sess_iquic *enc_sess = (struct enc_sess_iquic *) sess;
2672    int in_init;
2673
2674    if (enc_sess->esi_ssl)
2675    {
2676        in_init = SSL_in_init(enc_sess->esi_ssl);
2677        LSQ_DEBUG("in_init: %d", in_init);
2678        return in_init;
2679    }
2680    else
2681    {
2682        LSQ_DEBUG("no SSL object, in_init: 0");
2683        return 0;
2684    }
2685}
2686
2687
2688static int
2689iquic_esfi_data_in (enc_session_t *sess, enum enc_level enc_level,
2690                                    const unsigned char *buf, size_t len)
2691{
2692    struct enc_sess_iquic *enc_sess = (struct enc_sess_iquic *) sess;
2693    int s;
2694    size_t str_sz;
2695    char str[MAX(1500 * 5, ERR_ERROR_STRING_BUF_LEN)];
2696
2697    if (!enc_sess->esi_ssl)
2698        return -1;
2699
2700    s = SSL_provide_quic_data(enc_sess->esi_ssl,
2701                (enum ssl_encryption_level_t) enc_level, buf, len);
2702    if (!s)
2703    {
2704        LSQ_WARN("SSL_provide_quic_data returned false: %s",
2705                                    ERR_error_string(ERR_get_error(), str));
2706        return -1;
2707    }
2708    LSQ_DEBUG("provided %zu bytes of %u-level data to SSL", len, enc_level);
2709    str_sz = lsquic_hexdump(buf, len, str, sizeof(str));
2710    LSQ_DEBUG("\n%.*s", (int) str_sz, str);
2711    s = SSL_do_handshake(enc_sess->esi_ssl);
2712    LSQ_DEBUG("do_handshake returns %d", s);
2713    return 0;
2714}
2715
2716
2717static void iquic_esfi_shake_stream (enc_session_t *sess,
2718                            struct lsquic_stream *stream, const char *what);
2719
2720
2721const struct enc_session_funcs_iquic lsquic_enc_session_iquic_ietf_v1 =
2722{
2723    .esfi_create_client  = iquic_esfi_create_client,
2724    .esfi_destroy        = iquic_esfi_destroy,
2725    .esfi_get_peer_transport_params
2726                         = iquic_esfi_get_peer_transport_params,
2727    .esfi_reset_dcid     = iquic_esfi_reset_dcid,
2728    .esfi_init_server    = iquic_esfi_init_server,
2729    .esfi_set_iscid      = iquic_esfi_set_iscid,
2730    .esfi_set_streams    = iquic_esfi_set_streams,
2731    .esfi_create_server  = iquic_esfi_create_server,
2732    .esfi_shake_stream   = iquic_esfi_shake_stream,
2733    .esfi_handshake_confirmed
2734                         = iquic_esfi_handshake_confirmed,
2735    .esfi_in_init        = iquic_esfi_in_init,
2736    .esfi_data_in        = iquic_esfi_data_in,
2737};
2738
2739
2740const struct enc_session_funcs_common lsquic_enc_session_common_ietf_v1 =
2741{
2742    .esf_encrypt_packet  = iquic_esf_encrypt_packet,
2743    .esf_decrypt_packet  = iquic_esf_decrypt_packet,
2744    .esf_flush_encryption= iquic_esf_flush_encryption,
2745    .esf_global_cleanup  = iquic_esf_global_cleanup,
2746    .esf_global_init     = iquic_esf_global_init,
2747    .esf_tag_len         = IQUIC_TAG_LEN,
2748    .esf_get_server_cert_chain
2749                         = iquic_esf_get_server_cert_chain,
2750    .esf_get_sni         = iquic_esf_get_sni,
2751    .esf_cipher          = iquic_esf_cipher,
2752    .esf_keysize         = iquic_esf_keysize,
2753    .esf_alg_keysize     = iquic_esf_alg_keysize,
2754    .esf_is_sess_resume_enabled = iquic_esf_sess_resume_enabled,
2755    .esf_set_conn        = iquic_esf_set_conn,
2756};
2757
2758
2759static
2760const struct enc_session_funcs_common lsquic_enc_session_common_ietf_v1_no_flush =
2761{
2762    .esf_encrypt_packet  = iquic_esf_encrypt_packet,
2763    .esf_decrypt_packet  = iquic_esf_decrypt_packet,
2764    .esf_global_cleanup  = iquic_esf_global_cleanup,
2765    .esf_global_init     = iquic_esf_global_init,
2766    .esf_tag_len         = IQUIC_TAG_LEN,
2767    .esf_get_server_cert_chain
2768                         = iquic_esf_get_server_cert_chain,
2769    .esf_get_sni         = iquic_esf_get_sni,
2770    .esf_cipher          = iquic_esf_cipher,
2771    .esf_keysize         = iquic_esf_keysize,
2772    .esf_alg_keysize     = iquic_esf_alg_keysize,
2773    .esf_is_sess_resume_enabled = iquic_esf_sess_resume_enabled,
2774    .esf_set_conn        = iquic_esf_set_conn,
2775};
2776
2777
2778static void
2779cache_info (struct enc_sess_iquic *enc_sess)
2780{
2781    const SSL_CIPHER *cipher;
2782
2783    cipher = SSL_get_current_cipher(enc_sess->esi_ssl);
2784    enc_sess->esi_cached_info.cipher_name = SSL_CIPHER_get_name(cipher);
2785    SSL_CIPHER_get_bits(cipher, &enc_sess->esi_cached_info.alg_bits);
2786    enc_sess->esi_flags |= ESI_CACHED_INFO;
2787}
2788
2789
2790static void
2791drop_SSL (struct enc_sess_iquic *enc_sess)
2792{
2793    LSQ_DEBUG("drop SSL object");
2794    if (enc_sess->esi_conn->cn_if->ci_drop_crypto_streams)
2795        enc_sess->esi_conn->cn_if->ci_drop_crypto_streams(
2796                                                    enc_sess->esi_conn);
2797    cache_info(enc_sess);
2798    SSL_free(enc_sess->esi_ssl);
2799    enc_sess->esi_ssl = NULL;
2800    free_handshake_keys(enc_sess);
2801}
2802
2803
2804static void
2805maybe_drop_SSL (struct enc_sess_iquic *enc_sess)
2806{
2807    /* We rely on the following BoringSSL property: it writes new session
2808     * tickets before marking handshake as complete.  In this case, the new
2809     * session tickets have either been successfully written to crypto stream,
2810     * in which case we can close it, or (unlikely) they are buffered in the
2811     * frab list.
2812     */
2813    if ((enc_sess->esi_flags & (ESI_HSK_CONFIRMED|ESI_HANDSHAKE_OK))
2814                            == (ESI_HSK_CONFIRMED|ESI_HANDSHAKE_OK)
2815        && enc_sess->esi_ssl
2816        && lsquic_frab_list_empty(&enc_sess->esi_frals[ENC_LEV_FORW]))
2817    {
2818        if ((enc_sess->esi_flags & (ESI_SERVER|ESI_WANT_TICKET))
2819                                                            != ESI_WANT_TICKET)
2820            drop_SSL(enc_sess);
2821        else if (enc_sess->esi_alset
2822                && !lsquic_alarmset_is_set(enc_sess->esi_alset, AL_SESS_TICKET))
2823        {
2824            LSQ_DEBUG("no session ticket: delay dropping SSL object");
2825            lsquic_alarmset_set(enc_sess->esi_alset, AL_SESS_TICKET,
2826                /* Wait up to two seconds for session tickets */
2827                                                lsquic_time_now() + 2000000);
2828        }
2829    }
2830}
2831
2832
2833static void
2834no_sess_ticket (enum alarm_id alarm_id, void *ctx,
2835                                  lsquic_time_t expiry, lsquic_time_t now)
2836{
2837    struct enc_sess_iquic *enc_sess = ctx;
2838
2839    LSQ_DEBUG("no session tickets forthcoming -- drop SSL");
2840    drop_SSL(enc_sess);
2841}
2842
2843
2844typedef char enums_have_the_same_value[
2845    (int) ssl_encryption_initial     == (int) ENC_LEV_CLEAR &&
2846    (int) ssl_encryption_early_data  == (int) ENC_LEV_EARLY &&
2847    (int) ssl_encryption_handshake   == (int) ENC_LEV_INIT  &&
2848    (int) ssl_encryption_application == (int) ENC_LEV_FORW      ? 1 : -1];
2849
2850static int
2851set_secret (SSL *ssl, enum ssl_encryption_level_t level,
2852    const SSL_CIPHER *cipher, const uint8_t *secret, size_t secret_len, int rw)
2853{
2854    struct enc_sess_iquic *enc_sess;
2855    struct crypto_ctx_pair *pair;
2856    struct header_prot *hp;
2857    struct crypto_params crypa;
2858    int have_alpn;
2859    const unsigned char *alpn;
2860    unsigned alpn_len;
2861    size_t key_len;
2862    const enum enc_level enc_level = (enum enc_level) level;
2863    unsigned char key[EVP_MAX_KEY_LENGTH];
2864    char errbuf[ERR_ERROR_STRING_BUF_LEN];
2865#define hexbuf errbuf
2866
2867    enc_sess = SSL_get_ex_data(ssl, s_idx);
2868    if (!enc_sess)
2869        return 0;
2870
2871    if ((enc_sess->esi_flags & (ESI_ALPN_CHECKED|ESI_SERVER)) == ESI_SERVER
2872                                                        && enc_sess->esi_alpn)
2873    {
2874        enc_sess->esi_flags |= ESI_ALPN_CHECKED;
2875        SSL_get0_alpn_selected(enc_sess->esi_ssl, &alpn, &alpn_len);
2876        have_alpn = alpn && alpn_len == enc_sess->esi_alpn[0]
2877                            && 0 == memcmp(alpn, enc_sess->esi_alpn + 1, alpn_len);
2878        if (have_alpn)
2879            LSQ_DEBUG("Selected ALPN %.*s", (int) alpn_len, (char *) alpn);
2880        else
2881        {
2882            LSQ_INFO("No ALPN is selected: send fatal alert");
2883            SSL_send_fatal_alert(ssl, ALERT_NO_APPLICATION_PROTOCOL);
2884            return 0;
2885        }
2886    }
2887
2888    if (0 != get_crypto_params(enc_sess, cipher, &crypa))
2889        return 0;
2890
2891/*
2892    if (enc_sess->esi_flags & ESI_SERVER)
2893        secrets[0] = read_secret, secrets[1] = write_secret;
2894    else
2895        secrets[0] = write_secret, secrets[1] = read_secret;
2896        */
2897
2898    if (enc_level < ENC_LEV_FORW)
2899    {
2900        assert(enc_sess->esi_hsk_pairs);
2901        pair = &enc_sess->esi_hsk_pairs[enc_level];
2902        hp = &enc_sess->esi_hsk_hps[enc_level];
2903    }
2904    else
2905    {
2906        pair = &enc_sess->esi_pairs[0];
2907        hp = &enc_sess->esi_hp;
2908        enc_sess->esi_trasec_sz = secret_len;
2909        memcpy(enc_sess->esi_traffic_secrets[rw], secret, secret_len);
2910        enc_sess->esi_md = crypa.md;
2911        enc_sess->esi_aead = crypa.aead;
2912        if (!(hp->hp_flags & (HP_CAN_READ|HP_CAN_WRITE))
2913                && crypa.aead == EVP_aead_chacha20_poly1305())
2914        {
2915            LSQ_DEBUG("turn off header protection batching (chacha not "
2916                "supported)");
2917            enc_sess->esi_conn->cn_esf_c = &lsquic_enc_session_common_ietf_v1_no_flush;
2918        }
2919    }
2920    pair->ykp_thresh = IQUIC_INVALID_PACKNO;
2921
2922    if (enc_sess->esi_flags & ESI_LOG_SECRETS)
2923        LSQ_DEBUG("set %s secret for level %u: %s", rw2str[rw], enc_level,
2924                            HEXSTR(secret, secret_len, hexbuf));
2925    else
2926        LSQ_DEBUG("set %s for level %u", rw2str[rw], enc_level);
2927
2928    if (0 != init_crypto_ctx(&pair->ykp_ctx[rw], crypa.md,
2929                crypa.aead, secret, secret_len, rw2dir(rw)))
2930        goto err;
2931
2932    if (pair->ykp_ctx[!rw].yk_flags & YK_INITED)
2933    {
2934        /* Sanity check that the two sides end up with the same header
2935         * protection logic, as they should.
2936         */
2937        assert(hp->hp_gen_mask == crypa.gen_hp_mask);
2938    }
2939    else
2940    {
2941        hp->hp_enc_level = enc_level;
2942        hp->hp_gen_mask  = crypa.gen_hp_mask;
2943    }
2944    key_len = EVP_AEAD_key_length(crypa.aead);
2945    if (hp->hp_gen_mask == gen_hp_mask_aes)
2946    {
2947        lsquic_qhkdf_expand(crypa.md, secret, secret_len, PN_LABEL, PN_LABEL_SZ,
2948            key, key_len);
2949        EVP_CIPHER_CTX_init(&hp->hp_u.cipher_ctx[rw]);
2950        if (!EVP_EncryptInit_ex(&hp->hp_u.cipher_ctx[rw], crypa.hp, NULL, key, 0))
2951        {
2952            LSQ_ERROR("cannot initialize cipher on level %u", enc_level);
2953            goto err;
2954        }
2955    }
2956    else
2957        lsquic_qhkdf_expand(crypa.md, secret, secret_len, PN_LABEL, PN_LABEL_SZ,
2958            hp->hp_u.buf[rw], key_len);
2959    hp->hp_flags |= 1 << rw;
2960
2961    if (enc_sess->esi_flags & ESI_LOG_SECRETS)
2962    {
2963        log_crypto_ctx(enc_sess, &pair->ykp_ctx[rw], "new", rw);
2964        LSQ_DEBUG("%s hp: %s", rw2str[rw],
2965            HEXSTR(hp->hp_gen_mask == gen_hp_mask_aes ? key : hp->hp_u.buf[rw],
2966            key_len, hexbuf));
2967    }
2968
2969    if (rw && enc_level == ENC_LEV_FORW)
2970        enc_sess->esi_have_forw = 1;
2971
2972    return 1;
2973
2974  err:
2975    cleanup_crypto_ctx(&pair->ykp_ctx[0]);
2976    cleanup_crypto_ctx(&pair->ykp_ctx[1]);
2977    return 0;
2978#undef hexbuf
2979}
2980
2981
2982static int
2983cry_sm_set_read_secret (SSL *ssl, enum ssl_encryption_level_t level,
2984            const SSL_CIPHER *cipher, const uint8_t *secret, size_t secret_len)
2985{
2986    return set_secret(ssl, level, cipher, secret, secret_len, 0);
2987}
2988
2989
2990static int
2991cry_sm_set_write_secret (SSL *ssl, enum ssl_encryption_level_t level,
2992            const SSL_CIPHER *cipher, const uint8_t *secret, size_t secret_len)
2993{
2994    return set_secret(ssl, level, cipher, secret, secret_len, 1);
2995}
2996
2997
2998static int
2999cry_sm_write_message (SSL *ssl, enum ssl_encryption_level_t level,
3000                                            const uint8_t *data, size_t len)
3001{
3002    struct enc_sess_iquic *enc_sess;
3003    void *stream;
3004    ssize_t nw;
3005
3006    enc_sess = SSL_get_ex_data(ssl, s_idx);
3007    if (!enc_sess)
3008        return 0;
3009
3010    stream = enc_sess->esi_streams[level];
3011    if (!stream)
3012        return 0;
3013
3014    /* The frab list logic is only applicable on the client.  XXX This is
3015     * likely to change when support for key updates is added.
3016     */
3017    if (enc_sess->esi_flags & (ESI_ON_WRITE|ESI_SERVER))
3018        nw = enc_sess->esi_cryst_if->csi_write(stream, data, len);
3019    else
3020    {
3021        LSQ_DEBUG("not in on_write event: buffer in a frab list");
3022        if (0 == lsquic_frab_list_write(&enc_sess->esi_frals[level], data, len))
3023        {
3024            if (!lsquic_frab_list_empty(&enc_sess->esi_frals[level]))
3025                enc_sess->esi_cryst_if->csi_wantwrite(stream, 1);
3026            nw = len;
3027        }
3028        else
3029            nw = -1;
3030    }
3031
3032    if (nw >= 0 && (size_t) nw == len)
3033    {
3034        enc_sess->esi_last_w = (enum enc_level) level;
3035        LSQ_DEBUG("wrote %zu bytes to stream at encryption level %u",
3036            len, level);
3037        maybe_drop_SSL(enc_sess);
3038        return 1;
3039    }
3040    else
3041    {
3042        LSQ_INFO("could not write %zu bytes: returned %zd", len, nw);
3043        return 0;
3044    }
3045}
3046
3047
3048static int
3049cry_sm_flush_flight (SSL *ssl)
3050{
3051    struct enc_sess_iquic *enc_sess;
3052    void *stream;
3053    unsigned level;
3054    int s;
3055
3056    enc_sess = SSL_get_ex_data(ssl, s_idx);
3057    if (!enc_sess)
3058        return 0;
3059
3060    level = enc_sess->esi_last_w;
3061    stream = enc_sess->esi_streams[level];
3062    if (!stream)
3063        return 0;
3064
3065    if (lsquic_frab_list_empty(&enc_sess->esi_frals[level]))
3066    {
3067        s = enc_sess->esi_cryst_if->csi_flush(stream);
3068        return s == 0;
3069    }
3070    else
3071        /* Frab list will get flushed */    /* TODO: add support for
3072        recording flush points in frab list. */
3073        return 1;
3074}
3075
3076
3077static int
3078cry_sm_send_alert (SSL *ssl, enum ssl_encryption_level_t level, uint8_t alert)
3079{
3080    struct enc_sess_iquic *enc_sess;
3081
3082    enc_sess = SSL_get_ex_data(ssl, s_idx);
3083    if (!enc_sess)
3084        return 0;
3085
3086    LSQ_INFO("got alert %"PRIu8, alert);
3087    enc_sess->esi_conn->cn_if->ci_tls_alert(enc_sess->esi_conn, alert);
3088
3089    return 1;
3090}
3091
3092
3093static const SSL_QUIC_METHOD cry_quic_method =
3094{
3095    .set_read_secret        = cry_sm_set_read_secret,
3096    .set_write_secret       = cry_sm_set_write_secret,
3097    .add_handshake_data     = cry_sm_write_message,
3098    .flush_flight           = cry_sm_flush_flight,
3099    .send_alert             = cry_sm_send_alert,
3100};
3101
3102
3103static lsquic_stream_ctx_t *
3104chsk_ietf_on_new_stream (void *stream_if_ctx, struct lsquic_stream *stream)
3105{
3106    struct enc_sess_iquic *const enc_sess = stream_if_ctx;
3107    enum enc_level enc_level;
3108
3109    enc_level = enc_sess->esi_cryst_if->csi_enc_level(stream);
3110    if (enc_level == ENC_LEV_CLEAR)
3111        enc_sess->esi_cryst_if->csi_wantwrite(stream, 1);
3112
3113    LSQ_DEBUG("handshake stream created successfully");
3114
3115    return stream_if_ctx;
3116}
3117
3118
3119static lsquic_stream_ctx_t *
3120shsk_ietf_on_new_stream (void *stream_if_ctx, struct lsquic_stream *stream)
3121{
3122    struct enc_sess_iquic *const enc_sess = stream_if_ctx;
3123    enum enc_level enc_level;
3124
3125    enc_level = enc_sess->esi_cryst_if->csi_enc_level(stream);
3126    LSQ_DEBUG("on_new_stream called on level %u", enc_level);
3127
3128    enc_sess->esi_cryst_if->csi_wantread(stream, 1);
3129
3130    return stream_if_ctx;
3131}
3132
3133
3134static void
3135chsk_ietf_on_close (struct lsquic_stream *stream, lsquic_stream_ctx_t *ctx)
3136{
3137    struct enc_sess_iquic *const enc_sess = (struct enc_sess_iquic *) ctx;
3138    if (enc_sess && enc_sess->esi_cryst_if)
3139        LSQ_DEBUG("crypto stream level %u is closed",
3140                (unsigned) enc_sess->esi_cryst_if->csi_enc_level(stream));
3141}
3142
3143
3144static const char *const ihs2str[] = {
3145    [IHS_WANT_READ]  = "want read",
3146    [IHS_WANT_WRITE] = "want write",
3147    [IHS_WANT_RW]    = "want rw",
3148    [IHS_STOP]       = "stop",
3149};
3150
3151
3152static void
3153iquic_esfi_shake_stream (enc_session_t *sess,
3154                            struct lsquic_stream *stream, const char *what)
3155{
3156    struct enc_sess_iquic *enc_sess = (struct enc_sess_iquic *)sess;
3157    enum iquic_handshake_status st;
3158    enum enc_level enc_level;
3159    int write;
3160    if (0 == (enc_sess->esi_flags & ESI_HANDSHAKE_OK))
3161        st = iquic_esfi_handshake(enc_sess);
3162    else
3163        st = iquic_esfi_post_handshake(enc_sess);
3164    enc_level = enc_sess->esi_cryst_if->csi_enc_level(stream);
3165    LSQ_DEBUG("enc level %s after %s: %s", lsquic_enclev2str[enc_level], what,
3166                                                                ihs2str[st]);
3167    switch (st)
3168    {
3169    case IHS_WANT_READ:
3170        write = !lsquic_frab_list_empty(&enc_sess->esi_frals[enc_level]);
3171        enc_sess->esi_cryst_if->csi_wantwrite(stream, write);
3172        enc_sess->esi_cryst_if->csi_wantread(stream, 1);
3173        break;
3174    case IHS_WANT_WRITE:
3175        enc_sess->esi_cryst_if->csi_wantwrite(stream, 1);
3176        enc_sess->esi_cryst_if->csi_wantread(stream, 0);
3177        break;
3178    case IHS_WANT_RW:
3179        enc_sess->esi_cryst_if->csi_wantwrite(stream, 1);
3180        enc_sess->esi_cryst_if->csi_wantread(stream, 1);
3181        break;
3182    default:
3183        assert(st == IHS_STOP);
3184        write = !lsquic_frab_list_empty(&enc_sess->esi_frals[enc_level]);
3185        enc_sess->esi_cryst_if->csi_wantwrite(stream, write);
3186        enc_sess->esi_cryst_if->csi_wantread(stream, 0);
3187        break;
3188    }
3189    LSQ_DEBUG("Exit shake_stream");
3190    maybe_drop_SSL(enc_sess);
3191}
3192
3193
3194struct readf_ctx
3195{
3196    struct enc_sess_iquic  *enc_sess;
3197    enum enc_level          enc_level;
3198    int                     err;
3199};
3200
3201
3202static size_t
3203readf_cb (void *ctx, const unsigned char *buf, size_t len, int fin)
3204{
3205    struct readf_ctx *const readf_ctx = (void *) ctx;
3206    struct enc_sess_iquic *const enc_sess = readf_ctx->enc_sess;
3207    int s;
3208    size_t str_sz;
3209    char str[MAX(1500 * 5, ERR_ERROR_STRING_BUF_LEN)];
3210
3211    s = SSL_provide_quic_data(enc_sess->esi_ssl,
3212                (enum ssl_encryption_level_t) readf_ctx->enc_level, buf, len);
3213    if (s)
3214    {
3215        LSQ_DEBUG("provided %zu bytes of %u-level data to SSL", len,
3216                                                        readf_ctx->enc_level);
3217        str_sz = lsquic_hexdump(buf, len, str, sizeof(str));
3218        LSQ_DEBUG("\n%.*s", (int) str_sz, str);
3219        return len;
3220    }
3221    else
3222    {
3223        LSQ_WARN("SSL_provide_quic_data returned false: %s",
3224                                    ERR_error_string(ERR_get_error(), str));
3225        readf_ctx->err++;
3226        return 0;
3227    }
3228}
3229
3230
3231static size_t
3232discard_cb (void *ctx, const unsigned char *buf, size_t len, int fin)
3233{
3234    return len;
3235}
3236
3237
3238static void
3239chsk_ietf_on_read (struct lsquic_stream *stream, lsquic_stream_ctx_t *ctx)
3240{
3241    struct enc_sess_iquic *const enc_sess = (void *) ctx;
3242    enum enc_level enc_level = enc_sess->esi_cryst_if->csi_enc_level(stream);
3243    struct readf_ctx readf_ctx = { enc_sess, enc_level, 0, };
3244    ssize_t nread;
3245
3246
3247    if (enc_sess->esi_ssl)
3248    {
3249        nread = enc_sess->esi_cryst_if->csi_readf(stream, readf_cb, &readf_ctx);
3250        if (!(nread < 0 || readf_ctx.err))
3251            iquic_esfi_shake_stream((enc_session_t *)enc_sess, stream,
3252                                                                    "on_read");
3253        else
3254            enc_sess->esi_conn->cn_if->ci_internal_error(enc_sess->esi_conn,
3255                "shaking stream failed: nread: %zd, err: %d, SSL err: %"PRIu32,
3256                nread, readf_ctx.err, ERR_get_error());
3257    }
3258    else
3259    {
3260        /* This branch is reached when we don't want TLS ticket and drop
3261         * the SSL object before we process TLS tickets that have been
3262         * already received and waiting in the incoming stream buffer.
3263         */
3264        nread = enc_sess->esi_cryst_if->csi_readf(stream, discard_cb, NULL);
3265        lsquic_stream_wantread(stream, 0);
3266        LSQ_DEBUG("no SSL object: discard %zd bytes of SSL data", nread);
3267    }
3268}
3269
3270
3271static void
3272maybe_write_from_fral (struct enc_sess_iquic *enc_sess,
3273                                                struct lsquic_stream *stream)
3274{
3275    enum enc_level enc_level = enc_sess->esi_cryst_if->csi_enc_level(stream);
3276    struct frab_list *const fral = &enc_sess->esi_frals[enc_level];
3277    struct lsquic_reader reader = {
3278        .lsqr_read  = lsquic_frab_list_read,
3279        .lsqr_size  = lsquic_frab_list_size,
3280        .lsqr_ctx   = fral,
3281    };
3282    ssize_t nw;
3283
3284    if (lsquic_frab_list_empty(fral))
3285        return;
3286
3287    nw = lsquic_stream_writef(stream, &reader);
3288    if (nw >= 0)
3289    {
3290        LSQ_DEBUG("wrote %zd bytes to stream from frab list", nw);
3291        (void) lsquic_stream_flush(stream);
3292        if (lsquic_frab_list_empty(fral))
3293            lsquic_stream_wantwrite(stream, 0);
3294    }
3295    else
3296    {
3297        enc_sess->esi_conn->cn_if->ci_internal_error(enc_sess->esi_conn,
3298                            "cannot write to stream: %s", strerror(errno));
3299        lsquic_stream_wantwrite(stream, 0);
3300    }
3301}
3302
3303
3304static void
3305chsk_ietf_on_write (struct lsquic_stream *stream, lsquic_stream_ctx_t *ctx)
3306{
3307    struct enc_sess_iquic *const enc_sess = (void *) ctx;
3308
3309    maybe_write_from_fral(enc_sess, stream);
3310
3311    enc_sess->esi_flags |= ESI_ON_WRITE;
3312    iquic_esfi_shake_stream(enc_sess, stream, "on_write");
3313    enc_sess->esi_flags &= ~ESI_ON_WRITE;
3314}
3315
3316
3317const struct lsquic_stream_if lsquic_cry_sm_if =
3318{
3319    .on_new_stream = chsk_ietf_on_new_stream,
3320    .on_read       = chsk_ietf_on_read,
3321    .on_write      = chsk_ietf_on_write,
3322    .on_close      = chsk_ietf_on_close,
3323};
3324
3325
3326const struct lsquic_stream_if lsquic_mini_cry_sm_if =
3327{
3328    .on_new_stream = shsk_ietf_on_new_stream,
3329    .on_read       = chsk_ietf_on_read,
3330    .on_write      = chsk_ietf_on_write,
3331    .on_close      = chsk_ietf_on_close,
3332};
3333
3334
3335
3336
3337const unsigned char *const lsquic_retry_key_buf[N_IETF_RETRY_VERSIONS] =
3338{
3339    /* [draft-ietf-quic-tls-25] Section 5.8 */
3340    (unsigned char *)
3341        "\x4d\x32\xec\xdb\x2a\x21\x33\xc8\x41\xe4\x04\x3d\xf2\x7d\x44\x30",
3342    /* [draft-ietf-quic-tls-29] Section 5.8 */
3343    (unsigned char *)
3344        "\xcc\xce\x18\x7e\xd0\x9a\x09\xd0\x57\x28\x15\x5a\x6c\xb9\x6b\xe1",
3345    /* [draft-ietf-quic-tls-33] Section 5.8 */
3346    (unsigned char *)
3347        "\xbe\x0c\x69\x0b\x9f\x66\x57\x5a\x1d\x76\x6b\x54\xe3\x68\xc8\x4e",
3348};
3349
3350
3351const unsigned char *const lsquic_retry_nonce_buf[N_IETF_RETRY_VERSIONS] =
3352{
3353    /* [draft-ietf-quic-tls-25] Section 5.8 */
3354    (unsigned char *) "\x4d\x16\x11\xd0\x55\x13\xa5\x52\xc5\x87\xd5\x75",
3355    /* [draft-ietf-quic-tls-29] Section 5.8 */
3356    (unsigned char *) "\xe5\x49\x30\xf9\x7f\x21\x36\xf0\x53\x0a\x8c\x1c",
3357    /* [draft-ietf-quic-tls-33] Section 5.8 */
3358    (unsigned char *) "\x46\x15\x99\xd3\x5d\x63\x2b\xf2\x23\x98\x25\xbb",
3359};
3360
3361
3362int
3363lsquic_enc_sess_ietf_gen_quic_ctx (
3364                const struct lsquic_engine_settings *settings,
3365                enum lsquic_version version, unsigned char *buf, size_t bufsz)
3366{
3367    struct transport_params params;
3368    int len;
3369
3370    /* This code is pretty much copied from gen_trans_params(), with
3371     * small (but important) exceptions.
3372     */
3373
3374    memset(&params, 0, sizeof(params));
3375    params.tp_init_max_data = settings->es_init_max_data;
3376    params.tp_init_max_stream_data_bidi_local
3377                            = settings->es_init_max_stream_data_bidi_local;
3378    params.tp_init_max_stream_data_bidi_remote
3379                            = settings->es_init_max_stream_data_bidi_remote;
3380    params.tp_init_max_stream_data_uni
3381                            = settings->es_init_max_stream_data_uni;
3382    params.tp_init_max_streams_uni
3383                            = settings->es_init_max_streams_uni;
3384    params.tp_init_max_streams_bidi
3385                            = settings->es_init_max_streams_bidi;
3386    params.tp_ack_delay_exponent
3387                            = TP_DEF_ACK_DELAY_EXP;
3388    params.tp_max_idle_timeout = settings->es_idle_timeout * 1000;
3389    params.tp_max_ack_delay = TP_DEF_MAX_ACK_DELAY;
3390    params.tp_active_connection_id_limit = MAX_IETF_CONN_DCIDS;
3391    params.tp_set |= (1 << TPI_INIT_MAX_DATA)
3392                  |  (1 << TPI_INIT_MAX_STREAM_DATA_BIDI_LOCAL)
3393                  |  (1 << TPI_INIT_MAX_STREAM_DATA_BIDI_REMOTE)
3394                  |  (1 << TPI_INIT_MAX_STREAM_DATA_UNI)
3395                  |  (1 << TPI_INIT_MAX_STREAMS_UNI)
3396                  |  (1 << TPI_INIT_MAX_STREAMS_BIDI)
3397                  |  (1 << TPI_ACK_DELAY_EXPONENT)
3398                  |  (1 << TPI_MAX_IDLE_TIMEOUT)
3399                  |  (1 << TPI_MAX_ACK_DELAY)
3400                  |  (1 << TPI_ACTIVE_CONNECTION_ID_LIMIT)
3401                  ;
3402    if (settings->es_max_udp_payload_size_rx)
3403    {
3404        params.tp_max_udp_payload_size = settings->es_max_udp_payload_size_rx;
3405        params.tp_set |= 1 << TPI_MAX_UDP_PAYLOAD_SIZE;
3406    }
3407    if (!settings->es_allow_migration)
3408        params.tp_set |= 1 << TPI_DISABLE_ACTIVE_MIGRATION;
3409    if (settings->es_ql_bits)
3410    {
3411        params.tp_loss_bits = settings->es_ql_bits - 1;
3412        params.tp_set |= 1 << TPI_LOSS_BITS;
3413    }
3414    if (settings->es_delayed_acks)
3415    {
3416        params.tp_numerics[TPI_MIN_ACK_DELAY] = TP_MIN_ACK_DELAY;
3417        params.tp_set |= 1 << TPI_MIN_ACK_DELAY;
3418        params.tp_numerics[TPI_MIN_ACK_DELAY_02] = TP_MIN_ACK_DELAY;
3419        params.tp_set |= 1 << TPI_MIN_ACK_DELAY_02;
3420    }
3421    if (settings->es_timestamps)
3422    {
3423        params.tp_numerics[TPI_TIMESTAMPS] = TS_GENERATE_THEM;
3424        params.tp_set |= 1 << TPI_TIMESTAMPS;
3425    }
3426    if (settings->es_datagrams)
3427    {
3428        if (params.tp_set & (1 << TPI_MAX_UDP_PAYLOAD_SIZE))
3429            params.tp_numerics[TPI_MAX_DATAGRAM_FRAME_SIZE]
3430                                            = params.tp_max_udp_payload_size;
3431        else
3432            params.tp_numerics[TPI_MAX_DATAGRAM_FRAME_SIZE]
3433                                            = TP_DEF_MAX_UDP_PAYLOAD_SIZE;
3434        params.tp_set |= 1 << TPI_MAX_DATAGRAM_FRAME_SIZE;
3435    }
3436
3437    params.tp_set &= SERVER_0RTT_TPS;
3438
3439    len = (version == LSQVER_ID27 ? lsquic_tp_encode_27 : lsquic_tp_encode)(
3440                        &params, 1, buf, bufsz);
3441    if (len >= 0)
3442    {
3443        char str[MAX_TP_STR_SZ];
3444        LSQ_LOG1(LSQ_LOG_DEBUG, "generated QUIC server context of %d bytes "
3445            "for version %s", len, lsquic_ver2str[version]);
3446        LSQ_LOG1(LSQ_LOG_DEBUG, "%s", ((version == LSQVER_ID27
3447                ? lsquic_tp_to_str_27 : lsquic_tp_to_str)(&params, str,
3448                                                            sizeof(str)), str));
3449    }
3450    else
3451        LSQ_LOG1(LSQ_LOG_WARN, "cannot generate QUIC server context: %d",
3452                                                                        errno);
3453    return len;
3454}
3455
3456
3457struct lsquic_conn *
3458lsquic_ssl_to_conn (const struct ssl_st *ssl)
3459{
3460    struct enc_sess_iquic *enc_sess;
3461
3462    if (s_idx < 0)
3463        return NULL;
3464
3465    enc_sess = SSL_get_ex_data(ssl, s_idx);
3466    if (!enc_sess)
3467        return NULL;
3468
3469    return enc_sess->esi_conn;
3470}
3471
3472
3473int
3474lsquic_ssl_sess_to_resume_info (SSL *ssl, SSL_SESSION *session,
3475                                        unsigned char **buf, size_t *buf_sz)
3476{
3477    struct enc_sess_iquic *enc_sess;
3478    int status;
3479
3480    if (s_idx < 0)
3481        return -1;
3482
3483    enc_sess = SSL_get_ex_data(ssl, s_idx);
3484    if (!enc_sess)
3485        return -1;
3486
3487    status = iquic_ssl_sess_to_resume_info(enc_sess, ssl, session, buf, buf_sz);
3488    if (status == 0)
3489    {
3490        LSQ_DEBUG("%s called successfully, unset WANT_TICKET flag", __func__);
3491        enc_sess->esi_flags &= ~ESI_WANT_TICKET;
3492        lsquic_alarmset_unset(enc_sess->esi_alset, AL_SESS_TICKET);
3493    }
3494    return status;
3495}
3496