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