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