aboutsummaryrefslogtreecommitdiff
path: root/crypto.c
blob: 4125f7bbdad16f68573ec64039834a7f0a3fc438 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
#include "crypto.h"
#include "trusted_module.h"
#include "test.h"

#include <string.h>

#include <openssl/hmac.h>
#include <openssl/sha.h>

/* return true iff [b, bprime] encloses a */
bool encloses(uint64_t b, uint64_t bprime, uint64_t a)
{
    /* zero is not allowed as an index */
    if(a == 0)
        return false;
    return (b < a && a < bprime) || (bprime <= b && b < a) || (a < bprime && bprime <= b);
}

hash_t hash_node(const struct iomt_node *node)
{
    return sha256(node, sizeof(*node));
}

hash_t hmac_sha256(const void *data, size_t datalen, const void *key, size_t keylen)
{
    hash_t h;
    HMAC(EVP_sha256(), key, keylen, data, datalen, h.hash, NULL);
    return h;
}

hash_t sha256(const void *data, size_t datalen)
{
    hash_t h;
    SHA256(data, datalen, h.hash);
    return h;
}

bool is_zero(hash_t u)
{
    /* constant-time comparison */
    volatile char c = 0;
    for(int i = 0; i < 32; ++i)
        c |= u.hash[i];

    return c == 0;
}

void dump_hash(hash_t u)
{
    for(int i = 0; i < 32; ++i)
        printf("%02x", u.hash[i]);
    printf("\n");
}

bool hash_equals(hash_t a, hash_t b)
{
    return !memcmp(a.hash, b.hash, 32);
}

hash_t hash_xor(hash_t a, hash_t b)
{
    for(int i = 0; i < 32; ++i)
        a.hash[i] ^= b.hash[i];
    return a;
}

/* NOTE: we fail to distinguish between intermediate and leaf
 * nodes, making a second-preimage attack possible */
/* order: 0: u is left, v is right, 1: u is right, v is left */
hash_t merkle_parent(hash_t u, hash_t v, int order)
{
    if(is_zero(u))
        return v;
    if(is_zero(v))
        return u;

    /* append and hash */
    SHA256_CTX ctx;
    hash_t h;

    SHA256_Init(&ctx);

    if(order != 0)
        SHA256_Update(&ctx, v.hash, 32);

    SHA256_Update(&ctx, u.hash, 32);

    if(order == 0)
        SHA256_Update(&ctx, v.hash, 32);

    SHA256_Final(h.hash, &ctx);

    return h;
}

/* Calculate the root of a Merkle tree given the leaf node v, and n
 * complementary nodes, ordered from the closest node (the sibling
 * leaf node at the bottom of the tree) to most distant (the opposite
 * half of the tree). orders[i] represents whether each complementarty
 * node is a left or right child, which is necessary to compute the
 * proper hash value at each stage. This is the f_bt() algorithm
 * described in Mohanty et al. */

/* orders: 0 indiciates that the complementary node is LEFT child, 1:
 * node is RIGHT child */
hash_t merkle_compute(hash_t node, const hash_t *comp, const int *orders, size_t n)
{
    hash_t parent = node;
    for(size_t i = 0; i < n; ++i)
        parent = merkle_parent(comp[i], parent, orders[i]);

    return parent;
}

/* Given a node's index, return the index of the parent in an array
 * representation of a binary tree. */
int bintree_parent(int idx)
{
    return (idx - ((idx & 1) ? 1 : 2)) / 2;
}

int bintree_sibling(int idx)
{
    return idx + ((idx & 1) ? 1 : -1);
}

/* Calculate the indicies of the complementary nodes to a
 * leaf. `leafidx' is 0 for the rightmost leaf node. This function
 * will return an array with a length equal to the number of levels in
 * the tree minus one (the root is not a complentary node). The 0th
 * element of the returned array will be the index of the immediate
 * sibling, while the 1st element will be the index of the
 * complementary node one level above the leaf node, and so on. Note
 * that logleaves = log2(nleaves). If `orders' is not NULL, the
 * function will additionally allocate an array of `logleaves' *
 * sizeof(int) with each element representing whether each
 * complementary node is a left or right child. */
int *bintree_complement(int leafidx, int logleaves, int **orders)
{
    int *comp = calloc(logleaves, sizeof(int));
    if(orders)
        *orders = calloc(logleaves, sizeof(int));

    /* true index of leaf */
    int idx = (1 << logleaves) - 1 + leafidx;

    /* progress up the tree */
    for(int i = 0; i < logleaves; ++i)
    {
        /* output index of sibling node */
        comp[i] = bintree_sibling(idx);

        /* we really don't need the orders array */
        if(orders)
            (*orders)[i] = idx & 1;

        /* find parent index and loop */
        idx = bintree_parent(idx);
    }

    return comp;
}

hash_t *merkle_complement(const struct iomt *tree, int leafidx, int **orders)
{
    int *compidx = bintree_complement(leafidx, tree->mt_logleaves, orders);
    hash_t *comp = lookup_nodes(tree->mt_nodes, compidx, tree->mt_logleaves);
    free(compidx);
    return comp;
}

int *bintree_ancestors(int leafidx, int logleaves)
{
    int *dep = calloc(logleaves, sizeof(int));

    int idx = (1 << logleaves) - 1 + leafidx;
    for(int i = 0; i < logleaves; ++i)
    {
        idx = bintree_parent(idx);
        dep[i] = idx;
    }

    return dep;
}

/* Shim to get only the orders */
int *bintree_complement_ordersonly(int leafidx, int logleaves)
{
    int *orders;
    free(bintree_complement(leafidx, logleaves, &orders));
    return orders;
}

/* Index-Ordered Merkle Tree routines: */
/* Calculate the value of all the nodes of the tree, given the IOMT
 * leaves in mt_leaves. Leaf count *must* be an integer power of two,
 * otherwise bad things will happen. This function should only need to
 * be called once, namely when the service provider is created. */
void iomt_fill(struct iomt *tree)
{
    for(int i = 0; i < tree->mt_leafcount; ++i)
    {
        uint64_t mt_idx = (1 << tree->mt_logleaves) - 1 + i;
        tree->mt_nodes[mt_idx] = hash_node(tree->mt_leaves + i);
    }
    /* now loop up from the bottom level, calculating the parent of
     * each pair of nodes */
    for(int i = tree->mt_logleaves - 1; i >= 0; --i)
    {
        uint64_t baseidx = (1 << i) - 1;
        for(int j = 0; j < (1 << i); ++j)
        {
            uint64_t mt_idx = baseidx + j;
            tree->mt_nodes[mt_idx] = merkle_parent(tree->mt_nodes[2 * mt_idx + 1],
                                                 tree->mt_nodes[2 * mt_idx + 2],
                                                 0);
        }
    }
}

/* A bit of a hack: our complement calculation returns the *indices*
 * complementary nodes, which is good because the indices are much
 * smaller than the actual nodes (which are 32 bytes each with
 * SHA-256). However, the trusted module requires an array of the
 * actual hash values of the complementary nodes. It would be optimal
 * to modify each function to take the array of all nodes in the tree
 * in addition to the complement indices, but this function will serve
 * as a shim in the meantime. */
hash_t *lookup_nodes(const hash_t *nodes, const int *indices, int n)
{
    hash_t *ret = calloc(n, sizeof(hash_t));
    for(int i = 0; i < n; ++i)
        ret[i] = nodes[indices[i]];
    return ret;
}

void restore_nodes(hash_t *nodes, const int *indices, const hash_t *values, int n)
{
    for(int i = 0; i < n; ++i)
        nodes[indices[i]] = values[i];
}

/* Update mt_nodes to reflect a change to a leaf node's
 * value. Optionally, if old_dep is not NULL, *old_dep will be made to
 * point to an array of length mt_logleaves that contains the old node
 * values (whose indices are returned by bintree_ancestors()). NOTE:
 * this function will NOT set the corresponding IOMT leaf; use
 * iomt_update_leaf_full for that. */
void merkle_update(struct iomt *tree, uint64_t leafidx, hash_t newval, hash_t **old_dep)
{
    if(old_dep)
        *old_dep = calloc(tree->mt_logleaves, sizeof(hash_t));

    uint64_t idx = (1 << tree->mt_logleaves) - 1 + leafidx;

    tree->mt_nodes[idx] = newval;
    for(int i = 0; i < tree->mt_logleaves; ++i)
    {
        /* find the merkle parent of the two children first */
        hash_t parent = merkle_parent(tree->mt_nodes[idx],
                                      tree->mt_nodes[bintree_sibling(idx)],
                                      (idx + 1) & 1);

        idx = bintree_parent(idx);

        /* save old value */
        if(old_dep)
            (*old_dep)[i] = tree->mt_nodes[idx];

        tree->mt_nodes[idx] = parent;
    }
}

/* find a node with given idx */
struct iomt_node *iomt_find_leaf(const struct iomt *tree, uint64_t idx)
{
    for(int i = 0; i < tree->mt_leafcount; ++i)
        if(idx == tree->mt_leaves[i].idx)
            return tree->mt_leaves + i;
    return NULL;
}

struct iomt_node *iomt_find_encloser(const struct iomt *tree, uint64_t idx)
{
    for(int i = 0; i < tree->mt_leafcount; ++i)
        if(encloses(tree->mt_leaves[i].idx, tree->mt_leaves[i].next_idx, idx))
            return tree->mt_leaves + i;
    return NULL;
}

struct iomt_node *iomt_find_leaf_or_encloser(const struct iomt *tree, uint64_t idx)
{
    for(int i = 0; i < tree->mt_leafcount; ++i)
    {
        if(tree->mt_leaves[i].idx == idx ||
           encloses(tree->mt_leaves[i].idx, tree->mt_leaves[i].next_idx, idx))
            return tree->mt_leaves + i;
    }
    return NULL;
}

void iomt_update(struct iomt *tree, uint64_t idx, hash_t newval)
{
    /* update the leaf first, then use merkle_update */
    struct iomt_node *leaf = iomt_find_leaf(tree, idx);
    leaf->val = newval;

    merkle_update(tree, leaf - tree->mt_leaves, hash_node(leaf), NULL);
}

void iomt_update_leaf_full(struct iomt *tree, uint64_t leafidx,
                           uint64_t new_idx, uint64_t new_next_idx, hash_t new_val)
{
    struct iomt_node *leaf = tree->mt_leaves + leafidx;
    leaf->idx = new_idx;
    leaf->next_idx = new_next_idx;
    leaf->val = new_val;

    merkle_update(tree, leafidx, hash_node(leaf), NULL);
}

void iomt_update_leaf_idx(struct iomt *tree, uint64_t leafidx,
                          uint64_t new_idx)
{
    struct iomt_node *leaf = tree->mt_leaves + leafidx;
    leaf->idx = new_idx;

    merkle_update(tree, leafidx, hash_node(leaf), NULL);
}

void iomt_update_leaf_nextidx(struct iomt *tree, uint64_t leafidx,
                              uint64_t new_next_idx)
{
    struct iomt_node *leaf = tree->mt_leaves + leafidx;
    leaf->next_idx = new_next_idx;

    merkle_update(tree, leafidx, hash_node(leaf), NULL);
}

void iomt_update_leaf_hash(struct iomt *tree, uint64_t leafidx,
                           hash_t new_val)
{
    struct iomt_node *leaf = tree->mt_leaves + leafidx;
    leaf->val = new_val;

    merkle_update(tree, leafidx, hash_node(leaf), NULL);
}

/* Create a merkle tree with 2^logleaves leaves, each initialized to a
 * zero leaf (not a placeholder!) */
struct iomt *iomt_new(int logleaves)
{
    struct iomt *tree = calloc(1, sizeof(struct iomt));
    tree->mt_leafcount = 1 << logleaves;
    tree->mt_logleaves = logleaves;
    tree->mt_leaves = calloc(tree->mt_leafcount, sizeof(struct iomt_node));

    tree->mt_nodes = calloc(2 * tree->mt_leafcount - 1, sizeof(hash_t));

    return tree;
}

struct iomt *iomt_dup(const struct iomt *tree)
{
    struct iomt *newtree = calloc(1, sizeof(struct iomt));
    newtree->mt_leafcount = tree->mt_leafcount;
    newtree->mt_logleaves = tree->mt_logleaves;

    newtree->mt_leaves = calloc(tree->mt_leafcount, sizeof(struct iomt_node));
    memcpy(newtree->mt_leaves, tree->mt_leaves, tree->mt_leafcount * sizeof(struct iomt_node));

    newtree->mt_nodes = calloc(2 * tree->mt_leafcount - 1, sizeof(hash_t));
    memcpy(newtree->mt_nodes, tree->mt_nodes, (2 * tree->mt_leafcount - 1) * sizeof(hash_t));

    return newtree;
}

/* TODO: error checking */
uint64_t read_u64(int (*read_fn)(void *userdata, void *buf, size_t len), void *userdata)
{
    uint64_t n;
    read_fn(userdata, &n, sizeof(n));
    return n;
}

void write_u64(void (*write_fn)(void *userdata, const void *data, size_t len),
               void *userdata, uint64_t n)
{
    write_fn(userdata, &n, sizeof(n));
}


void iomt_serialize(const struct iomt *tree,
                    void (*write_fn)(void *userdata, const void *data, size_t len),
                    void *userdata)
{
    /* leafcount isn't needed */
    if(tree)
    {
        write_u64(write_fn, userdata, tree->mt_logleaves);

        write_fn(userdata, tree->mt_nodes, sizeof(hash_t) * (2 * tree->mt_leafcount - 1));
        write_fn(userdata, tree->mt_leaves, sizeof(struct iomt_node) * tree->mt_leafcount);
    }
    else
        write_u64(write_fn, userdata, 0);
}

struct iomt *iomt_deserialize(int (*read_fn)(void *userdata, void *buf, size_t len),
                              void *userdata)
{
    uint64_t logleaves = read_u64(read_fn, userdata);
    if(!logleaves)
        return NULL;
    struct iomt *tree = iomt_new(logleaves);

    read_fn(userdata, tree->mt_nodes, sizeof(hash_t) * (2 * tree->mt_leafcount - 1));
    read_fn(userdata, tree->mt_leaves, sizeof(struct iomt_node) * tree->mt_leafcount);

    return tree;
}

void iomt_free(struct iomt *tree)
{
    if(tree)
    {
        free(tree->mt_nodes);
        free(tree->mt_leaves);
        free(tree);
    }
}

/* arbitrary */
#define FILELINES_LOGLEAVES 10

struct iomt *iomt_from_lines(const char *filename)
{
    struct iomt *tree = iomt_new(FILELINES_LOGLEAVES);

    FILE *f = fopen(filename, "r");

    SHA256_CTX ctx;
    SHA256_Init(&ctx);

    int c;
    uint64_t line = 0;

    while(c != EOF)
    {
        c = fgetc(f);

        char ch = c;

        if(c != EOF)
            SHA256_Update(&ctx, &ch, sizeof(ch));

        if(ch == '\n' || c == EOF)
        {
            hash_t linehash;
            SHA256_Final(linehash.hash, &ctx);

            /* set this leaf to loop around */
            iomt_update_leaf_full(tree, line, line + 1, 1, linehash);

            if(line > 0)
            {
                /* make previously inserted leaf point to this leaf */
                iomt_update_leaf_nextidx(tree, line - 1, line + 1);
            }

            line++;

            /* re-initialize for next line */
            SHA256_Init(&ctx);
        }
    }

    fclose(f);

    return tree;
}

struct hashstring hash_format(hash_t h, int n)
{
    struct hashstring ret;
    for(int i = 0; i < n; ++i)
    {
        sprintf(ret.str + 2 * i, "%02x", h.hash[i]);
    }
    return ret;
}

void iomt_dump(const struct iomt *tree)
{
    for(int i = 0; i < tree->mt_leafcount; ++i)
    {
        printf("(%lu, %s, %lu)%s",
               tree->mt_leaves[i].idx,
               hash_format(tree->mt_leaves[i].val, 4).str,
               tree->mt_leaves[i].next_idx,
               (i == tree->mt_leafcount - 1) ? "\n" : ", ");
    }
}

/* convert the first 8 bytes (little endian) to a 64-bit int */
uint64_t hash_to_u64(hash_t h)
{
    uint64_t ret = 0;
    for(int i = 0; i < 8; ++i)
        ret |= h.hash[i] << (i * 8);
    return ret;
}

hash_t u64_to_hash(uint64_t n)
{
    hash_t ret = hash_null;
    for(int i = 0; i < 8; ++i)
    {
        ret.hash[i] = n & 0xff;
        n >>= 8;
    }
    return ret;
}

/* simple XOR cipher, so encryption and decryption are symmetric */
hash_t crypt_secret(hash_t encrypted_secret,
                    uint64_t file_idx, uint64_t file_version,
                    const void *key, size_t keylen)
{
    hash_t pad; /* key = encrypted_secret ^ pad */
    HMAC_CTX *ctx = HMAC_CTX_new();
    HMAC_Init_ex(ctx,
                 key, keylen,
                 EVP_sha256(), NULL);

    /* potential endianness issue */
    HMAC_Update(ctx, (const unsigned char*)&file_idx, sizeof(file_idx));
    HMAC_Update(ctx, (const unsigned char*)&file_version, sizeof(file_version));

    HMAC_Final(ctx, pad.hash, NULL);
    HMAC_CTX_free(ctx);

    return hash_xor(encrypted_secret, pad);
}

/* These are all fixed-length fields, so we can safely append them and
 * forgo any HMAC. */
hash_t calc_lambda(hash_t gamma, const struct iomt *buildcode, const struct iomt *composefile, hash_t kf)
{
    hash_t buildcode_root = hash_null, composefile_root = hash_null;
    if(buildcode)
        buildcode_root = buildcode->mt_nodes[0];
    if(composefile)
        composefile_root = composefile->mt_nodes[0];

    SHA256_CTX ctx;
    hash_t h;

    SHA256_Init(&ctx);

    SHA256_Update(&ctx, gamma.hash, sizeof(gamma.hash));
    SHA256_Update(&ctx, buildcode_root.hash, sizeof(buildcode_root.hash));
    SHA256_Update(&ctx, composefile_root.hash, sizeof(composefile_root.hash));
    SHA256_Update(&ctx, kf.hash, sizeof(kf.hash));

    SHA256_Final(h.hash, &ctx);

    return h;
}

/* Generate a signed acknowledgement for successful completion of a
 * request. We append a zero byte to the user request and take the
 * HMAC. */
hash_t ack_sign(const struct tm_request *req, int nzeros, const void *key, size_t keylen)
{
    HMAC_CTX *ctx = HMAC_CTX_new();
    HMAC_Init_ex(ctx,
                 key, keylen,
                 EVP_sha256(), NULL);

    HMAC_Update(ctx, (const unsigned char*)req, sizeof(*req));

    unsigned char zero = 0;
    for(int i = 0; i < nzeros; ++i)
        HMAC_Update(ctx, &zero, 1);

    hash_t hmac;
    HMAC_Final(ctx, hmac.hash, NULL);
    HMAC_CTX_free(ctx);

    return hmac;
}

bool ack_verify(const struct tm_request *req,
                const void *secret, size_t secret_len,
                hash_t hmac)
{
    hash_t correct = ack_sign(req, 1, secret, secret_len);
    return hash_equals(hmac, correct);
}

void write_to_fd(void *userdata, const void *data, size_t len)
{
    int *fdptr = userdata;
    write(*fdptr, data, len);
}


int read_from_fd(void *userdata, void *buf, size_t len)
{
    int *fdptr = userdata;
    return read(*fdptr, buf, len);
}

void crypto_test(void)
{
#if 1
    int *orders;
    int *comp = bintree_complement(6, 4, &orders);
    int correct[] = { 22, 9, 3, 2 };
    int correct_orders[] = { 1, 0, 0, 1 };
    check("Complement calculation", !memcmp(comp, correct, 4 * sizeof(int)) && !memcmp(orders, correct_orders, 4 * sizeof(int)));
    free(orders);
    free(comp);

    int *dep = bintree_ancestors(6, 4);
    int correct_dep[] = { 10, 4, 1, 0 };
    check("Dependency calculation", !memcmp(dep, correct_dep, 4 * sizeof(int)));
    free(dep);

    {
        /* test merkle tree with zeros */
        hash_t zero1, zero2;
        memset(zero1.hash, 0, sizeof(zero1.hash));
        memset(zero2.hash, 0, sizeof(zero2.hash));
        int orders[] = { 0 };

        /* this should return zero */
        hash_t res1 = merkle_compute(zero1, &zero2, orders, 1);
        check("Merkle parent with zeros", is_zero(res1));

        hash_t a = sha256("a", 1);
        hash_t b = sha256("b", 1);
        hash_t c = sha256("c", 1);
        hash_t d = sha256("d", 1);
        hash_t cd = merkle_parent(c, d, 0);
        //dump_hash(cd);
        char buf[64];
        memcpy(buf, c.hash, 32);
        memcpy(buf + 32, d.hash, 32);
        //dump_hash(sha256(buf, 64));
        check("Merkle parent", hash_equals(sha256(buf, 64), cd));

        hash_t a_comp[] = { b, cd };
        int a_orders[] = { 1, 1 };
        hash_t root1 = merkle_compute(a, a_comp, a_orders, 2);

        hash_t ab = merkle_parent(a, b, 0);
        hash_t root2 = merkle_parent(ab, cd, 0);
        //dump_hash(root1);
        //dump_hash(root2);
        check("Merkle compute", hash_equals(root1, root2));
    }
#endif
}