1/* Copyright (c) 2017 - 2022 LiteSpeed Technologies Inc.  See LICENSE. */
2#include <assert.h>
3#include <string.h>
4
5#include <openssl/ssl.h>
6#include <openssl/crypto.h>
7#include <openssl/stack.h>
8#include <openssl/x509.h>
9#include <openssl/rand.h>
10#include <openssl/curve25519.h>
11#include <openssl/hkdf.h>
12#include <openssl/hmac.h>
13
14#include <zlib.h>
15#ifdef WIN32
16#include <vc_compat.h>
17#endif
18
19#include "lsquic_types.h"
20#include "lsquic_crypto.h"
21#include "lsquic_parse.h"
22#include "lsquic_util.h"
23#include "lsquic_str.h"
24
25#define LSQUIC_LOGGER_MODULE LSQLM_CRYPTO
26#include "lsquic_logger.h"
27
28
29static const char s_hs_signature[] = "QUIC CHLO and server config signature";
30static int crypto_inited = 0;
31
32
33uint64_t lsquic_fnv1a_64(const uint8_t * data, int len)
34{
35    uint64_t hash = UINT64_C(14695981039346656037);
36    const uint8_t *end = data + len;
37    while(data < end)
38    {
39        hash ^= *data;
40        hash *= UINT64_C(1099511628211);
41        ++data;
42    }
43    return hash;
44}
45
46
47void lsquic_fnv1a_64_s(const uint8_t * data, int len, char *md)
48{
49    uint64_t hash = lsquic_fnv1a_64(data, len);
50    memcpy(md, (void *)&hash, 8);
51}
52
53
54#if defined( __x86_64 )||defined( __x86_64__ )
55
56static uint128 s_prime;
57static uint128 s_init_hash;
58
59
60static inline void make_uint128(uint128 *v, uint64_t hi, uint64_t lo)
61{
62    *v = hi;
63    *v <<= 64;
64    *v += lo;
65}
66
67
68void lsquic_fnv1a_inc(uint128 *hash, const uint8_t *data, int len)
69{
70    const uint8_t* end = data + len;
71    while(data < end)
72    {
73        *hash = (*hash ^ (*data)) * s_prime;
74        ++data;
75    }
76}
77
78uint128 lsquic_fnv1a_128_3(const uint8_t *data1, int len1,
79                      const uint8_t *data2, int len2,
80                      const uint8_t *data3, int len3)
81{
82    uint128 hash;
83    memcpy(&hash, &s_init_hash, 16);
84
85    lsquic_fnv1a_inc(&hash, data1, len1);
86    lsquic_fnv1a_inc(&hash, data2, len2);
87    lsquic_fnv1a_inc(&hash, data3, len3);
88    return hash;
89}
90
91/* HS_PKT_HASH_LENGTH bytes of md */
92void lsquic_serialize_fnv128_short(uint128 v, uint8_t *md)
93{
94    memcpy(md, (void *)&v, 12);
95}
96
97#else
98uint128  *uint128_times(uint128 *v, const uint128 *factor)
99{
100    uint64_t a96 = v->hi_ >> 32;
101    uint64_t a64 = v->hi_ & 0xffffffffu;
102    uint64_t a32 = v->lo_ >> 32;
103    uint64_t a00 = v->lo_ & 0xffffffffu;
104    uint64_t b96 = factor->hi_ >> 32;
105    uint64_t b64 = factor->hi_ & 0xffffffffu;
106    uint64_t b32 = factor->lo_ >> 32;
107    uint64_t b00 = factor->lo_ & 0xffffffffu;
108    uint64_t tmp, lolo;
109    // multiply [a96 .. a00] x [b96 .. b00]
110    // terms higher than c96 disappear off the high side
111    // terms c96 and c64 are safe to ignore carry bit
112    uint64_t c96 = a96 * b00 + a64 * b32 + a32 * b64 + a00 * b96;
113    uint64_t c64 = a64 * b00 + a32 * b32 + a00 * b64;
114    v->hi_ = (c96 << 32) + c64;
115    v->lo_ = 0;
116
117    tmp = a32 * b00;
118    v->hi_ += tmp >> 32;
119    v->lo_ += tmp << 32;
120
121    tmp = a00 * b32;
122    v->hi_ += tmp >> 32;
123    v->lo_ += tmp << 32;
124
125    tmp = a00 * b00;
126    lolo = v->lo_ + tmp;
127    if (lolo < v->lo_)
128        ++v->hi_;
129    v->lo_ = lolo;
130
131    return v;
132}
133
134void lsquic_fnv1a_inc(uint128 *hash, const uint8_t * data, int len)
135{
136    static const uint128 kPrime = {16777216, 315};
137    const uint8_t* end = data + len;
138    while(data < end)
139    {
140        hash->lo_ = (hash->lo_ ^ (uint64_t)*data);
141        uint128_times(hash, &kPrime);
142        ++data;
143    }
144}
145
146
147uint128 lsquic_fnv1a_128_3(const uint8_t * data1, int len1,
148                      const uint8_t * data2, int len2,
149                      const uint8_t * data3, int len3)
150{
151    uint128 hash = {UINT64_C(7809847782465536322), UINT64_C(7113472399480571277)};
152    lsquic_fnv1a_inc(&hash, data1, len1);
153    lsquic_fnv1a_inc(&hash, data2, len2);
154    lsquic_fnv1a_inc(&hash, data3, len3);
155    return hash;
156}
157
158
159/* HS_PKT_HASH_LENGTH bytes of md */
160void lsquic_serialize_fnv128_short(uint128 v, uint8_t *md)
161{
162    assert(HS_PKT_HASH_LENGTH == 8 + 4);
163    memcpy(md, (void *)&v.lo_, 8);
164    memcpy(md + 8, (void *)&v.hi_, 4);
165}
166
167#endif
168
169
170static void sha256(const uint8_t *buf, int len, uint8_t *h)
171{
172    SHA256_CTX ctx;
173    SHA256_Init(&ctx);
174    SHA256_Update(&ctx, buf, len);
175    SHA256_Final(h, &ctx);
176}
177
178
179/* base on rfc 5869 with sha256, prk is 32 bytes*/
180void lshkdf_extract(const unsigned char *ikm, int ikm_len, const unsigned char *salt,
181                  int salt_len, unsigned char *prk)
182{
183#ifndef NDEBUG
184    unsigned char *out;
185    unsigned int out_len;
186    out =
187#endif
188        HMAC(EVP_sha256(), salt, salt_len, ikm, ikm_len, prk,
189#ifndef NDEBUG
190                                                              &out_len
191#else
192                                                              NULL
193#endif
194                                                                      );
195    assert(out);
196    assert(out_len == 32);
197}
198
199
200#define SHA256LEN   32
201int lshkdf_expand(const unsigned char *prk, const unsigned char *info, int info_len,
202                uint16_t c_key_len, uint8_t *c_key,
203                uint16_t s_key_len, uint8_t *s_key,
204                uint16_t c_key_iv_len, uint8_t *c_key_iv,
205                uint16_t s_key_iv_len, uint8_t *s_key_iv,
206                uint16_t sub_key_len, uint8_t *sub_key,
207                uint8_t *c_hp, uint8_t *s_hp)
208{
209    const unsigned L = c_key_len + s_key_len + c_key_iv_len + s_key_iv_len
210            + sub_key_len
211            + (c_hp ? c_key_len : 0)
212            + (s_hp ? s_key_len : 0)
213            ;
214    unsigned char *p;
215    unsigned char output[
216        EVP_MAX_KEY_LENGTH * 2  /* Keys */
217      + EVP_MAX_IV_LENGTH * 2   /* IVs */
218      + 32                      /* Subkey */
219      + EVP_MAX_KEY_LENGTH * 2  /* Header protection */
220    ];
221
222    assert((size_t) L <= sizeof(output));
223
224#ifndef NDEBUG
225    const int s =
226#endif
227    HKDF_expand(output, L, EVP_sha256(), prk, 32, info, info_len);
228    assert(s);
229    p = output;
230    if (c_key_len)
231    {
232        memcpy(c_key, p, c_key_len);
233        p += c_key_len;
234    }
235    if (s_key_len)
236    {
237        memcpy(s_key, p, s_key_len);
238        p += s_key_len;
239    }
240    if (c_key_iv_len)
241    {
242        memcpy(c_key_iv, p, c_key_iv_len);
243        p += c_key_iv_len;
244    }
245    if (s_key_iv_len)
246    {
247        memcpy(s_key_iv, p, s_key_iv_len);
248        p += s_key_iv_len;
249    }
250    if (sub_key_len && sub_key)
251    {
252        memcpy(sub_key, p, sub_key_len);
253        p += sub_key_len;
254    }
255    if (c_key_len && c_hp)
256    {
257        memcpy(c_hp, p, c_key_len);
258        p += c_key_len;
259    }
260    if (s_key_len && s_hp)
261    {
262        memcpy(s_hp, p, s_key_len);
263        p += s_key_len;
264    }
265    return 0;
266}
267
268
269#ifndef NDEBUG
270int lsquic_export_key_material_simple(unsigned char *ikm, uint32_t ikm_len,
271                        unsigned char *salt, int salt_len,
272                        char *label, uint32_t label_len,
273                        const uint8_t *context, uint32_t context_len,
274                        uint8_t *key, uint16_t key_len)
275{
276    unsigned char prk[32];
277    int info_len;
278    uint8_t *info = NULL;
279    info = (uint8_t *)malloc(label_len + 1 + sizeof(uint32_t) + context_len);
280    if (!info)
281        return -1;
282
283    lshkdf_extract(ikm, ikm_len, salt, salt_len, prk);
284    memcpy(info, label, label_len);
285    info[label_len] = 0x00;
286    info_len = label_len + 1;
287    memcpy(info + info_len, &context_len, sizeof(uint32_t));
288    info_len += sizeof(uint32_t);
289    memcpy(info + info_len, context, context_len);
290    info_len += context_len;
291    lshkdf_expand(prk, info, info_len, key_len, key,
292                0, NULL, 0, NULL,0, NULL, 0, NULL, NULL, NULL);
293    free(info);
294    return 0;
295}
296#endif
297
298
299int
300lsquic_export_key_material(const unsigned char *ikm, uint32_t ikm_len,
301                        const unsigned char *salt, int salt_len,
302                        const unsigned char *context, uint32_t context_len,
303                        uint16_t c_key_len, uint8_t *c_key,
304                        uint16_t s_key_len, uint8_t *s_key,
305                        uint16_t c_key_iv_len, uint8_t *c_key_iv,
306                        uint16_t s_key_iv_len, uint8_t *s_key_iv,
307                        uint8_t *sub_key, uint8_t *c_hp, uint8_t *s_hp)
308{
309    unsigned char prk[32];
310    uint16_t sub_key_len = ikm_len;
311
312    lshkdf_extract(ikm, ikm_len, salt, salt_len, prk);
313    lshkdf_expand(prk, context, context_len, c_key_len, c_key,
314                s_key_len, s_key, c_key_iv_len, c_key_iv, s_key_iv_len,
315                s_key_iv, sub_key_len, sub_key, c_hp, s_hp);
316    return 0;
317}
318
319void lsquic_c255_get_pub_key(unsigned char *priv_key, unsigned char pub_key[32])
320{
321    X25519_public_from_private(pub_key, priv_key);
322}
323
324
325int lsquic_c255_gen_share_key(unsigned char *priv_key, unsigned char *peer_pub_key, unsigned char *shared_key)
326{
327    return X25519(shared_key, priv_key, peer_pub_key);
328}
329
330
331
332/* AEAD nonce is always zero */
333/* return 0 for OK */
334int lsquic_aes_aead_enc(EVP_AEAD_CTX *key,
335              const uint8_t *ad, size_t ad_len,
336              const uint8_t *nonce, size_t nonce_len,
337              const uint8_t *plain, size_t plain_len,
338              uint8_t *cypher, size_t *cypher_len)
339{
340    int ret = 0;
341    size_t max_out_len;
342    max_out_len = *cypher_len;//plain_len + EVP_AEAD_max_overhead(aead_);
343    assert(*cypher_len >= max_out_len);
344
345    LSQ_DEBUG("***lsquic_aes_aead_enc data %s", lsquic_get_bin_str(plain, plain_len, 40));
346    ret = EVP_AEAD_CTX_seal(key, cypher, cypher_len, max_out_len,
347                            nonce, nonce_len, plain, plain_len, ad, ad_len);
348//     LSQ_DEBUG("***lsquic_aes_aead_enc nonce: %s", lsquic_get_bin_str(nonce, nonce_len));
349//     LSQ_DEBUG("***lsquic_aes_aead_enc AD: %s", lsquic_get_bin_str(ad, ad_len));
350//     LSQ_DEBUG("***lsquic_aes_aead_enc return %d", (ret ? 0 : -1));
351    if (ret)
352    {
353        LSQ_DEBUG("***lsquic_aes_aead_enc succeed, cypher content %s",
354                  lsquic_get_bin_str(cypher, *cypher_len, 40));
355        return 0;
356    }
357    else
358    {
359        LSQ_DEBUG("***lsquic_aes_aead_enc failed.");
360        return -1;
361    }
362}
363
364
365/* return 0 for OK */
366int lsquic_aes_aead_dec(EVP_AEAD_CTX *key,
367              const uint8_t *ad, size_t ad_len,
368              const uint8_t *nonce, size_t nonce_len,
369              const uint8_t *cypher, size_t cypher_len,
370              uint8_t *plain, size_t *plain_len)
371{
372    int ret = 0;
373    size_t max_out_len = *plain_len;
374    assert(max_out_len >= cypher_len);
375
376    LSQ_DEBUG("***lsquic_aes_aead_dec data %s", lsquic_get_bin_str(cypher, cypher_len, 40));
377
378
379    ret = EVP_AEAD_CTX_open(key, plain, plain_len, max_out_len,
380                            nonce, nonce_len, cypher, cypher_len, ad, ad_len);
381
382//    LSQ_DEBUG("***lsquic_aes_aead_dec nonce: %s", lsquic_get_bin_str(nonce, nonce_len));
383//    LSQ_DEBUG("***lsquic_aes_aead_dec AD: %s", lsquic_get_bin_str(ad, ad_len));
384//    LSQ_DEBUG("***lsquic_aes_aead_dec return %d", (ret ? 0 : -1));
385    if (ret)
386    {
387        LSQ_DEBUG("***lsquic_aes_aead_dec succeed, plain content %s",
388              lsquic_get_bin_str(plain, *plain_len, 20));
389        return 0;
390    }
391    else
392    {
393        LSQ_DEBUG("***lsquic_aes_aead_dec failed.");
394        return -1;
395    }
396}
397
398/* 32 bytes client nonce with 4 bytes tm, 8 bytes orbit */
399void lsquic_gen_nonce_c(unsigned char *buf, uint64_t orbit)
400{
401    time_t tm = time(NULL);
402    unsigned char *p = buf;
403    memcpy(p, &tm, 4);
404    p += 4;
405    memcpy(p, &orbit, 8);
406    p += 8;
407    RAND_bytes(p, 20);
408    p += 20;
409}
410
411
412/* type 0 DER, 1: PEM */
413X509 *
414lsquic_bio_to_crt (const void *buf, int len, int type)
415{
416    X509 *crt = NULL;
417    BIO *bio = BIO_new_mem_buf(buf, len);
418    if (bio == NULL)
419        return NULL;
420
421    if (type == 0)
422        crt = d2i_X509_bio(bio, NULL);
423    else
424        crt = PEM_read_bio_X509(bio, &crt, 0 , NULL);
425    BIO_free(bio);
426    return crt;
427}
428
429
430int
431lsquic_gen_prof (const uint8_t *chlo_data, size_t chlo_data_len,
432             const uint8_t *scfg_data, uint32_t scfg_data_len,
433             const EVP_PKEY *priv_key, uint8_t *buf, size_t *buf_len)
434{
435    uint8_t chlo_hash[32] = {0};
436    size_t chlo_hash_len = 32; /* SHA256 */
437    EVP_MD_CTX sign_context;
438    EVP_PKEY_CTX* pkey_ctx = NULL;
439
440    sha256(chlo_data, chlo_data_len, chlo_hash);
441    EVP_MD_CTX_init(&sign_context);
442    if (!EVP_DigestSignInit(&sign_context, &pkey_ctx, EVP_sha256(), NULL, (EVP_PKEY *)priv_key))
443        return -1;
444
445    EVP_PKEY_CTX_set_rsa_padding(pkey_ctx, RSA_PKCS1_PSS_PADDING);
446    EVP_PKEY_CTX_set_rsa_pss_saltlen(pkey_ctx, -1);
447
448    if (!EVP_DigestSignUpdate(&sign_context, s_hs_signature, sizeof(s_hs_signature)) ||
449        !EVP_DigestSignUpdate(&sign_context, (const uint8_t*)(&chlo_hash_len), 4) ||
450        !EVP_DigestSignUpdate(&sign_context, chlo_hash, chlo_hash_len) ||
451        !EVP_DigestSignUpdate(&sign_context, scfg_data, scfg_data_len))
452    {
453        return -1;
454    }
455
456    size_t len = 0;
457    if (!EVP_DigestSignFinal(&sign_context, NULL, &len)) {
458        return -1;
459    }
460
461    if (len > *buf_len)
462        return -2;
463    if (buf)
464        EVP_DigestSignFinal(&sign_context, buf, buf_len);
465
466    EVP_MD_CTX_cleanup(&sign_context);
467    return 0;
468}
469
470
471/* -3 internal error, -1: verify failed, 0: Success */
472static int
473verify_prof0 (const uint8_t *chlo_data, size_t chlo_data_len,
474                const uint8_t *scfg_data, uint32_t scfg_data_len,
475                const EVP_PKEY *pub_key, const uint8_t *buf, size_t len)
476{
477    uint8_t chlo_hash[32] = {0};
478    size_t chlo_hash_len = 32; /* SHA256 */
479    EVP_MD_CTX sign_context;
480    EVP_PKEY_CTX* pkey_ctx = NULL;
481    int ret = 0;
482    EVP_MD_CTX_init(&sign_context);
483    sha256(chlo_data, chlo_data_len, chlo_hash);
484
485    // discarding const below to quiet compiler warning on call to ssl library code
486    if (!EVP_DigestVerifyInit(&sign_context, &pkey_ctx, EVP_sha256(), NULL, (EVP_PKEY *)pub_key))
487        return -4;
488
489    EVP_PKEY_CTX_set_rsa_padding(pkey_ctx, RSA_PKCS1_PSS_PADDING);
490    EVP_PKEY_CTX_set_rsa_pss_saltlen(pkey_ctx, -1);
491
492
493    if (!EVP_DigestVerifyUpdate(&sign_context, s_hs_signature, sizeof(s_hs_signature)) ||
494        !EVP_DigestVerifyUpdate(&sign_context, (const uint8_t*)(&chlo_hash_len), 4) ||
495        !EVP_DigestVerifyUpdate(&sign_context, chlo_hash, chlo_hash_len) ||
496        !EVP_DigestVerifyUpdate(&sign_context, scfg_data, scfg_data_len))
497    {
498        return -3;  /* set to -3, to avoid same as "not enough data" -2 */
499    }
500
501    ret = EVP_DigestVerifyFinal(&sign_context, buf, len);
502    EVP_MD_CTX_cleanup(&sign_context);
503
504    if (ret == 1)
505        return 0; //OK
506    else
507        return -1;  //failed
508}
509
510
511int
512lsquic_verify_prof (const uint8_t *chlo_data, size_t chlo_data_len,
513    lsquic_str_t *scfg, const EVP_PKEY *pub_key, const uint8_t *buf, size_t len)
514{
515    return verify_prof0(chlo_data, chlo_data_len,
516                        (const uint8_t *)lsquic_str_buf(scfg),
517                        lsquic_str_len(scfg), pub_key, buf, len);
518}
519
520
521void
522lsquic_crypto_init (void)
523{
524    if (crypto_inited)
525        return ;
526
527    //SSL_library_init();
528    CRYPTO_library_init();
529    /* XXX Should we seed? If yes, wherewith? */ // RAND_seed(seed, seed_len);
530
531#if defined( __x86_64 )||defined( __x86_64__ )
532    make_uint128(&s_prime, 16777216, 315);
533    make_uint128(&s_init_hash, 7809847782465536322, 7113472399480571277);
534#endif
535
536    /* MORE .... */
537    crypto_inited = 1;
538}
539
540