1 /*
2 * Copyright 2020 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 #include <crypto_utils/android_pubkey.h>
18 #include <fuzzer/FuzzedDataProvider.h>
19 #include <string.h>
20 #include <memory>
21 #include <openssl/obj_mac.h>
22 #include <openssl/rsa.h>
23 #include <cassert>
24 #include <cstdio>
25 #include <limits>
26
27 #define ANDROID_PUBKEY_MODULUS_SIZE_WORDS (ANDROID_PUBKEY_MODULUS_SIZE / 4)
28
LLVMFuzzerTestOneInput(const uint8_t * data,std::size_t size)29 extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, std::size_t size) {
30 if (size < 2050) {
31 return 0;
32 }
33
34 FuzzedDataProvider fdp(data, size);
35
36 uint8_t buffer[ANDROID_PUBKEY_ENCODED_SIZE];
37 uint32_t modulus_size_words = ANDROID_PUBKEY_MODULUS_SIZE_WORDS;
38 memcpy(buffer, &modulus_size_words, sizeof(uint32_t));
39
40 uint32_t n0inv = fdp.ConsumeIntegralInRange<uint32_t>(0,std::numeric_limits<uint32_t>::max());
41 memcpy(buffer+sizeof(uint32_t), &n0inv, sizeof(uint32_t));
42
43 std::string s = fdp.ConsumeBytesAsString(ANDROID_PUBKEY_MODULUS_SIZE);
44 uint8_t* modulus = (uint8_t*)s.c_str();
45 memcpy(buffer+sizeof(uint32_t)*2, modulus,
46 sizeof(uint8_t)*ANDROID_PUBKEY_MODULUS_SIZE);
47
48 std::string ss = fdp.ConsumeBytesAsString(ANDROID_PUBKEY_MODULUS_SIZE);
49 uint8_t* rr = (uint8_t*)ss.c_str();
50 memcpy(buffer+sizeof(uint32_t)*2+ANDROID_PUBKEY_MODULUS_SIZE, rr,
51 sizeof(uint8_t)*ANDROID_PUBKEY_MODULUS_SIZE);
52
53 int flip = fdp.ConsumeIntegralInRange<uint32_t>(0,1);
54 buffer[ANDROID_PUBKEY_ENCODED_SIZE-1] = (uint8_t)(flip == 0 ? 3 : 65537);
55
56 RSA* new_key = nullptr;
57 android_pubkey_decode(buffer, sizeof(uint8_t)*ANDROID_PUBKEY_ENCODED_SIZE, &new_key);
58
59 uint8_t key_data[ANDROID_PUBKEY_ENCODED_SIZE];
60 android_pubkey_encode(new_key, key_data, sizeof(key_data));
61
62 assert(0 == memcmp(buffer, key_data, sizeof(buffer)));
63
64 RSA_free(new_key);
65
66 return 0;
67 }
68