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