Coverage Report

Created: 2022-08-24 06:37

/src/cryptofuzz-normal-math/modules/wolfcrypt/bn_helper.cpp
Line
Count
Source (jump to first uncovered line)
1
#include "bn_ops.h"
2
#include <iostream>
3
4
namespace cryptofuzz {
5
namespace module {
6
7
namespace wolfCrypt_detail {
8
#if defined(CRYPTOFUZZ_WOLFCRYPT_ALLOCATION_FAILURES)
9
    extern bool disableAllocationFailures;
10
    extern bool haveAllocFailure;
11
#endif
12
} /* namespace wolfCrypt_detail */
13
14
namespace wolfCrypt_bignum {
15
16
406k
Bignum::read_radix_error_t Bignum::read_radix(mp_int* dest, const std::string& str, const size_t base) {
17
406k
    return read_radix(dest, str.c_str(), base);
18
406k
}
19
20
406k
Bignum::read_radix_error_t Bignum::read_radix(mp_int* dest, const char* str, const size_t base) {
21
406k
    Bignum::read_radix_error_t ret;
22
23
    /* Create a temporary variable for storing the result of mp_read_radix,
24
     * because if mp_read_radix fails (e.g. due to allocation failure),
25
     * it will set the value of the destination variable to 0.
26
     *
27
     * See OSS-Fuzz 31709 / ZD 11834 for discussion. */
28
406k
    auto newMp = (mp_int*)util::malloc(sizeof(mp_int));
29
406k
    if ( mp_init(newMp) != MP_OKAY ) {
30
0
        util::free(newMp);
31
0
        return READ_RADIX_FAIL_MEMORY;
32
0
    }
33
34
406k
    wolfCrypt_detail::haveAllocFailure = false;
35
406k
    if ( mp_read_radix(newMp, str, base) != MP_OKAY ) {
36
7.85k
        ret = wolfCrypt_detail::haveAllocFailure ? READ_RADIX_FAIL_MEMORY : READ_RADIX_FAIL_OTHER;
37
7.85k
        goto end;
38
7.85k
    }
39
40
398k
    wolfCrypt_detail::haveAllocFailure = false;
41
398k
    if ( mp_copy(newMp, dest) != MP_OKAY ) {
42
0
        ret = wolfCrypt_detail::haveAllocFailure ? READ_RADIX_FAIL_MEMORY : READ_RADIX_FAIL_OTHER;
43
0
        goto end;
44
0
    }
45
46
398k
    ret = READ_RADIX_OK;
47
48
406k
end:
49
406k
    CF_NORET(mp_clear(newMp));
50
406k
    util::free(newMp);
51
52
406k
    return ret;
53
398k
}
54
55
37.2k
void Bignum::baseConversion(void) const {
56
37.2k
#if !defined(WOLFSSL_SP_MATH)
57
37.2k
    uint8_t base = 2;
58
37.2k
    char* str = nullptr;
59
60
37.2k
    try { base = ds.Get<uint8_t>(); } catch ( fuzzing::datasource::Datasource::OutOfData ) { }
61
62
#if defined(CRYPTOFUZZ_WOLFCRYPT_DEBUG)
63
    std::cout << "Convert to base " << std::to_string(base) << " and back" << std::endl;
64
#endif
65
37.2k
    {
66
37.2k
        int size;
67
37.2k
        CF_CHECK_EQ(mp_radix_size(mp, base, &size), MP_OKAY);
68
440
        CF_ASSERT(size > 0, "Output of mp_radix_size is 0 or less");
69
70
440
        str = (char*)util::malloc(size);
71
72
440
#if defined(WOLFSSL_SP_MATH) || defined(WOLFSSL_SP_MATH_ALL) || !defined(USE_FAST_MATH)
73
440
        CF_CHECK_EQ(mp_toradix(mp, str, base), MP_OKAY);
74
#else
75
        wolfCrypt_detail::haveAllocFailure = false;
76
        CF_ASSERT(
77
                    mp_toradix(mp, str, base) == MP_OKAY ||
78
                    wolfCrypt_detail::haveAllocFailure ||
79
                    base < 2 ||
80
                    base > 64,
81
                    "wolfCrypt cannot convert mp to string");
82
83
        /* If allocation failure occurred, then do not use 'str' */
84
        CF_CHECK_FALSE(wolfCrypt_detail::haveAllocFailure);
85
#endif
86
87
410
        {
88
410
            const auto ret = read_radix(mp, str, base);
89
410
            CF_ASSERT(ret == READ_RADIX_OK || ret == READ_RADIX_FAIL_MEMORY, "wolfCrypt cannot parse the output of mp_toradix");
90
410
        }
91
410
    }
92
93
37.2k
end:
94
37.2k
    util::free(str);
95
37.2k
#endif
96
37.2k
}
97
98
24.8k
void Bignum::binaryConversion(void) const {
99
24.8k
    uint8_t* data = nullptr;
100
101
24.8k
    CF_CHECK_EQ(mp_isneg(mp), 0);
102
103
24.8k
    {
104
24.8k
        const auto size = mp_unsigned_bin_size(mp);
105
24.8k
        CF_ASSERT(size >= 0, "mp_unsigned_bin_size returned negative value");
106
107
24.8k
        data = util::malloc(size);
108
24.8k
        CF_CHECK_EQ(mp_to_unsigned_bin_len(mp, data, size), MP_OKAY);
109
110
        /* Ensure no allocation failure occurs in mp_read_unsigned_bin
111
         * because this can leave the mp in a corrupted state
112
         */
113
17.4k
        const auto cached_disableAllocationFailures = wolfCrypt_detail::disableAllocationFailures;
114
17.4k
        wolfCrypt_detail::disableAllocationFailures = true;
115
116
17.4k
        CF_ASSERT(mp_read_unsigned_bin(mp, data, size) == MP_OKAY, "Cannot parse output of mp_to_unsigned_bin_len");
117
118
17.4k
        wolfCrypt_detail::disableAllocationFailures = cached_disableAllocationFailures;
119
17.4k
    }
120
121
24.8k
end:
122
24.8k
    util::free(data);
123
24.8k
}
124
125
Bignum::Bignum(Datasource& ds) :
126
542k
    ds(ds) {
127
542k
    mp = (mp_int*)util::malloc(sizeof(mp_int));
128
542k
    if ( mp_init(mp) != MP_OKAY ) {
129
0
        util::free(mp);
130
0
        throw std::exception();
131
0
    }
132
542k
}
133
134
Bignum::Bignum(mp_int* mp, Datasource& ds) :
135
    mp(mp),
136
    ds(ds),
137
    noFree(true)
138
19.6k
{ }
139
140
Bignum::Bignum(const Bignum& other) :
141
313k
    ds(other.ds) {
142
313k
    mp = (mp_int*)util::malloc(sizeof(mp_int));
143
313k
    if ( mp_init(mp) != MP_OKAY ) {
144
0
        util::free(mp);
145
0
        throw std::exception();
146
0
    }
147
313k
    if ( mp_copy(other.mp, mp) != MP_OKAY ) {
148
0
        util::free(mp);
149
0
        throw std::exception();
150
0
    }
151
313k
}
152
153
Bignum::Bignum(const Bignum&& other) :
154
313k
    ds(other.ds) {
155
313k
    mp = (mp_int*)util::malloc(sizeof(mp_int));
156
313k
    if ( mp_init(mp) != MP_OKAY ) {
157
0
        util::free(mp);
158
0
        throw std::exception();
159
0
    }
160
313k
    if ( mp_copy(other.mp, mp) != MP_OKAY ) {
161
0
        util::free(mp);
162
0
        throw std::exception();
163
0
    }
164
313k
}
165
166
1.18M
Bignum::~Bignum() {
167
1.18M
    if ( noFree == false ) {
168
1.16M
        CF_NORET(mp_clear(mp));
169
1.16M
        util::free(mp);
170
1.16M
    }
171
1.18M
}
172
173
0
void Bignum::SetNoFree(void) {
174
0
    noFree = true;
175
0
}
176
177
406k
bool Bignum::Set(const std::string s) {
178
406k
    bool ret = false;
179
180
406k
    bool hex = false;
181
406k
    try {
182
406k
        hex = ds.Get<bool>();
183
406k
    } catch ( ... ) { }
184
185
#if defined(WOLFSSL_SP_MATH)
186
    hex = true;
187
#endif
188
189
406k
    if ( hex == true ) {
190
116k
        CF_CHECK_EQ(read_radix(mp, util::DecToHex(s), 16), READ_RADIX_OK);
191
289k
    } else {
192
289k
        CF_CHECK_EQ(read_radix(mp, s, 10), READ_RADIX_OK);
193
284k
    }
194
195
398k
    ret = true;
196
406k
end:
197
406k
    return ret;
198
398k
}
199
200
72.0k
bool Bignum::Set(const component::Bignum i) {
201
72.0k
    bool ret = false;
202
203
72.0k
    CF_CHECK_EQ(Set(i.ToString()), true);
204
205
70.7k
    ret = true;
206
72.0k
end:
207
72.0k
    return ret;
208
70.7k
}
209
210
393k
mp_int* Bignum::GetPtr(void) const {
211
393k
    {
212
393k
#if defined(WOLFSSL_SP_MATH) || defined(WOLFSSL_SP_MATH_ALL)
213
393k
        CF_ASSERT(mp->used <= mp->size, "used is larger than size");
214
#elif !defined(USE_FAST_MATH)
215
        CF_ASSERT(mp->used <= mp->alloc, "used is larger than size");
216
#endif
217
393k
    }
218
219
0
    {
220
        /* Optionally clamp the bignum. This should not affect its value. */
221
222
393k
        bool clamp = false;
223
224
393k
        try { clamp = ds.Get<bool>(); } catch ( fuzzing::datasource::Datasource::OutOfData ) { }
225
226
393k
        if ( clamp ) {
227
            /* Implemented as a macro so CF_NORET cannot be used here */
228
46.7k
            /* noret */ mp_clamp(mp);
229
46.7k
        }
230
393k
    }
231
232
393k
    {
233
        /* Optionally convert to a random base and back */
234
235
393k
        bool convert = false;
236
237
393k
        try { convert = ds.Get<bool>(); } catch ( fuzzing::datasource::Datasource::OutOfData ) { }
238
239
393k
        if ( convert ) {
240
45.2k
            baseConversion();
241
45.2k
        }
242
393k
    }
243
244
393k
    {
245
        /* Optionally convert to bytes and back */
246
247
393k
        bool convert = false;
248
249
393k
        try { convert = ds.Get<bool>(); } catch ( fuzzing::datasource::Datasource::OutOfData ) { }
250
251
393k
        if ( convert ) {
252
43.5k
            binaryConversion();
253
43.5k
        }
254
393k
    }
255
256
393k
    return mp;
257
393k
}
258
259
381k
mp_int* Bignum::GetPtrDirect(void) const {
260
381k
    return mp;
261
381k
}
262
263
2.45k
std::optional<uint64_t> Bignum::AsUint64(void) const {
264
2.45k
    std::optional<uint64_t> ret = std::nullopt;
265
2.45k
    uint64_t v = 0;
266
267
2.45k
#if !defined(WOLFSSL_SP_MATH)
268
2.45k
    CF_CHECK_EQ(mp_isneg(mp), 0);
269
2.45k
#endif
270
2.45k
    CF_CHECK_LTE(mp_count_bits(mp), (int)(sizeof(v) * 8));
271
2.25k
    CF_CHECK_EQ(mp_to_unsigned_bin_len(mp, (uint8_t*)&v, sizeof(v)), MP_OKAY);
272
2.25k
    v =
273
2.25k
        ((v & 0xFF00000000000000) >> 56) |
274
2.25k
        ((v & 0x00FF000000000000) >> 40) |
275
2.25k
        ((v & 0x0000FF0000000000) >> 24) |
276
2.25k
        ((v & 0x000000FF00000000) >>  8) |
277
2.25k
        ((v & 0x00000000FF000000) <<  8) |
278
2.25k
        ((v & 0x0000000000FF0000) << 24) |
279
2.25k
        ((v & 0x000000000000FF00) << 40) |
280
2.25k
        ((v & 0x00000000000000FF) << 56);
281
282
2.25k
    ret = v;
283
2.45k
end:
284
2.45k
    return ret;
285
2.25k
}
286
287
64.5k
std::optional<std::string> Bignum::ToDecString(void) {
288
64.5k
    std::optional<std::string> ret = std::nullopt;
289
64.5k
    char* str = nullptr;
290
291
#if defined(WOLFSSL_SP_MATH)
292
    str = (char*)util::malloc(8192);
293
294
    CF_CHECK_EQ(mp_tohex(mp, str), MP_OKAY);
295
    ret = { util::HexToDec(str) };
296
#else
297
64.5k
    bool hex = false;
298
64.5k
    int size;
299
300
64.5k
    try {
301
64.5k
        hex = ds.Get<bool>();
302
64.5k
    } catch ( ... ) { }
303
304
305
64.5k
    if ( hex == true ) {
306
5.09k
        CF_CHECK_EQ(mp_radix_size(mp, 16, &size), MP_OKAY);
307
5.09k
        CF_ASSERT(size > 0, "Output of mp_radix_size is 0 or less");
308
309
5.09k
        str = (char*)util::malloc(size+1);
310
311
5.09k
        CF_CHECK_EQ(mp_tohex(mp, str), MP_OKAY);
312
5.09k
        ret = { util::HexToDec(str) };
313
59.4k
    } else {
314
59.4k
        CF_CHECK_EQ(mp_radix_size(mp, 10, &size), MP_OKAY);
315
58.1k
        CF_ASSERT(size > 0, "Output of mp_radix_size is 0 or less");
316
317
58.1k
        str = (char*)util::malloc(size);
318
319
58.1k
        CF_CHECK_EQ(mp_toradix(mp, str, 10), MP_OKAY);
320
57.5k
        ret = std::string(str);
321
57.5k
    }
322
62.6k
#endif
323
324
64.5k
end:
325
64.5k
    free(str);
326
327
64.5k
    return ret;
328
64.5k
}
329
330
36.8k
std::optional<component::Bignum> Bignum::ToComponentBignum(void) {
331
36.8k
    std::optional<component::Bignum> ret = std::nullopt;
332
333
36.8k
    auto str = ToDecString();
334
36.8k
    CF_CHECK_NE(str, std::nullopt);
335
35.8k
    ret = { str };
336
36.8k
end:
337
36.8k
    return ret;
338
35.8k
}
339
340
55.4k
bool Bignum::ToBin(uint8_t* dest, const size_t size) {
341
55.4k
    bool ret = false;
342
343
55.4k
    const auto required = mp_unsigned_bin_size(GetPtr());
344
55.4k
    CF_ASSERT(required >= 0, "mp_unsigned_bin_size returned negative value");
345
346
55.4k
    CF_CHECK_GTE(size, static_cast<size_t>(required));
347
54.9k
    CF_CHECK_EQ(mp_to_unsigned_bin_len(GetPtr(), dest, size), MP_OKAY);
348
349
52.9k
    ret = true;
350
55.4k
end:
351
55.4k
    return ret;
352
52.9k
}
353
354
355
29.9k
std::optional<std::vector<uint8_t>> Bignum::ToBin(Datasource& ds, const component::Bignum b, std::optional<size_t> size) {
356
29.9k
    std::optional<std::vector<uint8_t>> ret = std::nullopt;
357
29.9k
    std::vector<uint8_t> v;
358
29.9k
    Bignum bn(ds);
359
29.9k
    uint16_t padding = 0;
360
361
29.9k
    CF_CHECK_EQ(bn.Set(b), true);
362
29.3k
    if ( size != std::nullopt ) {
363
0
        v.resize(*size);
364
29.3k
    } else {
365
29.3k
        try {
366
29.3k
            padding = ds.Get<uint16_t>();
367
29.3k
        } catch ( fuzzing::datasource::Datasource::OutOfData ) { }
368
369
29.3k
        v.resize( mp_unsigned_bin_size(bn.GetPtr()) + padding );
370
29.3k
    }
371
372
29.3k
    CF_CHECK_EQ(bn.ToBin(v.data(), v.size()), true);
373
374
27.3k
    ret = v;
375
29.9k
end:
376
29.9k
    return ret;
377
27.3k
}
378
379
24.8k
bool Bignum::ToBin(Datasource& ds, const component::Bignum b, uint8_t* dest, const size_t size) {
380
24.8k
    bool ret = false;
381
24.8k
    Bignum bn(ds);
382
383
24.8k
    CF_CHECK_EQ(bn.Set(b), true);
384
24.3k
    CF_CHECK_EQ(bn.ToBin(dest, size), true);
385
386
24.0k
    ret = true;
387
24.8k
end:
388
24.8k
    return ret;
389
24.0k
}
390
391
6.37k
bool Bignum::ToBin(Datasource& ds, const component::BignumPair b, uint8_t* dest, const size_t size) {
392
6.37k
    CF_ASSERT((size % 2) == 0, "Input size is not multiple of 2 in Bignum::ToBin");
393
394
6.37k
    bool ret = false;
395
6.37k
    const auto halfSize = size / 2;
396
397
6.37k
    CF_CHECK_EQ(ToBin(ds, b.first, dest, halfSize), true);
398
6.28k
    CF_CHECK_EQ(ToBin(ds, b.second, dest + halfSize, halfSize), true);
399
400
6.20k
    ret = true;
401
6.37k
end:
402
6.37k
    return ret;
403
6.20k
}
404
405
5.72k
std::optional<component::Bignum> Bignum::BinToBignum(Datasource& ds, const uint8_t* src, const size_t size) {
406
5.72k
    std::optional<component::Bignum> ret = std::nullopt;
407
408
5.72k
    wolfCrypt_bignum::Bignum bn(ds);
409
5.72k
    CF_CHECK_EQ(mp_read_unsigned_bin(bn.GetPtr(), src, size), MP_OKAY);
410
411
5.72k
    ret = bn.ToComponentBignum();
412
413
5.72k
end:
414
5.72k
    return ret;
415
5.72k
}
416
417
3.84k
std::optional<component::BignumPair> Bignum::BinToBignumPair(Datasource& ds, const uint8_t* src, const size_t size) {
418
3.84k
    CF_ASSERT((size % 2) == 0, "Input size is not multiple of 2 in Bignum::BinToBignumPair");
419
420
3.84k
    std::optional<component::BignumPair> ret = std::nullopt;
421
3.84k
    std::optional<component::Bignum> A, B;
422
3.84k
    const auto halfSize = size / 2;
423
424
3.84k
    {
425
3.84k
        wolfCrypt_bignum::Bignum bn(ds);
426
3.84k
        CF_CHECK_EQ(mp_read_unsigned_bin(bn.GetPtr(), src, halfSize), MP_OKAY);
427
3.84k
        CF_CHECK_NE(A = bn.ToComponentBignum(), std::nullopt);
428
3.75k
    }
429
430
0
    {
431
3.75k
        wolfCrypt_bignum::Bignum bn(ds);
432
3.75k
        CF_CHECK_EQ(mp_read_unsigned_bin(bn.GetPtr(), src + halfSize, halfSize), MP_OKAY);
433
3.75k
        CF_CHECK_NE(B = bn.ToComponentBignum(), std::nullopt);
434
3.69k
    }
435
436
437
0
    ret = {A->ToTrimmedString(), B->ToTrimmedString()};
438
439
3.84k
end:
440
3.84k
    return ret;
441
3.69k
}
442
443
78.3k
void Bignum::Randomize(void) {
444
78.3k
    std::vector<uint8_t> data;
445
78.3k
    try {
446
78.3k
        data = ds.GetData(0, 1, 1024);
447
78.3k
    } catch ( fuzzing::datasource::Datasource::OutOfData ) { }
448
449
78.3k
    if ( !data.empty() ) {
450
        /* ignore return value */ mp_read_unsigned_bin(GetPtrDirect(), data.data(), data.size());
451
2.31k
    }
452
78.3k
}
453
454
8.58k
bool Bignum::operator==(const Bignum& rhs) const {
455
8.58k
    return mp_cmp(GetPtr(), rhs.GetPtr()) == MP_EQ;
456
8.58k
}
457
458
BignumCluster::BignumCluster(Datasource& ds, Bignum bn0, Bignum bn1, Bignum bn2, Bignum bn3) :
459
    ds(ds),
460
    bn({bn0, bn1, bn2, bn3})
461
78.3k
{ }
462
463
78.3k
BignumCluster::~BignumCluster() {
464
391k
    for (size_t i = 0; i < 4; i++) {
465
313k
        if ( cache.bn[i] == nullptr ) {
466
23.8k
            continue;
467
23.8k
        }
468
469
289k
        mp_clear(cache.bn[i]);
470
289k
        util::free(cache.bn[i]);
471
289k
    }
472
78.3k
}
473
474
89.3k
Bignum& BignumCluster::operator[](const size_t index) {
475
89.3k
    CF_ASSERT(index < bn.size(), "Invalid index requested in BignumCluster::operator[]");
476
477
89.3k
    try {
478
        /* Rewire? */
479
89.3k
        if ( ds.Get<bool>() == true ) {
480
            /* Pick a random bignum */
481
9.06k
            const auto newIndex = ds.Get<uint8_t>() % 4;
482
483
            /* Same value? */
484
9.06k
            if ( bn[newIndex] == bn[index] ) {
485
                /* Then return reference to other bignum */
486
3.52k
                return bn[newIndex];
487
3.52k
            }
488
489
            /* Fall through */
490
9.06k
        }
491
89.3k
    } catch ( fuzzing::datasource::Datasource::OutOfData ) { }
492
493
85.8k
    return bn[index];
494
89.3k
}
495
496
299k
bool BignumCluster::Set(const size_t index, const std::string s) {
497
299k
    CF_ASSERT(index < bn.size(), "Invalid index requested in BignumCluster::Set");
498
499
299k
    return bn[index].Set(s);
500
299k
}
501
502
646
mp_int* BignumCluster::GetDestPtr(const size_t index) {
503
    /* Because it is requested as a destination pointer,
504
     * this bignum will be altered, hence invalidate
505
     * the cache
506
     */
507
646
    InvalidateCache();
508
509
646
    return bn[index].GetPtr();
510
646
}
511
512
72.3k
void BignumCluster::Save(void) {
513
361k
    for (size_t i = 0; i < 4; i++) {
514
289k
        mp_int* cached_mp = (mp_int*)util::malloc(sizeof(mp_int));
515
516
289k
        wolfCrypt_detail::disableAllocationFailures = true;
517
518
289k
        CF_ASSERT(mp_init(cached_mp) == MP_OKAY, "mp_init failed unexpectedly");
519
289k
        CF_ASSERT(mp_copy(bn[i].GetPtrDirect(), cached_mp) == MP_OKAY, "mp_copy failed unexpectedly");
520
521
289k
        wolfCrypt_detail::disableAllocationFailures = false;
522
523
289k
        cache.bn[i] = cached_mp;
524
289k
    }
525
72.3k
}
526
527
1.29k
void BignumCluster::InvalidateCache(void) {
528
1.29k
    cache.invalid = true;
529
1.29k
}
530
531
23.4k
bool BignumCluster::EqualsCache(void) const {
532
23.4k
    if ( cache.invalid == true ) {
533
1.08k
        return true;
534
1.08k
    }
535
536
111k
    for (size_t i = 0; i < 4; i++) {
537
89.5k
        if ( cache.bn[i] == nullptr ) {
538
0
            continue;
539
0
        }
540
541
89.5k
        wolfCrypt_detail::disableAllocationFailures = true;
542
543
89.5k
        if ( mp_cmp(bn[i].GetPtrDirect(), cache.bn[i]) != MP_EQ ) {
544
#if defined(CRYPTOFUZZ_WOLFCRYPT_DEBUG)
545
            char str[8192];
546
547
            std::cout << "Bignum with index " << std::to_string(i) << " was changed" << std::endl;
548
549
            wolfCrypt_detail::disableAllocationFailures = true;
550
551
            CF_ASSERT(mp_tohex(cache.bn[i], str) == MP_OKAY, "mp_tohex failed unexpectedly");
552
            printf("it was: %s\n", str);
553
554
            CF_ASSERT(mp_tohex(bn[i].GetPtrDirect(), str) == MP_OKAY, "mp_tohex failed unexpectedly");
555
            printf("it is now %s\n", str);
556
557
#endif
558
0
            wolfCrypt_detail::disableAllocationFailures = false;
559
560
0
            return false;
561
0
        }
562
563
89.5k
        wolfCrypt_detail::disableAllocationFailures = false;
564
89.5k
    }
565
566
22.3k
    return true;
567
22.3k
}
568
569
} /* namespace wolfCrypt_bignum */
570
} /* namespace module */
571
} /* namespace cryptofuzz */