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