• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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(DISTRIBUTED_KV_DATA_SERVICE_ABILITY_ID, "");
63         server.OnAddSystemAbility(BLUETOOTH_HOST_SYS_ABILITY_ID, "");
64         server.OnAddSystemAbility(POWER_MANAGER_SERVICE_ID, "");
65         server.OnAddSystemAbility(SUBSYS_ACCOUNT_SYS_ABILITY_ID_BEGIN, "");
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 
GetStreamPriorityMapFuzzTest()219 void GetStreamPriorityMapFuzzTest()
220 {
221     std::shared_ptr<AudioInterruptService> interruptService = std::make_shared<AudioInterruptService>();
222     if (interruptService == nullptr) {
223         return;
224     }
225     interruptService->GetStreamPriorityMap();
226 }
227 
SendInterruptEventFuzzTest()228 void SendInterruptEventFuzzTest()
229 {
230     AudioFocuState oldState = GetData<AudioFocuState>();
231     AudioFocuState newState = GetData<AudioFocuState>();
232     std::shared_ptr<AudioInterruptService> interruptService = std::make_shared<AudioInterruptService>();
233     std::list<std::pair<AudioInterrupt, AudioFocuState>> focusInfoList = {};
234     std::pair<AudioInterrupt, AudioFocuState> focusInfo = {};
235     focusInfo.first.streamUsage = GetData<StreamUsage>();
236     focusInfo.first.contentType = GetData<ContentType>();
237     focusInfo.first.audioFocusType.streamType = GetData<AudioStreamType>();
238     focusInfo.first.audioFocusType.sourceType = GetData<SourceType>();
239     focusInfo.first.audioFocusType.isPlay = GetData<bool>();
240     focusInfo.first.sessionId = GetData<int32_t>();
241     focusInfo.first.pauseWhenDucked = GetData<bool>();
242     focusInfo.first.pid = GetData<int32_t>();
243     focusInfo.first.mode = GetData<InterruptMode>();
244     focusInfo.second = GetData<AudioFocuState>();
245     focusInfoList.push_back(focusInfo);
246     auto it = focusInfoList.begin();
247     if (interruptService == nullptr) {
248         return;
249     }
250     bool removeFocusInfo = GetData<bool>();
251     interruptService->SendInterruptEvent(oldState, newState, it, removeFocusInfo);
252 }
253 
IsSameAppInShareModeFuzzTest()254 void IsSameAppInShareModeFuzzTest()
255 {
256     std::shared_ptr<AudioInterruptService> interruptService = std::make_shared<AudioInterruptService>();
257     AudioInterrupt incomingInterrupt, activateInterrupt;
258     incomingInterrupt.contentType = GetData<ContentType>();
259     incomingInterrupt.streamUsage = GetData<StreamUsage>();
260     incomingInterrupt.audioFocusType.streamType = GetData<AudioStreamType>();
261     activateInterrupt.contentType = GetData<ContentType>();
262     activateInterrupt.streamUsage = GetData<StreamUsage>();
263     activateInterrupt.audioFocusType.streamType = GetData<AudioStreamType>();
264     if (interruptService == nullptr) {
265         return;
266     }
267     interruptService->IsSameAppInShareMode(incomingInterrupt, activateInterrupt);
268 }
269 
SendFocusChangeEventFuzzTest()270 void SendFocusChangeEventFuzzTest()
271 {
272     std::shared_ptr<AudioInterruptService> interruptService = std::make_shared<AudioInterruptService>();
273     AudioInterrupt audioInterrupt;
274     int32_t zoneId = GetData<int32_t>();
275     int32_t callbackCategory = GetData<int32_t>();
276     audioInterrupt.contentType = GetData<ContentType>();
277     audioInterrupt.streamUsage = GetData<StreamUsage>();
278     audioInterrupt.audioFocusType.streamType = GetData<AudioStreamType>();
279     if (interruptService == nullptr) {
280         return;
281     }
282     interruptService->SendFocusChangeEvent(zoneId, callbackCategory, audioInterrupt);
283 }
284 
GetAudioFocusInfoListFuzzTest()285 void GetAudioFocusInfoListFuzzTest()
286 {
287     std::list<std::pair<AudioInterrupt, AudioFocuState>> focusInfoList = {};
288     std::pair<AudioInterrupt, AudioFocuState> focusInfo = {};
289     focusInfo.first.streamUsage = GetData<StreamUsage>();
290     focusInfo.first.contentType = GetData<ContentType>();
291     focusInfo.first.audioFocusType.streamType = GetData<AudioStreamType>();
292     focusInfo.first.audioFocusType.sourceType = GetData<SourceType>();
293     focusInfo.first.audioFocusType.isPlay = GetData<bool>();
294     focusInfo.first.sessionId = GetData<int32_t>();
295     focusInfo.first.pauseWhenDucked = GetData<bool>();
296     focusInfo.first.pid = GetData<int32_t>();
297     focusInfo.first.mode = GetData<InterruptMode>();
298     focusInfo.second = GetData<AudioFocuState>();
299     focusInfoList.push_back(focusInfo);
300     std::shared_ptr<AudioInterruptService> interruptService = std::make_shared<AudioInterruptService>();
301     int32_t zoneId = GetData<int32_t>();
302     if (interruptService == nullptr) {
303         return;
304     }
305     interruptService->GetAudioFocusInfoList(zoneId, focusInfoList);
306 }
307 
AudioVolumeMoreFuzzTest()308 void AudioVolumeMoreFuzzTest()
309 {
310     AudioStreamType streamType = GetData<AudioStreamType>();
311     VolumeAdjustType adjustType = GetData<VolumeAdjustType>();
312     int32_t volume = GetData<int32_t>();
313     int32_t streamId = GetData<int32_t>();
314     DeviceType deviceType = GetData<DeviceType>();
315     int32_t uid = GetData<int32_t>();
316     int32_t pid = GetData<int32_t>();
317 
318     bool mute = GetData<bool>();
319     GetServerPtr()->SetSystemVolumeLevel(streamType, volume);
320     GetServerPtr()->GetSystemVolumeLevel(streamType);
321     GetServerPtr()->SetLowPowerVolume(streamId, volume);
322     GetServerPtr()->GetLowPowerVolume(streamId);
323     GetServerPtr()->GetSingleStreamVolume(streamId);
324     GetServerPtr()->SetStreamMute(streamType, mute);
325     GetServerPtr()->GetStreamMute(streamType);
326     GetServerPtr()->IsStreamActive(streamType);
327     GetServerPtr()->GetMaxVolumeLevel(streamType);
328     GetServerPtr()->GetMinVolumeLevel(streamType);
329     GetServerPtr()->SetSystemVolumeLevelLegacy(streamType, volume);
330     GetServerPtr()->IsVolumeUnadjustable();
331     GetServerPtr()->AdjustVolumeByStep(adjustType);
332     GetServerPtr()->AdjustSystemVolumeByStep(streamType, adjustType);
333     GetServerPtr()->GetSystemVolumeInDb(streamType, volume, deviceType);
334     GetServerPtr()->GetSelectedDeviceInfo(uid, pid, streamType);
335 
336     AudioRendererInfo rendererInfo = getAudioRenderInfo();
337     GetServerPtr()->GetPreferredOutputStreamType(rendererInfo);
338 
339     SourceType sourceType = GetData<SourceType>();
340     int32_t capturerFlags = GetData<int32_t>();
341     AudioCapturerInfo capturerInfo = {
342         sourceType,
343         capturerFlags
344     };
345     GetServerPtr()->GetPreferredInputStreamType(capturerInfo);
346 }
347 
AudioDeviceMoreFuzzTest()348 void AudioDeviceMoreFuzzTest()
349 {
350     DeviceFlag flag = GetData<DeviceFlag>();
351     MessageParcel data;
352     data.WriteInterfaceToken(FORMMGR_INTERFACE_TOKEN);
353     data.WriteBuffer(RAW_DATA, g_dataSize);
354     data.RewindRead(0);
355     SourceType sourceType = GetData<SourceType>();
356     int32_t capturerFlags = GetData<int32_t>();
357     AudioCapturerInfo capturerInfo = {sourceType, capturerFlags};
358     AudioStreamInfo audioStreamInfo = {};
359     audioStreamInfo.samplingRate = GetData<AudioSamplingRate>();
360     audioStreamInfo.channels = GetData<AudioChannel>();
361     audioStreamInfo.format = GetData<AudioSampleFormat>();
362     audioStreamInfo.encoding = GetData<AudioEncodingType>();
363     InternalDeviceType deviceType = GetData<InternalDeviceType>();
364     uint32_t sessionId = GetData<uint32_t>();
365     bool active = GetData<bool>();
366     GetServerPtr()->SetDeviceActive(deviceType, active);
367     GetServerPtr()->IsDeviceActive(deviceType);
368     GetServerPtr()->GetDevices(flag);
369     GetServerPtr()->GetDevicesInner(flag);
370     AudioRingerMode ringMode = GetData<AudioRingerMode>();
371     GetServerPtr()->SetRingerMode(ringMode);
372     bool mute = GetData<bool>();
373     bool legacy = GetData<bool>();
374     GetServerPtr()->SetMicrophoneMute(mute);
375     GetServerPtr()->SetMicrophoneMuteCommon(mute, legacy);
376     GetServerPtr()->SetMicrophoneMuteAudioConfig(mute);
377 
378     PolicyType type = GetData<PolicyType>();
379     GetServerPtr()->SetMicrophoneMutePersistent(mute, type);
380     GetServerPtr()->GetPersistentMicMuteState();
381     GetServerPtr()->IsMicrophoneMuteLegacy();
382     GetServerPtr()->GetAudioScene();
383 }
384 
AudioPolicySomeMoreFuzzTest()385 void AudioPolicySomeMoreFuzzTest()
386 {
387     uint32_t sessionID = GetData<uint32_t>();
388     GetServerPtr()->OnAudioStreamRemoved(sessionID);
389     GetServerPtr()->ProcessSessionRemoved(sessionID);
390     GetServerPtr()->ProcessorCloseWakeupSource(sessionID);
391 }
392 
AudioPolicyOtherMoreFuzzTest()393 void AudioPolicyOtherMoreFuzzTest()
394 {
395     int pid = GetData<int>();
396     GetServerPtr()->RegisteredTrackerClientDied(pid, 0);
397 
398     int32_t clientUid = GetData<int32_t>();
399     StreamSetState streamSetState = GetData<StreamSetState>();
400     StreamUsage streamUsage = STREAM_USAGE_MEDIA;
401     GetServerPtr()->UpdateStreamState(clientUid, streamSetState, streamUsage);
402     GetServerPtr()->IsHighResolutionExist();
403     bool highResExist = GetData<bool>();
404     GetServerPtr()->SetHighResolutionExist(highResExist);
405 }
406 
AudioVolumeKeyCallbackStubMoreFuzzTest()407 void AudioVolumeKeyCallbackStubMoreFuzzTest()
408 {
409     sptr<AudioPolicyClientStub> listener =
410         static_cast<sptr<AudioPolicyClientStub>>(new(std::nothrow) AudioPolicyClientStubImpl());
411     VolumeEvent volumeEvent = {};
412     volumeEvent.volumeType =  GetData<AudioStreamType>();
413     volumeEvent.volume = GetData<int32_t>();
414     volumeEvent.updateUi = GetData<bool>();
415     volumeEvent.volumeGroupId = GetData<int32_t>();
416     std::string id = "123";
417     volumeEvent.networkId = id;
418 
419     MessageParcel data;
420     data.WriteInt32(static_cast<int32_t>(AudioPolicyClientCode::ON_VOLUME_KEY_EVENT));
421     data.WriteInt32(static_cast<int32_t>(volumeEvent.volumeType));
422     data.WriteInt32(volumeEvent.volume);
423     data.WriteBool(volumeEvent.updateUi);
424     data.WriteInt32(volumeEvent.volumeGroupId);
425     data.WriteString(volumeEvent.networkId);
426     MessageParcel reply;
427     MessageOption option;
428     listener->OnRemoteRequest(static_cast<uint32_t>(UPDATE_CALLBACK_CLIENT), data, reply, option);
429 }
430 
AudioPolicyManagerFuzzTest()431 void AudioPolicyManagerFuzzTest()
432 {
433 #ifdef AUDIO_WIRED_DETECT
434     AudioEvent audioEvent;
435     uint32_t eventType = GetData<uint32_t>();
436     uint32_t deviceType = GetData<uint32_t>();
437     audioEvent.eventType = eventType;
438     audioEvent.deviceType = deviceType;
439     audioEvent.name = DEFAULTNAME;
440     audioEvent.address = DEFAULTADDRESS;
441     int fd = GetData<int>();
442     ssize_t strLength = DEFAULTSTRLENGTH;
443     const char *msg = "SCENE";
444     AudioSocketThread::IsUpdatePnpDeviceState(&audioEvent);
445     AudioSocketThread::UpdatePnpDeviceState(&audioEvent);
446     AudioSocketThread::AudioPnpUeventOpen(&fd);
447     AudioSocketThread::UpdateDeviceState(audioEvent);
448     AudioSocketThread::DetectAnalogHeadsetState(&audioEvent);
449     AudioSocketThread::AudioPnpUeventParse(msg, strLength);
450     AudioInputThread::AudioPnpInputOpen();
451 
452     GetPnpServerPtr()->GetAudioPnpServer();
453     GetPnpServerPtr()->UnRegisterPnpStatusListener();
454     GetPnpServerPtr()->OnPnpDeviceStatusChanged(DEFAULTINFO);
455     AudioInputThread::AudioPnpInputPollAndRead();
456 #endif
457 }
458 
459 typedef void (*TestFuncs[15])();
460 
461 TestFuncs g_testFuncs = {
462     InitFuzzTest,
463     GetHighestPriorityAudioSceneFuzzTest,
464     AudioInterruptZoneDumpFuzzTest,
465     ClearAudioFocusInfoListOnAccountsChangedFuzzTest,
466     GetStreamTypePriorityFuzzTest,
467     GetStreamPriorityMapFuzzTest,
468     SendInterruptEventFuzzTest,
469     IsSameAppInShareModeFuzzTest,
470     GetAudioFocusInfoListFuzzTest,
471     AudioVolumeMoreFuzzTest,
472     AudioDeviceMoreFuzzTest,
473     AudioPolicySomeMoreFuzzTest,
474     AudioPolicyOtherMoreFuzzTest,
475     AudioVolumeKeyCallbackStubMoreFuzzTest,
476     AudioPolicyManagerFuzzTest,
477 };
478 
FuzzTest(const uint8_t * rawData,size_t size)479 bool FuzzTest(const uint8_t* rawData, size_t size)
480 {
481     if (rawData == nullptr) {
482         return false;
483     }
484 
485     // initialize data
486     RAW_DATA = rawData;
487     g_dataSize = size;
488     g_pos = 0;
489 
490     uint32_t code = GetData<uint32_t>();
491     uint32_t len = GetArrLength(g_testFuncs);
492     if (len > 0) {
493         g_testFuncs[code % len]();
494     } else {
495         AUDIO_INFO_LOG("%{public}s: The len length is equal to 0", __func__);
496     }
497 
498     return true;
499 }
500 } // namespace AudioStandard
501 } // namesapce OHOS
502 
LLVMFuzzerInitialize(int * argc,char *** argv)503 extern "C" int LLVMFuzzerInitialize(int *argc, char ***argv)
504 {
505     OHOS::AudioStandard::AudioFuzzTestGetPermission();
506     return 0;
507 }
508 
509 /* Fuzzer entry point */
LLVMFuzzerTestOneInput(const uint8_t * data,size_t size)510 extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size)
511 {
512     if (size < OHOS::AudioStandard::THRESHOLD) {
513         return 0;
514     }
515 
516     OHOS::AudioStandard::FuzzTest(data, size);
517     return 0;
518 }
519