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