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 // Don't lint the next line, as cpplint will suggest adding
18 // /tools/security as an include_dir
19 // NOLINTNEXTLINE
20 #include "fuzz_ffi.h"
21
22 #include <vector>
23 #include "include/ffi_common.h"
24
25 // Empty functions we can use for our function targets
fn(int num_args,...)26 void fn(int num_args, ...) {}
closure_fn(ffi_cif * cif __UNUSED__,void * resp,void ** args,void * userdata)27 void closure_fn(ffi_cif* cif __UNUSED__,
28 void* resp, void** args, void* userdata) {}
raw_closure_fn(ffi_cif * cif __UNUSED__,void * resp,ffi_raw * args,void * userdata)29 void raw_closure_fn(ffi_cif* cif __UNUSED__,
30 void* resp, ffi_raw* args, void* userdata) {}
java_raw_closure_fn(ffi_cif * cif __UNUSED__,void * resp,ffi_java_raw * args,void * userdata)31 void java_raw_closure_fn(ffi_cif* cif __UNUSED__,
32 void* resp, ffi_java_raw* args, void* userdata) {}
33
generateCustomType(FuzzedDataProvider * dataProvider)34 ffi_type* generateCustomType(FuzzedDataProvider* dataProvider) {
35 // Set our flag so we don't call a java-related function (triggers an abort)
36 args_contain_struct = true;
37
38 ffi_type* new_type = reinterpret_cast<ffi_type*>(malloc(sizeof(ffi_type)));
39 ffi_alloc_vector.push_back(new_type);
40
41 new_type->size = 0;
42 new_type->alignment = 0;
43 new_type->type = FFI_TYPE_STRUCT;
44
45 // Generate our subobjects
46 size_t num_elements = dataProvider->ConsumeIntegralInRange<size_t>(0,
47 MAX_NUM_ELEMENTS);
48 new_type->elements = reinterpret_cast<ffi_type**>(
49 malloc(sizeof(ffi_type*)*(num_elements+1)));
50
51 // Nested custom structs will cause an assert, so disable them
52 // TODO(michael.ensing@leviathansecurity.com):
53 // change the 'false' here to true once libffi supports nested structs.
54 // It'll just throw an assert currently.
55 for (size_t i=0; i < num_elements; i++) {
56 new_type->elements[i] = getRandomType(dataProvider, false);
57 }
58
59 // The final element must be a nullptr
60 new_type->elements[num_elements] = NULL;
61
62 // Get our size/alignment
63 ffi_get_struct_offsets(abi, new_type, NULL);
64
65 return new_type;
66 }
67
getTotalSize(ffi_type * type)68 size_t getTotalSize(ffi_type* type) {
69 if (type == NULL) {
70 return 0;
71 }
72
73 // Start the total as the size of the object itself
74 size_t total_size = type->size > sizeof(void*) ?
75 type->size : sizeof(void*);
76
77 // Recursively add the size of the subelements
78 if (type->elements != NULL) {
79 for (size_t i=0; type->elements[i] != NULL; i++) {
80 total_size += getTotalSize(type->elements[i]);
81 }
82 }
83
84 return total_size;
85 }
86
getRandomType(FuzzedDataProvider * dataProvider,bool allowCustomTypes)87 ffi_type* getRandomType(FuzzedDataProvider* dataProvider,
88 bool allowCustomTypes) {
89 // Which type? Let type==NUM_TYPES be our custom struct case
90 size_t type_index = dataProvider->ConsumeIntegralInRange<size_t>(0,
91 NUM_TYPES);
92 ffi_type* type;
93 if (type_index == NUM_TYPES) {
94 if (allowCustomTypes) {
95 type = generateCustomType(dataProvider);
96 } else {
97 return NULL;
98 }
99 } else {
100 type = ffi_types[type_index];
101 }
102
103 return type;
104 }
105
genArg(ffi_type * type,FuzzedDataProvider * dataProvider)106 void* genArg(ffi_type* type, FuzzedDataProvider* dataProvider) {
107 // Allocate the space for our arg
108 // TODO(michael.ensing@leviathansecurity.com):
109 // Properly allocate the correct amount of aligned-space,
110 // don't just double (which should contain any alignment)
111 size_t type_size = getTotalSize(type)*2;
112
113 if (type_size == 0) {
114 return NULL;
115 }
116
117 void* ret = malloc(type_size);
118
119 std::vector<uint8_t> bytes = dataProvider->ConsumeBytes<uint8_t>(type_size);
120 memcpy(ret, bytes.data(), bytes.size());
121
122 return ret;
123 }
124
buildArgArrays(ffi_type * arg_types[],void * arg_array[],size_t num_args,FuzzedDataProvider * dataProvider)125 bool buildArgArrays(ffi_type* arg_types[], void* arg_array[], size_t num_args,
126 FuzzedDataProvider* dataProvider) {
127 // The first value in our array should be the number of arguments
128 arg_types[0] = &ffi_type_sint;
129 size_t* size_ptr = reinterpret_cast<size_t*>(malloc(sizeof(size_t)));
130 *size_ptr = num_args;
131 arg_array[0] = size_ptr;
132
133 // Grab our arguments
134 for (size_t i = 1; i <= num_args; i++) {
135 // Determine what type we're using
136 ffi_type* type = getRandomType(dataProvider, true);
137 if (type == NULL) {
138 return false;
139 }
140 arg_types[i] = type;
141
142 // Generate a value for it and add to our arguments array
143 arg_array[i] = genArg(type, dataProvider);
144 }
145
146 // Our arrays of pointers need to be nullptr-terminated
147 arg_types[num_args+1] = NULL;
148 arg_array[num_args+1] = NULL;
149
150 return true;
151 }
152
runMainFunctions(ffi_cif * cif,void * resp_buf,void ** arg_array,FuzzedDataProvider * dataProvider)153 void runMainFunctions(ffi_cif* cif, void* resp_buf, void** arg_array,
154 FuzzedDataProvider* dataProvider) {
155 // Call function
156 ffi_call(cif, FFI_FN(fn), resp_buf, arg_array);
157
158 // Prep Closure
159 ffi_closure* pcl = NULL;
160 void* code;
161
162 pcl = reinterpret_cast<ffi_closure*>(
163 ffi_closure_alloc(sizeof(ffi_closure), &code));
164 if (pcl == NULL) {
165 return;
166 }
167
168 size_t buf_size = dataProvider->ConsumeIntegralInRange<size_t>(0,
169 MAX_RESP_SIZE);
170 std::vector<uint8_t> data_vector =
171 dataProvider->ConsumeBytes<uint8_t>(buf_size);
172 ffi_prep_closure_loc(pcl, cif, closure_fn, data_vector.data(), code);
173 ffi_closure_free(pcl);
174 }
175
runRawFunctions(ffi_cif * cif,void * resp_buf,void ** arg_array,FuzzedDataProvider * dataProvider)176 void runRawFunctions(ffi_cif* cif, void* resp_buf, void** arg_array,
177 FuzzedDataProvider* dataProvider) {
178 #if !FFI_NO_RAW_API && !FFI_NATIVE_RAW_API
179 // Allocate our ffi_raw and put our args there
180 size_t rsize = ffi_raw_size(cif);
181 ffi_raw* raw_args = reinterpret_cast<ffi_raw*>(malloc(rsize));
182 raw_alloc_vector.push_back(raw_args);
183 ffi_ptrarray_to_raw(cif, arg_array, raw_args);
184
185 // Call
186 ffi_raw_call(cif, FFI_FN(fn), resp_buf, raw_args);
187
188 // Prep Closure
189 #if FFI_CLOSURES
190 ffi_raw_closure* pcl = NULL;
191 void* code;
192
193 pcl = static_cast<ffi_raw_closure*>(
194 ffi_closure_alloc(sizeof(ffi_raw_closure), &code));
195 if (pcl == NULL) {
196 return;
197 }
198 size_t buf_size = dataProvider->ConsumeIntegralInRange<size_t>(0,
199 MAX_RESP_SIZE);
200 std::vector<uint8_t> data_vector =
201 dataProvider->ConsumeBytes<uint8_t>(buf_size);
202 ffi_prep_raw_closure_loc(pcl, cif, raw_closure_fn, data_vector.data(),
203 code);
204 ffi_closure_free(pcl);
205
206 #endif // FFI_CLOSURES
207 #endif // !FFI_NO_RAW_API && !FFI_NATIVE_RAW_API
208 }
209
runJavaFunctions(ffi_cif * cif,void * resp_buf,void ** arg_array,FuzzedDataProvider * dataProvider)210 void runJavaFunctions(ffi_cif* cif, void* resp_buf, void** arg_array,
211 FuzzedDataProvider* dataProvider) {
212 #if !defined(NO_JAVA_RAW_API)
213 #if !FFI_NO_RAW_API && !FFI_NATIVE_RAW_API
214
215 // Allocate our ffi_java_raw and put our args there
216 size_t rsize = ffi_java_raw_size(cif);
217 // NOTE: a buffer overread will occasionally happen if we don't
218 // increase rsize.
219 ffi_java_raw* raw_args = reinterpret_cast<ffi_raw*>(malloc(rsize*2));
220 raw_alloc_vector.push_back(raw_args);
221 ffi_ptrarray_to_raw(cif, arg_array, raw_args);
222
223 // Call
224 ffi_java_raw_call(cif, FFI_FN(fn), resp_buf, raw_args);
225
226 // Prep Closure
227 #if FFI_CLOSURES
228 ffi_java_raw_closure* pcl = NULL;
229 void* code;
230
231 pcl = static_cast<ffi_java_raw_closure*>(
232 ffi_closure_alloc(sizeof(ffi_java_raw_closure), &code));
233 if (pcl == NULL) {
234 return;
235 }
236 size_t buf_size = dataProvider->ConsumeIntegralInRange<size_t>(0,
237 MAX_RESP_SIZE);
238 std::vector<uint8_t> data_vector =
239 dataProvider->ConsumeBytes<uint8_t>(buf_size);
240 ffi_prep_java_raw_closure_loc(pcl, cif, raw_closure_fn, data_vector.data(),
241 code);
242
243 ffi_closure_free(pcl);
244
245
246 #endif // FFI_CLOSURES
247 #endif // !FFI_NATIVE_RAW_API
248 #endif // !NO_JAVA_RAW_API
249 }
250
freeFFI(ffi_type * ffi_type)251 void freeFFI(ffi_type* ffi_type) {
252 // Make sure it's one of our structs
253 if (ffi_type == NULL || ffi_type->type != FFI_TYPE_STRUCT) {
254 return;
255 }
256
257 if (ffi_type->elements != NULL) {
258 free(ffi_type->elements);
259 }
260
261 // Finally, free our object
262 free(ffi_type);
263 }
264
freeAll(void * arg_array[],size_t num_args,void * resp_buf)265 void freeAll(void* arg_array[], size_t num_args, void* resp_buf) {
266 // Free our custom struct objects
267 for (const auto& ffi : ffi_alloc_vector) {
268 freeFFI(ffi);
269 }
270 ffi_alloc_vector.clear();
271 for (const auto& raw : raw_alloc_vector) {
272 free(raw);
273 }
274 raw_alloc_vector.clear();
275
276 for (size_t i=0; i <= num_args; i++) {
277 free(arg_array[i]);
278 }
279
280 if (resp_buf) {
281 free(resp_buf);
282 }
283 }
284
LLVMFuzzerTestOneInput(const uint8_t * Data,size_t Size)285 extern "C" int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size) {
286 // Init our wrapper
287 FuzzedDataProvider dataProvider(Data, Size);
288 ffi_cif cif;
289 ffi_status ret;
290 void* resp_buf = NULL;
291 args_contain_struct = false;
292 ffi_type* rtype;
293
294 // How many args are we sending?
295 size_t num_args = dataProvider.ConsumeIntegralInRange<size_t>(0,
296 MAX_NUM_ARGS);
297
298 // Build our array of args (+2 for leading arg_count and trailing nullptr)
299 ffi_type* arg_types[num_args+2];
300 void* arg_array[num_args+2];
301 bool success = buildArgArrays(arg_types, arg_array, num_args,
302 &dataProvider);
303 if (!success) {
304 goto free;
305 }
306
307 // Get return type
308 rtype = dataProvider.PickValueInArray<ffi_type*, NUM_TYPES>(ffi_types);
309
310 // Create a buffer for our return value
311 resp_buf = malloc(MAX_RESP_SIZE);
312 if (resp_buf == NULL) {
313 goto free;
314 }
315
316 // Set up our ABI
317 // NOTE: fuzzing abi triggers an abort on linux-x86_64,
318 // so only fuzz it on ARM
319 #if MAX_ABI > 0 && defined(ARM)
320 abi = static_cast<ffi_abi>(
321 dataProvider.ConsumeIntegralInRange<uint32_t>(0, MAX_ABI));
322 #endif
323 #if HAVE_LONG_DOUBLE_VARIANT
324 ffi_prep_types(abi);
325 #endif
326
327 // ============= Call Functions =============
328 ret = ffi_prep_cif_var(&cif, abi, 1, num_args, rtype,
329 arg_types);
330 if (ret != FFI_OK) {
331 goto free;
332 }
333
334 runMainFunctions(&cif, resp_buf, arg_array, &dataProvider);
335 runRawFunctions(&cif, resp_buf, arg_array, &dataProvider);
336 if (!args_contain_struct) {
337 runJavaFunctions(&cif, resp_buf, arg_array, &dataProvider);
338 }
339
340 free:
341 freeAll(arg_array, num_args, resp_buf);
342 return 0;
343 }
344