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