1 /*
2 * Copyright (c) 2024 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 <iostream>
17 #include <cstddef>
18 #include <cstdint>
19 #include <cstring>
20 #undef private
21 #include "audio_info.h"
22 #include "audio_policy_server.h"
23 #include "audio_interrupt_service.h"
24 #include "audio_socket_thread.h"
25 #include "audio_pnp_server.h"
26 #include "audio_input_thread.h"
27 #include "accesstoken_kit.h"
28 #include "nativetoken_kit.h"
29 #include "token_setproc.h"
30 #include "access_token.h"
31
32 using namespace std;
33
34 namespace OHOS {
35 namespace AudioStandard {
36 using namespace std;
37 const int32_t LIMITSIZE = 4;
38 bool g_hasPnpServerInit = false;
39 bool g_hasServerInit = false;
40 bool g_hasPermission = false;
41 const std::u16string FORMMGR_INTERFACE_TOKEN = u"IAudioPolicy";
42 const bool RUN_ON_CREATE = false;
43 const int32_t SYSTEM_ABILITY_ID = 3009;
44 const string DEFAULTNAME = "name";
45 const string DEFAULTADDRESS = "address";
46 const string DEFAULTINFO = "EVENT_NAME=name;DEVICE_ADDRESS=address";
47 const ssize_t DEFAULTSTRLENGTH = 2;
48 static const uint8_t *RAW_DATA = nullptr;
49 static size_t g_dataSize = 0;
50 static size_t g_pos;
51 const size_t THRESHOLD = 10;
52
GetServerPtr()53 AudioPolicyServer* GetServerPtr()
54 {
55 static AudioPolicyServer server(SYSTEM_ABILITY_ID, RUN_ON_CREATE);
56 if (!g_hasServerInit) {
57 server.OnStart();
58 server.OnAddSystemAbility(AUDIO_DISTRIBUTED_SERVICE_ID, "");
59 #ifdef FEATURE_MULTIMODALINPUT_INPUT
60 server.OnAddSystemAbility(MULTIMODAL_INPUT_SERVICE_ID, "");
61 #endif
62 server.OnAddSystemAbility(BLUETOOTH_HOST_SYS_ABILITY_ID, "");
63 server.OnAddSystemAbility(POWER_MANAGER_SERVICE_ID, "");
64 server.OnAddSystemAbility(SUBSYS_ACCOUNT_SYS_ABILITY_ID_BEGIN, "");
65 server.audioPolicyService_.SetDefaultDeviceLoadFlag(true);
66 g_hasServerInit = true;
67 }
68 return &server;
69 }
70
AudioFuzzTestGetPermission()71 void AudioFuzzTestGetPermission()
72 {
73 if (!g_hasPermission) {
74 uint64_t tokenId;
75 constexpr int perNum = 10;
76 const char *perms[perNum] = {
77 "ohos.permission.MICROPHONE",
78 "ohos.permission.MANAGE_INTELLIGENT_VOICE",
79 "ohos.permission.MANAGE_AUDIO_CONFIG",
80 "ohos.permission.MICROPHONE_CONTROL",
81 "ohos.permission.MODIFY_AUDIO_SETTINGS",
82 "ohos.permission.ACCESS_NOTIFICATION_POLICY",
83 "ohos.permission.USE_BLUETOOTH",
84 "ohos.permission.CAPTURE_VOICE_DOWNLINK_AUDIO",
85 "ohos.permission.RECORD_VOICE_CALL",
86 "ohos.permission.MANAGE_SYSTEM_AUDIO_EFFECTS",
87 };
88
89 NativeTokenInfoParams infoInstance = {
90 .dcapsNum = 0,
91 .permsNum = 10,
92 .aclsNum = 0,
93 .dcaps = nullptr,
94 .perms = perms,
95 .acls = nullptr,
96 .processName = "audiofuzztest",
97 .aplStr = "system_basic",
98 };
99 tokenId = GetAccessTokenId(&infoInstance);
100 SetSelfTokenID(tokenId);
101 OHOS::Security::AccessToken::AccessTokenKit::ReloadNativeTokenInfo();
102 g_hasPermission = true;
103 }
104 }
105
106 /*
107 * describe: get data from outside untrusted data(RAW_DATA) which size is according to sizeof(T)
108 * tips: only support basic type
109 */
110 template<class T>
GetData()111 T GetData()
112 {
113 T object {};
114 size_t objectSize = sizeof(object);
115 if (RAW_DATA == nullptr || objectSize > g_dataSize - g_pos) {
116 return object;
117 }
118 errno_t ret = memcpy_s(&object, objectSize, RAW_DATA + g_pos, objectSize);
119 if (ret != EOK) {
120 return {};
121 }
122 g_pos += objectSize;
123 return object;
124 }
125
126 template<class T>
GetArrLength(T & arr)127 uint32_t GetArrLength(T& arr)
128 {
129 if (arr == nullptr) {
130 AUDIO_INFO_LOG("%{public}s: The array length is equal to 0", __func__);
131 return 0;
132 }
133 return sizeof(arr) / sizeof(arr[0]);
134 }
135
getAudioRenderInfo()136 static AudioRendererInfo getAudioRenderInfo()
137 {
138 ContentType contentType = GetData<ContentType>();
139 StreamUsage streamUsage = GetData<StreamUsage>();
140 int32_t rendererFlags = GetData<int32_t>();
141 std::string sceneType = "SCENE_MOVIE";
142 bool spatializationEnabled = GetData<bool>();
143 bool headTrackingEnabled = GetData<bool>();
144 int32_t originalFlag = GetData<int32_t>();
145 AudioRendererInfo rendererInfo = {
146 contentType,
147 streamUsage,
148 rendererFlags,
149 sceneType,
150 spatializationEnabled,
151 headTrackingEnabled,
152 originalFlag
153 };
154 return rendererInfo;
155 }
156
157 #ifdef AUDIO_WIRED_DETECT
GetPnpServerPtr()158 AudioPnpServer* GetPnpServerPtr()
159 {
160 static AudioPnpServer pnpServer;
161 if (!g_hasPnpServerInit) {
162 pnpServer.init();
163 g_hasPnpServerInit = true;
164 }
165 return &pnpServer;
166 }
167 #endif
168
InitFuzzTest()169 void InitFuzzTest()
170 {
171 sptr<AudioPolicyServer> server = nullptr;
172 std::shared_ptr<AudioInterruptService> interruptService = std::make_shared<AudioInterruptService>();
173 if (interruptService == nullptr) {
174 return;
175 }
176 interruptService->Init(server);
177 }
178
GetHighestPriorityAudioSceneFuzzTest()179 void GetHighestPriorityAudioSceneFuzzTest()
180 {
181 std::shared_ptr<AudioInterruptService> interruptService = std::make_shared<AudioInterruptService>();
182 int32_t zoneId = GetData<int32_t>();
183 if (interruptService == nullptr) {
184 return;
185 }
186 interruptService->GetHighestPriorityAudioScene(zoneId);
187 }
188
AudioInterruptZoneDumpFuzzTest()189 void AudioInterruptZoneDumpFuzzTest()
190 {
191 std::shared_ptr<AudioInterruptService> interruptService = std::make_shared<AudioInterruptService>();
192 std::string dumpString = "";
193 if (interruptService == nullptr) {
194 return;
195 }
196 interruptService->AudioInterruptZoneDump(dumpString);
197 }
198
ClearAudioFocusInfoListOnAccountsChangedFuzzTest()199 void ClearAudioFocusInfoListOnAccountsChangedFuzzTest()
200 {
201 std::shared_ptr<AudioInterruptService> interruptService = std::make_shared<AudioInterruptService>();
202 int zoneId = GetData<int32_t>();
203 if (interruptService == nullptr) {
204 return;
205 }
206 interruptService->ClearAudioFocusInfoListOnAccountsChanged(zoneId);
207 }
208
GetStreamTypePriorityFuzzTest()209 void GetStreamTypePriorityFuzzTest()
210 {
211 std::shared_ptr<AudioInterruptService> interruptService = std::make_shared<AudioInterruptService>();
212 OHOS::AudioStandard::AudioStreamType streamType = GetData<AudioStreamType>();
213 if (interruptService == nullptr) {
214 return;
215 }
216 interruptService->GetStreamTypePriority(streamType);
217 }
218
SendInterruptEventFuzzTest()219 void SendInterruptEventFuzzTest()
220 {
221 AudioFocuState oldState = GetData<AudioFocuState>();
222 AudioFocuState newState = GetData<AudioFocuState>();
223 std::shared_ptr<AudioInterruptService> interruptService = std::make_shared<AudioInterruptService>();
224 std::list<std::pair<AudioInterrupt, AudioFocuState>> focusInfoList = {};
225 std::pair<AudioInterrupt, AudioFocuState> focusInfo = {};
226 focusInfo.first.streamUsage = GetData<StreamUsage>();
227 focusInfo.first.contentType = GetData<ContentType>();
228 focusInfo.first.audioFocusType.streamType = GetData<AudioStreamType>();
229 focusInfo.first.audioFocusType.sourceType = GetData<SourceType>();
230 focusInfo.first.audioFocusType.isPlay = GetData<bool>();
231 focusInfo.first.sessionId = GetData<int32_t>();
232 focusInfo.first.pauseWhenDucked = GetData<bool>();
233 focusInfo.first.pid = GetData<int32_t>();
234 focusInfo.first.mode = GetData<InterruptMode>();
235 focusInfo.second = GetData<AudioFocuState>();
236 focusInfoList.push_back(focusInfo);
237 auto it = focusInfoList.begin();
238 if (interruptService == nullptr) {
239 return;
240 }
241 bool removeFocusInfo = GetData<bool>();
242 interruptService->SendInterruptEvent(oldState, newState, it, removeFocusInfo);
243 }
244
IsSameAppInShareModeFuzzTest()245 void IsSameAppInShareModeFuzzTest()
246 {
247 std::shared_ptr<AudioInterruptService> interruptService = std::make_shared<AudioInterruptService>();
248 AudioInterrupt incomingInterrupt;
249 AudioInterrupt activateInterrupt;
250 incomingInterrupt.contentType = GetData<ContentType>();
251 incomingInterrupt.streamUsage = GetData<StreamUsage>();
252 incomingInterrupt.audioFocusType.streamType = GetData<AudioStreamType>();
253 activateInterrupt.contentType = GetData<ContentType>();
254 activateInterrupt.streamUsage = GetData<StreamUsage>();
255 activateInterrupt.audioFocusType.streamType = GetData<AudioStreamType>();
256 if (interruptService == nullptr) {
257 return;
258 }
259 interruptService->IsSameAppInShareMode(incomingInterrupt, activateInterrupt);
260 }
261
SendFocusChangeEventFuzzTest()262 void SendFocusChangeEventFuzzTest()
263 {
264 std::shared_ptr<AudioInterruptService> interruptService = std::make_shared<AudioInterruptService>();
265 AudioInterrupt audioInterrupt;
266 int32_t zoneId = GetData<int32_t>();
267 int32_t callbackCategory = GetData<int32_t>();
268 audioInterrupt.contentType = GetData<ContentType>();
269 audioInterrupt.streamUsage = GetData<StreamUsage>();
270 audioInterrupt.audioFocusType.streamType = GetData<AudioStreamType>();
271 if (interruptService == nullptr) {
272 return;
273 }
274 interruptService->SendFocusChangeEvent(zoneId, callbackCategory, audioInterrupt);
275 }
276
GetAudioFocusInfoListFuzzTest()277 void GetAudioFocusInfoListFuzzTest()
278 {
279 std::list<std::pair<AudioInterrupt, AudioFocuState>> focusInfoList = {};
280 std::pair<AudioInterrupt, AudioFocuState> focusInfo = {};
281 focusInfo.first.streamUsage = GetData<StreamUsage>();
282 focusInfo.first.contentType = GetData<ContentType>();
283 focusInfo.first.audioFocusType.streamType = GetData<AudioStreamType>();
284 focusInfo.first.audioFocusType.sourceType = GetData<SourceType>();
285 focusInfo.first.audioFocusType.isPlay = GetData<bool>();
286 focusInfo.first.sessionId = GetData<int32_t>();
287 focusInfo.first.pauseWhenDucked = GetData<bool>();
288 focusInfo.first.pid = GetData<int32_t>();
289 focusInfo.first.mode = GetData<InterruptMode>();
290 focusInfo.second = GetData<AudioFocuState>();
291 focusInfoList.push_back(focusInfo);
292 std::shared_ptr<AudioInterruptService> interruptService = std::make_shared<AudioInterruptService>();
293 int32_t zoneId = GetData<int32_t>();
294 if (interruptService == nullptr) {
295 return;
296 }
297 interruptService->GetAudioFocusInfoList(zoneId, focusInfoList);
298 }
299
AudioVolumeMoreFuzzTest()300 void AudioVolumeMoreFuzzTest()
301 {
302 AudioStreamType streamType = GetData<AudioStreamType>();
303 VolumeAdjustType adjustType = GetData<VolumeAdjustType>();
304 int32_t volume = GetData<int32_t>();
305 int32_t streamId = GetData<int32_t>();
306 DeviceType deviceType = GetData<DeviceType>();
307 int32_t uid = GetData<int32_t>();
308 int32_t pid = GetData<int32_t>();
309
310 bool mute = GetData<bool>();
311 GetServerPtr()->SetSystemVolumeLevel(streamType, volume);
312 GetServerPtr()->GetSystemVolumeLevel(streamType);
313 GetServerPtr()->SetLowPowerVolume(streamId, volume);
314 GetServerPtr()->GetLowPowerVolume(streamId);
315 GetServerPtr()->GetSingleStreamVolume(streamId);
316 GetServerPtr()->SetStreamMute(streamType, mute);
317 GetServerPtr()->GetStreamMute(streamType);
318 GetServerPtr()->IsStreamActive(streamType);
319 GetServerPtr()->GetMaxVolumeLevel(streamType);
320 GetServerPtr()->GetMinVolumeLevel(streamType);
321 GetServerPtr()->SetSystemVolumeLevelLegacy(streamType, volume);
322 GetServerPtr()->IsVolumeUnadjustable();
323 GetServerPtr()->AdjustVolumeByStep(adjustType);
324 GetServerPtr()->AdjustSystemVolumeByStep(streamType, adjustType);
325 GetServerPtr()->GetSystemVolumeInDb(streamType, volume, deviceType);
326 GetServerPtr()->GetSelectedDeviceInfo(uid, pid, streamType);
327
328 AudioRendererInfo rendererInfo = getAudioRenderInfo();
329 GetServerPtr()->GetPreferredOutputStreamType(rendererInfo);
330
331 SourceType sourceType = GetData<SourceType>();
332 int32_t capturerFlags = GetData<int32_t>();
333 AudioCapturerInfo capturerInfo = {
334 sourceType,
335 capturerFlags
336 };
337 GetServerPtr()->GetPreferredInputStreamType(capturerInfo);
338 }
339
AudioDeviceMoreFuzzTest()340 void AudioDeviceMoreFuzzTest()
341 {
342 DeviceFlag flag = GetData<DeviceFlag>();
343 MessageParcel data;
344 data.WriteInterfaceToken(FORMMGR_INTERFACE_TOKEN);
345 data.WriteBuffer(RAW_DATA, g_dataSize);
346 data.RewindRead(0);
347 SourceType sourceType = GetData<SourceType>();
348 int32_t capturerFlags = GetData<int32_t>();
349 AudioCapturerInfo capturerInfo = {sourceType, capturerFlags};
350 AudioStreamInfo audioStreamInfo = {};
351 audioStreamInfo.samplingRate = GetData<AudioSamplingRate>();
352 audioStreamInfo.channels = GetData<AudioChannel>();
353 audioStreamInfo.format = GetData<AudioSampleFormat>();
354 audioStreamInfo.encoding = GetData<AudioEncodingType>();
355 InternalDeviceType deviceType = GetData<InternalDeviceType>();
356 uint32_t sessionId = GetData<uint32_t>();
357 bool active = GetData<bool>();
358 GetServerPtr()->SetDeviceActive(deviceType, active);
359 GetServerPtr()->IsDeviceActive(deviceType);
360 GetServerPtr()->GetDevices(flag);
361 GetServerPtr()->GetDevicesInner(flag);
362 AudioRingerMode ringMode = GetData<AudioRingerMode>();
363 GetServerPtr()->SetRingerMode(ringMode);
364 bool mute = GetData<bool>();
365 bool legacy = GetData<bool>();
366 GetServerPtr()->SetMicrophoneMute(mute);
367 GetServerPtr()->SetMicrophoneMuteCommon(mute, legacy);
368 GetServerPtr()->SetMicrophoneMuteAudioConfig(mute);
369
370 PolicyType type = GetData<PolicyType>();
371 GetServerPtr()->SetMicrophoneMutePersistent(mute, type);
372 GetServerPtr()->GetPersistentMicMuteState();
373 GetServerPtr()->IsMicrophoneMuteLegacy();
374 GetServerPtr()->GetAudioScene();
375
376 StreamUsage streamUsage = GetData<StreamUsage>();
377 GetServerPtr()->GetDirectPlaybackSupport(audioStreamInfo, streamUsage);
378 }
379
AudioPolicyOtherMoreFuzzTest()380 void AudioPolicyOtherMoreFuzzTest()
381 {
382 int pid = GetData<int>();
383 GetServerPtr()->RegisteredTrackerClientDied(pid, 0);
384
385 int32_t clientUid = GetData<int32_t>();
386 StreamSetState streamSetState = GetData<StreamSetState>();
387 StreamUsage streamUsage = STREAM_USAGE_MEDIA;
388 GetServerPtr()->UpdateStreamState(clientUid, streamSetState, streamUsage);
389 GetServerPtr()->IsHighResolutionExist();
390 bool highResExist = GetData<bool>();
391 GetServerPtr()->SetHighResolutionExist(highResExist);
392 }
393
AudioVolumeKeyCallbackStubMoreFuzzTest()394 void AudioVolumeKeyCallbackStubMoreFuzzTest()
395 {
396 sptr<AudioPolicyClientStub> listener =
397 static_cast<sptr<AudioPolicyClientStub>>(new(std::nothrow) AudioPolicyClientStubImpl());
398 VolumeEvent volumeEvent = {};
399 volumeEvent.volumeType = GetData<AudioStreamType>();
400 volumeEvent.volume = GetData<int32_t>();
401 volumeEvent.updateUi = GetData<bool>();
402 volumeEvent.volumeGroupId = GetData<int32_t>();
403 std::string id = "123";
404 volumeEvent.networkId = id;
405
406 MessageParcel data;
407 data.WriteInt32(static_cast<int32_t>(AudioPolicyClientCode::ON_VOLUME_KEY_EVENT));
408 data.WriteInt32(static_cast<int32_t>(volumeEvent.volumeType));
409 data.WriteInt32(volumeEvent.volume);
410 data.WriteBool(volumeEvent.updateUi);
411 data.WriteInt32(volumeEvent.volumeGroupId);
412 data.WriteString(volumeEvent.networkId);
413 MessageParcel reply;
414 MessageOption option;
415 listener->OnRemoteRequest(static_cast<uint32_t>(UPDATE_CALLBACK_CLIENT), data, reply, option);
416 }
417
AudioPolicyManagerFuzzTest()418 void AudioPolicyManagerFuzzTest()
419 {
420 #ifdef AUDIO_WIRED_DETECT
421 AudioEvent audioEvent;
422 uint32_t eventType = GetData<uint32_t>();
423 uint32_t deviceType = GetData<uint32_t>();
424 audioEvent.eventType = eventType;
425 audioEvent.deviceType = deviceType;
426 audioEvent.name = DEFAULTNAME;
427 audioEvent.address = DEFAULTADDRESS;
428 int fd = GetData<int>();
429 ssize_t strLength = DEFAULTSTRLENGTH;
430 const char *msg = "SCENE";
431 AudioSocketThread::IsUpdatePnpDeviceState(&audioEvent);
432 AudioSocketThread::UpdatePnpDeviceState(&audioEvent);
433 AudioSocketThread::AudioPnpUeventOpen(&fd);
434 AudioSocketThread::UpdateDeviceState(audioEvent);
435 AudioSocketThread::DetectAnalogHeadsetState(&audioEvent);
436 AudioSocketThread::SetAudioPnpUevent(&audioEvent);
437 AudioSocketThread::AudioPnpUeventParse(msg, strLength);
438 AudioInputThread::AudioPnpInputOpen();
439
440 GetPnpServerPtr()->GetAudioPnpServer();
441 GetPnpServerPtr()->UnRegisterPnpStatusListener();
442 GetPnpServerPtr()->OnPnpDeviceStatusChanged(DEFAULTINFO);
443 AudioInputThread::AudioPnpInputPollAndRead();
444 #endif
445 }
446
ForceVolumeKeyControlTypeFuzzTest()447 void ForceVolumeKeyControlTypeFuzzTest()
448 {
449 std::shared_ptr<AudioInterruptService> interruptService = std::make_shared<AudioInterruptService>();
450 int32_t volumeType = GetData<int32_t>();
451 int32_t duration = GetData<int32_t>();
452 if (interruptService == nullptr) {
453 return;
454 }
455 interruptService->ForceVolumeKeyControlType(static_cast<AudioVolumeType>(volumeType), duration);
456 }
457
458 typedef void (*TestFuncs[16])();
459
460 TestFuncs g_testFuncs = {
461 InitFuzzTest,
462 GetHighestPriorityAudioSceneFuzzTest,
463 AudioInterruptZoneDumpFuzzTest,
464 ClearAudioFocusInfoListOnAccountsChangedFuzzTest,
465 GetStreamTypePriorityFuzzTest,
466 SendInterruptEventFuzzTest,
467 IsSameAppInShareModeFuzzTest,
468 GetAudioFocusInfoListFuzzTest,
469 AudioVolumeMoreFuzzTest,
470 AudioDeviceMoreFuzzTest,
471 AudioPolicyOtherMoreFuzzTest,
472 AudioVolumeKeyCallbackStubMoreFuzzTest,
473 AudioPolicyManagerFuzzTest,
474 ForceVolumeKeyControlTypeFuzzTest,
475 };
476
FuzzTest(const uint8_t * rawData,size_t size)477 bool FuzzTest(const uint8_t* rawData, size_t size)
478 {
479 if (rawData == nullptr) {
480 return false;
481 }
482
483 // initialize data
484 RAW_DATA = rawData;
485 g_dataSize = size;
486 g_pos = 0;
487
488 uint32_t code = GetData<uint32_t>();
489 uint32_t len = GetArrLength(g_testFuncs);
490 if (len > 0) {
491 g_testFuncs[code % len]();
492 } else {
493 AUDIO_INFO_LOG("%{public}s: The len length is equal to 0", __func__);
494 }
495
496 return true;
497 }
498 } // namespace AudioStandard
499 } // namesapce OHOS
500
LLVMFuzzerInitialize(int * argc,char *** argv)501 extern "C" int LLVMFuzzerInitialize(int *argc, char ***argv)
502 {
503 OHOS::AudioStandard::AudioFuzzTestGetPermission();
504 return 0;
505 }
506
507 /* Fuzzer entry point */
LLVMFuzzerTestOneInput(const uint8_t * data,size_t size)508 extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size)
509 {
510 if (size < OHOS::AudioStandard::THRESHOLD) {
511 return 0;
512 }
513
514 OHOS::AudioStandard::FuzzTest(data, size);
515 return 0;
516 }
517