lsquic_crypto.c revision 50aadb33
1/* Copyright (c) 2017 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
12#include <zlib.h>
13
14#include "lsquic_types.h"
15#include "lsquic_crypto.h"
16#include "lsquic_alarmset.h"
17#include "lsquic_parse.h"
18#include "lsquic_util.h"
19#include "lsquic_str.h"
20
21#define LSQUIC_LOGGER_MODULE LSQLM_CRYPTO
22#include "lsquic_logger.h"
23
24
25static const char s_hs_signature[] = "QUIC CHLO and server config signature";
26static int crypto_inited = 0;
27
28
29void rand_bytes(void *data, int len)
30{
31    RAND_bytes(data, len);
32}
33
34
35uint64_t fnv1a_64(const uint8_t * data, int len)
36{
37    uint64_t hash = UINT64_C(14695981039346656037);
38    const uint8_t *end = data + len;
39    while(data < end)
40    {
41        hash ^= *data;
42        hash *= UINT64_C(1099511628211);
43        ++data;
44    }
45    return hash;
46}
47
48
49void fnv1a_64_s(const uint8_t * data, int len, char *md)
50{
51    uint64_t hash = fnv1a_64(data, len);
52    memcpy(md, (void *)&hash, 8);
53}
54
55
56#if defined( __x86_64 )||defined( __x86_64__ )
57
58static uint128 s_prime;
59static uint128 s_init_hash;
60
61
62static inline void make_uint128(uint128 *v, uint64_t hi, uint64_t lo)
63{
64    *v = hi;
65    *v <<= 64;
66    *v += lo;
67}
68
69
70void fnv1a_inc(uint128 *hash, const uint8_t *data, int len)
71{
72    const uint8_t* end = data + len;
73    while(data < end)
74    {
75        *hash = (*hash ^ (*data)) * s_prime;
76        ++data;
77    }
78}
79
80uint128 fnv1a_128_2(const uint8_t * data1, int len1, const uint8_t *data2, int len2)
81{
82    uint128 hash;
83    memcpy(&hash, &s_init_hash, 16);
84
85    fnv1a_inc(&hash, data1, len1);
86    if (data2)
87        fnv1a_inc(&hash, data2, len2);
88    return hash;
89}
90
91uint128 fnv1a_128_3(const uint8_t *data1, int len1,
92                      const uint8_t *data2, int len2,
93                      const uint8_t *data3, int len3)
94{
95    uint128 hash;
96    memcpy(&hash, &s_init_hash, 16);
97
98    fnv1a_inc(&hash, data1, len1);
99    fnv1a_inc(&hash, data2, len2);
100    fnv1a_inc(&hash, data3, len3);
101    return hash;
102}
103
104void fnv1a_128_2_s(const uint8_t * data1, int len1, const uint8_t * data2, int len2, uint8_t  *md)
105{
106    uint128 hash = fnv1a_128_2(data1, len1, data2, len2);
107    memcpy(md, (void *)&hash, 16);
108}
109
110/* HS_PKT_HASH_LENGTH bytes of md */
111void serialize_fnv128_short(uint128 v, uint8_t *md)
112{
113    memcpy(md, (void *)&v, 12);
114}
115
116#else
117uint128  *uint128_times(uint128 *v, const uint128 *factor)
118{
119    uint64_t a96 = v->hi_ >> 32;
120    uint64_t a64 = v->hi_ & 0xffffffffu;
121    uint64_t a32 = v->lo_ >> 32;
122    uint64_t a00 = v->lo_ & 0xffffffffu;
123    uint64_t b96 = factor->hi_ >> 32;
124    uint64_t b64 = factor->hi_ & 0xffffffffu;
125    uint64_t b32 = factor->lo_ >> 32;
126    uint64_t b00 = factor->lo_ & 0xffffffffu;
127    uint64_t tmp, lolo;
128    // multiply [a96 .. a00] x [b96 .. b00]
129    // terms higher than c96 disappear off the high side
130    // terms c96 and c64 are safe to ignore carry bit
131    uint64_t c96 = a96 * b00 + a64 * b32 + a32 * b64 + a00 * b96;
132    uint64_t c64 = a64 * b00 + a32 * b32 + a00 * b64;
133    v->hi_ = (c96 << 32) + c64;
134    v->lo_ = 0;
135
136    tmp = a32 * b00;
137    v->hi_ += tmp >> 32;
138    v->lo_ += tmp << 32;
139
140    tmp = a00 * b32;
141    v->hi_ += tmp >> 32;
142    v->lo_ += tmp << 32;
143
144    tmp = a00 * b00;
145    lolo = v->lo_ + tmp;
146    if (lolo < v->lo_)
147        ++v->hi_;
148    v->lo_ = lolo;
149
150    return v;
151}
152
153void fnv1a_inc(uint128 *hash, const uint8_t * data, int len)
154{
155    static const uint128 kPrime = {16777216, 315};
156    const uint8_t* end = data + len;
157    while(data < end)
158    {
159        hash->lo_ = (hash->lo_ ^ (uint64_t)*data);
160        uint128_times(hash, &kPrime);
161        ++data;
162    }
163}
164
165
166uint128 fnv1a_128_2(const uint8_t * data1, int len1, const uint8_t * data2, int len2)
167{
168    uint128 hash = {UINT64_C(7809847782465536322), UINT64_C(7113472399480571277)};
169    fnv1a_inc(&hash, data1, len1);
170    if (data2)
171        fnv1a_inc(&hash, data2, len2);
172    return hash;
173}
174
175
176uint128 fnv1a_128_3(const uint8_t * data1, int len1,
177                      const uint8_t * data2, int len2,
178                      const uint8_t * data3, int len3)
179{
180    uint128 hash = {UINT64_C(7809847782465536322), UINT64_C(7113472399480571277)};
181    fnv1a_inc(&hash, data1, len1);
182    fnv1a_inc(&hash, data2, len2);
183    fnv1a_inc(&hash, data3, len3);
184    return hash;
185}
186
187
188void fnv1a_128_2_s(const uint8_t * data1, int len1, const uint8_t * data2, int len2, uint8_t  *md)
189{
190    uint128 hash = fnv1a_128_2(data1, len1, data2, len2);
191    memcpy(md, (void *)&hash.lo_, 8);
192    memcpy(md + 8, (void *)&hash.hi_, 8);
193}
194
195/* HS_PKT_HASH_LENGTH bytes of md */
196void serialize_fnv128_short(uint128 v, uint8_t *md)
197{
198    assert(HS_PKT_HASH_LENGTH == 8 + 4);
199    memcpy(md, (void *)&v.lo_, 8);
200    memcpy(md + 8, (void *)&v.hi_, 4);
201}
202
203#endif
204
205uint128 fnv1a_128(const uint8_t * data, int len)
206{
207    return fnv1a_128_2(data, len , NULL, 0);
208}
209
210
211void fnv1a_128_s(const uint8_t * data, int len, uint8_t  *md)
212{
213    return fnv1a_128_2_s(data, len, NULL, 0, md);
214}
215
216
217/* packet data = header + MD + payload */
218/* return 0 if OK */
219int verify_hs_pkt(const uint8_t *pkg_data, size_t header_len, size_t pkg_len)
220{
221    uint8_t md[HS_PKT_HASH_LENGTH];
222    uint128 hash;
223    if (pkg_len < header_len + HS_PKT_HASH_LENGTH)
224        return -1;
225
226    hash = fnv1a_128_2(pkg_data, header_len, pkg_data + header_len + HS_PKT_HASH_LENGTH,
227                       pkg_len - header_len - HS_PKT_HASH_LENGTH);
228    serialize_fnv128_short(hash, md);
229    return memcmp(md, pkg_data + header_len, HS_PKT_HASH_LENGTH);
230}
231
232/* packet data = header + MD + payload, update the MD part */
233int update_hs_pkt_hash(uint8_t *pkg_data, int header_len, int pkg_len)
234{
235    uint8_t md[HS_PKT_HASH_LENGTH];
236    uint128 hash;
237    if (pkg_len < header_len + HS_PKT_HASH_LENGTH)
238        return -1;
239
240    hash = fnv1a_128_2(pkg_data, header_len, pkg_data + header_len + HS_PKT_HASH_LENGTH,
241                       pkg_len - header_len - HS_PKT_HASH_LENGTH);
242    serialize_fnv128_short(hash, md);
243    memcpy(pkg_data + header_len, md, HS_PKT_HASH_LENGTH);
244    return 0;
245}
246
247int get_hs_pkt_hash_len()
248{
249    return HS_PKT_HASH_LENGTH;
250}
251
252
253void sha256(const uint8_t *buf, int len, uint8_t *h)
254{
255    SHA256_CTX ctx;
256    SHA256_Init(&ctx);
257    SHA256_Update(&ctx, buf, len);
258    SHA256_Final(h, &ctx);
259}
260
261
262/* base on rfc 5869 with sha256, prk is 32 bytes*/
263void lshkdf_extract(const unsigned char *ikm, int ikm_len, const unsigned char *salt,
264                  int salt_len, unsigned char *prk)
265{
266#ifndef NDEBUG
267    unsigned char *out;
268    unsigned int out_len;
269    out =
270#endif
271        HMAC(EVP_sha256(), salt, salt_len, ikm, ikm_len, prk,
272#ifndef NDEBUG
273                                                              &out_len
274#else
275                                                              NULL
276#endif
277                                                                      );
278    assert(out);
279    assert(out_len == 32);
280}
281
282
283int lshkdf_expand(const unsigned char *prk, const unsigned char *info, int info_len,
284                uint16_t c_key_len, uint8_t *c_key,
285                uint16_t s_key_len, uint8_t *s_key,
286                uint16_t c_key_iv_len, uint8_t *c_key_iv,
287                uint16_t s_key_iv_len, uint8_t *s_key_iv,
288                uint16_t sub_key_len, uint8_t *sub_key)
289{
290    const int SHA256LEN = 32;
291    int L = c_key_len + s_key_len + c_key_iv_len + s_key_iv_len + sub_key_len;
292    int N = (L + SHA256LEN - 1) / SHA256LEN;
293    unsigned char *p_org;
294    uint8_t *buf;
295    unsigned char *p;
296    unsigned char T[SHA256LEN + 1];
297    int T_len = 0;
298    int i;
299    uint8_t *pb;
300
301    p_org = malloc(N * SHA256LEN);
302    if (!p_org)
303        return -1;
304
305    buf = malloc(SHA256LEN + info_len + 13);
306    if (!buf)
307    {
308        free(p_org);
309        return -1;
310    }
311
312    p = p_org;
313
314    for (i = 1; i <= N; ++i)
315    {
316        pb = buf;
317        if (T_len > 0)
318        {
319            memcpy(pb, T, T_len);
320            pb += T_len;
321        }
322
323        memcpy(pb, info, info_len);
324        pb += info_len;
325        *pb = i;
326        ++pb;
327
328        HMAC(EVP_sha256(), prk, SHA256LEN, buf, pb - buf, T, NULL);
329        if (i != N)
330            T_len = SHA256LEN;
331        else
332            T_len = L - (N - 1) * SHA256LEN;
333
334        memcpy(p, T, T_len);
335        p += T_len;
336    }
337
338    free(buf);
339
340    p = p_org;
341    if (c_key_len)
342    {
343        memcpy(c_key, p, c_key_len);
344        p += c_key_len;
345    }
346    if (s_key_len)
347    {
348        memcpy(s_key, p, s_key_len);
349        p += s_key_len;
350    }
351    if (c_key_iv_len)
352    {
353        memcpy(c_key_iv, p, c_key_iv_len);
354        p += c_key_iv_len;
355    }
356    if (s_key_iv_len)
357    {
358        memcpy(s_key_iv, p, s_key_iv_len);
359        p += s_key_iv_len;
360    }
361    if (sub_key_len && sub_key)
362    {
363        memcpy(sub_key, p, sub_key_len);
364        p += sub_key_len;
365    }
366
367    free(p_org);
368    return 0;
369}
370
371
372int export_key_material_simple(unsigned char *ikm, uint32_t ikm_len,
373                        unsigned char *salt, int salt_len,
374                        char *label, uint32_t label_len,
375                        const uint8_t *context, uint32_t context_len,
376                        uint8_t *key, uint16_t key_len)
377{
378    unsigned char prk[32];
379    int info_len;
380    uint8_t *info = NULL;
381    info = (uint8_t *)malloc(label_len + 1 + sizeof(uint32_t) + context_len);
382    if (!info)
383        return -1;
384
385    lshkdf_extract(ikm, ikm_len, salt, salt_len, prk);
386    memcpy(info, label, label_len);
387    info[label_len] = 0x00;
388    info_len = label_len + 1;
389    memcpy(info + info_len, &context_len, sizeof(uint32_t));
390    info_len += sizeof(uint32_t);
391    memcpy(info + info_len, context, context_len);
392    info_len += context_len;
393    lshkdf_expand(prk, info, info_len, key_len, key,
394                0, NULL, 0, NULL,0, NULL, 0, NULL);
395    free(info);
396    return 0;
397}
398
399
400int export_key_material(const unsigned char *ikm, uint32_t ikm_len,
401                        const unsigned char *salt, int salt_len,
402                        const unsigned char *context, uint32_t context_len,
403                        uint16_t c_key_len, uint8_t *c_key,
404                        uint16_t s_key_len, uint8_t *s_key,
405                        uint16_t c_key_iv_len, uint8_t *c_key_iv,
406                        uint16_t s_key_iv_len, uint8_t *s_key_iv,
407                        uint8_t *sub_key)
408{
409    unsigned char prk[32];
410    uint16_t sub_key_len = ikm_len;
411
412    lshkdf_extract(ikm, ikm_len, salt, salt_len, prk);
413    lshkdf_expand(prk, context, context_len, c_key_len, c_key,
414                s_key_len, s_key, c_key_iv_len, c_key_iv, s_key_iv_len,
415                s_key_iv, sub_key_len, sub_key);
416    return 0;
417}
418
419void c255_get_pub_key(unsigned char *priv_key, unsigned char pub_key[32])
420{
421    X25519_public_from_private(pub_key, priv_key);
422}
423
424
425int c255_gen_share_key(unsigned char *priv_key, unsigned char *peer_pub_key, unsigned char *shared_key)
426{
427    return X25519(shared_key, priv_key, peer_pub_key);
428}
429
430
431
432/* AEAD nonce is always zero */
433/* return 0 for OK */
434int aes_aead_enc(EVP_AEAD_CTX *key,
435              const uint8_t *ad, size_t ad_len,
436              const uint8_t *nonce, size_t nonce_len,
437              const uint8_t *plain, size_t plain_len,
438              uint8_t *cypher, size_t *cypher_len)
439{
440    int ret = 0;
441    size_t max_out_len;
442    max_out_len = *cypher_len;//plain_len + EVP_AEAD_max_overhead(aead_);
443    assert(*cypher_len >= max_out_len);
444
445    LSQ_DEBUG("***aes_aead_enc data %s", get_bin_str(plain, plain_len, 40));
446    ret = EVP_AEAD_CTX_seal(key, cypher, cypher_len, max_out_len,
447                            nonce, nonce_len, plain, plain_len, ad, ad_len);
448//     LSQ_DEBUG("***aes_aead_enc nonce: %s", get_bin_str(nonce, nonce_len));
449//     LSQ_DEBUG("***aes_aead_enc AD: %s", get_bin_str(ad, ad_len));
450//     LSQ_DEBUG("***aes_aead_enc return %d", (ret ? 0 : -1));
451    if (ret)
452    {
453        LSQ_DEBUG("***aes_aead_enc succeed, cypher content %s",
454                  get_bin_str(cypher, *cypher_len, 40));
455        return 0;
456    }
457    else
458    {
459        LSQ_DEBUG("***aes_aead_enc failed.");
460        return -1;
461    }
462}
463
464
465/* return 0 for OK */
466int aes_aead_dec(EVP_AEAD_CTX *key,
467              const uint8_t *ad, size_t ad_len,
468              const uint8_t *nonce, size_t nonce_len,
469              const uint8_t *cypher, size_t cypher_len,
470              uint8_t *plain, size_t *plain_len)
471{
472    int ret = 0;
473    size_t max_out_len = *plain_len;
474    assert(max_out_len >= cypher_len);
475
476    LSQ_DEBUG("***aes_aead_dec data %s", get_bin_str(cypher, cypher_len, 40));
477
478
479    ret = EVP_AEAD_CTX_open(key, plain, plain_len, max_out_len,
480                            nonce, nonce_len, cypher, cypher_len, ad, ad_len);
481
482//    LSQ_DEBUG("***aes_aead_dec nonce: %s", get_bin_str(nonce, nonce_len));
483//    LSQ_DEBUG("***aes_aead_dec AD: %s", get_bin_str(ad, ad_len));
484//    LSQ_DEBUG("***aes_aead_dec return %d", (ret ? 0 : -1));
485    if (ret)
486    {
487        LSQ_DEBUG("***aes_aead_dec succeed, plain content %s",
488              get_bin_str(plain, *plain_len, 20));
489        return 0;
490    }
491    else
492    {
493        LSQ_DEBUG("***aes_aead_dec failed.");
494        return -1;
495    }
496}
497
498/* aes 128, 16 bytes */
499int aes_get_key_length()
500{
501    return 16;
502}
503
504void gen_nonce_s(char *buf, int length)
505{
506    rand_bytes(buf, length);
507}
508
509/* 32 bytes client nonce with 4 bytes tm, 8 bytes orbit */
510void gen_nonce_c(unsigned char *buf, uint64_t orbit)
511{
512    time_t tm = time(NULL);
513    unsigned char *p = buf;
514    memcpy(p, &tm, 4);
515    p += 4;
516    memcpy(p, &orbit, 8);
517    p += 8;
518    rand_bytes(p, 20);
519    p += 20;
520}
521
522
523EVP_PKEY *PEM_to_key(const char *buf, int len)
524{
525    RSA *rsa = NULL;
526    EVP_PKEY *key = EVP_PKEY_new();
527    BIO *bio = BIO_new_mem_buf(buf, len);
528    if (!bio || !key)
529        return NULL;
530
531    rsa = PEM_read_bio_RSAPrivateKey(bio, &rsa, NULL, NULL);
532    if (!rsa)
533        return NULL;
534
535    EVP_PKEY_assign_RSA(key, rsa);
536    return key;
537}
538
539
540/* type 0 DER, 1: PEM */
541X509 *bio_to_crt(const void *buf, int len, int type)
542{
543    X509 *crt = NULL;
544    BIO *bio = BIO_new_mem_buf(buf, len);
545    if (bio == NULL)
546        return NULL;
547
548    if (type == 0)
549        crt = d2i_X509_bio(bio, NULL);
550    else
551        crt = PEM_read_bio_X509(bio, &crt, 0 , NULL);
552    BIO_free(bio);
553    return crt;
554}
555
556
557int read_rsa_priv_key(const uint8_t *buf, int len, EVP_PKEY *pkey)
558{
559
560    RSA *rsa = RSA_private_key_from_bytes(buf, len);
561    if (!rsa)
562        return -1;
563
564    return EVP_PKEY_assign_RSA(pkey, rsa);
565}
566
567
568int gen_prof(const uint8_t *chlo_data, size_t chlo_data_len,
569             const uint8_t *scfg_data, uint32_t scfg_data_len,
570             const EVP_PKEY *priv_key, uint8_t *buf, size_t *buf_len)
571{
572    uint8_t chlo_hash[32] = {0};
573    size_t chlo_hash_len = 32; /* SHA256 */
574    EVP_MD_CTX sign_context;
575    EVP_PKEY_CTX* pkey_ctx = NULL;
576
577    sha256(chlo_data, chlo_data_len, chlo_hash);
578    EVP_MD_CTX_init(&sign_context);
579    if (!EVP_DigestSignInit(&sign_context, &pkey_ctx, EVP_sha256(), NULL, (EVP_PKEY *)priv_key))
580        return -1;
581
582    EVP_PKEY_CTX_set_rsa_padding(pkey_ctx, RSA_PKCS1_PSS_PADDING);
583    EVP_PKEY_CTX_set_rsa_pss_saltlen(pkey_ctx, -1);
584
585    if (!EVP_DigestSignUpdate(&sign_context, s_hs_signature, sizeof(s_hs_signature)) ||
586        !EVP_DigestSignUpdate(&sign_context, (const uint8_t*)(&chlo_hash_len), 4) ||
587        !EVP_DigestSignUpdate(&sign_context, chlo_hash, chlo_hash_len) ||
588        !EVP_DigestSignUpdate(&sign_context, scfg_data, scfg_data_len))
589    {
590        return -1;
591    }
592
593    size_t len = 0;
594    if (!EVP_DigestSignFinal(&sign_context, NULL, &len)) {
595        return -1;
596    }
597
598    if (len > *buf_len)
599        return -2;
600    if (buf)
601        EVP_DigestSignFinal(&sign_context, buf, buf_len);
602
603    EVP_MD_CTX_cleanup(&sign_context);
604    return 0;
605}
606
607
608int verify_cert(const char *buf, int len)
609{
610    //X509_verify_cert();
611
612    return 0;
613}
614
615
616int verify_prof(const uint8_t *chlo_data, size_t chlo_data_len, lsquic_str_t * scfg,
617                const EVP_PKEY *pub_key, const uint8_t *buf, size_t len)
618{
619    return verify_prof0(chlo_data, chlo_data_len,
620                        (const uint8_t *)lsquic_str_buf(scfg),
621                        lsquic_str_len(scfg), pub_key, buf, len);
622}
623
624
625
626
627/* -3 internal error, -1: verify failed, 0: Success */
628int verify_prof0(const uint8_t *chlo_data, size_t chlo_data_len,
629                const uint8_t *scfg_data, uint32_t scfg_data_len,
630                const EVP_PKEY *pub_key, const uint8_t *buf, size_t len)
631{
632    uint8_t chlo_hash[32] = {0};
633    size_t chlo_hash_len = 32; /* SHA256 */
634    EVP_MD_CTX sign_context;
635    EVP_PKEY_CTX* pkey_ctx = NULL;
636    int ret = 0;
637    EVP_MD_CTX_init(&sign_context);
638    sha256(chlo_data, chlo_data_len, chlo_hash);
639
640    // discarding const below to quiet compiler warning on call to ssl library code
641    if (!EVP_DigestVerifyInit(&sign_context, &pkey_ctx, EVP_sha256(), NULL, (EVP_PKEY *)pub_key))
642        return -4;
643
644    EVP_PKEY_CTX_set_rsa_padding(pkey_ctx, RSA_PKCS1_PSS_PADDING);
645    EVP_PKEY_CTX_set_rsa_pss_saltlen(pkey_ctx, -1);
646
647
648    if (!EVP_DigestVerifyUpdate(&sign_context, s_hs_signature, sizeof(s_hs_signature)) ||
649        !EVP_DigestVerifyUpdate(&sign_context, (const uint8_t*)(&chlo_hash_len), 4) ||
650        !EVP_DigestVerifyUpdate(&sign_context, chlo_hash, chlo_hash_len) ||
651        !EVP_DigestVerifyUpdate(&sign_context, scfg_data, scfg_data_len))
652    {
653        return -3;  /* set to -3, to avoid same as "not enough data" -2 */
654    }
655
656    ret = EVP_DigestVerifyFinal(&sign_context, buf, len);
657    EVP_MD_CTX_cleanup(&sign_context);
658
659    if (ret == 1)
660        return 0; //OK
661    else
662        return -1;  //failed
663}
664
665
666void crypto_init(void *seed, int seed_len)
667{
668    if (crypto_inited)
669        return ;
670
671    //SSL_library_init();
672    CRYPTO_library_init();
673    RAND_seed(seed, seed_len);
674
675#if defined( __x86_64 )||defined( __x86_64__ )
676    make_uint128(&s_prime, 16777216, 315);
677    make_uint128(&s_init_hash, 7809847782465536322, 7113472399480571277);
678#endif
679
680    /* MORE .... */
681    crypto_inited = 1;
682}
683
684