lsquic_handshake.c revision a0e1aeee
1/* Copyright (c) 2017 - 2019 LiteSpeed Technologies Inc.  See LICENSE. */
2#define _GNU_SOURCE         /* for memmem */
3
4#include <netinet/in.h>
5#include <netdb.h>
6
7#include <assert.h>
8#include <errno.h>
9#include <limits.h>
10#include <time.h>
11#include <string.h>
12#include <sys/queue.h>
13#ifndef WIN32
14#include <sys/socket.h>
15#endif
16
17#include <openssl/ssl.h>
18#include <openssl/crypto.h>
19#include <openssl/stack.h>
20#include <openssl/x509.h>
21#include <openssl/rand.h>
22#include <openssl/nid.h>
23#include <openssl/bn.h>
24#include <zlib.h>
25
26#include "lsquic.h"
27#include "lsquic_types.h"
28#include "lsquic_crypto.h"
29#include "lsquic_str.h"
30#include "lsquic_enc_sess.h"
31#include "lsquic_parse.h"
32#include "lsquic_crt_compress.h"
33#include "lsquic_util.h"
34#include "lsquic_version.h"
35#include "lsquic_mm.h"
36#include "lsquic_engine_public.h"
37#include "lsquic_hash.h"
38#include "lsquic_buf.h"
39#include "lsquic_qtags.h"
40#include "lsquic_byteswap.h"
41#include "lsquic_sizes.h"
42#include "lsquic_tokgen.h"
43#include "lsquic_conn.h"
44#include "lsquic_packet_common.h"
45#include "lsquic_packet_out.h"
46#include "lsquic_packet_in.h"
47#include "lsquic_handshake.h"
48
49#include "fiu-local.h"
50
51#include "lsquic_ev_log.h"
52
53#define MIN_CHLO_SIZE 1024
54
55#define MAX_SCFG_LENGTH 512
56#define MAX_SPUBS_LENGTH 32
57
58#define LSQUIC_LOGGER_MODULE LSQLM_HANDSHAKE
59#include "lsquic_logger.h"
60
61enum handshake_state
62{
63    HSK_CHLO_REJ = 0,
64    HSK_SHLO,
65    HSK_COMPLETED,
66    N_HSK_STATES
67};
68
69#if LSQUIC_KEEP_ENC_SESS_HISTORY
70typedef unsigned char eshist_idx_t;
71
72enum enc_sess_history_event
73{
74    ESHE_EMPTY              =  '\0',
75    ESHE_SET_SNI            =  'I',
76    ESHE_SET_SNO            =  'O',
77    ESHE_SET_STK            =  'K',
78    ESHE_SET_SCID           =  'D',
79    ESHE_SET_PROF           =  'P',
80    ESHE_SET_SRST           =  'S',
81    ESHE_VSTK_OK            =  'V',
82    ESHE_VSTK_FAILED        =  'W',
83    ESHE_SNI_FAIL           =  'J',
84    ESHE_HAS_SSTK           =  'H',
85    ESHE_UNKNOWN_CONFIG     =  'a',
86    ESHE_MISSING_SCID       =  'b',
87    ESHE_EMPTY_CCRT         =  'c',
88    ESHE_MISSING_SNO        =  'd',
89    ESHE_SNO_MISMATCH       =  'e',
90    ESHE_SNO_OK             =  'f',
91    ESHE_MULTI2_2BITS       =  'i',
92    ESHE_SNI_DELAYED        =  'Y',
93};
94#endif
95
96
97typedef struct hs_ctx_st
98{
99    enum {
100        HSET_TCID     =   (1 << 0),     /* tcid is set */
101        HSET_SMHL     =   (1 << 1),     /* smhl is set */
102        HSET_SCID     =   (1 << 2),
103        HSET_IRTT     =   (1 << 3),
104        HSET_SRST     =   (1 << 4),
105    }           set;
106    enum {
107        HOPT_NSTP     =   (1 << 0),     /* NSTP option present in COPT */
108        HOPT_SREJ     =   (1 << 1),     /* SREJ option present in COPT */
109    }           opts;
110    uint32_t    pdmd;
111    uint32_t    aead;
112    uint32_t    kexs;
113
114    uint32_t    mids;
115    uint32_t    scls;
116    uint32_t    cfcw;
117    uint32_t    sfcw;
118    uint32_t    smids;
119    uint32_t    scfcw;
120    uint32_t    ssfcw;
121    uint32_t    icsl;
122
123    uint32_t    irtt;
124    uint64_t    rcid;
125    uint32_t    tcid;
126    uint32_t    smhl;
127    uint64_t    sttl;
128    unsigned char scid[SCID_LENGTH];
129    //unsigned char chlo_hash[32]; //SHA256 HASH of CHLO
130    unsigned char nonc[DNONC_LENGTH]; /* 4 tm, 8 orbit ---> REJ, 20 rand */
131    unsigned char  pubs[32];
132    unsigned char srst[SRST_LENGTH];
133
134    uint32_t    rrej;
135    struct lsquic_str ccs;
136    struct lsquic_str uaid;
137    struct lsquic_str sni;   /* 0 rtt */
138    struct lsquic_str ccrt;
139    struct lsquic_str stk;
140    struct lsquic_str sno;
141    struct lsquic_str prof;
142
143    struct lsquic_str csct;
144    struct lsquic_str crt; /* compressed certs buffer */
145    struct lsquic_str scfg_pubs; /* Need to copy PUBS, as KEXS comes after it */
146} hs_ctx_t;
147
148
149/* client side need to store 0rtt info per STK */
150typedef struct lsquic_session_cache_info_st
151{
152    unsigned char   sscid[SCID_LENGTH];
153    unsigned char   spubs[32];  /* server pub key for next time 0rtt */
154    uint32_t    ver;  /* one VERSION */
155    uint32_t    aead;
156    uint32_t    kexs;
157    uint32_t    pdmd;
158    uint64_t    orbt;
159    uint64_t    expy;
160    int         scfg_flag; /* 0, no-init, 1, no parse, 2, parsed */
161    struct lsquic_str    sstk;
162    struct lsquic_str    scfg;
163    struct lsquic_str    sni_key;   /* This is only used as key */
164    struct lsquic_hash_elem hash_el;
165
166} lsquic_session_cache_info_t;
167
168
169/* client */
170typedef struct c_cert_item_st
171{
172    struct lsquic_str*  crts;
173    struct lsquic_str*  hashs;
174    int                 count;
175} c_cert_item_t;
176
177
178struct lsquic_zero_rtt_storage
179{
180    uint32_t    quic_version_tag;
181    uint32_t    serializer_version;
182    uint32_t    ver;
183    uint32_t    aead;
184    uint32_t    kexs;
185    uint32_t    pdmd;
186    uint64_t    orbt;
187    uint64_t    expy;
188    uint64_t    sstk_len;
189    uint64_t    scfg_len;
190    uint64_t    scfg_flag;
191    uint8_t     sstk[STK_LENGTH];
192    uint8_t     scfg[MAX_SCFG_LENGTH];
193    uint8_t     sscid[SCID_LENGTH];
194    uint8_t     spubs[MAX_SPUBS_LENGTH];
195    uint32_t    cert_count;
196};
197
198
199
200
201struct lsquic_enc_session
202{
203    enum handshake_state hsk_state;
204    enum {
205        ES_SERVER =     1 << 0,
206        ES_RECV_REJ =   1 << 1,
207        ES_RECV_SREJ =  1 << 2,
208        ES_FREE_CERT_PTR = 1 << 3,
209    }                    es_flags;
210
211    uint8_t have_key; /* 0, no 1, I, 2, D, 3, F */
212    uint8_t peer_have_final_key;
213    uint8_t server_start_use_final_key;
214
215    lsquic_cid_t cid;
216    unsigned char priv_key[32];
217    EVP_AEAD_CTX *enc_ctx_i;
218    EVP_AEAD_CTX *dec_ctx_i;
219
220    /* Have to save the initial key for diversification need */
221    unsigned char enc_key_i[aes128_key_len];
222    unsigned char dec_key_i[aes128_key_len];
223    unsigned char enc_key_nonce_i[aes128_iv_len];
224    unsigned char dec_key_nonce_i[aes128_iv_len];
225
226    EVP_AEAD_CTX *enc_ctx_f;
227    EVP_AEAD_CTX *dec_ctx_f;
228    unsigned char enc_key_nonce_f[aes128_iv_len];
229    unsigned char dec_key_nonce_f[aes128_iv_len];
230
231    hs_ctx_t hs_ctx;
232    lsquic_session_cache_info_t *info;
233    c_cert_item_t *cert_item;
234    lsquic_server_config_t *server_config;
235    SSL_CTX *  ssl_ctx;
236    const struct lsquic_engine_public *enpub;
237    struct lsquic_str * cert_ptr; /* pointer to the leaf cert of the server, not real copy */
238    struct lsquic_str   chlo; /* real copy of CHLO message */
239    struct lsquic_str   sstk;
240    struct lsquic_str   ssno;
241
242#if LSQUIC_KEEP_ENC_SESS_HISTORY
243    eshist_idx_t        es_hist_idx;
244    unsigned char       es_hist_buf[1 << ESHIST_BITS];
245#endif
246};
247
248
249
250/* server side */
251typedef struct compress_cert_hash_item_st
252{
253    struct lsquic_str*   domain; /*with port, such as "xyz.com:8088" as the key */
254    struct lsquic_str*   crts_compress_buf;
255    struct lsquic_hash_elem hash_el;
256
257} compress_cert_hash_item_t;
258
259/**
260 * server side, just for performance, will save the compressed certs buffer
261 */
262static struct lsquic_hash *s_compressed_server_certs;
263
264/***
265 * Server side, it will store thr domain/cert [only the leaf cert]
266 */
267static struct lsquic_hash *s_server_certs;
268
269/**
270 * server side, will save one copy of s_server_scfg, it will update once a day
271 * This global pointer is point to the value in the hashtable
272 * Better to be put in ShM
273 */
274static lsquic_server_config_t s_server_config;
275
276/* server side, only one cert */
277typedef struct cert_item_st
278{
279    struct lsquic_str*      crt;
280    struct lsquic_hash_elem hash_el;
281    unsigned char           key[0];
282} cert_item_t;
283
284/* server */
285static cert_item_t* s_find_cert(const unsigned char *, size_t);
286static void s_free_cert_hash_item(cert_item_t *item);
287static cert_item_t* s_insert_cert(const unsigned char *key, size_t key_sz,
288                                                const struct lsquic_str *crt);
289
290static compress_cert_hash_item_t* find_compress_certs(struct lsquic_str *domain);
291static compress_cert_hash_item_t *make_compress_cert_hash_item(struct lsquic_str *domain, struct lsquic_str *crts_compress_buf);
292
293#ifdef NDEBUG
294static
295enum hsk_failure_reason
296verify_stk (enc_session_t *,
297               const struct sockaddr *ip_addr, uint64_t tm, lsquic_str_t *stk);
298static
299void gen_stk(lsquic_server_config_t *, const struct sockaddr *, uint64_t tm,
300             unsigned char stk_out[STK_LENGTH]);
301#endif
302
303/* client */
304static c_cert_item_t *make_c_cert_item(struct lsquic_str **certs, int count);
305static void free_c_cert_item(c_cert_item_t *item);
306
307static int get_tag_val_u32 (unsigned char *v, int len, uint32_t *val);
308static int init_hs_hash_tables(int flags);
309static uint32_t get_tag_value_i32(unsigned char *, int);
310static uint64_t get_tag_value_i64(unsigned char *, int);
311
312static void determine_keys(struct lsquic_enc_session *enc_session, int is_client);
313
314
315#if LSQUIC_KEEP_ENC_SESS_HISTORY
316static void
317eshist_append (struct lsquic_enc_session *enc_session,
318                                        enum enc_sess_history_event eh_event)
319{
320    enc_session->es_hist_buf[
321                    ESHIST_MASK & enc_session->es_hist_idx++ ] = eh_event;
322}
323
324
325#   define ESHIST_APPEND(sess, event) eshist_append(sess, event)
326#else
327#   define ESHIST_APPEND(sess, event) do { } while (0)
328#endif
329
330static int
331lsquic_handshake_init(int flags)
332{
333    crypto_init();
334    return init_hs_hash_tables(flags);
335}
336
337
338static void
339cleanup_hs_hash_tables (void)
340{
341    struct lsquic_hash_elem *el;
342    if (s_compressed_server_certs)
343    {
344        for (el = lsquic_hash_first(s_compressed_server_certs); el;
345                        el = lsquic_hash_next(s_compressed_server_certs))
346        {
347            compress_cert_hash_item_t *item = lsquic_hashelem_getdata(el);
348            lsquic_str_delete(item->domain);
349            lsquic_str_delete(item->crts_compress_buf);
350            free(item);
351        }
352        lsquic_hash_destroy(s_compressed_server_certs);
353        s_compressed_server_certs = NULL;
354    }
355
356    if (s_server_certs)
357    {
358        for (el = lsquic_hash_first(s_server_certs); el;
359                                    el = lsquic_hash_next(s_server_certs))
360        {
361            s_free_cert_hash_item( lsquic_hashelem_getdata(el) );
362        }
363        lsquic_hash_destroy(s_server_certs);
364        s_server_certs = NULL;
365    }
366}
367
368
369static void
370lsquic_handshake_cleanup (void)
371{
372    cleanup_hs_hash_tables();
373    lsquic_crt_cleanup();
374}
375
376
377/* return -1 for fail, 0 OK*/
378static int init_hs_hash_tables(int flags)
379{
380    if (flags & LSQUIC_GLOBAL_SERVER)
381    {
382        s_compressed_server_certs = lsquic_hash_create();
383        if (!s_compressed_server_certs)
384            return -1;
385
386        s_server_certs = lsquic_hash_create();
387        if (!s_server_certs)
388            return -1;
389    }
390
391    return 0;
392}
393
394
395/* server */
396static cert_item_t *
397s_find_cert (const unsigned char *key, size_t key_sz)
398{
399    struct lsquic_hash_elem *el;
400
401    if (!s_server_certs)
402        return NULL;
403
404    el = lsquic_hash_find(s_server_certs, key, key_sz);
405    if (el == NULL)
406        return NULL;
407
408    return lsquic_hashelem_getdata(el);
409}
410
411
412/* client */
413static c_cert_item_t *
414make_c_cert_item (lsquic_str_t **certs, int count)
415{
416    int i;
417    uint64_t hash;
418    c_cert_item_t *item = calloc(1, sizeof(*item));
419    item->crts = (lsquic_str_t *)malloc(count * sizeof(lsquic_str_t));
420    item->hashs = lsquic_str_new(NULL, 0);
421    item->count = count;
422    for (i = 0; i < count; ++i)
423    {
424        lsquic_str_copy(&item->crts[i], certs[i]);
425        hash = fnv1a_64((const uint8_t *)lsquic_str_cstr(certs[i]),
426                        lsquic_str_len(certs[i]));
427        lsquic_str_append(item->hashs, (char *)&hash, 8);
428    }
429    return item;
430}
431
432
433/* client */
434static void
435free_c_cert_item (c_cert_item_t *item)
436{
437    int i;
438    if (item)
439    {
440        lsquic_str_delete(item->hashs);
441        for(i=0; i<item->count; ++i)
442            lsquic_str_d(&item->crts[i]);
443        free(item->crts);
444        free(item);
445    }
446}
447
448
449/* server */
450static void
451s_free_cert_hash_item (cert_item_t *item)
452{
453    if (item)
454    {
455        lsquic_str_delete(item->crt);
456        free(item);
457    }
458}
459
460
461/* server */
462static cert_item_t *
463s_insert_cert (const unsigned char *key, size_t key_sz, const lsquic_str_t *crt)
464{
465    struct lsquic_hash_elem *el;
466    lsquic_str_t *crt_copy;
467    cert_item_t *item;
468
469    crt_copy = lsquic_str_new(lsquic_str_cstr(crt), lsquic_str_len(crt));
470    if (!crt_copy)
471        return NULL;
472
473    item = calloc(1, sizeof(*item) + key_sz);
474    if (!item)
475    {
476        lsquic_str_delete(crt_copy);
477        return NULL;
478    }
479
480    item->crt = crt_copy;
481    memcpy(item->key, key, key_sz);
482    el = lsquic_hash_insert(s_server_certs, item->key, key_sz,
483                                                        item, &item->hash_el);
484    if (el)
485        return lsquic_hashelem_getdata(el);
486    else
487    {
488        s_free_cert_hash_item(item);
489        return NULL;
490    }
491}
492
493
494/* server */
495static compress_cert_hash_item_t *
496find_compress_certs(lsquic_str_t *domain)
497{
498    struct lsquic_hash_elem *el;
499
500    if (!s_compressed_server_certs)
501        return NULL;
502
503    el = lsquic_hash_find(s_compressed_server_certs, lsquic_str_cstr(domain),
504                                                    lsquic_str_len(domain));
505    if (el == NULL)
506        return NULL;
507
508    return lsquic_hashelem_getdata(el);
509}
510
511
512/* server */
513static compress_cert_hash_item_t *
514make_compress_cert_hash_item(lsquic_str_t *domain, lsquic_str_t *crts_compress_buf)
515{
516    compress_cert_hash_item_t *item = calloc(1, sizeof(*item));
517    item->crts_compress_buf = lsquic_str_new(NULL, 0);
518    item->domain = lsquic_str_new(NULL, 0);
519    lsquic_str_copy(item->domain, domain);
520    lsquic_str_copy(item->crts_compress_buf, crts_compress_buf);
521    return item;
522}
523
524
525/* server */
526#if __GNUC__
527__attribute__((unused))        /* XXX why? */
528#endif
529static void
530free_compress_cert_hash_item(compress_cert_hash_item_t *item)
531{
532    if (item)
533    {
534        lsquic_str_delete(item->crts_compress_buf);
535        lsquic_str_delete(item->domain);
536        free(item);
537    }
538}
539
540
541/* server */
542static int insert_compress_certs(compress_cert_hash_item_t *item)
543{
544    if (lsquic_hash_insert(s_compressed_server_certs,
545            lsquic_str_cstr(item->domain),
546                lsquic_str_len(item->domain), item, &item->hash_el) == NULL)
547    {
548        return -1;
549    }
550    else
551        return 0;
552}
553
554
555enum rtt_deserialize_return_type
556{
557    RTT_DESERIALIZE_OK              = 0,
558    RTT_DESERIALIZE_BAD_QUIC_VER    = 1,
559    RTT_DESERIALIZE_BAD_SERIAL_VER  = 2,
560    RTT_DESERIALIZE_BAD_CERT_SIZE   = 3,
561};
562
563#define RTT_SERIALIZER_VERSION  (1 << 0)
564
565static void
566lsquic_enc_session_serialize_zero_rtt(struct lsquic_zero_rtt_storage *storage,
567                                        enum lsquic_version version,
568                                        const lsquic_session_cache_info_t *info,
569                                                const c_cert_item_t *cert_item)
570{
571    uint32_t i;
572    uint32_t *cert_len;
573    uint8_t *cert_data;
574    /*
575     * assign versions
576     */
577    storage->quic_version_tag = lsquic_ver2tag(version);
578    storage->serializer_version = RTT_SERIALIZER_VERSION;
579    /*
580     * server config
581     */
582    storage->ver = info->ver;
583    storage->aead = info->aead;
584    storage->kexs = info->kexs;
585    storage->pdmd = info->pdmd;
586    storage->orbt = info->orbt;
587    storage->expy = info->expy;
588    storage->sstk_len = lsquic_str_len(&info->sstk);
589    storage->scfg_len = lsquic_str_len(&info->scfg);
590    storage->scfg_flag = info->scfg_flag;
591    memcpy(storage->sstk, lsquic_str_buf(&info->sstk), storage->sstk_len);
592    memcpy(storage->scfg, lsquic_str_buf(&info->scfg), storage->scfg_len);
593    memcpy(storage->sscid, &info->sscid, SCID_LENGTH);
594    memcpy(storage->spubs, &info->spubs, MAX_SPUBS_LENGTH);
595    /*
596     * certificate chain
597     */
598    storage->cert_count = (uint32_t)cert_item->count;
599    cert_len = (uint32_t *)(storage + 1);
600    cert_data = (uint8_t *)(cert_len + 1);
601    for (i = 0; i < storage->cert_count; i++)
602    {
603        *cert_len = lsquic_str_len(&cert_item->crts[i]);
604        memcpy(cert_data, lsquic_str_buf(&cert_item->crts[i]), *cert_len);
605        cert_len = (uint32_t *)(cert_data + *cert_len);
606        cert_data = (uint8_t *)(cert_len + 1);
607    }
608}
609
610
611#define CHECK_SPACE(need, start, end) \
612    do { if ((intptr_t) (need) > ((intptr_t) (end) - (intptr_t) (start))) \
613        { return RTT_DESERIALIZE_BAD_CERT_SIZE; } \
614    } while (0) \
615
616static enum rtt_deserialize_return_type
617lsquic_enc_session_deserialize_zero_rtt(
618                                const struct lsquic_zero_rtt_storage *storage,
619                                                        size_t storage_size,
620                                const struct lsquic_engine_settings *settings,
621                                            lsquic_session_cache_info_t *info,
622                                                    c_cert_item_t *cert_item)
623{
624    enum lsquic_version ver;
625    uint32_t i, len;
626    uint64_t hash;
627    uint32_t *cert_len;
628    uint8_t *cert_data;
629    void *storage_end = (uint8_t *)storage + storage_size;
630    /*
631     * check versions
632     */
633    ver = lsquic_tag2ver(storage->quic_version_tag);
634    if ((int)ver == -1 || !((1 << ver) & settings->es_versions))
635        return RTT_DESERIALIZE_BAD_QUIC_VER;
636    if (storage->serializer_version != RTT_SERIALIZER_VERSION)
637        return RTT_DESERIALIZE_BAD_SERIAL_VER;
638    /*
639     * server config
640     */
641    info->ver = storage->ver;
642    info->aead = storage->aead;
643    info->kexs = storage->kexs;
644    info->pdmd = storage->pdmd;
645    info->orbt = storage->orbt;
646    info->expy = storage->expy;
647    info->scfg_flag = storage->scfg_flag;
648    lsquic_str_setto(&info->sstk, storage->sstk, storage->sstk_len);
649    lsquic_str_setto(&info->scfg, storage->scfg, storage->scfg_len);
650    memcpy(&info->sscid, storage->sscid, SCID_LENGTH);
651    memcpy(&info->spubs, storage->spubs, MAX_SPUBS_LENGTH);
652    /*
653     * certificate chain
654     */
655    cert_item->count = storage->cert_count;
656    cert_item->crts = malloc(cert_item->count * sizeof(lsquic_str_t));
657    cert_item->hashs = lsquic_str_new(NULL, 0);
658    cert_len = (uint32_t *)(storage + 1);
659    for (i = 0; i < storage->cert_count; i++)
660    {
661        CHECK_SPACE(sizeof(uint32_t), cert_len, storage_end);
662        cert_data = (uint8_t *)(cert_len + 1);
663        memcpy(&len, cert_len, sizeof(len));
664        CHECK_SPACE(len, cert_data, storage_end);
665        lsquic_str_prealloc(&cert_item->crts[i], len);
666        lsquic_str_setlen(&cert_item->crts[i], len);
667        memcpy(lsquic_str_buf(&cert_item->crts[i]), cert_data, len);
668        hash = fnv1a_64((const uint8_t *)cert_data, len);
669        lsquic_str_append(cert_item->hashs, (char *)&hash, 8);
670        cert_len = (uint32_t *)(cert_data + len);
671    }
672    return RTT_DESERIALIZE_OK;
673}
674
675
676static enc_session_t *
677lsquic_enc_session_create_client (const char *domain, lsquic_cid_t cid,
678                                    const struct lsquic_engine_public *enpub,
679                                    const unsigned char *zero_rtt, size_t zero_rtt_len)
680{
681    lsquic_session_cache_info_t *info;
682    struct lsquic_enc_session *enc_session;
683    c_cert_item_t *item;
684    const struct lsquic_zero_rtt_storage *zero_rtt_storage;
685
686    if (!domain)
687    {
688        errno = EINVAL;
689        return NULL;
690    }
691
692    enc_session = calloc(1, sizeof(*enc_session));
693    if (!enc_session)
694        return NULL;
695
696    /* have to allocate every time */
697    info = calloc(1, sizeof(*info));
698    if (!info)
699    {
700        free(enc_session);
701        return NULL;
702    }
703
704    if (zero_rtt && zero_rtt_len > sizeof(struct lsquic_zero_rtt_storage))
705    {
706        item = calloc(1, sizeof(*item));
707        if (!item)
708        {
709            free(enc_session);
710            free(info);
711            return NULL;
712        }
713        zero_rtt_storage = (const struct lsquic_zero_rtt_storage *)zero_rtt;
714        switch (lsquic_enc_session_deserialize_zero_rtt(zero_rtt_storage,
715                                                        zero_rtt_len,
716                                                        &enpub->enp_settings,
717                                                        info, item))
718        {
719            case RTT_DESERIALIZE_BAD_QUIC_VER:
720                LSQ_ERROR("provided zero_rtt has unsupported QUIC version");
721                free(item);
722                break;
723            case RTT_DESERIALIZE_BAD_SERIAL_VER:
724                LSQ_ERROR("provided zero_rtt has bad serializer version");
725                free(item);
726                break;
727            case RTT_DESERIALIZE_BAD_CERT_SIZE:
728                LSQ_ERROR("provided zero_rtt has bad cert size");
729                free(item);
730                break;
731            case RTT_DESERIALIZE_OK:
732                memcpy(enc_session->hs_ctx.pubs, info->spubs, 32);
733                enc_session->cert_item = item;
734                break;
735        }
736    }
737    enc_session->enpub = enpub;
738    enc_session->cid   = cid;
739    enc_session->info  = info;
740    /* FIXME: allocation may fail */
741    lsquic_str_append(&enc_session->hs_ctx.sni, domain, strlen(domain));
742    return enc_session;
743}
744
745
746/* Server side: Session_cache_entry can be saved for 0rtt */
747static enc_session_t *
748lsquic_enc_session_create_server (lsquic_cid_t cid,
749                        const struct lsquic_engine_public *enpub)
750{
751    fiu_return_on("handshake/new_enc_session", NULL);
752
753    struct lsquic_enc_session *enc_session;
754
755    enc_session = calloc(1, sizeof(*enc_session));
756    if (!enc_session)
757        return NULL;
758
759    enc_session->enpub = enpub;
760    enc_session->cid = cid;
761    enc_session->es_flags |= ES_SERVER;
762    return enc_session;
763}
764
765
766static void
767lsquic_enc_session_reset_cid (enc_session_t *enc_session_p,
768                                        const lsquic_cid_t *new_cid)
769{
770    struct lsquic_enc_session *const enc_session = enc_session_p;
771
772    LSQ_INFOC("changing CID to %"CID_FMT, CID_BITS(new_cid));
773    enc_session->cid = *new_cid;
774}
775
776
777static void
778lsquic_enc_session_destroy (enc_session_t *enc_session_p)
779{
780    struct lsquic_enc_session *const enc_session = enc_session_p;
781    if (!enc_session)
782        return ;
783
784    hs_ctx_t *hs_ctx = &enc_session->hs_ctx;
785
786    lsquic_str_d(&hs_ctx->sni);
787    lsquic_str_d(&hs_ctx->ccs);
788    lsquic_str_d(&hs_ctx->ccrt);
789    lsquic_str_d(&hs_ctx->stk);
790    lsquic_str_d(&hs_ctx->sno);
791    lsquic_str_d(&hs_ctx->prof);
792    lsquic_str_d(&hs_ctx->csct);
793    lsquic_str_d(&hs_ctx->crt);
794    lsquic_str_d(&hs_ctx->uaid);
795    lsquic_str_d(&hs_ctx->scfg_pubs);
796    lsquic_str_d(&enc_session->chlo);
797    lsquic_str_d(&enc_session->sstk);
798    lsquic_str_d(&enc_session->ssno);
799    if (enc_session->dec_ctx_i)
800    {
801        EVP_AEAD_CTX_cleanup(enc_session->dec_ctx_i);
802        free(enc_session->dec_ctx_i);
803    }
804    if (enc_session->enc_ctx_i)
805    {
806        EVP_AEAD_CTX_cleanup(enc_session->enc_ctx_i);
807        free(enc_session->enc_ctx_i);
808    }
809    if (enc_session->dec_ctx_f)
810    {
811        EVP_AEAD_CTX_cleanup(enc_session->dec_ctx_f);
812        free(enc_session->dec_ctx_f);
813    }
814    if (enc_session->enc_ctx_f)
815    {
816        EVP_AEAD_CTX_cleanup(enc_session->enc_ctx_f);
817        free(enc_session->enc_ctx_f);
818    }
819    if (enc_session->info)
820    {
821        lsquic_str_d(&enc_session->info->sstk);
822        lsquic_str_d(&enc_session->info->scfg);
823        lsquic_str_d(&enc_session->info->sni_key);
824        free(enc_session->info);
825    }
826    if (enc_session->cert_item)
827    {
828        free_c_cert_item(enc_session->cert_item);
829        enc_session->cert_item = NULL;
830    }
831    if ((enc_session->es_flags & ES_FREE_CERT_PTR) && enc_session->cert_ptr)
832        lsquic_str_delete(enc_session->cert_ptr);
833    free(enc_session);
834
835}
836
837
838static int get_hs_state(struct lsquic_enc_session *enc_session)
839{
840    return enc_session->hsk_state;
841}
842
843
844/* make sure have more room for encrypt */
845static int
846lsquic_enc_session_is_hsk_done (enc_session_t *enc_session_p)
847{
848    struct lsquic_enc_session *const enc_session = enc_session_p;
849    return (get_hs_state(enc_session) == HSK_COMPLETED);
850}
851
852
853static void
854process_copt (struct lsquic_enc_session *enc_session, const uint32_t *const opts,
855                unsigned n_opts)
856{
857    unsigned i;
858    for (i = 0; i < n_opts; ++i)
859        switch (opts[i])
860        {
861        case QTAG_NSTP:
862            enc_session->hs_ctx.opts |= HOPT_NSTP;
863            break;
864        case QTAG_SREJ:
865            enc_session->hs_ctx.opts |= HOPT_SREJ;
866            break;
867        }
868}
869
870
871static int parse_hs_data (struct lsquic_enc_session *enc_session, uint32_t tag,
872                          unsigned char *val, int len, uint32_t head_tag)
873{
874    hs_ctx_t * hs_ctx = &enc_session->hs_ctx;
875    int is_client = (head_tag != QTAG_CHLO);
876
877    switch(tag)
878    {
879    case QTAG_PDMD:
880        hs_ctx->pdmd = get_tag_value_i32(val, len);
881        break;
882
883    case QTAG_MIDS:
884        if (0 != get_tag_val_u32(val, len,
885                    (is_client ? &hs_ctx->mids : &hs_ctx->smids)))
886            return -1;
887        break;
888
889    case QTAG_SCLS:
890        hs_ctx->scls = get_tag_value_i32(val, len);
891        break;
892
893    case QTAG_CFCW:
894        if (0 != get_tag_val_u32(val, len, (is_client ? &hs_ctx->cfcw : &hs_ctx->scfcw)))
895            return -1;
896        break;
897
898    case QTAG_SFCW:
899        if (0 != get_tag_val_u32(val, len, (is_client ? &hs_ctx->sfcw : &hs_ctx->ssfcw)))
900            return -1;
901        break;
902
903    case QTAG_ICSL:
904        hs_ctx->icsl = get_tag_value_i32(val, len);
905        break;
906
907    case QTAG_IRTT:
908        if (0 != get_tag_val_u32(val, len, &hs_ctx->irtt))
909            return -1;
910        hs_ctx->set |= HSET_IRTT;
911        break;
912
913    case QTAG_COPT:
914        if (0 == len % sizeof(uint32_t))
915            process_copt(enc_session, (uint32_t *) val, len / sizeof(uint32_t));
916        /* else ignore, following the reference implementation */
917        break;
918
919    case QTAG_SNI:
920        lsquic_str_setto(&hs_ctx->sni, val, len);
921        ESHIST_APPEND(enc_session, ESHE_SET_SNI);
922        break;
923
924    case QTAG_CCS:
925        lsquic_str_setto(&hs_ctx->ccs, val, len);
926        break;
927
928    case QTAG_CCRT:
929        lsquic_str_setto(&hs_ctx->ccrt, val, len);
930        break;
931
932    case QTAG_CRT:
933        lsquic_str_setto(&hs_ctx->crt, val, len);
934        break;
935
936    case QTAG_PUBS:
937        if (head_tag == QTAG_SCFG)
938            lsquic_str_setto(&hs_ctx->scfg_pubs, val, len);
939        else if (len == 32)
940            memcpy(hs_ctx->pubs, val, len);
941        break;
942
943    case QTAG_RCID:
944        hs_ctx->rcid = get_tag_value_i64(val, len);
945        break;
946
947    case QTAG_UAID:
948        lsquic_str_setto(&hs_ctx->uaid, val, len);
949        break;
950
951    case QTAG_SMHL:
952        if (0 != get_tag_val_u32(val, len, &hs_ctx->smhl))
953            return -1;
954        hs_ctx->set |= HSET_SMHL;
955        break;
956
957    case QTAG_TCID:
958        if (0 != get_tag_val_u32(val, len, &hs_ctx->tcid))
959            return -1;
960        hs_ctx->set |= HSET_TCID;
961        break;
962
963    case QTAG_EXPY:
964        enc_session->info->expy = get_tag_value_i64(val, len);
965        break;
966
967    case QTAG_ORBT:
968        enc_session->info->orbt = get_tag_value_i64(val, len);
969        break;
970
971    case QTAG_SNO:
972        if (is_client)
973        {
974            lsquic_str_setto(&enc_session->ssno, val, len);
975        }
976        else
977        {
978            /* Server side save a copy of SNO just for verify */
979            lsquic_str_setto(&hs_ctx->sno, val, len);
980        }
981        ESHIST_APPEND(enc_session, ESHE_SET_SNO);
982        break;
983
984    case QTAG_STK:
985        if (is_client)
986        {
987            lsquic_str_setto(&enc_session->info->sstk, val, len);
988        }
989        else
990        {
991            /* Server need to save a copy to verify */
992            lsquic_str_setto(&hs_ctx->stk, val, len);
993        }
994        ESHIST_APPEND(enc_session, ESHE_SET_STK);
995        break;
996
997    case QTAG_SCID:
998        if (len != SCID_LENGTH)
999            return -1;
1000        if (is_client)
1001        {
1002            memcpy(enc_session->info->sscid, val, len);
1003        }
1004        else
1005        {
1006            memcpy(hs_ctx->scid, val, len);
1007            hs_ctx->set |= HSET_SCID;
1008        }
1009        ESHIST_APPEND(enc_session, ESHE_SET_SCID);
1010        break;
1011
1012    case QTAG_AEAD:
1013        if (is_client)
1014            enc_session->info->aead = get_tag_value_i32(val, len);
1015        else
1016            hs_ctx->aead = get_tag_value_i32(val, len);
1017        break;
1018
1019    case QTAG_KEXS:
1020        if (is_client)
1021        {
1022            if (head_tag == QTAG_SCFG && 0 == len % 4)
1023            {
1024                const unsigned char *p, *end;
1025                unsigned pub_idx, idx;
1026#ifdef WIN32
1027                pub_idx = 0;
1028#endif
1029
1030                for (p = val; p < val + len; p += 4)
1031                    if (0 == memcmp(p, "C255", 4))
1032                    {
1033                        memcpy(&enc_session->info->kexs, p, 4);
1034                        pub_idx = (p - val) / 4;
1035                        LSQ_DEBUG("Parsing SCFG: supported KEXS C255 at "
1036                                                        "index %u", pub_idx);
1037                        break;
1038                    }
1039                if (p >= val + len)
1040                {
1041                    LSQ_INFO("supported KEXS not found, trouble ahead");
1042                    break;
1043                }
1044                if (lsquic_str_len(&hs_ctx->scfg_pubs) > 0)
1045                {
1046                    p = (const unsigned char *)
1047                                        lsquic_str_cstr(&hs_ctx->scfg_pubs);
1048                    end = p + lsquic_str_len(&hs_ctx->scfg_pubs);
1049
1050                    for (idx = 0; p < end; ++idx)
1051                    {
1052                        uint32_t sz = 0;
1053                        if (p + 3 > end)
1054                            break;
1055                        sz |= *p++;
1056                        sz |= *p++ << 8;
1057                        sz |= *p++ << 16;
1058                        if (p + sz > end)
1059                            break;
1060                        if (idx == pub_idx)
1061                        {
1062                            if (sz == 32)
1063                            {
1064                                memcpy(hs_ctx->pubs, p, 32);
1065                                memcpy(enc_session->info->spubs, p, 32);
1066                            }
1067                            break;
1068                        }
1069                        p += sz;
1070                    }
1071                }
1072                else
1073                    LSQ_INFO("No PUBS from SCFG to parse");
1074            }
1075        }
1076        else
1077            hs_ctx->kexs = get_tag_value_i32(val, len);
1078        break;
1079
1080    case QTAG_NONC:
1081        if (len != sizeof(hs_ctx->nonc))
1082            return -1;
1083        memcpy(hs_ctx->nonc, val, len);
1084        break;
1085
1086    case QTAG_SCFG:
1087        if (is_client)
1088        {
1089            lsquic_str_setto(&enc_session->info->scfg, val, len);
1090            enc_session->info->scfg_flag = 1;
1091        }
1092        else
1093            LSQ_INFO("unexpected SCFG");
1094        break;
1095
1096    case QTAG_PROF:
1097        lsquic_str_setto(&hs_ctx->prof, val, len);
1098        ESHIST_APPEND(enc_session, ESHE_SET_PROF);
1099        break;
1100
1101    case QTAG_STTL:
1102        hs_ctx->sttl = get_tag_value_i64(val, len);
1103        break;
1104
1105    case QTAG_SRST:
1106        if (enc_session->es_flags & ES_SERVER)
1107            break;
1108        if (len != sizeof(hs_ctx->srst))
1109        {
1110            LSQ_INFO("Unexpected size of SRST: %u instead of %zu bytes",
1111                len, sizeof(hs_ctx->srst));
1112            return -1;
1113        }
1114        memcpy(hs_ctx->srst, val, len);
1115        hs_ctx->set |= HSET_SRST;
1116        ESHIST_APPEND(enc_session, ESHE_SET_SRST);
1117        break;
1118
1119    default:
1120        LSQ_DEBUG("Ignored tag '%.*s'", 4, (char *)&tag);
1121        break;
1122    }
1123
1124    return 0;
1125}
1126
1127
1128/* only for the hs stream-frame data, NOT with the packet header or frame header*/
1129static enum handshake_error parse_hs (struct lsquic_enc_session *enc_session,
1130                                      const unsigned char *buf, int buf_len,
1131                                      uint32_t *head_tag)
1132{
1133    uint16_t i;
1134    const unsigned char *p = buf;
1135    const unsigned char *pend = buf + buf_len;
1136
1137    unsigned char *data;
1138    uint32_t len = 0, offset = 0;
1139    uint16_t num;
1140    uint32_t tag;
1141    if (buf_len < 6)
1142        return DATA_FORMAT_ERROR;
1143
1144    memcpy(&tag, p, 4);
1145    p += 4;
1146
1147    if (enc_session->es_flags & ES_SERVER)
1148    {   /* Server only expects to receive CHLO messages from the client */
1149        if (tag != QTAG_CHLO)
1150            return DATA_FORMAT_ERROR;
1151    }
1152    else
1153    {
1154        if (tag != QTAG_SREJ && tag != QTAG_REJ && tag != QTAG_SHLO &&
1155                                                        tag != QTAG_SCFG)
1156            return DATA_FORMAT_ERROR;
1157    }
1158
1159    *head_tag = tag;
1160
1161    memcpy((char *)&num, p, 2);
1162    p += 2 + 2;  /* the 2 bytes padding 0x0000 need to be bypassed */
1163
1164    if (num < 1)
1165        return DATA_FORMAT_ERROR;
1166
1167    data = (uint8_t *)(buf + 4 * 2 * (1 + num));
1168    if ((const char *)data > (const char *)pend)
1169    {
1170        LSQ_DEBUG("parse_hs tag '%.*s' error: data not enough", 4, (char *)head_tag);
1171        return DATA_NOT_ENOUGH;
1172    }
1173
1174    /* check last offset */
1175    memcpy((char *)&len, data - 4, 4);
1176    if ((const char *)data + len > (const char *)pend)
1177    {
1178        LSQ_DEBUG("parse_hs tag '%.*s' error: data not enough!!!", 4, (char *)head_tag);
1179        return DATA_NOT_ENOUGH;
1180    }
1181
1182    for (i=0; i<num; ++i)
1183    {
1184        memcpy((char *)&tag, p, 4);
1185        p += 4;
1186        memcpy((char *)&len, p, 4);
1187        len -= offset;
1188        p += 4;
1189
1190        if ((const char *)data + offset + len > (const char *)pend)
1191            return DATA_FORMAT_ERROR;
1192
1193        if (0 != parse_hs_data(enc_session, tag, data + offset, len,
1194                                                                *head_tag))
1195            return DATA_FORMAT_ERROR;
1196        offset += len;
1197    }
1198
1199    LSQ_DEBUG("parse_hs tag '%.*s' no error.", 4, (char *)head_tag);
1200    return DATA_NO_ERROR;
1201}
1202
1203
1204static uint32_t get_tag_value_i32(unsigned char *val, int len)
1205{
1206    uint32_t v;
1207    if (len < 4)
1208        return 0;
1209    memcpy(&v, val, 4);
1210    return v;
1211}
1212
1213
1214static uint64_t get_tag_value_i64(unsigned char *val, int len)
1215{
1216    uint64_t v;
1217    if (len < 8)
1218        return 0;
1219    memcpy(&v, val, 8);
1220    return v;
1221}
1222
1223
1224static int
1225get_tag_val_u32 (unsigned char *v, int len, uint32_t *val)
1226{
1227    if (len != 4)
1228        return -1;
1229    memcpy(val, v, 4);
1230    return 0;
1231}
1232
1233
1234/*  From "QUIC Crypto" for easy reference:
1235 *
1236 *  A handshake message consists of:
1237 *    - The tag of the message.
1238 *    - A uint16 containing the number of tag-value pairs.
1239 *    - Two bytes of padding which should be zero when sent but ignored when
1240 *          received.
1241 *    - A series of uint32 tags and uint32 end offsets, one for each
1242 *          tag-value pair. The tags must be strictly monotonically
1243 *          increasing, and the end-offsets must be monotonic non-decreasing.
1244 *          The end offset gives the offset, from the start of the value
1245 *          data, to a byte one beyond the end of the data for that tag.
1246 *          (Thus the end offset of the last tag contains the length of the
1247 *          value data).
1248 *    - The value data, concatenated without padding.
1249 */
1250
1251struct table_entry { uint32_t tag, off; };
1252
1253struct message_writer
1254{
1255    unsigned char       *mw_p;
1256    struct table_entry   mw_first_dummy_entry;
1257    struct table_entry  *mw_entry,
1258                        *mw_prev_entry,
1259                        *mw_end;
1260};
1261
1262/* MW_ family of macros is used to write entries to handshake message
1263 * (MW stands for "message writer").
1264 */
1265#define MW_BEGIN(mw, msg_tag, n_entries, data_ptr) do {             \
1266    uint32_t t_ = msg_tag;                                          \
1267    uint16_t n_ = n_entries;                                        \
1268    memcpy(data_ptr, &t_, 4);                                       \
1269    memcpy(data_ptr + 4, &n_, 2);                                   \
1270    memset(data_ptr + 4 + 2, 0, 2);                                 \
1271    (mw)->mw_entry = (void *) (data_ptr + 8);                       \
1272    (mw)->mw_p = data_ptr + 8 +                                     \
1273                    (n_entries) * sizeof((mw)->mw_entry[0]);        \
1274    (mw)->mw_first_dummy_entry.tag = 0;                             \
1275    (mw)->mw_first_dummy_entry.off = 0;                             \
1276    (mw)->mw_prev_entry = &(mw)->mw_first_dummy_entry;              \
1277    (mw)->mw_end = (void *) (mw)->mw_p;                             \
1278} while (0)
1279
1280#ifndef NDEBUG
1281#   define MW_END(mw) do {                                          \
1282        assert((mw)->mw_entry == (mw)->mw_end);                     \
1283    } while (0)
1284#else
1285#   define MW_END(mw)
1286#endif
1287
1288#define MW_P(mw) ((mw)->mw_p)
1289
1290#define MW_ADVANCE_P(mw, n) do {                                    \
1291    MW_P(mw) += (n);                                                \
1292} while (0)
1293
1294#define MW_WRITE_TABLE_ENTRY(mw, tag_, sz) do {                     \
1295    assert((mw)->mw_prev_entry->tag < (tag_));                      \
1296    assert((mw)->mw_entry < (mw)->mw_end);                          \
1297    (mw)->mw_entry->tag = (tag_);                                   \
1298    (mw)->mw_entry->off = (mw)->mw_prev_entry->off + (sz);          \
1299    (mw)->mw_prev_entry = (mw)->mw_entry;                           \
1300    ++(mw)->mw_entry;                                               \
1301} while (0)
1302
1303#define MW_WRITE_BUFFER(mw, tag, buf, sz) do {                      \
1304    MW_WRITE_TABLE_ENTRY(mw, tag, sz);                              \
1305    memcpy(MW_P(mw), buf, sz);                                      \
1306    MW_ADVANCE_P(mw, sz);                                           \
1307} while (0)
1308
1309#define MW_WRITE_LS_STR(mw, tag, s) \
1310    MW_WRITE_BUFFER(mw, tag, lsquic_str_buf(s), lsquic_str_len(s))
1311
1312#define MW_WRITE_UINT32(mw, tag, val) do {                          \
1313    uint32_t v_ = (val);                                            \
1314    MW_WRITE_BUFFER(mw, tag, &v_, sizeof(v_));                      \
1315} while (0)
1316
1317#define MW_WRITE_UINT64(mw, tag, val) do {                          \
1318    uint64_t v_ = (val);                                            \
1319    MW_WRITE_BUFFER(mw, tag, &v_, sizeof(v_));                      \
1320} while (0)
1321
1322
1323/* MSG_LEN_ family of macros calculates buffer size required for a
1324 * handshake message.
1325 */
1326#define MSG_LEN_INIT(len) do {                                      \
1327    len = 4 /* Tag */ + 2 /* # tags */ + 2 /* Two zero bytes */;    \
1328} while (0)
1329
1330#define MSG_LEN_ADD(len, payload_sz) do {                           \
1331    len += 4 + 4 + (payload_sz);                                    \
1332} while (0)
1333
1334#define MSG_LEN_VAL(len) (+(len))
1335
1336
1337static int
1338lsquic_enc_session_gen_chlo (enc_session_t *enc_session_p,
1339                        enum lsquic_version version, uint8_t *buf, size_t *len)
1340{
1341    struct lsquic_enc_session *const enc_session = enc_session_p;
1342    int include_pad;
1343    const lsquic_str_t *const ccs = get_common_certs_hash();
1344    const struct lsquic_engine_settings *const settings =
1345                                        &enc_session->enpub->enp_settings;
1346    c_cert_item_t *const cert_item = enc_session->cert_item;
1347    unsigned char pub_key[32];
1348    size_t ua_len;
1349    uint32_t opts[1];  /* Only NSTP is supported for now */
1350    unsigned n_opts, msg_len, n_tags, pad_size;
1351    struct message_writer mw;
1352
1353    /* Before we do anything else, sanity check: */
1354    if (*len < MIN_CHLO_SIZE)
1355        return -1;
1356
1357    n_opts = 0;
1358    /* CHLO is not regenerated during version negotiation.  Hence we always
1359     * include this option to cover the case when Q044 or Q046 gets negotiated
1360     * down.
1361     */
1362    if (settings->es_support_nstp)
1363        opts[ n_opts++ ] = QTAG_NSTP;
1364
1365    /* Count tags and calculate required buffer size: */
1366    MSG_LEN_INIT(msg_len);                  n_tags = 0;
1367    MSG_LEN_ADD(msg_len, 4);                ++n_tags;           /* PDMD */
1368    MSG_LEN_ADD(msg_len, 4);                ++n_tags;           /* AEAD */
1369    MSG_LEN_ADD(msg_len, 4);                ++n_tags;           /* VER  */
1370    MSG_LEN_ADD(msg_len, 4);                ++n_tags;           /* MIDS */
1371    MSG_LEN_ADD(msg_len, 4);                ++n_tags;           /* SCLS */
1372    MSG_LEN_ADD(msg_len, 4);                ++n_tags;           /* CFCW */
1373    MSG_LEN_ADD(msg_len, 4);                ++n_tags;           /* SFCW */
1374    MSG_LEN_ADD(msg_len, 4);                ++n_tags;           /* ICSL */
1375    MSG_LEN_ADD(msg_len, 4);                ++n_tags;           /* SMHL */
1376    MSG_LEN_ADD(msg_len, 4);                ++n_tags;           /* KEXS */
1377    MSG_LEN_ADD(msg_len, 0);                ++n_tags;           /* CSCT */
1378    if (n_opts > 0)
1379    {
1380        MSG_LEN_ADD(msg_len, sizeof(opts[0]) * n_opts);
1381                                            ++n_tags;           /* COPT */
1382    }
1383    if (settings->es_ua)
1384    {
1385        ua_len = strlen(settings->es_ua);
1386        if (ua_len > 0)
1387        {
1388            MSG_LEN_ADD(msg_len, ua_len);   ++n_tags;           /* UAID */
1389        }
1390    }
1391    else
1392        ua_len = 0;
1393    if (settings->es_support_tcid0)
1394    {
1395        MSG_LEN_ADD(msg_len, 4);            ++n_tags;           /* TCID */
1396    }
1397    MSG_LEN_ADD(msg_len, lsquic_str_len(&enc_session->hs_ctx.sni));
1398                                            ++n_tags;           /* SNI  */
1399    MSG_LEN_ADD(msg_len, lsquic_str_len(ccs));  ++n_tags;           /* CCS  */
1400    if (cert_item)
1401    {
1402        enc_session->cert_ptr = &cert_item->crts[0];
1403        MSG_LEN_ADD(msg_len, lsquic_str_len(cert_item->hashs));
1404                                            ++n_tags;           /* CCRT */
1405        MSG_LEN_ADD(msg_len, 8);            ++n_tags;           /* XLCT */
1406    }
1407    MSG_LEN_ADD(msg_len, lsquic_str_len(&enc_session->ssno));
1408                                            ++n_tags;           /* SNO  */
1409    MSG_LEN_ADD(msg_len, lsquic_str_len(&enc_session->info->sstk));
1410                                            ++n_tags;           /* STK  */
1411    if (lsquic_str_len(&enc_session->info->scfg) > 0)
1412    {
1413        MSG_LEN_ADD(msg_len, sizeof(enc_session->info->sscid));
1414                                            ++n_tags;           /* SCID */
1415        if (enc_session->cert_ptr)
1416        {
1417            MSG_LEN_ADD(msg_len, sizeof(pub_key));
1418                                            ++n_tags;           /* PUBS */
1419            MSG_LEN_ADD(msg_len, sizeof(enc_session->hs_ctx.nonc));
1420                                            ++n_tags;           /* NONC */
1421            rand_bytes(enc_session->priv_key, 32);
1422            c255_get_pub_key(enc_session->priv_key, pub_key);
1423            gen_nonce_c(enc_session->hs_ctx.nonc, enc_session->info->orbt);
1424        }
1425    }
1426    include_pad = MSG_LEN_VAL(msg_len) < MIN_CHLO_SIZE;
1427    if (include_pad)
1428    {
1429        if (MSG_LEN_VAL(msg_len) + sizeof(struct table_entry) < MIN_CHLO_SIZE)
1430            pad_size = MIN_CHLO_SIZE - MSG_LEN_VAL(msg_len) -
1431                                                sizeof(struct table_entry);
1432        else
1433            pad_size = 0;
1434        MSG_LEN_ADD(msg_len, pad_size);     ++n_tags;           /* PAD  */
1435    }
1436#ifdef WIN32
1437    else
1438        pad_size = 0;
1439#endif
1440
1441    /* Check that we have enough room in the output buffer: */
1442    if (MSG_LEN_VAL(msg_len) > *len)
1443        return -1;
1444
1445    /* Write CHLO: */
1446    MW_BEGIN(&mw, QTAG_CHLO, n_tags, buf);
1447    if (include_pad)
1448    {
1449        memset(MW_P(&mw), '-', pad_size);
1450        MW_WRITE_TABLE_ENTRY(&mw, QTAG_PAD, pad_size);
1451        MW_ADVANCE_P(&mw, pad_size);
1452    }
1453    MW_WRITE_LS_STR(&mw, QTAG_SNI, &enc_session->hs_ctx.sni);
1454    MW_WRITE_LS_STR(&mw, QTAG_STK, &enc_session->info->sstk);
1455    MW_WRITE_LS_STR(&mw, QTAG_SNO, &enc_session->ssno);
1456    MW_WRITE_UINT32(&mw, QTAG_VER, lsquic_ver2tag(version));
1457    MW_WRITE_LS_STR(&mw, QTAG_CCS, ccs);
1458    if (lsquic_str_len(&enc_session->info->scfg) > 0 && enc_session->cert_ptr)
1459        MW_WRITE_BUFFER(&mw, QTAG_NONC, enc_session->hs_ctx.nonc,
1460                                        sizeof(enc_session->hs_ctx.nonc));
1461    MW_WRITE_UINT32(&mw, QTAG_AEAD, settings->es_aead);
1462    if (ua_len)
1463        MW_WRITE_BUFFER(&mw, QTAG_UAID, settings->es_ua, ua_len);
1464    if (lsquic_str_len(&enc_session->info->scfg) > 0)
1465        MW_WRITE_BUFFER(&mw, QTAG_SCID, enc_session->info->sscid,
1466                                        sizeof(enc_session->info->sscid));
1467    if (settings->es_support_tcid0)
1468        MW_WRITE_UINT32(&mw, QTAG_TCID, 0);
1469    MW_WRITE_UINT32(&mw, QTAG_PDMD, settings->es_pdmd);
1470    MW_WRITE_UINT32(&mw, QTAG_SMHL, 1);
1471    MW_WRITE_UINT32(&mw, QTAG_ICSL, settings->es_idle_conn_to / 1000000);
1472    if (lsquic_str_len(&enc_session->info->scfg) > 0 && enc_session->cert_ptr)
1473        MW_WRITE_BUFFER(&mw, QTAG_PUBS, pub_key, sizeof(pub_key));
1474    MW_WRITE_UINT32(&mw, QTAG_MIDS, settings->es_max_streams_in);
1475    MW_WRITE_UINT32(&mw, QTAG_SCLS, settings->es_silent_close);
1476    MW_WRITE_UINT32(&mw, QTAG_KEXS, settings->es_kexs);
1477    if (cert_item)
1478        MW_WRITE_BUFFER(&mw, QTAG_XLCT, lsquic_str_buf(cert_item->hashs), 8);
1479    /* CSCT is empty on purpose (retained from original code) */
1480    MW_WRITE_TABLE_ENTRY(&mw, QTAG_CSCT, 0);
1481    if (n_opts > 0)
1482        MW_WRITE_BUFFER(&mw, QTAG_COPT, opts, n_opts * sizeof(opts[0]));
1483    if (cert_item)
1484        MW_WRITE_LS_STR(&mw, QTAG_CCRT, cert_item->hashs);
1485    MW_WRITE_UINT32(&mw, QTAG_CFCW, settings->es_cfcw);
1486    MW_WRITE_UINT32(&mw, QTAG_SFCW, settings->es_sfcw);
1487    MW_END(&mw);
1488    assert(buf + *len >= MW_P(&mw));
1489
1490    *len = MW_P(&mw) - buf;
1491
1492    lsquic_str_setto(&enc_session->chlo, buf, *len);
1493
1494    if (lsquic_str_len(&enc_session->info->scfg) > 0 && enc_session->cert_ptr)
1495    {
1496        enc_session->have_key = 0;
1497        assert(lsquic_str_len(enc_session->cert_ptr) > 0);
1498        determine_keys(enc_session, 1);
1499        enc_session->have_key = 1;
1500    }
1501
1502    LSQ_DEBUG("lsquic_enc_session_gen_chlo called, return 0, buf_len %zd.", *len);
1503    return 0;
1504}
1505
1506
1507static enum handshake_error
1508determine_rtts (struct lsquic_enc_session *enc_session,
1509                                    const struct sockaddr *ip_addr, time_t t)
1510{
1511    hs_ctx_t *const hs_ctx = &enc_session->hs_ctx;
1512    enum hsk_failure_reason hfr;
1513
1514    if (!(hs_ctx->set & HSET_SCID))
1515    {
1516        hs_ctx->rrej = HFR_CONFIG_INCHOATE_HELLO;
1517        ESHIST_APPEND(enc_session, ESHE_MISSING_SCID);
1518        goto fail_1rtt;
1519    }
1520
1521    hfr = verify_stk(enc_session, ip_addr, t, &hs_ctx->stk);
1522    if (hfr != HFR_HANDSHAKE_OK)
1523    {
1524        hs_ctx->rrej = hfr;
1525        ESHIST_APPEND(enc_session, ESHE_VSTK_FAILED);
1526        goto fail_1rtt;
1527    }
1528    else
1529        ESHIST_APPEND(enc_session, ESHE_VSTK_OK);
1530
1531    if (memcmp(enc_session->server_config->lsc_scfg->info.sscid, hs_ctx->scid, 16) != 0)
1532    {
1533        hs_ctx->rrej = HFR_CONFIG_UNKNOWN_CONFIG;
1534        ESHIST_APPEND(enc_session, ESHE_UNKNOWN_CONFIG);
1535        goto fail_1rtt;
1536    }
1537
1538    if (!(lsquic_str_len(&hs_ctx->ccrt) > 0))
1539    {
1540        /* We provide incorrect RREJ here because there is not one that fits
1541         * this case.  We can tell them apart: one comes in SREJ, the other
1542         * in REJ.
1543         */
1544        hs_ctx->rrej = HFR_CONFIG_INCHOATE_HELLO;
1545        ESHIST_APPEND(enc_session, ESHE_EMPTY_CCRT);
1546        goto fail_1rtt;
1547    }
1548
1549    if (lsquic_str_len(&enc_session->ssno) > 0)
1550    {
1551        if (lsquic_str_len(&hs_ctx->sno) == 0)
1552        {
1553            hs_ctx->rrej = HFR_SERVER_NONCE_REQUIRED;
1554            ESHIST_APPEND(enc_session, ESHE_MISSING_SNO);
1555            goto fail_1rtt;
1556        }
1557        else if (lsquic_str_bcmp(&enc_session->ssno, &hs_ctx->sno) != 0)
1558        {
1559            hs_ctx->rrej = HFR_SERVER_NONCE_INVALID;
1560            ESHIST_APPEND(enc_session, ESHE_SNO_MISMATCH);
1561            goto fail_1rtt;
1562        }
1563        else
1564            ESHIST_APPEND(enc_session, ESHE_SNO_OK);
1565    }
1566
1567    enc_session->hsk_state = HSK_SHLO;
1568    memcpy(enc_session->priv_key, enc_session->server_config->lsc_scfg->info.priv_key, 32);
1569    return HS_SHLO;
1570
1571  fail_1rtt:
1572    enc_session->hsk_state = HSK_CHLO_REJ;
1573    return HS_1RTT;
1574}
1575
1576
1577static int
1578config_has_correct_size (const void *data, unsigned shm_len)
1579{
1580    /* EVP_AEAD_CTX from boringssl after-18d9f28f0df9f95570. */
1581    struct new_evp_aead_ctx_st {
1582        void *ptr1;     /* aead */
1583        void *ptr2;     /* aead_state */
1584        uint8_t tag_len;
1585    };
1586
1587    /* This is how SHM would like in 5.2.1 builds 7 and 8: */
1588    struct old_scfg_info
1589    {
1590        unsigned char   sscid[SCID_LENGTH];
1591        unsigned char   priv_key[32];
1592        unsigned char   skt_key[16];
1593        uint32_t        aead;
1594        uint32_t        kexs;
1595        uint32_t        pdmd;
1596        uint64_t        orbt;
1597        uint64_t        expy;
1598        struct new_evp_aead_ctx_st ctx;
1599        short           scfg_len;
1600    };
1601
1602    const SCFG_t               *const modern_config = data;
1603    const struct old_scfg_info *const old_info      = data;
1604    size_t expected_size;
1605
1606    expected_size = modern_config->info.scfg_len + sizeof(*modern_config);
1607    if (expected_size == shm_len)
1608        return 1;
1609
1610    if (old_info->scfg_len + sizeof(*old_info) == shm_len)
1611    {
1612        LSQ_WARN("Generating new server config");
1613        return 0;
1614    }
1615
1616    LSQ_ERROR("Server config has size %u -- expected %zd", shm_len,
1617                                                            expected_size);
1618    return 0;
1619}
1620
1621
1622static lsquic_server_config_t *
1623get_valid_scfg (const struct lsquic_engine_public *enpub)
1624{
1625#define SERVER_SCFG_KEY         "SERVER_SCFG"
1626#define SERVER_SCFG_KEY_SIZE    (sizeof(SERVER_SCFG_KEY) - 1)
1627    const struct lsquic_engine_settings *const settings = &enpub->enp_settings;
1628    const struct lsquic_shared_hash_if *const shi = enpub->enp_shi;
1629    void *const shi_ctx = enpub->enp_shi_ctx;
1630    uint8_t spubs[35] = {0x20, 0, 0, };/* need to init first 3 bytes */
1631    time_t t = time(NULL);
1632    unsigned int real_len;
1633    SCFG_info_t *temp_scfg;
1634    SCFG_t *tmp_scfg_copy = NULL;
1635    void *scfg_ptr;
1636    int ret;
1637    unsigned msg_len, server_config_sz;
1638    struct message_writer mw;
1639
1640    if (s_server_config.lsc_scfg && (s_server_config.lsc_scfg->info.expy > (uint64_t)t))
1641        return &s_server_config;
1642
1643    ret = shi->shi_lookup(shi_ctx, SERVER_SCFG_KEY, SERVER_SCFG_KEY_SIZE,
1644                          &scfg_ptr, &real_len);
1645    if (ret == 1)
1646    {
1647        if (config_has_correct_size(scfg_ptr, real_len) &&
1648                (s_server_config.lsc_scfg = scfg_ptr,
1649                            s_server_config.lsc_scfg->info.expy > (uint64_t)t))
1650        {
1651            /* Why need to init here, because this memory may be read from SHM,
1652             * the struct is ready but AEAD_CTX is not ready.
1653             **/
1654            EVP_AEAD_CTX_init(&s_server_config.lsc_stk_ctx, EVP_aead_aes_128_gcm(),
1655                              s_server_config.lsc_scfg->info.skt_key, 16, 12, NULL);
1656            return &s_server_config;
1657        }
1658        else
1659        {
1660            shi->shi_delete(shi_ctx, SERVER_SCFG_KEY, SERVER_SCFG_KEY_SIZE);
1661        }
1662    }
1663
1664    MSG_LEN_INIT(msg_len);
1665    MSG_LEN_ADD(msg_len, sizeof(temp_scfg->sscid));
1666    MSG_LEN_ADD(msg_len, sizeof(spubs));
1667    MSG_LEN_ADD(msg_len, enpub->enp_ver_tags_len);
1668    MSG_LEN_ADD(msg_len, sizeof(temp_scfg->aead));
1669    MSG_LEN_ADD(msg_len, sizeof(temp_scfg->kexs));
1670    MSG_LEN_ADD(msg_len, sizeof(temp_scfg->pdmd));
1671    MSG_LEN_ADD(msg_len, sizeof(temp_scfg->orbt));
1672    MSG_LEN_ADD(msg_len, sizeof(temp_scfg->expy));
1673
1674    server_config_sz = sizeof(*s_server_config.lsc_scfg) + MSG_LEN_VAL(msg_len);
1675    s_server_config.lsc_scfg = malloc(server_config_sz);
1676    if (!s_server_config.lsc_scfg)
1677        return NULL;
1678
1679    temp_scfg = &s_server_config.lsc_scfg->info;
1680    rand_bytes(temp_scfg->skt_key, sizeof(temp_scfg->skt_key));
1681    rand_bytes(temp_scfg->sscid, sizeof(temp_scfg->sscid));
1682    rand_bytes(temp_scfg->priv_key, sizeof(temp_scfg->priv_key));
1683    c255_get_pub_key(temp_scfg->priv_key, spubs + 3);
1684    temp_scfg->aead = settings->es_aead;
1685    temp_scfg->kexs = settings->es_kexs;
1686    temp_scfg->pdmd = settings->es_pdmd;
1687    temp_scfg->orbt = 0;
1688    temp_scfg->expy = t + settings->es_sttl;
1689
1690    MW_BEGIN(&mw, QTAG_SCFG, 8, s_server_config.lsc_scfg->scfg);
1691    MW_WRITE_BUFFER(&mw, QTAG_VER, enpub->enp_ver_tags_buf,
1692                                                enpub->enp_ver_tags_len);
1693    MW_WRITE_UINT32(&mw, QTAG_AEAD, temp_scfg->aead);
1694    MW_WRITE_BUFFER(&mw, QTAG_SCID, temp_scfg->sscid, sizeof(temp_scfg->sscid));
1695    MW_WRITE_UINT32(&mw, QTAG_PDMD, temp_scfg->pdmd);
1696    MW_WRITE_BUFFER(&mw, QTAG_PUBS, spubs, sizeof(spubs));
1697    MW_WRITE_UINT32(&mw, QTAG_KEXS, temp_scfg->kexs);
1698    MW_WRITE_UINT64(&mw, QTAG_ORBT, temp_scfg->orbt);
1699    MW_WRITE_UINT64(&mw, QTAG_EXPY, temp_scfg->expy);
1700    MW_END(&mw);
1701    assert(MW_P(&mw) == s_server_config.lsc_scfg->scfg + MSG_LEN_VAL(msg_len));
1702
1703    temp_scfg->scfg_len = MSG_LEN_VAL(msg_len);
1704
1705    LSQ_DEBUG("%s called, return len %d.", __func__, temp_scfg->scfg_len);
1706
1707//     /* TODO: will shi_delete call free to release the buffer? */
1708//     shi->shi_delete(shi_ctx, SERVER_SCFG_KEY, SERVER_SCFG_KEY_SIZE);
1709    void *scfg_key = strdup(SERVER_SCFG_KEY);
1710    shi->shi_insert(shi_ctx, scfg_key, SERVER_SCFG_KEY_SIZE,
1711            s_server_config.lsc_scfg, server_config_sz, t + settings->es_sttl);
1712
1713    ret = shi->shi_lookup(shi_ctx, scfg_key, SERVER_SCFG_KEY_SIZE,
1714                          &scfg_ptr, &real_len);
1715    if (ret == 1)
1716    {
1717        tmp_scfg_copy = scfg_ptr;
1718        if (tmp_scfg_copy != s_server_config.lsc_scfg)
1719        {
1720            free(s_server_config.lsc_scfg);
1721            s_server_config.lsc_scfg = tmp_scfg_copy;
1722        }
1723    }
1724    else
1725    {
1726        /* Since internal error occured, but I have to use a SCFG, log it*/
1727        LSQ_DEBUG("get_valid_scfg got an shi internal error.\n");
1728    }
1729
1730    ret = EVP_AEAD_CTX_init(&s_server_config.lsc_stk_ctx, EVP_aead_aes_128_gcm(),
1731                              s_server_config.lsc_scfg->info.skt_key,
1732                              sizeof(s_server_config.lsc_scfg->info.skt_key), 12, NULL);
1733
1734    LSQ_DEBUG("get_valid_scfg::EVP_AEAD_CTX_init return %d.", ret);
1735    return &s_server_config;
1736}
1737
1738
1739static int
1740generate_crt (struct lsquic_enc_session *enc_session, int common_case)
1741{
1742    int i, n, len, crt_num, rv = -1;
1743    lsquic_str_t **crts;
1744    unsigned char *out;
1745    X509* crt;
1746    STACK_OF(X509)      *pXchain;
1747    SSL_CTX *const ctx = enc_session->ssl_ctx;
1748    hs_ctx_t *const hs_ctx = &enc_session->hs_ctx;
1749
1750    SSL_CTX_get0_chain_certs(ctx, &pXchain);
1751    n = sk_X509_num(pXchain);
1752    crt_num = n + 1;
1753
1754    crts = calloc(crt_num, sizeof(crts[0]));
1755    if (!crts)
1756        return -1;
1757
1758    crts[0] = lsquic_str_new(lsquic_str_cstr(enc_session->cert_ptr),
1759                                    lsquic_str_len(enc_session->cert_ptr));
1760    if (!crts[0])
1761        goto cleanup;
1762
1763    for (i = 1; i < crt_num; i++)
1764    {
1765        crt = sk_X509_value(pXchain, i - 1);
1766        out = NULL;
1767        len = i2d_X509(crt, &out);
1768        if (len < 0)
1769            goto cleanup;
1770        crts[i] = lsquic_str_new((const char *) out, len);
1771        OPENSSL_free(out);
1772    }
1773
1774    if (0 != compress_certs(crts, crt_num, &hs_ctx->ccs, &hs_ctx->ccrt,
1775                                                            &hs_ctx->crt))
1776        goto cleanup;
1777
1778    if (common_case)
1779    {
1780        if (0 != insert_compress_certs(make_compress_cert_hash_item(
1781                                                &hs_ctx->sni, &hs_ctx->crt)))
1782            goto cleanup;
1783    }
1784
1785    /* We got here, set rv to 0: success */
1786    rv = 0;
1787
1788  cleanup:
1789    for (i = 0; i < crt_num; ++i)
1790        if (crts[i])
1791            lsquic_str_delete(crts[i]);
1792    free(crts);
1793    return rv;
1794}
1795
1796
1797/* rtt == 1 case */
1798static int
1799gen_rej1_data (struct lsquic_enc_session *enc_session, uint8_t *data,
1800                    size_t max_len, const struct sockaddr *ip, time_t t)
1801{
1802    int len;
1803    EVP_PKEY * rsa_priv_key;
1804    SSL_CTX *ctx = enc_session->ssl_ctx;
1805    const struct lsquic_engine_settings *const settings =
1806                                        &enc_session->enpub->enp_settings;
1807    hs_ctx_t *const hs_ctx = &enc_session->hs_ctx;
1808    int scfg_len = enc_session->server_config->lsc_scfg->info.scfg_len;
1809    uint8_t *scfg_data = enc_session->server_config->lsc_scfg->scfg;
1810    char prof_buf[512];
1811    size_t prof_len = 512;
1812    compress_cert_hash_item_t* compress_certs_item;
1813    int common_case;
1814    size_t msg_len;
1815    struct message_writer mw;
1816
1817    rsa_priv_key = SSL_CTX_get0_privatekey(ctx);
1818    if (!rsa_priv_key)
1819        return -1;
1820
1821    lsquic_str_d(&hs_ctx->crt);
1822
1823    /**
1824     * Only cache hs_ctx->ccs is the hardcoded common certs and hs_ctx->ccrt is empty case
1825     * This is the most common case
1826     */
1827    common_case = lsquic_str_len(&hs_ctx->ccrt) == 0
1828               && lsquic_str_bcmp(&hs_ctx->ccs, get_common_certs_hash()) == 0;
1829    if (common_case)
1830        compress_certs_item = find_compress_certs(&hs_ctx->sni);
1831    else
1832        compress_certs_item = NULL;
1833
1834    if (compress_certs_item)
1835    {
1836        lsquic_str_d(&hs_ctx->crt);
1837        lsquic_str_copy(&hs_ctx->crt, compress_certs_item->crts_compress_buf);
1838    }
1839    else
1840        generate_crt(enc_session, common_case);
1841
1842    LSQ_DEBUG("gQUIC rej1 data");
1843    LSQ_DEBUG("gQUIC NOT enabled");
1844    gen_prof((const uint8_t *)lsquic_str_cstr(&enc_session->chlo),
1845         (size_t)lsquic_str_len(&enc_session->chlo),
1846         scfg_data, scfg_len,
1847         rsa_priv_key, (uint8_t *)prof_buf, &prof_len);
1848
1849    lsquic_str_setto(&hs_ctx->prof, prof_buf, prof_len);
1850
1851    if (!hs_ctx->rrej)
1852    {
1853        LSQ_WARN("REJ: RREJ is not set, use default");
1854        hs_ctx->rrej = HFR_CLIENT_NONCE_UNKNOWN;
1855    }
1856
1857    MSG_LEN_INIT(msg_len);
1858    MSG_LEN_ADD(msg_len, sizeof(hs_ctx->rrej));
1859    MSG_LEN_ADD(msg_len, scfg_len);
1860    MSG_LEN_ADD(msg_len, STK_LENGTH);
1861    MSG_LEN_ADD(msg_len, SNO_LENGTH);
1862    MSG_LEN_ADD(msg_len, sizeof(settings->es_sttl));
1863    MSG_LEN_ADD(msg_len, lsquic_str_len(&hs_ctx->prof));
1864    MSG_LEN_ADD(msg_len, lsquic_str_len(&hs_ctx->crt));
1865
1866    if (MSG_LEN_VAL(msg_len) > max_len)
1867        return -1;
1868
1869    memcpy(enc_session->priv_key, enc_session->server_config->lsc_scfg->info.priv_key, 32);
1870
1871    if (lsquic_str_len(&enc_session->sstk) != STK_LENGTH)
1872    {
1873        lsquic_str_d(&enc_session->sstk);
1874        lsquic_str_prealloc(&enc_session->sstk, STK_LENGTH);
1875        lsquic_str_setlen(&enc_session->sstk, STK_LENGTH);
1876    }
1877    gen_stk(enc_session->server_config, ip, t,
1878                        (unsigned char *) lsquic_str_buf(&enc_session->sstk));
1879
1880    if (lsquic_str_len(&enc_session->ssno) != SNO_LENGTH)
1881    {
1882        lsquic_str_d(&enc_session->ssno);
1883        lsquic_str_prealloc(&enc_session->ssno, SNO_LENGTH);
1884        lsquic_str_setlen(&enc_session->ssno, SNO_LENGTH);
1885    }
1886    rand_bytes(lsquic_str_buf(&enc_session->ssno), SNO_LENGTH);
1887
1888    MW_BEGIN(&mw, QTAG_REJ, 7, data);
1889    MW_WRITE_LS_STR(&mw, QTAG_STK, &enc_session->sstk);
1890    MW_WRITE_LS_STR(&mw, QTAG_SNO, &enc_session->ssno);
1891    MW_WRITE_LS_STR(&mw, QTAG_PROF, &hs_ctx->prof);
1892    MW_WRITE_BUFFER(&mw, QTAG_SCFG, scfg_data, scfg_len);
1893    MW_WRITE_BUFFER(&mw, QTAG_RREJ, &hs_ctx->rrej, sizeof(hs_ctx->rrej));
1894    MW_WRITE_BUFFER(&mw, QTAG_STTL, &settings->es_sttl,
1895                                                sizeof(settings->es_sttl));
1896    MW_WRITE_LS_STR(&mw, QTAG_CRT, &hs_ctx->crt);
1897    MW_END(&mw);
1898
1899    assert(data + max_len >= MW_P(&mw));
1900    len = MW_P(&mw) - data;
1901    LSQ_DEBUG("gen_rej1_data called, return len %d.", len);
1902    return len;
1903}
1904
1905
1906/* rtt == 0 case */
1907static int
1908gen_shlo_data (uint8_t *buf, size_t buf_len, struct lsquic_enc_session *enc_session,
1909                  enum lsquic_version version, const struct sockaddr *ip,
1910                  time_t t, uint8_t *nonce)
1911{
1912    char pub_key[32];
1913    const struct lsquic_engine_settings *const settings =
1914                                        &enc_session->enpub->enp_settings;
1915    struct message_writer mw;
1916    int len;
1917    const int include_reset_token = version >= LSQVER_046;
1918    size_t msg_len;
1919
1920    MSG_LEN_INIT(msg_len);
1921    MSG_LEN_ADD(msg_len, enc_session->enpub->enp_ver_tags_len);
1922    MSG_LEN_ADD(msg_len, sizeof(pub_key));
1923    MSG_LEN_ADD(msg_len, 4);    /* MIDS */
1924    MSG_LEN_ADD(msg_len, 4);    /* CFCW */
1925    MSG_LEN_ADD(msg_len, 4);    /* SFCW */
1926    MSG_LEN_ADD(msg_len, 4);    /* ICSL */
1927    MSG_LEN_ADD(msg_len, 4);    /* SMHL */
1928    MSG_LEN_ADD(msg_len, lsquic_str_len(&enc_session->sstk));
1929    MSG_LEN_ADD(msg_len, lsquic_str_len(&enc_session->ssno));
1930    if (include_reset_token)
1931        MSG_LEN_ADD(msg_len, SRST_LENGTH);
1932
1933    if (MSG_LEN_VAL(msg_len) > buf_len)
1934        return -1;
1935
1936    rand_bytes(nonce, 32);
1937    rand_bytes(enc_session->priv_key, 32);
1938    c255_get_pub_key(enc_session->priv_key, (unsigned char *)pub_key);
1939    if (lsquic_str_len(&enc_session->sstk) != STK_LENGTH)
1940    {
1941        lsquic_str_d(&enc_session->sstk);
1942        lsquic_str_prealloc(&enc_session->sstk, STK_LENGTH);
1943        lsquic_str_setlen(&enc_session->sstk, STK_LENGTH);
1944    }
1945    gen_stk(enc_session->server_config, ip, t,
1946                        (unsigned char *) lsquic_str_buf(&enc_session->sstk));
1947    if (lsquic_str_len(&enc_session->ssno) != SNO_LENGTH)
1948    {
1949        lsquic_str_d(&enc_session->ssno);
1950        lsquic_str_prealloc(&enc_session->ssno, SNO_LENGTH);
1951        lsquic_str_setlen(&enc_session->ssno, SNO_LENGTH);
1952    }
1953    rand_bytes(lsquic_str_buf(&enc_session->ssno), SNO_LENGTH);
1954
1955    MW_BEGIN(&mw, QTAG_SHLO, 9 + include_reset_token, buf);
1956    MW_WRITE_LS_STR(&mw, QTAG_STK, &enc_session->sstk);
1957    MW_WRITE_LS_STR(&mw, QTAG_SNO, &enc_session->ssno);
1958    MW_WRITE_BUFFER(&mw, QTAG_VER, enc_session->enpub->enp_ver_tags_buf,
1959                                    enc_session->enpub->enp_ver_tags_len);
1960    MW_WRITE_UINT32(&mw, QTAG_SMHL, 1);
1961    MW_WRITE_UINT32(&mw, QTAG_ICSL, settings->es_idle_conn_to / 1000000);
1962    MW_WRITE_BUFFER(&mw, QTAG_PUBS, pub_key, sizeof(pub_key));
1963    MW_WRITE_UINT32(&mw, QTAG_MIDS, settings->es_max_streams_in);
1964    if (include_reset_token)
1965    {
1966        MW_WRITE_TABLE_ENTRY(&mw, QTAG_SRST, SRST_LENGTH);
1967        lsquic_tg_generate_sreset(enc_session->enpub->enp_tokgen,
1968                                                &enc_session->cid, MW_P(&mw));
1969        MW_ADVANCE_P(&mw, SRST_LENGTH);
1970    }
1971    MW_WRITE_UINT32(&mw, QTAG_CFCW, settings->es_cfcw);
1972    MW_WRITE_UINT32(&mw, QTAG_SFCW, settings->es_sfcw);
1973    MW_END(&mw);
1974
1975    assert(buf + buf_len >= MW_P(&mw));
1976    len = MW_P(&mw) - buf;
1977    LSQ_DEBUG("gen_shlo_data called, return len %d.", len);
1978    return len;
1979}
1980
1981
1982/* Generate key based on issuer and serial number.  The key has the following
1983 * structure:
1984 *
1985 *      size_t          length of issuer.  This field is required to prevent
1986 *                        the chance (however remote) that concatenation of
1987 *                        the next two fields is ambiguous.
1988 *      uint8_t[]       DER-encoded issuer
1989 *      uint8_t[]       Serial number represented as sequence of bytes output
1990 *                        by BN_bn2bin
1991 *
1992 * Return size of the key or zero on error.
1993 */
1994static size_t
1995gen_iasn_key (X509 *cert, unsigned char *const out, size_t const sz)
1996{
1997    const unsigned char *name_bytes;
1998    size_t name_sz;
1999    X509_NAME *name;
2000    ASN1_INTEGER *sernum;
2001    BIGNUM *bn;
2002    unsigned bn_sz;
2003
2004    name = X509_get_issuer_name(cert);
2005    if (!name)
2006        return 0;
2007    if (!X509_NAME_get0_der(name, &name_bytes, &name_sz))
2008        return 0;
2009    sernum = X509_get_serialNumber(cert);
2010    if (!sernum)
2011        return 0;
2012    bn = ASN1_INTEGER_to_BN(sernum, NULL);
2013    if (!bn)
2014        return 0;
2015    bn_sz = BN_num_bytes(bn);
2016    if (sizeof(size_t) + name_sz + bn_sz > sz)
2017    {
2018        BN_free(bn);
2019        return 0;
2020    }
2021
2022    memcpy(out, &name_sz, sizeof(name_sz));
2023    memcpy(out + sizeof(name_sz), name_bytes, name_sz);
2024    BN_bn2bin(bn, out + sizeof(name_sz) +  name_sz);
2025    BN_free(bn);
2026
2027    return sizeof(name_sz) + name_sz + bn_sz;
2028}
2029
2030
2031static enum { GET_SNI_OK, GET_SNI_ERR, GET_SNI_DELAYED, }
2032get_sni_SSL_CTX(struct lsquic_enc_session *enc_session, lsquic_lookup_cert_f cb,
2033                    void *cb_ctx, const struct sockaddr *local)
2034{
2035    X509 *crt = NULL;
2036    unsigned char *out;
2037    int len;
2038    lsquic_str_t crtstr;
2039    cert_item_t *item;
2040    struct ssl_ctx_st *ssl_ctx;
2041    size_t key_sz;
2042    unsigned char key[0x400];
2043
2044    if (!enc_session->ssl_ctx)
2045    {
2046        if (!cb)
2047            return GET_SNI_ERR;
2048        ssl_ctx = cb(cb_ctx, local, lsquic_str_cstr(&enc_session->hs_ctx.sni));
2049        if (ssl_ctx == NULL)
2050            return GET_SNI_ERR;
2051        enc_session->ssl_ctx = ssl_ctx;
2052    }
2053
2054    if (enc_session->cert_ptr == NULL)
2055    {
2056        crt = SSL_CTX_get0_certificate(enc_session->ssl_ctx);
2057        if (!crt)
2058            return GET_SNI_ERR;
2059        key_sz = gen_iasn_key(crt, key, sizeof(key));
2060        if (key_sz)
2061        {
2062            item = s_find_cert(key, key_sz);
2063            if (item)
2064                LSQ_DEBUG("found cert in cache");
2065            else
2066            {
2067                out = NULL;
2068                len = i2d_X509(crt, &out);
2069                if (len < 0)
2070                    return GET_SNI_ERR;
2071                lsquic_str_set(&crtstr, (char *) out, len);
2072                item = s_insert_cert(key, key_sz, &crtstr);
2073                if (item)
2074                {
2075                    OPENSSL_free(out);
2076                    LSQ_DEBUG("inserted cert into cache");
2077                }
2078                else
2079                {
2080                    LSQ_DEBUG("cert insertion failed, keep own copy");
2081                    goto copy;
2082                }
2083            }
2084            enc_session->cert_ptr = item->crt;
2085        }
2086        else
2087        {
2088            LSQ_INFO("cannot generate cert cache key, make copy");
2089            out = NULL;
2090            len = i2d_X509(crt, &out);
2091            if (len < 0)
2092                return GET_SNI_ERR;
2093  copy:     enc_session->cert_ptr = lsquic_str_new((char *) out, len);
2094            OPENSSL_free(out);
2095            if (!enc_session->cert_ptr)
2096                return GET_SNI_ERR;
2097            enc_session->es_flags |= ES_FREE_CERT_PTR;
2098        }
2099    }
2100    return GET_SNI_OK;
2101}
2102
2103
2104/***
2105 * Comments: data and len are the frame(s) parsed data, no packet header.
2106 * return rtt number:
2107 *      1 for rej1 and 0 for shlo
2108 *      DATA_NOT_ENOUGH(-2) for not enough data,
2109 *      DATA_FORMAT_ERROR(-1) all other errors
2110 *      HS_DELAYED handshake delayed
2111 */
2112static enum handshake_error
2113handle_chlo_frames_data(const uint8_t *data, int len,
2114                                        struct lsquic_enc_session *enc_session,
2115                                        lsquic_lookup_cert_f cb, void *cb_ctx,
2116                                        const struct sockaddr *local,
2117                                        const struct lsquic_shared_hash_if *shi,
2118                                        void *shi_ctx, const struct sockaddr *ip, time_t t)
2119{
2120    /* start to parse it */
2121//     struct lsquic_enc_session *enc_session = retrive_enc_session(cid);
2122    uint32_t head_tag;
2123    enum handshake_error rtt;
2124    int ret;
2125
2126    LSQ_DEBUG("handle_chlo_frames_data called.");
2127
2128    ret = parse_hs(enc_session, data, len, &head_tag);
2129    if (ret)
2130    {
2131        LSQ_DEBUG("handle_chlo_frames_data parse_hs error,s o quit.");
2132        return ret;
2133    }
2134
2135    if (head_tag != QTAG_CHLO)
2136    {
2137        LSQ_DEBUG("handle_chlo_frames_data got data format error 1.");
2138        return DATA_FORMAT_ERROR;
2139    }
2140
2141
2142    rtt = determine_rtts(enc_session, ip, t);
2143    ESHIST_APPEND(enc_session, ESHE_MULTI2_2BITS + rtt);
2144    lsquic_str_setto(&enc_session->chlo, (const char *)data, len);
2145    switch (get_sni_SSL_CTX(enc_session, cb, cb_ctx, local))
2146    {
2147    case GET_SNI_DELAYED:
2148        ESHIST_APPEND(enc_session, ESHE_SNI_DELAYED);
2149        LSQ_DEBUG("%s: sni delayed", __func__);
2150        return HS_DELAYED;
2151    case GET_SNI_ERR:
2152        ESHIST_APPEND(enc_session, ESHE_SNI_FAIL);
2153        LSQ_DEBUG("handle_chlo_frames_data got data format error 2.");
2154        return DATA_FORMAT_ERROR;
2155    default:
2156        break;
2157    }
2158
2159
2160    LSQ_DEBUG("handle_chlo_frames_data return %d.", rtt);
2161    return rtt;
2162}
2163
2164
2165static int handle_chlo_reply_verify_prof(struct lsquic_enc_session *enc_session,
2166                                         lsquic_str_t **out_certs,
2167                                         size_t *out_certs_count,
2168                                         lsquic_str_t *cached_certs,
2169                                         int cached_certs_count)
2170{
2171    const unsigned char *const in =
2172                (const unsigned char *) lsquic_str_buf(&enc_session->hs_ctx.crt);
2173    const unsigned char *const in_end =
2174                                    in + lsquic_str_len(&enc_session->hs_ctx.crt);
2175    EVP_PKEY *pub_key;
2176    int ret;
2177    size_t i;
2178    X509 *cert, *server_cert;
2179    STACK_OF(X509) *chain = NULL;
2180    ret = decompress_certs(in, in_end,cached_certs, cached_certs_count,
2181                           out_certs, out_certs_count);
2182    if (ret)
2183        return ret;
2184
2185    server_cert = bio_to_crt((const char *)lsquic_str_cstr(out_certs[0]),
2186                      lsquic_str_len(out_certs[0]), 0);
2187    pub_key = X509_get_pubkey(server_cert);
2188    ret = verify_prof((const uint8_t *)lsquic_str_cstr(&enc_session->chlo),
2189                      (size_t)lsquic_str_len(&enc_session->chlo),
2190                      &enc_session->info->scfg,
2191                      pub_key,
2192                      (const uint8_t *)lsquic_str_cstr(&enc_session->hs_ctx.prof),
2193                      lsquic_str_len(&enc_session->hs_ctx.prof));
2194    EVP_PKEY_free(pub_key);
2195    if (ret != 0)
2196        goto cleanup;
2197
2198    if (enc_session->enpub->enp_verify_cert)
2199    {
2200        chain = sk_X509_new_null();
2201        sk_X509_push(chain, server_cert);
2202        for (i = 1; i < *out_certs_count; ++i)
2203        {
2204            cert = bio_to_crt((const char *)lsquic_str_cstr(out_certs[i]),
2205                                    lsquic_str_len(out_certs[i]), 0);
2206            if (cert)
2207                sk_X509_push(chain, cert);
2208            else
2209            {
2210                LSQ_WARN("cannot push certificate to stack");
2211                ret = -1;
2212                goto cleanup;
2213            }
2214        }
2215        ret = enc_session->enpub->enp_verify_cert(
2216                                enc_session->enpub->enp_verify_ctx, chain);
2217        LSQ_INFO("server certificate verification %ssuccessful",
2218                                                    ret == 0 ? "" : "not ");
2219    }
2220    EV_LOG_CHECK_CERTS(&enc_session->cid, (const lsquic_str_t **)out_certs, *out_certs_count);
2221
2222  cleanup:
2223    if (chain)
2224        sk_X509_free(chain);
2225    X509_free(server_cert);
2226    return ret;
2227}
2228
2229
2230void setup_aead_ctx(EVP_AEAD_CTX **ctx, unsigned char key[], int key_len,
2231                    unsigned char *key_copy)
2232{
2233    const EVP_AEAD *aead_ = EVP_aead_aes_128_gcm();
2234    const int auth_tag_size = 12;
2235    if (*ctx)
2236    {
2237        EVP_AEAD_CTX_cleanup(*ctx);
2238    }
2239    else
2240        *ctx = (EVP_AEAD_CTX *)malloc(sizeof(EVP_AEAD_CTX));
2241
2242    EVP_AEAD_CTX_init(*ctx, aead_, key, key_len, auth_tag_size, NULL);
2243    if (key_copy)
2244        memcpy(key_copy, key, key_len);
2245}
2246
2247
2248static int
2249determine_diversification_key (enc_session_t *enc_session_p,
2250                  uint8_t *diversification_nonce
2251                                                , int is_client
2252                  )
2253{
2254    struct lsquic_enc_session *const enc_session = enc_session_p;
2255    EVP_AEAD_CTX **ctx_s_key;
2256    unsigned char *key_i, *iv;
2257    uint8_t ikm[aes128_key_len + aes128_iv_len];
2258
2259    if (is_client)
2260    {
2261        ctx_s_key = &enc_session->dec_ctx_i;
2262        key_i = enc_session->dec_key_i;
2263        iv = enc_session->dec_key_nonce_i;
2264    }
2265    else
2266    {
2267        ctx_s_key = &enc_session->enc_ctx_i;
2268        key_i = enc_session->enc_key_i;
2269        iv = enc_session->enc_key_nonce_i;
2270    }
2271    memcpy(ikm, key_i, aes128_key_len);
2272    memcpy(ikm + aes128_key_len, iv, aes128_iv_len);
2273    export_key_material(ikm, aes128_key_len + aes128_iv_len,
2274                        diversification_nonce, DNONC_LENGTH,
2275                        (const unsigned char *) "QUIC key diversification", 24,
2276                        0, NULL, aes128_key_len, key_i, 0, NULL,
2277                        aes128_iv_len, iv, NULL);
2278
2279    setup_aead_ctx(ctx_s_key, key_i, aes128_key_len, NULL);
2280    LSQ_DEBUG("determine_diversification_keys diversification_key: %s\n",
2281              get_bin_str(key_i, aes128_key_len, 512));
2282    LSQ_DEBUG("determine_diversification_keys diversification_key nonce: %s\n",
2283              get_bin_str(iv, aes128_iv_len, 512));
2284    return 0;
2285}
2286
2287
2288/* After CHLO msg generatered, call it to determine_keys */
2289static void
2290determine_keys (struct lsquic_enc_session *enc_session,  int is_client)
2291{
2292    lsquic_str_t *chlo = &enc_session->chlo;
2293    uint8_t shared_key_c[32];
2294    struct lsquic_buf *nonce_c = lsquic_buf_create(100);
2295    struct lsquic_buf *hkdf_input = lsquic_buf_create(0);
2296
2297    unsigned char c_key[aes128_key_len];
2298    unsigned char s_key[aes128_key_len];
2299    unsigned char *c_key_bin = NULL;
2300    unsigned char *s_key_bin = NULL;
2301
2302    unsigned char *c_iv;
2303    unsigned char *s_iv;
2304    unsigned char sub_key[32];
2305    EVP_AEAD_CTX **ctx_c_key, **ctx_s_key;
2306    char key_flag;
2307
2308    lsquic_buf_clear(nonce_c);
2309    lsquic_buf_clear(hkdf_input);
2310    if (enc_session->have_key == 0)
2311    {
2312        lsquic_buf_append(hkdf_input, "QUIC key expansion\0", 18 + 1); // Add a 0x00 */
2313        key_flag = 'I';
2314    }
2315    else
2316    {
2317        lsquic_buf_append(hkdf_input, "QUIC forward secure key expansion\0", 33 + 1); // Add a 0x00 */
2318        key_flag = 'F';
2319    }
2320
2321    c255_gen_share_key(enc_session->priv_key,
2322                       enc_session->hs_ctx.pubs,
2323                       (unsigned char *)shared_key_c);
2324    if (is_client)
2325    {
2326        if (enc_session->have_key == 0)
2327        {
2328            ctx_c_key = &enc_session->enc_ctx_i;
2329            ctx_s_key = &enc_session->dec_ctx_i;
2330            c_iv = (unsigned char *) enc_session->enc_key_nonce_i;
2331            s_iv = (unsigned char *) enc_session->dec_key_nonce_i;
2332            c_key_bin = enc_session->enc_key_i;
2333            s_key_bin = enc_session->dec_key_i;
2334        }
2335        else
2336        {
2337            ctx_c_key = &enc_session->enc_ctx_f;
2338            ctx_s_key = &enc_session->dec_ctx_f;
2339            c_iv = (unsigned char *) enc_session->enc_key_nonce_f;
2340            s_iv = (unsigned char *) enc_session->dec_key_nonce_f;
2341        }
2342    }
2343    else
2344    {
2345        if (enc_session->have_key == 0)
2346        {
2347            ctx_c_key = &enc_session->dec_ctx_i;
2348            ctx_s_key = &enc_session->enc_ctx_i;
2349            c_iv = (unsigned char *) enc_session->dec_key_nonce_i;
2350            s_iv = (unsigned char *) enc_session->enc_key_nonce_i;
2351            c_key_bin = enc_session->dec_key_i;
2352            s_key_bin = enc_session->enc_key_i;
2353        }
2354        else
2355        {
2356            ctx_c_key = &enc_session->dec_ctx_f;
2357            ctx_s_key = &enc_session->enc_ctx_f;
2358            c_iv = (unsigned char *) enc_session->dec_key_nonce_f;
2359            s_iv = (unsigned char *) enc_session->enc_key_nonce_f;
2360        }
2361    }
2362
2363    LSQ_DEBUG("export_key_material c255_gen_share_key %s",
2364              get_bin_str(shared_key_c, 32, 512));
2365
2366    lsquic_buf_append(hkdf_input, (const char *) enc_session->cid.idbuf,
2367                                                        enc_session->cid.len);
2368    lsquic_buf_append(hkdf_input, lsquic_str_cstr(chlo), lsquic_str_len(chlo)); /* CHLO msg */
2369    if (is_client)
2370    {
2371        lsquic_buf_append(hkdf_input, lsquic_str_cstr(&enc_session->info->scfg),
2372                       lsquic_str_len(&enc_session->info->scfg)); /* scfg msg */
2373    }
2374    else
2375    {
2376        lsquic_buf_append(hkdf_input,
2377                (const char *) enc_session->server_config->lsc_scfg->scfg,
2378                       enc_session->server_config->lsc_scfg->info.scfg_len);
2379    }
2380    lsquic_buf_append(hkdf_input, lsquic_str_cstr(enc_session->cert_ptr),
2381                   lsquic_str_len(enc_session->cert_ptr));
2382    LSQ_DEBUG("export_key_material hkdf_input %s",
2383              get_bin_str(lsquic_buf_begin(hkdf_input),
2384                          (size_t)lsquic_buf_size(hkdf_input), 512));
2385
2386    /* then need to use the salts and the shared_key_* to get the real aead key */
2387    lsquic_buf_append(nonce_c, (const char *) enc_session->hs_ctx.nonc, 32);
2388    lsquic_buf_append(nonce_c, lsquic_str_cstr(&enc_session->ssno),
2389                   lsquic_str_len(&enc_session->ssno));
2390    LSQ_DEBUG("export_key_material nonce %s",
2391              get_bin_str(lsquic_buf_begin(nonce_c),
2392                          (size_t)lsquic_buf_size(nonce_c), 512));
2393
2394    export_key_material(shared_key_c, 32,
2395                        (unsigned char *)lsquic_buf_begin(nonce_c), lsquic_buf_size(nonce_c),
2396                        (unsigned char *)lsquic_buf_begin(hkdf_input),
2397                        lsquic_buf_size(hkdf_input),
2398                        aes128_key_len, c_key,
2399                        aes128_key_len, s_key,
2400                        aes128_iv_len, c_iv,
2401                        aes128_iv_len, s_iv,
2402                        sub_key);
2403
2404    setup_aead_ctx(ctx_c_key, c_key, aes128_key_len, c_key_bin);
2405    setup_aead_ctx(ctx_s_key, s_key, aes128_key_len, s_key_bin);
2406
2407
2408    lsquic_buf_destroy(nonce_c);
2409    lsquic_buf_destroy(hkdf_input);
2410
2411    LSQ_DEBUG("***export_key_material '%c' c_key: %s", key_flag,
2412              get_bin_str(c_key, aes128_key_len, 512));
2413    LSQ_DEBUG("***export_key_material '%c' s_key: %s", key_flag,
2414              get_bin_str(s_key, aes128_key_len, 512));
2415    LSQ_DEBUG("***export_key_material '%c' c_iv: %s", key_flag,
2416              get_bin_str(c_iv, aes128_iv_len, 512));
2417    LSQ_DEBUG("***export_key_material '%c' s_iv: %s", key_flag,
2418              get_bin_str(s_iv, aes128_iv_len, 512));
2419    LSQ_DEBUG("***export_key_material '%c' subkey: %s", key_flag,
2420              get_bin_str(sub_key, 32, 512));
2421}
2422
2423
2424/* 0 Match */
2425static int cached_certs_match(c_cert_item_t *item,
2426                                        lsquic_str_t **certs, int count)
2427{
2428    int i;
2429    if (!item || item->count != count)
2430        return -1;
2431
2432    for (i=0; i<count; ++i)
2433    {
2434        if (lsquic_str_bcmp(certs[i], &item->crts[i]) != 0)
2435            return -1;
2436    }
2437
2438    return 0;
2439}
2440
2441
2442static const char *
2443he2str (enum handshake_error he)
2444{
2445    switch (he)
2446    {
2447    case DATA_NOT_ENOUGH:   return "DATA_NOT_ENOUGH";
2448    case HS_ERROR:          return "HS_ERROR";
2449    case HS_SHLO:           return "HS_SHLO";
2450    case HS_1RTT:           return "HS_1RTT";
2451    case HS_SREJ:           return "HS_SREJ";
2452    case HS_DELAYED:        return "HS_DELAYED";
2453    case HS_PK_OFFLOAD:     return "HS_PK_OFFLOAD";
2454    default:
2455        assert(0);          return "<unknown enum value>";
2456    }
2457}
2458
2459
2460/* NOT packet, just the frames-data */
2461/* return rtt number:
2462 *      0 OK
2463 *      DATA_NOT_ENOUGH(-2) for not enough data,
2464 *      DATA_FORMAT_ERROR(-1) all other errors
2465 */
2466static int
2467lsquic_enc_session_handle_chlo_reply (enc_session_t *enc_session_p,
2468                                                const uint8_t *data, int len)
2469{
2470    struct lsquic_enc_session *const enc_session = enc_session_p;
2471    uint32_t head_tag;
2472    int ret, got_srej;
2473    lsquic_session_cache_info_t *info = enc_session->info;
2474    c_cert_item_t *cert_item = enc_session->cert_item;
2475
2476    /* FIXME get the number first */
2477    lsquic_str_t **out_certs = NULL;
2478    size_t out_certs_count = 0, i;
2479
2480    ret = parse_hs(enc_session, data, len, &head_tag);
2481    if (ret)
2482        goto end;
2483
2484    got_srej = head_tag == QTAG_SREJ;
2485    switch (head_tag)
2486    {
2487    case QTAG_SREJ:
2488        if (enc_session->es_flags & ES_RECV_SREJ)
2489        {
2490            LSQ_DEBUG("received second SREJ: handshake failed");
2491            ret = -1;
2492            goto end;
2493        }
2494        enc_session->es_flags |= ES_RECV_SREJ;
2495        /* fall-through */
2496    case QTAG_REJ:
2497        enc_session->hsk_state = HSK_CHLO_REJ;
2498        enc_session->es_flags |= ES_RECV_REJ;
2499        break;
2500    case QTAG_SHLO:
2501        enc_session->hsk_state = HSK_COMPLETED;
2502        EV_LOG_HSK_COMPLETED(&enc_session->cid);
2503        if (!(enc_session->es_flags & ES_RECV_REJ))
2504            EV_LOG_ZERO_RTT(&enc_session->cid);
2505        break;
2506    default:
2507        ret = 1;    /* XXX Why 1? */
2508        goto end;
2509    }
2510
2511    if (info->scfg_flag == 1)
2512    {
2513        ret = parse_hs(enc_session, (uint8_t *)lsquic_str_cstr(&info->scfg),
2514                       lsquic_str_len(&info->scfg), &head_tag);
2515
2516        /* After handled, set the length to 0 to avoid do it again*/
2517        enc_session->info->scfg_flag = 2;
2518        if (ret)
2519            goto end;
2520
2521        if (got_srej)
2522        {
2523            if (lsquic_str_len(&enc_session->info->sstk))
2524                ret = HS_SREJ;
2525            else
2526            {
2527                LSQ_DEBUG("expected STK in SREJ message from the server");
2528                ret = -1;
2529            }
2530            goto end;
2531        }
2532
2533        if (lsquic_str_len(&enc_session->hs_ctx.crt) > 0)
2534        {
2535            out_certs_count = get_certs_count(&enc_session->hs_ctx.crt);
2536            if (out_certs_count > 0)
2537            {
2538                out_certs = malloc(out_certs_count * sizeof(lsquic_str_t *));
2539                if (!out_certs)
2540                {
2541                    ret = -1;
2542                    goto end;
2543                }
2544
2545                for (i=0; i<out_certs_count; ++i)
2546                    out_certs[i] = lsquic_str_new(NULL, 0);
2547
2548                ret = handle_chlo_reply_verify_prof(enc_session, out_certs,
2549                                            &out_certs_count,
2550                                            (cert_item ? cert_item->crts : NULL),
2551                                            (cert_item ? cert_item->count : 0));
2552                if (ret == 0)
2553                {
2554                    if (out_certs_count > 0)
2555                    {
2556                        if (cached_certs_match(cert_item, out_certs,
2557                                                        out_certs_count) != 0)
2558                        {
2559                            cert_item = make_c_cert_item(out_certs,
2560                                                            out_certs_count);
2561                            enc_session->cert_item = cert_item;
2562                            enc_session->cert_ptr = &cert_item->crts[0];
2563                        }
2564                    }
2565                }
2566                for (i=0; i<out_certs_count; ++i)
2567                    lsquic_str_delete(out_certs[i]);
2568                free(out_certs);
2569
2570                if (ret)
2571                    goto end;
2572            }
2573        }
2574    }
2575
2576    if (enc_session->hsk_state == HSK_COMPLETED)
2577    {
2578        determine_keys(enc_session , 1);
2579        enc_session->have_key = 3;
2580    }
2581
2582  end:
2583    LSQ_DEBUG("lsquic_enc_session_handle_chlo_reply called, buf in %d, return %d.", len, ret);
2584    EV_LOG_CONN_EVENT(&enc_session->cid, "%s returning %s", __func__,
2585                                                                he2str(ret));
2586    return ret;
2587}
2588
2589
2590/** stk = 16 bytes IP ( V4 is 4 bytes, will add 12 byes 0 )
2591 *      + 8 bytes time
2592 *      + 36 bytes random bytes (24 bytes can be reserved for other using)
2593 *  then stk first 48 byte will be encrypted with AES128-GCM
2594 *  when encrypting, the salt is the last 12 bytes
2595 */
2596#ifdef NDEBUG
2597static
2598#endif
2599void
2600gen_stk (lsquic_server_config_t *server_config, const struct sockaddr *ip_addr,
2601         uint64_t tm, unsigned char stk_out[STK_LENGTH])
2602{
2603    unsigned char stk[STK_LENGTH + 16];
2604    size_t out_len = STK_LENGTH + 16;
2605
2606    memset(stk, 0 , 24);
2607    if (AF_INET == ip_addr->sa_family)
2608        memcpy(stk, &((struct sockaddr_in *)ip_addr)->sin_addr.s_addr, 4);
2609    else
2610        memcpy(stk, &((struct sockaddr_in6 *)ip_addr)->sin6_addr, 16);
2611    memcpy(stk + 16, &tm, 8);
2612    rand_bytes(stk + 24, STK_LENGTH - 24 - 12);
2613    rand_bytes(stk_out + STK_LENGTH - 12, 12);
2614    aes_aead_enc(&server_config->lsc_stk_ctx, NULL, 0, stk_out + STK_LENGTH - 12, 12, stk,
2615                 STK_LENGTH - 12 - 12, stk_out, &out_len);
2616}
2617
2618
2619/* server using */
2620#ifdef NDEBUG
2621static
2622#endif
2623enum hsk_failure_reason
2624verify_stk0 (lsquic_server_config_t *server_config,
2625             const struct sockaddr *ip_addr, uint64_t tm, lsquic_str_t *stk,
2626             unsigned secs_since_stk_generated)
2627{
2628    uint64_t tm0, exp;
2629    unsigned char *const stks = (unsigned char *) lsquic_str_buf(stk);
2630    unsigned char stk_out[STK_LENGTH];
2631    size_t out_len = STK_LENGTH;
2632
2633    if (lsquic_str_len(stk) < STK_LENGTH)
2634        return HFR_SRC_ADDR_TOKEN_INVALID;
2635
2636    int ret = aes_aead_dec(&server_config->lsc_stk_ctx, NULL, 0,
2637                           stks + STK_LENGTH - 12, 12, stks,
2638                           STK_LENGTH - 12, stk_out, &out_len);
2639    if (ret != 0)
2640    {
2641        LSQ_DEBUG("***verify_stk decrypted failed.");
2642        return HFR_SRC_ADDR_TOKEN_DECRYPTION;
2643    }
2644
2645    if (AF_INET == ip_addr->sa_family)
2646    {
2647        if (memcmp(stk_out, &((struct sockaddr_in *)ip_addr)->sin_addr.s_addr, 4) != 0)
2648        {
2649            LSQ_DEBUG("***verify_stk for ipv4 failed.");
2650            return HFR_SRC_ADDR_TOKEN_DIFFERENT_IP_ADDRESS;
2651        }
2652    }
2653    else
2654    {
2655        if (memcmp(stk_out, &((struct sockaddr_in6 *)ip_addr)->sin6_addr, 16) != 0)
2656        {
2657            LSQ_DEBUG("***verify_stk for ipv6 failed.");
2658            return HFR_SRC_ADDR_TOKEN_DIFFERENT_IP_ADDRESS;
2659        }
2660    }
2661
2662    memcpy((void *)&tm0, stk_out + 16, 8);
2663    if (tm < tm0)
2664    {
2665        LSQ_DEBUG("***verify_stk timestamp is in the future.");
2666        return HFR_SRC_ADDR_TOKEN_CLOCK_SKEW;
2667    }
2668
2669    if (secs_since_stk_generated)
2670        exp = tm0 + secs_since_stk_generated;
2671    else
2672        exp = server_config->lsc_scfg->info.expy;
2673
2674    if (tm > server_config->lsc_scfg->info.expy /* XXX this check does not seem needed */ ||
2675                                                        tm0 > exp)
2676    {
2677        LSQ_DEBUG("***verify_stk stk expired");
2678        return HFR_SRC_ADDR_TOKEN_EXPIRED;
2679    }
2680
2681    LSQ_DEBUG("***verify_stk pass.");
2682    return HFR_HANDSHAKE_OK;
2683}
2684
2685
2686/* 0, verified, other fail */
2687#ifdef NDEBUG
2688static
2689#endif
2690enum hsk_failure_reason
2691verify_stk (enc_session_t *enc_session_p,
2692               const struct sockaddr *ip_addr, uint64_t tm, lsquic_str_t *stk)
2693{
2694    struct lsquic_enc_session *const enc_session = enc_session_p;
2695    if (lsquic_str_len(&enc_session->sstk) > 0)
2696    {
2697        ESHIST_APPEND(enc_session, ESHE_HAS_SSTK);
2698        if (0 == lsquic_str_bcmp(&enc_session->sstk, &enc_session->hs_ctx.stk))
2699            return HFR_HANDSHAKE_OK;
2700        else
2701            return HFR_SRC_ADDR_TOKEN_INVALID;
2702    }
2703    else
2704        return verify_stk0(enc_session->server_config, ip_addr, tm, stk, 0);
2705}
2706
2707
2708#if 0   /* unused */
2709enum AEAD_TYPE determineaead()
2710{
2711    return AEAD_AESG;
2712}
2713
2714
2715enum KENX_TYPE determinekexs()
2716{
2717    /* only support C255 now */
2718    return KENX_C255;
2719}
2720
2721
2722#endif /* 0 */
2723
2724static uint64_t combine_path_id_pack_num(uint8_t path_id, uint64_t pack_num)
2725{
2726    uint64_t v = ((uint64_t)path_id << 56) | pack_num;
2727    return v;
2728}
2729
2730
2731#   define IS_SERVER(session) ((session)->es_flags & ES_SERVER)
2732
2733static int
2734verify_packet_hash (const struct lsquic_enc_session *enc_session,
2735    enum lsquic_version version, const unsigned char *buf, size_t *header_len,
2736    size_t data_len, unsigned char *buf_out, size_t max_out_len,
2737    size_t *out_len)
2738{
2739    uint8_t md[HS_PKT_HASH_LENGTH];
2740    uint128 hash;
2741    int ret;
2742
2743    if (data_len < HS_PKT_HASH_LENGTH)
2744        return -1;
2745
2746    if (!enc_session || (IS_SERVER(enc_session)))
2747        hash = fnv1a_128_3(buf, *header_len,
2748                    buf + *header_len + HS_PKT_HASH_LENGTH,
2749                    data_len - HS_PKT_HASH_LENGTH,
2750                    (unsigned char *) "Client", 6);
2751    else
2752        hash = fnv1a_128_3(buf, *header_len,
2753                    buf + *header_len + HS_PKT_HASH_LENGTH,
2754                    data_len - HS_PKT_HASH_LENGTH,
2755                    (unsigned char *) "Server", 6);
2756
2757    serialize_fnv128_short(hash, md);
2758    ret = memcmp(md, buf + *header_len, HS_PKT_HASH_LENGTH);
2759    if(ret == 0)
2760    {
2761        *header_len += HS_PKT_HASH_LENGTH;
2762        *out_len = data_len - HS_PKT_HASH_LENGTH;
2763        if (max_out_len < *header_len + *out_len)
2764            return -1;
2765
2766        memcpy(buf_out, buf, *header_len + *out_len);
2767        return 0;
2768    }
2769    else
2770        return -1;
2771}
2772
2773
2774static enum enc_level
2775decrypt_packet (struct lsquic_enc_session *enc_session, uint8_t path_id,
2776                uint64_t pack_num, unsigned char *buf, size_t *header_len,
2777                size_t data_len, unsigned char *buf_out, size_t max_out_len,
2778                size_t *out_len)
2779{
2780    int ret;
2781    /* Comment: 12 = sizeof(dec_key_iv] 4 + sizeof(pack_num) 8 */
2782    uint8_t nonce[12];
2783    uint64_t path_id_packet_number;
2784    EVP_AEAD_CTX *key = NULL;
2785    int try_times = 0;
2786    enum enc_level enc_level;
2787
2788    path_id_packet_number = combine_path_id_pack_num(path_id, pack_num);
2789    memcpy(buf_out, buf, *header_len);
2790    do
2791    {
2792        if (enc_session->have_key == 3 && try_times == 0)
2793        {
2794            key = enc_session->dec_ctx_f;
2795            memcpy(nonce, enc_session->dec_key_nonce_f, 4);
2796            LSQ_DEBUG("decrypt_packet using 'F' key...");
2797            enc_level = ENC_LEV_FORW;
2798        }
2799        else
2800        {
2801            key = enc_session->dec_ctx_i;
2802            memcpy(nonce, enc_session->dec_key_nonce_i, 4);
2803            LSQ_DEBUG("decrypt_packet using 'I' key...");
2804            enc_level = ENC_LEV_INIT;
2805        }
2806        memcpy(nonce + 4, &path_id_packet_number,
2807               sizeof(path_id_packet_number));
2808
2809        *out_len = data_len;
2810        ret = aes_aead_dec(key,
2811                           buf, *header_len,
2812                           nonce, 12,
2813                           buf + *header_len, data_len,
2814                           buf_out + *header_len, out_len);
2815
2816        if (ret != 0)
2817            ++try_times;
2818        else
2819        {
2820            if (enc_session->peer_have_final_key == 0 &&
2821                enc_session->have_key == 3 &&
2822                try_times == 0)
2823            {
2824                LSQ_DEBUG("!!!decrypt_packet find peer have final key.");
2825                enc_session->peer_have_final_key = 1;
2826                EV_LOG_CONN_EVENT(&enc_session->cid, "settled on private key "
2827                    "'%c' after %d tries (packet number %"PRIu64")",
2828                    key == enc_session->dec_ctx_f ? 'F' : 'I',
2829                    try_times, pack_num);
2830            }
2831            break;
2832        }
2833    }
2834    while (try_times < 2);
2835
2836    LSQ_DEBUG("***decrypt_packet %s.", (ret == 0 ? "succeed" : "failed"));
2837    return ret == 0 ? enc_level : (enum enc_level) -1;
2838}
2839
2840
2841static int
2842lsquic_enc_session_have_key_gt_one (enc_session_t *enc_session_p)
2843{
2844    struct lsquic_enc_session *const enc_session = enc_session_p;
2845    return enc_session && enc_session->have_key > 1;
2846}
2847
2848
2849/* The size of `buf' is *header_len plus data_len.  The two parts of the
2850 * buffer correspond to the header and the payload of incoming QUIC packet.
2851 */
2852static enum enc_level
2853lsquic_enc_session_decrypt (enc_session_t *enc_session_p,
2854               enum lsquic_version version,
2855               uint8_t path_id, uint64_t pack_num,
2856               unsigned char *buf, size_t *header_len, size_t data_len,
2857               unsigned char *diversification_nonce,
2858               unsigned char *buf_out, size_t max_out_len, size_t *out_len)
2859{
2860    struct lsquic_enc_session *const enc_session = enc_session_p;
2861    /* Client: got SHLO which should have diversification_nonce */
2862    if (diversification_nonce && enc_session && enc_session->have_key == 1)
2863    {
2864        determine_diversification_key(enc_session, diversification_nonce, 1);
2865        enc_session->have_key = 2;
2866    }
2867
2868    if (lsquic_enc_session_have_key_gt_one(enc_session))
2869        return decrypt_packet(enc_session, path_id, pack_num, buf,
2870                        header_len, data_len, buf_out, max_out_len, out_len);
2871    else if (0 == verify_packet_hash(enc_session, version, buf, header_len,
2872                                     data_len, buf_out, max_out_len, out_len))
2873        return ENC_LEV_CLEAR;
2874    else
2875        return -1;
2876}
2877
2878
2879static enum dec_packin
2880gquic_decrypt_packet (enc_session_t *enc_session_p,
2881                            struct lsquic_engine_public *enpub,
2882                            const struct lsquic_conn *lconn,
2883                            struct lsquic_packet_in *packet_in)
2884{
2885    size_t header_len, data_len;
2886    enum enc_level enc_level;
2887    size_t out_len = 0;
2888    unsigned char *copy = lsquic_mm_get_packet_in_buf(&enpub->enp_mm, 1370);
2889    if (!copy)
2890    {
2891        LSQ_WARN("cannot allocate memory to copy incoming packet data");
2892        return DECPI_NOMEM;
2893    }
2894
2895    assert(packet_in->pi_data);
2896    header_len = packet_in->pi_header_sz;
2897    data_len   = packet_in->pi_data_sz - packet_in->pi_header_sz;
2898    enc_level = lsquic_enc_session_decrypt(enc_session_p,
2899                        lconn->cn_version, 0,
2900                        packet_in->pi_packno, packet_in->pi_data,
2901                        &header_len, data_len,
2902                        lsquic_packet_in_nonce(packet_in),
2903                        copy, 1370, &out_len);
2904    if ((enum enc_level) -1 == enc_level)
2905    {
2906        lsquic_mm_put_packet_in_buf(&enpub->enp_mm, copy, 1370);
2907        EV_LOG_CONN_EVENT(&lconn->cn_cid, "could not decrypt packet %"PRIu64,
2908                                                        packet_in->pi_packno);
2909        return DECPI_BADCRYPT;
2910    }
2911
2912    assert(header_len + out_len <= 1370);
2913    if (packet_in->pi_flags & PI_OWN_DATA)
2914        lsquic_mm_put_packet_in_buf(&enpub->enp_mm, packet_in->pi_data, 1370);
2915    packet_in->pi_data = copy;
2916    packet_in->pi_flags |= PI_OWN_DATA | PI_DECRYPTED
2917                        | (enc_level << PIBIT_ENC_LEV_SHIFT);
2918    packet_in->pi_header_sz = header_len;
2919    packet_in->pi_data_sz   = out_len + header_len;
2920    EV_LOG_CONN_EVENT(&lconn->cn_cid, "decrypted packet %"PRIu64,
2921                                                    packet_in->pi_packno);
2922    return DECPI_OK;
2923}
2924
2925
2926static enum enc_level
2927gquic_encrypt_buf (struct lsquic_enc_session *enc_session,
2928               enum lsquic_version version,
2929               uint8_t path_id, uint64_t pack_num,
2930               const unsigned char *header, size_t header_len,
2931               const unsigned char *data, size_t data_len,
2932               unsigned char *buf_out, size_t max_out_len, size_t *out_len,
2933               int is_hello)
2934{
2935    uint8_t md[HS_PKT_HASH_LENGTH];
2936    uint128 hash;
2937    int ret;
2938    enum enc_level enc_level;
2939    int is_chlo = (is_hello && ((IS_SERVER(enc_session)) == 0));
2940    int is_shlo = (is_hello && (IS_SERVER(enc_session)));
2941
2942    /* Comment: 12 = sizeof(dec_key_iv] 4 + sizeof(pack_num) 8 */
2943    uint8_t nonce[12];
2944    uint64_t path_id_packet_number;
2945    EVP_AEAD_CTX *key;
2946
2947    if (enc_session)
2948        LSQ_DEBUG("%s: hsk_state: %d", __func__, enc_session->hsk_state);
2949    else
2950        LSQ_DEBUG("%s: enc_session is not set", __func__);
2951
2952    if (!enc_session || enc_session->have_key == 0 || is_chlo)
2953    {
2954        *out_len = header_len + data_len + HS_PKT_HASH_LENGTH;
2955        if (max_out_len < *out_len)
2956            return -1;
2957
2958        if (!enc_session || (IS_SERVER(enc_session)))
2959            hash = fnv1a_128_3(header, header_len, data, data_len,
2960                                        (unsigned char *) "Server", 6);
2961        else
2962            hash = fnv1a_128_3(header, header_len, data, data_len,
2963                                        (unsigned char *) "Client", 6);
2964
2965        serialize_fnv128_short(hash, md);
2966        memcpy(buf_out, header, header_len);
2967        memcpy(buf_out + header_len, md, HS_PKT_HASH_LENGTH);
2968        memcpy(buf_out + header_len + HS_PKT_HASH_LENGTH, data, data_len);
2969        return ENC_LEV_CLEAR;
2970    }
2971    else
2972    {
2973        if (enc_session->have_key != 3 || is_shlo ||
2974            ((IS_SERVER(enc_session)) &&
2975             enc_session->server_start_use_final_key == 0))
2976        {
2977            LSQ_DEBUG("lsquic_enc_session_encrypt using 'I' key...");
2978            key = enc_session->enc_ctx_i;
2979            memcpy(nonce, enc_session->enc_key_nonce_i, 4);
2980            if (is_shlo && enc_session->have_key == 3)
2981            {
2982                enc_session->server_start_use_final_key = 1;
2983            }
2984            enc_level = ENC_LEV_INIT;
2985        }
2986        else
2987        {
2988            LSQ_DEBUG("lsquic_enc_session_encrypt using 'F' key...");
2989            key = enc_session->enc_ctx_f;
2990            memcpy(nonce, enc_session->enc_key_nonce_f, 4);
2991            enc_level = ENC_LEV_FORW;
2992        }
2993        path_id_packet_number = combine_path_id_pack_num(path_id, pack_num);
2994        memcpy(nonce + 4, &path_id_packet_number,
2995               sizeof(path_id_packet_number));
2996
2997        memcpy(buf_out, header, header_len);
2998        *out_len = max_out_len - header_len;
2999
3000        ret = aes_aead_enc(key, header, header_len, nonce, 12, data,
3001                           data_len, buf_out + header_len, out_len);
3002        if (ret == 0)
3003        {
3004            *out_len += header_len;
3005            return enc_level;
3006        }
3007        else
3008            return -1;
3009    }
3010}
3011
3012
3013/* server */
3014/* out_len should have init value as the max length of out */
3015/* return -1 error, 0, SHLO, 1, RTT1, 2, RTT2, DELAYED */
3016static enum handshake_error
3017lsquic_enc_session_handle_chlo(enc_session_t *enc_session_p,
3018                                 enum lsquic_version version,
3019                                 const uint8_t *in, int in_len, time_t t,
3020                                 const struct sockaddr *peer,
3021                                 const struct sockaddr *local,
3022                                 uint8_t *out, size_t *out_len,
3023                                 uint8_t nonce[DNONC_LENGTH], int *nonce_set)
3024{
3025    struct lsquic_enc_session *const enc_session = enc_session_p;
3026    enum handshake_error rtt;
3027    int len;
3028    lsquic_server_config_t *server_config;
3029    const struct lsquic_engine_public *const enpub = enc_session->enpub;
3030    const struct lsquic_shared_hash_if *const shi = enpub->enp_shi;
3031    void *const shi_ctx = enpub->enp_shi_ctx;
3032
3033    server_config = get_valid_scfg(enpub);
3034    if (!server_config)
3035        return HS_ERROR;
3036    assert(server_config->lsc_scfg);
3037
3038    enc_session->server_config = server_config;
3039
3040    *nonce_set = 0;
3041    rtt = handle_chlo_frames_data(in, in_len, enc_session,
3042                    enpub->enp_lookup_cert, enpub->enp_cert_lu_ctx,
3043                    local, shi, shi_ctx, peer, t);
3044    if (rtt == HS_1RTT)
3045    {
3046
3047        LSQ_DEBUG("lsquic_enc_session_handle_chlo call gen_rej1_data");
3048        len = gen_rej1_data(enc_session, out, *out_len, peer, t);
3049        if (len == -2)
3050        {
3051            rtt = HS_PK_OFFLOAD;
3052            goto end;
3053        }
3054        if (len < 0)
3055        {
3056            rtt = HS_ERROR;
3057            goto end;
3058        }
3059        *out_len = len;
3060    }
3061    else if (rtt == HS_SHLO)
3062    {
3063        enc_session->have_key = 0;
3064        determine_keys(enc_session, 0);
3065        enc_session->have_key = 1;
3066
3067        if (lsquic_str_len(&enc_session->hs_ctx.stk) > 0)
3068        {
3069            shi->shi_delete(shi_ctx, lsquic_str_cstr(&enc_session->hs_ctx.stk),
3070                            lsquic_str_len(&enc_session->hs_ctx.stk));
3071        }
3072
3073        LSQ_DEBUG("lsquic_enc_session_handle_chlo call gen_shlo_data");
3074        len = gen_shlo_data(out, *out_len, enc_session, version, peer,
3075                                                                    t, nonce);
3076        if (len < 0)
3077        {
3078            rtt = HS_ERROR;
3079            goto end;
3080        }
3081        *out_len = len;
3082        *nonce_set = 1;
3083
3084        determine_diversification_key(enc_session, nonce, 0);
3085        enc_session->have_key = 2;
3086        determine_keys(enc_session, 0);
3087        enc_session->have_key = 3;
3088
3089        enc_session->hsk_state = HSK_COMPLETED;
3090        LSQ_DEBUG("lsquic_enc_session_handle_chlo have_key 3 hsk_state HSK_COMPLETED.");
3091    }
3092
3093  end:
3094    EV_LOG_CONN_EVENT(&enc_session->cid, "%s returning %s", __func__,
3095                                                            he2str(rtt));
3096    return rtt;
3097}
3098
3099
3100static int
3101lsquic_enc_session_get_peer_option (enc_session_t *enc_session_p,
3102                                                                uint32_t tag)
3103{
3104    struct lsquic_enc_session *const enc_session = enc_session_p;
3105    switch (tag)
3106    {
3107    case QTAG_NSTP:
3108        return !!(enc_session->hs_ctx.opts & HOPT_NSTP);
3109    case QTAG_SREJ:
3110        return !!(enc_session->hs_ctx.opts & HOPT_SREJ);
3111    default:
3112        assert(0);
3113        return 0;
3114    }
3115}
3116
3117
3118/* Query a several parameters sent by the peer that are required by
3119 * connection.
3120 */
3121static int
3122lsquic_enc_session_get_peer_setting (enc_session_t *enc_session_p,
3123                                        uint32_t tag, uint32_t *val)
3124{
3125    struct lsquic_enc_session *const enc_session = enc_session_p;
3126    switch (tag)
3127    {
3128    case QTAG_TCID:
3129        if (enc_session->hs_ctx.set & HSET_TCID)
3130        {
3131            *val = enc_session->hs_ctx.tcid;
3132            return 0;
3133        }
3134        else
3135            return -1;
3136    case QTAG_SMHL:
3137        if (enc_session->hs_ctx.set & HSET_SMHL)
3138        {
3139            *val = enc_session->hs_ctx.smhl;
3140            return 0;
3141        }
3142        else
3143            return -1;
3144    case QTAG_IRTT:
3145        if (enc_session->hs_ctx.set & HSET_IRTT)
3146        {
3147            *val = enc_session->hs_ctx.irtt;
3148            return 0;
3149        }
3150        else
3151            return -1;
3152    }
3153
3154    /* XXX For the following values, there is no record which were present
3155     *     in CHLO or SHLO and which were not.  Assume that zero means that
3156     *     they weren't present.
3157     */
3158    if (IS_SERVER(enc_session))
3159        switch (tag)
3160        {
3161        case QTAG_CFCW:
3162            if (enc_session->hs_ctx.scfcw)
3163            {
3164                *val = enc_session->hs_ctx.scfcw;
3165                return 0;
3166            }
3167            else
3168                return -1;
3169        case QTAG_SFCW:
3170            if (enc_session->hs_ctx.ssfcw)
3171            {
3172                *val = enc_session->hs_ctx.ssfcw;
3173                return 0;
3174            }
3175            else
3176                return -1;
3177        case QTAG_MIDS:
3178            if (enc_session->hs_ctx.smids)
3179            {
3180                *val = enc_session->hs_ctx.smids;
3181                return 0;
3182            }
3183            else
3184                return -1;
3185        default:
3186            return -1;
3187        }
3188    else
3189        switch (tag)
3190        {
3191        case QTAG_CFCW:
3192            if (enc_session->hs_ctx.cfcw)
3193            {
3194                *val = enc_session->hs_ctx.cfcw;
3195                return 0;
3196            }
3197            else
3198                return -1;
3199        case QTAG_SFCW:
3200            if (enc_session->hs_ctx.sfcw)
3201            {
3202                *val = enc_session->hs_ctx.sfcw;
3203                return 0;
3204            }
3205            else
3206                return -1;
3207        case QTAG_MIDS:
3208            if (enc_session->hs_ctx.mids)
3209            {
3210                *val = enc_session->hs_ctx.mids;
3211                return 0;
3212            }
3213            else
3214                return -1;
3215        default:
3216            return -1;
3217        }
3218}
3219
3220
3221static const char *
3222lsquic_enc_session_cipher (enc_session_t *enc_session_p)
3223{
3224    return LN_aes_128_gcm; /* TODO: get this string from enc_session */
3225}
3226
3227
3228static int
3229lsquic_enc_session_keysize (enc_session_t *enc_session_p)
3230{
3231    return 128 /* bits */ / 8; /* TODO: get this info from enc_session */
3232}
3233
3234
3235static int
3236lsquic_enc_session_alg_keysize (enc_session_t *enc_session_p)
3237{
3238    return 16; /* TODO: get this info from enc_session */
3239}
3240
3241
3242#if LSQUIC_KEEP_ENC_SESS_HISTORY
3243static void
3244lsquic_get_enc_hist (enc_session_t *enc_session_p,
3245                                        char buf[(1 << ESHIST_BITS) + 1])
3246{
3247    struct lsquic_enc_session *const enc_session = enc_session_p;
3248    const unsigned hist_idx = ESHIST_MASK & enc_session->es_hist_idx;
3249    if (enc_session->es_hist_buf[hist_idx] == ESHE_EMPTY)
3250        memcpy(buf, enc_session->es_hist_buf, hist_idx + 1);
3251    else
3252    {
3253        memcpy(buf, enc_session->es_hist_buf + hist_idx, sizeof(enc_session->es_hist_buf) - hist_idx);
3254        memcpy(buf + hist_idx, enc_session->es_hist_buf, hist_idx);
3255        buf[(1 << ESHIST_BITS)] = '\0';
3256    }
3257}
3258
3259
3260#endif
3261
3262
3263static const char *
3264lsquic_enc_session_get_ua (enc_session_t *enc_session_p)
3265{
3266    struct lsquic_enc_session *const enc_session = enc_session_p;
3267    if (enc_session && lsquic_str_len(&enc_session->hs_ctx.uaid) > 0)
3268        return lsquic_str_buf(&enc_session->hs_ctx.uaid);
3269    else
3270        return NULL;
3271}
3272
3273
3274#if LSQUIC_ENABLE_HANDSHAKE_DISABLE
3275static void
3276set_handshake_completed (struct lsquic_enc_session *enc_session)
3277{
3278    enc_session->hsk_state = HSK_COMPLETED;
3279}
3280
3281
3282#endif
3283
3284static const char *
3285lsquic_enc_session_get_sni (enc_session_t *enc_session_p)
3286{
3287    struct lsquic_enc_session *const enc_session = enc_session_p;
3288    return lsquic_str_cstr(&enc_session->hs_ctx.sni);
3289}
3290
3291
3292#ifndef NDEBUG
3293static uint8_t
3294lsquic_enc_session_have_key (enc_session_t *enc_session_p)
3295{
3296    struct lsquic_enc_session *const enc_session = enc_session_p;
3297    return enc_session->have_key;
3298}
3299
3300
3301static void
3302lsquic_enc_session_set_have_key (enc_session_t *enc_session_p, uint8_t val)
3303{
3304    struct lsquic_enc_session *const enc_session = enc_session_p;
3305    enc_session->have_key = val;
3306}
3307
3308
3309static const unsigned char *
3310lsquic_enc_session_get_enc_key_i (enc_session_t *enc_session_p)
3311{
3312    struct lsquic_enc_session *const enc_session = enc_session_p;
3313    return enc_session->enc_key_i;
3314}
3315
3316
3317static const unsigned char *
3318lsquic_enc_session_get_dec_key_i (enc_session_t *enc_session_p)
3319{
3320    struct lsquic_enc_session *const enc_session = enc_session_p;
3321    return enc_session->dec_key_i;
3322}
3323
3324
3325static const unsigned char *
3326lsquic_enc_session_get_enc_key_nonce_i (enc_session_t *enc_session_p)
3327{
3328    struct lsquic_enc_session *const enc_session = enc_session_p;
3329    return enc_session->enc_key_nonce_i;
3330}
3331
3332
3333static const unsigned char *
3334lsquic_enc_session_get_dec_key_nonce_i (enc_session_t *enc_session_p)
3335{
3336    struct lsquic_enc_session *const enc_session = enc_session_p;
3337    return enc_session->dec_key_nonce_i;
3338}
3339
3340
3341static const unsigned char *
3342lsquic_enc_session_get_enc_key_nonce_f (enc_session_t *enc_session_p)
3343{
3344    struct lsquic_enc_session *const enc_session = enc_session_p;
3345    return enc_session->enc_key_nonce_f;
3346}
3347
3348
3349static const unsigned char *
3350lsquic_enc_session_get_dec_key_nonce_f (enc_session_t *enc_session_p)
3351{
3352    struct lsquic_enc_session *const enc_session = enc_session_p;
3353    return enc_session->dec_key_nonce_f;
3354}
3355
3356
3357#endif  /* not defined NDEBUG */
3358
3359
3360static size_t
3361lsquic_enc_session_mem_used (enc_session_t *enc_session_p)
3362{
3363    struct lsquic_enc_session *const enc_session = enc_session_p;
3364    size_t size;
3365
3366    size = sizeof(*enc_session);
3367
3368    size += lsquic_str_len(&enc_session->chlo);
3369    size += lsquic_str_len(&enc_session->sstk);
3370    size += lsquic_str_len(&enc_session->ssno);
3371
3372    size += lsquic_str_len(&enc_session->hs_ctx.ccs);
3373    size += lsquic_str_len(&enc_session->hs_ctx.uaid);
3374    size += lsquic_str_len(&enc_session->hs_ctx.sni);
3375    size += lsquic_str_len(&enc_session->hs_ctx.ccrt);
3376    size += lsquic_str_len(&enc_session->hs_ctx.stk);
3377    size += lsquic_str_len(&enc_session->hs_ctx.sno);
3378    size += lsquic_str_len(&enc_session->hs_ctx.prof);
3379    size += lsquic_str_len(&enc_session->hs_ctx.csct);
3380    size += lsquic_str_len(&enc_session->hs_ctx.crt);
3381
3382    if (enc_session->info)
3383    {
3384        size += sizeof(*enc_session->info);
3385        size += lsquic_str_len(&enc_session->info->sstk);
3386        size += lsquic_str_len(&enc_session->info->scfg);
3387        size += lsquic_str_len(&enc_session->info->sni_key);
3388    }
3389
3390    /* TODO: calculate memory taken up by SSL stuff */
3391
3392    return size;
3393}
3394
3395
3396static int
3397lsquic_enc_session_verify_reset_token (enc_session_t *enc_session_p,
3398                                        const unsigned char *buf, size_t bufsz)
3399{
3400    struct lsquic_enc_session *const enc_session = enc_session_p;
3401    if (bufsz == SRST_LENGTH
3402            && 0 == (enc_session->es_flags & ES_SERVER)
3403            && (enc_session->hs_ctx.set & HSET_SRST)
3404            && 0 == memcmp(buf, enc_session->hs_ctx.srst, SRST_LENGTH))
3405        return 0;
3406    else
3407        return -1;
3408}
3409
3410
3411static int
3412lsquic_enc_session_did_zero_rtt_succeed (enc_session_t *enc_session_p)
3413{
3414    struct lsquic_enc_session *const enc_session = enc_session_p;
3415    return !(enc_session->es_flags & ES_RECV_REJ);
3416}
3417
3418
3419static int
3420lsquic_enc_session_is_zero_rtt_enabled (enc_session_t *enc_session_p)
3421{
3422    struct lsquic_enc_session *const enc_session = enc_session_p;
3423    return enc_session->info && enc_session->cert_item;
3424}
3425
3426
3427static ssize_t
3428gquic_really_encrypt_packet (struct lsquic_enc_session *enc_session,
3429    const struct lsquic_conn *lconn, struct lsquic_packet_out *packet_out,
3430    unsigned char *buf, size_t bufsz)
3431{
3432    int header_sz, is_hello_packet;
3433    enum enc_level enc_level;
3434    size_t packet_sz;
3435    unsigned char header_buf[GQUIC_MAX_PUBHDR_SZ];
3436
3437    header_sz = lconn->cn_pf->pf_gen_reg_pkt_header(lconn, packet_out,
3438                                            header_buf, sizeof(header_buf));
3439    if (header_sz < 0)
3440        return -1;
3441
3442    is_hello_packet = !!(packet_out->po_flags & PO_HELLO);
3443    enc_level = gquic_encrypt_buf(enc_session, lconn->cn_version, 0,
3444                packet_out->po_packno, header_buf, header_sz,
3445                packet_out->po_data, packet_out->po_data_sz,
3446                buf, bufsz, &packet_sz, is_hello_packet);
3447    if ((int) enc_level >= 0)
3448    {
3449        LSQ_DEBUG("encrypted packet %"PRIu64"; plaintext is %zu bytes, "
3450            "ciphertext is %zd bytes",
3451            packet_out->po_packno,
3452            lconn->cn_pf->pf_packout_size(lconn, packet_out) +
3453                                                packet_out->po_data_sz,
3454            packet_sz);
3455        lsquic_packet_out_set_enc_level(packet_out, enc_level);
3456        return packet_sz;
3457    }
3458    else
3459        return -1;
3460}
3461
3462
3463static STACK_OF(X509) *
3464lsquic_enc_session_get_server_cert_chain (enc_session_t *enc_session_p)
3465{
3466    struct lsquic_enc_session *const enc_session = enc_session_p;
3467    const struct c_cert_item_st *item;
3468    STACK_OF(X509) *chain;
3469    X509 *cert;
3470    int i;
3471
3472    if (enc_session->es_flags & ES_SERVER)
3473        return NULL;
3474    item = enc_session->cert_item;
3475    if (!item)
3476    {
3477        LSQ_WARN("could not find certificates for `%.*s'",
3478                            (int) lsquic_str_len(&enc_session->hs_ctx.sni),
3479                            lsquic_str_cstr(&enc_session->hs_ctx.sni));
3480        return NULL;
3481    }
3482
3483    chain = sk_X509_new_null();
3484    for (i = 0; i < item->count; ++i)
3485    {
3486        cert = bio_to_crt(lsquic_str_cstr(&item->crts[i]),
3487                                lsquic_str_len(&item->crts[i]), 0);
3488        if (cert)
3489            sk_X509_push(chain, cert);
3490        else
3491        {
3492            sk_X509_free(chain);
3493            return NULL;
3494        }
3495    }
3496
3497    return chain;
3498}
3499
3500
3501static void
3502maybe_dispatch_zero_rtt (enc_session_t *enc_session_p,
3503                struct lsquic_conn *lconn,
3504                void (*cb)(struct lsquic_conn *, const unsigned char *, size_t))
3505{
3506    struct lsquic_enc_session *const enc_session = enc_session_p;
3507    void *buf;
3508    size_t sz;
3509    int i;
3510
3511    if (!(enc_session->info && enc_session->cert_item && cb))
3512    {
3513        LSQ_DEBUG("no zero-rtt information or callback is not set");
3514        return;
3515    }
3516
3517    for (sz = 0, i = 0; i < enc_session->cert_item->count; ++i)
3518    {
3519        sz += sizeof(uint32_t);
3520        sz += lsquic_str_len(&enc_session->cert_item->crts[i]);
3521    }
3522    sz += sizeof(struct lsquic_zero_rtt_storage);
3523
3524    buf = malloc(sz);
3525    if (!buf)
3526    {
3527        LSQ_WARN("malloc failed: cannot allocate %zu bytes for zero-rtt", sz);
3528        return;
3529    }
3530
3531    lsquic_enc_session_serialize_zero_rtt(
3532        (struct lsquic_zero_rtt_storage *) buf, lconn->cn_version,
3533        enc_session->info, enc_session->cert_item);
3534
3535    cb(lconn, buf, sz);
3536    free(buf);
3537}
3538
3539
3540#if LSQUIC_ENABLE_HANDSHAKE_DISABLE
3541static ssize_t
3542just_copy_packet (const struct lsquic_conn *lconn,
3543                  const struct lsquic_packet_out *packet_out, unsigned char *buf,
3544                  size_t bufsz)
3545{
3546    int header_sz;
3547
3548    header_sz = lconn->cn_pf->pf_gen_reg_pkt_header(lconn, packet_out,
3549                                                                buf, bufsz);
3550    if (header_sz < 0)
3551        return -1;
3552
3553    if ((unsigned) header_sz + packet_out->po_data_sz > bufsz)
3554    {
3555        LSQ_WARN("packet too large (%d bytes) to encrypt",
3556                                        header_sz + packet_out->po_data_sz);
3557        return -1;
3558    }
3559
3560    memcpy(buf + header_sz, packet_out->po_data, packet_out->po_data_sz);
3561    return header_sz + packet_out->po_data_sz;
3562}
3563
3564
3565#endif
3566
3567
3568static enum enc_packout
3569gquic_encrypt_packet (enc_session_t *enc_session_p,
3570        const struct lsquic_engine_public *enpub,
3571        struct lsquic_conn *lconn, struct lsquic_packet_out *packet_out)
3572{
3573    struct lsquic_enc_session *const enc_session = enc_session_p;
3574    ssize_t enc_sz;
3575    size_t bufsz;
3576    unsigned sent_sz;
3577    unsigned char *buf;
3578    int ipv6;
3579
3580    bufsz = lconn->cn_pf->pf_packout_size(lconn, packet_out);
3581    if (bufsz > USHRT_MAX)
3582        return ENCPA_BADCRYPT;  /* To cause connection to close */
3583    ipv6 = NP_IS_IPv6(packet_out->po_path);
3584    buf = enpub->enp_pmi->pmi_allocate(enpub->enp_pmi_ctx,
3585                                packet_out->po_path->np_peer_ctx, bufsz, ipv6);
3586    if (!buf)
3587    {
3588        LSQ_DEBUG("could not allocate memory for outgoing packet of size %zd",
3589                                                                        bufsz);
3590        return ENCPA_NOMEM;
3591    }
3592
3593#if LSQUIC_ENABLE_HANDSHAKE_DISABLE
3594    if (getenv("LSQUIC_DISABLE_HANDSHAKE"))
3595    {
3596        enc_sz = just_copy_packet(lconn, packet_out, buf, bufsz);
3597        sent_sz = enc_sz + GQUIC_PACKET_HASH_SZ;
3598    }
3599    else
3600#endif
3601    {
3602        enc_sz = gquic_really_encrypt_packet(enc_session,
3603                                                lconn, packet_out, buf, bufsz);
3604        sent_sz = enc_sz;
3605    }
3606
3607    if (enc_sz < 0)
3608    {
3609        enpub->enp_pmi->pmi_return(enpub->enp_pmi_ctx,
3610                                packet_out->po_path->np_peer_ctx, buf, ipv6);
3611        return ENCPA_BADCRYPT;
3612    }
3613
3614    packet_out->po_enc_data    = buf;
3615    packet_out->po_enc_data_sz = enc_sz;
3616    packet_out->po_sent_sz     = sent_sz;
3617    packet_out->po_flags &= ~PO_IPv6;
3618    packet_out->po_flags |= PO_ENCRYPTED|PO_SENT_SZ|(ipv6 << POIPv6_SHIFT);
3619
3620    return ENCPA_OK;
3621}
3622
3623
3624#ifdef NDEBUG
3625const
3626#endif
3627struct enc_session_funcs_common lsquic_enc_session_common_gquic_1 =
3628{
3629    .esf_global_init    = lsquic_handshake_init,
3630    .esf_global_cleanup = lsquic_handshake_cleanup,
3631    .esf_cipher = lsquic_enc_session_cipher,
3632    .esf_keysize = lsquic_enc_session_keysize,
3633    .esf_alg_keysize = lsquic_enc_session_alg_keysize,
3634    .esf_get_sni = lsquic_enc_session_get_sni,
3635    .esf_encrypt_packet = gquic_encrypt_packet,
3636    .esf_decrypt_packet = gquic_decrypt_packet,
3637    .esf_tag_len = GQUIC_PACKET_HASH_SZ,
3638    .esf_get_server_cert_chain = lsquic_enc_session_get_server_cert_chain,
3639    .esf_verify_reset_token = lsquic_enc_session_verify_reset_token,
3640    .esf_did_zero_rtt_succeed = lsquic_enc_session_did_zero_rtt_succeed,
3641    .esf_is_zero_rtt_enabled = lsquic_enc_session_is_zero_rtt_enabled,
3642};
3643
3644
3645#ifdef NDEBUG
3646const
3647#endif
3648struct enc_session_funcs_gquic lsquic_enc_session_gquic_gquic_1 =
3649{
3650#if LSQUIC_KEEP_ENC_SESS_HISTORY
3651    .esf_get_hist       = lsquic_get_enc_hist,
3652#endif
3653    .esf_destroy = lsquic_enc_session_destroy,
3654    .esf_is_hsk_done = lsquic_enc_session_is_hsk_done,
3655    .esf_get_peer_setting = lsquic_enc_session_get_peer_setting,
3656    .esf_get_peer_option = lsquic_enc_session_get_peer_option,
3657    .esf_create_server = lsquic_enc_session_create_server,
3658    .esf_handle_chlo = lsquic_enc_session_handle_chlo,
3659    .esf_get_ua = lsquic_enc_session_get_ua,
3660    .esf_have_key_gt_one = lsquic_enc_session_have_key_gt_one,
3661#ifndef NDEBUG
3662    .esf_determine_diversification_key = determine_diversification_key,
3663    .esf_have_key = lsquic_enc_session_have_key,
3664    .esf_set_have_key = lsquic_enc_session_set_have_key,
3665    .esf_get_enc_key_i = lsquic_enc_session_get_enc_key_i,
3666    .esf_get_dec_key_i = lsquic_enc_session_get_dec_key_i,
3667    .esf_get_enc_key_nonce_i = lsquic_enc_session_get_enc_key_nonce_i,
3668    .esf_get_dec_key_nonce_i = lsquic_enc_session_get_dec_key_nonce_i,
3669    .esf_get_enc_key_nonce_f = lsquic_enc_session_get_enc_key_nonce_f,
3670    .esf_get_dec_key_nonce_f = lsquic_enc_session_get_dec_key_nonce_f,
3671#endif /* !defined(NDEBUG) */
3672#if LSQUIC_ENABLE_HANDSHAKE_DISABLE
3673    .esf_set_handshake_completed = set_handshake_completed,
3674#endif
3675    .esf_create_client = lsquic_enc_session_create_client,
3676    .esf_gen_chlo = lsquic_enc_session_gen_chlo,
3677    .esf_handle_chlo_reply = lsquic_enc_session_handle_chlo_reply,
3678    .esf_mem_used = lsquic_enc_session_mem_used,
3679    .esf_maybe_dispatch_zero_rtt = maybe_dispatch_zero_rtt,
3680    .esf_reset_cid = lsquic_enc_session_reset_cid,
3681};
3682
3683
3684typedef char reset_token_lengths_match[
3685                                SRST_LENGTH == IQUIC_SRESET_TOKEN_SZ ? 1 : -1];
3686
3687
3688