1 /*
2 * Copyright (C) 2022 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 #include <fuzzbinder/libbinder_driver.h>
17
18 #include <fuzzbinder/random_parcel.h>
19
20 namespace android {
21
fuzzService(const sp<IBinder> & binder,FuzzedDataProvider && provider)22 void fuzzService(const sp<IBinder>& binder, FuzzedDataProvider&& provider) {
23 sp<IBinder> target;
24
25 RandomParcelOptions options{
26 .extraBinders = {binder},
27 .extraFds = {},
28 };
29
30 while (provider.remaining_bytes() > 0) {
31 uint32_t code = provider.ConsumeIntegral<uint32_t>();
32 uint32_t flags = provider.ConsumeIntegral<uint32_t>();
33 Parcel data;
34
35 sp<IBinder> target = options.extraBinders.at(
36 provider.ConsumeIntegralInRange<size_t>(0, options.extraBinders.size() - 1));
37 options.writeHeader = [&target](Parcel* p, FuzzedDataProvider& provider) {
38 // most code will be behind checks that the head of the Parcel
39 // is exactly this, so make it easier for fuzzers to reach this
40 if (provider.ConsumeBool()) {
41 p->writeInterfaceToken(target->getInterfaceDescriptor());
42 }
43 };
44
45 std::vector<uint8_t> subData = provider.ConsumeBytes<uint8_t>(
46 provider.ConsumeIntegralInRange<size_t>(0, provider.remaining_bytes()));
47 fillRandomParcel(&data, FuzzedDataProvider(subData.data(), subData.size()), options);
48
49 Parcel reply;
50 (void)target->transact(code, data, &reply, flags);
51
52 // feed back in binders and fds that are returned from the service, so that
53 // we can fuzz those binders, and use the fds and binders to feed back into
54 // the binders
55 auto retBinders = reply.debugReadAllStrongBinders();
56 options.extraBinders.insert(options.extraBinders.end(), retBinders.begin(),
57 retBinders.end());
58 auto retFds = reply.debugReadAllFileDescriptors();
59 for (size_t i = 0; i < retFds.size(); i++) {
60 options.extraFds.push_back(base::unique_fd(dup(retFds[i])));
61 }
62 }
63 }
64
65 } // namespace android
66