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