lsquic_handshake.c revision 03d03a42
1/* Copyright (c) 2017 - 2019 LiteSpeed Technologies Inc.  See LICENSE. */
2
3#include <assert.h>
4#include <errno.h>
5#include <time.h>
6#include <string.h>
7#include <sys/queue.h>
8#ifndef WIN32
9#include <sys/socket.h>
10#endif
11
12#include <openssl/ssl.h>
13#include <openssl/crypto.h>
14#include <openssl/stack.h>
15#include <openssl/x509.h>
16#include <openssl/rand.h>
17#include <openssl/nid.h>
18#include <zlib.h>
19
20#include "lsquic.h"
21#include "lsquic_types.h"
22#include "lsquic_crypto.h"
23#include "lsquic_str.h"
24#include "lsquic_handshake.h"
25#include "lsquic_parse.h"
26#include "lsquic_crt_compress.h"
27#include "lsquic_util.h"
28#include "lsquic_version.h"
29#include "lsquic_mm.h"
30#include "lsquic_engine_public.h"
31#include "lsquic_hash.h"
32#include "lsquic_buf.h"
33#include "lsquic_qtags.h"
34
35#include "fiu-local.h"
36
37#include "lsquic_ev_log.h"
38
39#define MIN_CHLO_SIZE 1024
40
41#define LSQUIC_LOGGER_MODULE LSQLM_HANDSHAKE
42#include "lsquic_logger.h"
43
44enum handshake_state
45{
46    HSK_CHLO_REJ = 0,
47    HSK_SHLO,
48    HSK_COMPLETED,
49    N_HSK_STATES
50};
51
52#if LSQUIC_KEEP_ENC_SESS_HISTORY
53typedef unsigned char eshist_idx_t;
54
55enum enc_sess_history_event
56{
57    ESHE_EMPTY              =  '\0',
58    ESHE_SET_SNI            =  'I',
59    ESHE_SET_SNO            =  'O',
60    ESHE_SET_STK            =  'K',
61    ESHE_SET_SCID           =  'D',
62    ESHE_SET_PROF           =  'P',
63    ESHE_SET_SRST           =  'S',
64};
65#endif
66
67
68typedef struct hs_ctx_st
69{
70    enum {
71        HSET_TCID     =   (1 << 0),     /* tcid is set */
72        HSET_SMHL     =   (1 << 1),     /* smhl is set */
73        HSET_SCID     =   (1 << 2),
74        HSET_IRTT     =   (1 << 3),
75        HSET_SRST     =   (1 << 4),
76    }           set;
77    enum {
78        HOPT_NSTP     =   (1 << 0),     /* NSTP option present in COPT */
79        HOPT_SREJ     =   (1 << 1),     /* SREJ option present in COPT */
80    }           opts;
81    uint32_t    pdmd;
82    uint32_t    aead;
83    uint32_t    kexs;
84
85    uint32_t    mids;
86    uint32_t    scls;
87    uint32_t    cfcw;
88    uint32_t    sfcw;
89    uint32_t    icsl;
90
91    uint32_t    irtt;
92    uint64_t    rcid;
93    uint32_t    tcid;
94    uint32_t    smhl;
95    uint64_t    sttl;
96    unsigned char scid[SCID_LENGTH];
97    //unsigned char chlo_hash[32]; //SHA256 HASH of CHLO
98    unsigned char nonc[DNONC_LENGTH]; /* 4 tm, 8 orbit ---> REJ, 20 rand */
99    unsigned char  pubs[32];
100    unsigned char srst[SRST_LENGTH];
101
102    uint32_t    rrej;
103    struct lsquic_str ccs;
104    struct lsquic_str sni;   /* 0 rtt */
105    struct lsquic_str ccrt;
106    struct lsquic_str stk;
107    struct lsquic_str sno;
108    struct lsquic_str prof;
109
110    struct lsquic_str csct;
111    struct lsquic_str crt; /* compressed certs buffer */
112    struct lsquic_str scfg_pubs; /* Need to copy PUBS, as KEXS comes after it */
113} hs_ctx_t;
114
115
116struct lsquic_enc_session
117{
118    enum handshake_state hsk_state;
119    enum {
120        ES_RECV_REJ =   1 << 2,
121    }                    es_flags;
122
123    uint8_t have_key; /* 0, no 1, I, 2, D, 3, F */
124    uint8_t peer_have_final_key;
125    uint8_t server_start_use_final_key;
126
127    lsquic_cid_t cid;
128    unsigned char priv_key[32];
129    EVP_AEAD_CTX *enc_ctx_i;
130    EVP_AEAD_CTX *dec_ctx_i;
131
132    /* Have to save the initial key for diversification need */
133    unsigned char enc_key_i[aes128_key_len];
134    unsigned char dec_key_i[aes128_key_len];
135    unsigned char enc_key_nonce_i[aes128_iv_len];
136    unsigned char dec_key_nonce_i[aes128_iv_len];
137
138    EVP_AEAD_CTX *enc_ctx_f;
139    EVP_AEAD_CTX *dec_ctx_f;
140    unsigned char enc_key_nonce_f[aes128_iv_len];
141    unsigned char dec_key_nonce_f[aes128_iv_len];
142
143    hs_ctx_t hs_ctx;
144    lsquic_session_cache_info_t *info;
145    c_cert_item_t *cert_item;
146    SSL_CTX *  ssl_ctx;
147    const struct lsquic_engine_public *enpub;
148    struct lsquic_str * cert_ptr; /* pointer to the leaf cert of the server, not real copy */
149    struct lsquic_str   chlo; /* real copy of CHLO message */
150    struct lsquic_str   sstk;
151    struct lsquic_str   ssno;
152
153#if LSQUIC_KEEP_ENC_SESS_HISTORY
154    eshist_idx_t        es_hist_idx;
155    unsigned char       es_hist_buf[1 << ESHIST_BITS];
156#endif
157};
158
159
160
161/* client */
162static c_cert_item_t *make_c_cert_item(struct lsquic_str **certs, int count);
163static void free_c_cert_item(c_cert_item_t *item);
164
165static int get_tag_val_u32 (unsigned char *v, int len, uint32_t *val);
166static int init_hs_hash_tables(int flags);
167static uint32_t get_tag_value_i32(unsigned char *, int);
168static uint64_t get_tag_value_i64(unsigned char *, int);
169
170static int determine_keys(lsquic_enc_session_t *enc_session);
171
172
173#if LSQUIC_KEEP_ENC_SESS_HISTORY
174static void
175eshist_append (lsquic_enc_session_t *enc_session,
176                                        enum enc_sess_history_event eh_event)
177{
178    enc_session->es_hist_buf[
179                    ESHIST_MASK & enc_session->es_hist_idx++ ] = eh_event;
180}
181
182
183#   define ESHIST_APPEND(sess, event) eshist_append(sess, event)
184#else
185#   define ESHIST_APPEND(sess, event) do { } while (0)
186#endif
187
188static int
189lsquic_handshake_init(int flags)
190{
191    crypto_init();
192    return init_hs_hash_tables(flags);
193}
194
195
196static void
197lsquic_handshake_cleanup (void)
198{
199    lsquic_crt_cleanup();
200}
201
202
203/* return -1 for fail, 0 OK*/
204static int init_hs_hash_tables(int flags)
205{
206
207    return 0;
208}
209
210
211/* client */
212static c_cert_item_t *
213make_c_cert_item (lsquic_str_t **certs, int count)
214{
215    int i;
216    uint64_t hash;
217    c_cert_item_t *item = (c_cert_item_t *)malloc(sizeof(c_cert_item_t));
218    item->crts = (lsquic_str_t *)malloc(count * sizeof(lsquic_str_t));
219    item->hashs = lsquic_str_new(NULL, 0);
220    item->count = count;
221    for (i = 0; i < count; ++i)
222    {
223        lsquic_str_copy(&item->crts[i], certs[i]);
224        hash = fnv1a_64((const uint8_t *)lsquic_str_cstr(certs[i]),
225                        lsquic_str_len(certs[i]));
226        lsquic_str_append(item->hashs, (char *)&hash, 8);
227    }
228    return item;
229}
230
231
232/* client */
233static void
234free_c_cert_item (c_cert_item_t *item)
235{
236    int i;
237    if (item)
238    {
239        lsquic_str_delete(item->hashs);
240        for(i=0; i<item->count; ++i)
241            lsquic_str_d(&item->crts[i]);
242        free(item->crts);
243        free(item);
244    }
245}
246
247
248enum rtt_deserialize_return_type
249{
250    RTT_DESERIALIZE_OK              = 0,
251    RTT_DESERIALIZE_BAD_QUIC_VER    = 1,
252    RTT_DESERIALIZE_BAD_SERIAL_VER  = 2,
253    RTT_DESERIALIZE_BAD_CERT_SIZE   = 3,
254};
255
256#define RTT_SERIALIZER_VERSION  (1 << 0)
257
258static void
259lsquic_enc_session_serialize_zero_rtt(struct lsquic_zero_rtt_storage *storage,
260                                        enum lsquic_version version,
261                                        const lsquic_session_cache_info_t *info,
262                                                const c_cert_item_t *cert_item)
263{
264    uint32_t i;
265    uint32_t *cert_len;
266    uint8_t *cert_data;
267    /*
268     * assign versions
269     */
270    storage->quic_version_tag = lsquic_ver2tag(version);
271    storage->serializer_version = RTT_SERIALIZER_VERSION;
272    /*
273     * server config
274     */
275    storage->ver = info->ver;
276    storage->aead = info->aead;
277    storage->kexs = info->kexs;
278    storage->pdmd = info->pdmd;
279    storage->orbt = info->orbt;
280    storage->expy = info->expy;
281    storage->sstk_len = lsquic_str_len(&info->sstk);
282    storage->scfg_len = lsquic_str_len(&info->scfg);
283    storage->scfg_flag = info->scfg_flag;
284    memcpy(storage->sstk, lsquic_str_buf(&info->sstk), storage->sstk_len);
285    memcpy(storage->scfg, lsquic_str_buf(&info->scfg), storage->scfg_len);
286    memcpy(storage->sscid, &info->sscid, SCID_LENGTH);
287    memcpy(storage->spubs, &info->spubs, MAX_SPUBS_LENGTH);
288    /*
289     * certificate chain
290     */
291    storage->cert_count = (uint32_t)cert_item->count;
292    cert_len = (uint32_t *)(storage + 1);
293    cert_data = (uint8_t *)(cert_len + 1);
294    for (i = 0; i < storage->cert_count; i++)
295    {
296        *cert_len = lsquic_str_len(&cert_item->crts[i]);
297        memcpy(cert_data, lsquic_str_buf(&cert_item->crts[i]), *cert_len);
298        cert_len = (uint32_t *)(cert_data + *cert_len);
299        cert_data = (uint8_t *)(cert_len + 1);
300    }
301}
302
303
304#define CHECK_SPACE(need, start, end) \
305    do { if ((intptr_t) (need) > ((intptr_t) (end) - (intptr_t) (start))) \
306        { return RTT_DESERIALIZE_BAD_CERT_SIZE; } \
307    } while (0) \
308
309static enum rtt_deserialize_return_type
310lsquic_enc_session_deserialize_zero_rtt(
311                                const struct lsquic_zero_rtt_storage *storage,
312                                                        size_t storage_size,
313                                const struct lsquic_engine_settings *settings,
314                                            lsquic_session_cache_info_t *info,
315                                                    c_cert_item_t *cert_item)
316{
317    enum lsquic_version ver;
318    uint32_t i, len;
319    uint64_t hash;
320    uint32_t *cert_len;
321    uint8_t *cert_data;
322    void *storage_end = (uint8_t *)storage + storage_size;
323    /*
324     * check versions
325     */
326    ver = lsquic_tag2ver(storage->quic_version_tag);
327    if ((int)ver == -1 || !((1 << ver) & settings->es_versions))
328        return RTT_DESERIALIZE_BAD_QUIC_VER;
329    if (storage->serializer_version != RTT_SERIALIZER_VERSION)
330        return RTT_DESERIALIZE_BAD_SERIAL_VER;
331    /*
332     * server config
333     */
334    info->ver = storage->ver;
335    info->aead = storage->aead;
336    info->kexs = storage->kexs;
337    info->pdmd = storage->pdmd;
338    info->orbt = storage->orbt;
339    info->expy = storage->expy;
340    info->scfg_flag = storage->scfg_flag;
341    lsquic_str_setto(&info->sstk, storage->sstk, storage->sstk_len);
342    lsquic_str_setto(&info->scfg, storage->scfg, storage->scfg_len);
343    memcpy(&info->sscid, storage->sscid, SCID_LENGTH);
344    memcpy(&info->spubs, storage->spubs, MAX_SPUBS_LENGTH);
345    /*
346     * certificate chain
347     */
348    cert_item->count = storage->cert_count;
349    cert_item->crts = malloc(cert_item->count * sizeof(lsquic_str_t));
350    cert_item->hashs = lsquic_str_new(NULL, 0);
351    cert_len = (uint32_t *)(storage + 1);
352    for (i = 0; i < storage->cert_count; i++)
353    {
354        CHECK_SPACE(sizeof(uint32_t), cert_len, storage_end);
355        cert_data = (uint8_t *)(cert_len + 1);
356        memcpy(&len, cert_len, sizeof(len));
357        CHECK_SPACE(len, cert_data, storage_end);
358        lsquic_str_prealloc(&cert_item->crts[i], len);
359        lsquic_str_setlen(&cert_item->crts[i], len);
360        memcpy(lsquic_str_buf(&cert_item->crts[i]), cert_data, len);
361        hash = fnv1a_64((const uint8_t *)cert_data, len);
362        lsquic_str_append(cert_item->hashs, (char *)&hash, 8);
363        cert_len = (uint32_t *)(cert_data + len);
364    }
365    return RTT_DESERIALIZE_OK;
366}
367
368
369static lsquic_enc_session_t *
370lsquic_enc_session_create_client (const char *domain, lsquic_cid_t cid,
371                                    const struct lsquic_engine_public *enpub,
372                                    const unsigned char *zero_rtt, size_t zero_rtt_len)
373{
374    lsquic_session_cache_info_t *info;
375    lsquic_enc_session_t *enc_session;
376    c_cert_item_t *item;
377    const struct lsquic_zero_rtt_storage *zero_rtt_storage;
378
379    if (!domain)
380    {
381        errno = EINVAL;
382        return NULL;
383    }
384
385    enc_session = calloc(1, sizeof(*enc_session));
386    if (!enc_session)
387        return NULL;
388
389    /* have to allocate every time */
390    info = calloc(1, sizeof(*info));
391    if (!info)
392    {
393        free(enc_session);
394        return NULL;
395    }
396
397    if (zero_rtt && zero_rtt_len > sizeof(struct lsquic_zero_rtt_storage))
398    {
399        item = calloc(1, sizeof(*item));
400        if (!item)
401        {
402            free(enc_session);
403            free(info);
404            return NULL;
405        }
406        zero_rtt_storage = (const struct lsquic_zero_rtt_storage *)zero_rtt;
407        switch (lsquic_enc_session_deserialize_zero_rtt(zero_rtt_storage,
408                                                        zero_rtt_len,
409                                                        &enpub->enp_settings,
410                                                        info, item))
411        {
412            case RTT_DESERIALIZE_BAD_QUIC_VER:
413                LSQ_ERROR("provided zero_rtt has unsupported QUIC version");
414                free(item);
415                break;
416            case RTT_DESERIALIZE_BAD_SERIAL_VER:
417                LSQ_ERROR("provided zero_rtt has bad serializer version");
418                free(item);
419                break;
420            case RTT_DESERIALIZE_BAD_CERT_SIZE:
421                LSQ_ERROR("provided zero_rtt has bad cert size");
422                free(item);
423                break;
424            case RTT_DESERIALIZE_OK:
425                memcpy(enc_session->hs_ctx.pubs, info->spubs, 32);
426                enc_session->cert_item = item;
427                break;
428        }
429    }
430    enc_session->enpub = enpub;
431    enc_session->cid   = cid;
432    enc_session->info  = info;
433    /* FIXME: allocation may fail */
434    lsquic_str_append(&enc_session->hs_ctx.sni, domain, strlen(domain));
435    return enc_session;
436}
437
438
439static void
440lsquic_enc_session_destroy (lsquic_enc_session_t *enc_session)
441{
442    if (!enc_session)
443        return ;
444
445    hs_ctx_t *hs_ctx = &enc_session->hs_ctx;
446    lsquic_str_d(&hs_ctx->sni);
447    lsquic_str_d(&hs_ctx->ccs);
448    lsquic_str_d(&hs_ctx->ccrt);
449    lsquic_str_d(&hs_ctx->stk);
450    lsquic_str_d(&hs_ctx->sno);
451    lsquic_str_d(&hs_ctx->prof);
452    lsquic_str_d(&hs_ctx->csct);
453    lsquic_str_d(&hs_ctx->crt);
454    lsquic_str_d(&hs_ctx->scfg_pubs);
455    lsquic_str_d(&enc_session->chlo);
456    lsquic_str_d(&enc_session->sstk);
457    lsquic_str_d(&enc_session->ssno);
458    if (enc_session->dec_ctx_i)
459    {
460        EVP_AEAD_CTX_cleanup(enc_session->dec_ctx_i);
461        free(enc_session->dec_ctx_i);
462    }
463    if (enc_session->enc_ctx_i)
464    {
465        EVP_AEAD_CTX_cleanup(enc_session->enc_ctx_i);
466        free(enc_session->enc_ctx_i);
467    }
468    if (enc_session->dec_ctx_f)
469    {
470        EVP_AEAD_CTX_cleanup(enc_session->dec_ctx_f);
471        free(enc_session->dec_ctx_f);
472    }
473    if (enc_session->enc_ctx_f)
474    {
475        EVP_AEAD_CTX_cleanup(enc_session->enc_ctx_f);
476        free(enc_session->enc_ctx_f);
477    }
478    if (enc_session->info)
479    {
480        lsquic_str_d(&enc_session->info->sstk);
481        lsquic_str_d(&enc_session->info->scfg);
482        lsquic_str_d(&enc_session->info->sni_key);
483        free(enc_session->info);
484    }
485    if (enc_session->cert_item)
486    {
487        free_c_cert_item(enc_session->cert_item);
488        enc_session->cert_item = NULL;
489    }
490    free(enc_session);
491
492}
493
494
495static int get_hs_state(lsquic_enc_session_t *enc_session)
496{
497    return enc_session->hsk_state;
498}
499
500
501/* make sure have more room for encrypt */
502static int
503lsquic_enc_session_is_hsk_done (lsquic_enc_session_t *enc_session)
504{
505    return (get_hs_state(enc_session) == HSK_COMPLETED);
506}
507
508
509static void
510process_copt (lsquic_enc_session_t *enc_session, const uint32_t *const opts,
511                unsigned n_opts)
512{
513    unsigned i;
514    for (i = 0; i < n_opts; ++i)
515        switch (opts[i])
516        {
517        case QTAG_NSTP:
518            enc_session->hs_ctx.opts |= HOPT_NSTP;
519            break;
520        case QTAG_SREJ:
521            enc_session->hs_ctx.opts |= HOPT_SREJ;
522            break;
523        }
524}
525
526
527static int parse_hs_data (lsquic_enc_session_t *enc_session, uint32_t tag,
528                          unsigned char *val, int len, uint32_t head_tag)
529{
530    hs_ctx_t * hs_ctx = &enc_session->hs_ctx;
531
532    switch(tag)
533    {
534    case QTAG_PDMD:
535        hs_ctx->pdmd = get_tag_value_i32(val, len);
536        break;
537
538    case QTAG_MIDS:
539        if (0 != get_tag_val_u32(val, len, &hs_ctx->mids))
540            return -1;
541        break;
542
543    case QTAG_SCLS:
544        hs_ctx->scls = get_tag_value_i32(val, len);
545        break;
546
547    case QTAG_CFCW:
548        if (0 != get_tag_val_u32(val, len, &hs_ctx->cfcw))
549            return -1;
550        break;
551
552    case QTAG_SFCW:
553        if (0 != get_tag_val_u32(val, len, &hs_ctx->sfcw))
554            return -1;
555        break;
556
557    case QTAG_ICSL:
558        hs_ctx->icsl = get_tag_value_i32(val, len);
559        break;
560
561    case QTAG_IRTT:
562        if (0 != get_tag_val_u32(val, len, &hs_ctx->irtt))
563            return -1;
564        hs_ctx->set |= HSET_IRTT;
565        break;
566
567    case QTAG_COPT:
568        if (0 == len % sizeof(uint32_t))
569            process_copt(enc_session, (uint32_t *) val, len / sizeof(uint32_t));
570        /* else ignore, following the reference implementation */
571        break;
572
573    case QTAG_SNI:
574        lsquic_str_setto(&hs_ctx->sni, val, len);
575        ESHIST_APPEND(enc_session, ESHE_SET_SNI);
576        break;
577
578    case QTAG_CCS:
579        lsquic_str_setto(&hs_ctx->ccs, val, len);
580        break;
581
582    case QTAG_CCRT:
583        lsquic_str_setto(&hs_ctx->ccrt, val, len);
584        break;
585
586    case QTAG_CRT:
587        lsquic_str_setto(&hs_ctx->crt, val, len);
588        break;
589
590    case QTAG_PUBS:
591        if (head_tag == QTAG_SCFG)
592            lsquic_str_setto(&hs_ctx->scfg_pubs, val, len);
593        else if (len == 32)
594            memcpy(hs_ctx->pubs, val, len);
595        break;
596
597    case QTAG_RCID:
598        hs_ctx->rcid = get_tag_value_i64(val, len);
599        break;
600
601
602    case QTAG_SMHL:
603        if (0 != get_tag_val_u32(val, len, &hs_ctx->smhl))
604            return -1;
605        hs_ctx->set |= HSET_SMHL;
606        break;
607
608    case QTAG_TCID:
609        if (0 != get_tag_val_u32(val, len, &hs_ctx->tcid))
610            return -1;
611        hs_ctx->set |= HSET_TCID;
612        break;
613
614    case QTAG_EXPY:
615        enc_session->info->expy = get_tag_value_i64(val, len);
616        break;
617
618    case QTAG_ORBT:
619        enc_session->info->orbt = get_tag_value_i64(val, len);
620        break;
621
622    case QTAG_SNO:
623        lsquic_str_setto(&enc_session->ssno, val, len);
624        ESHIST_APPEND(enc_session, ESHE_SET_SNO);
625        break;
626
627    case QTAG_STK:
628        lsquic_str_setto(&enc_session->info->sstk, val, len);
629    ESHIST_APPEND(enc_session, ESHE_SET_STK);
630    break;
631
632    case QTAG_SCID:
633        if (len != SCID_LENGTH)
634            return -1;
635        memcpy(enc_session->info->sscid, val, len);
636        ESHIST_APPEND(enc_session, ESHE_SET_SCID);
637        break;
638
639    case QTAG_AEAD:
640        enc_session->info->aead = get_tag_value_i32(val, len);
641        break;
642
643    case QTAG_KEXS:
644    {
645            if (head_tag == QTAG_SCFG && 0 == len % 4)
646            {
647                const unsigned char *p, *end;
648                unsigned pub_idx, idx;
649#ifdef WIN32
650                pub_idx = 0;
651#endif
652
653                for (p = val; p < val + len; p += 4)
654                    if (0 == memcmp(p, "C255", 4))
655                    {
656                        memcpy(&enc_session->info->kexs, p, 4);
657                        pub_idx = (p - val) / 4;
658                        LSQ_DEBUG("Parsing SCFG: supported KEXS C255 at "
659                                                        "index %u", pub_idx);
660                        break;
661                    }
662                if (p >= val + len)
663                {
664                    LSQ_INFO("supported KEXS not found, trouble ahead");
665                    break;
666                }
667                if (lsquic_str_len(&hs_ctx->scfg_pubs) > 0)
668                {
669                    p = (const unsigned char *)
670                                        lsquic_str_cstr(&hs_ctx->scfg_pubs);
671                    end = p + lsquic_str_len(&hs_ctx->scfg_pubs);
672
673                    for (idx = 0; p < end; ++idx)
674                    {
675                        uint32_t sz = 0;
676                        if (p + 3 > end)
677                            break;
678                        sz |= *p++;
679                        sz |= *p++ << 8;
680                        sz |= *p++ << 16;
681                        if (p + sz > end)
682                            break;
683                        if (idx == pub_idx)
684                        {
685                            if (sz == 32)
686                            {
687                                memcpy(hs_ctx->pubs, p, 32);
688                                memcpy(enc_session->info->spubs, p, 32);
689                            }
690                            break;
691                        }
692                        p += sz;
693                    }
694                }
695                else
696                    LSQ_INFO("No PUBS from SCFG to parse");
697            }
698        }
699        break;
700
701    case QTAG_NONC:
702        if (len != sizeof(hs_ctx->nonc))
703            return -1;
704        memcpy(hs_ctx->nonc, val, len);
705        break;
706
707    case QTAG_SCFG:
708        lsquic_str_setto(&enc_session->info->scfg, val, len);
709        enc_session->info->scfg_flag = 1;
710        break;
711
712    case QTAG_PROF:
713        lsquic_str_setto(&hs_ctx->prof, val, len);
714        ESHIST_APPEND(enc_session, ESHE_SET_PROF);
715        break;
716
717    case QTAG_STTL:
718        hs_ctx->sttl = get_tag_value_i64(val, len);
719        break;
720
721    case QTAG_SRST:
722        if (len != sizeof(hs_ctx->srst))
723        {
724            LSQ_INFO("Unexpected size of SRST: %u instead of %zu bytes",
725                len, sizeof(hs_ctx->srst));
726            return -1;
727        }
728        memcpy(hs_ctx->srst, val, len);
729        hs_ctx->set |= HSET_SRST;
730        ESHIST_APPEND(enc_session, ESHE_SET_SRST);
731        break;
732
733    default:
734        LSQ_DEBUG("Ignored tag '%.*s'", 4, (char *)&tag);
735        break;
736    }
737
738    return 0;
739}
740
741
742/* only for the hs stream-frame data, NOT with the packet header or frame header*/
743static enum handshake_error parse_hs (lsquic_enc_session_t *enc_session,
744                                      const unsigned char *buf, int buf_len,
745                                      uint32_t *head_tag)
746{
747    uint16_t i;
748    const unsigned char *p = buf;
749    const unsigned char *pend = buf + buf_len;
750
751    unsigned char *data;
752    uint32_t len = 0, offset = 0;
753    uint16_t num;
754    uint32_t tag;
755    if (buf_len < 6)
756        return DATA_FORMAT_ERROR;
757
758    memcpy(&tag, p, 4);
759    p += 4;
760
761    {
762        if (tag != QTAG_SREJ && tag != QTAG_REJ && tag != QTAG_SHLO &&
763                                                        tag != QTAG_SCFG)
764            return DATA_FORMAT_ERROR;
765    }
766
767    *head_tag = tag;
768
769    memcpy((char *)&num, p, 2);
770    p += 2 + 2;  /* the 2 bytes padding 0x0000 need to be bypassed */
771
772    if (num < 1)
773        return DATA_FORMAT_ERROR;
774
775    data = (uint8_t *)(buf + 4 * 2 * (1 + num));
776    if ((const char *)data > (const char *)pend)
777    {
778        LSQ_DEBUG("parse_hs tag '%.*s' error: data not enough", 4, (char *)head_tag);
779        return DATA_NOT_ENOUGH;
780    }
781
782    /* check last offset */
783    memcpy((char *)&len, data - 4, 4);
784    if ((const char *)data + len > (const char *)pend)
785    {
786        LSQ_DEBUG("parse_hs tag '%.*s' error: data not enough!!!", 4, (char *)head_tag);
787        return DATA_NOT_ENOUGH;
788    }
789
790    for (i=0; i<num; ++i)
791    {
792        memcpy((char *)&tag, p, 4);
793        p += 4;
794        memcpy((char *)&len, p, 4);
795        len -= offset;
796        p += 4;
797
798        if ((const char *)data + offset + len > (const char *)pend)
799            return DATA_FORMAT_ERROR;
800
801        if (0 != parse_hs_data(enc_session, tag, data + offset, len,
802                                                                *head_tag))
803            return DATA_FORMAT_ERROR;
804        offset += len;
805    }
806
807    LSQ_DEBUG("parse_hs tag '%.*s' no error.", 4, (char *)head_tag);
808    return DATA_NO_ERROR;
809}
810
811
812static uint32_t get_tag_value_i32(unsigned char *val, int len)
813{
814    uint32_t v;
815    if (len < 4)
816        return 0;
817    memcpy(&v, val, 4);
818    return v;
819}
820
821
822static uint64_t get_tag_value_i64(unsigned char *val, int len)
823{
824    uint64_t v;
825    if (len < 8)
826        return 0;
827    memcpy(&v, val, 8);
828    return v;
829}
830
831
832static int
833get_tag_val_u32 (unsigned char *v, int len, uint32_t *val)
834{
835    if (len != 4)
836        return -1;
837    memcpy(val, v, 4);
838    return 0;
839}
840
841
842static void
843generate_cid_buf (void *buf, size_t bufsz)
844{
845    RAND_bytes(buf, bufsz);
846}
847
848
849static lsquic_cid_t
850lsquic_generate_cid (void)
851{
852    lsquic_cid_t cid;
853    generate_cid_buf(&cid, sizeof(cid));
854    return cid;
855}
856
857
858/*  From "QUIC Crypto" for easy reference:
859 *
860 *  A handshake message consists of:
861 *    - The tag of the message.
862 *    - A uint16 containing the number of tag-value pairs.
863 *    - Two bytes of padding which should be zero when sent but ignored when
864 *          received.
865 *    - A series of uint32 tags and uint32 end offsets, one for each
866 *          tag-value pair. The tags must be strictly monotonically
867 *          increasing, and the end-offsets must be monotonic non-decreasing.
868 *          The end offset gives the offset, from the start of the value
869 *          data, to a byte one beyond the end of the data for that tag.
870 *          (Thus the end offset of the last tag contains the length of the
871 *          value data).
872 *    - The value data, concatenated without padding.
873 */
874
875struct table_entry { uint32_t tag, off; };
876
877struct message_writer
878{
879    unsigned char       *mw_p;
880    struct table_entry   mw_first_dummy_entry;
881    struct table_entry  *mw_entry,
882                        *mw_prev_entry,
883                        *mw_end;
884};
885
886/* MW_ family of macros is used to write entries to handshake message
887 * (MW stands for "message writer").
888 */
889#define MW_BEGIN(mw, msg_tag, n_entries, data_ptr) do {             \
890    uint32_t t_ = msg_tag;                                          \
891    uint16_t n_ = n_entries;                                        \
892    memcpy(data_ptr, &t_, 4);                                       \
893    memcpy(data_ptr + 4, &n_, 2);                                   \
894    memset(data_ptr + 4 + 2, 0, 2);                                 \
895    (mw)->mw_entry = (void *) (data_ptr + 8);                       \
896    (mw)->mw_p = data_ptr + 8 +                                     \
897                    (n_entries) * sizeof((mw)->mw_entry[0]);        \
898    (mw)->mw_first_dummy_entry.tag = 0;                             \
899    (mw)->mw_first_dummy_entry.off = 0;                             \
900    (mw)->mw_prev_entry = &(mw)->mw_first_dummy_entry;              \
901    (mw)->mw_end = (void *) (mw)->mw_p;                             \
902} while (0)
903
904#ifndef NDEBUG
905#   define MW_END(mw) do {                                          \
906        assert((mw)->mw_entry == (mw)->mw_end);                     \
907    } while (0)
908#else
909#   define MW_END(mw)
910#endif
911
912#define MW_P(mw) ((mw)->mw_p)
913
914#define MW_ADVANCE_P(mw, n) do {                                    \
915    MW_P(mw) += (n);                                                \
916} while (0)
917
918#define MW_WRITE_TABLE_ENTRY(mw, tag_, sz) do {                     \
919    assert((mw)->mw_prev_entry->tag < (tag_));                      \
920    assert((mw)->mw_entry < (mw)->mw_end);                          \
921    (mw)->mw_entry->tag = (tag_);                                   \
922    (mw)->mw_entry->off = (mw)->mw_prev_entry->off + (sz);          \
923    (mw)->mw_prev_entry = (mw)->mw_entry;                           \
924    ++(mw)->mw_entry;                                               \
925} while (0)
926
927#define MW_WRITE_BUFFER(mw, tag, buf, sz) do {                      \
928    MW_WRITE_TABLE_ENTRY(mw, tag, sz);                              \
929    memcpy(MW_P(mw), buf, sz);                                      \
930    MW_ADVANCE_P(mw, sz);                                           \
931} while (0)
932
933#define MW_WRITE_LS_STR(mw, tag, s) \
934    MW_WRITE_BUFFER(mw, tag, lsquic_str_buf(s), lsquic_str_len(s))
935
936#define MW_WRITE_UINT32(mw, tag, val) do {                          \
937    uint32_t v_ = (val);                                            \
938    MW_WRITE_BUFFER(mw, tag, &v_, sizeof(v_));                      \
939} while (0)
940
941#define MW_WRITE_UINT64(mw, tag, val) do {                          \
942    uint64_t v_ = (val);                                            \
943    MW_WRITE_BUFFER(mw, tag, &v_, sizeof(v_));                      \
944} while (0)
945
946
947/* MSG_LEN_ family of macros calculates buffer size required for a
948 * handshake message.
949 */
950#define MSG_LEN_INIT(len) do {                                      \
951    len = 4 /* Tag */ + 2 /* # tags */ + 2 /* Two zero bytes */;    \
952} while (0)
953
954#define MSG_LEN_ADD(len, payload_sz) do {                           \
955    len += 4 + 4 + (payload_sz);                                    \
956} while (0)
957
958#define MSG_LEN_VAL(len) (+(len))
959
960
961static int
962lsquic_enc_session_gen_chlo (lsquic_enc_session_t *enc_session,
963                        enum lsquic_version version, uint8_t *buf, size_t *len)
964{
965    int ret, include_pad;
966    const lsquic_str_t *const ccs = get_common_certs_hash();
967    const struct lsquic_engine_settings *const settings =
968                                        &enc_session->enpub->enp_settings;
969    c_cert_item_t *const cert_item = enc_session->cert_item;
970    unsigned char pub_key[32];
971    size_t ua_len;
972    uint32_t opts[1];  /* Only NSTP is supported for now */
973    unsigned n_opts, msg_len, n_tags, pad_size;
974    struct message_writer mw;
975
976    /* Before we do anything else, sanity check: */
977    if (*len < MIN_CHLO_SIZE)
978        return -1;
979
980    n_opts = 0;
981    /* CHLO is not regenerated during version negotiation.  Hence we always
982     * include this option to cover the case when Q044 gets negotiated down.
983     */
984    if (settings->es_support_nstp)
985        opts[ n_opts++ ] = QTAG_NSTP;
986
987    /* Count tags and calculate required buffer size: */
988    MSG_LEN_INIT(msg_len);                  n_tags = 0;
989    MSG_LEN_ADD(msg_len, 4);                ++n_tags;           /* PDMD */
990    MSG_LEN_ADD(msg_len, 4);                ++n_tags;           /* AEAD */
991    MSG_LEN_ADD(msg_len, 4);                ++n_tags;           /* VER  */
992    MSG_LEN_ADD(msg_len, 4);                ++n_tags;           /* MIDS */
993    MSG_LEN_ADD(msg_len, 4);                ++n_tags;           /* SCLS */
994    MSG_LEN_ADD(msg_len, 4);                ++n_tags;           /* CFCW */
995    MSG_LEN_ADD(msg_len, 4);                ++n_tags;           /* SFCW */
996    MSG_LEN_ADD(msg_len, 4);                ++n_tags;           /* ICSL */
997    MSG_LEN_ADD(msg_len, 4);                ++n_tags;           /* SMHL */
998    MSG_LEN_ADD(msg_len, 4);                ++n_tags;           /* KEXS */
999    MSG_LEN_ADD(msg_len, 0);                ++n_tags;           /* CSCT */
1000    if (n_opts > 0)
1001    {
1002        MSG_LEN_ADD(msg_len, sizeof(opts[0]) * n_opts);
1003                                            ++n_tags;           /* COPT */
1004    }
1005    if (settings->es_ua)
1006    {
1007        ua_len = strlen(settings->es_ua);
1008        if (ua_len > 0)
1009        {
1010            MSG_LEN_ADD(msg_len, ua_len);   ++n_tags;           /* UAID */
1011        }
1012    }
1013    else
1014        ua_len = 0;
1015    if (settings->es_support_tcid0)
1016    {
1017        MSG_LEN_ADD(msg_len, 4);            ++n_tags;           /* TCID */
1018    }
1019    MSG_LEN_ADD(msg_len, lsquic_str_len(&enc_session->hs_ctx.sni));
1020                                            ++n_tags;           /* SNI  */
1021    MSG_LEN_ADD(msg_len, lsquic_str_len(ccs));  ++n_tags;           /* CCS  */
1022    if (cert_item)
1023    {
1024        enc_session->cert_ptr = &cert_item->crts[0];
1025        MSG_LEN_ADD(msg_len, lsquic_str_len(cert_item->hashs));
1026                                            ++n_tags;           /* CCRT */
1027        MSG_LEN_ADD(msg_len, 8);            ++n_tags;           /* XLCT */
1028    }
1029    MSG_LEN_ADD(msg_len, lsquic_str_len(&enc_session->ssno));
1030                                            ++n_tags;           /* SNO  */
1031    MSG_LEN_ADD(msg_len, lsquic_str_len(&enc_session->info->sstk));
1032                                            ++n_tags;           /* STK  */
1033    if (lsquic_str_len(&enc_session->info->scfg) > 0)
1034    {
1035        MSG_LEN_ADD(msg_len, sizeof(enc_session->info->sscid));
1036                                            ++n_tags;           /* SCID */
1037        if (enc_session->cert_ptr)
1038        {
1039            MSG_LEN_ADD(msg_len, sizeof(pub_key));
1040                                            ++n_tags;           /* PUBS */
1041            MSG_LEN_ADD(msg_len, sizeof(enc_session->hs_ctx.nonc));
1042                                            ++n_tags;           /* NONC */
1043            rand_bytes(enc_session->priv_key, 32);
1044            c255_get_pub_key(enc_session->priv_key, pub_key);
1045            gen_nonce_c(enc_session->hs_ctx.nonc, enc_session->info->orbt);
1046        }
1047    }
1048    include_pad = MSG_LEN_VAL(msg_len) < MIN_CHLO_SIZE;
1049    if (include_pad)
1050    {
1051        if (MSG_LEN_VAL(msg_len) + sizeof(struct table_entry) < MIN_CHLO_SIZE)
1052            pad_size = MIN_CHLO_SIZE - MSG_LEN_VAL(msg_len) -
1053                                                sizeof(struct table_entry);
1054        else
1055            pad_size = 0;
1056        MSG_LEN_ADD(msg_len, pad_size);     ++n_tags;           /* PAD  */
1057    }
1058#ifdef WIN32
1059    else
1060        pad_size = 0;
1061#endif
1062
1063    /* Check that we have enough room in the output buffer: */
1064    if (MSG_LEN_VAL(msg_len) > *len)
1065        return -1;
1066
1067    /* Write CHLO: */
1068    MW_BEGIN(&mw, QTAG_CHLO, n_tags, buf);
1069    if (include_pad)
1070    {
1071        memset(MW_P(&mw), '-', pad_size);
1072        MW_WRITE_TABLE_ENTRY(&mw, QTAG_PAD, pad_size);
1073        MW_ADVANCE_P(&mw, pad_size);
1074    }
1075    MW_WRITE_LS_STR(&mw, QTAG_SNI, &enc_session->hs_ctx.sni);
1076    MW_WRITE_LS_STR(&mw, QTAG_STK, &enc_session->info->sstk);
1077    MW_WRITE_LS_STR(&mw, QTAG_SNO, &enc_session->ssno);
1078    MW_WRITE_UINT32(&mw, QTAG_VER, lsquic_ver2tag(version));
1079    MW_WRITE_LS_STR(&mw, QTAG_CCS, ccs);
1080    if (lsquic_str_len(&enc_session->info->scfg) > 0 && enc_session->cert_ptr)
1081        MW_WRITE_BUFFER(&mw, QTAG_NONC, enc_session->hs_ctx.nonc,
1082                                        sizeof(enc_session->hs_ctx.nonc));
1083    MW_WRITE_UINT32(&mw, QTAG_AEAD, settings->es_aead);
1084    if (ua_len)
1085        MW_WRITE_BUFFER(&mw, QTAG_UAID, settings->es_ua, ua_len);
1086    if (lsquic_str_len(&enc_session->info->scfg) > 0)
1087        MW_WRITE_BUFFER(&mw, QTAG_SCID, enc_session->info->sscid,
1088                                        sizeof(enc_session->info->sscid));
1089    if (settings->es_support_tcid0)
1090        MW_WRITE_UINT32(&mw, QTAG_TCID, 0);
1091    MW_WRITE_UINT32(&mw, QTAG_PDMD, settings->es_pdmd);
1092    MW_WRITE_UINT32(&mw, QTAG_SMHL, 1);
1093    MW_WRITE_UINT32(&mw, QTAG_ICSL, settings->es_idle_conn_to / 1000000);
1094    if (lsquic_str_len(&enc_session->info->scfg) > 0 && enc_session->cert_ptr)
1095        MW_WRITE_BUFFER(&mw, QTAG_PUBS, pub_key, sizeof(pub_key));
1096    MW_WRITE_UINT32(&mw, QTAG_MIDS, settings->es_max_streams_in);
1097    MW_WRITE_UINT32(&mw, QTAG_SCLS, settings->es_silent_close);
1098    MW_WRITE_UINT32(&mw, QTAG_KEXS, settings->es_kexs);
1099    if (cert_item)
1100        MW_WRITE_BUFFER(&mw, QTAG_XLCT, lsquic_str_buf(cert_item->hashs), 8);
1101    /* CSCT is empty on purpose (retained from original code) */
1102    MW_WRITE_TABLE_ENTRY(&mw, QTAG_CSCT, 0);
1103    if (n_opts > 0)
1104        MW_WRITE_BUFFER(&mw, QTAG_COPT, opts, n_opts * sizeof(opts[0]));
1105    if (cert_item)
1106        MW_WRITE_LS_STR(&mw, QTAG_CCRT, cert_item->hashs);
1107    MW_WRITE_UINT32(&mw, QTAG_CFCW, settings->es_cfcw);
1108    MW_WRITE_UINT32(&mw, QTAG_SFCW, settings->es_sfcw);
1109    MW_END(&mw);
1110    assert(buf + *len >= MW_P(&mw));
1111
1112    *len = MW_P(&mw) - buf;
1113
1114    lsquic_str_setto(&enc_session->chlo, buf, *len);
1115
1116    if (lsquic_str_len(&enc_session->info->scfg) > 0 && enc_session->cert_ptr)
1117    {
1118        enc_session->have_key = 0;
1119        assert(lsquic_str_len(enc_session->cert_ptr) > 0);
1120        ret = determine_keys(enc_session
1121                                            );
1122        enc_session->have_key = 1;
1123    }
1124    else
1125        ret = 0;
1126
1127    LSQ_DEBUG("lsquic_enc_session_gen_chlo called, return %d, buf_len %zd.", ret, *len);
1128    return ret;
1129}
1130
1131
1132static int handle_chlo_reply_verify_prof(lsquic_enc_session_t *enc_session,
1133                                         lsquic_str_t **out_certs,
1134                                         size_t *out_certs_count,
1135                                         lsquic_str_t *cached_certs,
1136                                         int cached_certs_count)
1137{
1138    const unsigned char *const in =
1139                (const unsigned char *) lsquic_str_buf(&enc_session->hs_ctx.crt);
1140    const unsigned char *const in_end =
1141                                    in + lsquic_str_len(&enc_session->hs_ctx.crt);
1142    EVP_PKEY *pub_key;
1143    int ret;
1144    size_t i;
1145    X509 *cert, *server_cert;
1146    STACK_OF(X509) *chain = NULL;
1147    ret = decompress_certs(in, in_end,cached_certs, cached_certs_count,
1148                           out_certs, out_certs_count);
1149    if (ret)
1150        return ret;
1151
1152    server_cert = bio_to_crt((const char *)lsquic_str_cstr(out_certs[0]),
1153                      lsquic_str_len(out_certs[0]), 0);
1154    pub_key = X509_get_pubkey(server_cert);
1155    ret = verify_prof((const uint8_t *)lsquic_str_cstr(&enc_session->chlo),
1156                      (size_t)lsquic_str_len(&enc_session->chlo),
1157                      &enc_session->info->scfg,
1158                      pub_key,
1159                      (const uint8_t *)lsquic_str_cstr(&enc_session->hs_ctx.prof),
1160                      lsquic_str_len(&enc_session->hs_ctx.prof));
1161    EVP_PKEY_free(pub_key);
1162    if (ret != 0)
1163        goto cleanup;
1164
1165    if (enc_session->enpub->enp_verify_cert)
1166    {
1167        chain = sk_X509_new_null();
1168        sk_X509_push(chain, server_cert);
1169        for (i = 1; i < *out_certs_count; ++i)
1170        {
1171            cert = bio_to_crt((const char *)lsquic_str_cstr(out_certs[i]),
1172                                    lsquic_str_len(out_certs[i]), 0);
1173            if (cert)
1174                sk_X509_push(chain, cert);
1175            else
1176            {
1177                LSQ_WARN("cannot push certificate to stack");
1178                ret = -1;
1179                goto cleanup;
1180            }
1181        }
1182        ret = enc_session->enpub->enp_verify_cert(
1183                                enc_session->enpub->enp_verify_ctx, chain);
1184        LSQ_INFO("server certificate verification %ssuccessful",
1185                                                    ret == 0 ? "" : "not ");
1186    }
1187
1188  cleanup:
1189    if (chain)
1190        sk_X509_free(chain);
1191    X509_free(server_cert);
1192    return ret;
1193}
1194
1195
1196void setup_aead_ctx(EVP_AEAD_CTX **ctx, unsigned char key[], int key_len,
1197                    unsigned char *key_copy)
1198{
1199    const EVP_AEAD *aead_ = EVP_aead_aes_128_gcm();
1200    const int auth_tag_size = 12;
1201    if (*ctx)
1202    {
1203        EVP_AEAD_CTX_cleanup(*ctx);
1204    }
1205    else
1206        *ctx = (EVP_AEAD_CTX *)malloc(sizeof(EVP_AEAD_CTX));
1207
1208    EVP_AEAD_CTX_init(*ctx, aead_, key, key_len, auth_tag_size, NULL);
1209    if (key_copy)
1210        memcpy(key_copy, key, key_len);
1211}
1212
1213
1214static int
1215determine_diversification_key (lsquic_enc_session_t *enc_session,
1216                  uint8_t *diversification_nonce
1217                  )
1218{
1219    EVP_AEAD_CTX **ctx_s_key;
1220    unsigned char *key_i, *iv;
1221    uint8_t ikm[aes128_key_len + aes128_iv_len];
1222
1223    ctx_s_key = &enc_session->dec_ctx_i;
1224    key_i = enc_session->dec_key_i;
1225    iv = enc_session->dec_key_nonce_i;
1226    memcpy(ikm, key_i, aes128_key_len);
1227    memcpy(ikm + aes128_key_len, iv, aes128_iv_len);
1228    export_key_material(ikm, aes128_key_len + aes128_iv_len,
1229                        diversification_nonce, DNONC_LENGTH,
1230                        (const unsigned char *) "QUIC key diversification", 24,
1231                        0, NULL, aes128_key_len, key_i, 0, NULL,
1232                        aes128_iv_len, iv, NULL);
1233
1234    setup_aead_ctx(ctx_s_key, key_i, aes128_key_len, NULL);
1235    LSQ_DEBUG("determine_diversification_keys diversification_key: %s\n",
1236              get_bin_str(key_i, aes128_key_len, 512));
1237    LSQ_DEBUG("determine_diversification_keys diversification_key nonce: %s\n",
1238              get_bin_str(iv, aes128_iv_len, 512));
1239    return 0;
1240}
1241
1242
1243/* After CHLO msg generatered, call it to determine_keys */
1244static int determine_keys(lsquic_enc_session_t *enc_session)
1245{
1246    lsquic_str_t *chlo = &enc_session->chlo;
1247    uint8_t shared_key_c[32];
1248    struct lsquic_buf *nonce_c = lsquic_buf_create(100);
1249    struct lsquic_buf *hkdf_input = lsquic_buf_create(0);
1250
1251    unsigned char c_key[aes128_key_len];
1252    unsigned char s_key[aes128_key_len];
1253    unsigned char *c_key_bin = NULL;
1254    unsigned char *s_key_bin = NULL;
1255
1256    unsigned char *c_iv;
1257    unsigned char *s_iv;
1258    unsigned char sub_key[32];
1259    EVP_AEAD_CTX **ctx_c_key, **ctx_s_key;
1260    char key_flag;
1261
1262    lsquic_buf_clear(nonce_c);
1263    lsquic_buf_clear(hkdf_input);
1264    if (enc_session->have_key == 0)
1265    {
1266        lsquic_buf_append(hkdf_input, "QUIC key expansion\0", 18 + 1); // Add a 0x00 */
1267        key_flag = 'I';
1268    }
1269    else
1270    {
1271        lsquic_buf_append(hkdf_input, "QUIC forward secure key expansion\0", 33 + 1); // Add a 0x00 */
1272        key_flag = 'F';
1273    }
1274
1275    c255_gen_share_key(enc_session->priv_key,
1276                       enc_session->hs_ctx.pubs,
1277                       (unsigned char *)shared_key_c);
1278    {
1279        if (enc_session->have_key == 0)
1280        {
1281            ctx_c_key = &enc_session->enc_ctx_i;
1282            ctx_s_key = &enc_session->dec_ctx_i;
1283            c_iv = (unsigned char *) enc_session->enc_key_nonce_i;
1284            s_iv = (unsigned char *) enc_session->dec_key_nonce_i;
1285            c_key_bin = enc_session->enc_key_i;
1286            s_key_bin = enc_session->dec_key_i;
1287        }
1288        else
1289        {
1290            ctx_c_key = &enc_session->enc_ctx_f;
1291            ctx_s_key = &enc_session->dec_ctx_f;
1292            c_iv = (unsigned char *) enc_session->enc_key_nonce_f;
1293            s_iv = (unsigned char *) enc_session->dec_key_nonce_f;
1294        }
1295    }
1296
1297    LSQ_DEBUG("export_key_material c255_gen_share_key %s",
1298              get_bin_str(shared_key_c, 32, 512));
1299
1300    lsquic_buf_append(hkdf_input, (char *)&enc_session->cid, sizeof(enc_session->cid));
1301    lsquic_buf_append(hkdf_input, lsquic_str_cstr(chlo), lsquic_str_len(chlo)); /* CHLO msg */
1302    {
1303        lsquic_buf_append(hkdf_input, lsquic_str_cstr(&enc_session->info->scfg),
1304                       lsquic_str_len(&enc_session->info->scfg)); /* scfg msg */
1305    }
1306    lsquic_buf_append(hkdf_input, lsquic_str_cstr(enc_session->cert_ptr),
1307                   lsquic_str_len(enc_session->cert_ptr));
1308    LSQ_DEBUG("export_key_material hkdf_input %s",
1309              get_bin_str(lsquic_buf_begin(hkdf_input),
1310                          (size_t)lsquic_buf_size(hkdf_input), 512));
1311
1312    /* then need to use the salts and the shared_key_* to get the real aead key */
1313    lsquic_buf_append(nonce_c, (const char *) enc_session->hs_ctx.nonc, 32);
1314    lsquic_buf_append(nonce_c, lsquic_str_cstr(&enc_session->ssno),
1315                   lsquic_str_len(&enc_session->ssno));
1316    LSQ_DEBUG("export_key_material nonce %s",
1317              get_bin_str(lsquic_buf_begin(nonce_c),
1318                          (size_t)lsquic_buf_size(nonce_c), 512));
1319
1320    export_key_material(shared_key_c, 32,
1321                        (unsigned char *)lsquic_buf_begin(nonce_c), lsquic_buf_size(nonce_c),
1322                        (unsigned char *)lsquic_buf_begin(hkdf_input),
1323                        lsquic_buf_size(hkdf_input),
1324                        aes128_key_len, c_key,
1325                        aes128_key_len, s_key,
1326                        aes128_iv_len, c_iv,
1327                        aes128_iv_len, s_iv,
1328                        sub_key);
1329
1330    setup_aead_ctx(ctx_c_key, c_key, aes128_key_len, c_key_bin);
1331    setup_aead_ctx(ctx_s_key, s_key, aes128_key_len, s_key_bin);
1332
1333
1334    lsquic_buf_destroy(nonce_c);
1335    lsquic_buf_destroy(hkdf_input);
1336
1337    LSQ_DEBUG("***export_key_material '%c' c_key: %s", key_flag,
1338              get_bin_str(c_key, aes128_key_len, 512));
1339    LSQ_DEBUG("***export_key_material '%c' s_key: %s", key_flag,
1340              get_bin_str(s_key, aes128_key_len, 512));
1341    LSQ_DEBUG("***export_key_material '%c' c_iv: %s", key_flag,
1342              get_bin_str(c_iv, aes128_iv_len, 512));
1343    LSQ_DEBUG("***export_key_material '%c' s_iv: %s", key_flag,
1344              get_bin_str(s_iv, aes128_iv_len, 512));
1345    LSQ_DEBUG("***export_key_material '%c' subkey: %s", key_flag,
1346              get_bin_str(sub_key, 32, 512));
1347
1348    return 0;
1349}
1350
1351
1352/* 0 Match */
1353static int cached_certs_match(c_cert_item_t *item,
1354                                        lsquic_str_t **certs, int count)
1355{
1356    int i;
1357    if (!item || item->count != count)
1358        return -1;
1359
1360    for (i=0; i<count; ++i)
1361    {
1362        if (lsquic_str_bcmp(certs[i], &item->crts[i]) != 0)
1363            return -1;
1364    }
1365
1366    return 0;
1367}
1368
1369
1370static const char *
1371he2str (enum handshake_error he)
1372{
1373    switch (he)
1374    {
1375    case DATA_NOT_ENOUGH:   return "DATA_NOT_ENOUGH";
1376    case HS_ERROR:          return "HS_ERROR";
1377    case HS_SHLO:           return "HS_SHLO";
1378    case HS_1RTT:           return "HS_1RTT";
1379    case HS_2RTT:           return "HS_2RTT";
1380    default:
1381        assert(0);          return "<unknown enum value>";
1382    }
1383}
1384
1385
1386/* NOT packet, just the frames-data */
1387/* return rtt number:
1388 *      0 OK
1389 *      DATA_NOT_ENOUGH(-2) for not enough data,
1390 *      DATA_FORMAT_ERROR(-1) all other errors
1391 */
1392static int
1393lsquic_enc_session_handle_chlo_reply (lsquic_enc_session_t *enc_session,
1394                                                const uint8_t *data, int len)
1395{
1396    uint32_t head_tag;
1397    int ret;
1398    lsquic_session_cache_info_t *info = enc_session->info;
1399    c_cert_item_t *cert_item = enc_session->cert_item;
1400
1401    /* FIXME get the number first */
1402    lsquic_str_t **out_certs = NULL;
1403    size_t out_certs_count = 0, i;
1404
1405    ret = parse_hs(enc_session, data, len, &head_tag);
1406    if (ret)
1407        goto end;
1408
1409    if (head_tag != QTAG_SREJ &&
1410        head_tag != QTAG_REJ &&
1411        head_tag != QTAG_SHLO)
1412    {
1413        ret = 1;
1414        goto end;
1415    }
1416
1417    if (head_tag == QTAG_SREJ || head_tag == QTAG_REJ)
1418    {
1419        enc_session->hsk_state = HSK_CHLO_REJ;
1420        enc_session->es_flags |= ES_RECV_REJ;
1421    }
1422    else if(head_tag == QTAG_SHLO)
1423    {
1424        enc_session->hsk_state = HSK_COMPLETED;
1425    }
1426
1427    if (info->scfg_flag == 1)
1428    {
1429        ret = parse_hs(enc_session, (uint8_t *)lsquic_str_cstr(&info->scfg),
1430                       lsquic_str_len(&info->scfg), &head_tag);
1431
1432        /* After handled, set the length to 0 to avoid do it again*/
1433        enc_session->info->scfg_flag = 2;
1434        if (ret)
1435            goto end;
1436
1437        if (lsquic_str_len(&enc_session->hs_ctx.crt) > 0)
1438        {
1439            out_certs_count = get_certs_count(&enc_session->hs_ctx.crt);
1440            if (out_certs_count > 0)
1441            {
1442                out_certs = malloc(out_certs_count * sizeof(lsquic_str_t *));
1443                if (!out_certs)
1444                {
1445                    ret = -1;
1446                    goto end;
1447                }
1448
1449                for (i=0; i<out_certs_count; ++i)
1450                    out_certs[i] = lsquic_str_new(NULL, 0);
1451
1452                ret = handle_chlo_reply_verify_prof(enc_session, out_certs,
1453                                            &out_certs_count,
1454                                            (cert_item ? cert_item->crts : NULL),
1455                                            (cert_item ? cert_item->count : 0));
1456                if (ret == 0)
1457                {
1458                    if (out_certs_count > 0)
1459                    {
1460                        if (cached_certs_match(cert_item, out_certs,
1461                                                        out_certs_count) != 0)
1462                        {
1463                            cert_item = make_c_cert_item(out_certs,
1464                                                            out_certs_count);
1465                            enc_session->cert_item = cert_item;
1466                            enc_session->cert_ptr = &cert_item->crts[0];
1467                        }
1468                    }
1469                }
1470                for (i=0; i<out_certs_count; ++i)
1471                    lsquic_str_delete(out_certs[i]);
1472                free(out_certs);
1473
1474                if (ret)
1475                    goto end;
1476            }
1477        }
1478    }
1479
1480    if (enc_session->hsk_state == HSK_COMPLETED)
1481    {
1482        ret = determine_keys(enc_session
1483                                           ); /* FIXME: check ret */
1484        enc_session->have_key = 3;
1485    }
1486
1487  end:
1488    LSQ_DEBUG("lsquic_enc_session_handle_chlo_reply called, buf in %d, return %d.", len, ret);
1489    EV_LOG_CONN_EVENT(enc_session->cid, "%s returning %s", __func__,
1490                                                                he2str(ret));
1491    return ret;
1492}
1493
1494
1495static uint64_t combine_path_id_pack_num(uint8_t path_id, uint64_t pack_num)
1496{
1497    uint64_t v = ((uint64_t)path_id << 56) | pack_num;
1498    return v;
1499}
1500
1501
1502#   define IS_SERVER(session) 0
1503
1504static int
1505verify_packet_hash (const lsquic_enc_session_t *enc_session,
1506    enum lsquic_version version, const unsigned char *buf, size_t *header_len,
1507    size_t data_len, unsigned char *buf_out, size_t max_out_len,
1508    size_t *out_len)
1509{
1510    uint8_t md[HS_PKT_HASH_LENGTH];
1511    uint128 hash;
1512    int ret;
1513
1514    if (data_len < HS_PKT_HASH_LENGTH)
1515        return -1;
1516
1517    if (version >= LSQVER_039)
1518    {
1519        hash = fnv1a_128_3(buf, *header_len,
1520                    buf + *header_len + HS_PKT_HASH_LENGTH,
1521                    data_len - HS_PKT_HASH_LENGTH,
1522                    (unsigned char *) "Server", 6);
1523    }
1524    else
1525    {
1526        hash = fnv1a_128_2(buf, *header_len,
1527                        buf + *header_len + HS_PKT_HASH_LENGTH,
1528                        data_len - HS_PKT_HASH_LENGTH);
1529    }
1530
1531    serialize_fnv128_short(hash, md);
1532    ret = memcmp(md, buf + *header_len, HS_PKT_HASH_LENGTH);
1533    if(ret == 0)
1534    {
1535        *header_len += HS_PKT_HASH_LENGTH;
1536        *out_len = data_len - HS_PKT_HASH_LENGTH;
1537        if (max_out_len < *header_len + *out_len)
1538            return -1;
1539
1540        memcpy(buf_out, buf, *header_len + *out_len);
1541        return 0;
1542    }
1543    else
1544        return -1;
1545}
1546
1547
1548static enum enc_level
1549decrypt_packet (lsquic_enc_session_t *enc_session, uint8_t path_id,
1550                uint64_t pack_num, unsigned char *buf, size_t *header_len,
1551                size_t data_len, unsigned char *buf_out, size_t max_out_len,
1552                size_t *out_len)
1553{
1554    int ret;
1555    /* Comment: 12 = sizeof(dec_key_iv] 4 + sizeof(pack_num) 8 */
1556    uint8_t nonce[12];
1557    uint64_t path_id_packet_number;
1558    EVP_AEAD_CTX *key = NULL;
1559    int try_times = 0;
1560    enum enc_level enc_level;
1561
1562    path_id_packet_number = combine_path_id_pack_num(path_id, pack_num);
1563    memcpy(buf_out, buf, *header_len);
1564    do
1565    {
1566        if (enc_session->have_key == 3 && try_times == 0)
1567        {
1568            key = enc_session->dec_ctx_f;
1569            memcpy(nonce, enc_session->dec_key_nonce_f, 4);
1570            LSQ_DEBUG("decrypt_packet using 'F' key...");
1571            enc_level = ENC_LEV_FORW;
1572        }
1573        else
1574        {
1575            key = enc_session->dec_ctx_i;
1576            memcpy(nonce, enc_session->dec_key_nonce_i, 4);
1577            LSQ_DEBUG("decrypt_packet using 'I' key...");
1578            enc_level = ENC_LEV_INIT;
1579        }
1580        memcpy(nonce + 4, &path_id_packet_number,
1581               sizeof(path_id_packet_number));
1582
1583        *out_len = data_len;
1584        ret = aes_aead_dec(key,
1585                           buf, *header_len,
1586                           nonce, 12,
1587                           buf + *header_len, data_len,
1588                           buf_out + *header_len, out_len);
1589
1590        if (ret != 0)
1591            ++try_times;
1592        else
1593        {
1594            if (enc_session->peer_have_final_key == 0 &&
1595                enc_session->have_key == 3 &&
1596                try_times == 0)
1597            {
1598                LSQ_DEBUG("!!!decrypt_packet find peer have final key.");
1599                enc_session->peer_have_final_key = 1;
1600                EV_LOG_CONN_EVENT(enc_session->cid, "settled on private key "
1601                    "'%c' after %d tries (packet number %"PRIu64")",
1602                    key == enc_session->dec_ctx_f ? 'F' : 'I',
1603                    try_times, pack_num);
1604            }
1605            break;
1606        }
1607    }
1608    while (try_times < 2);
1609
1610    LSQ_DEBUG("***decrypt_packet %s.", (ret == 0 ? "succeed" : "failed"));
1611    return ret == 0 ? enc_level : (enum enc_level) -1;
1612}
1613
1614
1615static int
1616lsquic_enc_session_have_key_gt_one (const lsquic_enc_session_t *enc_session)
1617{
1618    return enc_session && enc_session->have_key > 1;
1619}
1620
1621
1622/* The size of `buf' is *header_len plus data_len.  The two parts of the
1623 * buffer correspond to the header and the payload of incoming QUIC packet.
1624 */
1625static enum enc_level
1626lsquic_enc_session_decrypt (lsquic_enc_session_t *enc_session,
1627               enum lsquic_version version,
1628               uint8_t path_id, uint64_t pack_num,
1629               unsigned char *buf, size_t *header_len, size_t data_len,
1630               unsigned char *diversification_nonce,
1631               unsigned char *buf_out, size_t max_out_len, size_t *out_len)
1632{
1633    /* Client: got SHLO which should have diversification_nonce */
1634    if (diversification_nonce && enc_session && enc_session->have_key == 1)
1635    {
1636        determine_diversification_key(enc_session, diversification_nonce);
1637        enc_session->have_key = 2;
1638    }
1639
1640    if (lsquic_enc_session_have_key_gt_one(enc_session))
1641        return decrypt_packet(enc_session, path_id, pack_num, buf,
1642                        header_len, data_len, buf_out, max_out_len, out_len);
1643    else if (0 == verify_packet_hash(enc_session, version, buf, header_len,
1644                                     data_len, buf_out, max_out_len, out_len))
1645        return ENC_LEV_CLEAR;
1646    else
1647        return -1;
1648}
1649
1650
1651static enum enc_level
1652lsquic_enc_session_encrypt (lsquic_enc_session_t *enc_session,
1653               enum lsquic_version version,
1654               uint8_t path_id, uint64_t pack_num,
1655               const unsigned char *header, size_t header_len,
1656               const unsigned char *data, size_t data_len,
1657               unsigned char *buf_out, size_t max_out_len, size_t *out_len,
1658               int is_hello)
1659{
1660    uint8_t md[HS_PKT_HASH_LENGTH];
1661    uint128 hash;
1662    int ret;
1663    enum enc_level enc_level;
1664    int is_chlo = (is_hello && ((IS_SERVER(enc_session)) == 0));
1665    int is_shlo = (is_hello && (IS_SERVER(enc_session)));
1666
1667    /* Comment: 12 = sizeof(dec_key_iv] 4 + sizeof(pack_num) 8 */
1668    uint8_t nonce[12];
1669    uint64_t path_id_packet_number;
1670    EVP_AEAD_CTX *key;
1671
1672    if (enc_session)
1673        LSQ_DEBUG("%s: hsk_state: %d", __func__, enc_session->hsk_state);
1674    else
1675        LSQ_DEBUG("%s: enc_session is not set", __func__);
1676
1677    if (!enc_session || enc_session->have_key == 0 || is_chlo)
1678    {
1679        *out_len = header_len + data_len + HS_PKT_HASH_LENGTH;
1680        if (max_out_len < *out_len)
1681            return -1;
1682
1683        if (version >= LSQVER_039)
1684        {
1685            hash = fnv1a_128_3(header, header_len, data, data_len,
1686                                        (unsigned char *) "Client", 6);
1687        }
1688        else
1689        {
1690            hash = fnv1a_128_2(header, header_len, data, data_len);
1691        }
1692
1693        serialize_fnv128_short(hash, md);
1694        memcpy(buf_out, header, header_len);
1695        memcpy(buf_out + header_len, md, HS_PKT_HASH_LENGTH);
1696        memcpy(buf_out + header_len + HS_PKT_HASH_LENGTH, data, data_len);
1697        return ENC_LEV_CLEAR;
1698    }
1699    else
1700    {
1701        if (enc_session->have_key != 3 || is_shlo ||
1702            ((IS_SERVER(enc_session)) &&
1703             enc_session->server_start_use_final_key == 0))
1704        {
1705            LSQ_DEBUG("lsquic_enc_session_encrypt using 'I' key...");
1706            key = enc_session->enc_ctx_i;
1707            memcpy(nonce, enc_session->enc_key_nonce_i, 4);
1708            if (is_shlo && enc_session->have_key == 3)
1709            {
1710                enc_session->server_start_use_final_key = 1;
1711            }
1712            enc_level = ENC_LEV_INIT;
1713        }
1714        else
1715        {
1716            LSQ_DEBUG("lsquic_enc_session_encrypt using 'F' key...");
1717            key = enc_session->enc_ctx_f;
1718            memcpy(nonce, enc_session->enc_key_nonce_f, 4);
1719            enc_level = ENC_LEV_FORW;
1720        }
1721        path_id_packet_number = combine_path_id_pack_num(path_id, pack_num);
1722        memcpy(nonce + 4, &path_id_packet_number,
1723               sizeof(path_id_packet_number));
1724
1725        memcpy(buf_out, header, header_len);
1726        *out_len = max_out_len - header_len;
1727
1728        ret = aes_aead_enc(key, header, header_len, nonce, 12, data,
1729                           data_len, buf_out + header_len, out_len);
1730        if (ret == 0)
1731        {
1732            *out_len += header_len;
1733            return enc_level;
1734        }
1735        else
1736            return -1;
1737    }
1738}
1739
1740
1741static int
1742lsquic_enc_session_get_peer_option (const lsquic_enc_session_t *enc_session,
1743                                                                uint32_t tag)
1744{
1745    switch (tag)
1746    {
1747    case QTAG_NSTP:
1748        return !!(enc_session->hs_ctx.opts & HOPT_NSTP);
1749    case QTAG_SREJ:
1750        return !!(enc_session->hs_ctx.opts & HOPT_SREJ);
1751    default:
1752        assert(0);
1753        return 0;
1754    }
1755}
1756
1757
1758/* Query a several parameters sent by the peer that are required by
1759 * connection.
1760 */
1761static int
1762lsquic_enc_session_get_peer_setting (const lsquic_enc_session_t *enc_session,
1763                                        uint32_t tag, uint32_t *val)
1764{
1765    switch (tag)
1766    {
1767    case QTAG_TCID:
1768        if (enc_session->hs_ctx.set & HSET_TCID)
1769        {
1770            *val = enc_session->hs_ctx.tcid;
1771            return 0;
1772        }
1773        else
1774            return -1;
1775    case QTAG_SMHL:
1776        if (enc_session->hs_ctx.set & HSET_SMHL)
1777        {
1778            *val = enc_session->hs_ctx.smhl;
1779            return 0;
1780        }
1781        else
1782            return -1;
1783    case QTAG_IRTT:
1784        if (enc_session->hs_ctx.set & HSET_IRTT)
1785        {
1786            *val = enc_session->hs_ctx.irtt;
1787            return 0;
1788        }
1789        else
1790            return -1;
1791    }
1792
1793    /* XXX For the following values, there is no record which were present
1794     *     in CHLO or SHLO and which were not.  Assume that zero means that
1795     *     they weren't present.
1796     */
1797        switch (tag)
1798        {
1799        case QTAG_CFCW:
1800            if (enc_session->hs_ctx.cfcw)
1801            {
1802                *val = enc_session->hs_ctx.cfcw;
1803                return 0;
1804            }
1805            else
1806                return -1;
1807        case QTAG_SFCW:
1808            if (enc_session->hs_ctx.sfcw)
1809            {
1810                *val = enc_session->hs_ctx.sfcw;
1811                return 0;
1812            }
1813            else
1814                return -1;
1815        case QTAG_MIDS:
1816            if (enc_session->hs_ctx.mids)
1817            {
1818                *val = enc_session->hs_ctx.mids;
1819                return 0;
1820            }
1821            else
1822                return -1;
1823        default:
1824            return -1;
1825        }
1826}
1827
1828
1829#if LSQUIC_KEEP_ENC_SESS_HISTORY
1830static void
1831lsquic_get_enc_hist (const lsquic_enc_session_t *enc_session,
1832                                        char buf[(1 << ESHIST_BITS) + 1])
1833{
1834    const unsigned hist_idx = ESHIST_MASK & enc_session->es_hist_idx;
1835    if (enc_session->es_hist_buf[hist_idx] == ESHE_EMPTY)
1836        memcpy(buf, enc_session->es_hist_buf, hist_idx + 1);
1837    else
1838    {
1839        memcpy(buf, enc_session->es_hist_buf + hist_idx, sizeof(enc_session->es_hist_buf) - hist_idx);
1840        memcpy(buf + hist_idx, enc_session->es_hist_buf, hist_idx);
1841        buf[(1 << ESHIST_BITS)] = '\0';
1842    }
1843}
1844
1845
1846#endif
1847
1848
1849
1850
1851static size_t
1852lsquic_enc_session_mem_used (struct lsquic_enc_session *enc_session)
1853{
1854    size_t size;
1855
1856    size = sizeof(*enc_session);
1857
1858    size += lsquic_str_len(&enc_session->chlo);
1859    size += lsquic_str_len(&enc_session->sstk);
1860    size += lsquic_str_len(&enc_session->ssno);
1861
1862    size += lsquic_str_len(&enc_session->hs_ctx.ccs);
1863    size += lsquic_str_len(&enc_session->hs_ctx.sni);
1864    size += lsquic_str_len(&enc_session->hs_ctx.ccrt);
1865    size += lsquic_str_len(&enc_session->hs_ctx.stk);
1866    size += lsquic_str_len(&enc_session->hs_ctx.sno);
1867    size += lsquic_str_len(&enc_session->hs_ctx.prof);
1868    size += lsquic_str_len(&enc_session->hs_ctx.csct);
1869    size += lsquic_str_len(&enc_session->hs_ctx.crt);
1870
1871    if (enc_session->info)
1872    {
1873        size += sizeof(*enc_session->info);
1874        size += lsquic_str_len(&enc_session->info->sstk);
1875        size += lsquic_str_len(&enc_session->info->scfg);
1876        size += lsquic_str_len(&enc_session->info->sni_key);
1877    }
1878
1879    /* TODO: calculate memory taken up by SSL stuff */
1880
1881    return size;
1882}
1883
1884
1885static int
1886lsquic_enc_session_verify_reset_token (lsquic_enc_session_t *enc_session,
1887                                        const unsigned char *buf, size_t bufsz)
1888{
1889    if (bufsz == SRST_LENGTH
1890            && (enc_session->hs_ctx.set & HSET_SRST)
1891            && 0 == memcmp(buf, enc_session->hs_ctx.srst, SRST_LENGTH))
1892        return 0;
1893    else
1894        return -1;
1895}
1896
1897
1898static int
1899lsquic_enc_session_did_zero_rtt_succeed (const lsquic_enc_session_t *enc_session)
1900{
1901    return !(enc_session->es_flags & ES_RECV_REJ);
1902}
1903
1904
1905static int
1906lsquic_enc_session_is_zero_rtt_enabled (const lsquic_enc_session_t *enc_session)
1907{
1908    return enc_session->info && enc_session->cert_item;
1909}
1910
1911
1912static c_cert_item_t *
1913lsquic_enc_session_get_cert_item (const lsquic_enc_session_t *enc_session)
1914{
1915    return enc_session->cert_item;
1916}
1917
1918
1919static STACK_OF(X509) *
1920lsquic_enc_session_get_server_cert_chain (lsquic_enc_session_t *enc_session)
1921{
1922    const struct c_cert_item_st *item;
1923    STACK_OF(X509) *chain;
1924    X509 *cert;
1925    int i;
1926
1927    item = enc_session->cert_item;
1928    if (!item)
1929    {
1930        LSQ_WARN("could not find certificates for `%.*s'",
1931                            (int) lsquic_str_len(&enc_session->hs_ctx.sni),
1932                            lsquic_str_cstr(&enc_session->hs_ctx.sni));
1933        return NULL;
1934    }
1935
1936    chain = sk_X509_new_null();
1937    for (i = 0; i < item->count; ++i)
1938    {
1939        cert = bio_to_crt(lsquic_str_cstr(&item->crts[i]),
1940                                lsquic_str_len(&item->crts[i]), 0);
1941        if (cert)
1942            sk_X509_push(chain, cert);
1943        else
1944        {
1945            sk_X509_free(chain);
1946            return NULL;
1947        }
1948    }
1949
1950    return chain;
1951}
1952
1953
1954ssize_t
1955lsquic_enc_session_get_zero_rtt (lsquic_enc_session_t *enc_session,
1956                                                enum lsquic_version version,
1957                                                        void *buf, size_t len)
1958{
1959    int i;
1960    size_t sz = 0;
1961    if (!enc_session->info || !enc_session->cert_item)
1962    {
1963        LSQ_DEBUG("client asked for rtt_into but it is not available");
1964        return 0;
1965    }
1966    for (i = 0; i < enc_session->cert_item->count; ++i)
1967    {
1968        sz += sizeof(uint32_t);
1969        sz += lsquic_str_len(&enc_session->cert_item->crts[i]);
1970    }
1971    sz += sizeof(struct lsquic_zero_rtt_storage);
1972    if (len < sz)
1973    {
1974        LSQ_DEBUG("client provided buf is too small %zu < %zu", len, sz);
1975        errno = ENOBUFS;
1976        return -1;
1977    }
1978    lsquic_enc_session_serialize_zero_rtt((struct lsquic_zero_rtt_storage *)buf,
1979                                                    version, enc_session->info,
1980                                                    enc_session->cert_item);
1981    return sz;
1982}
1983
1984
1985#ifdef NDEBUG
1986const
1987#endif
1988struct enc_session_funcs lsquic_enc_session_gquic_1 =
1989{
1990    .esf_global_init    = lsquic_handshake_init,
1991    .esf_global_cleanup = lsquic_handshake_cleanup,
1992#if LSQUIC_KEEP_ENC_SESS_HISTORY
1993    .esf_get_hist       = lsquic_get_enc_hist,
1994#endif
1995    .esf_destroy = lsquic_enc_session_destroy,
1996    .esf_is_hsk_done = lsquic_enc_session_is_hsk_done,
1997    .esf_encrypt = lsquic_enc_session_encrypt,
1998    .esf_decrypt = lsquic_enc_session_decrypt,
1999    .esf_get_peer_setting = lsquic_enc_session_get_peer_setting,
2000    .esf_get_peer_option = lsquic_enc_session_get_peer_option,
2001    .esf_create_client = lsquic_enc_session_create_client,
2002    .esf_generate_cid = lsquic_generate_cid,
2003    .esf_gen_chlo = lsquic_enc_session_gen_chlo,
2004    .esf_handle_chlo_reply = lsquic_enc_session_handle_chlo_reply,
2005    .esf_mem_used = lsquic_enc_session_mem_used,
2006    .esf_verify_reset_token = lsquic_enc_session_verify_reset_token,
2007    .esf_did_zero_rtt_succeed = lsquic_enc_session_did_zero_rtt_succeed,
2008    .esf_is_zero_rtt_enabled = lsquic_enc_session_is_zero_rtt_enabled,
2009    .esf_get_cert_item = lsquic_enc_session_get_cert_item,
2010    .esf_get_server_cert_chain = lsquic_enc_session_get_server_cert_chain,
2011    .esf_get_zero_rtt = lsquic_enc_session_get_zero_rtt,
2012};
2013
2014
2015const char *const lsquic_enclev2str[] =
2016{
2017    [ENC_LEV_UNSET] = "unset",
2018    [ENC_LEV_CLEAR] = "clear",
2019    [ENC_LEV_INIT]  = "initial",
2020    [ENC_LEV_FORW]  = "forw-secure",
2021};
2022
2023
2024enum lsquic_version
2025lsquic_zero_rtt_version (const unsigned char *buf, size_t bufsz)
2026{
2027    lsquic_ver_tag_t tag;
2028
2029    if (bufsz >= sizeof(tag))
2030    {
2031        memcpy(&tag, buf, sizeof(tag));
2032        return lsquic_tag2ver(tag);
2033    }
2034    else
2035        return -1;
2036}
2037