lsquic_enc_sess_ietf.c revision 662de5e1
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));
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_set_cert_cb(enc_sess->esi_ssl, iquic_lookup_cert, enc_sess);
1117    SSL_set_ex_data(enc_sess->esi_ssl, s_idx, enc_sess);
1118    SSL_set_accept_state(enc_sess->esi_ssl);
1119    LSQ_DEBUG("initialized server enc session");
1120    enc_sess->esi_flags |= ESI_INITIALIZED;
1121    return 0;
1122}
1123
1124
1125#if __BYTE_ORDER == __LITTLE_ENDIAN
1126#define WRITE_NUM(var_, val_, ptr_) do {                        \
1127    var_ = (val_);                                              \
1128    var_ = bswap_32(var_);                                      \
1129    memcpy((ptr_), &var_, sizeof(var_));                        \
1130    ptr_ += sizeof(var_);                                       \
1131} while (0)
1132#else
1133#define WRITE_NUM(var_, val_, ptr_) do {                        \
1134    var_ = (val_);                                              \
1135    memcpy((ptr_), &var_, sizeof(var_));                        \
1136    ptr_ += sizeof(var_);                                       \
1137} while (0)
1138#endif
1139
1140static int
1141iquic_new_session_cb (SSL *ssl, SSL_SESSION *session)
1142{
1143    struct enc_sess_iquic *enc_sess;
1144    uint32_t max_early_data_size, num;
1145    unsigned char *p, *buf;
1146    uint8_t *ticket_buf;
1147    size_t ticket_sz;
1148    lsquic_ver_tag_t tag;
1149    const uint8_t *trapa_buf;
1150    SSL_CTX *ssl_ctx;
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    max_early_data_size = SSL_SESSION_get_max_early_data_size(session);
1157    if (max_early_data_size && 0xFFFFFFFFu != max_early_data_size)
1158    {
1159        /* XXX We do not catch the case when early_data extension is present
1160         * and max_early_data_size is set to zero, which is an invalid value.
1161         * This is because there is no way to check this using existing
1162         * BoringSSL APIs.
1163         */
1164        /* See [draft-ietf-quic-tls-23], Section 4.5 */
1165        LSQ_INFO("max_early_data_size=0x%X, protocol violation",
1166                                                        max_early_data_size);
1167        enc_sess->esi_conn->cn_if->ci_abort_error(enc_sess->esi_conn, 0,
1168            TEC_PROTOCOL_VIOLATION, "max_early_data_size is set to %u "
1169                "instead of 0xFFFFFFFF as mandated by standard",
1170                max_early_data_size);
1171        ssl_ctx = SSL_get_SSL_CTX(ssl);
1172        SSL_CTX_sess_set_new_cb(ssl_ctx, NULL);
1173        return 0;
1174    }
1175
1176    SSL_get_peer_quic_transport_params(enc_sess->esi_ssl, &trapa_buf,
1177                                                                &trapa_sz);
1178    if (!(trapa_buf + trapa_sz))
1179    {
1180        LSQ_WARN("no transport parameters: cannot generate zero-rtt info");
1181        return 0;
1182    }
1183    if (trapa_sz > UINT32_MAX)
1184    {
1185        LSQ_WARN("trapa size too large: %zu", trapa_sz);
1186        return 0;
1187    }
1188
1189    if (!SSL_SESSION_to_bytes(session, &ticket_buf, &ticket_sz))
1190    {
1191        LSQ_INFO("could not serialize new session");
1192        return 0;
1193    }
1194    if (ticket_sz > UINT32_MAX)
1195    {
1196        LSQ_WARN("ticket size too large: %zu", ticket_sz);
1197        OPENSSL_free(ticket_buf);
1198        return 0;
1199    }
1200
1201    buf_sz = sizeof(tag) + sizeof(uint32_t) + sizeof(uint32_t)
1202                                + ticket_sz + sizeof(uint32_t) + trapa_sz;
1203    buf = malloc(buf_sz);
1204    if (!buf)
1205    {
1206        OPENSSL_free(ticket_buf);
1207        LSQ_WARN("%s: malloc failed", __func__);
1208        return 0;
1209    }
1210
1211    p = buf;
1212    tag = lsquic_ver2tag(enc_sess->esi_conn->cn_version);
1213    memcpy(p, &tag, sizeof(tag));
1214    p += sizeof(tag);
1215
1216    WRITE_NUM(num, ZERO_RTT_VERSION, p);
1217    WRITE_NUM(num, ticket_sz, p);
1218    memcpy(p, ticket_buf, ticket_sz);
1219    p += ticket_sz;
1220    WRITE_NUM(num, trapa_sz, p);
1221    memcpy(p, trapa_buf, trapa_sz);
1222    p += trapa_sz;
1223
1224    assert(buf + buf_sz == p);
1225    OPENSSL_free(ticket_buf);
1226
1227    LSQ_DEBUG("generated %zu bytes of zero-rtt buffer", buf_sz);
1228
1229    enc_sess->esi_enpub->enp_stream_if->on_zero_rtt_info(enc_sess->esi_conn,
1230                                                                buf, buf_sz);
1231    free(buf);
1232    enc_sess->esi_flags &= ~ESI_WANT_TICKET;
1233    lsquic_alarmset_unset(enc_sess->esi_alset, AL_SESS_TICKET);
1234    return 0;
1235}
1236
1237
1238static int
1239init_client (struct enc_sess_iquic *const enc_sess)
1240{
1241    SSL_CTX *ssl_ctx;
1242    SSL_SESSION *ssl_session;
1243    const struct alpn_map *am;
1244    int transpa_len;
1245    char errbuf[ERR_ERROR_STRING_BUF_LEN];
1246#define hexbuf errbuf   /* This is a dual-purpose buffer */
1247    unsigned char trans_params[0x80];
1248
1249    for (am = s_alpns; am < s_alpns + sizeof(s_alpns)
1250                                                / sizeof(s_alpns[0]); ++am)
1251        if (am->version == enc_sess->esi_ver_neg->vn_ver)
1252            goto ok;
1253
1254    LSQ_ERROR("version %s has no matching ALPN",
1255                            lsquic_ver2str[enc_sess->esi_ver_neg->vn_ver]);
1256    return -1;
1257
1258  ok:
1259    enc_sess->esi_alpn = am->alpn;
1260    LSQ_DEBUG("Create new SSL_CTX");
1261    ssl_ctx = SSL_CTX_new(TLS_method());
1262    if (!ssl_ctx)
1263    {
1264        LSQ_ERROR("cannot create SSL context: %s",
1265            ERR_error_string(ERR_get_error(), errbuf));
1266        goto err;
1267    }
1268    SSL_CTX_set_min_proto_version(ssl_ctx, TLS1_3_VERSION);
1269    SSL_CTX_set_max_proto_version(ssl_ctx, TLS1_3_VERSION);
1270    SSL_CTX_set_default_verify_paths(ssl_ctx);
1271    SSL_CTX_set_session_cache_mode(ssl_ctx, SSL_SESS_CACHE_CLIENT);
1272    if (enc_sess->esi_enpub->enp_stream_if->on_zero_rtt_info)
1273        SSL_CTX_sess_set_new_cb(ssl_ctx, iquic_new_session_cb);
1274    if (enc_sess->esi_enpub->enp_kli)
1275        SSL_CTX_set_keylog_callback(ssl_ctx, keylog_callback);
1276    if (enc_sess->esi_enpub->enp_verify_cert)
1277        SSL_CTX_set_custom_verify(ssl_ctx, SSL_VERIFY_PEER,
1278            verify_server_cert_callback);
1279    SSL_CTX_set_early_data_enabled(ssl_ctx, 1);
1280
1281    transpa_len = gen_trans_params(enc_sess, trans_params,
1282                                                    sizeof(trans_params));
1283    if (transpa_len < 0)
1284    {
1285        goto err;
1286    }
1287
1288    enc_sess->esi_ssl = SSL_new(ssl_ctx);
1289    if (!enc_sess->esi_ssl)
1290    {
1291        LSQ_ERROR("cannot create SSL object: %s",
1292            ERR_error_string(ERR_get_error(), errbuf));
1293        goto err;
1294    }
1295    if (!(SSL_set_quic_method(enc_sess->esi_ssl, &cry_quic_method)))
1296    {
1297        LSQ_INFO("could not set stream method");
1298        goto err;
1299    }
1300    maybe_setup_key_logging(enc_sess);
1301    if (1 != SSL_set_quic_transport_params(enc_sess->esi_ssl, trans_params,
1302                                                            transpa_len))
1303    {
1304        LSQ_ERROR("cannot set QUIC transport params: %s",
1305            ERR_error_string(ERR_get_error(), errbuf));
1306        goto err;
1307    }
1308    if (0 != SSL_set_alpn_protos(enc_sess->esi_ssl, am->alpn, am->alpn[0] + 1))
1309    {
1310        LSQ_ERROR("cannot set ALPN: %s",
1311            ERR_error_string(ERR_get_error(), errbuf));
1312        goto err;
1313    }
1314    if (1 != SSL_set_tlsext_host_name(enc_sess->esi_ssl,
1315                                                    enc_sess->esi_hostname))
1316    {
1317        LSQ_ERROR("cannot set hostname: %s",
1318            ERR_error_string(ERR_get_error(), errbuf));
1319        goto err;
1320    }
1321    free(enc_sess->esi_hostname);
1322    enc_sess->esi_hostname = NULL;
1323    if (enc_sess->esi_zero_rtt_buf)
1324    {
1325        ssl_session = maybe_create_SSL_SESSION(enc_sess, ssl_ctx);
1326        if (ssl_session)
1327        {
1328            if (SSL_set_session(enc_sess->esi_ssl, ssl_session))
1329                enc_sess->esi_flags |= ESI_USE_SSL_TICKET;
1330            else
1331                LSQ_WARN("cannot set session");
1332        }
1333    }
1334
1335    SSL_set_ex_data(enc_sess->esi_ssl, s_idx, enc_sess);
1336    SSL_set_connect_state(enc_sess->esi_ssl);
1337    SSL_CTX_free(ssl_ctx);
1338    LSQ_DEBUG("initialized client enc session");
1339    enc_sess->esi_flags |= ESI_INITIALIZED;
1340    return 0;
1341
1342  err:
1343    if (ssl_ctx)
1344        SSL_CTX_free(ssl_ctx);
1345    return -1;
1346#undef hexbuf
1347}
1348
1349
1350struct crypto_params
1351{
1352    const EVP_AEAD      *aead;
1353    const EVP_MD        *md;
1354    const EVP_CIPHER    *hp;
1355    gen_hp_mask_f        gen_hp_mask;
1356};
1357
1358
1359static int
1360get_crypto_params (const struct enc_sess_iquic *enc_sess,
1361                                                struct crypto_params *params)
1362{
1363    const SSL_CIPHER *cipher;
1364    unsigned key_sz, iv_sz;
1365    uint32_t id;
1366
1367    cipher = SSL_get_current_cipher(enc_sess->esi_ssl);
1368    id = SSL_CIPHER_get_id(cipher);
1369
1370    LSQ_DEBUG("Negotiated cipher ID is 0x%"PRIX32, id);
1371
1372    /* RFC 8446, Appendix B.4 */
1373    switch (id)
1374    {
1375    case 0x03000000 | 0x1301:       /* TLS_AES_128_GCM_SHA256 */
1376        params->md          = EVP_sha256();
1377        params->aead        = EVP_aead_aes_128_gcm();
1378        params->hp          = EVP_aes_128_ecb();
1379        params->gen_hp_mask = gen_hp_mask_aes;
1380        break;
1381    case 0x03000000 | 0x1302:       /* TLS_AES_256_GCM_SHA384 */
1382        params->md          = EVP_sha384();
1383        params->aead        = EVP_aead_aes_256_gcm();
1384        params->hp          = EVP_aes_256_ecb();
1385        params->gen_hp_mask = gen_hp_mask_aes;
1386        break;
1387    case 0x03000000 | 0x1303:       /* TLS_CHACHA20_POLY1305_SHA256 */
1388        params->md          = EVP_sha256();
1389        params->aead        = EVP_aead_chacha20_poly1305();
1390        params->hp          = NULL;
1391        params->gen_hp_mask = gen_hp_mask_chacha20;
1392        break;
1393    default:
1394        /* TLS_AES_128_CCM_SHA256 and TLS_AES_128_CCM_8_SHA256 are not
1395         * supported by BoringSSL (grep for \b0x130[45]\b).
1396         */
1397        LSQ_DEBUG("unsupported cipher 0x%"PRIX32, id);
1398        return -1;
1399    }
1400
1401    key_sz = EVP_AEAD_key_length(params->aead);
1402    if (key_sz > EVP_MAX_KEY_LENGTH)
1403    {
1404        LSQ_DEBUG("key size %u is too large", key_sz);
1405        return -1;
1406    }
1407
1408    iv_sz = EVP_AEAD_nonce_length(params->aead);
1409    if (iv_sz < 8)
1410        iv_sz = 8;  /* [draft-ietf-quic-tls-11], Section 5.3 */
1411    if (iv_sz > EVP_MAX_IV_LENGTH)
1412    {
1413        LSQ_DEBUG("iv size %u is too large", iv_sz);
1414        return -1;
1415    }
1416
1417    if (key_sz > EVP_MAX_KEY_LENGTH)
1418    {
1419        LSQ_DEBUG("PN size %u is too large", key_sz);
1420        return -1;
1421    }
1422
1423    return 0;
1424}
1425
1426
1427static int
1428get_peer_transport_params (struct enc_sess_iquic *enc_sess)
1429{
1430    struct transport_params *const trans_params = &enc_sess->esi_peer_tp;
1431    const uint8_t *params_buf;
1432    size_t bufsz;
1433    char params_str[0x200];
1434
1435    SSL_get_peer_quic_transport_params(enc_sess->esi_ssl, &params_buf, &bufsz);
1436    if (!params_buf)
1437    {
1438        LSQ_DEBUG("no peer transport parameters");
1439        return -1;
1440    }
1441
1442    LSQ_DEBUG("have peer transport parameters (%zu bytes)", bufsz);
1443    if (0 > lsquic_tp_decode(params_buf, bufsz,
1444                            !(enc_sess->esi_flags & ESI_SERVER),
1445                                                trans_params))
1446    {
1447        lsquic_hexdump(params_buf, bufsz, params_str, sizeof(params_str));
1448        LSQ_DEBUG("could not parse peer transport parameters (%zd bytes):\n%s",
1449            bufsz, params_str);
1450        return -1;
1451    }
1452
1453    if ((enc_sess->esi_flags & (ESI_ODCID|ESI_SERVER)) == ESI_ODCID)
1454    {
1455        if (!(trans_params->tp_flags & TRAPA_ORIGINAL_CID))
1456        {
1457            LSQ_DEBUG("server did not produce original DCID (ODCID)");
1458            return -1;
1459        }
1460        if (LSQUIC_CIDS_EQ(&enc_sess->esi_odcid,
1461                                        &trans_params->tp_original_cid))
1462            LSQ_DEBUG("ODCID values match");
1463        else
1464        {
1465            if (LSQ_LOG_ENABLED(LSQ_LOG_DEBUG))
1466            {
1467                char cidbuf[2][MAX_CID_LEN * 2 + 1];
1468                lsquic_cid2str(&enc_sess->esi_odcid, cidbuf[0]);
1469                lsquic_cid2str(&trans_params->tp_original_cid, cidbuf[1]);
1470                LSQ_DEBUG("server provided ODCID %s that does not match "
1471                    "our ODCID %s", cidbuf[1], cidbuf[0]);
1472            }
1473            return -1;
1474        }
1475    }
1476
1477    return 0;
1478}
1479
1480
1481static int
1482maybe_get_peer_transport_params (struct enc_sess_iquic *enc_sess)
1483{
1484    int s;
1485
1486    if (enc_sess->esi_flags & ESI_HAVE_PEER_TP)
1487        return 0;
1488
1489    s = get_peer_transport_params(enc_sess);
1490    if (s == 0)
1491        enc_sess->esi_flags |= ESI_HAVE_PEER_TP;
1492
1493    return s;
1494}
1495
1496
1497static enum iquic_handshake_status
1498iquic_esfi_handshake (struct enc_sess_iquic *enc_sess)
1499{
1500    int s, err;
1501    enum lsquic_hsk_status hsk_status;
1502    char errbuf[ERR_ERROR_STRING_BUF_LEN];
1503
1504    s = SSL_do_handshake(enc_sess->esi_ssl);
1505    if (s <= 0)
1506    {
1507        err = SSL_get_error(enc_sess->esi_ssl, s);
1508        switch (err)
1509        {
1510        case SSL_ERROR_WANT_READ:
1511            LSQ_DEBUG("retry read");
1512            return IHS_WANT_READ;
1513        case SSL_ERROR_WANT_WRITE:
1514            LSQ_DEBUG("retry write");
1515            return IHS_WANT_WRITE;
1516        case SSL_EARLY_DATA_REJECTED:   /* XXX should this be included here? */
1517        case SSL_ERROR_EARLY_DATA_REJECTED:
1518            LSQ_DEBUG("early data rejected");
1519            hsk_status = LSQ_HSK_0RTT_FAIL;
1520            goto err;
1521        default:
1522            LSQ_DEBUG("handshake: %s", ERR_error_string(err, errbuf));
1523            hsk_status = LSQ_HSK_FAIL;
1524            goto err;
1525        }
1526    }
1527
1528
1529    if (SSL_in_early_data(enc_sess->esi_ssl))
1530    {
1531        LSQ_DEBUG("in early data");
1532        if (enc_sess->esi_flags & ESI_SERVER)
1533            LSQ_DEBUG("TODO");
1534        else
1535            return IHS_WANT_READ;
1536    }
1537
1538    hsk_status = LSQ_HSK_OK;
1539    LSQ_DEBUG("handshake reported complete");
1540    EV_LOG_HSK_COMPLETED(LSQUIC_LOG_CONN_ID);
1541    /* The ESI_USE_SSL_TICKET flag indicates if the client attempted 0-RTT.
1542     * If the handshake is complete, and the client attempted 0-RTT, it
1543     * must have succeeded.
1544     */
1545    if (enc_sess->esi_flags & ESI_USE_SSL_TICKET)
1546    {
1547        hsk_status = LSQ_HSK_0RTT_OK;
1548        EV_LOG_ZERO_RTT(LSQUIC_LOG_CONN_ID);
1549    }
1550
1551    if (0 != maybe_get_peer_transport_params(enc_sess))
1552    {
1553        hsk_status = LSQ_HSK_FAIL;
1554        goto err;
1555    }
1556
1557    enc_sess->esi_flags |= ESI_HANDSHAKE_OK;
1558    enc_sess->esi_conn->cn_if->ci_hsk_done(enc_sess->esi_conn, hsk_status);
1559
1560    return IHS_STOP;    /* XXX: what else can come on the crypto stream? */
1561
1562  err:
1563    LSQ_DEBUG("handshake failed");
1564    enc_sess->esi_conn->cn_if->ci_hsk_done(enc_sess->esi_conn, hsk_status);
1565    return IHS_STOP;
1566}
1567
1568
1569static enum iquic_handshake_status
1570iquic_esfi_post_handshake (struct enc_sess_iquic *enc_sess)
1571{
1572    int s;
1573
1574    s = SSL_process_quic_post_handshake(enc_sess->esi_ssl);
1575    LSQ_DEBUG("SSL_process_quic_post_handshake() returned %d", s);
1576    if (s == 1)
1577        return IHS_WANT_READ;
1578    else
1579    {
1580        LSQ_DEBUG("TODO: abort connection?");
1581        return IHS_STOP;
1582    }
1583}
1584
1585
1586static struct transport_params *
1587iquic_esfi_get_peer_transport_params (enc_session_t *enc_session_p)
1588{
1589    struct enc_sess_iquic *const enc_sess = enc_session_p;
1590
1591    if (0 == maybe_get_peer_transport_params(enc_sess))
1592        return &enc_sess->esi_peer_tp;
1593    else
1594        return NULL;
1595}
1596
1597
1598void
1599iquic_esfi_destroy (enc_session_t *enc_session_p)
1600{
1601    struct enc_sess_iquic *const enc_sess = enc_session_p;
1602    struct frab_list *fral;
1603    LSQ_DEBUG("iquic_esfi_destroy");
1604
1605    for (fral = enc_sess->esi_frals; fral < enc_sess->esi_frals
1606            + sizeof(enc_sess->esi_frals) / sizeof(enc_sess->esi_frals[0]);
1607                ++fral)
1608        lsquic_frab_list_cleanup(fral);
1609    if (enc_sess->esi_keylog_handle)
1610        enc_sess->esi_enpub->enp_kli->kli_close(enc_sess->esi_keylog_handle);
1611    if (enc_sess->esi_ssl)
1612        SSL_free(enc_sess->esi_ssl);
1613
1614    free_handshake_keys(enc_sess);
1615
1616    free(enc_sess->esi_zero_rtt_buf);
1617    free(enc_sess->esi_hostname);
1618    free(enc_sess);
1619}
1620
1621
1622/* See [draft-ietf-quic-tls-14], Section 4 */
1623static const enum enc_level hety2el[] =
1624{
1625    [HETY_NOT_SET]   = ENC_LEV_FORW,
1626    [HETY_VERNEG]    = 0,
1627    [HETY_INITIAL]   = ENC_LEV_CLEAR,
1628    [HETY_RETRY]     = 0,
1629    [HETY_HANDSHAKE] = ENC_LEV_INIT,
1630    [HETY_0RTT]      = ENC_LEV_EARLY,
1631};
1632
1633
1634static const enum header_type pns2hety[] =
1635{
1636    [PNS_INIT]  = HETY_INITIAL,
1637    [PNS_HSK]   = HETY_HANDSHAKE,
1638    [PNS_APP]   = HETY_NOT_SET,
1639};
1640
1641
1642static const enum enc_level pns2enc_level[] =
1643{
1644    [PNS_INIT]  = ENC_LEV_CLEAR,
1645    [PNS_HSK]   = ENC_LEV_INIT,
1646    [PNS_APP]   = ENC_LEV_FORW,
1647};
1648
1649
1650static enum enc_packout
1651iquic_esf_encrypt_packet (enc_session_t *enc_session_p,
1652    const struct lsquic_engine_public *enpub, struct lsquic_conn *lconn,
1653    struct lsquic_packet_out *packet_out)
1654{
1655    struct enc_sess_iquic *const enc_sess = enc_session_p;
1656    unsigned char *dst;
1657    const struct crypto_ctx_pair *pair;
1658    const struct crypto_ctx *crypto_ctx;
1659    const struct header_prot *hp;
1660    enum enc_level enc_level;
1661    unsigned char nonce_buf[ sizeof(crypto_ctx->yk_iv_buf) + 8 ];
1662    unsigned char *nonce, *begin_xor;
1663    lsquic_packno_t packno;
1664    size_t out_sz, dst_sz;
1665    int header_sz;
1666    int ipv6;
1667    unsigned packno_off, packno_len, cliser;
1668    enum packnum_space pns;
1669    char errbuf[ERR_ERROR_STRING_BUF_LEN];
1670
1671    assert(lconn == enc_sess->esi_conn);
1672
1673    if (packet_out->po_flags & PO_MINI)
1674    {
1675        /* XXX TODO Don't rely on PO_MINI, generalize this logic */
1676        assert(enc_sess->esi_flags & ESI_SERVER);
1677        enc_level = hety2el[ packet_out->po_header_type ];
1678    }
1679    else
1680    {
1681        pns = lsquic_packet_out_pns(packet_out);
1682        /* TODO Obviously, will need more logic for 0-RTT */
1683        enc_level = pns2enc_level[ pns ];
1684        packet_out->po_header_type = pns2hety[ pns ];
1685    }
1686
1687    cliser = !!(enc_sess->esi_flags & ESI_SERVER);
1688    if (enc_level == ENC_LEV_FORW)
1689    {
1690        pair = &enc_sess->esi_pairs[ enc_sess->esi_key_phase ];
1691        crypto_ctx = &pair->ykp_ctx[ cliser ];
1692        hp = &enc_sess->esi_hp;
1693    }
1694    else if (enc_sess->esi_hsk_pairs)
1695    {
1696        pair = &enc_sess->esi_hsk_pairs[ enc_level ];
1697        crypto_ctx = &pair->ykp_ctx[ cliser ];
1698        hp = &enc_sess->esi_hsk_hps[ enc_level ];
1699    }
1700    else
1701    {
1702        assert(0);
1703        return ENCPA_BADCRYPT;
1704    }
1705
1706    if (UNLIKELY(0 == (crypto_ctx->yk_flags & YK_INITED)))
1707    {
1708        LSQ_WARN("encrypt crypto context at level %s not initialized",
1709                                            lsquic_enclev2str[enc_level]);
1710        return ENCPA_BADCRYPT;
1711    }
1712
1713    if (packet_out->po_data_sz < 3)
1714    {
1715        /* [draft-ietf-quic-tls-20] Section 5.4.2 */
1716        enum packno_bits bits = lsquic_packet_out_packno_bits(packet_out);
1717        unsigned len = iquic_packno_bits2len(bits);
1718        if (packet_out->po_data_sz + len < 4)
1719        {
1720            len = 4 - packet_out->po_data_sz - len;
1721            memset(packet_out->po_data + packet_out->po_data_sz, 0, len);
1722            packet_out->po_data_sz += len;
1723            packet_out->po_frame_types |= QUIC_FTBIT_PADDING;
1724            LSQ_DEBUG("padded packet %"PRIu64" with %u bytes of PADDING",
1725                packet_out->po_packno, len);
1726        }
1727    }
1728
1729    dst_sz = lconn->cn_pf->pf_packout_size(lconn, packet_out);
1730    ipv6 = NP_IS_IPv6(packet_out->po_path);
1731    dst = enpub->enp_pmi->pmi_allocate(enpub->enp_pmi_ctx,
1732                                packet_out->po_path->np_peer_ctx, dst_sz, ipv6);
1733    if (!dst)
1734    {
1735        LSQ_DEBUG("could not allocate memory for outgoing packet of size %zd",
1736                                                                        dst_sz);
1737        return ENCPA_NOMEM;
1738    }
1739
1740    /* Align nonce so we can perform XOR safely in one shot: */
1741    begin_xor = nonce_buf + sizeof(nonce_buf) - 8;
1742    begin_xor = (unsigned char *) ((uintptr_t) begin_xor & ~0x7);
1743    nonce = begin_xor - crypto_ctx->yk_iv_sz + 8;
1744    memcpy(nonce, crypto_ctx->yk_iv_buf, crypto_ctx->yk_iv_sz);
1745    packno = packet_out->po_packno;
1746    if (s_log_seal_and_open)
1747        LSQ_DEBUG("seal: iv: %s; packno: 0x%"PRIX64,
1748            HEXSTR(crypto_ctx->yk_iv_buf, crypto_ctx->yk_iv_sz, s_str), packno);
1749#if __BYTE_ORDER == __LITTLE_ENDIAN
1750    packno = bswap_64(packno);
1751#endif
1752    *((uint64_t *) begin_xor) ^= packno;
1753
1754    header_sz = lconn->cn_pf->pf_gen_reg_pkt_header(lconn, packet_out, dst,
1755                                                                        dst_sz);
1756    if (header_sz < 0)
1757        goto err;
1758    if (enc_level == ENC_LEV_FORW)
1759        dst[0] |= enc_sess->esi_key_phase << 2;
1760
1761    if (s_log_seal_and_open)
1762    {
1763        LSQ_DEBUG("seal: nonce (%u bytes): %s", crypto_ctx->yk_iv_sz,
1764            HEXSTR(nonce, crypto_ctx->yk_iv_sz, s_str));
1765        LSQ_DEBUG("seal: ad (%u bytes): %s", header_sz,
1766            HEXSTR(dst, header_sz, s_str));
1767        LSQ_DEBUG("seal: in (%u bytes): %s", packet_out->po_data_sz,
1768            HEXSTR(packet_out->po_data, packet_out->po_data_sz, s_str));
1769    }
1770    if (!EVP_AEAD_CTX_seal(&crypto_ctx->yk_aead_ctx, dst + header_sz, &out_sz,
1771                dst_sz - header_sz, nonce, crypto_ctx->yk_iv_sz, packet_out->po_data,
1772                packet_out->po_data_sz, dst, header_sz))
1773    {
1774        LSQ_WARN("cannot seal packet #%"PRIu64": %s", packet_out->po_packno,
1775            ERR_error_string(ERR_get_error(), errbuf));
1776        goto err;
1777    }
1778    assert(out_sz == dst_sz - header_sz);
1779
1780    lconn->cn_pf->pf_packno_info(lconn, packet_out, &packno_off, &packno_len);
1781#ifndef NDEBUG
1782    const unsigned sample_off = packno_off + 4;
1783    assert(sample_off + IQUIC_TAG_LEN <= dst_sz);
1784#endif
1785    apply_hp(enc_sess, hp, cliser, dst, packno_off, packno_len);
1786
1787    packet_out->po_enc_data    = dst;
1788    packet_out->po_enc_data_sz = dst_sz;
1789    packet_out->po_sent_sz     = dst_sz;
1790    packet_out->po_flags &= ~PO_IPv6;
1791    packet_out->po_flags |= PO_ENCRYPTED|PO_SENT_SZ|(ipv6 << POIPv6_SHIFT);
1792    lsquic_packet_out_set_enc_level(packet_out, enc_level);
1793    lsquic_packet_out_set_kp(packet_out, enc_sess->esi_key_phase);
1794    return ENCPA_OK;
1795
1796  err:
1797    enpub->enp_pmi->pmi_return(enpub->enp_pmi_ctx,
1798                                packet_out->po_path->np_peer_ctx, dst, ipv6);
1799    return ENCPA_BADCRYPT;
1800}
1801
1802
1803static enum dec_packin
1804iquic_esf_decrypt_packet (enc_session_t *enc_session_p,
1805        struct lsquic_engine_public *enpub, const struct lsquic_conn *lconn,
1806        struct lsquic_packet_in *packet_in)
1807{
1808    struct enc_sess_iquic *const enc_sess = enc_session_p;
1809    unsigned char *dst;
1810    struct crypto_ctx_pair *pair;
1811    const struct header_prot *hp;
1812    struct crypto_ctx *crypto_ctx = NULL;
1813    unsigned char nonce_buf[ sizeof(crypto_ctx->yk_iv_buf) + 8 ];
1814    unsigned char *nonce, *begin_xor;
1815    unsigned sample_off, packno_len, cliser, key_phase;
1816    enum enc_level enc_level;
1817    enum packnum_space pns;
1818    lsquic_packno_t packno;
1819    size_t out_sz;
1820    enum dec_packin dec_packin;
1821    int s;
1822    const size_t dst_sz = packet_in->pi_data_sz;
1823    unsigned char new_secret[EVP_MAX_KEY_LENGTH];
1824    struct crypto_ctx crypto_ctx_buf;
1825    char secret_str[EVP_MAX_KEY_LENGTH * 2 + 1];
1826    char errbuf[ERR_ERROR_STRING_BUF_LEN];
1827
1828    dst = lsquic_mm_get_packet_in_buf(&enpub->enp_mm, dst_sz);
1829    if (!dst)
1830    {
1831        LSQ_WARN("cannot allocate memory to copy incoming packet data");
1832        dec_packin = DECPI_NOMEM;
1833        goto err;
1834    }
1835
1836    enc_level = hety2el[packet_in->pi_header_type];
1837    if (enc_level == ENC_LEV_FORW)
1838        hp = &enc_sess->esi_hp;
1839    else if (enc_sess->esi_hsk_pairs)
1840        hp = &enc_sess->esi_hsk_hps[ enc_level ];
1841    else
1842        hp = NULL;
1843
1844    if (UNLIKELY(!(hp && header_prot_inited(hp))))
1845    {
1846        LSQ_DEBUG("header protection for level %u not initialized yet",
1847                                                                enc_level);
1848        dec_packin = DECPI_NOT_YET;
1849        goto err;
1850    }
1851
1852    /* Decrypt packet number.  After this operation, packet_in is adjusted:
1853     * the packet number becomes part of the header.
1854     */
1855    sample_off = packet_in->pi_header_sz + 4;
1856    if (sample_off + IQUIC_TAG_LEN > packet_in->pi_data_sz)
1857    {
1858        LSQ_INFO("packet data is too short: %hu bytes",
1859                                                packet_in->pi_data_sz);
1860        dec_packin = DECPI_TOO_SHORT;
1861        goto err;
1862    }
1863    cliser = !(enc_sess->esi_flags & ESI_SERVER);
1864    memcpy(dst, packet_in->pi_data, sample_off);
1865    packet_in->pi_packno =
1866    packno = strip_hp(enc_sess, hp, cliser,
1867        packet_in->pi_data + sample_off,
1868        dst, packet_in->pi_header_sz, &packno_len);
1869
1870    if (enc_level == ENC_LEV_FORW)
1871    {
1872        key_phase = (dst[0] & 0x04) > 0;
1873        if (key_phase == enc_sess->esi_key_phase)
1874        {
1875            pair = &enc_sess->esi_pairs[ key_phase ];
1876            crypto_ctx = &pair->ykp_ctx[ cliser ];
1877        }
1878        else if (!is_valid_packno(
1879                        enc_sess->esi_pairs[enc_sess->esi_key_phase].ykp_thresh)
1880                || packet_in->pi_packno
1881                    > enc_sess->esi_pairs[enc_sess->esi_key_phase].ykp_thresh)
1882        {
1883            lsquic_qhkdf_expand(enc_sess->esi_md,
1884                enc_sess->esi_traffic_secrets[cliser], enc_sess->esi_trasec_sz,
1885                "traffic upd", 11, new_secret, enc_sess->esi_trasec_sz);
1886            if (enc_sess->esi_flags & ESI_LOG_SECRETS)
1887                LSQ_DEBUG("key phase changed to %u, will try decrypting using "
1888                    "new secret %s", key_phase, HEXSTR(new_secret,
1889                    enc_sess->esi_trasec_sz, secret_str));
1890            else
1891                LSQ_DEBUG("key phase changed to %u, will try decrypting using "
1892                    "new secret", key_phase);
1893            crypto_ctx = &crypto_ctx_buf;
1894            crypto_ctx->yk_flags = 0;
1895            s = init_crypto_ctx(crypto_ctx, enc_sess->esi_md,
1896                        enc_sess->esi_aead, new_secret, enc_sess->esi_trasec_sz,
1897                        evp_aead_open);
1898            if (s != 0)
1899            {
1900                LSQ_ERROR("could not init open crypto ctx (key phase)");
1901                dec_packin = DECPI_BADCRYPT;
1902                goto err;
1903            }
1904        }
1905        else
1906        {
1907            pair = &enc_sess->esi_pairs[ key_phase ];
1908            crypto_ctx = &pair->ykp_ctx[ cliser ];
1909            if (UNLIKELY(0 == (crypto_ctx->yk_flags & YK_INITED)))
1910            {
1911                LSQ_DEBUG("supposedly older context is not initialized (key "
1912                    "phase: %u)", key_phase);
1913                dec_packin = DECPI_BADCRYPT;
1914                goto err;
1915            }
1916        }
1917    }
1918    else
1919    {
1920        key_phase = 0;
1921        assert(enc_sess->esi_hsk_pairs);
1922        pair = &enc_sess->esi_hsk_pairs[ enc_level ];
1923        crypto_ctx = &pair->ykp_ctx[ cliser ];
1924        if (UNLIKELY(0 == (crypto_ctx->yk_flags & YK_INITED)))
1925        {
1926            LSQ_WARN("decrypt crypto context at level %s not initialized",
1927                                                    lsquic_enclev2str[enc_level]);
1928            dec_packin = DECPI_BADCRYPT;
1929            goto err;
1930        }
1931    }
1932
1933    if (s_log_seal_and_open)
1934        LSQ_DEBUG("open: iv: %s; packno: 0x%"PRIX64,
1935            HEXSTR(crypto_ctx->yk_iv_buf, crypto_ctx->yk_iv_sz, s_str), packno);
1936    /* Align nonce so we can perform XOR safely in one shot: */
1937    begin_xor = nonce_buf + sizeof(nonce_buf) - 8;
1938    begin_xor = (unsigned char *) ((uintptr_t) begin_xor & ~0x7);
1939    nonce = begin_xor - crypto_ctx->yk_iv_sz + 8;
1940    memcpy(nonce, crypto_ctx->yk_iv_buf, crypto_ctx->yk_iv_sz);
1941#if __BYTE_ORDER == __LITTLE_ENDIAN
1942    packno = bswap_64(packno);
1943#endif
1944    *((uint64_t *) begin_xor) ^= packno;
1945
1946    packet_in->pi_header_sz += packno_len;
1947
1948    if (s_log_seal_and_open)
1949    {
1950        LSQ_DEBUG("open: nonce (%u bytes): %s", crypto_ctx->yk_iv_sz,
1951            HEXSTR(nonce, crypto_ctx->yk_iv_sz, s_str));
1952        LSQ_DEBUG("open: ad (%u bytes): %s", packet_in->pi_header_sz,
1953            HEXSTR(dst, packet_in->pi_header_sz, s_str));
1954        LSQ_DEBUG("open: in (%u bytes): %s", packet_in->pi_data_sz
1955            - packet_in->pi_header_sz, HEXSTR(packet_in->pi_data
1956            + packet_in->pi_header_sz, packet_in->pi_data_sz
1957            - packet_in->pi_header_sz, s_str));
1958    }
1959    if (!EVP_AEAD_CTX_open(&crypto_ctx->yk_aead_ctx,
1960                dst + packet_in->pi_header_sz, &out_sz,
1961                dst_sz - packet_in->pi_header_sz, nonce, crypto_ctx->yk_iv_sz,
1962                packet_in->pi_data + packet_in->pi_header_sz,
1963                packet_in->pi_data_sz - packet_in->pi_header_sz,
1964                dst, packet_in->pi_header_sz))
1965    {
1966        LSQ_INFO("cannot open packet #%"PRIu64": %s", packet_in->pi_packno,
1967            ERR_error_string(ERR_get_error(), errbuf));
1968        dec_packin = DECPI_BADCRYPT;
1969        goto err;
1970    }
1971
1972    if (dst[0] & (0x0C << (packet_in->pi_header_type == HETY_NOT_SET)))
1973    {
1974        LSQ_DEBUG("reserved bits are not set to zero");
1975        dec_packin = DECPI_VIOLATION;
1976        goto err;
1977    }
1978
1979    if (crypto_ctx == &crypto_ctx_buf)
1980    {
1981        LSQ_DEBUG("decryption in the new key phase %u successful, rotate "
1982            "keys", key_phase);
1983        pair = &enc_sess->esi_pairs[ key_phase ];
1984        pair->ykp_thresh = packet_in->pi_packno;
1985        pair->ykp_ctx[ cliser ] = crypto_ctx_buf;
1986        memcpy(enc_sess->esi_traffic_secrets[ cliser ], new_secret,
1987                                                enc_sess->esi_trasec_sz);
1988        lsquic_qhkdf_expand(enc_sess->esi_md,
1989            enc_sess->esi_traffic_secrets[!cliser], enc_sess->esi_trasec_sz,
1990            "traffic upd", 11, new_secret, enc_sess->esi_trasec_sz);
1991        memcpy(enc_sess->esi_traffic_secrets[ !cliser ], new_secret,
1992                                                enc_sess->esi_trasec_sz);
1993        s = init_crypto_ctx(&pair->ykp_ctx[ !cliser ], enc_sess->esi_md,
1994                    enc_sess->esi_aead, new_secret, enc_sess->esi_trasec_sz,
1995                    evp_aead_seal);
1996        if (s != 0)
1997        {
1998            LSQ_ERROR("could not init seal crypto ctx (key phase)");
1999            cleanup_crypto_ctx(&pair->ykp_ctx[ !cliser ]);
2000            /* XXX Is this the proper thing to do?  Packet decrypted fine... */
2001            dec_packin = DECPI_BADCRYPT;
2002            goto err;
2003        }
2004        if (enc_sess->esi_flags & ESI_LOG_SECRETS)
2005            log_crypto_pair(enc_sess, pair, "updated");
2006        enc_sess->esi_key_phase = key_phase;
2007    }
2008
2009    packet_in->pi_data_sz = packet_in->pi_header_sz + out_sz;
2010    if (packet_in->pi_flags & PI_OWN_DATA)
2011        lsquic_mm_put_packet_in_buf(&enpub->enp_mm, packet_in->pi_data,
2012                                                        packet_in->pi_data_sz);
2013    packet_in->pi_data = dst;
2014    packet_in->pi_flags |= PI_OWN_DATA | PI_DECRYPTED
2015                        | (enc_level << PIBIT_ENC_LEV_SHIFT);
2016    EV_LOG_CONN_EVENT(LSQUIC_LOG_CONN_ID, "decrypted packet %"PRIu64,
2017                                                    packet_in->pi_packno);
2018    pns = lsquic_enclev2pns[enc_level];
2019    if (packet_in->pi_packno > enc_sess->esi_max_packno[pns])
2020        enc_sess->esi_max_packno[pns] = packet_in->pi_packno;
2021    /* XXX Compiler complains that `pair' may be uninitialized here, but this
2022     * variable is set in `if (crypto_ctx == &crypto_ctx_buf)' above.
2023     */
2024    if (is_valid_packno(pair->ykp_thresh)
2025                                && packet_in->pi_packno > pair->ykp_thresh)
2026        pair->ykp_thresh = packet_in->pi_packno;
2027    return DECPI_OK;
2028
2029  err:
2030    if (crypto_ctx == &crypto_ctx_buf)
2031        cleanup_crypto_ctx(crypto_ctx);
2032    if (dst)
2033        lsquic_mm_put_packet_in_buf(&enpub->enp_mm, dst, dst_sz);
2034    EV_LOG_CONN_EVENT(LSQUIC_LOG_CONN_ID, "could not decrypt packet (type %s, "
2035        "number %"PRIu64")", lsquic_hety2str[packet_in->pi_header_type],
2036                                                    packet_in->pi_packno);
2037    return dec_packin;
2038}
2039
2040
2041static const char *
2042iquic_esf_get_sni (enc_session_t *enc_session_p)
2043{
2044    struct enc_sess_iquic *const enc_sess = enc_session_p;
2045
2046    return SSL_get_servername(enc_sess->esi_ssl, TLSEXT_NAMETYPE_host_name);
2047}
2048
2049
2050static int
2051iquic_esf_global_init (int flags)
2052{
2053    s_idx = SSL_get_ex_new_index(0, NULL, NULL, NULL, NULL);
2054    if (s_idx >= 0)
2055    {
2056        LSQ_LOG1(LSQ_LOG_DEBUG, "SSL extra data index: %d", s_idx);
2057        return 0;
2058    }
2059    else
2060    {
2061        LSQ_LOG1(LSQ_LOG_ERROR, "%s: could not select index", __func__);
2062        return -1;
2063    }
2064}
2065
2066
2067static void
2068iquic_esf_global_cleanup (void)
2069{
2070}
2071
2072
2073static void *
2074copy_X509 (void *cert)
2075{
2076    X509_up_ref(cert);
2077    return cert;
2078}
2079
2080
2081static struct stack_st_X509 *
2082iquic_esf_get_server_cert_chain (enc_session_t *enc_session_p)
2083{
2084    struct enc_sess_iquic *const enc_sess = enc_session_p;
2085    STACK_OF(X509) *chain;
2086
2087    if (enc_sess->esi_ssl)
2088    {
2089        chain = SSL_get_peer_cert_chain(enc_sess->esi_ssl);
2090        return (struct stack_st_X509 *)
2091            sk_deep_copy((const _STACK *) chain, sk_X509_call_copy_func,
2092                copy_X509, sk_X509_call_free_func, (void(*)(void*))X509_free);
2093    }
2094    else
2095        return NULL;
2096}
2097
2098
2099static const char *
2100iquic_esf_cipher (enc_session_t *enc_session_p)
2101{
2102    struct enc_sess_iquic *const enc_sess = enc_session_p;
2103    const SSL_CIPHER *cipher;
2104
2105    if (enc_sess->esi_flags & ESI_CACHED_INFO)
2106        return enc_sess->esi_cached_info.cipher_name;
2107    else if (enc_sess->esi_ssl)
2108    {
2109        cipher = SSL_get_current_cipher(enc_sess->esi_ssl);
2110        return SSL_CIPHER_get_name(cipher);
2111    }
2112    else
2113    {
2114        LSQ_WARN("SSL session is not set");
2115        return "null";
2116    }
2117}
2118
2119
2120static int
2121iquic_esf_keysize (enc_session_t *enc_session_p)
2122{
2123    struct enc_sess_iquic *const enc_sess = enc_session_p;
2124    const SSL_CIPHER *cipher;
2125    uint32_t id;
2126
2127    if (enc_sess->esi_flags & ESI_CACHED_INFO)
2128        return enc_sess->esi_cached_info.alg_bits / 8;
2129    else if (enc_sess->esi_ssl)
2130    {
2131        cipher = SSL_get_current_cipher(enc_sess->esi_ssl);
2132        id = SSL_CIPHER_get_id(cipher);
2133
2134        /* RFC 8446, Appendix B.4 */
2135        switch (id)
2136        {
2137        case 0x03000000 | 0x1301:       /* TLS_AES_128_GCM_SHA256 */
2138            return 128 / 8;
2139        case 0x03000000 | 0x1302:       /* TLS_AES_256_GCM_SHA384 */
2140            return 256 / 8;
2141        case 0x03000000 | 0x1303:       /* TLS_CHACHA20_POLY1305_SHA256 */
2142            return 256 / 8;
2143        default:
2144            return -1;
2145        }
2146    }
2147    else
2148    {
2149        LSQ_WARN("SSL session is not set");
2150        return -1;
2151    }
2152}
2153
2154
2155static int
2156iquic_esf_alg_keysize (enc_session_t *enc_session_p)
2157{
2158    /* Modeled on SslConnection::getEnv() */
2159    return iquic_esf_keysize(enc_session_p);
2160}
2161
2162
2163int
2164iquic_esfi_reset_dcid (enc_session_t *enc_session_p,
2165        const lsquic_cid_t *old_dcid, const lsquic_cid_t *new_dcid)
2166{
2167    struct enc_sess_iquic *const enc_sess = enc_session_p;
2168
2169    enc_sess->esi_odcid = *old_dcid;
2170    enc_sess->esi_flags |= ESI_ODCID;
2171    /* TODO: free previous handshake keys */
2172    if (0 == setup_handshake_keys(enc_sess, new_dcid))
2173    {
2174        LSQ_INFOC("reset DCID to %"CID_FMT, CID_BITS(new_dcid));
2175        return 0;
2176    }
2177    else
2178        return -1;
2179}
2180
2181
2182static void
2183iquic_esfi_1rtt_acked (enc_session_t *sess)
2184{
2185    struct enc_sess_iquic *enc_sess = (struct enc_sess_iquic *) sess;
2186
2187    if (!(enc_sess->esi_flags & ESI_1RTT_ACKED))
2188    {
2189        LSQ_DEBUG("1RTT packet has been acked");
2190        enc_sess->esi_flags |= ESI_1RTT_ACKED;
2191        maybe_drop_SSL(enc_sess);
2192    }
2193}
2194
2195
2196static void iquic_esfi_shake_stream (enc_session_t *sess,
2197                            struct lsquic_stream *stream, const char *what);
2198
2199
2200const struct enc_session_funcs_iquic lsquic_enc_session_iquic_ietf_v1 =
2201{
2202    .esfi_create_client  = iquic_esfi_create_client,
2203    .esfi_destroy        = iquic_esfi_destroy,
2204    .esfi_get_peer_transport_params
2205                         = iquic_esfi_get_peer_transport_params,
2206    .esfi_reset_dcid     = iquic_esfi_reset_dcid,
2207    .esfi_init_server    = iquic_esfi_init_server,
2208    .esfi_set_conn       = iquic_esfi_set_conn,
2209    .esfi_set_streams    = iquic_esfi_set_streams,
2210    .esfi_create_server  = iquic_esfi_create_server,
2211    .esfi_shake_stream   = iquic_esfi_shake_stream,
2212    .esfi_1rtt_acked     = iquic_esfi_1rtt_acked,
2213};
2214
2215
2216const struct enc_session_funcs_common lsquic_enc_session_common_ietf_v1 =
2217{
2218    .esf_encrypt_packet  = iquic_esf_encrypt_packet,
2219    .esf_decrypt_packet  = iquic_esf_decrypt_packet,
2220    .esf_global_cleanup  = iquic_esf_global_cleanup,
2221    .esf_global_init     = iquic_esf_global_init,
2222    .esf_tag_len         = IQUIC_TAG_LEN,
2223    .esf_get_server_cert_chain
2224                         = iquic_esf_get_server_cert_chain,
2225    .esf_get_sni         = iquic_esf_get_sni,
2226    .esf_cipher          = iquic_esf_cipher,
2227    .esf_keysize         = iquic_esf_keysize,
2228    .esf_alg_keysize     = iquic_esf_alg_keysize,
2229};
2230
2231
2232static void
2233cache_info (struct enc_sess_iquic *enc_sess)
2234{
2235    const SSL_CIPHER *cipher;
2236
2237    cipher = SSL_get_current_cipher(enc_sess->esi_ssl);
2238    enc_sess->esi_cached_info.cipher_name = SSL_CIPHER_get_name(cipher);
2239    SSL_CIPHER_get_bits(cipher, &enc_sess->esi_cached_info.alg_bits);
2240    enc_sess->esi_flags |= ESI_CACHED_INFO;
2241}
2242
2243
2244static void
2245drop_SSL (struct enc_sess_iquic *enc_sess)
2246{
2247    LSQ_DEBUG("drop SSL object");
2248    if (enc_sess->esi_conn->cn_if->ci_drop_crypto_streams)
2249        enc_sess->esi_conn->cn_if->ci_drop_crypto_streams(
2250                                                    enc_sess->esi_conn);
2251    cache_info(enc_sess);
2252    SSL_free(enc_sess->esi_ssl);
2253    enc_sess->esi_ssl = NULL;
2254    free_handshake_keys(enc_sess);
2255}
2256
2257
2258static void
2259maybe_drop_SSL (struct enc_sess_iquic *enc_sess)
2260{
2261    /* We rely on the following BoringSSL property: it writes new session
2262     * tickets before marking handshake as complete.  In this case, the new
2263     * session tickets have either been successfully written to crypto stream,
2264     * in which case we can close it, or (unlikely) they are buffered in the
2265     * frab list.
2266     */
2267    if ((enc_sess->esi_flags & (ESI_1RTT_ACKED|ESI_HANDSHAKE_OK))
2268                            == (ESI_1RTT_ACKED|ESI_HANDSHAKE_OK)
2269        && enc_sess->esi_ssl
2270        && lsquic_frab_list_empty(&enc_sess->esi_frals[ENC_LEV_FORW]))
2271    {
2272        if ((enc_sess->esi_flags & (ESI_SERVER|ESI_WANT_TICKET))
2273                                                            != ESI_WANT_TICKET)
2274            drop_SSL(enc_sess);
2275        else if (enc_sess->esi_alset
2276                && !lsquic_alarmset_is_set(enc_sess->esi_alset, AL_SESS_TICKET))
2277        {
2278            LSQ_DEBUG("no session ticket: delay dropping SSL object");
2279            lsquic_alarmset_set(enc_sess->esi_alset, AL_SESS_TICKET,
2280                /* Wait up to two seconds for session tickets */
2281                                                lsquic_time_now() + 2000000);
2282        }
2283    }
2284}
2285
2286
2287static void
2288no_sess_ticket (enum alarm_id alarm_id, void *ctx,
2289                                  lsquic_time_t expiry, lsquic_time_t now)
2290{
2291    struct enc_sess_iquic *enc_sess = ctx;
2292
2293    LSQ_DEBUG("no session tickets forthcoming -- drop SSL");
2294    drop_SSL(enc_sess);
2295}
2296
2297
2298typedef char enums_have_the_same_value[
2299    (int) ssl_encryption_initial     == (int) ENC_LEV_CLEAR &&
2300    (int) ssl_encryption_early_data  == (int) ENC_LEV_EARLY &&
2301    (int) ssl_encryption_handshake   == (int) ENC_LEV_INIT  &&
2302    (int) ssl_encryption_application == (int) ENC_LEV_FORW      ? 1 : -1];
2303
2304static int
2305cry_sm_set_encryption_secret (SSL *ssl, enum ssl_encryption_level_t level,
2306                    const uint8_t *read_secret, const uint8_t *write_secret,
2307                    size_t secret_len)
2308{
2309    struct enc_sess_iquic *enc_sess;
2310    struct crypto_ctx_pair *pair;
2311    struct header_prot *hp;
2312    struct crypto_params crypa;
2313    int i;
2314    int have_alpn;
2315    const unsigned char *alpn;
2316    unsigned alpn_len;
2317    const enum enc_level enc_level = (enum enc_level) level;
2318    const uint8_t *secrets[2];
2319    char errbuf[ERR_ERROR_STRING_BUF_LEN];
2320#define hexbuf errbuf
2321
2322    enc_sess = SSL_get_ex_data(ssl, s_idx);
2323    if (!enc_sess)
2324        return 0;
2325
2326    if ((enc_sess->esi_flags & (ESI_ALPN_CHECKED|ESI_SERVER)) == ESI_SERVER)
2327    {
2328        enc_sess->esi_flags |= ESI_ALPN_CHECKED;
2329        SSL_get0_alpn_selected(enc_sess->esi_ssl, &alpn, &alpn_len);
2330        have_alpn = alpn && alpn_len == enc_sess->esi_alpn[0]
2331                            && 0 == memcmp(alpn, enc_sess->esi_alpn + 1, alpn_len);
2332        if (have_alpn)
2333            LSQ_DEBUG("Selected ALPN %.*s", (int) alpn_len, (char *) alpn);
2334        else
2335        {
2336            LSQ_INFO("No ALPN is selected: send fatal alert");
2337            SSL_send_fatal_alert(ssl, ALERT_NO_APPLICATION_PROTOCOL);
2338            return 0;
2339        }
2340    }
2341
2342    if (0 != get_crypto_params(enc_sess, &crypa))
2343        return 0;
2344
2345    if (enc_sess->esi_flags & ESI_SERVER)
2346    {
2347        if (enc_level != ENC_LEV_EARLY)
2348            secrets[0] = read_secret, secrets[1] = write_secret;
2349        else
2350            secrets[1] = read_secret, secrets[0] = write_secret;
2351    }
2352    else
2353    {
2354        if (enc_level != ENC_LEV_EARLY)
2355            secrets[0] = write_secret, secrets[1] = read_secret;
2356        else
2357            secrets[1] = write_secret, secrets[0] = read_secret;
2358    }
2359
2360    if (enc_level < ENC_LEV_FORW)
2361    {
2362        assert(enc_sess->esi_hsk_pairs);
2363        pair = &enc_sess->esi_hsk_pairs[enc_level];
2364        hp = &enc_sess->esi_hsk_hps[enc_level];
2365    }
2366    else
2367    {
2368        pair = &enc_sess->esi_pairs[0];
2369        hp = &enc_sess->esi_hp;
2370        enc_sess->esi_trasec_sz = secret_len;
2371        memcpy(enc_sess->esi_traffic_secrets[0], secrets[0], secret_len);
2372        memcpy(enc_sess->esi_traffic_secrets[1], secrets[1], secret_len);
2373        enc_sess->esi_md = crypa.md;
2374        enc_sess->esi_aead = crypa.aead;
2375    }
2376    pair->ykp_thresh = IQUIC_INVALID_PACKNO;
2377
2378    LSQ_DEBUG("set encryption for level %u", enc_level);
2379    for (i = 1; i >= 0; --i)
2380    {
2381        if (secrets[i])
2382        {
2383            if (enc_sess->esi_flags & ESI_LOG_SECRETS)
2384                LSQ_DEBUG("new %s secret: %s", i ? "server" : "client",
2385                                    HEXSTR(secrets[i], secret_len, hexbuf));
2386            if (0 != init_crypto_ctx(&pair->ykp_ctx[i], crypa.md,
2387                        crypa.aead, secrets[i], secret_len, enc_sess->esi_dir[i]))
2388                goto err;
2389        }
2390        else
2391            assert(level == ssl_encryption_early_data);
2392    }
2393
2394    hp->hp_enc_level = enc_level;
2395    hp->hp_cipher    = crypa.hp;
2396    hp->hp_gen_mask  = crypa.gen_hp_mask;
2397    derive_hp_secrets(hp, crypa.md, crypa.aead, secret_len, secrets[0],
2398                                                                secrets[1]);
2399
2400    if (enc_sess->esi_flags & ESI_LOG_SECRETS)
2401    {
2402        log_crypto_pair(enc_sess, pair, "new");
2403        log_hp(enc_sess, hp, "new");
2404    }
2405
2406    return 1;
2407
2408  err:
2409    cleanup_crypto_ctx(&pair->ykp_ctx[0]);
2410    cleanup_crypto_ctx(&pair->ykp_ctx[1]);
2411    return 0;
2412#undef hexbuf
2413}
2414
2415
2416static int
2417cry_sm_write_message (SSL *ssl, enum ssl_encryption_level_t level,
2418                                            const uint8_t *data, size_t len)
2419{
2420    struct enc_sess_iquic *enc_sess;
2421    void *stream;
2422    ssize_t nw;
2423
2424    enc_sess = SSL_get_ex_data(ssl, s_idx);
2425    if (!enc_sess)
2426        return 0;
2427
2428    stream = enc_sess->esi_streams[level];
2429    if (!stream)
2430        return 0;
2431
2432    /* The frab list logic is only applicable on the client.  XXX This is
2433     * likely to change when support for key updates is added.
2434     */
2435    if (enc_sess->esi_flags & (ESI_ON_WRITE|ESI_SERVER))
2436        nw = enc_sess->esi_cryst_if->csi_write(stream, data, len);
2437    else
2438    {
2439        LSQ_DEBUG("not in on_write event: buffer in a frab list");
2440        if (0 == lsquic_frab_list_write(&enc_sess->esi_frals[level], data, len))
2441        {
2442            if (!lsquic_frab_list_empty(&enc_sess->esi_frals[level]))
2443                enc_sess->esi_cryst_if->csi_wantwrite(stream, 1);
2444            nw = len;
2445        }
2446        else
2447            nw = -1;
2448    }
2449
2450    if (nw >= 0 && (size_t) nw == len)
2451    {
2452        enc_sess->esi_last_w = (enum enc_level) level;
2453        LSQ_DEBUG("wrote %zu bytes to stream at encryption level %u",
2454            len, level);
2455        maybe_drop_SSL(enc_sess);
2456        return 1;
2457    }
2458    else
2459    {
2460        LSQ_INFO("could not write %zu bytes: returned %zd", len, nw);
2461        return 0;
2462    }
2463}
2464
2465
2466static int
2467cry_sm_flush_flight (SSL *ssl)
2468{
2469    struct enc_sess_iquic *enc_sess;
2470    void *stream;
2471    unsigned level;
2472    int s;
2473
2474    enc_sess = SSL_get_ex_data(ssl, s_idx);
2475    if (!enc_sess)
2476        return 0;
2477
2478    level = enc_sess->esi_last_w;
2479    stream = enc_sess->esi_streams[level];
2480    if (!stream)
2481        return 0;
2482
2483    if (lsquic_frab_list_empty(&enc_sess->esi_frals[level]))
2484    {
2485        s = enc_sess->esi_cryst_if->csi_flush(stream);
2486        return s == 0;
2487    }
2488    else
2489        /* Frab list will get flushed */    /* TODO: add support for
2490        recording flush points in frab list. */
2491        return 1;
2492}
2493
2494
2495static int
2496cry_sm_send_alert (SSL *ssl, enum ssl_encryption_level_t level, uint8_t alert)
2497{
2498    struct enc_sess_iquic *enc_sess;
2499
2500    enc_sess = SSL_get_ex_data(ssl, s_idx);
2501    if (!enc_sess)
2502        return 0;
2503
2504    LSQ_INFO("got alert %"PRIu8, alert);
2505    enc_sess->esi_conn->cn_if->ci_tls_alert(enc_sess->esi_conn, alert);
2506
2507    return 1;
2508}
2509
2510
2511static const SSL_QUIC_METHOD cry_quic_method =
2512{
2513    .set_encryption_secrets = cry_sm_set_encryption_secret,
2514    .add_handshake_data     = cry_sm_write_message,
2515    .flush_flight           = cry_sm_flush_flight,
2516    .send_alert             = cry_sm_send_alert,
2517};
2518
2519
2520static lsquic_stream_ctx_t *
2521chsk_ietf_on_new_stream (void *stream_if_ctx, struct lsquic_stream *stream)
2522{
2523    struct enc_sess_iquic *const enc_sess = stream_if_ctx;
2524    enum enc_level enc_level;
2525
2526    enc_level = enc_sess->esi_cryst_if->csi_enc_level(stream);
2527    if (enc_level != ENC_LEV_CLEAR)
2528    {
2529        LSQ_DEBUG("skip initialization of stream at level %u", enc_level);
2530        goto end;
2531    }
2532
2533    if (
2534        (enc_sess->esi_flags & ESI_SERVER) == 0 &&
2535        0 != init_client(enc_sess))
2536    {
2537        LSQ_WARN("enc session could not be initialized");
2538        return NULL;
2539    }
2540
2541    enc_sess->esi_cryst_if->csi_wantwrite(stream, 1);
2542
2543    LSQ_DEBUG("handshake stream created successfully");
2544
2545  end:
2546    return stream_if_ctx;
2547}
2548
2549
2550static lsquic_stream_ctx_t *
2551shsk_ietf_on_new_stream (void *stream_if_ctx, struct lsquic_stream *stream)
2552{
2553    struct enc_sess_iquic *const enc_sess = stream_if_ctx;
2554    enum enc_level enc_level;
2555
2556    enc_level = enc_sess->esi_cryst_if->csi_enc_level(stream);
2557    LSQ_DEBUG("on_new_stream called on level %u", enc_level);
2558
2559    enc_sess->esi_cryst_if->csi_wantread(stream, 1);
2560
2561    return stream_if_ctx;
2562}
2563
2564
2565static void
2566chsk_ietf_on_close (struct lsquic_stream *stream, lsquic_stream_ctx_t *ctx)
2567{
2568    struct enc_sess_iquic *const enc_sess = (struct enc_sess_iquic *) ctx;
2569    LSQ_DEBUG("crypto stream level %u is closed",
2570                (unsigned) enc_sess->esi_cryst_if->csi_enc_level(stream));
2571}
2572
2573
2574static const char *const ihs2str[] = {
2575    [IHS_WANT_READ]  = "want read",
2576    [IHS_WANT_WRITE] = "want write",
2577    [IHS_STOP]       = "stop",
2578};
2579
2580
2581static void
2582iquic_esfi_shake_stream (enc_session_t *sess,
2583                            struct lsquic_stream *stream, const char *what)
2584{
2585    struct enc_sess_iquic *enc_sess = (struct enc_sess_iquic *)sess;
2586    enum iquic_handshake_status st;
2587    enum enc_level enc_level;
2588    int write;
2589    if (0 == (enc_sess->esi_flags & ESI_HANDSHAKE_OK))
2590        st = iquic_esfi_handshake(enc_sess);
2591    else
2592        st = iquic_esfi_post_handshake(enc_sess);
2593    enc_level = enc_sess->esi_cryst_if->csi_enc_level(stream);
2594    LSQ_DEBUG("enc level %s after %s: %s", lsquic_enclev2str[enc_level], what,
2595                                                                ihs2str[st]);
2596    switch (st)
2597    {
2598    case IHS_WANT_READ:
2599        write = !lsquic_frab_list_empty(&enc_sess->esi_frals[enc_level]);
2600        enc_sess->esi_cryst_if->csi_wantwrite(stream, write);
2601        enc_sess->esi_cryst_if->csi_wantread(stream, 1);
2602        break;
2603    case IHS_WANT_WRITE:
2604        enc_sess->esi_cryst_if->csi_wantwrite(stream, 1);
2605        enc_sess->esi_cryst_if->csi_wantread(stream, 0);
2606        break;
2607    default:
2608        assert(st == IHS_STOP);
2609        write = !lsquic_frab_list_empty(&enc_sess->esi_frals[enc_level]);
2610        enc_sess->esi_cryst_if->csi_wantwrite(stream, write);
2611        enc_sess->esi_cryst_if->csi_wantread(stream, 0);
2612        break;
2613    }
2614    LSQ_DEBUG("Exit shake_stream");
2615    maybe_drop_SSL(enc_sess);
2616}
2617
2618
2619struct readf_ctx
2620{
2621    struct enc_sess_iquic  *enc_sess;
2622    enum enc_level          enc_level;
2623    int                     err;
2624};
2625
2626
2627static size_t
2628readf_cb (void *ctx, const unsigned char *buf, size_t len, int fin)
2629{
2630    struct readf_ctx *const readf_ctx = (void *) ctx;
2631    struct enc_sess_iquic *const enc_sess = readf_ctx->enc_sess;
2632    int s;
2633    size_t str_sz;
2634    char str[MAX(1500 * 5, ERR_ERROR_STRING_BUF_LEN)];
2635
2636    s = SSL_provide_quic_data(enc_sess->esi_ssl,
2637                (enum ssl_encryption_level_t) readf_ctx->enc_level, buf, len);
2638    if (s)
2639    {
2640        LSQ_DEBUG("provided %zu bytes of %u-level data to SSL", len,
2641                                                        readf_ctx->enc_level);
2642        str_sz = lsquic_hexdump(buf, len, str, sizeof(str));
2643        LSQ_DEBUG("\n%.*s", (int) str_sz, str);
2644        return len;
2645    }
2646    else
2647    {
2648        LSQ_WARN("SSL_provide_quic_data returned false: %s",
2649                                    ERR_error_string(ERR_get_error(), str));
2650        readf_ctx->err++;
2651        return 0;
2652    }
2653}
2654
2655
2656static size_t
2657discard_cb (void *ctx, const unsigned char *buf, size_t len, int fin)
2658{
2659    return len;
2660}
2661
2662
2663static void
2664chsk_ietf_on_read (struct lsquic_stream *stream, lsquic_stream_ctx_t *ctx)
2665{
2666    struct enc_sess_iquic *const enc_sess = (void *) ctx;
2667    enum enc_level enc_level = enc_sess->esi_cryst_if->csi_enc_level(stream);
2668    struct readf_ctx readf_ctx = { enc_sess, enc_level, 0, };
2669    ssize_t nread;
2670
2671
2672    if (enc_sess->esi_ssl)
2673    {
2674        nread = enc_sess->esi_cryst_if->csi_readf(stream, readf_cb, &readf_ctx);
2675        if (!(nread < 0 || readf_ctx.err))
2676            iquic_esfi_shake_stream((enc_session_t *)enc_sess, stream,
2677                                                                    "on_read");
2678        else
2679            enc_sess->esi_conn->cn_if->ci_internal_error(enc_sess->esi_conn,
2680                "shaking stream failed: nread: %zd, err: %d, SSL err: %"PRIu32,
2681                nread, readf_ctx.err, ERR_get_error());
2682    }
2683    else
2684    {
2685        /* This branch is reached when we don't want TLS ticket and drop
2686         * the SSL object before we process TLS tickets that have been
2687         * already received and waiting in the incoming stream buffer.
2688         */
2689        nread = enc_sess->esi_cryst_if->csi_readf(stream, discard_cb, NULL);
2690        lsquic_stream_wantread(stream, 0);
2691        LSQ_DEBUG("no SSL object: discard %zd bytes of SSL data", nread);
2692    }
2693}
2694
2695
2696static void
2697maybe_write_from_fral (struct enc_sess_iquic *enc_sess,
2698                                                struct lsquic_stream *stream)
2699{
2700    enum enc_level enc_level = enc_sess->esi_cryst_if->csi_enc_level(stream);
2701    struct frab_list *const fral = &enc_sess->esi_frals[enc_level];
2702    struct lsquic_reader reader = {
2703        .lsqr_read  = lsquic_frab_list_read,
2704        .lsqr_size  = lsquic_frab_list_size,
2705        .lsqr_ctx   = fral,
2706    };
2707    ssize_t nw;
2708
2709    if (lsquic_frab_list_empty(fral))
2710        return;
2711
2712    nw = lsquic_stream_writef(stream, &reader);
2713    if (nw >= 0)
2714    {
2715        LSQ_DEBUG("wrote %zd bytes to stream from frab list", nw);
2716        (void) lsquic_stream_flush(stream);
2717        if (lsquic_frab_list_empty(fral))
2718            lsquic_stream_wantwrite(stream, 0);
2719    }
2720    else
2721    {
2722        /* TODO: abort connection */
2723        LSQ_WARN("cannot write to stream: %s", strerror(errno));
2724        lsquic_stream_wantwrite(stream, 0);
2725    }
2726}
2727
2728
2729static void
2730chsk_ietf_on_write (struct lsquic_stream *stream, lsquic_stream_ctx_t *ctx)
2731{
2732    struct enc_sess_iquic *const enc_sess = (void *) ctx;
2733
2734    maybe_write_from_fral(enc_sess, stream);
2735
2736    enc_sess->esi_flags |= ESI_ON_WRITE;
2737    iquic_esfi_shake_stream(enc_sess, stream, "on_write");
2738    enc_sess->esi_flags &= ~ESI_ON_WRITE;
2739}
2740
2741
2742const struct lsquic_stream_if lsquic_cry_sm_if =
2743{
2744    .on_new_stream = chsk_ietf_on_new_stream,
2745    .on_read       = chsk_ietf_on_read,
2746    .on_write      = chsk_ietf_on_write,
2747    .on_close      = chsk_ietf_on_close,
2748};
2749
2750
2751const struct lsquic_stream_if lsquic_mini_cry_sm_if =
2752{
2753    .on_new_stream = shsk_ietf_on_new_stream,
2754    .on_read       = chsk_ietf_on_read,
2755    .on_write      = chsk_ietf_on_write,
2756    .on_close      = chsk_ietf_on_close,
2757};
2758
2759
2760struct ssl_st *
2761lsquic_hsk_getssl (lsquic_conn_t *conn)
2762{
2763    if (!conn || !(conn->cn_flags & LSCONN_IETF))
2764        return NULL;
2765    return ((struct enc_sess_iquic *)conn->cn_enc_session)->esi_ssl;
2766}
2767