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