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 <securec.h>
17
18 #include "huks_hdi_fuzz_common.h"
19
20 #define HKS_TAG_TYPE_MASK (0xF << 28)
21 #define HKS_TAG_TYPE_BYTES (5 << 28)
22
InitHuksCoreEngine(struct HuksHdi ** coreEngine)23 int32_t InitHuksCoreEngine(struct HuksHdi **coreEngine)
24 {
25 if (coreEngine == nullptr) {
26 return -1;
27 }
28 if (*coreEngine != nullptr) {
29 return 0;
30 }
31 int ret = HuksInitHuksCoreEngine();
32 if (ret == 0) {
33 struct HuksHdi *instance = HuksGetCoreEngine();
34 if (instance->HuksHdiModuleInit() == 0) {
35 *coreEngine = instance;
36 return 0;
37 }
38 }
39 return -1;
40 }
41
GetTagType(uint32_t tag)42 static uint32_t GetTagType(uint32_t tag)
43 {
44 return (tag & (uint32_t)HKS_TAG_TYPE_MASK);
45 }
46
IsAdditionOverflow(uint32_t a,uint32_t b)47 static inline bool IsAdditionOverflow(uint32_t a, uint32_t b)
48 {
49 return (UINT32_MAX - a) < b;
50 }
51
HuksFreshParamSet(struct HksParamSet * paramSet,bool isCopy)52 int32_t HuksFreshParamSet(struct HksParamSet *paramSet, bool isCopy)
53 {
54 uint32_t size = paramSet->paramSetSize;
55 uint32_t offset = sizeof(struct HksParamSet) + sizeof(struct HksParam) * paramSet->paramsCnt;
56
57 for (uint32_t i = 0; i < paramSet->paramsCnt; i++) {
58 if (offset > size) {
59 return HUKS_FAILURE;
60 }
61 if (GetTagType(paramSet->params[i].tag) == HKS_TAG_TYPE_BYTES) {
62 if (IsAdditionOverflow(offset, paramSet->params[i].blob.size)) {
63 return HUKS_FAILURE;
64 }
65
66 if (isCopy && (memcpy_s((uint8_t *)paramSet + offset, size - offset,
67 paramSet->params[i].blob.data, paramSet->params[i].blob.size) != EOK)) {
68 return HUKS_FAILURE;
69 }
70 paramSet->params[i].blob.data = (uint8_t *)paramSet + offset;
71 offset += paramSet->params[i].blob.size;
72 }
73 }
74
75 if (paramSet->paramSetSize != offset) {
76 return HUKS_FAILURE;
77 }
78 return HUKS_SUCCESS;
79 }