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 
17 #include <fuzzer/FuzzedDataProvider.h>
18 #include <media/NdkMediaCrypto.h>
19 #include <functional>
20 
21 #include <functional>
22 
23 constexpr size_t kMaxString = 256;
24 constexpr size_t kMinBytes = 0;
25 constexpr size_t kMaxBytes = 1000;
26 constexpr size_t kMaxRuns = 100;
27 
LLVMFuzzerTestOneInput(const uint8_t * data,size_t size)28 extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
29     FuzzedDataProvider fdp(data, size);
30     AMediaUUID uuid = {};
31     size_t apiCount = 0;
32     int32_t maxLen = fdp.ConsumeIntegralInRange<size_t>(kMinBytes, (size_t)sizeof(AMediaUUID));
33     for (size_t idx = 0; idx < maxLen; ++idx) {
34         uuid[idx] = fdp.ConsumeIntegral<uint8_t>();
35     }
36     std::vector<uint8_t> initData =
37             fdp.ConsumeBytes<uint8_t>(fdp.ConsumeIntegralInRange<size_t>(kMinBytes, kMaxBytes));
38     AMediaCrypto* crypto = AMediaCrypto_new(uuid, initData.data(), initData.size());
39     /*
40      * The AMediaCrypto_isCryptoSchemeSupported API doesn't consume any input bytes,
41      * so when PickValueInArray() selects it repeatedly, only one byte is consumed by 'fdp'.
42      * As a result, on larger inputs, AMediaCrypto_isCryptoSchemeSupported can run a large
43      * number of times, potentially causing a timeout crash.
44      * Therefore, to prevent this issue, while loop is limited to kMaxRuns.
45      */
46     while (fdp.remaining_bytes() && ++apiCount <= kMaxRuns) {
47         auto invokeNdkCryptoFuzzer = fdp.PickValueInArray<const std::function<void()>>({
48                 [&]() {
49                     AMediaCrypto_requiresSecureDecoderComponent(
50                             fdp.ConsumeRandomLengthString(kMaxString).c_str());
51                 },
52                 [&]() { AMediaCrypto_isCryptoSchemeSupported(uuid); },
53         });
54         invokeNdkCryptoFuzzer();
55     }
56     AMediaCrypto_delete(crypto);
57     return 0;
58 }
59