1 /*
2 * Copyright (c) 2022 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 #include "systemabilitymanager_fuzzer.h"
17
18 #include "if_system_ability_manager.h"
19 #include "sam_mock_permission.h"
20 #include "system_ability_manager.h"
21
22 #include <cstddef>
23 #include <cstdint>
24 #include <unistd.h>
25 #include <cstdlib>
26 #include <fcntl.h>
27
28 namespace OHOS {
29 namespace Samgr {
30 namespace {
31 constexpr size_t THRESHOLD = 10;
32 constexpr uint8_t MAX_CALL_TRANSACTION = 64;
33 constexpr int32_t OFFSET = 4;
34 const std::u16string SAMGR_INTERFACE_TOKEN = u"ohos.samgr.accessToken";
35 bool flag_ = false;
36 }
37
Convert2Uint32(const uint8_t * ptr)38 uint32_t Convert2Uint32(const uint8_t* ptr)
39 {
40 if (ptr == nullptr) {
41 return 0;
42 }
43 return (ptr[0] << 24) | (ptr[1] << 16) | (ptr[2] << 8) | (ptr[3]); // this is a general method of converting in fuzz
44 }
45
FuzzSystemAbilityManager(const uint8_t * rawData,size_t size)46 void FuzzSystemAbilityManager(const uint8_t* rawData, size_t size)
47 {
48 SamMockPermission::MockPermission();
49 uint32_t code = Convert2Uint32(rawData);
50 rawData = rawData + OFFSET;
51 size = size - OFFSET;
52 MessageParcel data;
53 data.WriteInterfaceToken(SAMGR_INTERFACE_TOKEN);
54 data.WriteBuffer(rawData, size);
55 data.RewindRead(0);
56 MessageParcel reply;
57 MessageOption option;
58 sptr<SystemAbilityManager> manager = SystemAbilityManager::GetInstance();
59 if (!flag_) {
60 manager->Init();
61 flag_ = true;
62 }
63 manager->OnRemoteRequest(code % MAX_CALL_TRANSACTION, data, reply, option);
64 }
65 }
66 }
67
68 /* Fuzzer entry point */
LLVMFuzzerTestOneInput(const uint8_t * data,size_t size)69 extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size)
70 {
71 if (size < OHOS::Samgr::THRESHOLD) {
72 return 0;
73 }
74
75 OHOS::Samgr::FuzzSystemAbilityManager(data, size);
76 return 0;
77 }
78
79