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
FuzzTimeRequestTime(const uint8_t * data,size_t size)66 bool FuzzTimeRequestTime(const uint8_t *data, size_t size)
67 {
68 std::string host(reinterpret_cast<const char *>(data), size);
69 SNTPClient client;
70 client.RequestTime(host);
71 return true;
72 }
73 } // namespace OHOS
74
75 /* Fuzzer entry point */
LLVMFuzzerTestOneInput(const uint8_t * data,size_t size)76 extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size)
77 {
78 if (size < OHOS::THRESHOLD) {
79 return 0;
80 }
81
82 /* Run your code on data */
83 OHOS::FuzzTimeCreateMessage(data, size);
84 OHOS::FuzzTimeReceivedMessage(data, size);
85 OHOS::FuzzTimeRequestTime(data, size);
86 return 0;
87 }