• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2021-2025 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 #define HUKS_DISABLE_LOG_AT_FILE_TO_REDUCE_ROM_SIZE
16 
17 #include "hks_error_code.h"
18 #ifdef HKS_CONFIG_FILE
19 #include HKS_CONFIG_FILE
20 #else
21 #include "hks_config.h"
22 #endif
23 
24 #include "hks_client_service.h"
25 
26 #include <stdbool.h>
27 #include <stddef.h>
28 #include <stdint.h>
29 #include <stdatomic.h>
30 #include "hks_type.h"
31 #include "hks_base_check.h"
32 #include "hks_client_check.h"
33 #ifdef HKS_SUPPORT_API_ATTEST_KEY
34 #include "hks_client_service_dcm.h"
35 #include "parameter.h"
36 #endif
37 #include "hks_client_service_common.h"
38 #include "hks_client_service_util.h"
39 #include "hks_common_check.h"
40 #include "hks_event_info.h"
41 #include "hks_hitrace.h"
42 #include "hks_log.h"
43 #include "hks_mem.h"
44 #include "hks_param.h"
45 #include "hks_permission_check.h"
46 #include "hks_plugin_adapter.h"
47 #include "hks_report.h"
48 #include "hks_session_manager.h"
49 #include "hks_storage.h"
50 #include "hks_storage_manager.h"
51 #include "hks_template.h"
52 #include "huks_access.h"
53 #include "hks_util.h"
54 
55 #include "hks_upgrade_key_accesser.h"
56 #include "hks_upgrade_helper.h"
57 #include "hks_report_generate_key.h"
58 #include "hks_report_delete_key.h"
59 #include "hks_report_import_key.h"
60 #include "hks_report_list_aliases.h"
61 #include "hks_report_check_key_exited.h"
62 #include "hks_report_rename_key.h"
63 #include "hks_report_data_size.h"
64 #include "hks_report_common.h"
65 #include "hks_report_three_stage_get.h"
66 #include "hks_type_enum.h"
67 #include "hks_type_inner.h"
68 
69 #ifdef L2_STANDARD
70 #include "hks_ha_event_report.h"
71 #endif
72 
73 #ifdef HKS_ENABLE_SMALL_TO_SERVICE
74 #include "hks_get_process_info.h"
75 
76 #include <string.h>
77 #endif
78 
79 #include "securec.h"
80 
81 #ifdef HKS_SUPPORT_USER_AUTH_ACCESS_CONTROL
82 #include "hks_useridm_api_wrap.h"
83 #endif
84 
85 #ifdef HKS_SUPPORT_GET_BUNDLE_INFO
86 #include "hks_bms_api_wrap.h"
87 #endif
88 #ifdef HUKS_ENABLE_SKIP_UPGRADE_KEY_STORAGE_SECURE_LEVEL
89 #include "hks_config_parser.h"
90 #endif
91 
IfNotSuccAppendHdiErrorInfo(int32_t hdiRet)92 static void IfNotSuccAppendHdiErrorInfo(int32_t hdiRet)
93 {
94     (void)hdiRet;
95 #ifdef L2_STANDARD
96     if (hdiRet == HKS_SUCCESS) {
97         return;
98     }
99     uint32_t errInfoSize = sizeof(struct ErrorInfo);
100     uint8_t *errInfo = (uint8_t *)HksMalloc(errInfoSize);
101     HKS_IF_NULL_RETURN_VOID(errInfo)
102     struct HksBlob errMsg = {.size =  errInfoSize, .data = errInfo};
103     int32_t ret = HuksAccessGetErrorInfo(&errMsg);
104     if (ret == HKS_ERROR_API_NOT_SUPPORTED) {
105         HKS_FREE(errInfo);
106         return;
107     }
108     uint32_t offset = sizeof(struct ErrorInfoHead);
109     if (ret == HKS_SUCCESS && CheckBlob(&errMsg) == HKS_SUCCESS && errMsg.size > offset) {
110         HksAppendThreadErrMsg((uint8_t *)(errMsg.data + offset), errMsg.size - offset);
111     } else {
112         HKS_LOG_E("HuksAccessGetErrorInfo fail, ret = %" LOG_PUBLIC "d, errMsg size = %" LOG_PUBLIC "u",
113             ret, errMsg.size);
114     }
115     HKS_FREE(errInfo);
116 #endif
117 }
118 
119 #ifndef _CUT_AUTHENTICATE_
120 #ifdef _STORAGE_LITE_
GetKeyData(const struct HksProcessInfo * processInfo,const struct HksBlob * keyAlias,const struct HksParamSet * paramSet,struct HksBlob * key,enum HksStorageType mode)121 static int32_t GetKeyData(const struct HksProcessInfo *processInfo, const struct HksBlob *keyAlias,
122     const struct HksParamSet *paramSet, struct HksBlob *key, enum HksStorageType mode)
123 {
124     (void)paramSet;
125     int32_t ret = HksManageStoreGetKeyBlob(processInfo, NULL, keyAlias, key, mode);
126     HKS_IF_NOT_SUCC_LOGE(ret, "get key blob from storage failed, ret = %" LOG_PUBLIC "d", ret)
127     return ret;
128 }
129 
CheckKeyCondition(const struct HksProcessInfo * processInfo,const struct HksBlob * keyAlias,const struct HksParamSet * paramSet)130 static int32_t CheckKeyCondition(const struct HksProcessInfo *processInfo, const struct HksBlob *keyAlias,
131     const struct HksParamSet *paramSet)
132 {
133     (void)paramSet;
134     /* check is enough buffer to store */
135     uint32_t size = 0;
136     int32_t ret = HksStoreGetToatalSize(&size);
137     HKS_IF_NOT_SUCC_LOGE_RETURN(ret, ret, "get total size from storage failed, ret = %" LOG_PUBLIC "d", ret)
138 
139     if (size >= MAX_KEY_SIZE) {
140         /* is key exist */
141         ret = HksManageStoreIsKeyBlobExist(processInfo, NULL, keyAlias, HKS_STORAGE_TYPE_KEY);
142         HKS_IF_NOT_SUCC_LOGE_RETURN(ret, HKS_ERROR_STORAGE_FAILURE, "buffer exceeds limit")
143     }
144 
145     return HKS_SUCCESS;
146 }
147 
HksServiceGetKeyInfoList(const struct HksProcessInfo * processInfo,const struct HksParamSet * paramSet,struct HksKeyInfo * keyInfoList,uint32_t * listCount)148 int32_t HksServiceGetKeyInfoList(const struct HksProcessInfo *processInfo, const struct HksParamSet *paramSet,
149     struct HksKeyInfo *keyInfoList, uint32_t *listCount)
150 {
151     (void)paramSet;
152     int32_t ret = HksCheckGetKeyInfoListParams(&(processInfo->processName), keyInfoList, listCount);
153     HKS_IF_NOT_SUCC_RETURN(ret, ret)
154 
155     ret = HksStoreGetKeyInfoList(keyInfoList, listCount);
156 
157 #ifdef L2_STANDARD
158     HksReport(__func__, processInfo, NULL, ret);
159 #endif
160 
161     return ret;
162 }
163 #else
164 
165 #ifdef HKS_ENABLE_UPGRADE_KEY
CheckAndUpgradeKeyIfNeed(const struct HksProcessInfo * processInfo,const struct HksBlob * keyAlias,const struct HksParamSet * paramSet,struct HksBlob * key)166 static int32_t CheckAndUpgradeKeyIfNeed(const struct HksProcessInfo *processInfo, const struct HksBlob *keyAlias,
167     const struct HksParamSet *paramSet, struct HksBlob *key)
168 {
169      // check version and upgrade key if need
170     struct HksParam *keyVersion = NULL;
171     int32_t ret = HksGetParam((const struct HksParamSet *)key->data, HKS_TAG_KEY_VERSION, &keyVersion);
172     HKS_IF_NOT_SUCC_LOGE_RETURN(ret, HKS_ERROR_CORRUPT_FILE, "get param key version failed!")
173     if (keyVersion->uint32Param == HKS_KEY_VERSION) {
174         return ret;
175     }
176     struct HksBlob newKey = { .size = 0, .data = NULL };
177     do {
178         if (keyVersion->uint32Param == 0 || keyVersion->uint32Param > HKS_KEY_VERSION) {
179             ret = HKS_ERROR_BAD_STATE;
180             break;
181         }
182 
183         newKey.data = (uint8_t *)HksMalloc(MAX_KEY_SIZE);
184         if (newKey.data == NULL) {
185             ret = HKS_ERROR_MALLOC_FAIL;
186             break;
187         }
188         newKey.size = MAX_KEY_SIZE;
189         ret = HksDoUpgradeKeyAccess(key, paramSet, &newKey);
190         IfNotSuccAppendHdiErrorInfo(ret);
191         HKS_IF_NOT_SUCC_LOGE_BREAK(ret, "do upgrade access failed!")
192         ret = HksManageStoreKeyBlob(processInfo, paramSet, keyAlias, &newKey, HKS_STORAGE_TYPE_KEY);
193         HKS_IF_NOT_SUCC_LOGE_BREAK(ret, "store upgraded key blob failed!")
194 
195         HKS_FREE_BLOB(*key);
196         key->data = newKey.data;
197         key->size = newKey.size;
198         return ret;
199     } while (0);
200     HKS_FREE_BLOB(*key);
201     HKS_FREE_BLOB(newKey);
202     return ret;
203 }
204 #endif
205 
GetKeyData(const struct HksProcessInfo * processInfo,const struct HksBlob * keyAlias,const struct HksParamSet * paramSet,struct HksBlob * key,enum HksStorageType mode)206 static int32_t GetKeyData(const struct HksProcessInfo *processInfo, const struct HksBlob *keyAlias,
207     const struct HksParamSet *paramSet, struct HksBlob *key, enum HksStorageType mode)
208 {
209     int32_t ret;
210 #ifdef HKS_ENABLE_SMALL_TO_SERVICE
211     ret = HksManageStoreIsKeyBlobExist(processInfo, paramSet, keyAlias, mode);
212     if (ret != HKS_SUCCESS) {
213         if (HksCheckNeedUpgradeForSmallToService(processInfo) == HKS_SUCCESS) {
214             ret = HksChangeKeyOwnerForSmallToService(processInfo, paramSet, keyAlias, mode);
215             HKS_IF_NOT_SUCCESS_LOGE_RETURN(ret, HKS_ERROR_NOT_EXIST,
216                 "do upgrade operation for small to service failed, ret = %" LOG_PUBLIC "d", ret)
217         }
218     }
219 #endif
220     ret = GetKeyFileData(processInfo, paramSet, keyAlias, key, mode);
221     HKS_IF_NOT_SUCC_LOGE_RETURN(ret, ret, "get key fail data failed!")
222 
223 #ifdef HKS_ENABLE_UPGRADE_KEY
224     // check version and upgrade key if need
225     ret = CheckAndUpgradeKeyIfNeed(processInfo, keyAlias, paramSet, key);
226 #endif
227     return ret;
228 }
229 
230 // pre-declaration for used in CheckKeyCondition
231 int32_t HksServiceDeleteKey(const struct HksProcessInfo *processInfo, const struct HksBlob *keyAlias,
232     const struct HksParamSet *paramSet);
233 
CheckKeyCondition(const struct HksProcessInfo * processInfo,const struct HksBlob * keyAlias,const struct HksParamSet * paramSet)234 static int32_t CheckKeyCondition(const struct HksProcessInfo *processInfo, const struct HksBlob *keyAlias,
235     const struct HksParamSet *paramSet)
236 {
237     struct HksParam *isKeyOverride = NULL;
238     int32_t ret = HksGetParam(paramSet, HKS_TAG_KEY_OVERRIDE, &isKeyOverride);
239     if (ret != HKS_SUCCESS || isKeyOverride->boolParam) {
240         ret = HksServiceDeleteKey(processInfo, keyAlias, paramSet);
241         HKS_IF_TRUE_LOGE_RETURN(ret != HKS_SUCCESS && ret != HKS_ERROR_NOT_EXIST, ret,
242             "delete keyblob from storage failed, ret = %" LOG_PUBLIC "d", ret)
243     }
244 
245     uint32_t fileCount;
246     ret = HksManageGetKeyCountByProcessName(processInfo, paramSet, &fileCount);
247     HKS_IF_NOT_SUCC_RETURN(ret, ret)
248 
249     return ret;
250 }
251 
HksServiceGetKeyInfoList(const struct HksProcessInfo * processInfo,const struct HksParamSet * paramSet,struct HksKeyInfo * keyInfoList,uint32_t * listCount)252 int32_t HksServiceGetKeyInfoList(const struct HksProcessInfo *processInfo, const struct HksParamSet *paramSet,
253     struct HksKeyInfo *keyInfoList, uint32_t *listCount)
254 {
255     int32_t ret;
256 #ifdef L2_STANDARD
257     struct HksParamSet *newParamSet = NULL;
258 #endif
259 
260 #ifdef HKS_ENABLE_SMALL_TO_SERVICE
261     uint32_t listMaxCnt = *listCount;
262 #endif
263     do {
264         ret = HksCheckGetKeyInfoListParams(&processInfo->processName, keyInfoList, listCount);
265         HKS_IF_NOT_SUCC_LOGE_BREAK(ret, "check params failed, ret = %" LOG_PUBLIC "d", ret)
266 
267 #ifdef L2_STANDARD
268         ret = AppendStorageLevelIfNotExistInner(processInfo, paramSet, &newParamSet);
269         HKS_IF_NOT_SUCC_LOGE_BREAK(ret, "append storage level failed")
270 #else
271         const struct HksParamSet *newParamSet = paramSet;
272 #endif
273         ret = HksManageGetKeyAliasByProcessName(processInfo, newParamSet, keyInfoList, listCount);
274         HKS_IF_NOT_SUCC_LOGE_BREAK(ret, "get key alias list from storage failed, ret = %" LOG_PUBLIC "d", ret)
275         for (uint32_t i = 0; i < *listCount; ++i) {
276             struct HksBlob keyFromFile = { 0, NULL };
277             ret = GetKeyFileData(processInfo, newParamSet, &(keyInfoList[i].alias), &keyFromFile, HKS_STORAGE_TYPE_KEY);
278             HKS_IF_NOT_SUCC_LOGE_BREAK(ret, "get key data failed, ret = %" LOG_PUBLIC "d", ret)
279             ret = GetKeyParamSet(&keyFromFile, keyInfoList[i].paramSet);
280             HKS_FREE_BLOB(keyFromFile);
281             HKS_IF_NOT_SUCC_LOGE_BREAK(ret, "get key paramSet failed, ret = %" LOG_PUBLIC "d", ret)
282         }
283     } while (0);
284 #ifdef L2_STANDARD
285     HksFreeParamSet(&newParamSet);
286 #endif
287 
288 #ifdef HKS_ENABLE_SMALL_TO_SERVICE
289     if (ret == HKS_SUCCESS && HksCheckNeedUpgradeForSmallToService(processInfo) == HKS_SUCCESS) {
290         ret = HksGetOldKeyInfoListForSmallToService(processInfo, keyInfoList, listMaxCnt, listCount);
291     }
292 #endif
293 
294 #ifdef L2_STANDARD
295     HksReport(__func__, processInfo, NULL, ret);
296 #endif
297 
298     return ret;
299 }
300 #endif
301 #endif /* _CUT_AUTHENTICATE_ */
302 
303 #ifndef _CUT_AUTHENTICATE_
304 
DksAppendKeyAliasAndNewParamSet(struct HksParamSet * paramSet,const struct HksBlob * keyAlias,struct HksParamSet ** outParamSet)305 static int32_t DksAppendKeyAliasAndNewParamSet(struct HksParamSet *paramSet, const struct HksBlob *keyAlias,
306     struct HksParamSet **outParamSet)
307 {
308     int32_t ret;
309     struct HksParamSet *newParamSet = NULL;
310     do {
311         if (paramSet != NULL) {
312             ret = AppendToNewParamSet(paramSet, &newParamSet);
313         } else {
314             ret = HksInitParamSet(&newParamSet);
315         }
316         HKS_IF_NOT_SUCC_LOGE_BREAK(ret, "init new param set failed, ret = %" LOG_PUBLIC "d", ret)
317         struct HksParam paramArray[] = {
318             { .tag = HKS_TAG_KEY_ALIAS, .blob = {.size = keyAlias->size, .data = keyAlias->data} },
319         };
320         ret = HksAddParams(newParamSet, paramArray, HKS_ARRAY_SIZE(paramArray));
321         HKS_IF_NOT_SUCC_LOGE_BREAK(ret, "add key alias, ret = %" LOG_PUBLIC "d", ret)
322 
323         ret = HksBuildParamSet(&newParamSet);
324         HKS_IF_NOT_SUCC_LOGE_BREAK(ret, "build new param set failed, ret = %" LOG_PUBLIC "d", ret)
325 
326         HksFreeParamSet(&paramSet);
327         *outParamSet = newParamSet;
328         return ret;
329     } while (false);
330     HksFreeParamSet(&newParamSet);
331     return ret;
332 }
333 
GetKeyAndNewParamSet(const struct HksProcessInfo * processInfo,const struct HksBlob * keyAlias,const struct HksParamSet * paramSet,struct HksBlob * key,struct HksParamSet ** outParamSet)334 static int32_t GetKeyAndNewParamSet(const struct HksProcessInfo *processInfo, const struct HksBlob *keyAlias,
335     const struct HksParamSet *paramSet, struct HksBlob *key, struct HksParamSet **outParamSet)
336 {
337     int32_t ret = AppendProcessInfoAndDefaultStrategy(paramSet, processInfo, NULL, outParamSet);
338     HKS_IF_NOT_SUCC_LOGE_RETURN(ret, ret,
339         "append process info and default strategy failed, ret = %" LOG_PUBLIC "d", ret)
340 
341     struct HksParam* dksParam = NULL;
342     ret = HksGetParam(paramSet, DKS_TAG_IS_USE_DISTRIBUTED_KEY, &dksParam);
343     if (ret == HKS_SUCCESS && dksParam->boolParam) {
344         HKS_LOG_D("dks recover after use, has the DKS_TAG_IS_USE_DISTRIBUTED_KEY tag, read keyfile from Ta cache!");
345         ret = DksAppendKeyAliasAndNewParamSet(*outParamSet, keyAlias, outParamSet);
346         HKS_IF_NOT_SUCC_LOGE(ret, "dks append key alias and new param set failed, ret = %" LOG_PUBLIC "d.", ret)
347     } else if (ret == HKS_ERROR_PARAM_NOT_EXIST || (ret == HKS_SUCCESS && !dksParam->boolParam)) {
348         ret = GetKeyData(processInfo, keyAlias, *outParamSet, key, HKS_STORAGE_TYPE_KEY);
349         HKS_IF_NOT_SUCC_LOGE(ret, "get key data failed, ret = %" LOG_PUBLIC "d.", ret)
350     } else {
351         HKS_IF_NOT_SUCC_LOGE(ret, "get DKS_TAG_IS_USE_DISTRIBUTED_KEY failed, ret = %" LOG_PUBLIC "d.", ret)
352     }
353     // free outParamSet together after do-while
354     return ret;
355 }
356 
357 #ifdef HKS_SUPPORT_ED25519_TO_X25519
GetAgreeStoreKey(uint32_t keyAliasTag,const struct HksProcessInfo * processInfo,const struct HksParamSet * paramSet,struct HksBlob * key)358 static int32_t GetAgreeStoreKey(uint32_t keyAliasTag, const struct HksProcessInfo *processInfo,
359     const struct HksParamSet *paramSet, struct HksBlob *key)
360 {
361     struct HksParam *keyAliasParam = NULL;
362     int32_t ret = HksGetParam(paramSet, keyAliasTag, &keyAliasParam);
363     HKS_IF_NOT_SUCC_LOGE_RETURN(ret, ret, "get agree key alias tag failed")
364 
365     HKS_IF_TRUE_LOGE_RETURN(keyAliasParam->blob.size > HKS_MAX_KEY_ALIAS_LEN, HKS_ERROR_INVALID_ARGUMENT,
366         "invalid main key size: %" LOG_PUBLIC "u", keyAliasParam->blob.size)
367 
368     return GetKeyData(processInfo, &(keyAliasParam->blob), paramSet, key, HKS_STORAGE_TYPE_KEY);
369 }
370 
TranslateToInnerCurve25519Format(const uint32_t alg,const struct HksBlob * key,struct HksBlob * publicKey)371 static int32_t TranslateToInnerCurve25519Format(const uint32_t alg, const struct HksBlob *key,
372     struct HksBlob *publicKey)
373 {
374     HKS_IF_TRUE_LOGE_RETURN(key->size != HKS_KEY_BYTES(HKS_CURVE25519_KEY_SIZE_256), HKS_ERROR_INVALID_KEY_INFO,
375         "Invalid curve25519 public key size! key size = 0x%" LOG_PUBLIC "X", key->size)
376 
377     uint32_t totalSize = sizeof(struct HksPubKeyInfo) + key->size;
378     uint8_t *buffer = (uint8_t *)HksMalloc(totalSize);
379     HKS_IF_NULL_LOGE_RETURN(buffer, HKS_ERROR_MALLOC_FAIL, "malloc failed! %" LOG_PUBLIC "u", totalSize)
380 
381     (void)memset_s(buffer, totalSize, 0, totalSize);
382 
383     struct HksPubKeyInfo *curve25519Key = (struct HksPubKeyInfo *)buffer;
384     curve25519Key->keyAlg = (enum HksKeyAlg)alg;
385     curve25519Key->keySize = HKS_CURVE25519_KEY_SIZE_256;
386     curve25519Key->nOrXSize = key->size; /* curve25519 public key */
387 
388     uint32_t offset = sizeof(struct HksPubKeyInfo);
389     (void)memcpy_s(buffer + offset, totalSize - offset, key->data, key->size);
390     publicKey->data = buffer;
391     publicKey->size = totalSize;
392     return HKS_SUCCESS;
393 }
394 
GetAgreePublicKey(const uint32_t alg,const struct HksProcessInfo * processInfo,const struct HksParamSet * paramSet,struct HksBlob * key)395 static int32_t GetAgreePublicKey(const uint32_t alg, const struct HksProcessInfo *processInfo,
396     const struct HksParamSet *paramSet, struct HksBlob *key)
397 {
398     struct HksParam *isKeyAliasParam = NULL;
399     int32_t ret = HksGetParam(paramSet, HKS_TAG_AGREE_PUBLIC_KEY_IS_KEY_ALIAS, &isKeyAliasParam);
400     if ((ret == HKS_SUCCESS) && (!(isKeyAliasParam->boolParam))) {
401         struct HksParam *keyParam = NULL;
402         ret = HksGetParam(paramSet, HKS_TAG_AGREE_PUBLIC_KEY, &keyParam);
403         HKS_IF_NOT_SUCC_LOGE_RETURN(ret, ret, "get agree public key tag fail")
404 
405         return TranslateToInnerCurve25519Format(alg, &(keyParam->blob), key);
406     }
407 
408     return GetAgreeStoreKey(HKS_TAG_AGREE_PUBLIC_KEY, processInfo, paramSet, key);
409 }
410 
GetAgreePrivateKey(const struct HksProcessInfo * processInfo,const struct HksParamSet * paramSet,struct HksBlob * key)411 static int32_t GetAgreePrivateKey(const struct HksProcessInfo *processInfo,
412     const struct HksParamSet *paramSet, struct HksBlob *key)
413 {
414     return GetAgreeStoreKey(HKS_TAG_AGREE_PRIVATE_KEY_ALIAS, processInfo, paramSet, key);
415 }
416 
ConbineIntoKeyPair(const struct HksBlob * privateKey,const struct HksBlob * publicKey,struct HksBlob * keyPair)417 static int32_t ConbineIntoKeyPair(const struct HksBlob *privateKey,
418     const struct HksBlob *publicKey, struct HksBlob *keyPair)
419 {
420     uint32_t size = sizeof(struct Hks25519KeyPair) + privateKey->size + publicKey->size; /* size has been checked */
421     uint8_t *buffer = (uint8_t *)HksMalloc(size);
422     HKS_IF_NULL_RETURN(buffer, HKS_ERROR_MALLOC_FAIL)
423 
424     (void)memset_s(buffer, size, 0, size);
425 
426     struct Hks25519KeyPair keyPairStruct = { publicKey->size, privateKey->size };
427     uint32_t offset = 0;
428 
429     (void)memcpy_s(buffer + offset, size, &keyPairStruct, sizeof(keyPairStruct));
430     offset += sizeof(keyPairStruct);
431 
432     (void)memcpy_s(buffer  + offset, size - offset, publicKey->data, publicKey->size);
433     offset += publicKey->size;
434 
435     (void)memcpy_s(buffer  + offset, size - offset, privateKey->data, privateKey->size) ;
436 
437     keyPair->data = buffer;
438     keyPair->size = size;
439     return HKS_SUCCESS;
440 }
441 
GetAgreeKeyPair(const uint32_t alg,const struct HksProcessInfo * processInfo,const struct HksParamSet * paramSet,struct HksBlob * key)442 static int32_t GetAgreeKeyPair(const uint32_t alg, const struct HksProcessInfo *processInfo,
443     const struct HksParamSet *paramSet, struct HksBlob *key)
444 {
445     int32_t ret;
446     struct HksBlob privateKey = { 0, NULL };
447     struct HksBlob publicKey = { 0, NULL };
448     do {
449         ret = GetAgreePublicKey(alg, processInfo, paramSet, &publicKey);
450         HKS_IF_NOT_SUCC_BREAK(ret)
451 
452         ret = GetAgreePrivateKey(processInfo, paramSet, &privateKey);
453         HKS_IF_NOT_SUCC_BREAK(ret)
454 
455         ret = ConbineIntoKeyPair(&privateKey, &publicKey, key);
456     } while (0);
457 
458     HKS_FREE_BLOB(privateKey);
459     HKS_FREE_BLOB(publicKey);
460     return ret;
461 }
462 #endif
463 
GetAgreeBaseKey(const struct HksProcessInfo * processInfo,const struct HksParamSet * paramSet,struct HksBlob * key)464 static int32_t GetAgreeBaseKey(const struct HksProcessInfo *processInfo, const struct HksParamSet *paramSet,
465     struct HksBlob *key)
466 {
467     (void)key;
468     struct HksParam *keyAlgParam = NULL;
469     int32_t ret = HksGetParam(paramSet, HKS_TAG_ALGORITHM, &keyAlgParam);
470     HKS_IF_NOT_SUCC_LOGE_RETURN(ret, HKS_ERROR_CHECK_GET_ALG_FAIL, "get alg tag fail")
471 
472     HKS_IF_TRUE_LOGI_RETURN(keyAlgParam->uint32Param != HKS_ALG_AES, HKS_SUCCESS,
473         "not an aes key, no need check main key and derive factor")
474 
475 #ifdef HKS_SUPPORT_ED25519_TO_X25519
476     struct HksParam *agreeAlgParam = NULL;
477     ret = HksGetParam(paramSet, HKS_TAG_AGREE_ALG, &agreeAlgParam);
478     HKS_IF_NOT_SUCC_RETURN(ret, HKS_ERROR_CHECK_GET_ALG_FAIL)
479 
480     HKS_IF_TRUE_RETURN(agreeAlgParam->uint32Param != HKS_ALG_X25519 && agreeAlgParam->uint32Param != HKS_ALG_ED25519,
481         HKS_ERROR_INVALID_ALGORITHM)
482 
483     return GetAgreeKeyPair(agreeAlgParam->uint32Param, processInfo, paramSet, key);
484 #else
485     (void)processInfo;
486     return HKS_ERROR_INVALID_ARGUMENT; /* if aes generated by agree but x25519/ed25519 is ot support, return error */
487 #endif
488 }
489 
GetDeriveMainKey(const struct HksProcessInfo * processInfo,const struct HksParamSet * paramSet,struct HksBlob * key)490 static int32_t GetDeriveMainKey(const struct HksProcessInfo *processInfo, const struct HksParamSet *paramSet,
491     struct HksBlob *key)
492 {
493     struct HksParam *keyGenTypeParam = NULL;
494     int32_t ret = HksGetParam(paramSet, HKS_TAG_KEY_GENERATE_TYPE, &keyGenTypeParam);
495     /* not set tag KEY_GENERATE_TYPE, gen key by default type */
496     HKS_IF_NOT_SUCC_RETURN(ret, HKS_SUCCESS)
497 
498     if (keyGenTypeParam->uint32Param == HKS_KEY_GENERATE_TYPE_AGREE) {
499         return GetAgreeBaseKey(processInfo, paramSet, key);
500     } else if (keyGenTypeParam->uint32Param == HKS_KEY_GENERATE_TYPE_DEFAULT) {
501         return HKS_SUCCESS;
502     }
503     return HKS_ERROR_INVALID_ARGUMENT;
504 }
505 
GetKeyIn(const struct HksProcessInfo * processInfo,const struct HksParamSet * paramSet,struct HksBlob * key)506 static int32_t GetKeyIn(const struct HksProcessInfo *processInfo, const struct HksParamSet *paramSet,
507     struct HksBlob *key)
508 {
509     int32_t ret = GetDeriveMainKey(processInfo, paramSet, key);
510     HKS_IF_NOT_SUCC_RETURN(ret, ret)
511 
512     /* if not generate by derive, init keyIn by default value(ca to ta not accept null pointer) */
513     if (key->data == NULL) {
514         key->size = 1; /* malloc least buffer as keyIn buffer */
515         key->data = (uint8_t *)HksMalloc(key->size);
516         HKS_IF_NULL_LOGE_RETURN(key->data, HKS_ERROR_MALLOC_FAIL, "malloc failed")
517 
518         key->data[0] = 0;
519     }
520     return HKS_SUCCESS;
521 }
522 
StoreOrCopyKeyBlob(const struct HksParamSet * paramSet,const struct HksProcessInfo * processInfo,struct HksBlob * output,struct HksBlob * outData,bool isNeedStorage)523 static int32_t StoreOrCopyKeyBlob(const struct HksParamSet *paramSet, const struct HksProcessInfo *processInfo,
524     struct HksBlob *output, struct HksBlob *outData, bool isNeedStorage)
525 {
526     if (!isNeedStorage) {
527         HKS_IF_TRUE_LOGE_RETURN(outData->size != 0 &&
528             memcpy_s(outData->data, outData->size, output->data, output->size) != EOK, HKS_ERROR_INSUFFICIENT_MEMORY,
529             "copy keyblob data fail")
530         outData->size = output->size;
531         return HKS_SUCCESS;
532     }
533 
534     struct HksParam *keyAliasParam = NULL;
535     int32_t ret = HksGetParam(paramSet, HKS_TAG_KEY_ALIAS, &keyAliasParam);
536     HKS_IF_NOT_SUCC_LOGE_RETURN(ret, ret, "get key alias fail, ret = %" LOG_PUBLIC "d", ret)
537 
538     HKS_IF_TRUE_LOGE_RETURN(keyAliasParam->blob.size > HKS_MAX_KEY_ALIAS_LEN, HKS_ERROR_INVALID_ARGUMENT,
539         "key alias size is too long, size is %" LOG_PUBLIC "u", keyAliasParam->blob.size)
540 
541     ret = CheckKeyCondition(processInfo, &keyAliasParam->blob, paramSet);
542     HKS_IF_NOT_SUCC_LOGE_RETURN(ret, ret, "CheckKeyCondition fail, ret = %" LOG_PUBLIC "d", ret)
543 
544     ret = HksManageStoreKeyBlob(processInfo, paramSet, &keyAliasParam->blob, output, HKS_STORAGE_TYPE_KEY);
545     HKS_IF_NOT_SUCC_LOGE(ret, "store keyblob to storage failed, ret = %" LOG_PUBLIC "d", ret)
546 
547     return ret;
548 }
549 
HksReportEvent(const char * funcName,const struct HksHitraceId * traceId,const struct HksProcessInfo * processInfo,const struct HksParamSet * paramSet,int32_t ret)550 static void HksReportEvent(const char *funcName, const struct HksHitraceId *traceId,
551     const struct HksProcessInfo *processInfo, const struct HksParamSet *paramSet, int32_t ret)
552 {
553 #ifdef L2_STANDARD
554     HksHitraceEnd(traceId);
555     HksReport(funcName, processInfo, paramSet, ret);
556 #else
557     (void)funcName;
558     (void)traceId;
559     (void)processInfo;
560     (void)paramSet;
561     (void)ret;
562 #endif
563 }
564 
HksServiceGenerateKey(const struct HksProcessInfo * processInfo,const struct HksBlob * keyAlias,const struct HksParamSet * paramSetIn,struct HksBlob * keyOut)565 int32_t HksServiceGenerateKey(const struct HksProcessInfo *processInfo, const struct HksBlob *keyAlias,
566     const struct HksParamSet *paramSetIn, struct HksBlob *keyOut)
567 {
568     struct HksParamSet *newParamSet = NULL;
569     uint64_t enterTime = 0;
570     (void)HksElapsedRealTime(&enterTime);
571     uint8_t *keyOutBuffer = (uint8_t *)HksMalloc(MAX_KEY_SIZE);
572     HKS_IF_NULL_RETURN(keyOutBuffer, HKS_ERROR_MALLOC_FAIL)
573     struct HksHitraceId traceId = {0};
574 
575 #ifdef L2_STANDARD
576     traceId = HksHitraceBegin(__func__, HKS_HITRACE_FLAG_DEFAULT | HKS_HITRACE_FLAG_NO_BE_INFO);
577 #endif
578 
579     struct HksBlob output = { MAX_KEY_SIZE, keyOutBuffer };
580     struct HksBlob keyIn = { 0, NULL };
581     int32_t ret;
582     do {
583         /* if user don't pass the key out buffer, we will use a tmp key out buffer */
584         if ((keyOut != NULL) && (keyOut->data != NULL) && (keyOut->size != 0)) {
585             output = *keyOut;
586         }
587 
588         ret = HksCheckGenAndImportKeyParams(&processInfo->processName, keyAlias, paramSetIn, &output);
589         HKS_IF_NOT_SUCC_LOGE_BREAK(ret, "check generate key params failed, ret = %" LOG_PUBLIC "d", ret)
590 
591         ret = AppendNewInfoForGenKeyInService(processInfo, paramSetIn, &newParamSet);
592         HKS_IF_NOT_SUCC_LOGE_BREAK(ret, "append processName tag failed, ret = %" LOG_PUBLIC "d", ret)
593 
594         ret = CheckKeyCondition(processInfo, keyAlias, newParamSet);
595         HKS_IF_NOT_SUCC_LOGE_BREAK(ret, "check key condition failed, ret = %" LOG_PUBLIC "d", ret)
596 
597         ret = GetKeyIn(processInfo, newParamSet, &keyIn);
598         HKS_IF_NOT_SUCC_LOGE_BREAK(ret, "get keyIn failed, ret = %" LOG_PUBLIC "d", ret)
599 
600         ret = HuksAccessGenerateKey(keyAlias, newParamSet, &keyIn, &output);
601         IfNotSuccAppendHdiErrorInfo(ret);
602         HKS_IF_NOT_SUCC_LOGE_BREAK(ret, "access level generate key failed, ret = %" LOG_PUBLIC "d", ret)
603 
604         ret = HksManageStoreKeyBlob(processInfo, newParamSet, keyAlias, &output, HKS_STORAGE_TYPE_KEY);
605         HKS_IF_NOT_SUCC_LOGE(ret, "store keyblob to storage failed, ret = %" LOG_PUBLIC "d", ret)
606     } while (0);
607 #ifdef L2_STANDARD
608     struct HksParamSet *reportParamSet = NULL;
609     struct InfoPair infoPair = { .startTime = enterTime, .traceId = traceId.traceId.chainId };
610     (void)PreConstructGenKeyReportParamSet(keyAlias, paramSetIn, infoPair, &output, &reportParamSet);
611     (void)ConstructReportParamSet(__func__, processInfo, ret, &reportParamSet);
612     HksEventReport(__func__, processInfo, paramSetIn, reportParamSet, ret);
613     DeConstructReportParamSet(&reportParamSet);
614 #endif
615     HKS_FREE(keyOutBuffer);
616     if (keyIn.data != NULL) {
617         (void)memset_s(keyIn.data, keyIn.size, 0, keyIn.size);
618     }
619     HKS_FREE(keyIn.data);
620     HksFreeParamSet(&newParamSet);
621     HksHitraceEnd(&traceId);
622     return ret;
623 }
624 
HksServiceSign(const struct HksProcessInfo * processInfo,const struct HksBlob * keyAlias,const struct HksParamSet * paramSet,const struct HksBlob * srcData,struct HksBlob * signature)625 int32_t HksServiceSign(const struct HksProcessInfo *processInfo, const struct HksBlob *keyAlias,
626     const struct HksParamSet *paramSet, const struct HksBlob *srcData, struct HksBlob *signature)
627 {
628     int32_t ret;
629     uint64_t startTime = 0;
630     (void)HksElapsedRealTime(&startTime);
631     struct HksParamSet *newParamSet = NULL;
632     struct HksBlob keyFromFile = { 0, NULL };
633     struct HksHitraceId traceId = {0};
634 
635 #ifdef L2_STANDARD
636     traceId = HksHitraceBegin(__func__, HKS_HITRACE_FLAG_DEFAULT | HKS_HITRACE_FLAG_NO_BE_INFO);
637 #endif
638 
639     do {
640         ret = HksCheckAllParams(&processInfo->processName, keyAlias, paramSet, srcData, signature);
641         HKS_IF_NOT_SUCC_LOGE_BREAK(ret, "check sign params failed, ret = %" LOG_PUBLIC "d", ret)
642 
643         ret = GetKeyAndNewParamSet(processInfo, keyAlias, paramSet, &keyFromFile, &newParamSet);
644         HKS_IF_NOT_SUCC_LOGE(ret, "sign: get main key and new paramSet failed, ret = %" LOG_PUBLIC "d", ret)
645 
646         if (ret == HKS_SUCCESS) {
647             ret = HuksAccessSign(&keyFromFile, newParamSet, srcData, signature);
648             IfNotSuccAppendHdiErrorInfo(ret);
649         }
650 #ifdef SUPPORT_STORAGE_BACKUP
651         if (ret == HKS_ERROR_CORRUPT_FILE || ret == HKS_ERROR_FILE_SIZE_FAIL || ret == HKS_ERROR_NOT_EXIST) {
652             HKS_FREE_BLOB(keyFromFile);
653             ret = GetKeyData(processInfo, keyAlias, newParamSet, &keyFromFile, HKS_STORAGE_TYPE_BAK_KEY);
654             HKS_IF_NOT_SUCC_LOGE_BREAK(ret, "sign: get bak key and new paramSet failed, ret = %" LOG_PUBLIC "d", ret)
655 
656             ret = HuksAccessSign(&keyFromFile, newParamSet, srcData, signature);
657             IfNotSuccAppendHdiErrorInfo(ret);
658         }
659 #endif
660     } while (0);
661 
662 #ifdef L2_STANDARD
663     HksOneStageReportInfo info = {ret, startTime, traceId.traceId.chainId, __func__, HKS_ONE_STAGE_SIGN_VERIFY};
664     (void)HksOneStageEventReport(keyAlias, &keyFromFile, paramSet, processInfo, &info);
665 #endif
666     HksHitraceEnd(&traceId);
667     HKS_FREE_BLOB(keyFromFile);
668     HksFreeParamSet(&newParamSet);
669     return ret;
670 }
671 
HksServiceVerify(const struct HksProcessInfo * processInfo,const struct HksBlob * keyAlias,const struct HksParamSet * paramSet,const struct HksBlob * srcData,const struct HksBlob * signature)672 int32_t HksServiceVerify(const struct HksProcessInfo *processInfo, const struct HksBlob *keyAlias,
673     const struct HksParamSet *paramSet, const struct HksBlob *srcData, const struct HksBlob *signature)
674 {
675     int32_t ret;
676     uint64_t startTime = 0;
677     (void)HksElapsedRealTime(&startTime);
678     struct HksParamSet *newParamSet = NULL;
679     struct HksBlob keyFromFile = { 0, NULL };
680     struct HksHitraceId traceId = {0};
681 
682 #ifdef L2_STANDARD
683     traceId = HksHitraceBegin(__func__, HKS_HITRACE_FLAG_DEFAULT | HKS_HITRACE_FLAG_NO_BE_INFO);
684 #endif
685 
686     do {
687         ret = HksCheckAllParams(&processInfo->processName, keyAlias, paramSet, srcData, signature);
688         HKS_IF_NOT_SUCC_LOGE_BREAK(ret, "check verify params failed, ret = %" LOG_PUBLIC "d", ret)
689 
690         ret = GetKeyAndNewParamSet(processInfo, keyAlias, paramSet, &keyFromFile, &newParamSet);
691         HKS_IF_NOT_SUCC_LOGE(ret, "verify: get main key and new paramSet failed, ret = %" LOG_PUBLIC "d", ret)
692 
693         if (ret == HKS_SUCCESS) {
694             ret = HuksAccessVerify(&keyFromFile, newParamSet, srcData, signature);
695             IfNotSuccAppendHdiErrorInfo(ret);
696         }
697 #ifdef SUPPORT_STORAGE_BACKUP
698         if (ret == HKS_ERROR_CORRUPT_FILE || ret == HKS_ERROR_FILE_SIZE_FAIL || ret == HKS_ERROR_NOT_EXIST) {
699             HKS_FREE_BLOB(keyFromFile);
700             ret = GetKeyData(processInfo, keyAlias, newParamSet, &keyFromFile, HKS_STORAGE_TYPE_BAK_KEY);
701             HKS_IF_NOT_SUCC_LOGE_BREAK(ret, "verify: get bak key and new paramSet failed, ret = %" LOG_PUBLIC "d", ret)
702 
703             ret = HuksAccessVerify(&keyFromFile, newParamSet, srcData, signature);
704             IfNotSuccAppendHdiErrorInfo(ret);
705         }
706 #endif
707     } while (0);
708 
709 #ifdef L2_STANDARD
710     HksOneStageReportInfo info = {ret, startTime, traceId.traceId.chainId, __func__, HKS_ONE_STAGE_SIGN_VERIFY};
711     (void)HksOneStageEventReport(keyAlias, &keyFromFile, paramSet, processInfo, &info);
712 #endif
713     HksHitraceEnd(&traceId);
714     HKS_FREE_BLOB(keyFromFile);
715     HksFreeParamSet(&newParamSet);
716     return ret;
717 }
718 
HksServiceEncrypt(const struct HksProcessInfo * processInfo,const struct HksBlob * keyAlias,const struct HksParamSet * paramSet,const struct HksBlob * plainText,struct HksBlob * cipherText)719 int32_t HksServiceEncrypt(const struct HksProcessInfo *processInfo, const struct HksBlob *keyAlias,
720     const struct HksParamSet *paramSet, const struct HksBlob *plainText, struct HksBlob *cipherText)
721 {
722     int32_t ret;
723     uint64_t startTime = 0;
724     (void)HksElapsedRealTime(&startTime);
725     struct HksParamSet *newParamSet = NULL;
726     struct HksBlob keyFromFile = { 0, NULL };
727 
728     do {
729         ret = HksCheckAllParams(&processInfo->processName, keyAlias, paramSet, plainText, cipherText);
730         HKS_IF_NOT_SUCC_LOGE_BREAK(ret, "check encrypt failed, ret = %" LOG_PUBLIC "d", ret)
731 
732         ret = GetKeyAndNewParamSet(processInfo, keyAlias, paramSet, &keyFromFile, &newParamSet);
733         HKS_IF_NOT_SUCC_LOGE(ret, "encrypt: get main key and new paramSet failed, ret = %" LOG_PUBLIC "d", ret)
734 
735         if (ret == HKS_SUCCESS) {
736             ret = HuksAccessEncrypt(&keyFromFile, newParamSet, plainText, cipherText);
737             IfNotSuccAppendHdiErrorInfo(ret);
738         }
739 #ifdef SUPPORT_STORAGE_BACKUP
740         if (ret == HKS_ERROR_CORRUPT_FILE || ret == HKS_ERROR_FILE_SIZE_FAIL || ret == HKS_ERROR_NOT_EXIST) {
741             HKS_FREE_BLOB(keyFromFile);
742             ret = GetKeyData(processInfo, keyAlias, newParamSet, &keyFromFile, HKS_STORAGE_TYPE_BAK_KEY);
743             HKS_IF_NOT_SUCC_LOGE_BREAK(ret,
744                 "encrypt: get bak key and new paramSet failed, ret = %" LOG_PUBLIC "d", ret)
745             ret = HuksAccessEncrypt(&keyFromFile, newParamSet, plainText, cipherText);
746             IfNotSuccAppendHdiErrorInfo(ret);
747         }
748 #endif
749     } while (0);
750 
751 #ifdef L2_STANDARD
752     HksOneStageReportInfo info = {ret, startTime, 0, __func__, HKS_ONE_STAGE_CRYPTO};
753     (void)HksOneStageEventReport(keyAlias, &keyFromFile, paramSet, processInfo, &info);
754 #endif
755     HKS_FREE_BLOB(keyFromFile);
756     HksFreeParamSet(&newParamSet);
757     return ret;
758 }
759 
HksServiceDecrypt(const struct HksProcessInfo * processInfo,const struct HksBlob * keyAlias,const struct HksParamSet * paramSet,const struct HksBlob * cipherText,struct HksBlob * plainText)760 int32_t HksServiceDecrypt(const struct HksProcessInfo *processInfo, const struct HksBlob *keyAlias,
761     const struct HksParamSet *paramSet, const struct HksBlob *cipherText, struct HksBlob *plainText)
762 {
763     int32_t ret;
764     uint64_t startTime = 0;
765     (void)HksElapsedRealTime(&startTime);
766     struct HksParamSet *newParamSet = NULL;
767     struct HksBlob keyFromFile = { 0, NULL };
768     struct HksHitraceId traceId = {0};
769 
770 #ifdef L2_STANDARD
771     traceId = HksHitraceBegin(__func__, HKS_HITRACE_FLAG_DEFAULT | HKS_HITRACE_FLAG_NO_BE_INFO);
772 #endif
773 
774     do {
775         ret = HksCheckAllParams(&processInfo->processName, keyAlias, paramSet, cipherText, plainText);
776         HKS_IF_NOT_SUCC_LOGE_BREAK(ret, "check decrypt failed, ret = %" LOG_PUBLIC "d", ret)
777 
778         ret = GetKeyAndNewParamSet(processInfo, keyAlias, paramSet, &keyFromFile, &newParamSet);
779         HKS_IF_NOT_SUCC_LOGE(ret, "decrypt: get main key and new paramSet failed, ret = %" LOG_PUBLIC "d", ret)
780 
781         if (ret == HKS_SUCCESS) {
782             ret = HuksAccessDecrypt(&keyFromFile, newParamSet, cipherText, plainText);
783             IfNotSuccAppendHdiErrorInfo(ret);
784         }
785 #ifdef SUPPORT_STORAGE_BACKUP
786         if (ret == HKS_ERROR_CORRUPT_FILE || ret == HKS_ERROR_FILE_SIZE_FAIL || ret == HKS_ERROR_NOT_EXIST) {
787             HKS_FREE_BLOB(keyFromFile);
788             ret = GetKeyData(processInfo, keyAlias, newParamSet, &keyFromFile, HKS_STORAGE_TYPE_BAK_KEY);
789             HKS_IF_NOT_SUCC_LOGE_BREAK(ret,
790                 "decrypt: get bak key and new paramSet failed, ret = %" LOG_PUBLIC "d", ret)
791             ret = HuksAccessDecrypt(&keyFromFile, newParamSet, cipherText, plainText);
792             IfNotSuccAppendHdiErrorInfo(ret);
793         }
794 #endif
795     } while (0);
796 #ifdef L2_STANDARD
797     HksOneStageReportInfo info = {ret, startTime, traceId.traceId.chainId, __func__, HKS_ONE_STAGE_CRYPTO};
798     HksOneStageEventReport(keyAlias, &keyFromFile, paramSet, processInfo, &info);
799 #endif
800     HksHitraceEnd(&traceId);
801     HKS_FREE_BLOB(keyFromFile);
802     HksFreeParamSet(&newParamSet);
803     return ret;
804 }
805 
HksServiceDeleteKey(const struct HksProcessInfo * processInfo,const struct HksBlob * keyAlias,const struct HksParamSet * paramSet)806 int32_t HksServiceDeleteKey(const struct HksProcessInfo *processInfo, const struct HksBlob *keyAlias,
807     const struct HksParamSet *paramSet)
808 {
809     int32_t ret = HKS_SUCCESS;
810 #ifdef L2_STANDARD
811     uint64_t enterTime = 0;
812     (void)HksElapsedRealTime(&enterTime);
813     struct HksParamSet *newParamSet = NULL;
814 #else
815     const struct HksParamSet *newParamSet = paramSet;
816 #endif
817     do {
818         ret = HksCheckProcessNameAndKeyAlias(&processInfo->processName, keyAlias);
819         HKS_IF_NOT_SUCC_BREAK(ret)
820 
821 #ifdef L2_STANDARD
822         ret = AppendStorageLevelIfNotExistInner(processInfo, paramSet, &newParamSet);
823         HKS_IF_NOT_SUCC_LOGE_BREAK(ret, "append storage level failed")
824 #endif
825         /*
826         * Detele key first, record log if failed; then delete cert chain, return error if failed;
827         * Return error code of deleteKey in the end.
828         */
829         ret = HksManageStoreDeleteKeyBlob(processInfo, newParamSet, keyAlias, HKS_STORAGE_TYPE_KEY);
830         if ((ret != HKS_SUCCESS) && (ret != HKS_ERROR_NOT_EXIST)) {
831             HKS_LOG_E("service delete main key failed, ret = %" LOG_PUBLIC "d", ret);
832         }
833 #ifdef HKS_ENABLE_SMALL_TO_SERVICE
834         int32_t oldRet = HKS_FAILURE;
835         if (HksCheckNeedUpgradeForSmallToService(processInfo) == HKS_SUCCESS) {
836             oldRet = HksDeleteOldKeyForSmallToService(keyAlias);
837             ret = (oldRet == HKS_SUCCESS) ? HKS_SUCCESS : ret;
838         }
839 #endif
840     } while (0);
841 #ifdef L2_STANDARD
842     struct HksParamSet *reportParamSet = NULL;
843     (void)PreConstructDeleteKeyReportParamSet(keyAlias, paramSet, enterTime, &reportParamSet);
844     (void)ConstructReportParamSet(__func__, processInfo, ret, &reportParamSet);
845     HksEventReport(__func__, processInfo, NULL, reportParamSet, ret);
846     DeConstructReportParamSet(&reportParamSet);
847     HksFreeParamSet(&newParamSet);
848 #endif
849     return ret;
850 }
851 
HksServiceKeyExist(const struct HksProcessInfo * processInfo,const struct HksBlob * keyAlias,const struct HksParamSet * paramSet)852 int32_t HksServiceKeyExist(const struct HksProcessInfo *processInfo, const struct HksBlob *keyAlias,
853     const struct HksParamSet *paramSet)
854 {
855     uint64_t enterTime = 0;
856     (void)HksElapsedRealTime(&enterTime);
857     int32_t ret = HksCheckProcessNameAndKeyAlias(&processInfo->processName, keyAlias);
858     HKS_IF_NOT_SUCC_RETURN(ret, ret)
859 
860 #ifdef L2_STANDARD
861     struct HksParamSet *newParamSet = NULL;
862     ret = AppendStorageLevelIfNotExistInner(processInfo, paramSet, &newParamSet);
863     HKS_IF_NOT_SUCC_LOGE_RETURN(ret, ret, "append storage level failed")
864 #else
865     const struct HksParamSet *newParamSet = paramSet;
866 #endif
867 
868     ret = HksManageStoreIsKeyBlobExist(processInfo, newParamSet, keyAlias, HKS_STORAGE_TYPE_KEY);
869 #ifdef L2_STANDARD
870     HksFreeParamSet(&newParamSet);
871 #endif
872 
873 #ifdef HKS_ENABLE_SMALL_TO_SERVICE
874     if (HksCheckNeedUpgradeForSmallToService(processInfo) == HKS_SUCCESS) {
875         if (ret == HKS_ERROR_NOT_EXIST) {
876             // if change key owner success, the key should exist; otherwise the key not exist
877             int32_t oldRet = HksChangeKeyOwnerForSmallToService(processInfo, NULL, keyAlias, HKS_STORAGE_TYPE_KEY);
878             ret = (oldRet == HKS_SUCCESS) ? HKS_SUCCESS : ret;
879         }
880     }
881 #endif
882 #ifdef L2_STANDARD
883     struct HksParamSet *reportParamSet = NULL;
884     (void)PreConstructCheckKeyExitedReportParamSet(keyAlias, paramSet, enterTime, &reportParamSet);
885     (void)ConstructReportParamSet(__func__, processInfo, ret, &reportParamSet);
886     HksEventReport(__func__, processInfo, NULL, reportParamSet, ret);
887     DeConstructReportParamSet(&reportParamSet);
888 #endif
889     return ret;
890 }
891 
HksServiceGetKeyParamSet(const struct HksProcessInfo * processInfo,const struct HksBlob * keyAlias,const struct HksParamSet * paramSetIn,struct HksParamSet * paramSetOut)892 int32_t HksServiceGetKeyParamSet(const struct HksProcessInfo *processInfo, const struct HksBlob *keyAlias,
893     const struct HksParamSet *paramSetIn, struct HksParamSet *paramSetOut)
894 {
895     int32_t ret;
896     struct HksParamSet *newParamSet = NULL;
897     struct HksBlob keyFromFile = { 0, NULL };
898 
899     do {
900         ret = HksCheckGetKeyParamSetParams(&processInfo->processName, keyAlias, paramSetOut);
901         HKS_IF_NOT_SUCC_LOGE_BREAK(ret, "check get key paramSet params failed, ret = %" LOG_PUBLIC "d", ret)
902 
903         ret = GetKeyAndNewParamSet(processInfo, keyAlias, paramSetIn, &keyFromFile, &newParamSet);
904         HKS_IF_NOT_SUCC_LOGE(ret,
905             "get key paramSet: get key and new paramSet failed, ret = %" LOG_PUBLIC "d", ret)
906 
907         if (ret == HKS_SUCCESS) {
908             ret = HuksAccessGetKeyProperties(newParamSet, &keyFromFile);
909             IfNotSuccAppendHdiErrorInfo(ret);
910         }
911 #ifdef SUPPORT_STORAGE_BACKUP
912         if (ret == HKS_ERROR_CORRUPT_FILE || ret == HKS_ERROR_FILE_SIZE_FAIL || ret == HKS_ERROR_NOT_EXIST) {
913             HKS_FREE_BLOB(keyFromFile);
914             ret = GetKeyData(processInfo, keyAlias, newParamSet, &keyFromFile, HKS_STORAGE_TYPE_BAK_KEY);
915             HKS_IF_NOT_SUCC_LOGE_BREAK(ret,
916                 "get key paramSet: get bak key and new paramSet failed, ret = %" LOG_PUBLIC "d", ret)
917             ret = HuksAccessGetKeyProperties(newParamSet, &keyFromFile);
918             IfNotSuccAppendHdiErrorInfo(ret);
919         }
920 #endif
921         HKS_IF_NOT_SUCC_LOGE_BREAK(ret,
922             "get key paramset or access level check key validity failed, ret = %" LOG_PUBLIC "d", ret)
923 
924         ret = GetKeyParamSet(&keyFromFile, paramSetOut);
925         HKS_IF_NOT_SUCC_LOGE(ret, "get Key paramSet failed, ret = %" LOG_PUBLIC "d", ret)
926     } while (0);
927 
928     HKS_FREE_BLOB(keyFromFile);
929     HksFreeParamSet(&newParamSet);
930 
931 #ifdef L2_STANDARD
932     HksReport(__func__, processInfo, paramSetOut, ret);
933 #endif
934 
935     return ret;
936 }
937 
HksServiceImportKey(const struct HksProcessInfo * processInfo,const struct HksBlob * keyAlias,const struct HksParamSet * paramSet,const struct HksBlob * key)938 int32_t HksServiceImportKey(const struct HksProcessInfo *processInfo, const struct HksBlob *keyAlias,
939     const struct HksParamSet *paramSet, const struct HksBlob *key)
940 {
941     int32_t ret;
942     struct HksParamSet *newParamSet = NULL;
943     uint8_t *keyOutBuffer = (uint8_t *)HksMalloc(MAX_KEY_SIZE);
944     HKS_IF_NULL_LOGE_RETURN(keyOutBuffer, HKS_ERROR_MALLOC_FAIL, "malloc keyOutBuffer failed.")
945     struct HksBlob keyOut = { MAX_KEY_SIZE, keyOutBuffer };
946 #ifdef L2_STANDARD
947     struct HksParamSet *reportParamSet = NULL;
948     uint64_t enterTime = 0;
949     (void)HksElapsedRealTime(&enterTime);
950 #endif
951     do {
952         ret = HksCheckGenAndImportKeyParams(&processInfo->processName, keyAlias, paramSet, key);
953         HKS_IF_NOT_SUCC_LOGE_BREAK(ret, "check import key params failed, ret = %" LOG_PUBLIC "d", ret)
954 
955         ret = AppendNewInfoForGenKeyInService(processInfo, paramSet, &newParamSet);
956         HKS_IF_NOT_SUCC_LOGE_BREAK(ret, "append processName tag failed, ret = %" LOG_PUBLIC "d", ret)
957 
958         ret = CheckKeyCondition(processInfo, keyAlias, newParamSet);
959         HKS_IF_NOT_SUCC_LOGE_BREAK(ret, "import: check key condition failed, ret = %" LOG_PUBLIC "d", ret)
960 
961         ret = HuksAccessImportKey(keyAlias, key, newParamSet, &keyOut);
962         IfNotSuccAppendHdiErrorInfo(ret);
963         HKS_IF_NOT_SUCC_LOGE_BREAK(ret, "access level import public key failed, ret = %" LOG_PUBLIC "d", ret)
964 
965         ret = HksManageStoreKeyBlob(processInfo, newParamSet, keyAlias, &keyOut, HKS_STORAGE_TYPE_KEY);
966         HKS_IF_NOT_SUCC_LOGE(ret, "store keyblob to storage failed, ret = %" LOG_PUBLIC "d", ret)
967     } while (0);
968 #ifdef L2_STANDARD
969     (void)PreConstructImportKeyReportParamSet(keyAlias, paramSet, enterTime, &keyOut, &reportParamSet);
970     (void)ConstructReportParamSet(__func__, processInfo, ret, &reportParamSet);
971     HksEventReport(__func__, processInfo, paramSet, reportParamSet, ret);
972     DeConstructReportParamSet(&reportParamSet);
973 #endif
974     HKS_FREE(keyOutBuffer);
975     HksFreeParamSet(&newParamSet);
976     return ret;
977 }
978 
GetKeyAndNewParamSetInForGenKeyInService(const struct HksProcessInfo * processInfo,const struct HksBlob * keyAlias,const struct HksParamSet * paramSet,struct HksBlob * key,struct HksParamSet ** outParamSet)979 static int32_t GetKeyAndNewParamSetInForGenKeyInService(const struct HksProcessInfo *processInfo,
980     const struct HksBlob *keyAlias, const struct HksParamSet *paramSet, struct HksBlob *key,
981     struct HksParamSet **outParamSet)
982 {
983     int32_t ret = AppendNewInfoForGenKeyInService(processInfo, paramSet, outParamSet);
984     HKS_IF_NOT_SUCC_LOGE_RETURN(ret, ret, "append new info failed, ret = %" LOG_PUBLIC "d", ret)
985 
986     ret = GetKeyData(processInfo, keyAlias, *outParamSet, key, HKS_STORAGE_TYPE_KEY);
987     if (ret != HKS_SUCCESS) {
988         HKS_LOG_E("get key data failed, ret = %" LOG_PUBLIC "d.", ret);
989         HksFreeParamSet(outParamSet);
990     }
991 
992     return ret;
993 }
994 
HksServiceImportWrappedKey(const struct HksProcessInfo * processInfo,const struct HksBlob * keyAlias,const struct HksBlob * wrappingKeyAlias,const struct HksParamSet * paramSet,const struct HksBlob * wrappedKeyData)995 int32_t HksServiceImportWrappedKey(const struct HksProcessInfo *processInfo, const struct HksBlob *keyAlias,
996     const struct HksBlob *wrappingKeyAlias, const struct HksParamSet *paramSet, const struct HksBlob *wrappedKeyData)
997 {
998     int32_t ret;
999     struct HksParamSet *newParamSet = NULL;
1000     struct HksBlob wrappingKeyFromFile = { 0, NULL };
1001     struct HksHitraceId traceId = {0};
1002 
1003 #ifdef L2_STANDARD
1004     traceId = HksHitraceBegin(__func__, HKS_HITRACE_FLAG_DEFAULT | HKS_HITRACE_FLAG_NO_BE_INFO);
1005 #endif
1006 
1007     do {
1008         ret = HksCheckImportWrappedKeyParams(&processInfo->processName, keyAlias,
1009             wrappingKeyAlias, paramSet, wrappedKeyData);
1010         HKS_IF_NOT_SUCC_LOGE_BREAK(ret, "check import params failed, ret = %" LOG_PUBLIC "d", ret)
1011 
1012         ret = HksServiceKeyExist(processInfo, wrappingKeyAlias, paramSet);
1013         HKS_IF_NOT_SUCC_LOGE_BREAK(ret, "wrapping key is not exist, ret = %" LOG_PUBLIC "d", ret)
1014 
1015         ret = GetKeyAndNewParamSetInForGenKeyInService(processInfo, wrappingKeyAlias, paramSet, &wrappingKeyFromFile,
1016             &newParamSet);
1017         HKS_IF_NOT_SUCC_LOGE_BREAK(ret, "get wrapping key and new paramSet failed, ret = %" LOG_PUBLIC "d", ret)
1018 
1019         ret = CheckKeyCondition(processInfo, keyAlias, newParamSet);
1020         HKS_IF_NOT_SUCC_LOGE_BREAK(ret, "check condition failed, ret = %" LOG_PUBLIC "d", ret)
1021 
1022         uint8_t *keyOutBuffer = (uint8_t *)HksMalloc(MAX_KEY_SIZE);
1023         if (keyOutBuffer == NULL) {
1024             ret = HKS_ERROR_MALLOC_FAIL;
1025             break;
1026         }
1027         struct HksBlob keyOut = { MAX_KEY_SIZE, keyOutBuffer };
1028         ret = HuksAccessImportWrappedKey(wrappingKeyAlias, &wrappingKeyFromFile, wrappedKeyData, newParamSet, &keyOut);
1029         IfNotSuccAppendHdiErrorInfo(ret);
1030         if (ret != HKS_SUCCESS) {
1031             HKS_LOG_E("access level import wrapped key failed, ret = %" LOG_PUBLIC "d", ret);
1032             HKS_FREE(keyOutBuffer);
1033             break;
1034         }
1035         ret = HksManageStoreKeyBlob(processInfo, newParamSet, keyAlias, &keyOut, HKS_STORAGE_TYPE_KEY);
1036         HKS_IF_NOT_SUCC_LOGE(ret, "store keyblob to storage failed, ret = %" LOG_PUBLIC "d", ret)
1037         HKS_FREE(keyOutBuffer);
1038     } while (0);
1039 
1040     HKS_FREE_BLOB(wrappingKeyFromFile);
1041     HksFreeParamSet(&newParamSet);
1042     HksReportEvent(__func__, &traceId, processInfo, paramSet, ret);
1043     return ret;
1044 }
1045 
HksServiceExportPublicKey(const struct HksProcessInfo * processInfo,const struct HksBlob * keyAlias,const struct HksParamSet * paramSet,struct HksBlob * key)1046 int32_t HksServiceExportPublicKey(const struct HksProcessInfo *processInfo, const struct HksBlob *keyAlias,
1047     const struct HksParamSet *paramSet, struct HksBlob *key)
1048 {
1049     int32_t ret;
1050     struct HksParamSet *newParamSet = NULL;
1051     struct HksBlob keyFromFile = { 0, NULL };
1052 
1053     do {
1054         ret = HksCheckExportPublicKeyParams(&processInfo->processName, keyAlias, key);
1055         HKS_IF_NOT_SUCC_LOGE_BREAK(ret, "check export public key params failed, ret = %" LOG_PUBLIC "d", ret)
1056 
1057         ret = GetKeyAndNewParamSet(processInfo, keyAlias, paramSet, &keyFromFile, &newParamSet);
1058         HKS_IF_NOT_SUCC_LOGE(ret, "export public: get main key and new paramSet failed, ret = %" LOG_PUBLIC "d", ret)
1059 
1060         if (ret == HKS_SUCCESS) {
1061             ret = HuksAccessExportPublicKey(&keyFromFile, newParamSet, key);
1062             IfNotSuccAppendHdiErrorInfo(ret);
1063         }
1064 #ifdef SUPPORT_STORAGE_BACKUP
1065         if (ret == HKS_ERROR_CORRUPT_FILE || ret == HKS_ERROR_FILE_SIZE_FAIL || ret == HKS_ERROR_NOT_EXIST) {
1066             HKS_FREE_BLOB(keyFromFile);
1067             ret = GetKeyData(processInfo, keyAlias, newParamSet, &keyFromFile, HKS_STORAGE_TYPE_BAK_KEY);
1068             HKS_IF_NOT_SUCC_LOGE_BREAK(ret,
1069                 "export public: get bak key and new paramSet failed, ret = %" LOG_PUBLIC "d", ret)
1070             ret = HuksAccessExportPublicKey(&keyFromFile, newParamSet, key);
1071             IfNotSuccAppendHdiErrorInfo(ret);
1072         }
1073 #endif
1074     } while (0);
1075 
1076     HKS_FREE_BLOB(keyFromFile);
1077     HksFreeParamSet(&newParamSet);
1078 
1079 #ifdef L2_STANDARD
1080     HksReport(__func__, processInfo, NULL, ret);
1081 #endif
1082 
1083     return ret;
1084 }
1085 
HksServiceAgreeKey(const struct HksProcessInfo * processInfo,const struct HksParamSet * paramSet,const struct HksBlob * privateKey,const struct HksBlob * peerPublicKey,struct HksBlob * agreedKey)1086 int32_t HksServiceAgreeKey(const struct HksProcessInfo *processInfo, const struct HksParamSet *paramSet,
1087     const struct HksBlob *privateKey, const struct HksBlob *peerPublicKey, struct HksBlob *agreedKey)
1088 {
1089     int32_t ret;
1090     uint64_t startTime = 0;
1091     (void)HksElapsedRealTime(&startTime);
1092     struct HksParamSet *newParamSet = NULL;
1093     struct HksBlob keyFromFile = { 0, NULL };
1094     struct HksHitraceId traceId = {0};
1095 
1096 #ifdef L2_STANDARD
1097     traceId = HksHitraceBegin(__func__, HKS_HITRACE_FLAG_DEFAULT | HKS_HITRACE_FLAG_NO_BE_INFO);
1098 #endif
1099 
1100     do {
1101         ret = HksCheckAllParams(&processInfo->processName, privateKey, paramSet, peerPublicKey, agreedKey);
1102         HKS_IF_NOT_SUCC_LOGE_BREAK(ret, "check agree key params failed, ret = %" LOG_PUBLIC "d", ret)
1103 
1104         ret = GetKeyAndNewParamSet(processInfo, privateKey, paramSet, &keyFromFile, &newParamSet);
1105         HKS_IF_NOT_SUCC_LOGE(ret, "agree: get main key and new paramSet failed, ret = %" LOG_PUBLIC "d", ret)
1106 
1107         if (ret == HKS_SUCCESS) {
1108             ret = HuksAccessAgreeKey(newParamSet, &keyFromFile, peerPublicKey, agreedKey);
1109             IfNotSuccAppendHdiErrorInfo(ret);
1110         }
1111 #ifdef SUPPORT_STORAGE_BACKUP
1112         if (ret == HKS_ERROR_CORRUPT_FILE || ret == HKS_ERROR_FILE_SIZE_FAIL || ret == HKS_ERROR_NOT_EXIST) {
1113             HKS_FREE_BLOB(keyFromFile);
1114             ret = GetKeyData(processInfo, privateKey, newParamSet, &keyFromFile, HKS_STORAGE_TYPE_BAK_KEY);
1115             HKS_IF_NOT_SUCC_LOGE_BREAK(ret, "agree: get bak key and new paramSet failed, ret = %" LOG_PUBLIC "d", ret)
1116             ret = HuksAccessAgreeKey(newParamSet, &keyFromFile, peerPublicKey, agreedKey);
1117             IfNotSuccAppendHdiErrorInfo(ret);
1118         }
1119 #endif
1120     } while (0);
1121 
1122 #ifdef L2_STANDARD
1123     HksOneStageReportInfo info = {ret, startTime, traceId.traceId.chainId, __func__, HKS_ONE_STAGE_AGREE};
1124     (void)HksOneStageEventReport(agreedKey, &keyFromFile, paramSet, processInfo, &info);
1125 #endif
1126     HksHitraceEnd(&traceId);
1127     HKS_FREE_BLOB(keyFromFile);
1128     HksFreeParamSet(&newParamSet);
1129     return ret;
1130 }
1131 
HksServiceDeriveKey(const struct HksProcessInfo * processInfo,const struct HksParamSet * paramSet,const struct HksBlob * mainKey,struct HksBlob * derivedKey)1132 int32_t HksServiceDeriveKey(const struct HksProcessInfo *processInfo, const struct HksParamSet *paramSet,
1133     const struct HksBlob *mainKey, struct HksBlob *derivedKey)
1134 {
1135     int32_t ret;
1136     uint64_t startTime = 0;
1137     (void)HksElapsedRealTime(&startTime);
1138     struct HksParamSet *newParamSet = NULL;
1139     struct HksBlob keyFromFile = { 0, NULL };
1140     struct HksHitraceId traceId = {0};
1141 
1142 #ifdef L2_STANDARD
1143     traceId = HksHitraceBegin(__func__, HKS_HITRACE_FLAG_DEFAULT | HKS_HITRACE_FLAG_NO_BE_INFO);
1144 #endif
1145 
1146     do {
1147         ret = HksCheckDeriveKeyParams(&processInfo->processName, paramSet, mainKey, derivedKey);
1148         HKS_IF_NOT_SUCC_LOGE_BREAK(ret, "check derive key params failed, ret = %" LOG_PUBLIC "d", ret)
1149 
1150         ret = GetKeyAndNewParamSet(processInfo, mainKey, paramSet, &keyFromFile, &newParamSet);
1151         HKS_IF_NOT_SUCC_LOGE(ret, "derive: get main key and new paramSet failed, ret = %" LOG_PUBLIC "d", ret)
1152 
1153         if (ret == HKS_SUCCESS) {
1154             ret = HuksAccessDeriveKey(newParamSet, &keyFromFile, derivedKey);
1155             IfNotSuccAppendHdiErrorInfo(ret);
1156         }
1157 #ifdef SUPPORT_STORAGE_BACKUP
1158         if (ret == HKS_ERROR_CORRUPT_FILE || ret == HKS_ERROR_FILE_SIZE_FAIL || ret == HKS_ERROR_NOT_EXIST) {
1159             HKS_FREE_BLOB(keyFromFile);
1160             ret = GetKeyData(processInfo, mainKey, newParamSet, &keyFromFile, HKS_STORAGE_TYPE_BAK_KEY);
1161             HKS_IF_NOT_SUCC_LOGE_BREAK(ret, "derive: get bak key and new paramSet failed, ret = %" LOG_PUBLIC "d", ret)
1162             ret = HuksAccessDeriveKey(newParamSet, &keyFromFile, derivedKey);
1163             IfNotSuccAppendHdiErrorInfo(ret);
1164         }
1165 #endif
1166     } while (0);
1167 
1168 #ifdef L2_STANDARD
1169     HksOneStageReportInfo info = {ret, startTime, traceId.traceId.chainId, __func__, HKS_ONE_STAGE_DERIVE};
1170     (void)HksOneStageEventReport(derivedKey, &keyFromFile, paramSet, processInfo, &info);
1171 #endif
1172     HksHitraceEnd(&traceId);
1173     HKS_FREE_BLOB(keyFromFile);
1174     HksFreeParamSet(&newParamSet);
1175     return ret;
1176 }
1177 
HksServiceMac(const struct HksProcessInfo * processInfo,const struct HksBlob * key,const struct HksParamSet * paramSet,const struct HksBlob * srcData,struct HksBlob * mac)1178 int32_t HksServiceMac(const struct HksProcessInfo *processInfo, const struct HksBlob *key,
1179     const struct HksParamSet *paramSet, const struct HksBlob *srcData, struct HksBlob *mac)
1180 {
1181     int32_t ret;
1182     uint64_t startTime = 0;
1183     (void)HksElapsedRealTime(&startTime);
1184     struct HksParamSet *newParamSet = NULL;
1185     struct HksBlob keyFromFile = { 0, NULL };
1186     struct HksHitraceId traceId = {0};
1187 
1188 #ifdef L2_STANDARD
1189     traceId = HksHitraceBegin(__func__, HKS_HITRACE_FLAG_DEFAULT | HKS_HITRACE_FLAG_NO_BE_INFO);
1190 #endif
1191 
1192     do {
1193         ret = HksCheckAllParams(&processInfo->processName, key, paramSet, srcData, mac);
1194         HKS_IF_NOT_SUCC_LOGE_BREAK(ret, "check mac params failed, ret = %" LOG_PUBLIC "d", ret)
1195 
1196         ret = GetKeyAndNewParamSet(processInfo, key, paramSet, &keyFromFile, &newParamSet);
1197         HKS_IF_NOT_SUCC_LOGE(ret, "mac: get main key and new paramSet failed, ret = %" LOG_PUBLIC "d", ret)
1198 
1199         if (ret == HKS_SUCCESS) {
1200             ret = HuksAccessMac(&keyFromFile, newParamSet, srcData, mac);
1201             IfNotSuccAppendHdiErrorInfo(ret);
1202         }
1203 #ifdef SUPPORT_STORAGE_BACKUP
1204         if (ret == HKS_ERROR_CORRUPT_FILE || ret == HKS_ERROR_FILE_SIZE_FAIL || ret == HKS_ERROR_NOT_EXIST) {
1205             HKS_FREE_BLOB(keyFromFile);
1206             ret = GetKeyData(processInfo, key, newParamSet, &keyFromFile, HKS_STORAGE_TYPE_BAK_KEY);
1207             HKS_IF_NOT_SUCC_LOGE_BREAK(ret, "mac: get bak key and new paramSet failed, ret = %" LOG_PUBLIC "d", ret)
1208             ret = HuksAccessMac(&keyFromFile, newParamSet, srcData, mac);
1209             IfNotSuccAppendHdiErrorInfo(ret);
1210         }
1211 #endif
1212     } while (0);
1213 
1214 #ifdef L2_STANDARD
1215     HksOneStageReportInfo info = {ret, startTime, traceId.traceId.chainId, __func__, HKS_ONE_STAGE_MAC};
1216     (void)HksOneStageEventReport(key, &keyFromFile, paramSet, processInfo, &info);
1217 #endif
1218     HksHitraceEnd(&traceId);
1219     HKS_FREE_BLOB(keyFromFile);
1220     HksFreeParamSet(&newParamSet);
1221     return ret;
1222 }
1223 
HksServiceInitialize(void)1224 int32_t HksServiceInitialize(void)
1225 {
1226     int32_t ret;
1227     do {
1228         ret = HuksAccessModuleInit();
1229         IfNotSuccAppendHdiErrorInfo(ret);
1230         HKS_IF_NOT_SUCC_LOGE_BREAK(ret, "hks core service initialize failed! ret = %" LOG_PUBLIC "d", ret)
1231 
1232         ret = HksInitPluginProxy();
1233         HKS_IF_NOT_SUCC_LOGE_BREAK(ret, "Init plugin failed, ret=%" LOG_PUBLIC "d", ret);
1234 
1235 #ifdef _STORAGE_LITE_
1236         ret = HksLoadFileToBuffer();
1237         HKS_IF_NOT_SUCC_LOGE_BREAK(ret, "load file to buffer failed, ret = %" LOG_PUBLIC "d", ret)
1238 #endif
1239 
1240 #ifdef HKS_ENABLE_MARK_CLEARED_FOR_SMALL_TO_SERVICE
1241         (void)HksMarkOldKeyClearedIfEmpty();
1242 #endif
1243     } while (0);
1244 
1245 #ifdef L2_STANDARD
1246     HksReport(__func__, NULL, NULL, ret);
1247 #endif
1248 
1249     return ret;
1250 }
1251 
HksServiceRefreshKeyInfo(const struct HksBlob * processName)1252 int32_t HksServiceRefreshKeyInfo(const struct HksBlob *processName)
1253 {
1254     int32_t ret;
1255 
1256     do {
1257         ret = HksStoreDestroy(processName);
1258         HKS_IF_NOT_SUCC_LOGE_BREAK(ret, "destroy storage files ret = 0x%" LOG_PUBLIC "X", ret)
1259 
1260 #ifndef _HARDWARE_ROOT_KEY_
1261         ret = HuksAccessRefresh();
1262         HKS_IF_NOT_SUCC_LOGE_BREAK(ret, "Hks core service refresh info failed! ret = 0x%" LOG_PUBLIC "X", ret)
1263 #endif
1264 
1265 #ifdef _STORAGE_LITE_
1266         ret = HksFileBufferRefresh();
1267         HKS_IF_NOT_SUCC_LOGE_BREAK(ret, "load file to buffer failed, ret = %" LOG_PUBLIC "d", ret)
1268 #endif
1269     } while (0);
1270 
1271 #ifdef L2_STANDARD
1272     int userId = 0;
1273     struct HksBlob userIdBlob = { sizeof(int), (uint8_t *)&userId };
1274     struct HksProcessInfo processInfo = {userIdBlob, *processName};
1275     HksReport(__func__, &processInfo, NULL, ret);
1276 #endif
1277 
1278     return ret;
1279 }
1280 
1281 #ifdef HKS_SUPPORT_API_ATTEST_KEY
1282 #ifdef HKS_SUPPORT_GET_BUNDLE_INFO
AddAppInfoToParamSet(const struct HksProcessInfo * processInfo,struct HksBlob * appInfo,struct HksParamSet * paramSet)1283 static int32_t AddAppInfoToParamSet(const struct HksProcessInfo *processInfo, struct HksBlob *appInfo,
1284     struct HksParamSet *paramSet)
1285 {
1286     int32_t ret;
1287     do {
1288         enum HksCallerType appidType = HksGetCallerType();
1289         if (appidType == HKS_HAP_TYPE) {
1290             ret = HksGetHapInfo(processInfo, appInfo);
1291             HKS_IF_NOT_SUCC_LOGE_BREAK(ret, "HksGetHapInfo failed")
1292         } else if (appidType == HKS_SA_TYPE) {
1293             ret = HksGetSaInfo(processInfo, appInfo);
1294             HKS_IF_NOT_SUCC_LOGE_BREAK(ret, "HksGetSaInfo failed")
1295         }
1296 
1297         ret = CheckBlob(appInfo);
1298         if (ret == HKS_SUCCESS) {
1299             struct HksParam params[] = {
1300                 { .tag = HKS_TAG_ATTESTATION_APPLICATION_ID, .blob = *appInfo },
1301                 { .tag = HKS_TAG_ATTESTATION_APPLICATION_ID_TYPE, .uint32Param = appidType }
1302             };
1303             ret = HksAddParams(paramSet, params, sizeof(params) / sizeof(params[0]));
1304             HKS_IF_NOT_SUCC_LOGE_BREAK(ret, "add appInfo failed")
1305         } else {
1306             HKS_IF_NOT_SUCC_LOGE_BREAK(ret, "Check appInfo Blob failed!")
1307         }
1308     } while (0);
1309     return ret;
1310 }
1311 #endif
1312 
AddModelToParamSet(struct HksParamSet * paramSet)1313 static int32_t AddModelToParamSet(struct HksParamSet *paramSet)
1314 {
1315     const char *modelPtr = GetProductModel();
1316     HKS_IF_NULL_LOGE_RETURN(modelPtr, HKS_ERROR_NULL_POINTER, "GetProductModel failed")
1317 
1318     struct HksParam modelParam = {
1319         .tag = HKS_TAG_ATTESTATION_ID_MODEL,
1320         .blob = { .size = strlen(modelPtr), .data = (uint8_t *)modelPtr }
1321     };
1322     int32_t ret = HksAddParams(paramSet, &modelParam, 1);
1323     HKS_IF_NOT_SUCC_LOGE(ret, "add model failed")
1324     return HKS_SUCCESS;
1325 }
1326 
AddAppInfoAndModelToParamSet(const struct HksProcessInfo * processInfo,const struct HksParamSet * paramSet,struct HksParamSet ** outParamSet)1327 static int32_t AddAppInfoAndModelToParamSet(const struct HksProcessInfo *processInfo,
1328     const struct HksParamSet *paramSet, struct HksParamSet **outParamSet)
1329 {
1330     int32_t ret;
1331     struct HksBlob appInfo = { 0, NULL };
1332     struct HksParamSet *newParamSet = NULL;
1333 
1334     do {
1335 #ifdef HKS_SUPPORT_GET_BUNDLE_INFO
1336         ret = AppendToNewParamSet(paramSet, &newParamSet);
1337         HKS_IF_NOT_SUCC_LOGE_BREAK(ret, "copy paramSet failed")
1338 
1339         ret = AddAppInfoToParamSet(processInfo, &appInfo, newParamSet);
1340         HKS_IF_NOT_SUCC_LOGE_BREAK(ret, "add appInfo to paramset failed")
1341 #else
1342         ret = AppendToNewParamSet(*outParamSet, &newParamSet);
1343         HKS_IF_NOT_SUCC_LOGE_BREAK(ret, "copy outParamSet failed")
1344 #endif
1345 
1346         ret = AddModelToParamSet(newParamSet);
1347         HKS_IF_NOT_SUCC_LOGE_BREAK(ret, "add model to paramset failed")
1348 
1349         ret = HksBuildParamSet(&newParamSet);
1350         HKS_IF_NOT_SUCC_LOGE_BREAK(ret, "build paramset failed")
1351 
1352 #ifndef HKS_SUPPORT_GET_BUNDLE_INFO
1353         HksFreeParamSet(outParamSet);
1354 #endif
1355         *outParamSet = newParamSet;
1356         HKS_FREE_BLOB(appInfo);
1357         return ret;
1358     } while (0);
1359 
1360     HKS_FREE_BLOB(appInfo);
1361     HksFreeParamSet(&newParamSet);
1362     return ret;
1363 }
1364 
DcmGenerateCertChainInAttestKey(const struct HksParamSet * paramSet,const uint8_t * remoteObject,struct HksBlob * certChain,uint32_t certChainCapacity)1365 static int32_t DcmGenerateCertChainInAttestKey(const struct HksParamSet *paramSet, const uint8_t *remoteObject,
1366     struct HksBlob *certChain, uint32_t certChainCapacity)
1367 {
1368     (void)paramSet;
1369     (void)remoteObject;
1370     (void)certChain;
1371     (void)certChainCapacity;
1372     int32_t ret = HKS_SUCCESS;
1373 #ifndef HKS_UNTRUSTED_RUNNING_ENV
1374     HKS_IF_NOT_TRUE_LOGI_RETURN(HksAttestIsAnonymous(paramSet), HKS_SUCCESS, "non anonymous attest key.")
1375     ret = DcmGenerateCertChain(certChain, remoteObject);
1376     HKS_IF_NOT_SUCC_LOGE_RETURN(ret, ret, "DcmGenerateCertChain fail, ret = %" LOG_PUBLIC "d.", ret)
1377 
1378     (void)memset_s(certChain->data, certChainCapacity, 0, certChainCapacity);
1379     certChain->size = certChainCapacity; // restore capacity size
1380 #endif
1381     return ret;
1382 }
1383 
AttestFree(struct HksBlob * keyFromFile,struct HksParamSet ** newParamSet,struct HksParamSet ** processInfoParamSet,struct HksHitraceId * traceId)1384 static void AttestFree(struct HksBlob *keyFromFile, struct HksParamSet **newParamSet,
1385     struct HksParamSet **processInfoParamSet, struct HksHitraceId *traceId)
1386 {
1387     HksFreeParamSet(newParamSet);
1388     HksFreeParamSet(processInfoParamSet);
1389     HksHitraceEnd(traceId);
1390     HKS_IF_NULL_LOGE_RETURN_VOID(keyFromFile, "keyFromFile is null")
1391     HKS_FREE_BLOB(*keyFromFile);
1392 }
1393 
AccessAttestKey(struct HksBlob * keyFromFile,struct HksParamSet * newParamSet,struct HksBlob * certChain)1394 static int32_t AccessAttestKey(struct HksBlob *keyFromFile, struct HksParamSet *newParamSet, struct HksBlob *certChain)
1395 {
1396     int32_t ret = HuksAccessAttestKey(keyFromFile, newParamSet, certChain);
1397     IfNotSuccAppendHdiErrorInfo(ret);
1398     return ret;
1399 }
1400 
HksServiceAttestKey(const struct HksProcessInfo * processInfo,const struct HksBlob * keyAlias,const struct HksParamSet * paramSet,struct HksBlob * certChain,const uint8_t * remoteObject)1401 int32_t HksServiceAttestKey(const struct HksProcessInfo *processInfo, const struct HksBlob *keyAlias,
1402     const struct HksParamSet *paramSet, struct HksBlob *certChain, const uint8_t *remoteObject)
1403 {
1404     uint64_t startTime = 0;
1405     (void)HksElapsedRealTime(&startTime);
1406     struct HksHitraceId traceId = HksHitraceBegin(__func__, HKS_HITRACE_FLAG_DEFAULT | HKS_HITRACE_FLAG_NO_BE_INFO);
1407     struct HksBlob keyFromFile = { 0, NULL };
1408     struct HksParamSet *newParamSet = NULL;
1409     struct HksParamSet *processInfoParamSet = NULL;
1410     int32_t ret = HksCheckAttestKeyParams(&processInfo->processName, keyAlias, paramSet, certChain);
1411     do {
1412         HKS_IF_NOT_SUCC_LOGE_BREAK(ret, "check attest key param fail");
1413 #ifdef HKS_SUPPORT_GET_BUNDLE_INFO
1414         ret = GetKeyAndNewParamSet(processInfo, keyAlias, paramSet, &keyFromFile, &processInfoParamSet);
1415         HKS_IF_NOT_SUCC_LOGE(ret, "GetKeyAndNewParamSet failed, ret = %" LOG_PUBLIC "d.", ret)
1416 #else
1417         ret = GetKeyAndNewParamSet(processInfo, keyAlias, paramSet, &keyFromFile, &newParamSet);
1418         HKS_IF_NOT_SUCC_LOGE(ret, "GetKeyAndNewParamSet failed, ret = %" LOG_PUBLIC "d.", ret)
1419 #endif
1420         uint32_t certChainCapacity = certChain->size;
1421         if (ret == HKS_SUCCESS) {
1422             ret = AddAppInfoAndModelToParamSet(processInfo, processInfoParamSet, &newParamSet);
1423             HKS_IF_NOT_SUCC_LOGE_BREAK(ret, "AddAppInfoAndModelToParamSet failed, ret = %" LOG_PUBLIC "d.", ret)
1424             ret = AccessAttestKey(&keyFromFile, newParamSet, certChain);
1425         }
1426 #ifdef SUPPORT_STORAGE_BACKUP
1427         if (ret == HKS_ERROR_CORRUPT_FILE || ret == HKS_ERROR_FILE_SIZE_FAIL || ret == HKS_ERROR_NOT_EXIST) {
1428             HKS_FREE_BLOB(keyFromFile);
1429 #ifdef HKS_SUPPORT_GET_BUNDLE_INFO
1430             HksFreeParamSet(&newParamSet);
1431 #endif
1432             ret = AddAppInfoAndModelToParamSet(processInfo, processInfoParamSet, &newParamSet);
1433             HKS_IF_NOT_SUCC_LOGE_BREAK(ret, "AddAppInfoAndModelToParamSet failed, ret = %" LOG_PUBLIC "d.", ret)
1434             ret = GetKeyData(processInfo, keyAlias, newParamSet, &keyFromFile, HKS_STORAGE_TYPE_BAK_KEY);
1435             HKS_IF_NOT_SUCC_LOGE_BREAK(ret, "get bak key and new paramSet failed, ret = %" LOG_PUBLIC "d", ret)
1436             ret = AccessAttestKey(&keyFromFile, newParamSet, certChain);
1437         }
1438 #endif
1439         HKS_IF_NOT_SUCC_LOGE_BREAK(ret, "HuksAttestKey fail, ret = %" LOG_PUBLIC "d.", ret)
1440         ret = DcmGenerateCertChainInAttestKey(paramSet, remoteObject, certChain, certChainCapacity);
1441     } while (0);
1442 #ifdef L2_STANDARD
1443     HksOneStageReportInfo info = {ret, startTime, traceId.traceId.chainId, __func__, HKS_ONE_STAGE_ATTEST};
1444     (void)HksOneStageEventReport(keyAlias, &keyFromFile, paramSet, processInfo, &info);
1445 #endif
1446 
1447     AttestFree(&keyFromFile, &newParamSet, &processInfoParamSet, &traceId);
1448     return ret;
1449 }
1450 #else // HKS_SUPPORT_API_ATTEST_KEY
HksServiceAttestKey(const struct HksProcessInfo * processInfo,const struct HksBlob * keyAlias,const struct HksParamSet * paramSet,struct HksBlob * certChain,const uint8_t * remoteObject)1451 int32_t HksServiceAttestKey(const struct HksProcessInfo *processInfo, const struct HksBlob *keyAlias,
1452     const struct HksParamSet *paramSet, struct HksBlob *certChain, const uint8_t *remoteObject)
1453 {
1454     (void)processInfo;
1455     (void)keyAlias;
1456     (void)paramSet;
1457     (void)certChain;
1458     (void)remoteObject;
1459     return HKS_ERROR_NOT_SUPPORTED;
1460 }
1461 #endif // HKS_SUPPORT_API_ATTEST_KEY
1462 
HksServiceInit(const struct HksProcessInfo * processInfo,const struct HksBlob * keyAlias,const struct HksParamSet * paramSet,struct HksBlob * handle,struct HksBlob * token)1463 int32_t HksServiceInit(const struct HksProcessInfo *processInfo, const struct HksBlob *keyAlias,
1464     const struct HksParamSet *paramSet, struct HksBlob *handle, struct HksBlob *token)
1465 {
1466     uint64_t startTime = 0;
1467     (void)HksElapsedRealTime(&startTime);
1468     int32_t ret;
1469     struct HksParamSet *newParamSet = NULL;
1470     struct HksBlob keyFromFile = { 0, NULL };
1471     struct HksHitraceId traceId = {0};
1472 
1473 #ifdef L2_STANDARD
1474     traceId = HksHitraceBegin(__func__, HKS_HITRACE_FLAG_DEFAULT | HKS_HITRACE_FLAG_NO_BE_INFO);
1475 #endif
1476 
1477     do {
1478         ret = HksCheckServiceInitParams(&processInfo->processName, keyAlias, paramSet);
1479         HKS_IF_NOT_SUCC_LOGE_BREAK(ret, "check ServiceInit params failed, ret = %" LOG_PUBLIC "d", ret)
1480 
1481         ret = GetKeyAndNewParamSet(processInfo, keyAlias, paramSet, &keyFromFile, &newParamSet);
1482         HKS_IF_NOT_SUCC_LOGE(ret, "GetKeyAndNewParamSet failed, ret = %" LOG_PUBLIC "d", ret)
1483 
1484         if (ret == HKS_SUCCESS) {
1485             ret = HuksAccessInit(&keyFromFile, newParamSet, handle, token);
1486             IfNotSuccAppendHdiErrorInfo(ret);
1487         }
1488 #ifdef SUPPORT_STORAGE_BACKUP
1489         if (ret == HKS_ERROR_CORRUPT_FILE || ret == HKS_ERROR_FILE_SIZE_FAIL || ret == HKS_ERROR_NOT_EXIST) {
1490             HKS_FREE_BLOB(keyFromFile);
1491             ret = GetKeyData(processInfo, keyAlias, newParamSet, &keyFromFile, HKS_STORAGE_TYPE_BAK_KEY);
1492             HKS_IF_NOT_SUCC_LOGE_BREAK(ret, "get bak key and new paramSet failed, ret = %" LOG_PUBLIC "d", ret)
1493             ret = HuksAccessInit(&keyFromFile, newParamSet, handle, token);
1494             IfNotSuccAppendHdiErrorInfo(ret);
1495         }
1496 #endif
1497         HKS_IF_NOT_SUCC_LOGE_BREAK(ret, "Huks Init failed, ret = %" LOG_PUBLIC "d", ret)
1498 
1499         ret = CreateOperation(processInfo, paramSet, handle, true);
1500         HKS_IF_NOT_SUCC_LOGE_BREAK(ret, "create operation failed, ret = %" LOG_PUBLIC "d", ret)
1501     } while (0);
1502 #ifdef L2_STANDARD
1503     HksEventInfo eventInfo = { };
1504     (void)HksGetInitEventInfo(keyAlias, &keyFromFile, paramSet, processInfo, &eventInfo);
1505     HksThreeStageReportInfo info = { ret, 0, HKS_INIT, startTime, traceId.traceId.chainId, handle };
1506     (void)HksServiceInitReport(__func__, processInfo, paramSet, &info, &eventInfo);
1507 #endif
1508     HKS_FREE_BLOB(keyFromFile);
1509     HksFreeParamSet(&newParamSet);
1510     HksHitraceEnd(&traceId);
1511     return ret;
1512 }
1513 
HksServiceCheckBatchUpdateTime(struct HksOperation * operation)1514 static int32_t HksServiceCheckBatchUpdateTime(struct HksOperation *operation)
1515 {
1516     uint64_t curTime = 0;
1517     int32_t ret = HksElapsedRealTime(&curTime);
1518     HKS_IF_NOT_SUCC_LOGE_RETURN(ret, ret, "HksElapsedRealTime failed");
1519     if (operation->batchOperationTimestamp < curTime) {
1520         HKS_LOG_E("Batch operation timeout");
1521         return HKS_ERROR_INVALID_TIME_OUT;
1522     }
1523     return ret;
1524 }
1525 
MarkAndDeleteOperation(struct HksOperation ** operation,const struct HksBlob * handle)1526 static void MarkAndDeleteOperation(struct HksOperation **operation, const struct HksBlob *handle)
1527 {
1528     HKS_IF_NULL_LOGE_RETURN_VOID(operation, "operation is null")
1529     MarkOperationUnUse(*operation);
1530     DeleteOperation(handle);
1531     *operation = NULL;
1532 }
1533 
HksUpdateEnd(struct HksOperation ** operation,struct HksHitraceId * traceId)1534 static void HksUpdateEnd(struct HksOperation **operation, struct HksHitraceId *traceId)
1535 {
1536     HKS_IF_TRUE_LOGE_RETURN_VOID(operation == NULL || traceId == NULL, "operation is null")
1537     MarkOperationUnUse(*operation);
1538     HksHitraceEnd(traceId);
1539 }
1540 
HksServiceUpdate(const struct HksBlob * handle,const struct HksProcessInfo * processInfo,const struct HksParamSet * paramSet,const struct HksBlob * inData,struct HksBlob * outData)1541 int32_t HksServiceUpdate(const struct HksBlob *handle, const struct HksProcessInfo *processInfo,
1542     const struct HksParamSet *paramSet, const struct HksBlob *inData, struct HksBlob *outData)
1543 {
1544     uint64_t startTime = 0;
1545     (void)HksElapsedRealTime(&startTime);
1546     struct HksHitraceId traceId = {0};
1547 
1548 #ifdef L2_STANDARD
1549     traceId = HksHitraceBegin(__func__, HKS_HITRACE_FLAG_DEFAULT | HKS_HITRACE_FLAG_NO_BE_INFO);
1550 #endif
1551     struct HksParamSet *newParamSet = NULL;
1552     struct HksOperation *operation;
1553     int32_t ret;
1554     do {
1555         operation = QueryOperationAndMarkInUse(processInfo, handle);
1556         ret = (operation == NULL ? HKS_ERROR_NOT_EXIST : HKS_SUCCESS);
1557         HKS_IF_NOT_SUCC_LOGE_BREAK(ret, "operationHandle is not exist or being busy")
1558 
1559 #ifdef HKS_SUPPORT_ACCESS_TOKEN
1560         if (operation->accessTokenId != processInfo->accessTokenId) {
1561             HKS_LOG_E("compare access token id failed, unauthorized calling");
1562             ret = HKS_ERROR_BAD_STATE;
1563             break;
1564         }
1565 #endif
1566 
1567         if (operation->isBatchOperation) {
1568             ret = HksServiceCheckBatchUpdateTime(operation);
1569             if (ret != HKS_SUCCESS) {
1570                 HKS_LOG_E("HksServiceCheckBatchUpdateTime fail, ret = %" LOG_PUBLIC "d", ret);
1571                 MarkAndDeleteOperation(&operation, handle);
1572                 break;
1573             }
1574         }
1575         ret = AppendProcessInfoAndDefaultStrategy(paramSet, processInfo, operation, &newParamSet);
1576         HKS_IF_NOT_SUCC_LOGE_BREAK(ret, "append process info failed, ret = %" LOG_PUBLIC "d", ret)
1577 
1578         ret = HksCheckAcrossAccountsPermission(newParamSet, processInfo->userIdInt);
1579         HKS_IF_NOT_SUCC_LOGE_BREAK(ret, "HksCheckAcrossAccountsPermission fail, ret = %" LOG_PUBLIC "d", ret)
1580 
1581         ret = HuksAccessUpdate(handle, newParamSet, inData, outData);
1582         IfNotSuccAppendHdiErrorInfo(ret);
1583         if (ret != HKS_SUCCESS) {
1584             HKS_LOG_E("HuksAccessUpdate fail, ret = %" LOG_PUBLIC "d", ret);
1585             MarkAndDeleteOperation(&operation, handle);
1586             break;
1587         }
1588     } while (0);
1589 #ifdef L2_STANDARD
1590     HksThreeStageReportInfo info = { ret, inData->size, HKS_UPDATE, startTime, traceId.traceId.chainId,
1591         handle, operation };
1592     (void)HksThreeStageReport(__func__, processInfo, paramSet, &info);
1593 #endif
1594     HksUpdateEnd(&operation, &traceId);
1595     HksFreeParamSet(&newParamSet);
1596     return ret;
1597 }
1598 
AppendAndQueryInFinish(const struct HksBlob * handle,const struct HksProcessInfo * processInfo,struct HksOperation ** outOperation)1599 static int32_t AppendAndQueryInFinish(const struct HksBlob *handle, const struct HksProcessInfo *processInfo,
1600     struct HksOperation **outOperation)
1601 {
1602     struct HksOperation *operation = QueryOperationAndMarkInUse(processInfo, handle);
1603     HKS_IF_NULL_LOGE_RETURN(operation, HKS_ERROR_NOT_EXIST, "operationHandle is not exist or being busy")
1604 #ifdef HKS_SUPPORT_ACCESS_TOKEN
1605     HKS_IF_TRUE_LOGE_RETURN(operation->accessTokenId != processInfo->accessTokenId, HKS_ERROR_BAD_STATE,
1606         "compare access token id failed, unauthorized calling")
1607 #endif
1608     *outOperation = operation;
1609     return HKS_SUCCESS;
1610 }
1611 
InitOutputDataForFinish(struct HksBlob * output,const struct HksBlob * outData,bool isStorage)1612 static int32_t InitOutputDataForFinish(struct HksBlob *output, const struct HksBlob *outData, bool isStorage)
1613 {
1614     output->data = (uint8_t *)HksMalloc(output->size);
1615     HKS_IF_NULL_RETURN(output->data, HKS_ERROR_MALLOC_FAIL)
1616 
1617     (void)memset_s(output->data, output->size, 0, output->size);
1618     if (!isStorage) {
1619         if ((memcpy_s(output->data, output->size, outData->data, outData->size) != EOK)) {
1620             HKS_FREE(output->data);
1621             return HKS_ERROR_INSUFFICIENT_MEMORY;
1622         }
1623     }
1624     return HKS_SUCCESS;
1625 }
1626 
HksServiceFinish(const struct HksBlob * handle,const struct HksProcessInfo * processInfo,const struct HksParamSet * paramSet,const struct HksBlob * inData,struct HksBlob * outData)1627 int32_t HksServiceFinish(const struct HksBlob *handle, const struct HksProcessInfo *processInfo,
1628     const struct HksParamSet *paramSet, const struct HksBlob *inData, struct HksBlob *outData)
1629 {
1630     uint64_t startTime = 0;
1631     (void)HksElapsedRealTime(&startTime);
1632     struct HksHitraceId traceId = {0};
1633 
1634 #ifdef L2_STANDARD
1635     traceId = HksHitraceBegin(__func__, HKS_HITRACE_FLAG_DEFAULT | HKS_HITRACE_FLAG_NO_BE_INFO);
1636 #endif
1637 
1638     struct HksParamSet *newParamSet = NULL;
1639     bool isNeedStorage = false;
1640     uint32_t outSize = outData->size;
1641     int32_t ret = HksCheckKeyNeedStored(paramSet, &isNeedStorage);
1642     if (ret == HKS_SUCCESS && isNeedStorage) {
1643         outSize = MAX_KEY_SIZE;
1644     }
1645     struct HksBlob output = { outSize, NULL };
1646     struct HksOperation *operation = NULL;
1647     do {
1648         if (outSize != 0) {
1649             ret = InitOutputDataForFinish(&output, outData, isNeedStorage);
1650             HKS_IF_NOT_SUCC_LOGE_BREAK(ret, "init output data failed")
1651         }
1652         ret = AppendAndQueryInFinish(handle, processInfo, &operation);
1653         HKS_IF_NOT_SUCC_LOGE_BREAK(ret, "AppendAndQueryInFinish fail, ret = %" LOG_PUBLIC "d", ret)
1654 
1655         ret = AppendProcessInfoAndDefaultStrategy(paramSet, processInfo, operation, &newParamSet);
1656         HKS_IF_NOT_SUCC_LOGE_BREAK(ret, "append process info failed, ret = %" LOG_PUBLIC "d", ret)
1657 
1658         ret = HksCheckAcrossAccountsPermission(newParamSet, processInfo->userIdInt);
1659         HKS_IF_NOT_SUCC_LOGE_BREAK(ret, "HksCheckAcrossAccountsPermission fail, ret = %" LOG_PUBLIC "d", ret)
1660 
1661         ret = HuksAccessFinish(handle, newParamSet, inData, &output);
1662         IfNotSuccAppendHdiErrorInfo(ret);
1663         HKS_IF_NOT_SUCC_LOGE_BREAK(ret, "HuksAccessFinish fail, ret = %" LOG_PUBLIC "d", ret)
1664 
1665         ret = StoreOrCopyKeyBlob(newParamSet, processInfo, &output, outData, isNeedStorage);
1666         HKS_IF_NOT_SUCC_LOGE_BREAK(ret, "StoreOrCopyKeyBlob fail, ret = %" LOG_PUBLIC "d", ret)
1667     } while (0);
1668     if (output.data != NULL) {
1669         (void)memset_s(output.data, output.size, 0, output.size);
1670     }
1671     HKS_FREE_BLOB(output);
1672     if (operation != NULL) {
1673 #ifdef L2_STANDARD
1674         HksThreeStageReportInfo info = { ret, inData->size, HKS_FINISH, startTime, traceId.traceId.chainId,
1675             handle, operation };
1676         (void)HksThreeStageReport(__func__, processInfo, paramSet, &info);
1677 #endif
1678         MarkAndDeleteOperation(&operation, handle);
1679     }
1680     HksFreeParamSet(&newParamSet);
1681     HksHitraceEnd(&traceId);
1682     return ret;
1683 }
1684 
HksServiceAbort(const struct HksBlob * handle,const struct HksProcessInfo * processInfo,const struct HksParamSet * paramSet)1685 int32_t HksServiceAbort(const struct HksBlob *handle, const struct HksProcessInfo *processInfo,
1686     const struct HksParamSet *paramSet)
1687 {
1688     uint64_t startTime = 0;
1689     (void)HksElapsedRealTime(&startTime);
1690     struct HksHitraceId traceId = {0};
1691 
1692 #ifdef L2_STANDARD
1693     traceId = HksHitraceBegin(__func__, HKS_HITRACE_FLAG_DEFAULT | HKS_HITRACE_FLAG_NO_BE_INFO);
1694 #endif
1695     struct HksParamSet *newParamSet = NULL;
1696     struct HksOperation *operation;
1697     int32_t ret;
1698     do {
1699         operation = QueryOperationAndMarkInUse(processInfo, handle);
1700         if (operation == NULL) {
1701             HKS_LOG_E("operationHandle is not exist or being busy");
1702             ret = HKS_SUCCESS; /* return success if the handle is not found */
1703             break;
1704         }
1705 
1706         ret = AppendProcessInfoAndDefaultStrategy(paramSet, processInfo, operation, &newParamSet);
1707         HKS_IF_NOT_SUCC_LOGE_BREAK(ret, "append process info failed, ret = %" LOG_PUBLIC "d", ret)
1708 
1709         ret = HksCheckAcrossAccountsPermission(newParamSet, processInfo->userIdInt);
1710         HKS_IF_NOT_SUCC_LOGE_BREAK(ret, "HksCheckAcrossAccountsPermission fail, ret = %" LOG_PUBLIC "d", ret)
1711 
1712         ret = HuksAccessAbort(handle, newParamSet);
1713         IfNotSuccAppendHdiErrorInfo(ret);
1714         HKS_IF_NOT_SUCC_LOGE(ret, "HuksAccessAbort fail, ret = %" LOG_PUBLIC "d", ret)
1715 #ifdef L2_STANDARD
1716         HksThreeStageReportInfo info = { ret, 0, HKS_ABORT, startTime, traceId.traceId.chainId, handle, operation };
1717         (void)HksThreeStageReport(__func__, processInfo, paramSet, &info);
1718 #endif
1719         MarkAndDeleteOperation(&operation, handle);
1720     } while (0);
1721     MarkOperationUnUse(operation);
1722     HksFreeParamSet(&newParamSet);
1723     HksHitraceEnd(&traceId);
1724     return ret;
1725 }
1726 
BuildAbortParamSet(struct HksParamSet ** newParamSet)1727 static int32_t BuildAbortParamSet(struct HksParamSet **newParamSet)
1728 {
1729     int32_t ret = HksInitParamSet(newParamSet);
1730     HKS_IF_NOT_SUCC_LOGE_RETURN(ret, ret, "HksInitParamSet fail!");
1731     do {
1732         // This param exists solely to pass the paramSet validation check
1733         struct HksParam Param = { .tag = HKS_TAG_KEY_STORAGE_FLAG, .uint32Param = HKS_STORAGE_TEMP};
1734         ret = HksAddParams(*newParamSet, &Param, 1);
1735         HKS_IF_NOT_SUCC_LOGE_BREAK(ret, "HksAddParams  fail!");
1736 
1737         ret = HksBuildParamSet(newParamSet);
1738         HKS_IF_NOT_SUCC_LOGE_BREAK(ret, "HksBuildParamSet  fail!");
1739     } while (0);
1740     if (ret != HKS_SUCCESS) {
1741         HksFreeParamSet(newParamSet);
1742     }
1743     return ret;
1744 }
1745 
HksServiceAbortByPid(int32_t pid)1746 int32_t HksServiceAbortByPid(int32_t pid)
1747 {
1748     struct HksParamSet *newParamSet = NULL;
1749     struct HksOperation *operation;
1750     int32_t ret;
1751     do {
1752         operation = QueryOperationByPidAndMarkInUse(pid);
1753         if (operation == NULL) {
1754             HKS_LOG_E("operationHandle by pid failed! not exist or being busy");
1755             ret = HKS_ERROR_NOT_EXIST; /* return success if the handle is not found */
1756             break;
1757         }
1758 
1759         ret = BuildAbortParamSet(&newParamSet);
1760         HKS_IF_NOT_SUCC_LOGE_BREAK(ret, "BuildAbortParamSet failed, ret = %" LOG_PUBLIC "d", ret)
1761 
1762         struct HksBlob handleBlob = { .data = (uint8_t *)(&(operation->handle)), .size = sizeof(operation->handle) };
1763         ret = HuksAccessAbort(&handleBlob, newParamSet);
1764         IfNotSuccAppendHdiErrorInfo(ret);
1765         HKS_IF_NOT_SUCC_LOGE(ret, "HuksAccessAbort for dead process fail, ret = %" LOG_PUBLIC "d", ret)
1766 
1767         MarkAndDeleteOperation(&operation, &handleBlob);
1768     } while (0);
1769     MarkOperationUnUse(operation);
1770     HksFreeParamSet(&newParamSet);
1771     return ret;
1772 }
1773 
HksServiceDeleteProcessInfo(const struct HksProcessInfo * processInfo)1774 void HksServiceDeleteProcessInfo(const struct HksProcessInfo *processInfo)
1775 {
1776 #ifndef __LITEOS_M__
1777     HKS_LOG_I("remove session");
1778     DeleteSessionByProcessInfo(processInfo);
1779 
1780     if (processInfo->processName.size == 0) {
1781         HksServiceDeleteUserIDKeyAliasFile(&processInfo->userId);
1782     } else {
1783         HksServiceDeleteUIDKeyAliasFile(processInfo);
1784     }
1785 #else
1786     (void)processInfo;
1787 #endif
1788 }
1789 
1790 #endif
1791 
HksServiceGenerateRandom(const struct HksProcessInfo * processInfo,struct HksBlob * random)1792 int32_t HksServiceGenerateRandom(const struct HksProcessInfo *processInfo, struct HksBlob *random)
1793 {
1794     int32_t ret;
1795     struct HksParamSet *newParamSet = NULL;
1796 
1797     do {
1798         ret = HksCheckGenerateRandomParams(&processInfo->processName, random);
1799         HKS_IF_NOT_SUCC_LOGE_BREAK(ret, "check generate random params failed, ret = %" LOG_PUBLIC "d", ret)
1800 
1801         ret = AppendProcessInfoAndDefaultStrategy(NULL, processInfo, NULL, &newParamSet);
1802         HKS_IF_NOT_SUCC_LOGE_BREAK(ret, "append process info failed, ret = %" LOG_PUBLIC "d", ret)
1803 
1804         ret = HuksAccessGenerateRandom(newParamSet, random);
1805         IfNotSuccAppendHdiErrorInfo(ret);
1806     } while (0);
1807 
1808     HksFreeParamSet(&newParamSet);
1809 
1810 #ifdef L2_STANDARD
1811     HksReport(__func__, processInfo, NULL, ret);
1812 #endif
1813 
1814     return ret;
1815 }
1816 
HksServiceListAliases(const struct HksProcessInfo * processInfo,const struct HksParamSet * paramSet,struct HksKeyAliasSet ** outData)1817 int32_t HksServiceListAliases(const struct HksProcessInfo *processInfo, const struct HksParamSet *paramSet,
1818     struct HksKeyAliasSet **outData)
1819 {
1820 #ifdef L2_STANDARD
1821     struct HksParamSet *newParamSet = NULL;
1822     uint64_t enterTime = 0;
1823     (void)HksElapsedRealTime(&enterTime);
1824     int32_t ret = HKS_SUCCESS;
1825     do {
1826         ret = AppendStorageLevelIfNotExistInner(processInfo, paramSet, &newParamSet);
1827         HKS_IF_NOT_SUCC_LOGE_BREAK(ret, "append storage level failed")
1828 
1829         ret = HksCheckListAliasesParam(&(processInfo->processName));
1830         HKS_IF_NOT_SUCC_LOGE_BREAK(ret, "check list aliases param failed, ret = %" LOG_PUBLIC "d", ret)
1831 
1832         ret = HksManageListAliasesByProcessName(processInfo, newParamSet, outData);
1833         HKS_IF_NOT_SUCC_LOGE_BREAK(ret, "list aliases by process name failed, ret = %" LOG_PUBLIC "d", ret)
1834     } while (0);
1835 
1836     HksFreeParamSet(&newParamSet);
1837 #ifdef L2_STANDARD
1838     struct HksParamSet *reportParamSet = NULL;
1839     (void)PreConstructListAliasesReportParamSet(paramSet, enterTime, &reportParamSet);
1840     (void)ConstructReportParamSet(__func__, processInfo, ret, &reportParamSet);
1841     HksEventReport(__func__, processInfo, NULL, reportParamSet, ret);
1842     DeConstructReportParamSet(&reportParamSet);
1843 #endif
1844     return ret;
1845 #else
1846     (void)processInfo;
1847     (void)paramSet;
1848     (void)outData;
1849     return HKS_SUCCESS;
1850 #endif
1851 }
1852 
HksServiceRenameKeyAlias(const struct HksProcessInfo * processInfo,const struct HksBlob * oldKeyAlias,const struct HksParamSet * paramSet,const struct HksBlob * newKeyAlias)1853 int32_t HksServiceRenameKeyAlias(const struct HksProcessInfo *processInfo, const struct HksBlob *oldKeyAlias,
1854     const struct HksParamSet *paramSet, const struct HksBlob *newKeyAlias)
1855 {
1856     uint64_t enterTime = 0;
1857     (void)HksElapsedRealTime(&enterTime);
1858     int32_t ret = HKS_SUCCESS;
1859     do {
1860         ret = HksCheckProcessNameAndKeyAlias(&processInfo->processName, oldKeyAlias);
1861         HKS_IF_NOT_SUCC_BREAK(ret, "HksCheckProcessNameAndKeyAlias failed!");
1862 
1863         ret = HKsCheckOldKeyAliasDiffNewKeyAlias(oldKeyAlias, newKeyAlias);
1864         if (ret != HKS_SUCCESS) {
1865             HKS_LOG_E("the new key alias same as old key alias !, ret = %" LOG_PUBLIC "d", ret);
1866             ret = HKS_ERROR_INVALID_ARGUMENT;
1867             break;
1868         }
1869 
1870         ret = HksCheckOldKeyExist(processInfo, oldKeyAlias, paramSet);
1871         HKS_IF_NOT_SUCC_BREAK(ret, "HksCheckOldKeyExist failed!, ret = %" LOG_PUBLIC "d", ret);
1872 
1873         ret = HksCheckNewKeyNotExist(processInfo, newKeyAlias, paramSet);
1874         HKS_IF_NOT_SUCC_BREAK(ret, "HksCheckNewKeyNotExist failed!, ret = %" LOG_PUBLIC "d", ret);
1875 
1876         ret = HksManageStoreRenameKeyAlias(processInfo, oldKeyAlias, paramSet, newKeyAlias,
1877             HKS_STORAGE_TYPE_KEY);
1878         if (ret != HKS_SUCCESS) {
1879             HKS_LOG_E("bad state, rename faild !, ret = %" LOG_PUBLIC "d", ret);
1880             ret = HKS_ERROR_BAD_STATE;
1881         }
1882     } while (0);
1883 #ifdef L2_STANDARD
1884     struct HksParamSet *reportParamSet = NULL;
1885     (void)PreConstructRenameReportParamSet(oldKeyAlias, newKeyAlias, paramSet,
1886         enterTime, &reportParamSet);
1887     (void)ConstructReportParamSet(__func__, processInfo, ret, &reportParamSet);
1888     HksEventReport(__func__, processInfo, paramSet, reportParamSet, ret);
1889     DeConstructReportParamSet(&reportParamSet);
1890 #endif
1891     return ret;
1892 }
1893 
1894 #ifdef L2_STANDARD
AppendChangeStorageLevelInfoInService(const struct HksProcessInfo * processInfo,const struct HksParamSet * paramSet,struct HksParamSet ** outParamSet)1895 static int32_t AppendChangeStorageLevelInfoInService(const struct HksProcessInfo *processInfo,
1896     const struct HksParamSet *paramSet, struct HksParamSet **outParamSet)
1897 {
1898     int32_t ret;
1899     struct HksParamSet *newParamSet = NULL;
1900     do {
1901         ret = (paramSet != NULL) ? AppendToNewParamSet(paramSet, &newParamSet) : HksInitParamSet(&newParamSet);
1902         HKS_IF_NOT_SUCC_LOGE_BREAK(ret, "append client service tag failed")
1903 
1904         // process name only can be inserted by service
1905         ret = HKS_ERROR_INVALID_ARGUMENT;
1906         HKS_IF_TRUE_BREAK(CheckProcessNameTagExist(newParamSet))
1907 
1908         struct HksParam paramArr[] = {
1909             { .tag = HKS_TAG_PROCESS_NAME, .blob = processInfo->processName },
1910             { .tag = HKS_TAG_USER_ID, .uint32Param = processInfo->userIdInt },
1911             { .tag = HKS_TAG_IS_CHANGE_STORAGE_LEVEL, .boolParam = true },
1912             { .tag = HKS_TAG_SCREEN_STATE, .boolParam = HksGetScreenState()},
1913 #ifdef HKS_SUPPORT_ACCESS_TOKEN
1914             { .tag = HKS_TAG_ACCESS_TOKEN_ID, .uint64Param = processInfo->accessTokenId },
1915 #endif
1916         };
1917 
1918         ret = HksAddParams(newParamSet, paramArr, HKS_ARRAY_SIZE(paramArr));
1919         HKS_IF_NOT_SUCC_LOGE_BREAK(ret, "add processInfo failed")
1920 
1921         ret = HksBuildParamSet(&newParamSet);
1922         HKS_IF_NOT_SUCC_LOGE_BREAK(ret, "build paramset failed")
1923 
1924         *outParamSet = newParamSet;
1925         return ret;
1926     } while (0);
1927     HksFreeParamSet(&newParamSet);
1928     return ret;
1929 }
1930 
1931 /*
1932  * dest key exist and src key exist, which means HKS_ERROR_KEY_CONFLICT
1933  * dest key exist and src key not exist, which means HKS_SUCCESS(not need update)
1934  * dest key not exist and src key exist, which means need update
1935  * dest key not exist and src key not exist, which means HKS_ERROR_NOT_EXIST
1936  */
HksCheckSrcKeyAndDestKeyCondition(const struct HksProcessInfo * processInfo,const struct HksBlob * keyAlias,const struct HksParamSet * srcParamSet,const struct HksParamSet * destParamSet,bool * isSkipUpdate)1937 static int32_t HksCheckSrcKeyAndDestKeyCondition(const struct HksProcessInfo *processInfo,
1938     const struct HksBlob *keyAlias, const struct HksParamSet *srcParamSet, const struct HksParamSet *destParamSet,
1939     bool *isSkipUpdate)
1940 {
1941     int32_t ret = HksManageStoreIsKeyBlobExist(processInfo, destParamSet, keyAlias, HKS_STORAGE_TYPE_KEY);
1942     if (ret == HKS_SUCCESS) {
1943         ret = HksManageStoreIsKeyBlobExist(processInfo, srcParamSet, keyAlias, HKS_STORAGE_TYPE_KEY);
1944         if (ret == HKS_SUCCESS) {
1945             HKS_LOG_E("source and destination both have key, key conflict");
1946             ret = HKS_ERROR_KEY_CONFLICT;
1947         } else if (ret == HKS_ERROR_NOT_EXIST) {
1948             HKS_LOG_I("destination already has key, source doesn't have key, no need to transfer key ");
1949             // no need to update key, actually return success
1950             *isSkipUpdate = true;
1951         } else {
1952             HKS_LOG_E("hks get key blob is exist failed");
1953         }
1954     } else if (ret == HKS_ERROR_NOT_EXIST) {
1955         ret = HksManageStoreIsKeyBlobExist(processInfo, srcParamSet, keyAlias, HKS_STORAGE_TYPE_KEY);
1956         HKS_IF_TRUE_LOGE(ret == HKS_ERROR_NOT_EXIST, "source and destination both don't have key");
1957     } else {
1958         HKS_LOG_E("hks get key blob is exist failed");
1959     }
1960     return ret;
1961 }
1962 
HksMallocNewKey(struct HksBlob * newKey)1963 static int32_t HksMallocNewKey(struct HksBlob *newKey)
1964 {
1965     newKey->data = (uint8_t *)HksMalloc(MAX_KEY_SIZE);
1966     HKS_IF_NULL_RETURN(newKey->data, HKS_ERROR_MALLOC_FAIL)
1967 
1968     newKey->size = MAX_KEY_SIZE;
1969     return HKS_SUCCESS;
1970 }
1971 #endif
1972 
HksServiceChangeStorageLevel(const struct HksProcessInfo * processInfo,const struct HksBlob * keyAlias,const struct HksParamSet * srcParamSet,const struct HksParamSet * destParamSet)1973 int32_t HksServiceChangeStorageLevel(const struct HksProcessInfo *processInfo, const struct HksBlob *keyAlias,
1974     const struct HksParamSet *srcParamSet, const struct HksParamSet *destParamSet)
1975 {
1976 #ifdef L2_STANDARD
1977     int32_t ret;
1978     bool isSkipUpdate = false;
1979     struct HksParamSet *newParamSet = NULL;
1980     struct HksBlob oldKey = { 0, NULL };
1981     struct HksBlob newKey = { 0, NULL };
1982     do {
1983         ret = HksCheckProcessInConfigList(&processInfo->processName);
1984         HKS_IF_NOT_SUCC_LOGE_BREAK(ret, "check process in config list failed, ret = %" LOG_PUBLIC "d", ret)
1985 
1986         ret = HksCheckChangeStorageLevelParams(&processInfo->processName, keyAlias, srcParamSet, destParamSet);
1987         HKS_IF_NOT_SUCC_LOGE_BREAK(ret, "check change storage level params failed, ret = %" LOG_PUBLIC "d", ret)
1988 
1989         ret = HksCheckSrcKeyAndDestKeyCondition(processInfo, keyAlias, srcParamSet, destParamSet, &isSkipUpdate);
1990         HKS_IF_NOT_SUCC_LOGE_BREAK(ret, "check src key and dest key condition failed, ret = %" LOG_PUBLIC "d", ret)
1991 
1992         ret = GetKeyFileData(processInfo, srcParamSet, keyAlias, &oldKey, HKS_STORAGE_TYPE_KEY);
1993         HKS_IF_NOT_SUCC_LOGE_BREAK(ret, "get key data failed, ret = %" LOG_PUBLIC "d.", ret)
1994 
1995         ret = AppendChangeStorageLevelInfoInService(processInfo, destParamSet, &newParamSet);
1996         HKS_IF_NOT_SUCC_LOGE_BREAK(ret, "append change storage level info failed, ret = %" LOG_PUBLIC "d", ret)
1997 
1998         ret = HksMallocNewKey(&newKey);
1999         HKS_IF_NOT_SUCC_LOGE_BREAK(ret, "new key malloc failed, ret = %" LOG_PUBLIC "d", ret)
2000 
2001         ret = HuksAccessUpgradeKey(&oldKey, newParamSet, &newKey);
2002         IfNotSuccAppendHdiErrorInfo(ret);
2003         HKS_IF_NOT_SUCC_LOGE_BREAK(ret, "access upgrade key failed, ret = %" LOG_PUBLIC "d", ret)
2004 
2005         ret = HksManageStoreKeyBlob(processInfo, newParamSet, keyAlias, &newKey, HKS_STORAGE_TYPE_KEY);
2006         HKS_IF_NOT_SUCC_LOGE_BREAK(ret, "store keyblob to storage failed, ret = %" LOG_PUBLIC "d", ret)
2007 
2008         ret = HksManageStoreDeleteKeyBlob(processInfo, srcParamSet, keyAlias, HKS_STORAGE_TYPE_KEY);
2009         if (ret != HKS_SUCCESS && ret != HKS_ERROR_NOT_EXIST) {
2010             ret = HksManageStoreDeleteKeyBlob(processInfo, srcParamSet, keyAlias, HKS_STORAGE_TYPE_KEY);
2011             if (ret != HKS_SUCCESS && ret != HKS_ERROR_NOT_EXIST) {
2012                 ret = HKS_ERROR_KEY_CLEAR_FAILED;
2013                 HKS_LOG_E("delete src key failed");
2014             }
2015         }
2016     } while (0);
2017 
2018     HksFreeParamSet(&newParamSet);
2019     HKS_FREE_BLOB(oldKey);
2020     HKS_FREE_BLOB(newKey);
2021     HksReport(__func__, processInfo, newParamSet, ret);
2022     HKS_IF_TRUE_RETURN(isSkipUpdate, HKS_SUCCESS)
2023     return ret;
2024 #else
2025     (void)processInfo;
2026     (void)keyAlias;
2027     (void)srcParamSet;
2028     (void)destParamSet;
2029     return HKS_SUCCESS;
2030 #endif
2031 }
2032 
HksServiceWrapKey(const struct HksBlob * srcData,const uint8_t * context)2033 int32_t HksServiceWrapKey(const struct HksBlob *srcData, const uint8_t *context)
2034 {
2035     struct HksIpcData ipcData = { srcData, context };
2036     uint32_t size = sizeof(ipcData);
2037     return HksPluginOnLocalRequestWrapKey(CODE_SA_WRAP_KEY, &ipcData, &size);
2038 }
2039 
HksServiceUnwrapKey(const struct HksBlob * srcData,const uint8_t * context)2040 int32_t HksServiceUnwrapKey(const struct HksBlob *srcData, const uint8_t *context)
2041 {
2042     struct HksIpcData ipcData = { srcData, context };
2043     uint32_t size = sizeof(ipcData);
2044     return HksPluginOnLocalRequestWrapKey(CODE_SA_UNWRAP_KEY, &ipcData, &size);
2045 }
2046