lsquic_enc_sess_ietf.c revision 65728dc5
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};
276
277
278static void
279gen_hp_mask_aes (struct enc_sess_iquic *enc_sess,
280        const struct header_prot *hp, unsigned cliser,
281        const unsigned char *sample, unsigned char mask[EVP_MAX_BLOCK_LENGTH])
282{
283    EVP_CIPHER_CTX hp_ctx;
284    int out_len;
285
286    EVP_CIPHER_CTX_init(&hp_ctx);
287    if (EVP_EncryptInit_ex(&hp_ctx, hp->hp_cipher, NULL, hp->hp_buf[cliser], 0)
288        && EVP_EncryptUpdate(&hp_ctx, mask, &out_len, sample, 16))
289    {
290        assert(out_len >= 5);
291    }
292    else
293    {
294        LSQ_WARN("cannot generate hp mask, error code: %"PRIu32,
295                                                            ERR_get_error());
296        enc_sess->esi_conn->cn_if->ci_internal_error(enc_sess->esi_conn,
297            "cannot generate hp mask, error code: %"PRIu32, ERR_get_error());
298    }
299
300    (void) EVP_CIPHER_CTX_cleanup(&hp_ctx);
301}
302
303
304static void
305gen_hp_mask_chacha20 (struct enc_sess_iquic *enc_sess,
306        const struct header_prot *hp, unsigned cliser,
307        const unsigned char *sample, unsigned char mask[EVP_MAX_BLOCK_LENGTH])
308{
309    const uint8_t *nonce;
310    uint32_t counter;
311
312#if __BYTE_ORDER == __LITTLE_ENDIAN
313    memcpy(&counter, sample, sizeof(counter));
314#else
315#error TODO: support non-little-endian machines
316#endif
317    nonce = sample + sizeof(counter);
318    CRYPTO_chacha_20(mask, (unsigned char [5]) { 0, 0, 0, 0, 0, }, 5,
319                                        hp->hp_buf[cliser], nonce, counter);
320}
321
322
323static void
324apply_hp (struct enc_sess_iquic *enc_sess,
325        const struct header_prot *hp, unsigned cliser,
326        unsigned char *dst, unsigned packno_off, unsigned packno_len)
327{
328    unsigned char mask[EVP_MAX_BLOCK_LENGTH];
329    char mask_str[5 * 2 + 1];
330
331    hp->hp_gen_mask(enc_sess, hp, cliser, dst + packno_off + 4, mask);
332    LSQ_DEBUG("apply header protection using mask %s",
333                                                HEXSTR(mask, 5, mask_str));
334    dst[0] ^= (0xF | (((dst[0] & 0x80) == 0) << 4)) & mask[0];
335    switch (packno_len)
336    {
337    case 4:
338        dst[packno_off + 3] ^= mask[4];
339        /* fall-through */
340    case 3:
341        dst[packno_off + 2] ^= mask[3];
342        /* fall-through */
343    case 2:
344        dst[packno_off + 1] ^= mask[2];
345        /* fall-through */
346    default:
347        dst[packno_off + 0] ^= mask[1];
348    }
349}
350
351
352static lsquic_packno_t
353decode_packno (lsquic_packno_t max_packno, lsquic_packno_t packno,
354                                                                unsigned shift)
355{
356    lsquic_packno_t candidates[3], epoch_delta;
357    int64_t diffs[3];
358    unsigned min;;
359
360    epoch_delta = 1ULL << shift;
361    candidates[1] = (max_packno & ~(epoch_delta - 1)) + packno;
362    candidates[0] = candidates[1] - epoch_delta;
363    candidates[2] = candidates[1] + epoch_delta;
364
365    diffs[0] = llabs((int64_t) candidates[0] - (int64_t) max_packno);
366    diffs[1] = llabs((int64_t) candidates[1] - (int64_t) max_packno);
367    diffs[2] = llabs((int64_t) candidates[2] - (int64_t) max_packno);
368
369    min = diffs[1] < diffs[0];
370    if (diffs[2] < diffs[min])
371        min = 2;
372
373    return candidates[min];
374}
375
376
377static lsquic_packno_t
378strip_hp (struct enc_sess_iquic *enc_sess,
379        const struct header_prot *hp, unsigned cliser,
380        const unsigned char *iv, unsigned char *dst, unsigned packno_off,
381        unsigned *packno_len)
382{
383    enum packnum_space pns;
384    lsquic_packno_t packno;
385    unsigned shift;
386    unsigned char mask[EVP_MAX_BLOCK_LENGTH];
387    char mask_str[5 * 2 + 1];
388
389    hp->hp_gen_mask(enc_sess, hp, cliser, iv, mask);
390    LSQ_DEBUG("strip header protection using mask %s",
391                                                HEXSTR(mask, 5, mask_str));
392    dst[0] ^= (0xF | (((dst[0] & 0x80) == 0) << 4)) & mask[0];
393    packno = 0;
394    shift = 0;
395    *packno_len = 1 + (dst[0] & 3);
396    switch (*packno_len)
397    {
398    case 4:
399        dst[packno_off + 3] ^= mask[4];
400        packno |= dst[packno_off + 3];
401        shift += 8;
402        /* fall-through */
403    case 3:
404        dst[packno_off + 2] ^= mask[3];
405        packno |= dst[packno_off + 2] << shift;
406        shift += 8;
407        /* fall-through */
408    case 2:
409        dst[packno_off + 1] ^= mask[2];
410        packno |= dst[packno_off + 1] << shift;
411        shift += 8;
412        /* fall-through */
413    default:
414        dst[packno_off + 0] ^= mask[1];
415        packno |= dst[packno_off + 0] << shift;
416        shift += 8;
417    }
418    pns = lsquic_enclev2pns[hp->hp_enc_level];
419    return decode_packno(enc_sess->esi_max_packno[pns], packno, shift);
420}
421
422
423static int
424gen_trans_params (struct enc_sess_iquic *enc_sess, unsigned char *buf,
425                                                                size_t bufsz)
426{
427    const struct lsquic_engine_settings *const settings =
428                                    &enc_sess->esi_enpub->enp_settings;
429    struct transport_params params;
430    int len;
431
432    memset(&params, 0, sizeof(params));
433    if (enc_sess->esi_flags & ESI_SERVER)
434    {
435        const struct lsquic_conn *const lconn = enc_sess->esi_conn;
436
437        params.tp_flags |= TRAPA_SERVER|TRAPA_RESET_TOKEN;
438
439        lsquic_tg_generate_sreset(enc_sess->esi_enpub->enp_tokgen,
440            CN_SCID(lconn), params.tp_stateless_reset_token);
441
442        if (enc_sess->esi_flags & ESI_ODCID)
443        {
444            params.tp_original_cid = enc_sess->esi_odcid;
445            params.tp_flags |= TRAPA_ORIGINAL_CID;
446        }
447#if LSQUIC_PREFERRED_ADDR
448        char addr_buf[INET6_ADDRSTRLEN + 6 /* port */ + 1];
449        const char *s, *colon;
450        struct lsquic_conn *conn;
451        struct conn_cid_elem *cce;
452        unsigned seqno;
453        s = getenv("LSQUIC_PREFERRED_ADDR4");
454        if (s && strlen(s) < sizeof(addr_buf) && (colon = strchr(s, ':')))
455        {
456            strncpy(addr_buf, s, colon - s);
457            addr_buf[colon - s] = '\0';
458            inet_pton(AF_INET, addr_buf, params.tp_preferred_address.ipv4_addr);
459            params.tp_preferred_address.ipv4_port = atoi(colon + 1);
460            params.tp_flags |= TRAPA_PREFADDR_IPv4;
461        }
462        s = getenv("LSQUIC_PREFERRED_ADDR6");
463        if (s && strlen(s) < sizeof(addr_buf) && (colon = strrchr(s, ':')))
464        {
465            strncpy(addr_buf, s, colon - s);
466            addr_buf[colon - s] = '\0';
467            inet_pton(AF_INET6, addr_buf,
468                                        params.tp_preferred_address.ipv6_addr);
469            params.tp_preferred_address.ipv6_port = atoi(colon + 1);
470            params.tp_flags |= TRAPA_PREFADDR_IPv6;
471        }
472        conn = enc_sess->esi_conn;
473        if ((params.tp_flags & (TRAPA_PREFADDR_IPv4|TRAPA_PREFADDR_IPv6))
474                            && (1 << conn->cn_n_cces) - 1 != conn->cn_cces_mask)
475        {
476            seqno = 0;
477            for (cce = lconn->cn_cces; cce < END_OF_CCES(lconn); ++cce)
478            {
479                if (lconn->cn_cces_mask & (1 << (cce - lconn->cn_cces)))
480                {
481                    if ((cce->cce_flags & CCE_SEQNO) && cce->cce_seqno > seqno)
482                        seqno = cce->cce_seqno;
483                }
484                else
485                    break;
486            }
487            if (cce == END_OF_CCES(lconn))
488            {
489                goto cant_use_prefaddr;
490            }
491            cce->cce_seqno = seqno + 1;
492            cce->cce_flags = CCE_SEQNO;
493            lsquic_generate_cid(&cce->cce_cid,
494                            enc_sess->esi_enpub->enp_settings.es_scid_len);
495            /* Don't add to hash: migration must not start until *after*
496             * handshake is complete.
497             */
498            conn->cn_cces_mask |= 1 << (cce - conn->cn_cces);
499            params.tp_preferred_address.cid = cce->cce_cid;
500            lsquic_tg_generate_sreset(enc_sess->esi_enpub->enp_tokgen,
501                &params.tp_preferred_address.cid,
502                params.tp_preferred_address.srst);
503        }
504        else
505        {
506  cant_use_prefaddr:
507            params.tp_flags &= ~(TRAPA_PREFADDR_IPv4|TRAPA_PREFADDR_IPv6);
508        }
509#endif
510    }
511    params.tp_init_max_data = settings->es_init_max_data;
512    params.tp_init_max_stream_data_bidi_local
513                            = settings->es_init_max_stream_data_bidi_local;
514    params.tp_init_max_stream_data_bidi_remote
515                            = settings->es_init_max_stream_data_bidi_remote;
516    params.tp_init_max_stream_data_uni
517                            = settings->es_init_max_stream_data_uni;
518    params.tp_init_max_streams_uni
519                            = settings->es_init_max_streams_uni;
520    params.tp_init_max_streams_bidi
521                            = settings->es_init_max_streams_bidi;
522    params.tp_ack_delay_exponent
523                            = TP_DEF_ACK_DELAY_EXP;
524    params.tp_idle_timeout  = settings->es_idle_timeout * 1000;
525    params.tp_max_ack_delay = TP_DEF_MAX_ACK_DELAY;
526    params.tp_max_packet_size = 1370 /* XXX: based on socket */;
527    params.tp_active_connection_id_limit = MAX_IETF_CONN_DCIDS
528        - 1 /* One slot is used by peer's SCID */
529        - !!(params.tp_flags & (TRAPA_PREFADDR_IPv4|TRAPA_PREFADDR_IPv6));
530    if (!settings->es_allow_migration)
531        params.tp_disable_active_migration = 1;
532
533    len = lsquic_tp_encode(&params, buf, bufsz);
534    if (len >= 0)
535        LSQ_DEBUG("generated transport parameters buffer of %d bytes", len);
536    else
537        LSQ_WARN("cannot generate transport parameters: %d", errno);
538    return len;
539}
540
541
542/*
543 * Format:
544 *      uint32_t    lsquic_ver_tag_t
545 *      uint32_t    encoder version
546 *      uint32_t    ticket_size
547 *      uint8_t     ticket_buf[ ticket_size ]
548 *      uint32_t    trapa_size
549 *      uint8_t     trapa_buf[ trapa_size ]
550 */
551
552#define ZERO_RTT_VERSION 1
553
554#if __BYTE_ORDER == __LITTLE_ENDIAN
555#define READ_NUM(var_, ptr_) do {                               \
556    memcpy(&var_, ptr_, sizeof(var_));                          \
557    var_ = bswap_32(var_);                                      \
558    ptr_ += sizeof(var_);                                       \
559} while (0)
560#else
561#define READ_NUM(var_, ptr_) do {                               \
562    memcpy(&var_, ptr_, sizeof(var_));                          \
563    ptr_ += sizeof(var_);                                       \
564} while (0)
565#endif
566
567static SSL_SESSION *
568maybe_create_SSL_SESSION (struct enc_sess_iquic *enc_sess,
569                                                    const SSL_CTX *ssl_ctx)
570{
571    SSL_SESSION *ssl_session;
572    lsquic_ver_tag_t ver_tag;
573    enum lsquic_version quic_ver;
574    uint32_t rtt_ver, ticket_sz, trapa_sz;
575    const unsigned char *ticket_buf, *trapa_buf, *p;
576    const unsigned char *const end
577                    = enc_sess->esi_zero_rtt_buf + enc_sess->esi_zero_rtt_sz;
578
579    if (enc_sess->esi_zero_rtt_sz
580                    < sizeof(ver_tag) + sizeof(rtt_ver) + sizeof(ticket_sz))
581    {
582        LSQ_DEBUG("rtt buf too short");
583        return NULL;
584    }
585
586    p = enc_sess->esi_zero_rtt_buf;
587    memcpy(&ver_tag, p, sizeof(ver_tag));
588    p += sizeof(ver_tag);
589    quic_ver = lsquic_tag2ver(ver_tag);
590    if (quic_ver != enc_sess->esi_ver_neg->vn_ver)
591    {
592        LSQ_DEBUG("negotiated version %s does not match that in the zero-rtt "
593            "info buffer", lsquic_ver2str[enc_sess->esi_ver_neg->vn_ver]);
594        return NULL;
595    }
596
597    READ_NUM(rtt_ver, p);
598    if (rtt_ver != ZERO_RTT_VERSION)
599    {
600        LSQ_DEBUG("cannot use zero-rtt buffer: encoded using %"PRIu32", "
601                "while current version is %u", rtt_ver, ZERO_RTT_VERSION);
602        return NULL;
603    }
604
605    READ_NUM(ticket_sz, p);
606    if (p + ticket_sz > end)
607    {
608        LSQ_WARN("truncated ticket buffer");
609        return NULL;
610    }
611
612    ticket_buf = p;
613    p += ticket_sz;
614
615    if (p + sizeof(trapa_sz) > end)
616    {
617        LSQ_WARN("too short to read trapa size");
618        return NULL;
619    }
620
621    READ_NUM(trapa_sz, p);
622    if (p + trapa_sz > end)
623    {
624        LSQ_WARN("truncated trapa buffer");
625        return NULL;
626    }
627    trapa_buf = p;
628    p += trapa_sz;
629    assert(p == end);
630
631    (void) /* TODO */ trapa_buf;
632
633    ssl_session = SSL_SESSION_from_bytes(ticket_buf, ticket_sz, ssl_ctx);
634    if (!ssl_session)
635    {
636        LSQ_WARN("SSL_SESSION could not be parsed out");
637        return NULL;
638    }
639
640    LSQ_INFO("instantiated SSL_SESSION from serialized buffer");
641    return ssl_session;
642}
643
644
645static void
646init_frals (struct enc_sess_iquic *enc_sess)
647{
648    struct frab_list *fral;
649
650    for (fral = enc_sess->esi_frals; fral < enc_sess->esi_frals
651            + sizeof(enc_sess->esi_frals) / sizeof(enc_sess->esi_frals[0]);
652                ++fral)
653        lsquic_frab_list_init(fral, 0x100, NULL, NULL, NULL);
654}
655
656
657static enc_session_t *
658iquic_esfi_create_client (const char *hostname,
659            struct lsquic_engine_public *enpub, struct lsquic_conn *lconn,
660            const lsquic_cid_t *dcid, const struct ver_neg *ver_neg,
661            void *crypto_streams[4], const struct crypto_stream_if *cryst_if,
662            const unsigned char *zero_rtt, size_t zero_rtt_sz,
663            struct lsquic_alarmset *alset)
664{
665    struct enc_sess_iquic *enc_sess;
666
667    enc_sess = calloc(1, sizeof(*enc_sess));
668    if (!enc_sess)
669        return NULL;
670
671    if (hostname)
672    {
673        enc_sess->esi_hostname = strdup(hostname);
674        if (!enc_sess->esi_hostname)
675        {
676            free(enc_sess);
677            return NULL;
678        }
679    }
680    else
681        enc_sess->esi_hostname = NULL;
682
683    enc_sess->esi_enpub = enpub;
684    enc_sess->esi_streams = crypto_streams;
685    enc_sess->esi_cryst_if = cryst_if;
686    enc_sess->esi_conn = lconn;
687    enc_sess->esi_ver_neg = ver_neg;
688
689    enc_sess->esi_dir[0] = evp_aead_seal;
690    enc_sess->esi_dir[1] = evp_aead_open;
691
692    LSQ_DEBUGC("created client, DCID: %"CID_FMT, CID_BITS(dcid));
693    {
694        const char *log;
695        log = getenv("LSQUIC_LOG_SECRETS");
696        if (log)
697        {
698            if (atoi(log))
699                enc_sess->esi_flags |= ESI_LOG_SECRETS;
700            LSQ_DEBUG("will %slog secrets", atoi(log) ? "" : "not ");
701        }
702    }
703
704    init_frals(enc_sess);
705
706    if (0 != setup_handshake_keys(enc_sess, dcid))
707    {
708        free(enc_sess);
709        return NULL;
710    }
711
712    /* Have to wait until the call to init_client() -- this is when the
713     * result of version negotiation is known.
714     */
715    if (zero_rtt && zero_rtt_sz)
716    {
717        enc_sess->esi_zero_rtt_buf = malloc(zero_rtt_sz);
718        if (enc_sess->esi_zero_rtt_buf)
719        {
720            memcpy(enc_sess->esi_zero_rtt_buf, zero_rtt, zero_rtt_sz);
721            enc_sess->esi_zero_rtt_sz = zero_rtt_sz;
722        }
723        else
724            enc_sess->esi_zero_rtt_sz = 0;
725    }
726    else
727    {
728        enc_sess->esi_zero_rtt_buf = NULL;
729        enc_sess->esi_zero_rtt_sz = 0;
730    }
731
732    if (enc_sess->esi_enpub->enp_stream_if->on_zero_rtt_info)
733        enc_sess->esi_flags |= ESI_WANT_TICKET;
734    enc_sess->esi_alset = alset;
735    lsquic_alarmset_init_alarm(enc_sess->esi_alset, AL_SESS_TICKET,
736                                            no_sess_ticket, enc_sess);
737
738    return enc_sess;
739}
740
741
742static void
743iquic_esfi_set_streams (enc_session_t *enc_session_p,
744        void *(crypto_streams)[4], const struct crypto_stream_if *cryst_if)
745{
746    struct enc_sess_iquic *const enc_sess = enc_session_p;
747    enc_sess->esi_streams = crypto_streams;
748    enc_sess->esi_cryst_if = cryst_if;
749}
750
751
752static enc_session_t *
753iquic_esfi_create_server (struct lsquic_engine_public *enpub,
754                    struct lsquic_conn *lconn, const lsquic_cid_t *first_dcid,
755                    void *(crypto_streams)[4],
756                    const struct crypto_stream_if *cryst_if,
757                    const struct lsquic_cid *odcid)
758{
759    struct enc_sess_iquic *enc_sess;
760
761    enc_sess = calloc(1, sizeof(*enc_sess));
762    if (!enc_sess)
763        return NULL;
764
765#ifndef NDEBUG
766    enc_sess->esi_sni_bypass = getenv("LSQUIC_SNI_BYPASS");
767#endif
768
769    enc_sess->esi_flags = ESI_SERVER;
770    enc_sess->esi_streams = crypto_streams;
771    enc_sess->esi_cryst_if = cryst_if;
772    enc_sess->esi_enpub = enpub;
773    enc_sess->esi_conn = lconn;
774
775    enc_sess->esi_dir[0] = evp_aead_open;
776    enc_sess->esi_dir[1] = evp_aead_seal;
777
778    if (odcid)
779    {
780        enc_sess->esi_odcid = *odcid;
781        enc_sess->esi_flags |= ESI_ODCID;
782    }
783
784    init_frals(enc_sess);
785
786    {
787        const char *log;
788        log = getenv("LSQUIC_LOG_SECRETS");
789        if (log)
790        {
791            if (atoi(log))
792                enc_sess->esi_flags |= ESI_LOG_SECRETS;
793            LSQ_DEBUG("will %slog secrets", atoi(log) ? "" : "not ");
794        }
795    }
796
797    if (0 != setup_handshake_keys(enc_sess, first_dcid))
798    {
799        free(enc_sess);
800        return NULL;
801    }
802
803    return enc_sess;
804}
805
806
807static void
808log_crypto_pair (const struct enc_sess_iquic *enc_sess,
809                    const struct crypto_ctx_pair *pair, const char *name)
810{
811    char hexbuf[EVP_MAX_MD_SIZE * 2 + 1];
812    LSQ_DEBUG("client %s key: %s", name,
813        HEXSTR(pair->ykp_ctx[0].yk_key_buf, pair->ykp_ctx[0].yk_key_sz,
814                                                                hexbuf));
815    LSQ_DEBUG("client %s iv: %s", name,
816        HEXSTR(pair->ykp_ctx[0].yk_iv_buf, pair->ykp_ctx[0].yk_iv_sz,
817                                                                hexbuf));
818    LSQ_DEBUG("server %s key: %s", name,
819        HEXSTR(pair->ykp_ctx[1].yk_key_buf, pair->ykp_ctx[1].yk_key_sz,
820                                                                hexbuf));
821    LSQ_DEBUG("server %s iv: %s", name,
822        HEXSTR(pair->ykp_ctx[1].yk_iv_buf, pair->ykp_ctx[1].yk_iv_sz,
823                                                                hexbuf));
824}
825
826
827static void
828log_hp (const struct enc_sess_iquic *enc_sess,
829                    const struct header_prot *hp, const char *name)
830{
831    char hexbuf[EVP_MAX_MD_SIZE * 2 + 1];
832    LSQ_DEBUG("client %s hp: %s", name,
833        HEXSTR(hp->hp_buf[0], hp->hp_sz, hexbuf));
834    LSQ_DEBUG("server %s hp: %s", name,
835        HEXSTR(hp->hp_buf[1], hp->hp_sz, hexbuf));
836}
837
838
839/* [draft-ietf-quic-tls-12] Section 5.3.2 */
840static int
841setup_handshake_keys (struct enc_sess_iquic *enc_sess, const lsquic_cid_t *cid)
842{
843    const EVP_MD *const md = EVP_sha256();
844    const EVP_AEAD *const aead = EVP_aead_aes_128_gcm();
845    struct crypto_ctx_pair *pair;
846    struct header_prot *hp;
847    size_t hsk_secret_sz;
848    unsigned char hsk_secret[EVP_MAX_MD_SIZE];
849    unsigned char secret[2][SHA256_DIGEST_LENGTH];  /* client, server */
850    char hexbuf[EVP_MAX_MD_SIZE * 2 + 1];
851
852    if (!enc_sess->esi_hsk_pairs)
853    {
854        enc_sess->esi_hsk_pairs = calloc(N_HSK_PAIRS,
855                                            sizeof(enc_sess->esi_hsk_pairs[0]));
856        enc_sess->esi_hsk_hps = calloc(N_HSK_PAIRS,
857                                            sizeof(enc_sess->esi_hsk_hps[0]));
858        if (!(enc_sess->esi_hsk_pairs && enc_sess->esi_hsk_hps))
859        {
860            free(enc_sess->esi_hsk_pairs);
861            free(enc_sess->esi_hsk_hps);
862            return -1;
863        }
864    }
865    pair = &enc_sess->esi_hsk_pairs[ENC_LEV_CLEAR];
866    pair->ykp_thresh = IQUIC_INVALID_PACKNO;
867    hp = &enc_sess->esi_hsk_hps[ENC_LEV_CLEAR];
868
869    HKDF_extract(hsk_secret, &hsk_secret_sz, md, cid->idbuf, cid->len,
870                                                        HSK_SALT, HSK_SALT_SZ);
871    if (enc_sess->esi_flags & ESI_LOG_SECRETS)
872    {
873        LSQ_DEBUG("handshake salt: %s", HEXSTR(HSK_SALT, HSK_SALT_SZ, hexbuf));
874        LSQ_DEBUG("handshake secret: %s", HEXSTR(hsk_secret, hsk_secret_sz,
875                                                                    hexbuf));
876    }
877
878    lsquic_qhkdf_expand(md, hsk_secret, hsk_secret_sz, CLIENT_LABEL,
879                CLIENT_LABEL_SZ, secret[0], sizeof(secret[0]));
880    LSQ_DEBUG("client handshake secret: %s",
881        HEXSTR(secret[0], sizeof(secret[0]), hexbuf));
882    if (0 != init_crypto_ctx(&pair->ykp_ctx[0], md, aead, secret[0],
883                sizeof(secret[0]), enc_sess->esi_dir[0]))
884        goto err;
885    lsquic_qhkdf_expand(md, hsk_secret, hsk_secret_sz, SERVER_LABEL,
886                SERVER_LABEL_SZ, secret[1], sizeof(secret[1]));
887    LSQ_DEBUG("server handshake secret: %s",
888        HEXSTR(secret[1], sizeof(secret[1]), hexbuf));
889    if (0 != init_crypto_ctx(&pair->ykp_ctx[1], md, aead, secret[1],
890                sizeof(secret[1]), enc_sess->esi_dir[1]))
891        goto err;
892
893    /* [draft-ietf-quic-tls-12] Section 5.6.1: AEAD_AES_128_GCM implies
894     * 128-bit AES-CTR.
895     */
896    hp->hp_cipher = EVP_aes_128_ecb();
897    hp->hp_gen_mask = gen_hp_mask_aes;
898    hp->hp_enc_level = ENC_LEV_CLEAR;
899    derive_hp_secrets(hp, md, aead, sizeof(secret[0]), secret[0], secret[1]);
900
901    if (enc_sess->esi_flags & ESI_LOG_SECRETS)
902    {
903        log_crypto_pair(enc_sess, pair, "handshake");
904        log_hp(enc_sess, hp, "handshake");
905    }
906
907    return 0;
908
909  err:
910    cleanup_crypto_ctx(&pair->ykp_ctx[0]);
911    cleanup_crypto_ctx(&pair->ykp_ctx[1]);
912    return -1;
913}
914
915
916static void
917free_handshake_keys (struct enc_sess_iquic *enc_sess)
918{
919    struct crypto_ctx_pair *pair;
920
921    if (enc_sess->esi_hsk_pairs)
922    {
923        assert(enc_sess->esi_hsk_hps);
924        for (pair = enc_sess->esi_hsk_pairs; pair <
925                enc_sess->esi_hsk_pairs + N_HSK_PAIRS; ++pair)
926        {
927            cleanup_crypto_ctx(&pair->ykp_ctx[0]);
928            cleanup_crypto_ctx(&pair->ykp_ctx[1]);
929        }
930        free(enc_sess->esi_hsk_pairs);
931        enc_sess->esi_hsk_pairs = NULL;
932        free(enc_sess->esi_hsk_hps);
933        enc_sess->esi_hsk_hps = NULL;
934    }
935    else
936        assert(!enc_sess->esi_hsk_hps);
937}
938
939
940static void
941keylog_callback (const SSL *ssl, const char *line)
942{
943    struct enc_sess_iquic *enc_sess;
944
945    enc_sess = SSL_get_ex_data(ssl, s_idx);
946    if (enc_sess->esi_keylog_handle)
947        enc_sess->esi_enpub->enp_kli->kli_log_line(
948                                        enc_sess->esi_keylog_handle, line);
949}
950
951
952static void
953maybe_setup_key_logging (struct enc_sess_iquic *enc_sess)
954{
955    if (enc_sess->esi_enpub->enp_kli)
956    {
957        enc_sess->esi_keylog_handle = enc_sess->esi_enpub->enp_kli->kli_open(
958                        enc_sess->esi_enpub->enp_kli_ctx, enc_sess->esi_conn);
959        LSQ_DEBUG("SSL keys %s be logged",
960                            enc_sess->esi_keylog_handle ? "will" : "will not");
961    }
962}
963
964
965static enum ssl_verify_result_t
966verify_server_cert_callback (SSL *ssl, uint8_t *out_alert)
967{
968    struct enc_sess_iquic *enc_sess;
969    struct stack_st_X509 *chain;
970    int s;
971
972    enc_sess = SSL_get_ex_data(ssl, s_idx);
973    chain = SSL_get_peer_cert_chain(ssl);
974    if (!chain)
975    {
976        LSQ_ERROR("cannot get peer chain");
977        return ssl_verify_invalid;
978    }
979
980    s = enc_sess->esi_enpub->enp_verify_cert(
981                                enc_sess->esi_enpub->enp_verify_ctx, chain);
982    return s == 0 ? ssl_verify_ok : ssl_verify_invalid;
983}
984
985
986static int
987iquic_lookup_cert (SSL *ssl, void *arg)
988{
989    struct enc_sess_iquic *const enc_sess = arg;
990    const struct network_path *path;
991    const char *server_name;
992    SSL_CTX *ssl_ctx;
993
994    server_name = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
995#ifndef NDEBUG
996    if (!server_name)
997        server_name = enc_sess->esi_sni_bypass;
998#endif
999    if (!server_name)
1000    {
1001        LSQ_DEBUG("cert lookup: server name is not set, error");
1002        return 0;
1003    }
1004
1005    path = enc_sess->esi_conn->cn_if->ci_get_path(enc_sess->esi_conn, NULL);
1006    ssl_ctx = enc_sess->esi_enpub->enp_lookup_cert(
1007                enc_sess->esi_enpub->enp_cert_lu_ctx, NP_LOCAL_SA(path),
1008                server_name);
1009
1010
1011    if (ssl_ctx)
1012    {
1013        if (SSL_set_SSL_CTX(enc_sess->esi_ssl, ssl_ctx))
1014        {
1015            LSQ_DEBUG("looked up cert for %s", server_name);
1016            if (enc_sess->esi_enpub->enp_kli)
1017                SSL_CTX_set_keylog_callback(ssl_ctx, keylog_callback);
1018            SSL_set_verify(enc_sess->esi_ssl,
1019                                    SSL_CTX_get_verify_mode(ssl_ctx), NULL);
1020            SSL_set_verify_depth(enc_sess->esi_ssl,
1021                                    SSL_CTX_get_verify_depth(ssl_ctx));
1022            SSL_clear_options(enc_sess->esi_ssl,
1023                                    SSL_get_options(enc_sess->esi_ssl));
1024            SSL_set_options(enc_sess->esi_ssl,
1025                                    SSL_CTX_get_options(ssl_ctx));
1026            return 1;
1027        }
1028        else
1029        {
1030            LSQ_WARN("cannot set SSL_CTX");
1031            return 0;
1032        }
1033    }
1034    else
1035    {
1036        LSQ_DEBUG("could not look up cert for %s", server_name);
1037        return 0;
1038    }
1039}
1040
1041
1042static void
1043iquic_esfi_set_conn (enc_session_t *enc_session_p, struct lsquic_conn *lconn)
1044{
1045    struct enc_sess_iquic *const enc_sess = enc_session_p;
1046    enc_sess->esi_conn = lconn;
1047    LSQ_DEBUG("updated conn reference");
1048}
1049
1050
1051static int
1052iquic_esfi_init_server (enc_session_t *enc_session_p)
1053{
1054    struct enc_sess_iquic *const enc_sess = enc_session_p;
1055    const struct alpn_map *am;
1056    int transpa_len;
1057    SSL_CTX *ssl_ctx = NULL;
1058    union {
1059        char errbuf[ERR_ERROR_STRING_BUF_LEN];
1060        unsigned char trans_params[sizeof(struct transport_params)];
1061    } u;
1062
1063    for (am = s_alpns; am < s_alpns + sizeof(s_alpns)
1064                                                / sizeof(s_alpns[0]); ++am)
1065        if (am->version == enc_sess->esi_conn->cn_version)
1066            goto ok;
1067
1068    LSQ_ERROR("version %s has no matching ALPN",
1069                            lsquic_ver2str[enc_sess->esi_conn->cn_version]);
1070    return -1;
1071
1072  ok:
1073    enc_sess->esi_alpn = am->alpn;
1074
1075    ssl_ctx = enc_sess->esi_enpub->enp_get_ssl_ctx(
1076                    lsquic_conn_get_peer_ctx(enc_sess->esi_conn, NULL));
1077    if (!ssl_ctx)
1078    {
1079        LSQ_ERROR("fetching SSL context associated with peer context failed");
1080        return -1;
1081    }
1082
1083    enc_sess->esi_ssl = SSL_new(ssl_ctx);
1084    if (!enc_sess->esi_ssl)
1085    {
1086        LSQ_ERROR("cannot create SSL object: %s",
1087            ERR_error_string(ERR_get_error(), u.errbuf));
1088        return -1;
1089    }
1090    if (!(SSL_set_quic_method(enc_sess->esi_ssl, &cry_quic_method)))
1091    {
1092        LSQ_INFO("could not set stream method");
1093        return -1;
1094    }
1095    maybe_setup_key_logging(enc_sess);
1096
1097    transpa_len = gen_trans_params(enc_sess, u.trans_params,
1098                                                    sizeof(u.trans_params));
1099    if (transpa_len < 0)
1100        return -1;
1101
1102    if (1 != SSL_set_quic_transport_params(enc_sess->esi_ssl, u.trans_params,
1103                                                            transpa_len))
1104    {
1105        LSQ_ERROR("cannot set QUIC transport params: %s",
1106            ERR_error_string(ERR_get_error(), u.errbuf));
1107        return -1;
1108    }
1109
1110    SSL_set_cert_cb(enc_sess->esi_ssl, iquic_lookup_cert, enc_sess);
1111    SSL_set_ex_data(enc_sess->esi_ssl, s_idx, enc_sess);
1112    SSL_set_accept_state(enc_sess->esi_ssl);
1113    LSQ_DEBUG("initialized server enc session");
1114    enc_sess->esi_flags |= ESI_INITIALIZED;
1115    return 0;
1116}
1117
1118
1119#if __BYTE_ORDER == __LITTLE_ENDIAN
1120#define WRITE_NUM(var_, val_, ptr_) do {                        \
1121    var_ = (val_);                                              \
1122    var_ = bswap_32(var_);                                      \
1123    memcpy((ptr_), &var_, sizeof(var_));                        \
1124    ptr_ += sizeof(var_);                                       \
1125} while (0)
1126#else
1127#define WRITE_NUM(var_, val_, ptr_) do {                        \
1128    var_ = (val_);                                              \
1129    memcpy((ptr_), &var_, sizeof(var_));                        \
1130    ptr_ += sizeof(var_);                                       \
1131} while (0)
1132#endif
1133
1134static int
1135iquic_new_session_cb (SSL *ssl, SSL_SESSION *session)
1136{
1137    struct enc_sess_iquic *enc_sess;
1138    uint32_t max_early_data_size, num;
1139    unsigned char *p, *buf;
1140    uint8_t *ticket_buf;
1141    size_t ticket_sz;
1142    lsquic_ver_tag_t tag;
1143    const uint8_t *trapa_buf;
1144    size_t trapa_sz, buf_sz;
1145
1146    enc_sess = SSL_get_ex_data(ssl, s_idx);
1147    assert(enc_sess->esi_enpub->enp_stream_if->on_zero_rtt_info);
1148
1149    max_early_data_size = SSL_SESSION_get_max_early_data_size(session);
1150    if (0xFFFFFFFFu != max_early_data_size)
1151        LSQ_WARN("max_early_data_size=0x%X, protocol violation",
1152                                                        max_early_data_size);
1153
1154    SSL_get_peer_quic_transport_params(enc_sess->esi_ssl, &trapa_buf,
1155                                                                &trapa_sz);
1156    if (!(trapa_buf + trapa_sz))
1157    {
1158        LSQ_WARN("no transport parameters: cannot generate zero-rtt info");
1159        return 0;
1160    }
1161    if (trapa_sz > UINT32_MAX)
1162    {
1163        LSQ_WARN("trapa size too large: %zu", trapa_sz);
1164        return 0;
1165    }
1166
1167    if (!SSL_SESSION_to_bytes(session, &ticket_buf, &ticket_sz))
1168    {
1169        LSQ_INFO("could not serialize new session");
1170        return 0;
1171    }
1172    if (ticket_sz > UINT32_MAX)
1173    {
1174        LSQ_WARN("ticket size too large: %zu", ticket_sz);
1175        OPENSSL_free(ticket_buf);
1176        return 0;
1177    }
1178
1179    buf_sz = sizeof(tag) + sizeof(uint32_t) + sizeof(uint32_t)
1180                                + ticket_sz + sizeof(uint32_t) + trapa_sz;
1181    buf = malloc(buf_sz);
1182    if (!buf)
1183    {
1184        OPENSSL_free(ticket_buf);
1185        LSQ_WARN("%s: malloc failed", __func__);
1186        return 0;
1187    }
1188
1189    p = buf;
1190    tag = lsquic_ver2tag(enc_sess->esi_conn->cn_version);
1191    memcpy(p, &tag, sizeof(tag));
1192    p += sizeof(tag);
1193
1194    WRITE_NUM(num, ZERO_RTT_VERSION, p);
1195    WRITE_NUM(num, ticket_sz, p);
1196    memcpy(p, ticket_buf, ticket_sz);
1197    p += ticket_sz;
1198    WRITE_NUM(num, trapa_sz, p);
1199    memcpy(p, trapa_buf, trapa_sz);
1200    p += trapa_sz;
1201
1202    assert(buf + buf_sz == p);
1203    OPENSSL_free(ticket_buf);
1204
1205    LSQ_DEBUG("generated %zu bytes of zero-rtt buffer", buf_sz);
1206
1207    enc_sess->esi_enpub->enp_stream_if->on_zero_rtt_info(enc_sess->esi_conn,
1208                                                                buf, buf_sz);
1209    free(buf);
1210    enc_sess->esi_flags &= ~ESI_WANT_TICKET;
1211    lsquic_alarmset_unset(enc_sess->esi_alset, AL_SESS_TICKET);
1212    return 0;
1213}
1214
1215
1216static int
1217init_client (struct enc_sess_iquic *const enc_sess)
1218{
1219    SSL_CTX *ssl_ctx;
1220    SSL_SESSION *ssl_session;
1221    const struct alpn_map *am;
1222    int transpa_len;
1223    char errbuf[ERR_ERROR_STRING_BUF_LEN];
1224#define hexbuf errbuf   /* This is a dual-purpose buffer */
1225    unsigned char trans_params[0x80];
1226
1227    for (am = s_alpns; am < s_alpns + sizeof(s_alpns)
1228                                                / sizeof(s_alpns[0]); ++am)
1229        if (am->version == enc_sess->esi_ver_neg->vn_ver)
1230            goto ok;
1231
1232    LSQ_ERROR("version %s has no matching ALPN",
1233                            lsquic_ver2str[enc_sess->esi_ver_neg->vn_ver]);
1234    return -1;
1235
1236  ok:
1237    enc_sess->esi_alpn = am->alpn;
1238    LSQ_DEBUG("Create new SSL_CTX");
1239    ssl_ctx = SSL_CTX_new(TLS_method());
1240    if (!ssl_ctx)
1241    {
1242        LSQ_ERROR("cannot create SSL context: %s",
1243            ERR_error_string(ERR_get_error(), errbuf));
1244        goto err;
1245    }
1246    SSL_CTX_set_min_proto_version(ssl_ctx, TLS1_3_VERSION);
1247    SSL_CTX_set_max_proto_version(ssl_ctx, TLS1_3_VERSION);
1248    SSL_CTX_set_default_verify_paths(ssl_ctx);
1249    SSL_CTX_set_session_cache_mode(ssl_ctx, SSL_SESS_CACHE_CLIENT);
1250    if (enc_sess->esi_enpub->enp_stream_if->on_zero_rtt_info)
1251        SSL_CTX_sess_set_new_cb(ssl_ctx, iquic_new_session_cb);
1252    if (enc_sess->esi_enpub->enp_kli)
1253        SSL_CTX_set_keylog_callback(ssl_ctx, keylog_callback);
1254    if (enc_sess->esi_enpub->enp_verify_cert)
1255        SSL_CTX_set_custom_verify(ssl_ctx, SSL_VERIFY_PEER,
1256            verify_server_cert_callback);
1257    SSL_CTX_set_early_data_enabled(ssl_ctx, 1);
1258
1259    transpa_len = gen_trans_params(enc_sess, trans_params,
1260                                                    sizeof(trans_params));
1261    if (transpa_len < 0)
1262    {
1263        goto err;
1264    }
1265
1266    enc_sess->esi_ssl = SSL_new(ssl_ctx);
1267    if (!enc_sess->esi_ssl)
1268    {
1269        LSQ_ERROR("cannot create SSL object: %s",
1270            ERR_error_string(ERR_get_error(), errbuf));
1271        goto err;
1272    }
1273    if (!(SSL_set_quic_method(enc_sess->esi_ssl, &cry_quic_method)))
1274    {
1275        LSQ_INFO("could not set stream method");
1276        goto err;
1277    }
1278    maybe_setup_key_logging(enc_sess);
1279    if (1 != SSL_set_quic_transport_params(enc_sess->esi_ssl, trans_params,
1280                                                            transpa_len))
1281    {
1282        LSQ_ERROR("cannot set QUIC transport params: %s",
1283            ERR_error_string(ERR_get_error(), errbuf));
1284        goto err;
1285    }
1286    if (0 != SSL_set_alpn_protos(enc_sess->esi_ssl, am->alpn, am->alpn[0] + 1))
1287    {
1288        LSQ_ERROR("cannot set ALPN: %s",
1289            ERR_error_string(ERR_get_error(), errbuf));
1290        goto err;
1291    }
1292    if (1 != SSL_set_tlsext_host_name(enc_sess->esi_ssl,
1293                                                    enc_sess->esi_hostname))
1294    {
1295        LSQ_ERROR("cannot set hostname: %s",
1296            ERR_error_string(ERR_get_error(), errbuf));
1297        goto err;
1298    }
1299    free(enc_sess->esi_hostname);
1300    enc_sess->esi_hostname = NULL;
1301    if (enc_sess->esi_zero_rtt_buf)
1302    {
1303        ssl_session = maybe_create_SSL_SESSION(enc_sess, ssl_ctx);
1304        if (ssl_session)
1305        {
1306            if (SSL_set_session(enc_sess->esi_ssl, ssl_session))
1307                enc_sess->esi_flags |= ESI_USE_SSL_TICKET;
1308            else
1309                LSQ_WARN("cannot set session");
1310        }
1311    }
1312
1313    SSL_set_ex_data(enc_sess->esi_ssl, s_idx, enc_sess);
1314    SSL_set_connect_state(enc_sess->esi_ssl);
1315    SSL_CTX_free(ssl_ctx);
1316    LSQ_DEBUG("initialized client enc session");
1317    enc_sess->esi_flags |= ESI_INITIALIZED;
1318    return 0;
1319
1320  err:
1321    if (ssl_ctx)
1322        SSL_CTX_free(ssl_ctx);
1323    return -1;
1324#undef hexbuf
1325}
1326
1327
1328struct crypto_params
1329{
1330    const EVP_AEAD      *aead;
1331    const EVP_MD        *md;
1332    const EVP_CIPHER    *hp;
1333    gen_hp_mask_f        gen_hp_mask;
1334};
1335
1336
1337static int
1338get_crypto_params (const struct enc_sess_iquic *enc_sess,
1339                                                struct crypto_params *params)
1340{
1341    const SSL_CIPHER *cipher;
1342    unsigned key_sz, iv_sz;
1343    uint32_t id;
1344
1345    cipher = SSL_get_current_cipher(enc_sess->esi_ssl);
1346    id = SSL_CIPHER_get_id(cipher);
1347
1348    LSQ_DEBUG("Negotiated cipher ID is 0x%"PRIX32, id);
1349
1350    /* RFC 8446, Appendix B.4 */
1351    switch (id)
1352    {
1353    case 0x03000000 | 0x1301:       /* TLS_AES_128_GCM_SHA256 */
1354        params->md          = EVP_sha256();
1355        params->aead        = EVP_aead_aes_128_gcm();
1356        params->hp          = EVP_aes_128_ecb();
1357        params->gen_hp_mask = gen_hp_mask_aes;
1358        break;
1359    case 0x03000000 | 0x1302:       /* TLS_AES_256_GCM_SHA384 */
1360        params->md          = EVP_sha384();
1361        params->aead        = EVP_aead_aes_256_gcm();
1362        params->hp          = EVP_aes_256_ecb();
1363        params->gen_hp_mask = gen_hp_mask_aes;
1364        break;
1365    case 0x03000000 | 0x1303:       /* TLS_CHACHA20_POLY1305_SHA256 */
1366        params->md          = EVP_sha256();
1367        params->aead        = EVP_aead_chacha20_poly1305();
1368        params->hp          = NULL;
1369        params->gen_hp_mask = gen_hp_mask_chacha20;
1370        break;
1371    default:
1372        /* TLS_AES_128_CCM_SHA256 and TLS_AES_128_CCM_8_SHA256 are not
1373         * supported by BoringSSL (grep for \b0x130[45]\b).
1374         */
1375        LSQ_DEBUG("unsupported cipher 0x%"PRIX32, id);
1376        return -1;
1377    }
1378
1379    key_sz = EVP_AEAD_key_length(params->aead);
1380    if (key_sz > EVP_MAX_KEY_LENGTH)
1381    {
1382        LSQ_DEBUG("key size %u is too large", key_sz);
1383        return -1;
1384    }
1385
1386    iv_sz = EVP_AEAD_nonce_length(params->aead);
1387    if (iv_sz < 8)
1388        iv_sz = 8;  /* [draft-ietf-quic-tls-11], Section 5.3 */
1389    if (iv_sz > EVP_MAX_IV_LENGTH)
1390    {
1391        LSQ_DEBUG("iv size %u is too large", iv_sz);
1392        return -1;
1393    }
1394
1395    if (key_sz > EVP_MAX_KEY_LENGTH)
1396    {
1397        LSQ_DEBUG("PN size %u is too large", key_sz);
1398        return -1;
1399    }
1400
1401    return 0;
1402}
1403
1404
1405static int
1406get_peer_transport_params (struct enc_sess_iquic *enc_sess)
1407{
1408    struct transport_params *const trans_params = &enc_sess->esi_peer_tp;
1409    const uint8_t *params_buf;
1410    size_t bufsz;
1411    char params_str[0x200];
1412
1413    SSL_get_peer_quic_transport_params(enc_sess->esi_ssl, &params_buf, &bufsz);
1414    if (!params_buf)
1415    {
1416        LSQ_DEBUG("no peer transport parameters");
1417        return -1;
1418    }
1419
1420    LSQ_DEBUG("have peer transport parameters (%zu bytes)", bufsz);
1421    if (0 > lsquic_tp_decode(params_buf, bufsz,
1422                            !(enc_sess->esi_flags & ESI_SERVER),
1423                                                trans_params))
1424    {
1425        lsquic_hexdump(params_buf, bufsz, params_str, sizeof(params_str));
1426        LSQ_DEBUG("could not parse peer transport parameters (%zd bytes):\n%s",
1427            bufsz, params_str);
1428        return -1;
1429    }
1430
1431    if ((enc_sess->esi_flags & (ESI_ODCID|ESI_SERVER)) == ESI_ODCID)
1432    {
1433        if (!(trans_params->tp_flags & TRAPA_ORIGINAL_CID))
1434        {
1435            LSQ_DEBUG("server did not produce original DCID (ODCID)");
1436            return -1;
1437        }
1438        if (LSQUIC_CIDS_EQ(&enc_sess->esi_odcid,
1439                                        &trans_params->tp_original_cid))
1440            LSQ_DEBUG("ODCID values match");
1441        else
1442        {
1443            if (LSQ_LOG_ENABLED(LSQ_LOG_DEBUG))
1444            {
1445                char cidbuf[2][MAX_CID_LEN * 2 + 1];
1446                lsquic_cid2str(&enc_sess->esi_odcid, cidbuf[0]);
1447                lsquic_cid2str(&trans_params->tp_original_cid, cidbuf[1]);
1448                LSQ_DEBUG("server provided ODCID %s that does not match "
1449                    "our ODCID %s", cidbuf[1], cidbuf[0]);
1450            }
1451            return -1;
1452        }
1453    }
1454
1455    return 0;
1456}
1457
1458
1459static int
1460maybe_get_peer_transport_params (struct enc_sess_iquic *enc_sess)
1461{
1462    int s;
1463
1464    if (enc_sess->esi_flags & ESI_HAVE_PEER_TP)
1465        return 0;
1466
1467    s = get_peer_transport_params(enc_sess);
1468    if (s == 0)
1469        enc_sess->esi_flags |= ESI_HAVE_PEER_TP;
1470
1471    return s;
1472}
1473
1474
1475static enum iquic_handshake_status
1476iquic_esfi_handshake (struct enc_sess_iquic *enc_sess)
1477{
1478    int s, err;
1479    enum lsquic_hsk_status hsk_status;
1480    char errbuf[ERR_ERROR_STRING_BUF_LEN];
1481
1482    s = SSL_do_handshake(enc_sess->esi_ssl);
1483    if (s <= 0)
1484    {
1485        err = SSL_get_error(enc_sess->esi_ssl, s);
1486        switch (err)
1487        {
1488        case SSL_ERROR_WANT_READ:
1489            LSQ_DEBUG("retry read");
1490            return IHS_WANT_READ;
1491        case SSL_ERROR_WANT_WRITE:
1492            LSQ_DEBUG("retry write");
1493            return IHS_WANT_WRITE;
1494        case SSL_EARLY_DATA_REJECTED:   /* XXX should this be included here? */
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