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