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