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 <cstdio>
24 
25 #define ANDROID_PUBKEY_MODULUS_SIZE_WORDS (ANDROID_PUBKEY_MODULUS_SIZE / 4)
26 
LLVMFuzzerTestOneInput(const uint8_t * data,std::size_t size)27 extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, std::size_t size) {
28     if (size < 2050) {
29         return 0;
30     }
31 
32     FuzzedDataProvider fdp(data, size);
33 
34     uint8_t buffer[ANDROID_PUBKEY_ENCODED_SIZE];
35     uint32_t modulus_size_words = ANDROID_PUBKEY_MODULUS_SIZE_WORDS;
36     memcpy(buffer, &modulus_size_words, sizeof(uint32_t));
37 
38     uint32_t n0inv = fdp.ConsumeIntegralInRange<uint32_t>(0,2^32);
39     memcpy(buffer+sizeof(uint32_t), &n0inv, sizeof(uint32_t));
40 
41     std::string s = fdp.ConsumeBytesAsString(ANDROID_PUBKEY_MODULUS_SIZE);
42     uint8_t* modulus = (uint8_t*)s.c_str();
43     memcpy(buffer+sizeof(uint32_t)*2, modulus,
44            sizeof(uint8_t)*ANDROID_PUBKEY_MODULUS_SIZE);
45 
46     std::string ss = fdp.ConsumeBytesAsString(ANDROID_PUBKEY_MODULUS_SIZE);
47     uint8_t* rr = (uint8_t*)ss.c_str();
48     memcpy(buffer+sizeof(uint32_t)*2+ANDROID_PUBKEY_MODULUS_SIZE, rr,
49            sizeof(uint8_t)*ANDROID_PUBKEY_MODULUS_SIZE);
50 
51     int flip = fdp.ConsumeIntegralInRange<uint32_t>(0,1);
52     buffer[ANDROID_PUBKEY_ENCODED_SIZE-1] = (uint8_t)(flip == 0 ? 3 : 65537);
53 
54     RSA* new_key = nullptr;
55     android_pubkey_decode(buffer, sizeof(uint8_t)*ANDROID_PUBKEY_ENCODED_SIZE, &new_key);
56 
57     uint8_t key_data[ANDROID_PUBKEY_ENCODED_SIZE];
58     android_pubkey_encode(new_key, key_data, sizeof(key_data));
59 
60     assert(0 == memcmp(buffer, key_data, sizeof(buffer)));
61 
62     RSA_free(new_key);
63 
64     return 0;
65 }
66