1 /*
2 * Copyright (C) 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 <functional>
18 #include <memory>
19
20 #include <keymaster/serializable.h>
21
22 #include "fuzzer/FuzzedDataProvider.h"
23 #include "serializable_types.h"
24
25 static constexpr uint16_t kMinBufferSize = 1;
26 static constexpr uint16_t kMaxBufferSize = 2048;
27
RunDeserialize(keymaster::Serializable * ser,FuzzedDataProvider * fdp)28 void RunDeserialize(keymaster::Serializable* ser, FuzzedDataProvider* fdp) {
29 uint16_t buf_size = fdp->ConsumeIntegralInRange<uint16_t>(kMinBufferSize, kMaxBufferSize);
30 std::unique_ptr<uint8_t[]> in_buf = std::unique_ptr<uint8_t[]>(new uint8_t[buf_size]);
31 const uint8_t* data_ptr = in_buf.get();
32 // memset((void*) data_ptr, 0x41, buf_size);
33 int32_t end = fdp->ConsumeIntegralInRange<int32_t>(0, buf_size);
34 ser->Deserialize(&data_ptr, data_ptr + end);
35 }
36
RunSerialize(keymaster::Serializable * ser,FuzzedDataProvider * fdp)37 void RunSerialize(keymaster::Serializable* ser, FuzzedDataProvider* fdp) {
38 uint16_t buf_size = ser->SerializedSize();
39 std::unique_ptr<uint8_t[]> out_buf = std::unique_ptr<uint8_t[]>(new uint8_t[buf_size]);
40 // memset((void*) out_buf.get(), 0x41, buf_size);
41 int32_t end = fdp->ConsumeIntegralInRange<int32_t>(0, buf_size);
42 ser->Serialize(out_buf.get(), out_buf.get() + end);
43 }
44
LLVMFuzzerTestOneInput(const uint8_t * data,size_t size)45 extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
46 FuzzedDataProvider fdp(data, size);
47 std::unique_ptr<keymaster::Serializable> serializable =
48 keymaster::getSerializable(fdp.ConsumeEnum<keymaster::SerializableType>());
49 /*if(fdp.remaining_bytes() > 1) {
50 RunDeserialize(serializable.get(), &fdp);
51 }*/
52 for (size_t i = 0; fdp.remaining_bytes() > 0; i++) {
53 if (fdp.ConsumeBool()) {
54 RunSerialize(serializable.get(), &fdp);
55 } else {
56 RunDeserialize(serializable.get(), &fdp);
57 }
58 }
59 return 0;
60 }
61