1 /*
2  * Copyright (c) 2023 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 "huks_hdi_fuzzer.h"
17 #include "huks_hdi_passthrough_adapter.h"
18 #include "huks_hdi_fuzz_common.h"
19 
20 #include <cstddef>
21 #include <cstdint>
22 #include <securec.h>
23 
24 struct HuksHdi *g_instance = nullptr;
25 
26 #define INIT_KEY_ALIAS_SIZE 27
27 
DoSomethingInterestingWithMyAPI(const uint8_t * data,size_t size)28 bool DoSomethingInterestingWithMyAPI(const uint8_t* data, size_t size)
29 {
30     if (data == nullptr || size <= (sizeof(struct HksParamSet) + INIT_KEY_ALIAS_SIZE)) {
31         return false;
32     }
33     uint8_t *myData = static_cast<uint8_t *>(malloc(sizeof(uint8_t) * size));
34     if (myData == nullptr) {
35         return false;
36     }
37     (void)memcpy_s(myData, size, data, size);
38     struct HksBlob keyAlias = { INIT_KEY_ALIAS_SIZE, myData };
39     struct HksParamSet *paramSetIn = reinterpret_cast<struct HksParamSet *>(myData + INIT_KEY_ALIAS_SIZE);
40     paramSetIn->paramSetSize = size - INIT_KEY_ALIAS_SIZE;
41 #ifdef HUKS_HDI_SOFTWARE
42     if (HuksFreshParamSet(paramSetIn, false) != 0) {
43         free(myData);
44         return false;
45     }
46 #endif
47     uint8_t keyBuff[1] = {0};
48     struct HksBlob key = {
49         .data = keyBuff,
50         .size = sizeof(keyBuff)
51     };
52     uint8_t buffer[1024];
53     struct HksBlob out = {
54         .data = buffer,
55         .size = sizeof(buffer)
56     };
57     (void)g_instance->HuksHdiGenerateKey(&keyAlias, paramSetIn, &key, &out);
58     free(myData);
59     return true;
60 }
61 
62 /* Fuzzer entry point */
LLVMFuzzerTestOneInput(const uint8_t * data,size_t size)63 extern "C" int32_t LLVMFuzzerTestOneInput(const uint8_t *data, size_t size)
64 {
65     if (InitHuksCoreEngine(&g_instance) != 0) {
66         return -1;
67     }
68     DoSomethingInterestingWithMyAPI(data, size);
69     return 0;
70 }
71