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 "timesntp_fuzzer.h"
17 
18 #include <cstddef>
19 #include <cstdint>
20 #include <string_ex.h>
21 
22 #include "time_service_fuzz_utils.h"
23 #define private public
24 #include "sntp_client.h"
25 
26 using namespace OHOS::MiscServices;
27 
28 namespace OHOS {
29 constexpr size_t THRESHOLD = 4;
30 constexpr size_t NTP_PACKAGE_SIZE = 48;
31 
Convert(const uint8_t * data,size_t size,char * buf)32 void Convert(const uint8_t *data, size_t size, char* buf)
33 {
34     size_t copySize = (size < NTP_PACKAGE_SIZE) ? size : NTP_PACKAGE_SIZE;
35 
36     for (size_t i = 0; i < copySize; ++i) {
37         buf[i] = static_cast<char>(data[i]);
38     }
39     for (size_t i = copySize; i < NTP_PACKAGE_SIZE; ++i) {
40         buf[i] = 0;
41     }
42 }
43 
FuzzTimeCreateMessage(const uint8_t * data,size_t size)44 bool FuzzTimeCreateMessage(const uint8_t *data, size_t size)
45 {
46     char sendBuf[NTP_PACKAGE_SIZE] = { 0 };
47 
48     Convert(data, size, sendBuf);
49 
50     SNTPClient client;
51     client.CreateMessage(sendBuf);
52     return true;
53 }
54 
FuzzTimeReceivedMessage(const uint8_t * data,size_t size)55 bool FuzzTimeReceivedMessage(const uint8_t *data, size_t size)
56 {
57     char sendBuf[NTP_PACKAGE_SIZE] = { 0 };
58 
59     Convert(data, size, sendBuf);
60 
61     SNTPClient client;
62     client.ReceivedMessage(sendBuf);
63     return true;
64 }
65 
66 } // namespace OHOS
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::THRESHOLD) {
72         return 0;
73     }
74 
75     /* Run your code on data */
76     OHOS::FuzzTimeCreateMessage(data, size);
77     OHOS::FuzzTimeReceivedMessage(data, size);
78     return 0;
79 }