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