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