diff --git a/README_zh.md b/README_zh.md index 2913693758b23ab3fb34035d8d94131ff1530137..88f3395a5b0df7ada07ddaea61ac5999386799a1 100755 --- a/README_zh.md +++ b/README_zh.md @@ -56,15 +56,15 @@ │ └── os_adapter # 系统能力适配层 └── services # 设备互信认证服务层代码 ├── frameworks # 设备互信认证框架层代码 - ├── data_manager # 设备互信群组信息管理模块 - ├── identity_manager # 认证凭据管理模块 + ├── data_manager # 设备互信数据管理模块 ├── legacy │ ├── authenticators # 认证执行模块 │ ├── group_auth # 设备群组认证服务 │ ├── group_manager # 设备群组管理服务 - ├── creds_manager # 凭据管理模块 + │ ├── identity_manager # 认证凭据管理模块 + │ └── creds_manager # 凭据管理模块 ├── mk_agree # 设备级主密钥协商 - ├── cred_manager # 账号凭据插件管理模块 + ├── ext_plugin_manager # 账号凭据插件管理模块 ├── key_agree_sdk # 密钥协商sdk ├── privacy_enhancement # 隐私增强模块 ├── session_manager # 会话管理模块 diff --git a/common_lib/impl/src/json_utils.c b/common_lib/impl/src/json_utils.c index 53d5e321b02d71fc60471257fed30d0a6a6ffce3..bc7dccfd2f30124cd02e62d43b9e6383a18c4f00 100644 --- a/common_lib/impl/src/json_utils.c +++ b/common_lib/impl/src/json_utils.c @@ -305,6 +305,38 @@ int32_t GetUnsignedIntFromJson(const CJson *jsonObj, const char *key, uint32_t * return CLIB_ERR_JSON_GET; } +int32_t GetUint8FromJson(const CJson *jsonObj, const char *key, uint8_t *value) +{ + if (jsonObj == NULL || key == NULL || value == NULL) { + return CLIB_ERR_NULL_PTR; + } + + cJSON *jsonObjTmp = cJSON_GetObjectItemCaseSensitive(jsonObj, key); + if (jsonObjTmp != NULL && cJSON_IsNumber(jsonObjTmp)) { + double realValue = cJSON_GetNumberValue(jsonObjTmp); + if (realValue < 0) { + int8_t tmpValue = (int8_t)realValue; + *value = (uint8_t)tmpValue; + } else { + *value = (uint8_t)realValue; + } + return CLIB_SUCCESS; + } + + int len = cJSON_GetArraySize(jsonObj); + for (int i = 0; i < len; i++) { + cJSON *item = cJSON_GetArrayItem(jsonObj, i); + if (cJSON_IsObject(item)) { + int8_t ret = GetUint8FromJson(item, key, value); + if (ret == CLIB_SUCCESS) { + return ret; + } + } + } + + return CLIB_ERR_JSON_GET; +} + int32_t GetInt64FromJson(const CJson *jsonObj, const char *key, int64_t *value) { const char *str = GetStringFromJson(jsonObj, key); diff --git a/common_lib/interfaces/json_utils.h b/common_lib/interfaces/json_utils.h index 2ac66d10770072366eedf6762ebc62ec3ba8978e..ad59c6ba64f6fe09e2300be907a2d705b6a92c34 100644 --- a/common_lib/interfaces/json_utils.h +++ b/common_lib/interfaces/json_utils.h @@ -100,6 +100,7 @@ int32_t AddStringArrayToJson(CJson *jsonObj, const char *key, const char * const void ClearSensitiveStringInJson(CJson *jsonObj, const char *key); void ClearAndFreeJsonString(char *jsonStr); int32_t GetUnsignedIntFromJson(const CJson *jsonObj, const char *key, uint32_t *value); +int32_t GetUint8FromJson(const CJson *jsonObj, const char *key, uint8_t *value); #ifdef __cplusplus } diff --git a/deps_adapter/BUILD.gn b/deps_adapter/BUILD.gn index 03ccf7b4b81a325f13517b1e00190a1a9971306f..62cdacaf633bb26f1263e2a73bb4e1cdaa102d02 100644 --- a/deps_adapter/BUILD.gn +++ b/deps_adapter/BUILD.gn @@ -36,6 +36,7 @@ if (defined(ohos_lite)) { sources += [ "${key_management_adapter_path}/impl/src/common/mbedtls_ec_adapter.c", "${key_management_adapter_path}/impl/src/huks_adapter.c", + "${key_management_adapter_path}/impl/src/huks_adapter_utils.c", "${key_management_adapter_path}/impl/src/mini/huks_adapter_diff_impl.c", "${os_adapter_path}/impl/src/liteos/hc_condition.c", "${os_adapter_path}/impl/src/liteos/hc_dev_info.c", @@ -87,6 +88,7 @@ if (defined(ohos_lite)) { sources += [ "${key_management_adapter_path}/impl/src/common/mbedtls_ec_adapter.c", "${key_management_adapter_path}/impl/src/huks_adapter.c", + "${key_management_adapter_path}/impl/src/huks_adapter_utils.c", "${key_management_adapter_path}/impl/src/small/huks_adapter_diff_impl.c", "${os_adapter_path}/impl/src/hc_log.c", "${os_adapter_path}/impl/src/linux/hc_condition.c", @@ -129,6 +131,7 @@ if (defined(ohos_lite)) { sources += [ "${key_management_adapter_path}/impl/src/common/mbedtls_ec_adapter.c", "${key_management_adapter_path}/impl/src/huks_adapter.c", + "${key_management_adapter_path}/impl/src/huks_adapter_utils.c", "${key_management_adapter_path}/impl/src/standard/crypto_hash_to_point.c", "${key_management_adapter_path}/impl/src/standard/huks_adapter_diff_impl.c", "${os_adapter_path}/impl/src/hc_log.c", @@ -182,6 +185,7 @@ if (defined(ohos_lite)) { sources += [ "${key_management_adapter_path}/impl/src/common/mbedtls_ec_adapter.c", "${key_management_adapter_path}/impl/src/huks_adapter.c", + "${key_management_adapter_path}/impl/src/huks_adapter_utils.c", "${key_management_adapter_path}/impl/src/standard/crypto_hash_to_point.c", "${key_management_adapter_path}/impl/src/standard/huks_adapter_diff_impl.c", "${os_adapter_path}/impl/src/hc_log.c", diff --git a/deps_adapter/key_management_adapter/impl/src/common/mbedtls_ec_adapter.c b/deps_adapter/key_management_adapter/impl/src/common/mbedtls_ec_adapter.c index bdfe6b17d897ee5f51a87d2499d5345b3cb178e7..42c081616d7fc30401243c24ea03087645387e78 100644 --- a/deps_adapter/key_management_adapter/impl/src/common/mbedtls_ec_adapter.c +++ b/deps_adapter/key_management_adapter/impl/src/common/mbedtls_ec_adapter.c @@ -26,6 +26,7 @@ #include "hal_error.h" #include "hc_log.h" #include "huks_adapter.h" +#include "huks_adapter_utils.h" #define LOG_AND_RETURN_IF_MBED_FAIL(ret, fmt, ...) \ do { \ diff --git a/deps_adapter/key_management_adapter/impl/src/huks_adapter.c b/deps_adapter/key_management_adapter/impl/src/huks_adapter.c index 74dc43a8476db7121097358ff539a23c1ce39beb..fa541974863c7e42677db4e8e4c80d9d375f6410 100644 --- a/deps_adapter/key_management_adapter/impl/src/huks_adapter.c +++ b/deps_adapter/key_management_adapter/impl/src/huks_adapter.c @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021-2023 Huawei Device Co., Ltd. + * Copyright (C) 2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -14,104 +14,22 @@ */ #include "huks_adapter.h" +#include "huks_adapter_utils.h" + #include "huks_adapter_diff_impl.h" #include "hc_log.h" -#include "hks_api.h" -#include "hks_param.h" -#include "hks_type.h" #include "mbedtls_ec_adapter.h" #include "string_util.h" -#define BASE_IMPORT_PARAMS_LEN 7 -#define EXT_IMPORT_PARAMS_LEN 2 #define ECDH_COMMON_SIZE_P256 512 -#define BASE_HMAC_PARAMS_LEN 3 -#define BASE_HMAC_DERIVE_PARAMS_LEN 5 -#define BASE_HMAC_FINISH_PARAMS_LEN 3 -#define BASE_AGREE_WITH_STORAGE_PARAMS_LEN 9 -#define BASE_HKDF_PARAMS_LEN 6 -#define BASE_COMPUTE_PSEUDONYM_PSK_PARAMS_LEN 11 -#define BASE_SIGN_PARAMS_LEN 3 -#define BASE_ENCRYPT_PARAMS_LEN 7 -#define BASE_DECRYPT_PARAMS_LEN 7 -#define BASE_AGREE_INIT_PARAMS_LEN 3 -#define BASE_AGREE_FINISH_PARAMS_LEN 7 -#define BASE_AGREE_PARAMS_LEN 3 -#define BASE_GENERATE_KEY_PAIR_PARAMS_LEN 6 -#define BASE_VERIFY_PARAMS_LEN 4 -#define BASE_IMPORT_PUB_KEY_PARAMS_LEN 8 -#define EXT_DE_PARAMS_LEN 1 -#define EXT_CE_PARAMS_LEN 2 -#define PSEUDONYM_KEY_FACTOR "hichain_pseudonym_psk_key" -#define PSEUDONYM_KEY_LEBEL "hichain_pseudonym_psk_label" - -static uint32_t g_purposeToHksKeyPurpose[] = { - HKS_KEY_PURPOSE_MAC, - HKS_KEY_PURPOSE_DERIVE, - HKS_KEY_PURPOSE_SIGN | HKS_KEY_PURPOSE_VERIFY, - HKS_KEY_PURPOSE_AGREE -}; static enum HksKeyAlg g_algToHksAlgorithm[] = { HKS_ALG_ED25519, HKS_ALG_X25519, - HKS_ALG_ECC + HKS_ALG_ECC, + HKS_ALG_AES, }; -static int32_t CheckKeyParams(const KeyParams *keyParams) -{ - CHECK_PTR_RETURN_HAL_ERROR_CODE(keyParams, "keyParams"); - CHECK_PTR_RETURN_HAL_ERROR_CODE(keyParams->keyBuff.key, "keyParams->keyBuff.key"); - CHECK_LEN_ZERO_RETURN_ERROR_CODE(keyParams->keyBuff.keyLen, "keyParams->keyBuff.keyLen"); - return HAL_SUCCESS; -} - -static int32_t BaseCheckParams(const Uint8Buff **inParams, const char **paramTags, uint32_t len) -{ - for (uint32_t i = 0; i < len; i++) { - CHECK_PTR_RETURN_HAL_ERROR_CODE(inParams[i], paramTags[i]); - CHECK_PTR_RETURN_HAL_ERROR_CODE(inParams[i]->val, paramTags[i]); - CHECK_LEN_ZERO_RETURN_ERROR_CODE(inParams[i]->length, paramTags[i]); - } - return HAL_SUCCESS; -} - -static void FreeParamSet(struct HksParamSet *paramSet) -{ - if (paramSet == NULL) { - return; - } - HksFreeParamSet(¶mSet); -} - -static int32_t ConstructParamSet(struct HksParamSet **out, const struct HksParam *inParam, - const uint32_t inParamNum) -{ - struct HksParamSet *paramSet = NULL; - int32_t res = HksInitParamSet(¶mSet); - if (res != HKS_SUCCESS) { - LOGE("init param set failed, res = %d", res); - return HAL_ERR_INIT_PARAM_SET_FAILED; - } - - res = HksAddParams(paramSet, inParam, inParamNum); - if (res != HKS_SUCCESS) { - LOGE("add param failed, res = %d", res); - FreeParamSet(paramSet); - return HAL_ERR_ADD_PARAM_FAILED; - } - - res = HksBuildParamSet(¶mSet); - if (res != HKS_SUCCESS) { - LOGE("build param set failed, res = %d", res); - FreeParamSet(paramSet); - return HAL_ERR_BUILD_PARAM_SET_FAILED; - } - - *out = paramSet; - return HAL_SUCCESS; -} - static int32_t Sha256(const Uint8Buff *message, Uint8Buff *hash) { CHECK_PTR_RETURN_HAL_ERROR_CODE(message, "message"); @@ -141,7 +59,7 @@ static int32_t Sha256(const Uint8Buff *message, Uint8Buff *hash) if (res != HKS_SUCCESS || hashBlob.size != SHA256_LEN) { LOGE("[HUKS]: HksHash fail. [Res]: %d", res); FreeParamSet(paramSet); - return HAL_FAILED; + return HAL_ERR_HUKS; } FreeParamSet(paramSet); @@ -164,128 +82,6 @@ static int32_t GenerateRandom(Uint8Buff *rand) return HAL_SUCCESS; } -static uint32_t GetParamLen(bool isDeStorage, uint32_t baseLen) -{ -#ifdef DEV_AUTH_ENABLE_CE - if (isDeStorage) { - return baseLen + EXT_DE_PARAMS_LEN; - } else { - return baseLen + EXT_CE_PARAMS_LEN; - } -#else - (void)isDeStorage; - return baseLen; -#endif -} - -static void AddStorageExtParams(struct HksParam *params, bool isDeStorage, uint32_t *idx, int32_t osAccountId) -{ -#ifdef DEV_AUTH_ENABLE_CE - if (isDeStorage) { - params[*idx].tag = HKS_TAG_AUTH_STORAGE_LEVEL; - params[(*idx)++].uint32Param = HKS_AUTH_STORAGE_LEVEL_DE; - } else { - params[*idx].tag = HKS_TAG_AUTH_STORAGE_LEVEL; - params[(*idx)++].uint32Param = HKS_AUTH_STORAGE_LEVEL_CE; - params[*idx].tag = HKS_TAG_SPECIFIC_USER_ID; - params[(*idx)++].uint32Param = osAccountId; - } -#else - (void)params; - (void)isDeStorage; - (void)idx; - (void)osAccountId; -#endif -} - -static int32_t ConstructDeParamSet(struct HksParamSet **paramSet) -{ - struct HksParam keyParam[] = { - { - .tag = HKS_TAG_AUTH_STORAGE_LEVEL, - .uint32Param = HKS_AUTH_STORAGE_LEVEL_DE - } - }; - - int32_t res = ConstructParamSet(paramSet, keyParam, CAL_ARRAY_SIZE(keyParam)); - if (res != HAL_SUCCESS) { - LOGE("Construct de param set failed, res = %d", res); - } - return res; -} - -static int32_t ConstructCeParamSet(int32_t osAccountId, struct HksParamSet **paramSet) -{ - struct HksParam keyParam[] = { - { - .tag = HKS_TAG_AUTH_STORAGE_LEVEL, - .uint32Param = HKS_AUTH_STORAGE_LEVEL_CE - }, { - .tag = HKS_TAG_SPECIFIC_USER_ID, - .uint32Param = osAccountId - } - }; - - int32_t res = ConstructParamSet(paramSet, keyParam, CAL_ARRAY_SIZE(keyParam)); - if (res != HAL_SUCCESS) { - LOGE("Construct ce param set failed, res = %d", res); - } - return res; -} - -static int32_t ChangeStorageLevel(const struct HksBlob *keyAliasBlob, const struct HksParamSet *deParamSet, - const struct HksParamSet *ceParamSet) -{ -#ifdef DEV_AUTH_ENABLE_CE - return HksChangeStorageLevel(keyAliasBlob, deParamSet, ceParamSet); -#else - (void)keyAliasBlob; - (void)deParamSet; - (void)ceParamSet; - return HKS_SUCCESS; -#endif -} - -static void MoveDeKeyToCe(bool isKeyAlias, int32_t osAccountId, const struct HksBlob *keyAliasBlob) -{ - if (!isKeyAlias) { - return; - } - struct HksParamSet *deParamSet = NULL; - if (ConstructDeParamSet(&deParamSet) != HAL_SUCCESS) { - return; - } - struct HksParamSet *ceParamSet = NULL; - if (ConstructCeParamSet(osAccountId, &ceParamSet) != HAL_SUCCESS) { - return; - } - int32_t res = ChangeStorageLevel(keyAliasBlob, deParamSet, ceParamSet); - if (res != HKS_SUCCESS) { - LOGE("Failed to move de key to ce!"); - } -} - -static int32_t ConstructCheckParamSet(bool isDeStorage, int32_t osAccountId, struct HksParamSet **paramSet) -{ - uint32_t len = GetParamLen(isDeStorage, 0); - if (len == 0) { - return HAL_SUCCESS; - } - struct HksParam *checkParams = (struct HksParam *)HcMalloc(sizeof(struct HksParam) * len, 0); - if (checkParams == NULL) { - LOGE("Malloc for checkParams failed."); - return HAL_ERR_BAD_ALLOC; - } - uint32_t idx = 0; - AddStorageExtParams(checkParams, isDeStorage, &idx, osAccountId); - int32_t res = ConstructParamSet(paramSet, checkParams, idx); - HcFree(checkParams); - if (res != HAL_SUCCESS) { - LOGE("Failed to construct check param set, res: %d", res); - } - return res; -} - static int32_t CheckKeyExist(const Uint8Buff *keyAlias, bool isDeStorage, int32_t osAccountId) { CHECK_PTR_RETURN_HAL_ERROR_CODE(keyAlias, "keyAlias"); @@ -319,35 +115,19 @@ static int32_t CheckKeyExist(const Uint8Buff *keyAlias, bool isDeStorage, int32_ } FreeParamSet(deParamSet); FreeParamSet(ceParamSet); + + if (res == HKS_ERROR_NOT_EXIST) { + LOGE("[HUKS]: Key not exist. [Res]: %d", res); + return HAL_ERR_KEY_NOT_EXIST; + } if (res != HKS_SUCCESS) { - LOGI("[HUKS]: HksKeyExist fail. [Res]: %d", res); - return HAL_FAILED; + LOGE("[HUKS]: HksKeyExist fail. [Res]: %d", res); + return HAL_ERR_HUKS; } return HAL_SUCCESS; } -static int32_t ConstructDeleteParamSet(bool isDeStorage, int32_t osAccountId, struct HksParamSet **paramSet) -{ - uint32_t len = GetParamLen(isDeStorage, 0); - if (len == 0) { - return HAL_SUCCESS; - } - struct HksParam *deleteParams = (struct HksParam *)HcMalloc(sizeof(struct HksParam) * len, 0); - if (deleteParams == NULL) { - LOGE("Malloc for deleteParams failed."); - return HAL_ERR_BAD_ALLOC; - } - uint32_t idx = 0; - AddStorageExtParams(deleteParams, isDeStorage, &idx, osAccountId); - int32_t res = ConstructParamSet(paramSet, deleteParams, idx); - HcFree(deleteParams); - if (res != HAL_SUCCESS) { - LOGE("Failed to construct delete param set, res: %d", res); - } - return res; -} - static int32_t DeleteKey(const Uint8Buff *keyAlias, bool isDeStorage, int32_t osAccountId) { CHECK_PTR_RETURN_HAL_ERROR_CODE(keyAlias, "keyAlias"); @@ -389,49 +169,8 @@ static int32_t DeleteKey(const Uint8Buff *keyAlias, bool isDeStorage, int32_t os } if (res != HKS_SUCCESS) { LOGE("[HUKS]: HksDeleteKey fail. [Res]: %d", res); - return HAL_FAILED; - } - return HAL_SUCCESS; -} - -static int32_t ConstructHmacParamSet(bool isDeStorage, int32_t osAccountId, bool isAlias, - struct HksParamSet **hmacParamSet) -{ - uint32_t len = GetParamLen(isDeStorage, BASE_HMAC_PARAMS_LEN); - struct HksParam *hmacParams = (struct HksParam *)HcMalloc(sizeof(struct HksParam) * len, 0); - if (hmacParams == NULL) { - LOGE("Malloc for hmacParams failed."); - return HAL_ERR_BAD_ALLOC; + return HAL_ERR_HUKS; } - uint32_t idx = 0; - hmacParams[idx].tag = HKS_TAG_PURPOSE; - hmacParams[idx++].uint32Param = HKS_KEY_PURPOSE_MAC; - hmacParams[idx].tag = HKS_TAG_DIGEST; - hmacParams[idx++].uint32Param = HKS_DIGEST_SHA256; - hmacParams[idx].tag = HKS_TAG_IS_KEY_ALIAS; - hmacParams[idx++].boolParam = isAlias; - AddStorageExtParams(hmacParams, isDeStorage, &idx, osAccountId); - int32_t res = ConstructParamSet(hmacParamSet, hmacParams, idx); - HcFree(hmacParams); - if (res != HAL_SUCCESS) { - LOGE("Construct hmac param set failed, res = %d", res); - } - return res; -} - -static int32_t CheckHmacParams(const KeyParams *keyParams, const Uint8Buff *message, const Uint8Buff *outHmac) -{ - int32_t res = CheckKeyParams(keyParams); - if (res != HAL_SUCCESS) { - return res; - } - const Uint8Buff *inParams[] = { message, outHmac }; - const char *paramTags[] = { "message", "outHmac" }; - res = BaseCheckParams(inParams, paramTags, CAL_ARRAY_SIZE(inParams)); - if (res != HAL_SUCCESS) { - return res; - } - CHECK_LEN_EQUAL_RETURN(outHmac->length, HMAC_LEN, "outHmac->length"); return HAL_SUCCESS; } @@ -476,77 +215,6 @@ static int32_t ComputeHmac(const KeyParams *keyParams, const Uint8Buff *message, return HAL_SUCCESS; } -static int32_t ConstructDeriveParamSet(const KeyParams *keyParams, const Uint8Buff *message, - struct HksParamSet **deriveParamSet) -{ - struct HksBlob srcBlob = { message->length, message->val }; - uint32_t len = GetParamLen(keyParams->isDeStorage, BASE_HMAC_DERIVE_PARAMS_LEN); - struct HksParam *hmacDeriveParams = (struct HksParam *)HcMalloc(sizeof(struct HksParam) * len, 0); - if (hmacDeriveParams == NULL) { - LOGE("Malloc for hmacDeriveParams failed."); - return HAL_ERR_BAD_ALLOC; - } - uint32_t idx = 0; - hmacDeriveParams[idx].tag = HKS_TAG_ALGORITHM; - hmacDeriveParams[idx++].uint32Param = HKS_ALG_HMAC; - hmacDeriveParams[idx].tag = HKS_TAG_PURPOSE; - hmacDeriveParams[idx++].uint32Param = HKS_KEY_PURPOSE_DERIVE; - hmacDeriveParams[idx].tag = HKS_TAG_DIGEST; - hmacDeriveParams[idx++].uint32Param = HKS_DIGEST_SHA256; - hmacDeriveParams[idx].tag = HKS_TAG_DERIVE_KEY_SIZE; - hmacDeriveParams[idx++].uint32Param = HMAC_LEN; - hmacDeriveParams[idx].tag = HKS_TAG_INFO; - hmacDeriveParams[idx++].blob = srcBlob; - AddStorageExtParams(hmacDeriveParams, keyParams->isDeStorage, &idx, keyParams->osAccountId); - int32_t res = ConstructParamSet(deriveParamSet, hmacDeriveParams, idx); - HcFree(hmacDeriveParams); - if (res != HAL_SUCCESS) { - LOGE("Construct derive param set failed, res = %d", res); - } - return res; -} - -static int32_t ConstructFinishParamSet(const KeyParams *keyParams, struct HksParamSet **finishParamSet) -{ - uint32_t len = GetParamLen(keyParams->isDeStorage, BASE_HMAC_FINISH_PARAMS_LEN); - struct HksParam *hmacFinishParams = (struct HksParam *)HcMalloc(sizeof(struct HksParam) * len, 0); - if (hmacFinishParams == NULL) { - LOGE("Malloc for hmacFinishParams failed."); - return HAL_ERR_BAD_ALLOC; - } - uint32_t idx = 0; - hmacFinishParams[idx].tag = HKS_TAG_ALGORITHM; - hmacFinishParams[idx++].uint32Param = HKS_ALG_AES; - hmacFinishParams[idx].tag = HKS_TAG_KEY_SIZE; - hmacFinishParams[idx++].uint32Param = HKS_AES_KEY_SIZE_256; - hmacFinishParams[idx].tag = HKS_TAG_PURPOSE; - hmacFinishParams[idx++].uint32Param = HKS_KEY_PURPOSE_ENCRYPT | HKS_KEY_PURPOSE_DECRYPT; - AddStorageExtParams(hmacFinishParams, keyParams->isDeStorage, &idx, keyParams->osAccountId); - int32_t res = ConstructParamSet(finishParamSet, hmacFinishParams, idx); - HcFree(hmacFinishParams); - if (res != HAL_SUCCESS) { - LOGE("Construct finish param set failed, res = %d", res); - } - return res; -} - -static int32_t CheckHmacWithThreeStageParams(const KeyParams *keyParams, const Uint8Buff *message, - const Uint8Buff *outHmac) -{ - int32_t res = CheckKeyParams(keyParams); - if (res != HAL_SUCCESS) { - return res; - } - const Uint8Buff *inParams[] = { message, outHmac }; - const char *paramTags[] = { "message", "outHmac" }; - res = BaseCheckParams(inParams, paramTags, CAL_ARRAY_SIZE(inParams)); - if (res != HAL_SUCCESS) { - return res; - } - CHECK_LEN_EQUAL_RETURN(outHmac->length, HMAC_LEN, "outHmac->length"); - return HAL_SUCCESS; -} - static int32_t ComputeHmacWithThreeStageInner(const KeyParams *keyParams, const Uint8Buff *message, Uint8Buff *outHmac) { struct HksParamSet *deriveParamSet = NULL; @@ -616,54 +284,6 @@ static int32_t ComputeHmacWithThreeStage(const KeyParams *keyParams, const Uint8 return res; } -static int32_t ConstructHkdfParamSet(bool isDeStorage, const KeyParams *keyParams, const Uint8Buff *salt, - const Uint8Buff *keyInfo, struct HksParamSet **paramSet) -{ - struct HksBlob saltBlob = { salt->length, salt->val }; - struct HksBlob keyInfoBlob = { 0, NULL }; - if (keyInfo != NULL) { - keyInfoBlob.size = keyInfo->length; - keyInfoBlob.data = keyInfo->val; - } - uint32_t len = GetParamLen(isDeStorage, BASE_HKDF_PARAMS_LEN); - struct HksParam *hkdfParams = (struct HksParam *)HcMalloc(sizeof(struct HksParam) * len, 0); - if (hkdfParams == NULL) { - LOGE("Malloc for hkdfParams failed."); - return HAL_ERR_BAD_ALLOC; - } - uint32_t idx = 0; - hkdfParams[idx].tag = HKS_TAG_PURPOSE; - hkdfParams[idx++].uint32Param = HKS_KEY_PURPOSE_DERIVE; - hkdfParams[idx].tag = HKS_TAG_ALGORITHM; - hkdfParams[idx++].uint32Param = HKS_ALG_HKDF; - hkdfParams[idx].tag = HKS_TAG_DIGEST; - hkdfParams[idx++].uint32Param = HKS_DIGEST_SHA256; - hkdfParams[idx].tag = HKS_TAG_SALT; - hkdfParams[idx++].blob = saltBlob; - hkdfParams[idx].tag = HKS_TAG_INFO; - hkdfParams[idx++].blob = keyInfoBlob; - hkdfParams[idx].tag = HKS_TAG_IS_KEY_ALIAS; - hkdfParams[idx++].boolParam = keyParams->keyBuff.isAlias; - AddStorageExtParams(hkdfParams, isDeStorage, &idx, keyParams->osAccountId); - int32_t res = ConstructParamSet(paramSet, hkdfParams, idx); - HcFree(hkdfParams); - if (res != HAL_SUCCESS) { - LOGE("Failed to construct hkdf param set, res: %d", res); - } - return res; -} - -static int32_t CheckHkdfParams(const KeyParams *keyParams, const Uint8Buff *salt, const Uint8Buff *outHkdf) -{ - int32_t res = CheckKeyParams(keyParams); - if (res != HAL_SUCCESS) { - return res; - } - const Uint8Buff *inParams[] = { salt, outHkdf }; - const char *paramTags[] = { "salt", "outHkdf" }; - return BaseCheckParams(inParams, paramTags, CAL_ARRAY_SIZE(inParams)); -} - static int32_t ComputeHkdf(const KeyParams *keyParams, const Uint8Buff *salt, const Uint8Buff *keyInfo, Uint8Buff *outHkdf) { @@ -711,58 +331,6 @@ static int32_t ComputeHkdf(const KeyParams *keyParams, const Uint8Buff *salt, co return HAL_SUCCESS; } -static int32_t ConstructPseudonymParamSet(const KeyParams *keyParams, const Uint8Buff *pskKeyAlias, - const struct HksBlob *extInfoBlob, uint32_t outLen, struct HksParamSet **paramSet) -{ - struct HksBlob saltBlob = { HcStrlen(PSEUDONYM_KEY_FACTOR), (uint8_t *)PSEUDONYM_KEY_FACTOR }; - struct HksBlob keyInfoBlob = { HcStrlen(PSEUDONYM_KEY_LEBEL), (uint8_t *)PSEUDONYM_KEY_LEBEL }; - struct HksBlob pskAliasBlob = { pskKeyAlias->length, pskKeyAlias->val }; - uint32_t len = GetParamLen(keyParams->isDeStorage, BASE_COMPUTE_PSEUDONYM_PSK_PARAMS_LEN); - struct HksParam *hkdfParams = (struct HksParam *)HcMalloc(sizeof(struct HksParam) * len, 0); - if (hkdfParams == NULL) { - LOGE("Malloc for hkdfParams failed."); - return HAL_ERR_BAD_ALLOC; - } - uint32_t idx = 0; - hkdfParams[idx].tag = HKS_TAG_PURPOSE; - hkdfParams[idx++].uint32Param = HKS_KEY_PURPOSE_DERIVE; - hkdfParams[idx].tag = HKS_TAG_ALGORITHM; - hkdfParams[idx++].uint32Param = HKS_ALG_HKDF; - hkdfParams[idx].tag = HKS_TAG_DIGEST; - hkdfParams[idx++].uint32Param = HKS_DIGEST_SHA256; - hkdfParams[idx].tag = HKS_TAG_SALT; - hkdfParams[idx++].blob = saltBlob; - hkdfParams[idx].tag = HKS_TAG_INFO; - hkdfParams[idx++].blob = keyInfoBlob; - hkdfParams[idx].tag = HKS_TAG_IS_KEY_ALIAS; - hkdfParams[idx++].boolParam = true; - hkdfParams[idx].tag = HKS_TAG_KEY_STORAGE_FLAG; - hkdfParams[idx++].uint32Param = HKS_STORAGE_ONLY_USED_IN_HUKS; - hkdfParams[idx].tag = HKS_TAG_DERIVE_AGREE_KEY_STORAGE_FLAG; - hkdfParams[idx++].uint32Param = HKS_STORAGE_ONLY_USED_IN_HUKS; - hkdfParams[idx].tag = HKS_TAG_KEY_SIZE; - hkdfParams[idx++].uint32Param = outLen * BITS_PER_BYTE; - hkdfParams[idx].tag = HKS_TAG_KEY_ALIAS; - hkdfParams[idx++].blob = pskAliasBlob; - hkdfParams[idx].tag = HKS_TAG_EXT_INFO; - hkdfParams[idx++].blob = *extInfoBlob; - AddStorageExtParams(hkdfParams, keyParams->isDeStorage, &idx, keyParams->osAccountId); - int32_t res = ConstructParamSet(paramSet, hkdfParams, idx); - HcFree(hkdfParams); - return res; -} - -static int32_t CheckPskParams(const KeyParams *keyParams, const Uint8Buff *pskKeyAlias, const Uint8Buff *outPsk) -{ - int32_t res = CheckKeyParams(keyParams); - if (res != HAL_SUCCESS) { - return res; - } - const Uint8Buff *inParams[] = { pskKeyAlias, outPsk }; - const char *paramTags[] = { "pskKeyAlias", "outPsk" }; - return BaseCheckParams(inParams, paramTags, CAL_ARRAY_SIZE(inParams)); -} - static int32_t ComputePseudonymPskInner(const KeyParams *keyParams, const Uint8Buff *pskKeyAlias, const Uint8Buff *extInfo, Uint8Buff *outPsk) { @@ -856,54 +424,6 @@ static int32_t ConstructOutParamSet(struct HksParamSet **outParamSet) return HAL_SUCCESS; } -static int32_t GetExtInfoByParamSet(const struct HksParamSet *outParamSet, Uint8Buff *outExtInfo) -{ - struct HksParam *extInfoParam = NULL; - int32_t res = HksGetParam(outParamSet, HKS_TAG_EXT_INFO, &extInfoParam); - if (res != HKS_SUCCESS) { - LOGE("Failed to get extInfoParam!"); - return HAL_FAILED; - } - if (extInfoParam->blob.data == NULL || extInfoParam->blob.size == 0) { - LOGE("Extra info blob is null!"); - return HAL_FAILED; - } - uint8_t *tmpExtInfoVal = (uint8_t *)HcMalloc(extInfoParam->blob.size, 0); - if (tmpExtInfoVal == NULL) { - LOGE("Failed to alloc memory for extInfo value!"); - return HAL_ERR_BAD_ALLOC; - } - if (memcpy_s(tmpExtInfoVal, extInfoParam->blob.size, extInfoParam->blob.data, extInfoParam->blob.size) != EOK) { - LOGE("Failed to copy extInfo!"); - HcFree(tmpExtInfoVal); - return HAL_ERR_MEMORY_COPY; - } - outExtInfo->val = tmpExtInfoVal; - outExtInfo->length = extInfoParam->blob.size; - return HAL_SUCCESS; -} - -static int32_t ConstructGetKeyExtInfoParamSet(const KeyParams *keyParams, struct HksParamSet **paramSet) -{ - uint32_t len = GetParamLen(keyParams->isDeStorage, 0); - if (len == 0) { - return HAL_SUCCESS; - } - struct HksParam *getParams = (struct HksParam *)HcMalloc(sizeof(struct HksParam) * len, 0); - if (getParams == NULL) { - LOGE("Malloc for getParams failed."); - return HAL_ERR_BAD_ALLOC; - } - uint32_t idx = 0; - AddStorageExtParams(getParams, keyParams->isDeStorage, &idx, keyParams->osAccountId); - int32_t res = ConstructParamSet(paramSet, getParams, idx); - HcFree(getParams); - if (res != HAL_SUCCESS) { - LOGE("Failed to construct get param set, res: %d", res); - } - return res; -} - static int32_t GetKeyExtInfoInner(const KeyParams *keyParams, Uint8Buff *outExtInfo) { struct HksParamSet *paramSet = NULL; @@ -959,65 +479,6 @@ static int32_t GetKeyExtInfo(const KeyParams *keyParams, Uint8Buff *outExtInfo) return res; } -static int32_t CheckAesGcmEncryptParam(const KeyParams *keyParams, const Uint8Buff *plain, - const GcmParam *encryptInfo, Uint8Buff *outCipher) -{ - int32_t res = CheckKeyParams(keyParams); - if (res != HAL_SUCCESS) { - return res; - } - const Uint8Buff *inParams[] = { plain, outCipher }; - const char* paramTags[] = { "plain", "outCipher" }; - res = BaseCheckParams(inParams, paramTags, CAL_ARRAY_SIZE(inParams)); - if (res != HAL_SUCCESS) { - return res; - } - - CHECK_PTR_RETURN_HAL_ERROR_CODE(encryptInfo, "encryptInfo"); - CHECK_PTR_RETURN_HAL_ERROR_CODE(encryptInfo->aad, "aad"); - CHECK_LEN_ZERO_RETURN_ERROR_CODE(encryptInfo->aadLen, "aadLen"); - CHECK_PTR_RETURN_HAL_ERROR_CODE(encryptInfo->nonce, "nonce"); - CHECK_LEN_LOWER_RETURN(encryptInfo->nonceLen, HKS_AE_NONCE_LEN, "nonceLen"); - CHECK_LEN_LOWER_RETURN(outCipher->length, plain->length + HKS_AE_TAG_LEN, "outCipher"); - - return HAL_SUCCESS; -} - -static int32_t ConstructAesGcmEncryptParamSet(const GcmParam *encryptInfo, const KeyParams *keyParams, - struct HksParamSet **paramSet) -{ - struct HksBlob nonceBlob = { encryptInfo->nonceLen, encryptInfo->nonce }; - struct HksBlob aadBlob = { encryptInfo->aadLen, encryptInfo->aad }; - uint32_t len = GetParamLen(keyParams->isDeStorage, BASE_ENCRYPT_PARAMS_LEN); - struct HksParam *encryptParams = (struct HksParam *)HcMalloc(sizeof(struct HksParam) * len, 0); - if (encryptParams == NULL) { - LOGE("Malloc for encryptParams failed."); - return HAL_ERR_BAD_ALLOC; - } - uint32_t idx = 0; - encryptParams[idx].tag = HKS_TAG_PURPOSE; - encryptParams[idx++].uint32Param = HKS_KEY_PURPOSE_ENCRYPT; - encryptParams[idx].tag = HKS_TAG_ALGORITHM; - encryptParams[idx++].uint32Param = HKS_ALG_AES; - encryptParams[idx].tag = HKS_TAG_BLOCK_MODE; - encryptParams[idx++].uint32Param = HKS_MODE_GCM; - encryptParams[idx].tag = HKS_TAG_PADDING; - encryptParams[idx++].uint32Param = HKS_PADDING_NONE; - encryptParams[idx].tag = HKS_TAG_NONCE; - encryptParams[idx++].blob = nonceBlob; - encryptParams[idx].tag = HKS_TAG_ASSOCIATED_DATA; - encryptParams[idx++].blob = aadBlob; - encryptParams[idx].tag = HKS_TAG_IS_KEY_ALIAS; - encryptParams[idx++].boolParam = keyParams->keyBuff.isAlias; - AddStorageExtParams(encryptParams, keyParams->isDeStorage, &idx, keyParams->osAccountId); - int32_t res = ConstructParamSet(paramSet, encryptParams, idx); - HcFree(encryptParams); - if (res != HAL_SUCCESS) { - LOGE("Failed to construct encrypt param set, res: %d", res); - } - return res; -} - static int32_t AesGcmEncrypt(const KeyParams *keyParams, const Uint8Buff *plain, const GcmParam *encryptInfo, Uint8Buff *outCipher) { @@ -1047,65 +508,6 @@ static int32_t AesGcmEncrypt(const KeyParams *keyParams, const Uint8Buff *plain, return HAL_SUCCESS; } -static int32_t CheckAesGcmDecryptParam(const KeyParams *keyParams, const Uint8Buff *cipher, - const GcmParam *decryptInfo, Uint8Buff *outPlain) -{ - int32_t res = CheckKeyParams(keyParams); - if (res != HAL_SUCCESS) { - return res; - } - const Uint8Buff *inParams[] = { cipher, outPlain }; - const char *paramTags[] = { "cipher", "outPlain" }; - res = BaseCheckParams(inParams, paramTags, CAL_ARRAY_SIZE(inParams)); - if (res != HAL_SUCCESS) { - return res; - } - - CHECK_PTR_RETURN_HAL_ERROR_CODE(decryptInfo, "decryptInfo"); - CHECK_PTR_RETURN_HAL_ERROR_CODE(decryptInfo->aad, "aad"); - CHECK_LEN_ZERO_RETURN_ERROR_CODE(decryptInfo->aadLen, "aadLen"); - CHECK_PTR_RETURN_HAL_ERROR_CODE(decryptInfo->nonce, "nonce"); - CHECK_LEN_LOWER_RETURN(decryptInfo->nonceLen, HKS_AE_NONCE_LEN, "nonceLen"); - CHECK_LEN_LOWER_RETURN(outPlain->length, cipher->length - HKS_AE_TAG_LEN, "outPlain"); - - return HAL_SUCCESS; -} - -static int32_t ConstructAesGcmDecryptParamSet(const GcmParam *decryptInfo, const KeyParams *keyParams, - struct HksParamSet **paramSet) -{ - struct HksBlob nonceBlob = { decryptInfo->nonceLen, decryptInfo->nonce }; - struct HksBlob aadBlob = { decryptInfo->aadLen, decryptInfo->aad }; - uint32_t len = GetParamLen(keyParams->isDeStorage, BASE_DECRYPT_PARAMS_LEN); - struct HksParam *decryptParams = (struct HksParam *)HcMalloc(sizeof(struct HksParam) * len, 0); - if (decryptParams == NULL) { - LOGE("Malloc for decryptParams failed."); - return HAL_ERR_BAD_ALLOC; - } - uint32_t idx = 0; - decryptParams[idx].tag = HKS_TAG_PURPOSE; - decryptParams[idx++].uint32Param = HKS_KEY_PURPOSE_DECRYPT; - decryptParams[idx].tag = HKS_TAG_ALGORITHM; - decryptParams[idx++].uint32Param = HKS_ALG_AES; - decryptParams[idx].tag = HKS_TAG_BLOCK_MODE; - decryptParams[idx++].uint32Param = HKS_MODE_GCM; - decryptParams[idx].tag = HKS_TAG_PADDING; - decryptParams[idx++].uint32Param = HKS_PADDING_NONE; - decryptParams[idx].tag = HKS_TAG_NONCE; - decryptParams[idx++].blob = nonceBlob; - decryptParams[idx].tag = HKS_TAG_ASSOCIATED_DATA; - decryptParams[idx++].blob = aadBlob; - decryptParams[idx].tag = HKS_TAG_IS_KEY_ALIAS; - decryptParams[idx++].boolParam = keyParams->keyBuff.isAlias; - AddStorageExtParams(decryptParams, keyParams->isDeStorage, &idx, keyParams->osAccountId); - int32_t res = ConstructParamSet(paramSet, decryptParams, idx); - HcFree(decryptParams); - if (res != HAL_SUCCESS) { - LOGE("Failed to construct decrypt param set, res: %d", res); - } - return res; -} - static int32_t AesGcmDecrypt(const KeyParams *keyParams, const Uint8Buff *cipher, const GcmParam *decryptInfo, Uint8Buff *outPlain) { @@ -1156,63 +558,6 @@ static int32_t HashToPoint(const Uint8Buff *hash, Algorithm algo, Uint8Buff *out return HashToPointX25519(hash, outEcPoint); } -static int32_t ConstructInitParamsP256(struct HksParamSet **initParamSet, const KeyParams *keyParams) -{ - uint32_t len = GetParamLen(keyParams->isDeStorage, BASE_AGREE_INIT_PARAMS_LEN); - struct HksParam *initParams = (struct HksParam *)HcMalloc(sizeof(struct HksParam) * len, 0); - if (initParams == NULL) { - LOGE("Malloc for initParams failed."); - return HAL_ERR_BAD_ALLOC; - } - uint32_t idx = 0; - initParams[idx].tag = HKS_TAG_ALGORITHM; - initParams[idx++].uint32Param = HKS_ALG_ECDH; - initParams[idx].tag = HKS_TAG_PURPOSE; - initParams[idx++].uint32Param = HKS_KEY_PURPOSE_AGREE; - initParams[idx].tag = HKS_TAG_KEY_SIZE; - initParams[idx++].uint32Param = HKS_ECC_KEY_SIZE_256; - AddStorageExtParams(initParams, keyParams->isDeStorage, &idx, keyParams->osAccountId); - int32_t res = ConstructParamSet(initParamSet, initParams, idx); - HcFree(initParams); - if (res != HAL_SUCCESS) { - LOGE("Construct init param set failed, res = %d", res); - } - return res; -} - -static int32_t ConstructFinishParamsP256(struct HksParamSet **finishParamSet, const KeyParams *keyParams, - const struct HksBlob *sharedKeyAliasBlob) -{ - uint32_t len = GetParamLen(keyParams->isDeStorage, BASE_AGREE_FINISH_PARAMS_LEN); - struct HksParam *finishParams = (struct HksParam *)HcMalloc(sizeof(struct HksParam) * len, 0); - if (finishParams == NULL) { - LOGE("Malloc for finishParams failed."); - return HAL_ERR_BAD_ALLOC; - } - uint32_t idx = 0; - finishParams[idx].tag = HKS_TAG_KEY_STORAGE_FLAG; - finishParams[idx++].uint32Param = HKS_STORAGE_PERSISTENT; - finishParams[idx].tag = HKS_TAG_IS_KEY_ALIAS; - finishParams[idx++].boolParam = true; - finishParams[idx].tag = HKS_TAG_ALGORITHM; - finishParams[idx++].uint32Param = HKS_ALG_AES; - finishParams[idx].tag = HKS_TAG_KEY_SIZE; - finishParams[idx++].uint32Param = HKS_AES_KEY_SIZE_256; - finishParams[idx].tag = HKS_TAG_PURPOSE; - finishParams[idx++].uint32Param = HKS_KEY_PURPOSE_DERIVE; - finishParams[idx].tag = HKS_TAG_DIGEST; - finishParams[idx++].uint32Param = HKS_DIGEST_SHA256; - finishParams[idx].tag = HKS_TAG_KEY_ALIAS; - finishParams[idx++].blob = *sharedKeyAliasBlob; - AddStorageExtParams(finishParams, keyParams->isDeStorage, &idx, keyParams->osAccountId); - int32_t res = ConstructParamSet(finishParamSet, finishParams, idx); - HcFree(finishParams); - if (res != HAL_SUCCESS) { - LOGE("Construct finish param set failed, res = %d", res); - } - return res; -} - static int32_t AgreeSharedSecretWithStorageP256(const KeyParams *priKeyParams, const KeyBuff *pubKeyBuff, const struct HksBlob *sharedKeyAliasBlob) { @@ -1262,69 +607,6 @@ static int32_t AgreeSharedSecretWithStorageP256(const KeyParams *priKeyParams, c return res; } -static int32_t ConstructAgreeWithStorageParams(struct HksParamSet **paramSet, uint32_t keyLen, Algorithm algo, - const KeyParams *priKeyParams, const KeyBuff *pubKeyBuff) -{ - struct HksBlob priKeyBlob = { priKeyParams->keyBuff.keyLen, priKeyParams->keyBuff.key }; - struct HksBlob pubKeyBlob = { pubKeyBuff->keyLen, pubKeyBuff->key }; - uint32_t len = GetParamLen(priKeyParams->isDeStorage, BASE_AGREE_WITH_STORAGE_PARAMS_LEN); - struct HksParam *agreeParams = (struct HksParam *)HcMalloc(sizeof(struct HksParam) * len, 0); - if (agreeParams == NULL) { - LOGE("Malloc for agreeParams failed."); - return HAL_ERR_BAD_ALLOC; - } - uint32_t idx = 0; - agreeParams[idx].tag = HKS_TAG_ALGORITHM; - agreeParams[idx++].uint32Param = HKS_ALG_AES; - agreeParams[idx].tag = HKS_TAG_KEY_SIZE; - agreeParams[idx++].uint32Param = keyLen * BITS_PER_BYTE; - agreeParams[idx].tag = HKS_TAG_PURPOSE; - agreeParams[idx++].uint32Param = HKS_KEY_PURPOSE_DERIVE; - agreeParams[idx].tag = HKS_TAG_DIGEST; - agreeParams[idx++].uint32Param = HKS_DIGEST_SHA256; - agreeParams[idx].tag = HKS_TAG_KEY_GENERATE_TYPE; - agreeParams[idx++].uint32Param = HKS_KEY_GENERATE_TYPE_AGREE; - agreeParams[idx].tag = HKS_TAG_AGREE_ALG; - agreeParams[idx++].uint32Param = g_algToHksAlgorithm[algo]; // only support HKS_ALG_ED25519 and HKS_ALG_X25519 - agreeParams[idx].tag = HKS_TAG_AGREE_PRIVATE_KEY_ALIAS; - agreeParams[idx++].blob = priKeyBlob; - agreeParams[idx].tag = HKS_TAG_AGREE_PUBLIC_KEY; - agreeParams[idx++].blob = pubKeyBlob; - agreeParams[idx].tag = HKS_TAG_AGREE_PUBLIC_KEY_IS_KEY_ALIAS; - agreeParams[idx++].boolParam = pubKeyBuff->isAlias; - AddStorageExtParams(agreeParams, priKeyParams->isDeStorage, &idx, priKeyParams->osAccountId); - int32_t res = ConstructParamSet(paramSet, agreeParams, idx); - HcFree(agreeParams); - if (res != HAL_SUCCESS) { - LOGE("Construct agree param set failed, res = %d", res); - } - return res; -} - -static int32_t CheckAgreeWithStorageParams(const KeyParams *priKeyParams, const KeyBuff *pubKeyBuff, - uint32_t sharedKeyLen, const Uint8Buff *sharedKeyAlias) -{ - int32_t res = CheckKeyParams(priKeyParams); - if (res != HAL_SUCCESS) { - return res; - } - CHECK_PTR_RETURN_HAL_ERROR_CODE(pubKeyBuff, "pubKeyBuff"); - CHECK_PTR_RETURN_HAL_ERROR_CODE(pubKeyBuff->key, "pubKeyBuff->key"); - CHECK_LEN_ZERO_RETURN_ERROR_CODE(pubKeyBuff->keyLen, "pubKeyBuff->keyLen"); - CHECK_PTR_RETURN_HAL_ERROR_CODE(sharedKeyAlias, "sharedKeyAlias"); - CHECK_PTR_RETURN_HAL_ERROR_CODE(sharedKeyAlias->val, "sharedKeyAlias->val"); - CHECK_LEN_ZERO_RETURN_ERROR_CODE(sharedKeyAlias->length, "sharedKeyAlias->length"); - CHECK_LEN_ZERO_RETURN_ERROR_CODE(sharedKeyLen, "sharedKeyLen"); - return HAL_SUCCESS; -} - -static void MoveSharedKeyToCe(const KeyParams *priKeyParams, const struct HksBlob *sharedKeyAlias) -{ - struct HksBlob priKeyBlob = { priKeyParams->keyBuff.keyLen, priKeyParams->keyBuff.key }; - MoveDeKeyToCe(priKeyParams->keyBuff.isAlias, priKeyParams->osAccountId, &priKeyBlob); - MoveDeKeyToCe(true, priKeyParams->osAccountId, sharedKeyAlias); -} - static int32_t AgreeSharedSecretWithStorage(const KeyParams *priKeyParams, const KeyBuff *pubKeyBuff, Algorithm algo, uint32_t sharedKeyLen, const Uint8Buff *sharedKeyAlias) { @@ -1380,46 +662,6 @@ static int32_t AgreeSharedSecretWithStorage(const KeyParams *priKeyParams, const return HAL_SUCCESS; } -static int32_t CheckAgreeParams(const KeyParams *priKeyParams, const KeyBuff *pubKey, const Uint8Buff *sharedKey) -{ - int32_t res = CheckKeyParams(priKeyParams); - if (res != HAL_SUCCESS) { - return res; - } - CHECK_PTR_RETURN_HAL_ERROR_CODE(pubKey, "pubKey"); - CHECK_PTR_RETURN_HAL_ERROR_CODE(pubKey->key, "pubKey->key"); - CHECK_LEN_ZERO_RETURN_ERROR_CODE(pubKey->keyLen, "pubKey->keyLen"); - CHECK_PTR_RETURN_HAL_ERROR_CODE(sharedKey, "sharedKey"); - CHECK_PTR_RETURN_HAL_ERROR_CODE(sharedKey->val, "sharedKey->val"); - CHECK_LEN_ZERO_RETURN_ERROR_CODE(sharedKey->length, "sharedKey->length"); - return HAL_SUCCESS; -} - -static int32_t ConstructAgreeParamSet(const KeyParams *keyParams, Algorithm algo, const Uint8Buff *sharedKey, - struct HksParamSet **paramSet) -{ - uint32_t len = GetParamLen(keyParams->isDeStorage, BASE_AGREE_PARAMS_LEN); - struct HksParam *agreeParams = (struct HksParam *)HcMalloc(sizeof(struct HksParam) * len, 0); - if (agreeParams == NULL) { - LOGE("Malloc for agreeParams failed."); - return HAL_ERR_BAD_ALLOC; - } - uint32_t idx = 0; - agreeParams[idx].tag = HKS_TAG_ALGORITHM; - agreeParams[idx++].uint32Param = g_algToHksAlgorithm[algo]; // only support HKS_ALG_X25519 now - agreeParams[idx].tag = HKS_TAG_KEY_SIZE; - agreeParams[idx++].uint32Param = sharedKey->length * BITS_PER_BYTE; - agreeParams[idx].tag = HKS_TAG_IS_KEY_ALIAS; - agreeParams[idx++].boolParam = keyParams->keyBuff.isAlias; - AddStorageExtParams(agreeParams, keyParams->isDeStorage, &idx, keyParams->osAccountId); - int32_t res = ConstructParamSet(paramSet, agreeParams, idx); - HcFree(agreeParams); - if (res != HAL_SUCCESS) { - LOGE("Construct agree param set failed, res = %d", res); - } - return res; -} - static int32_t AgreeSharedSecret(const KeyParams *priKeyParams, const KeyBuff *pubKey, Algorithm algo, Uint8Buff *sharedKey) { @@ -1455,97 +697,6 @@ static int32_t AgreeSharedSecret(const KeyParams *priKeyParams, const KeyBuff *p return HAL_SUCCESS; } -static int32_t BigNumExpMod(const Uint8Buff *base, const Uint8Buff *exp, const char *bigNumHex, Uint8Buff *outNum) -{ - const Uint8Buff *inParams[] = { base, exp, outNum }; - const char *paramTags[] = { "base", "exp", "outNum" }; - int32_t res = BaseCheckParams(inParams, paramTags, CAL_ARRAY_SIZE(inParams)); - if (res != HAL_SUCCESS) { - return res; - } - - CHECK_PTR_RETURN_HAL_ERROR_CODE(bigNumHex, "bigNumHex"); - uint32_t primeLen = HcStrlen(bigNumHex) / BYTE_TO_HEX_OPER_LENGTH; - if ((primeLen != BIG_PRIME_LEN_384) && (primeLen != BIG_PRIME_LEN_256)) { - LOGE("Not support big number len %d", outNum->length); - return HAL_FAILED; - } - CHECK_LEN_EQUAL_RETURN(outNum->length, primeLen, "outNum->length"); - - struct HksBlob baseBlob = { base->length, base->val }; - struct HksBlob expBlob = { exp->length, exp->val }; - struct HksBlob outNumBlob = { outNum->length, outNum->val }; - struct HksBlob bigNumBlob = { 0, NULL }; - bigNumBlob.size = outNum->length; - bigNumBlob.data = (uint8_t *)HcMalloc(bigNumBlob.size, 0); - if (bigNumBlob.data == NULL) { - LOGE("malloc bigNumBlob.data failed."); - return HAL_ERR_BAD_ALLOC; - } - res = HexStringToByte(bigNumHex, bigNumBlob.data, bigNumBlob.size); - if (res != HAL_SUCCESS) { - LOGE("HexStringToByte for bigNumHex failed."); - HcFree(bigNumBlob.data); - return res; - } - - res = HksBnExpMod(&outNumBlob, &baseBlob, &expBlob, &bigNumBlob); - if (res != HKS_SUCCESS) { - LOGE("Huks calculate big number exp mod failed, res = %d", res); - HcFree(bigNumBlob.data); - return HAL_FAILED; - } - outNum->length = outNumBlob.size; - - HcFree(bigNumBlob.data); - return HAL_SUCCESS; -} - -static int32_t ConstructGenerateKeyPairWithStorageParams(struct HksParamSet **paramSet, Algorithm algo, - uint32_t keyLen, KeyPurpose purpose, const KeyParams *authIdParams) -{ - struct HksBlob authIdBlob = { authIdParams->keyBuff.keyLen, authIdParams->keyBuff.key }; - uint32_t len = GetParamLen(authIdParams->isDeStorage, BASE_GENERATE_KEY_PAIR_PARAMS_LEN); - struct HksParam *generateParams = (struct HksParam *)HcMalloc(sizeof(struct HksParam) * len, 0); - if (generateParams == NULL) { - LOGE("Malloc for generateParams failed."); - return HAL_ERR_BAD_ALLOC; - } - uint32_t idx = 0; - generateParams[idx].tag = HKS_TAG_ALGORITHM; - generateParams[idx++].uint32Param = g_algToHksAlgorithm[algo]; - generateParams[idx].tag = HKS_TAG_KEY_STORAGE_FLAG; - generateParams[idx++].uint32Param = HKS_STORAGE_PERSISTENT; - generateParams[idx].tag = HKS_TAG_PURPOSE; - generateParams[idx++].uint32Param = g_purposeToHksKeyPurpose[purpose]; - generateParams[idx].tag = HKS_TAG_KEY_SIZE; - generateParams[idx++].uint32Param = keyLen * BITS_PER_BYTE; - generateParams[idx].tag = HKS_TAG_KEY_AUTH_ID; - generateParams[idx++].blob = authIdBlob; - generateParams[idx].tag = HKS_TAG_DIGEST; - generateParams[idx++].uint32Param = HKS_DIGEST_SHA256; - AddStorageExtParams(generateParams, authIdParams->isDeStorage, &idx, authIdParams->osAccountId); - int32_t res = ConstructParamSet(paramSet, generateParams, idx); - HcFree(generateParams); - if (res != HAL_SUCCESS) { - LOGE("Construct generate key pair param set failed, res = %d", res); - } - return res; -} - -static int32_t CheckGenerateKeyPairParams(const KeyParams *keyParams, const ExtraInfo *exInfo, uint32_t keyLen) -{ - int32_t res = CheckKeyParams(keyParams); - if (res != HAL_SUCCESS) { - return res; - } - CHECK_PTR_RETURN_HAL_ERROR_CODE(exInfo, "exInfo"); - CHECK_PTR_RETURN_HAL_ERROR_CODE(exInfo->authId.val, "authId->val"); - CHECK_LEN_ZERO_RETURN_ERROR_CODE(exInfo->authId.length, "authId->length"); - CHECK_LEN_ZERO_RETURN_ERROR_CODE(keyLen, "keyLen"); - return HAL_SUCCESS; -} - static int32_t GenerateKeyPairWithStorage(const KeyParams *keyParams, uint32_t keyLen, Algorithm algo, KeyPurpose purpose, const ExtraInfo *exInfo) { @@ -1572,7 +723,7 @@ static int32_t GenerateKeyPairWithStorage(const KeyParams *keyParams, uint32_t k LOGI("[HUKS]: HksGenerateKey quit. [Res]: %d", res); if (res != HKS_SUCCESS) { LOGE("[HUKS]: HksGenerateKey fail. [Res]: %d", res); - return HAL_FAILED; + return HAL_ERR_HUKS; } return HAL_SUCCESS; } @@ -1614,32 +765,6 @@ static int32_t GetKeyPair(struct HksParamSet *outParamSet, Uint8Buff *outPriKey, return HAL_SUCCESS; } -static int32_t ConstructGenerateKeyPairParams(struct HksParamSet **paramSet, Algorithm algo, uint32_t keyLen) -{ - struct HksParam keyParam[] = { - { - .tag = HKS_TAG_KEY_STORAGE_FLAG, - .uint32Param = HKS_STORAGE_TEMP - }, { - .tag = HKS_TAG_ALGORITHM, - .uint32Param = g_algToHksAlgorithm[algo] - }, { - .tag = HKS_TAG_KEY_SIZE, - .uint32Param = keyLen * BITS_PER_BYTE - }, { - .tag = HKS_TAG_IS_KEY_ALIAS, - .uint32Param = false - } - }; - - int32_t res = ConstructParamSet(paramSet, keyParam, CAL_ARRAY_SIZE(keyParam)); - if (res != HAL_SUCCESS) { - LOGE("Construct param set failed, res = %d", res); - return res; - } - return res; -} - static int32_t GenerateKeyPair(Algorithm algo, Uint8Buff *outPriKey, Uint8Buff *outPubKey) { CHECK_PTR_RETURN_HAL_ERROR_CODE(outPriKey, "outPriKey"); @@ -1693,39 +818,6 @@ ERR: return res; } -static int32_t ConstructExportParams(bool isDeStorage, int32_t osAccountId, struct HksParamSet **paramSet) -{ - uint32_t len = GetParamLen(isDeStorage, 0); - if (len == 0) { - return HAL_SUCCESS; - } - struct HksParam *exportParams = (struct HksParam *)HcMalloc(sizeof(struct HksParam) * len, 0); - if (exportParams == NULL) { - LOGE("Malloc for exportParams failed."); - return HAL_ERR_BAD_ALLOC; - } - uint32_t idx = 0; - AddStorageExtParams(exportParams, isDeStorage, &idx, osAccountId); - int32_t res = ConstructParamSet(paramSet, exportParams, idx); - HcFree(exportParams); - if (res != HAL_SUCCESS) { - LOGE("Failed to construct export param set, res: %d", res); - } - return res; -} - -static int32_t CheckExportParams(const KeyParams *keyParams, const Uint8Buff *outPubKey) -{ - int32_t res = CheckKeyParams(keyParams); - if (res != HAL_SUCCESS) { - return res; - } - CHECK_PTR_RETURN_HAL_ERROR_CODE(outPubKey, "outPubKey"); - CHECK_PTR_RETURN_HAL_ERROR_CODE(outPubKey->val, "outPubKey->val"); - CHECK_LEN_ZERO_RETURN_ERROR_CODE(outPubKey->length, "outPubKey->length"); - return HAL_SUCCESS; -} - static int32_t ExportPublicKey(const KeyParams *keyParams, Uint8Buff *outPubKey) { int32_t res = CheckExportParams(keyParams, outPubKey); @@ -1766,49 +858,12 @@ static int32_t ExportPublicKey(const KeyParams *keyParams, Uint8Buff *outPubKey) FreeParamSet(ceParamSet); if (res != HKS_SUCCESS) { LOGE("[HUKS]: HksExportPublicKey failed. [Res]: %d", res); - return HAL_FAILED; + return HAL_ERR_HUKS; } outPubKey->length = keyBlob.size; return HAL_SUCCESS; } -static int32_t ConstructSignParams(bool isDeStorage, int32_t osAccountId, struct HksParamSet **paramSet, - Algorithm algo) -{ - uint32_t len = GetParamLen(isDeStorage, BASE_SIGN_PARAMS_LEN); - struct HksParam *signParams = (struct HksParam *)HcMalloc(sizeof(struct HksParam) * len, 0); - if (signParams == NULL) { - LOGE("Malloc for signParams failed."); - return HAL_ERR_BAD_ALLOC; - } - uint32_t idx = 0; - signParams[idx].tag = HKS_TAG_PURPOSE; - signParams[idx++].uint32Param = HKS_KEY_PURPOSE_SIGN; - signParams[idx].tag = HKS_TAG_ALGORITHM; - signParams[idx++].uint32Param = g_algToHksAlgorithm[algo]; // only support HKS_ALG_ED25519 and HKS_ALG_ECC. - signParams[idx].tag = HKS_TAG_DIGEST; - signParams[idx++].uint32Param = HKS_DIGEST_SHA256; - AddStorageExtParams(signParams, isDeStorage, &idx, osAccountId); - int32_t res = ConstructParamSet(paramSet, signParams, idx); - HcFree(signParams); - if (res != HAL_SUCCESS) { - LOGE("Construct sign param set failed, res = %d", res); - } - return res; -} - -static int32_t CheckSignParams(const KeyParams *keyParams, const Uint8Buff *message, - const Uint8Buff *outSignature) -{ - int32_t res = CheckKeyParams(keyParams); - if (res != HAL_SUCCESS) { - return res; - } - const Uint8Buff *inParams[] = { message, outSignature }; - const char *paramTags[] = { "message", "outSignature" }; - return BaseCheckParams(inParams, paramTags, CAL_ARRAY_SIZE(inParams)); -} - static int32_t Sign(const KeyParams *keyParams, const Uint8Buff *message, Algorithm algo, Uint8Buff *outSignature) { @@ -1864,44 +919,6 @@ static int32_t Sign(const KeyParams *keyParams, const Uint8Buff *message, Algori return HAL_SUCCESS; } -static int32_t ConstructVerifyParams(struct HksParamSet **paramSet, const KeyParams *keyParams, Algorithm algo) -{ - uint32_t len = GetParamLen(keyParams->isDeStorage, BASE_VERIFY_PARAMS_LEN); - struct HksParam *verifyParams = (struct HksParam *)HcMalloc(sizeof(struct HksParam) * len, 0); - if (verifyParams == NULL) { - LOGE("Malloc for verifyParams failed."); - return HAL_ERR_BAD_ALLOC; - } - uint32_t idx = 0; - verifyParams[idx].tag = HKS_TAG_PURPOSE; - verifyParams[idx++].uint32Param = HKS_KEY_PURPOSE_VERIFY; - verifyParams[idx].tag = HKS_TAG_ALGORITHM; - verifyParams[idx++].uint32Param = g_algToHksAlgorithm[algo]; // only support HKS_ALG_ED25519 and HKS_ALG_ECC. - verifyParams[idx].tag = HKS_TAG_IS_KEY_ALIAS; - verifyParams[idx++].boolParam = keyParams->keyBuff.isAlias; - verifyParams[idx].tag = HKS_TAG_DIGEST; - verifyParams[idx++].uint32Param = HKS_DIGEST_SHA256; - AddStorageExtParams(verifyParams, keyParams->isDeStorage, &idx, keyParams->osAccountId); - int32_t res = ConstructParamSet(paramSet, verifyParams, idx); - HcFree(verifyParams); - if (res != HAL_SUCCESS) { - LOGE("Construct verify param set failed, res = %d", res); - } - return res; -} - -static int32_t CheckVerifyParams(const KeyParams *keyParams, const Uint8Buff *message, - const Uint8Buff *signature) -{ - int32_t res = CheckKeyParams(keyParams); - if (res != HAL_SUCCESS) { - return res; - } - const Uint8Buff *inParams[] = { message, signature }; - const char *paramTags[] = { "message", "signature" }; - return BaseCheckParams(inParams, paramTags, CAL_ARRAY_SIZE(inParams)); -} - static int32_t Verify(const KeyParams *keyParams, const Uint8Buff *message, Algorithm algo, const Uint8Buff *signature) { @@ -1938,62 +955,6 @@ static int32_t Verify(const KeyParams *keyParams, const Uint8Buff *message, Algo return HAL_SUCCESS; } -static int32_t ConstructImportPublicKeyParams(struct HksParamSet **paramSet, Algorithm algo, uint32_t keyLen, - const KeyParams *authIdParams, const union KeyRoleInfoUnion *roleInfoUnion) -{ - if (g_algToHksAlgorithm[algo] == HKS_ALG_ECC) { - keyLen = ECC_PK_LEN; - } - struct HksBlob authIdBlob = { authIdParams->keyBuff.keyLen, authIdParams->keyBuff.key }; - uint32_t len = GetParamLen(authIdParams->isDeStorage, BASE_IMPORT_PUB_KEY_PARAMS_LEN); - struct HksParam *importParams = (struct HksParam *)HcMalloc(sizeof(struct HksParam) * len, 0); - if (importParams == NULL) { - LOGE("Malloc for importParams failed."); - return HAL_ERR_BAD_ALLOC; - } - uint32_t idx = 0; - importParams[idx].tag = HKS_TAG_ALGORITHM; - importParams[idx++].uint32Param = g_algToHksAlgorithm[algo]; - importParams[idx].tag = HKS_TAG_KEY_SIZE; - importParams[idx++].uint32Param = keyLen * BITS_PER_BYTE; - importParams[idx].tag = HKS_TAG_PADDING; - importParams[idx++].uint32Param = HKS_PADDING_NONE; - importParams[idx].tag = HKS_TAG_KEY_AUTH_ID; - importParams[idx++].blob = authIdBlob; - importParams[idx].tag = HKS_TAG_IS_ALLOWED_WRAP; - importParams[idx++].boolParam = true; - importParams[idx].tag = HKS_TAG_PURPOSE; - importParams[idx++].uint32Param = HKS_KEY_PURPOSE_VERIFY; - importParams[idx].tag = HKS_TAG_KEY_ROLE; - importParams[idx++].uint32Param = roleInfoUnion->roleInfo; - importParams[idx].tag = HKS_TAG_DIGEST; - importParams[idx++].uint32Param = HKS_DIGEST_SHA256; - AddStorageExtParams(importParams, authIdParams->isDeStorage, &idx, authIdParams->osAccountId); - int32_t res = ConstructParamSet(paramSet, importParams, idx); - HcFree(importParams); - if (res != HAL_SUCCESS) { - LOGE("Construct import param set failed, res = %d", res); - } - return res; -} - -static int32_t CheckImportPubKeyParams(const KeyParams *keyParams, const Uint8Buff *pubKey, - const ExtraInfo *exInfo) -{ - int32_t res = CheckKeyParams(keyParams); - if (res != HAL_SUCCESS) { - return res; - } - CHECK_PTR_RETURN_HAL_ERROR_CODE(pubKey, "pubKey"); - CHECK_PTR_RETURN_HAL_ERROR_CODE(pubKey->val, "pubKey->val"); - CHECK_LEN_ZERO_RETURN_ERROR_CODE(pubKey->length, "pubKey->length"); - CHECK_PTR_RETURN_HAL_ERROR_CODE(exInfo, "exInfo"); - CHECK_PTR_RETURN_HAL_ERROR_CODE(exInfo->authId.val, "authId->val"); - CHECK_LEN_ZERO_RETURN_ERROR_CODE(exInfo->authId.length, "authId->length"); - CHECK_LEN_HIGHER_RETURN(exInfo->pairType, PAIR_TYPE_END - 1, "pairType"); - return HAL_SUCCESS; -} - static int32_t ImportPublicKey(const KeyParams *keyParams, const Uint8Buff *pubKey, Algorithm algo, const ExtraInfo *exInfo) { @@ -2027,28 +988,11 @@ static int32_t ImportPublicKey(const KeyParams *keyParams, const Uint8Buff *pubK LOGI("[HUKS]: HksImportKey quit. [Res]: %d", res); if (res != HKS_SUCCESS) { LOGE("[HUKS]: HksImportKey fail. [Res]: %d", res); - return HAL_FAILED; + return HAL_ERR_HUKS; } return HAL_SUCCESS; } -static bool CheckBigNumCompareParams(const Uint8Buff *a, const Uint8Buff *b, int *res) -{ - if ((a == NULL || a->val == NULL) && (b == NULL || b->val == NULL)) { - *res = 0; // a = b - return false; - } - if ((a == NULL || a->val == NULL) && (b != NULL && b->val != NULL)) { - *res = 1; // a < b - return false; - } - if ((a != NULL && a->val != NULL) && (b == NULL || b->val == NULL)) { - *res = -1; // a > b - return false; - } - return true; -} - static int32_t BigNumCompare(const Uint8Buff *a, const Uint8Buff *b) { int res = 0; @@ -2149,77 +1093,6 @@ static bool CheckEcPublicKey(const Uint8Buff *pubKey, Algorithm algo) return false; } -static int32_t InitImportParam(const KeyParams *keyParams, const ExtraInfo *exInfo, struct HksParam **importParam) -{ - if (exInfo != NULL) { - CHECK_PTR_RETURN_HAL_ERROR_CODE(exInfo->authId.val, "authId"); - CHECK_LEN_ZERO_RETURN_ERROR_CODE(exInfo->authId.length, "authId"); - CHECK_LEN_HIGHER_RETURN(exInfo->pairType, PAIR_TYPE_END - 1, "pairType"); - } - uint32_t baseLen = ((exInfo == NULL) ? BASE_IMPORT_PARAMS_LEN : (BASE_IMPORT_PARAMS_LEN + EXT_IMPORT_PARAMS_LEN)); - uint32_t len = GetParamLen(keyParams->isDeStorage, baseLen); - *importParam = (struct HksParam *)HcMalloc(sizeof(struct HksParam) * len, 0); - if (*importParam == NULL) { - LOGE("Malloc for importParam failed."); - return HAL_ERR_BAD_ALLOC; - } - return HAL_SUCCESS; -} - -static int32_t ConstructImportSymmetricKeyParam(struct HksParamSet **paramSet, const KeyParams *keyParams, - uint32_t keyLen, KeyPurpose purpose, const ExtraInfo *exInfo) -{ - struct HksParam *importParam = NULL; - int32_t res = InitImportParam(keyParams, exInfo, &importParam); - if (res != HAL_SUCCESS) { - return res; - } - uint32_t idx = 0; - if (exInfo != NULL) { - struct HksBlob authIdBlob = { 0, NULL }; - union KeyRoleInfoUnion roleInfoUnion; - (void)memset_s(&roleInfoUnion, sizeof(roleInfoUnion), 0, sizeof(roleInfoUnion)); - authIdBlob.size = exInfo->authId.length; - authIdBlob.data = exInfo->authId.val; - roleInfoUnion.roleInfoStruct.userType = (uint8_t)exInfo->userType; - roleInfoUnion.roleInfoStruct.pairType = (uint8_t)exInfo->pairType; - importParam[idx].tag = HKS_TAG_KEY_AUTH_ID; - importParam[idx++].blob = authIdBlob; - importParam[idx].tag = HKS_TAG_KEY_ROLE; - importParam[idx++].uint32Param = roleInfoUnion.roleInfo; - } - - importParam[idx].tag = HKS_TAG_ALGORITHM; - importParam[idx++].uint32Param = HKS_ALG_AES; - importParam[idx].tag = HKS_TAG_KEY_SIZE; - importParam[idx++].uint32Param = keyLen * BITS_PER_BYTE; - importParam[idx].tag = HKS_TAG_PADDING; - importParam[idx++].uint32Param = HKS_PADDING_NONE; - importParam[idx].tag = HKS_TAG_IS_ALLOWED_WRAP; - importParam[idx++].boolParam = false; - importParam[idx].tag = HKS_TAG_PURPOSE; - importParam[idx++].uint32Param = g_purposeToHksKeyPurpose[purpose]; - importParam[idx].tag = HKS_TAG_BLOCK_MODE; - importParam[idx++].uint32Param = HKS_MODE_GCM; - importParam[idx].tag = HKS_TAG_DIGEST; - importParam[idx++].uint32Param = HKS_DIGEST_SHA256; - AddStorageExtParams(importParam, keyParams->isDeStorage, &idx, keyParams->osAccountId); - res = ConstructParamSet(paramSet, importParam, idx); - HcFree(importParam); - return res; -} - -static int32_t CheckImportSymmetricKeyParams(const KeyParams *keyParams, const Uint8Buff *authToken) -{ - int32_t res = CheckKeyParams(keyParams); - if (res != HAL_SUCCESS) { - return res; - } - const Uint8Buff *inParams[] = { authToken }; - const char *paramTags[] = { "authToken" }; - return BaseCheckParams(inParams, paramTags, CAL_ARRAY_SIZE(inParams)); -} - static int32_t ImportSymmetricKey(const KeyParams *keyParams, const Uint8Buff *authToken, KeyPurpose purpose, const ExtraInfo *exInfo) { diff --git a/deps_adapter/key_management_adapter/impl/src/huks_adapter_utils.c b/deps_adapter/key_management_adapter/impl/src/huks_adapter_utils.c new file mode 100644 index 0000000000000000000000000000000000000000..3d6ae17bd5077c745f45e3e06c6a3b66e3998b9b --- /dev/null +++ b/deps_adapter/key_management_adapter/impl/src/huks_adapter_utils.c @@ -0,0 +1,1160 @@ +/* + * Copyright (C) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "huks_adapter_utils.h" + +#include "hc_log.h" +#include "mbedtls_ec_adapter.h" +#include "string_util.h" + +#define BASE_IMPORT_PARAMS_LEN 7 +#define EXT_IMPORT_PARAMS_LEN 2 +#define BASE_HMAC_PARAMS_LEN 3 +#define BASE_HMAC_DERIVE_PARAMS_LEN 5 +#define BASE_HMAC_FINISH_PARAMS_LEN 3 +#define BASE_AGREE_WITH_STORAGE_PARAMS_LEN 9 +#define BASE_HKDF_PARAMS_LEN 6 +#define BASE_COMPUTE_PSEUDONYM_PSK_PARAMS_LEN 11 +#define BASE_SIGN_PARAMS_LEN 3 +#define BASE_ENCRYPT_PARAMS_LEN 7 +#define BASE_DECRYPT_PARAMS_LEN 7 +#define BASE_AGREE_INIT_PARAMS_LEN 3 +#define BASE_AGREE_FINISH_PARAMS_LEN 7 +#define BASE_AGREE_PARAMS_LEN 3 +#define BASE_GENERATE_KEY_PAIR_PARAMS_LEN 6 +#define BASE_VERIFY_PARAMS_LEN 4 +#define BASE_IMPORT_PUB_KEY_PARAMS_LEN 8 +#define EXT_DE_PARAMS_LEN 1 +#define EXT_CE_PARAMS_LEN 2 +#define PSEUDONYM_KEY_FACTOR "hichain_pseudonym_psk_key" +#define PSEUDONYM_KEY_LEBEL "hichain_pseudonym_psk_label" + +static uint32_t g_purposeToHksKeyPurpose[] = { + HKS_KEY_PURPOSE_MAC, + HKS_KEY_PURPOSE_DERIVE, + HKS_KEY_PURPOSE_SIGN | HKS_KEY_PURPOSE_VERIFY, + HKS_KEY_PURPOSE_AGREE +}; + +static enum HksKeyAlg g_algToHksAlgorithm[] = { + HKS_ALG_ED25519, + HKS_ALG_X25519, + HKS_ALG_ECC, + HKS_ALG_AES, +}; + +int32_t CheckKeyParams(const KeyParams *keyParams) +{ + CHECK_PTR_RETURN_HAL_ERROR_CODE(keyParams, "keyParams"); + CHECK_PTR_RETURN_HAL_ERROR_CODE(keyParams->keyBuff.key, "keyParams->keyBuff.key"); + CHECK_LEN_ZERO_RETURN_ERROR_CODE(keyParams->keyBuff.keyLen, "keyParams->keyBuff.keyLen"); + return HAL_SUCCESS; +} + +static int32_t BaseCheckParams(const Uint8Buff **inParams, const char **paramTags, uint32_t len) +{ + for (uint32_t i = 0; i < len; i++) { + CHECK_PTR_RETURN_HAL_ERROR_CODE(inParams[i], paramTags[i]); + CHECK_PTR_RETURN_HAL_ERROR_CODE(inParams[i]->val, paramTags[i]); + CHECK_LEN_ZERO_RETURN_ERROR_CODE(inParams[i]->length, paramTags[i]); + } + return HAL_SUCCESS; +} + +int32_t BigNumExpMod(const Uint8Buff *base, const Uint8Buff *exp, const char *bigNumHex, Uint8Buff *outNum) +{ + const Uint8Buff *inParams[] = { base, exp, outNum }; + const char *paramTags[] = { "base", "exp", "outNum" }; + int32_t res = BaseCheckParams(inParams, paramTags, CAL_ARRAY_SIZE(inParams)); + if (res != HAL_SUCCESS) { + return res; + } + + CHECK_PTR_RETURN_HAL_ERROR_CODE(bigNumHex, "bigNumHex"); + uint32_t primeLen = HcStrlen(bigNumHex) / BYTE_TO_HEX_OPER_LENGTH; + if ((primeLen != BIG_PRIME_LEN_384) && (primeLen != BIG_PRIME_LEN_256)) { + LOGE("Not support big number len %d", outNum->length); + return HAL_FAILED; + } + CHECK_LEN_EQUAL_RETURN(outNum->length, primeLen, "outNum->length"); + + struct HksBlob baseBlob = { base->length, base->val }; + struct HksBlob expBlob = { exp->length, exp->val }; + struct HksBlob outNumBlob = { outNum->length, outNum->val }; + struct HksBlob bigNumBlob = { 0, NULL }; + bigNumBlob.size = outNum->length; + bigNumBlob.data = (uint8_t *)HcMalloc(bigNumBlob.size, 0); + if (bigNumBlob.data == NULL) { + LOGE("malloc bigNumBlob.data failed."); + return HAL_ERR_BAD_ALLOC; + } + res = HexStringToByte(bigNumHex, bigNumBlob.data, bigNumBlob.size); + if (res != HAL_SUCCESS) { + LOGE("HexStringToByte for bigNumHex failed."); + HcFree(bigNumBlob.data); + return res; + } + + res = HksBnExpMod(&outNumBlob, &baseBlob, &expBlob, &bigNumBlob); + if (res != HKS_SUCCESS) { + LOGE("Huks calculate big number exp mod failed, res = %d", res); + HcFree(bigNumBlob.data); + return HAL_FAILED; + } + outNum->length = outNumBlob.size; + HcFree(bigNumBlob.data); + return HAL_SUCCESS; +} + +void FreeParamSet(struct HksParamSet *paramSet) +{ + if (paramSet == NULL) { + return; + } + HksFreeParamSet(¶mSet); +} + +int32_t ConstructParamSet(struct HksParamSet **out, const struct HksParam *inParam, + const uint32_t inParamNum) +{ + struct HksParamSet *paramSet = NULL; + int32_t res = HksInitParamSet(¶mSet); + if (res != HKS_SUCCESS) { + LOGE("init param set failed, res = %d", res); + return HAL_ERR_INIT_PARAM_SET_FAILED; + } + + res = HksAddParams(paramSet, inParam, inParamNum); + if (res != HKS_SUCCESS) { + LOGE("add param failed, res = %d", res); + FreeParamSet(paramSet); + return HAL_ERR_ADD_PARAM_FAILED; + } + + res = HksBuildParamSet(¶mSet); + if (res != HKS_SUCCESS) { + LOGE("build param set failed, res = %d", res); + FreeParamSet(paramSet); + return HAL_ERR_BUILD_PARAM_SET_FAILED; + } + + *out = paramSet; + return HAL_SUCCESS; +} + +static uint32_t GetParamLen(bool isDeStorage, uint32_t baseLen) +{ +#ifdef DEV_AUTH_ENABLE_CE + if (isDeStorage) { + return baseLen + EXT_DE_PARAMS_LEN; + } else { + return baseLen + EXT_CE_PARAMS_LEN; + } +#else + (void)isDeStorage; + return baseLen; +#endif +} + +static void AddStorageExtParams(struct HksParam *params, bool isDeStorage, uint32_t *idx, int32_t osAccountId) +{ +#ifdef DEV_AUTH_ENABLE_CE + if (isDeStorage) { + params[*idx].tag = HKS_TAG_AUTH_STORAGE_LEVEL; + params[(*idx)++].uint32Param = HKS_AUTH_STORAGE_LEVEL_DE; + } else { + params[*idx].tag = HKS_TAG_AUTH_STORAGE_LEVEL; + params[(*idx)++].uint32Param = HKS_AUTH_STORAGE_LEVEL_CE; + params[*idx].tag = HKS_TAG_SPECIFIC_USER_ID; + params[(*idx)++].uint32Param = osAccountId; + } +#else + (void)params; + (void)isDeStorage; + (void)idx; + (void)osAccountId; +#endif +} + +static int32_t ConstructDeParamSet(struct HksParamSet **paramSet) +{ + struct HksParam keyParam[] = { + { + .tag = HKS_TAG_AUTH_STORAGE_LEVEL, + .uint32Param = HKS_AUTH_STORAGE_LEVEL_DE + } + }; + + int32_t res = ConstructParamSet(paramSet, keyParam, CAL_ARRAY_SIZE(keyParam)); + if (res != HAL_SUCCESS) { + LOGE("Construct de param set failed, res = %d", res); + } + return res; +} + +static int32_t ConstructCeParamSet(int32_t osAccountId, struct HksParamSet **paramSet) +{ + struct HksParam keyParam[] = { + { + .tag = HKS_TAG_AUTH_STORAGE_LEVEL, + .uint32Param = HKS_AUTH_STORAGE_LEVEL_CE + }, { + .tag = HKS_TAG_SPECIFIC_USER_ID, + .uint32Param = osAccountId + } + }; + + int32_t res = ConstructParamSet(paramSet, keyParam, CAL_ARRAY_SIZE(keyParam)); + if (res != HAL_SUCCESS) { + LOGE("Construct ce param set failed, res = %d", res); + } + return res; +} + +static int32_t ChangeStorageLevel(const struct HksBlob *keyAliasBlob, const struct HksParamSet *deParamSet, + const struct HksParamSet *ceParamSet) +{ +#ifdef DEV_AUTH_ENABLE_CE + return HksChangeStorageLevel(keyAliasBlob, deParamSet, ceParamSet); +#else + (void)keyAliasBlob; + (void)deParamSet; + (void)ceParamSet; + return HKS_SUCCESS; +#endif +} + +void MoveDeKeyToCe(bool isKeyAlias, int32_t osAccountId, const struct HksBlob *keyAliasBlob) +{ + if (!isKeyAlias) { + return; + } + struct HksParamSet *deParamSet = NULL; + if (ConstructDeParamSet(&deParamSet) != HAL_SUCCESS) { + return; + } + struct HksParamSet *ceParamSet = NULL; + if (ConstructCeParamSet(osAccountId, &ceParamSet) != HAL_SUCCESS) { + return; + } + int32_t res = ChangeStorageLevel(keyAliasBlob, deParamSet, ceParamSet); + if (res != HKS_SUCCESS) { + LOGE("Failed to move de key to ce!"); + } +} + +int32_t ConstructCheckParamSet(bool isDeStorage, int32_t osAccountId, struct HksParamSet **paramSet) +{ + uint32_t len = GetParamLen(isDeStorage, 0); + if (len == 0) { + return HAL_SUCCESS; + } + struct HksParam *checkParams = (struct HksParam *)HcMalloc(sizeof(struct HksParam) * len, 0); + if (checkParams == NULL) { + LOGE("Malloc for checkParams failed."); + return HAL_ERR_BAD_ALLOC; + } + uint32_t idx = 0; + AddStorageExtParams(checkParams, isDeStorage, &idx, osAccountId); + int32_t res = ConstructParamSet(paramSet, checkParams, idx); + HcFree(checkParams); + if (res != HAL_SUCCESS) { + LOGE("Failed to construct check param set, res: %d", res); + } + return res; +} + +int32_t ConstructDeleteParamSet(bool isDeStorage, int32_t osAccountId, struct HksParamSet **paramSet) +{ + uint32_t len = GetParamLen(isDeStorage, 0); + if (len == 0) { + return HAL_SUCCESS; + } + struct HksParam *deleteParams = (struct HksParam *)HcMalloc(sizeof(struct HksParam) * len, 0); + if (deleteParams == NULL) { + LOGE("Malloc for deleteParams failed."); + return HAL_ERR_BAD_ALLOC; + } + uint32_t idx = 0; + AddStorageExtParams(deleteParams, isDeStorage, &idx, osAccountId); + int32_t res = ConstructParamSet(paramSet, deleteParams, idx); + HcFree(deleteParams); + if (res != HAL_SUCCESS) { + LOGE("Failed to construct delete param set, res: %d", res); + } + return res; +} + +int32_t ConstructHmacParamSet(bool isDeStorage, int32_t osAccountId, bool isAlias, + struct HksParamSet **hmacParamSet) +{ + uint32_t len = GetParamLen(isDeStorage, BASE_HMAC_PARAMS_LEN); + struct HksParam *hmacParams = (struct HksParam *)HcMalloc(sizeof(struct HksParam) * len, 0); + if (hmacParams == NULL) { + LOGE("Malloc for hmacParams failed."); + return HAL_ERR_BAD_ALLOC; + } + uint32_t idx = 0; + hmacParams[idx].tag = HKS_TAG_PURPOSE; + hmacParams[idx++].uint32Param = HKS_KEY_PURPOSE_MAC; + hmacParams[idx].tag = HKS_TAG_DIGEST; + hmacParams[idx++].uint32Param = HKS_DIGEST_SHA256; + hmacParams[idx].tag = HKS_TAG_IS_KEY_ALIAS; + hmacParams[idx++].boolParam = isAlias; + AddStorageExtParams(hmacParams, isDeStorage, &idx, osAccountId); + int32_t res = ConstructParamSet(hmacParamSet, hmacParams, idx); + HcFree(hmacParams); + if (res != HAL_SUCCESS) { + LOGE("Construct hmac param set failed, res = %d", res); + } + return res; +} + +int32_t CheckHmacParams(const KeyParams *keyParams, const Uint8Buff *message, const Uint8Buff *outHmac) +{ + int32_t res = CheckKeyParams(keyParams); + if (res != HAL_SUCCESS) { + return res; + } + const Uint8Buff *inParams[] = { message, outHmac }; + const char *paramTags[] = { "message", "outHmac" }; + res = BaseCheckParams(inParams, paramTags, CAL_ARRAY_SIZE(inParams)); + if (res != HAL_SUCCESS) { + return res; + } + CHECK_LEN_EQUAL_RETURN(outHmac->length, HMAC_LEN, "outHmac->length"); + return HAL_SUCCESS; +} + +int32_t ConstructDeriveParamSet(const KeyParams *keyParams, const Uint8Buff *message, + struct HksParamSet **deriveParamSet) +{ + struct HksBlob srcBlob = { message->length, message->val }; + uint32_t len = GetParamLen(keyParams->isDeStorage, BASE_HMAC_DERIVE_PARAMS_LEN); + struct HksParam *hmacDeriveParams = (struct HksParam *)HcMalloc(sizeof(struct HksParam) * len, 0); + if (hmacDeriveParams == NULL) { + LOGE("Malloc for hmacDeriveParams failed."); + return HAL_ERR_BAD_ALLOC; + } + uint32_t idx = 0; + hmacDeriveParams[idx].tag = HKS_TAG_ALGORITHM; + hmacDeriveParams[idx++].uint32Param = HKS_ALG_HMAC; + hmacDeriveParams[idx].tag = HKS_TAG_PURPOSE; + hmacDeriveParams[idx++].uint32Param = HKS_KEY_PURPOSE_DERIVE; + hmacDeriveParams[idx].tag = HKS_TAG_DIGEST; + hmacDeriveParams[idx++].uint32Param = HKS_DIGEST_SHA256; + hmacDeriveParams[idx].tag = HKS_TAG_DERIVE_KEY_SIZE; + hmacDeriveParams[idx++].uint32Param = HMAC_LEN; + hmacDeriveParams[idx].tag = HKS_TAG_INFO; + hmacDeriveParams[idx++].blob = srcBlob; + AddStorageExtParams(hmacDeriveParams, keyParams->isDeStorage, &idx, keyParams->osAccountId); + int32_t res = ConstructParamSet(deriveParamSet, hmacDeriveParams, idx); + HcFree(hmacDeriveParams); + if (res != HAL_SUCCESS) { + LOGE("Construct derive param set failed, res = %d", res); + } + return res; +} + +int32_t ConstructFinishParamSet(const KeyParams *keyParams, struct HksParamSet **finishParamSet) +{ + uint32_t len = GetParamLen(keyParams->isDeStorage, BASE_HMAC_FINISH_PARAMS_LEN); + struct HksParam *hmacFinishParams = (struct HksParam *)HcMalloc(sizeof(struct HksParam) * len, 0); + if (hmacFinishParams == NULL) { + LOGE("Malloc for hmacFinishParams failed."); + return HAL_ERR_BAD_ALLOC; + } + uint32_t idx = 0; + hmacFinishParams[idx].tag = HKS_TAG_ALGORITHM; + hmacFinishParams[idx++].uint32Param = HKS_ALG_AES; + hmacFinishParams[idx].tag = HKS_TAG_KEY_SIZE; + hmacFinishParams[idx++].uint32Param = HKS_AES_KEY_SIZE_256; + hmacFinishParams[idx].tag = HKS_TAG_PURPOSE; + hmacFinishParams[idx++].uint32Param = HKS_KEY_PURPOSE_ENCRYPT | HKS_KEY_PURPOSE_DECRYPT; + AddStorageExtParams(hmacFinishParams, keyParams->isDeStorage, &idx, keyParams->osAccountId); + int32_t res = ConstructParamSet(finishParamSet, hmacFinishParams, idx); + HcFree(hmacFinishParams); + if (res != HAL_SUCCESS) { + LOGE("Construct finish param set failed, res = %d", res); + } + return res; +} + +int32_t CheckHmacWithThreeStageParams(const KeyParams *keyParams, const Uint8Buff *message, + const Uint8Buff *outHmac) +{ + int32_t res = CheckKeyParams(keyParams); + if (res != HAL_SUCCESS) { + return res; + } + const Uint8Buff *inParams[] = { message, outHmac }; + const char *paramTags[] = { "message", "outHmac" }; + res = BaseCheckParams(inParams, paramTags, CAL_ARRAY_SIZE(inParams)); + if (res != HAL_SUCCESS) { + return res; + } + CHECK_LEN_EQUAL_RETURN(outHmac->length, HMAC_LEN, "outHmac->length"); + return HAL_SUCCESS; +} + +int32_t ConstructHkdfParamSet(bool isDeStorage, const KeyParams *keyParams, const Uint8Buff *salt, + const Uint8Buff *keyInfo, struct HksParamSet **paramSet) +{ + struct HksBlob saltBlob = { salt->length, salt->val }; + struct HksBlob keyInfoBlob = { 0, NULL }; + if (keyInfo != NULL) { + keyInfoBlob.size = keyInfo->length; + keyInfoBlob.data = keyInfo->val; + } + uint32_t len = GetParamLen(isDeStorage, BASE_HKDF_PARAMS_LEN); + struct HksParam *hkdfParams = (struct HksParam *)HcMalloc(sizeof(struct HksParam) * len, 0); + if (hkdfParams == NULL) { + LOGE("Malloc for hkdfParams failed."); + return HAL_ERR_BAD_ALLOC; + } + uint32_t idx = 0; + hkdfParams[idx].tag = HKS_TAG_PURPOSE; + hkdfParams[idx++].uint32Param = HKS_KEY_PURPOSE_DERIVE; + hkdfParams[idx].tag = HKS_TAG_ALGORITHM; + hkdfParams[idx++].uint32Param = HKS_ALG_HKDF; + hkdfParams[idx].tag = HKS_TAG_DIGEST; + hkdfParams[idx++].uint32Param = HKS_DIGEST_SHA256; + hkdfParams[idx].tag = HKS_TAG_SALT; + hkdfParams[idx++].blob = saltBlob; + hkdfParams[idx].tag = HKS_TAG_INFO; + hkdfParams[idx++].blob = keyInfoBlob; + hkdfParams[idx].tag = HKS_TAG_IS_KEY_ALIAS; + hkdfParams[idx++].boolParam = keyParams->keyBuff.isAlias; + AddStorageExtParams(hkdfParams, isDeStorage, &idx, keyParams->osAccountId); + int32_t res = ConstructParamSet(paramSet, hkdfParams, idx); + HcFree(hkdfParams); + if (res != HAL_SUCCESS) { + LOGE("Failed to construct hkdf param set, res: %d", res); + } + return res; +} + +int32_t CheckHkdfParams(const KeyParams *keyParams, const Uint8Buff *salt, const Uint8Buff *outHkdf) +{ + int32_t res = CheckKeyParams(keyParams); + if (res != HAL_SUCCESS) { + return res; + } + const Uint8Buff *inParams[] = { salt, outHkdf }; + const char *paramTags[] = { "salt", "outHkdf" }; + return BaseCheckParams(inParams, paramTags, CAL_ARRAY_SIZE(inParams)); +} + +int32_t ConstructPseudonymParamSet(const KeyParams *keyParams, const Uint8Buff *pskKeyAlias, + const struct HksBlob *extInfoBlob, uint32_t outLen, struct HksParamSet **paramSet) +{ + struct HksBlob saltBlob = { HcStrlen(PSEUDONYM_KEY_FACTOR), (uint8_t *)PSEUDONYM_KEY_FACTOR }; + struct HksBlob keyInfoBlob = { HcStrlen(PSEUDONYM_KEY_LEBEL), (uint8_t *)PSEUDONYM_KEY_LEBEL }; + struct HksBlob pskAliasBlob = { pskKeyAlias->length, pskKeyAlias->val }; + uint32_t len = GetParamLen(keyParams->isDeStorage, BASE_COMPUTE_PSEUDONYM_PSK_PARAMS_LEN); + struct HksParam *hkdfParams = (struct HksParam *)HcMalloc(sizeof(struct HksParam) * len, 0); + if (hkdfParams == NULL) { + LOGE("Malloc for hkdfParams failed."); + return HAL_ERR_BAD_ALLOC; + } + uint32_t idx = 0; + hkdfParams[idx].tag = HKS_TAG_PURPOSE; + hkdfParams[idx++].uint32Param = HKS_KEY_PURPOSE_DERIVE; + hkdfParams[idx].tag = HKS_TAG_ALGORITHM; + hkdfParams[idx++].uint32Param = HKS_ALG_HKDF; + hkdfParams[idx].tag = HKS_TAG_DIGEST; + hkdfParams[idx++].uint32Param = HKS_DIGEST_SHA256; + hkdfParams[idx].tag = HKS_TAG_SALT; + hkdfParams[idx++].blob = saltBlob; + hkdfParams[idx].tag = HKS_TAG_INFO; + hkdfParams[idx++].blob = keyInfoBlob; + hkdfParams[idx].tag = HKS_TAG_IS_KEY_ALIAS; + hkdfParams[idx++].boolParam = true; + hkdfParams[idx].tag = HKS_TAG_KEY_STORAGE_FLAG; + hkdfParams[idx++].uint32Param = HKS_STORAGE_ONLY_USED_IN_HUKS; + hkdfParams[idx].tag = HKS_TAG_DERIVE_AGREE_KEY_STORAGE_FLAG; + hkdfParams[idx++].uint32Param = HKS_STORAGE_ONLY_USED_IN_HUKS; + hkdfParams[idx].tag = HKS_TAG_KEY_SIZE; + hkdfParams[idx++].uint32Param = outLen * BITS_PER_BYTE; + hkdfParams[idx].tag = HKS_TAG_KEY_ALIAS; + hkdfParams[idx++].blob = pskAliasBlob; + hkdfParams[idx].tag = HKS_TAG_EXT_INFO; + hkdfParams[idx++].blob = *extInfoBlob; + AddStorageExtParams(hkdfParams, keyParams->isDeStorage, &idx, keyParams->osAccountId); + int32_t res = ConstructParamSet(paramSet, hkdfParams, idx); + HcFree(hkdfParams); + return res; +} + +int32_t CheckPskParams(const KeyParams *keyParams, const Uint8Buff *pskKeyAlias, const Uint8Buff *outPsk) +{ + int32_t res = CheckKeyParams(keyParams); + if (res != HAL_SUCCESS) { + return res; + } + const Uint8Buff *inParams[] = { pskKeyAlias, outPsk }; + const char *paramTags[] = { "pskKeyAlias", "outPsk" }; + return BaseCheckParams(inParams, paramTags, CAL_ARRAY_SIZE(inParams)); +} + +int32_t GetExtInfoByParamSet(const struct HksParamSet *outParamSet, Uint8Buff *outExtInfo) +{ + struct HksParam *extInfoParam = NULL; + int32_t res = HksGetParam(outParamSet, HKS_TAG_EXT_INFO, &extInfoParam); + if (res != HKS_SUCCESS) { + LOGE("Failed to get extInfoParam!"); + return HAL_FAILED; + } + if (extInfoParam->blob.data == NULL || extInfoParam->blob.size == 0) { + LOGE("Extra info blob is null!"); + return HAL_FAILED; + } + uint8_t *tmpExtInfoVal = (uint8_t *)HcMalloc(extInfoParam->blob.size, 0); + if (tmpExtInfoVal == NULL) { + LOGE("Failed to alloc memory for extInfo value!"); + return HAL_ERR_BAD_ALLOC; + } + if (memcpy_s(tmpExtInfoVal, extInfoParam->blob.size, extInfoParam->blob.data, extInfoParam->blob.size) != EOK) { + LOGE("Failed to copy extInfo!"); + HcFree(tmpExtInfoVal); + return HAL_ERR_MEMORY_COPY; + } + outExtInfo->val = tmpExtInfoVal; + outExtInfo->length = extInfoParam->blob.size; + return HAL_SUCCESS; +} + +int32_t ConstructGetKeyExtInfoParamSet(const KeyParams *keyParams, struct HksParamSet **paramSet) +{ + uint32_t len = GetParamLen(keyParams->isDeStorage, 0); + if (len == 0) { + return HAL_SUCCESS; + } + struct HksParam *getParams = (struct HksParam *)HcMalloc(sizeof(struct HksParam) * len, 0); + if (getParams == NULL) { + LOGE("Malloc for getParams failed."); + return HAL_ERR_BAD_ALLOC; + } + uint32_t idx = 0; + AddStorageExtParams(getParams, keyParams->isDeStorage, &idx, keyParams->osAccountId); + int32_t res = ConstructParamSet(paramSet, getParams, idx); + HcFree(getParams); + if (res != HAL_SUCCESS) { + LOGE("Failed to construct get param set, res: %d", res); + } + return res; +} + +int32_t CheckAesGcmEncryptParam(const KeyParams *keyParams, const Uint8Buff *plain, + const GcmParam *encryptInfo, Uint8Buff *outCipher) +{ + int32_t res = CheckKeyParams(keyParams); + if (res != HAL_SUCCESS) { + return res; + } + const Uint8Buff *inParams[] = { plain, outCipher }; + const char* paramTags[] = { "plain", "outCipher" }; + res = BaseCheckParams(inParams, paramTags, CAL_ARRAY_SIZE(inParams)); + if (res != HAL_SUCCESS) { + return res; + } + + CHECK_PTR_RETURN_HAL_ERROR_CODE(encryptInfo, "encryptInfo"); + CHECK_PTR_RETURN_HAL_ERROR_CODE(encryptInfo->aad, "aad"); + CHECK_LEN_ZERO_RETURN_ERROR_CODE(encryptInfo->aadLen, "aadLen"); + CHECK_PTR_RETURN_HAL_ERROR_CODE(encryptInfo->nonce, "nonce"); + CHECK_LEN_LOWER_RETURN(encryptInfo->nonceLen, HKS_AE_NONCE_LEN, "nonceLen"); + CHECK_LEN_LOWER_RETURN(outCipher->length, plain->length + HKS_AE_TAG_LEN, "outCipher"); + + return HAL_SUCCESS; +} + +int32_t ConstructAesGcmEncryptParamSet(const GcmParam *encryptInfo, const KeyParams *keyParams, + struct HksParamSet **paramSet) +{ + struct HksBlob nonceBlob = { encryptInfo->nonceLen, encryptInfo->nonce }; + struct HksBlob aadBlob = { encryptInfo->aadLen, encryptInfo->aad }; + uint32_t len = GetParamLen(keyParams->isDeStorage, BASE_ENCRYPT_PARAMS_LEN); + struct HksParam *encryptParams = (struct HksParam *)HcMalloc(sizeof(struct HksParam) * len, 0); + if (encryptParams == NULL) { + LOGE("Malloc for encryptParams failed."); + return HAL_ERR_BAD_ALLOC; + } + uint32_t idx = 0; + encryptParams[idx].tag = HKS_TAG_PURPOSE; + encryptParams[idx++].uint32Param = HKS_KEY_PURPOSE_ENCRYPT; + encryptParams[idx].tag = HKS_TAG_ALGORITHM; + encryptParams[idx++].uint32Param = HKS_ALG_AES; + encryptParams[idx].tag = HKS_TAG_BLOCK_MODE; + encryptParams[idx++].uint32Param = HKS_MODE_GCM; + encryptParams[idx].tag = HKS_TAG_PADDING; + encryptParams[idx++].uint32Param = HKS_PADDING_NONE; + encryptParams[idx].tag = HKS_TAG_NONCE; + encryptParams[idx++].blob = nonceBlob; + encryptParams[idx].tag = HKS_TAG_ASSOCIATED_DATA; + encryptParams[idx++].blob = aadBlob; + encryptParams[idx].tag = HKS_TAG_IS_KEY_ALIAS; + encryptParams[idx++].boolParam = keyParams->keyBuff.isAlias; + AddStorageExtParams(encryptParams, keyParams->isDeStorage, &idx, keyParams->osAccountId); + int32_t res = ConstructParamSet(paramSet, encryptParams, idx); + HcFree(encryptParams); + if (res != HAL_SUCCESS) { + LOGE("Failed to construct encrypt param set, res: %d", res); + } + return res; +} + +int32_t CheckAesGcmDecryptParam(const KeyParams *keyParams, const Uint8Buff *cipher, + const GcmParam *decryptInfo, Uint8Buff *outPlain) +{ + int32_t res = CheckKeyParams(keyParams); + if (res != HAL_SUCCESS) { + return res; + } + const Uint8Buff *inParams[] = { cipher, outPlain }; + const char *paramTags[] = { "cipher", "outPlain" }; + res = BaseCheckParams(inParams, paramTags, CAL_ARRAY_SIZE(inParams)); + if (res != HAL_SUCCESS) { + return res; + } + + CHECK_PTR_RETURN_HAL_ERROR_CODE(decryptInfo, "decryptInfo"); + CHECK_PTR_RETURN_HAL_ERROR_CODE(decryptInfo->aad, "aad"); + CHECK_LEN_ZERO_RETURN_ERROR_CODE(decryptInfo->aadLen, "aadLen"); + CHECK_PTR_RETURN_HAL_ERROR_CODE(decryptInfo->nonce, "nonce"); + CHECK_LEN_LOWER_RETURN(decryptInfo->nonceLen, HKS_AE_NONCE_LEN, "nonceLen"); + CHECK_LEN_LOWER_RETURN(outPlain->length, cipher->length - HKS_AE_TAG_LEN, "outPlain"); + + return HAL_SUCCESS; +} + +int32_t ConstructAesGcmDecryptParamSet(const GcmParam *decryptInfo, const KeyParams *keyParams, + struct HksParamSet **paramSet) +{ + struct HksBlob nonceBlob = { decryptInfo->nonceLen, decryptInfo->nonce }; + struct HksBlob aadBlob = { decryptInfo->aadLen, decryptInfo->aad }; + uint32_t len = GetParamLen(keyParams->isDeStorage, BASE_DECRYPT_PARAMS_LEN); + struct HksParam *decryptParams = (struct HksParam *)HcMalloc(sizeof(struct HksParam) * len, 0); + if (decryptParams == NULL) { + LOGE("Malloc for decryptParams failed."); + return HAL_ERR_BAD_ALLOC; + } + uint32_t idx = 0; + decryptParams[idx].tag = HKS_TAG_PURPOSE; + decryptParams[idx++].uint32Param = HKS_KEY_PURPOSE_DECRYPT; + decryptParams[idx].tag = HKS_TAG_ALGORITHM; + decryptParams[idx++].uint32Param = HKS_ALG_AES; + decryptParams[idx].tag = HKS_TAG_BLOCK_MODE; + decryptParams[idx++].uint32Param = HKS_MODE_GCM; + decryptParams[idx].tag = HKS_TAG_PADDING; + decryptParams[idx++].uint32Param = HKS_PADDING_NONE; + decryptParams[idx].tag = HKS_TAG_NONCE; + decryptParams[idx++].blob = nonceBlob; + decryptParams[idx].tag = HKS_TAG_ASSOCIATED_DATA; + decryptParams[idx++].blob = aadBlob; + decryptParams[idx].tag = HKS_TAG_IS_KEY_ALIAS; + decryptParams[idx++].boolParam = keyParams->keyBuff.isAlias; + AddStorageExtParams(decryptParams, keyParams->isDeStorage, &idx, keyParams->osAccountId); + int32_t res = ConstructParamSet(paramSet, decryptParams, idx); + HcFree(decryptParams); + if (res != HAL_SUCCESS) { + LOGE("Failed to construct decrypt param set, res: %d", res); + } + return res; +} + +int32_t ConstructInitParamsP256(struct HksParamSet **initParamSet, const KeyParams *keyParams) +{ + uint32_t len = GetParamLen(keyParams->isDeStorage, BASE_AGREE_INIT_PARAMS_LEN); + struct HksParam *initParams = (struct HksParam *)HcMalloc(sizeof(struct HksParam) * len, 0); + if (initParams == NULL) { + LOGE("Malloc for initParams failed."); + return HAL_ERR_BAD_ALLOC; + } + uint32_t idx = 0; + initParams[idx].tag = HKS_TAG_ALGORITHM; + initParams[idx++].uint32Param = HKS_ALG_ECDH; + initParams[idx].tag = HKS_TAG_PURPOSE; + initParams[idx++].uint32Param = HKS_KEY_PURPOSE_AGREE; + initParams[idx].tag = HKS_TAG_KEY_SIZE; + initParams[idx++].uint32Param = HKS_ECC_KEY_SIZE_256; + AddStorageExtParams(initParams, keyParams->isDeStorage, &idx, keyParams->osAccountId); + int32_t res = ConstructParamSet(initParamSet, initParams, idx); + HcFree(initParams); + if (res != HAL_SUCCESS) { + LOGE("Construct init param set failed, res = %d", res); + } + return res; +} + +int32_t ConstructFinishParamsP256(struct HksParamSet **finishParamSet, const KeyParams *keyParams, + const struct HksBlob *sharedKeyAliasBlob) +{ + uint32_t len = GetParamLen(keyParams->isDeStorage, BASE_AGREE_FINISH_PARAMS_LEN); + struct HksParam *finishParams = (struct HksParam *)HcMalloc(sizeof(struct HksParam) * len, 0); + if (finishParams == NULL) { + LOGE("Malloc for finishParams failed."); + return HAL_ERR_BAD_ALLOC; + } + uint32_t idx = 0; + finishParams[idx].tag = HKS_TAG_KEY_STORAGE_FLAG; + finishParams[idx++].uint32Param = HKS_STORAGE_PERSISTENT; + finishParams[idx].tag = HKS_TAG_IS_KEY_ALIAS; + finishParams[idx++].boolParam = true; + finishParams[idx].tag = HKS_TAG_ALGORITHM; + finishParams[idx++].uint32Param = HKS_ALG_AES; + finishParams[idx].tag = HKS_TAG_KEY_SIZE; + finishParams[idx++].uint32Param = HKS_AES_KEY_SIZE_256; + finishParams[idx].tag = HKS_TAG_PURPOSE; + finishParams[idx++].uint32Param = HKS_KEY_PURPOSE_DERIVE; + finishParams[idx].tag = HKS_TAG_DIGEST; + finishParams[idx++].uint32Param = HKS_DIGEST_SHA256; + finishParams[idx].tag = HKS_TAG_KEY_ALIAS; + finishParams[idx++].blob = *sharedKeyAliasBlob; + AddStorageExtParams(finishParams, keyParams->isDeStorage, &idx, keyParams->osAccountId); + int32_t res = ConstructParamSet(finishParamSet, finishParams, idx); + HcFree(finishParams); + if (res != HAL_SUCCESS) { + LOGE("Construct finish param set failed, res = %d", res); + } + return res; +} + +int32_t ConstructAgreeWithStorageParams(struct HksParamSet **paramSet, uint32_t keyLen, Algorithm algo, + const KeyParams *priKeyParams, const KeyBuff *pubKeyBuff) +{ + struct HksBlob priKeyBlob = { priKeyParams->keyBuff.keyLen, priKeyParams->keyBuff.key }; + struct HksBlob pubKeyBlob = { pubKeyBuff->keyLen, pubKeyBuff->key }; + uint32_t len = GetParamLen(priKeyParams->isDeStorage, BASE_AGREE_WITH_STORAGE_PARAMS_LEN); + struct HksParam *agreeParams = (struct HksParam *)HcMalloc(sizeof(struct HksParam) * len, 0); + if (agreeParams == NULL) { + LOGE("Malloc for agreeParams failed."); + return HAL_ERR_BAD_ALLOC; + } + uint32_t idx = 0; + agreeParams[idx].tag = HKS_TAG_ALGORITHM; + agreeParams[idx++].uint32Param = HKS_ALG_AES; + agreeParams[idx].tag = HKS_TAG_KEY_SIZE; + agreeParams[idx++].uint32Param = keyLen * BITS_PER_BYTE; + agreeParams[idx].tag = HKS_TAG_PURPOSE; + agreeParams[idx++].uint32Param = HKS_KEY_PURPOSE_DERIVE; + agreeParams[idx].tag = HKS_TAG_DIGEST; + agreeParams[idx++].uint32Param = HKS_DIGEST_SHA256; + agreeParams[idx].tag = HKS_TAG_KEY_GENERATE_TYPE; + agreeParams[idx++].uint32Param = HKS_KEY_GENERATE_TYPE_AGREE; + agreeParams[idx].tag = HKS_TAG_AGREE_ALG; + agreeParams[idx++].uint32Param = g_algToHksAlgorithm[algo]; // only support HKS_ALG_ED25519 and HKS_ALG_X25519 + agreeParams[idx].tag = HKS_TAG_AGREE_PRIVATE_KEY_ALIAS; + agreeParams[idx++].blob = priKeyBlob; + agreeParams[idx].tag = HKS_TAG_AGREE_PUBLIC_KEY; + agreeParams[idx++].blob = pubKeyBlob; + agreeParams[idx].tag = HKS_TAG_AGREE_PUBLIC_KEY_IS_KEY_ALIAS; + agreeParams[idx++].boolParam = pubKeyBuff->isAlias; + AddStorageExtParams(agreeParams, priKeyParams->isDeStorage, &idx, priKeyParams->osAccountId); + int32_t res = ConstructParamSet(paramSet, agreeParams, idx); + HcFree(agreeParams); + if (res != HAL_SUCCESS) { + LOGE("Construct agree param set failed, res = %d", res); + } + return res; +} + +int32_t CheckAgreeWithStorageParams(const KeyParams *priKeyParams, const KeyBuff *pubKeyBuff, + uint32_t sharedKeyLen, const Uint8Buff *sharedKeyAlias) +{ + int32_t res = CheckKeyParams(priKeyParams); + if (res != HAL_SUCCESS) { + return res; + } + CHECK_PTR_RETURN_HAL_ERROR_CODE(pubKeyBuff, "pubKeyBuff"); + CHECK_PTR_RETURN_HAL_ERROR_CODE(pubKeyBuff->key, "pubKeyBuff->key"); + CHECK_LEN_ZERO_RETURN_ERROR_CODE(pubKeyBuff->keyLen, "pubKeyBuff->keyLen"); + CHECK_PTR_RETURN_HAL_ERROR_CODE(sharedKeyAlias, "sharedKeyAlias"); + CHECK_PTR_RETURN_HAL_ERROR_CODE(sharedKeyAlias->val, "sharedKeyAlias->val"); + CHECK_LEN_ZERO_RETURN_ERROR_CODE(sharedKeyAlias->length, "sharedKeyAlias->length"); + CHECK_LEN_ZERO_RETURN_ERROR_CODE(sharedKeyLen, "sharedKeyLen"); + return HAL_SUCCESS; +} + +void MoveSharedKeyToCe(const KeyParams *priKeyParams, const struct HksBlob *sharedKeyAlias) +{ + struct HksBlob priKeyBlob = { priKeyParams->keyBuff.keyLen, priKeyParams->keyBuff.key }; + MoveDeKeyToCe(priKeyParams->keyBuff.isAlias, priKeyParams->osAccountId, &priKeyBlob); + MoveDeKeyToCe(true, priKeyParams->osAccountId, sharedKeyAlias); +} + + +int32_t CheckAgreeParams(const KeyParams *priKeyParams, const KeyBuff *pubKey, const Uint8Buff *sharedKey) +{ + int32_t res = CheckKeyParams(priKeyParams); + if (res != HAL_SUCCESS) { + return res; + } + CHECK_PTR_RETURN_HAL_ERROR_CODE(pubKey, "pubKey"); + CHECK_PTR_RETURN_HAL_ERROR_CODE(pubKey->key, "pubKey->key"); + CHECK_LEN_ZERO_RETURN_ERROR_CODE(pubKey->keyLen, "pubKey->keyLen"); + CHECK_PTR_RETURN_HAL_ERROR_CODE(sharedKey, "sharedKey"); + CHECK_PTR_RETURN_HAL_ERROR_CODE(sharedKey->val, "sharedKey->val"); + CHECK_LEN_ZERO_RETURN_ERROR_CODE(sharedKey->length, "sharedKey->length"); + return HAL_SUCCESS; +} + + +int32_t ConstructAgreeParamSet(const KeyParams *keyParams, Algorithm algo, const Uint8Buff *sharedKey, + struct HksParamSet **paramSet) +{ + uint32_t len = GetParamLen(keyParams->isDeStorage, BASE_AGREE_PARAMS_LEN); + struct HksParam *agreeParams = (struct HksParam *)HcMalloc(sizeof(struct HksParam) * len, 0); + if (agreeParams == NULL) { + LOGE("Malloc for agreeParams failed."); + return HAL_ERR_BAD_ALLOC; + } + uint32_t idx = 0; + agreeParams[idx].tag = HKS_TAG_ALGORITHM; + agreeParams[idx++].uint32Param = g_algToHksAlgorithm[algo]; // only support HKS_ALG_X25519 now + agreeParams[idx].tag = HKS_TAG_KEY_SIZE; + agreeParams[idx++].uint32Param = sharedKey->length * BITS_PER_BYTE; + agreeParams[idx].tag = HKS_TAG_IS_KEY_ALIAS; + agreeParams[idx++].boolParam = keyParams->keyBuff.isAlias; + AddStorageExtParams(agreeParams, keyParams->isDeStorage, &idx, keyParams->osAccountId); + int32_t res = ConstructParamSet(paramSet, agreeParams, idx); + HcFree(agreeParams); + if (res != HAL_SUCCESS) { + LOGE("Construct agree param set failed, res = %d", res); + } + return res; +} + +int32_t ConstructGenerateKeyPairWithStorageParams(struct HksParamSet **paramSet, Algorithm algo, + uint32_t keyLen, KeyPurpose purpose, const KeyParams *authIdParams) +{ + struct HksBlob authIdBlob = { authIdParams->keyBuff.keyLen, authIdParams->keyBuff.key }; + uint32_t len = GetParamLen(authIdParams->isDeStorage, BASE_GENERATE_KEY_PAIR_PARAMS_LEN); + struct HksParam *generateParams = (struct HksParam *)HcMalloc(sizeof(struct HksParam) * len, 0); + if (generateParams == NULL) { + LOGE("Malloc for generateParams failed."); + return HAL_ERR_BAD_ALLOC; + } + uint32_t idx = 0; + generateParams[idx].tag = HKS_TAG_ALGORITHM; + generateParams[idx++].uint32Param = g_algToHksAlgorithm[algo]; + generateParams[idx].tag = HKS_TAG_KEY_STORAGE_FLAG; + generateParams[idx++].uint32Param = HKS_STORAGE_PERSISTENT; + generateParams[idx].tag = HKS_TAG_PURPOSE; + generateParams[idx++].uint32Param = g_purposeToHksKeyPurpose[purpose]; + generateParams[idx].tag = HKS_TAG_KEY_SIZE; + generateParams[idx++].uint32Param = keyLen * BITS_PER_BYTE; + generateParams[idx].tag = HKS_TAG_KEY_AUTH_ID; + generateParams[idx++].blob = authIdBlob; + generateParams[idx].tag = HKS_TAG_DIGEST; + generateParams[idx++].uint32Param = HKS_DIGEST_SHA256; + AddStorageExtParams(generateParams, authIdParams->isDeStorage, &idx, authIdParams->osAccountId); + int32_t res = ConstructParamSet(paramSet, generateParams, idx); + HcFree(generateParams); + if (res != HAL_SUCCESS) { + LOGE("Construct generate key pair param set failed, res = %d", res); + } + return res; +} + +int32_t CheckGenerateKeyPairParams(const KeyParams *keyParams, const ExtraInfo *exInfo, uint32_t keyLen) +{ + int32_t res = CheckKeyParams(keyParams); + if (res != HAL_SUCCESS) { + return res; + } + CHECK_PTR_RETURN_HAL_ERROR_CODE(exInfo, "exInfo"); + CHECK_PTR_RETURN_HAL_ERROR_CODE(exInfo->authId.val, "authId->val"); + CHECK_LEN_ZERO_RETURN_ERROR_CODE(exInfo->authId.length, "authId->length"); + CHECK_LEN_ZERO_RETURN_ERROR_CODE(keyLen, "keyLen"); + return HAL_SUCCESS; +} + +int32_t ConstructGenerateKeyPairParams(struct HksParamSet **paramSet, Algorithm algo, uint32_t keyLen) +{ + struct HksParam keyParam[] = { + { + .tag = HKS_TAG_KEY_STORAGE_FLAG, + .uint32Param = HKS_STORAGE_TEMP + }, { + .tag = HKS_TAG_ALGORITHM, + .uint32Param = g_algToHksAlgorithm[algo] + }, { + .tag = HKS_TAG_KEY_SIZE, + .uint32Param = keyLen * BITS_PER_BYTE + }, { + .tag = HKS_TAG_IS_KEY_ALIAS, + .uint32Param = false + } + }; + + int32_t res = ConstructParamSet(paramSet, keyParam, CAL_ARRAY_SIZE(keyParam)); + if (res != HAL_SUCCESS) { + LOGE("Construct param set failed, res = %d", res); + return res; + } + return res; +} + +int32_t ConstructExportParams(bool isDeStorage, int32_t osAccountId, struct HksParamSet **paramSet) +{ + uint32_t len = GetParamLen(isDeStorage, 0); + if (len == 0) { + return HAL_SUCCESS; + } + struct HksParam *exportParams = (struct HksParam *)HcMalloc(sizeof(struct HksParam) * len, 0); + if (exportParams == NULL) { + LOGE("Malloc for exportParams failed."); + return HAL_ERR_BAD_ALLOC; + } + uint32_t idx = 0; + AddStorageExtParams(exportParams, isDeStorage, &idx, osAccountId); + int32_t res = ConstructParamSet(paramSet, exportParams, idx); + HcFree(exportParams); + if (res != HAL_SUCCESS) { + LOGE("Failed to construct export param set, res: %d", res); + } + return res; +} + +int32_t CheckExportParams(const KeyParams *keyParams, const Uint8Buff *outPubKey) +{ + int32_t res = CheckKeyParams(keyParams); + if (res != HAL_SUCCESS) { + return res; + } + CHECK_PTR_RETURN_HAL_ERROR_CODE(outPubKey, "outPubKey"); + CHECK_PTR_RETURN_HAL_ERROR_CODE(outPubKey->val, "outPubKey->val"); + CHECK_LEN_ZERO_RETURN_ERROR_CODE(outPubKey->length, "outPubKey->length"); + return HAL_SUCCESS; +} + +int32_t ConstructSignParams(bool isDeStorage, int32_t osAccountId, struct HksParamSet **paramSet, + Algorithm algo) +{ + uint32_t len = GetParamLen(isDeStorage, BASE_SIGN_PARAMS_LEN); + struct HksParam *signParams = (struct HksParam *)HcMalloc(sizeof(struct HksParam) * len, 0); + if (signParams == NULL) { + LOGE("Malloc for signParams failed."); + return HAL_ERR_BAD_ALLOC; + } + uint32_t idx = 0; + signParams[idx].tag = HKS_TAG_PURPOSE; + signParams[idx++].uint32Param = HKS_KEY_PURPOSE_SIGN; + signParams[idx].tag = HKS_TAG_ALGORITHM; + signParams[idx++].uint32Param = g_algToHksAlgorithm[algo]; // only support HKS_ALG_ED25519 and HKS_ALG_ECC. + signParams[idx].tag = HKS_TAG_DIGEST; + signParams[idx++].uint32Param = HKS_DIGEST_SHA256; + AddStorageExtParams(signParams, isDeStorage, &idx, osAccountId); + int32_t res = ConstructParamSet(paramSet, signParams, idx); + HcFree(signParams); + if (res != HAL_SUCCESS) { + LOGE("Construct sign param set failed, res = %d", res); + } + return res; +} + +int32_t CheckSignParams(const KeyParams *keyParams, const Uint8Buff *message, + const Uint8Buff *outSignature) +{ + int32_t res = CheckKeyParams(keyParams); + if (res != HAL_SUCCESS) { + return res; + } + const Uint8Buff *inParams[] = { message, outSignature }; + const char *paramTags[] = { "message", "outSignature" }; + return BaseCheckParams(inParams, paramTags, CAL_ARRAY_SIZE(inParams)); +} + +int32_t ConstructVerifyParams(struct HksParamSet **paramSet, const KeyParams *keyParams, Algorithm algo) +{ + uint32_t len = GetParamLen(keyParams->isDeStorage, BASE_VERIFY_PARAMS_LEN); + struct HksParam *verifyParams = (struct HksParam *)HcMalloc(sizeof(struct HksParam) * len, 0); + if (verifyParams == NULL) { + LOGE("Malloc for verifyParams failed."); + return HAL_ERR_BAD_ALLOC; + } + uint32_t idx = 0; + verifyParams[idx].tag = HKS_TAG_PURPOSE; + verifyParams[idx++].uint32Param = HKS_KEY_PURPOSE_VERIFY; + verifyParams[idx].tag = HKS_TAG_ALGORITHM; + verifyParams[idx++].uint32Param = g_algToHksAlgorithm[algo]; // only support HKS_ALG_ED25519 and HKS_ALG_ECC. + verifyParams[idx].tag = HKS_TAG_IS_KEY_ALIAS; + verifyParams[idx++].boolParam = keyParams->keyBuff.isAlias; + verifyParams[idx].tag = HKS_TAG_DIGEST; + verifyParams[idx++].uint32Param = HKS_DIGEST_SHA256; + AddStorageExtParams(verifyParams, keyParams->isDeStorage, &idx, keyParams->osAccountId); + int32_t res = ConstructParamSet(paramSet, verifyParams, idx); + HcFree(verifyParams); + if (res != HAL_SUCCESS) { + LOGE("Construct verify param set failed, res = %d", res); + } + return res; +} + +int32_t CheckVerifyParams(const KeyParams *keyParams, const Uint8Buff *message, + const Uint8Buff *signature) +{ + int32_t res = CheckKeyParams(keyParams); + if (res != HAL_SUCCESS) { + return res; + } + const Uint8Buff *inParams[] = { message, signature }; + const char *paramTags[] = { "message", "signature" }; + return BaseCheckParams(inParams, paramTags, CAL_ARRAY_SIZE(inParams)); +} + +int32_t ConstructImportPublicKeyParams(struct HksParamSet **paramSet, Algorithm algo, uint32_t keyLen, + const KeyParams *authIdParams, const union KeyRoleInfoUnion *roleInfoUnion) +{ + if (g_algToHksAlgorithm[algo] == HKS_ALG_ECC) { + keyLen = ECC_PK_LEN; + } + struct HksBlob authIdBlob = { authIdParams->keyBuff.keyLen, authIdParams->keyBuff.key }; + uint32_t len = GetParamLen(authIdParams->isDeStorage, BASE_IMPORT_PUB_KEY_PARAMS_LEN); + struct HksParam *importParams = (struct HksParam *)HcMalloc(sizeof(struct HksParam) * len, 0); + if (importParams == NULL) { + LOGE("Malloc for importParams failed."); + return HAL_ERR_BAD_ALLOC; + } + uint32_t idx = 0; + importParams[idx].tag = HKS_TAG_ALGORITHM; + importParams[idx++].uint32Param = g_algToHksAlgorithm[algo]; + importParams[idx].tag = HKS_TAG_KEY_SIZE; + importParams[idx++].uint32Param = keyLen * BITS_PER_BYTE; + importParams[idx].tag = HKS_TAG_PADDING; + importParams[idx++].uint32Param = HKS_PADDING_NONE; + importParams[idx].tag = HKS_TAG_KEY_AUTH_ID; + importParams[idx++].blob = authIdBlob; + importParams[idx].tag = HKS_TAG_IS_ALLOWED_WRAP; + importParams[idx++].boolParam = true; + importParams[idx].tag = HKS_TAG_PURPOSE; + importParams[idx++].uint32Param = HKS_KEY_PURPOSE_VERIFY; + importParams[idx].tag = HKS_TAG_KEY_ROLE; + importParams[idx++].uint32Param = roleInfoUnion->roleInfo; + importParams[idx].tag = HKS_TAG_DIGEST; + importParams[idx++].uint32Param = HKS_DIGEST_SHA256; + AddStorageExtParams(importParams, authIdParams->isDeStorage, &idx, authIdParams->osAccountId); + int32_t res = ConstructParamSet(paramSet, importParams, idx); + HcFree(importParams); + if (res != HAL_SUCCESS) { + LOGE("Construct import param set failed, res = %d", res); + } + return res; +} + +int32_t CheckImportPubKeyParams(const KeyParams *keyParams, const Uint8Buff *pubKey, + const ExtraInfo *exInfo) +{ + int32_t res = CheckKeyParams(keyParams); + if (res != HAL_SUCCESS) { + return res; + } + CHECK_PTR_RETURN_HAL_ERROR_CODE(pubKey, "pubKey"); + CHECK_PTR_RETURN_HAL_ERROR_CODE(pubKey->val, "pubKey->val"); + CHECK_LEN_ZERO_RETURN_ERROR_CODE(pubKey->length, "pubKey->length"); + CHECK_PTR_RETURN_HAL_ERROR_CODE(exInfo, "exInfo"); + CHECK_PTR_RETURN_HAL_ERROR_CODE(exInfo->authId.val, "authId->val"); + CHECK_LEN_ZERO_RETURN_ERROR_CODE(exInfo->authId.length, "authId->length"); + CHECK_LEN_HIGHER_RETURN(exInfo->pairType, PAIR_TYPE_END - 1, "pairType"); + return HAL_SUCCESS; +} + +bool CheckBigNumCompareParams(const Uint8Buff *a, const Uint8Buff *b, int *res) +{ + if ((a == NULL || a->val == NULL) && (b == NULL || b->val == NULL)) { + *res = 0; // a = b + return false; + } + if ((a == NULL || a->val == NULL) && (b != NULL && b->val != NULL)) { + *res = 1; // a < b + return false; + } + if ((a != NULL && a->val != NULL) && (b == NULL || b->val == NULL)) { + *res = -1; // a > b + return false; + } + return true; +} + +static int32_t InitImportParam(const KeyParams *keyParams, const ExtraInfo *exInfo, struct HksParam **importParam) +{ + if (exInfo != NULL) { + CHECK_PTR_RETURN_HAL_ERROR_CODE(exInfo->authId.val, "authId"); + CHECK_LEN_ZERO_RETURN_ERROR_CODE(exInfo->authId.length, "authId"); + CHECK_LEN_HIGHER_RETURN(exInfo->pairType, PAIR_TYPE_END - 1, "pairType"); + } + uint32_t baseLen = ((exInfo == NULL) ? BASE_IMPORT_PARAMS_LEN : (BASE_IMPORT_PARAMS_LEN + EXT_IMPORT_PARAMS_LEN)); + uint32_t len = GetParamLen(keyParams->isDeStorage, baseLen); + *importParam = (struct HksParam *)HcMalloc(sizeof(struct HksParam) * len, 0); + if (*importParam == NULL) { + LOGE("Malloc for importParam failed."); + return HAL_ERR_BAD_ALLOC; + } + return HAL_SUCCESS; +} + +int32_t ConstructImportSymmetricKeyParam(struct HksParamSet **paramSet, const KeyParams *keyParams, + uint32_t keyLen, KeyPurpose purpose, const ExtraInfo *exInfo) +{ + struct HksParam *importParam = NULL; + int32_t res = InitImportParam(keyParams, exInfo, &importParam); + if (res != HAL_SUCCESS) { + return res; + } + uint32_t idx = 0; + if (exInfo != NULL) { + struct HksBlob authIdBlob = { 0, NULL }; + union KeyRoleInfoUnion roleInfoUnion; + (void)memset_s(&roleInfoUnion, sizeof(roleInfoUnion), 0, sizeof(roleInfoUnion)); + authIdBlob.size = exInfo->authId.length; + authIdBlob.data = exInfo->authId.val; + roleInfoUnion.roleInfoStruct.userType = (uint8_t)exInfo->userType; + roleInfoUnion.roleInfoStruct.pairType = (uint8_t)exInfo->pairType; + importParam[idx].tag = HKS_TAG_KEY_AUTH_ID; + importParam[idx++].blob = authIdBlob; + importParam[idx].tag = HKS_TAG_KEY_ROLE; + importParam[idx++].uint32Param = roleInfoUnion.roleInfo; + } + + importParam[idx].tag = HKS_TAG_ALGORITHM; + importParam[idx++].uint32Param = HKS_ALG_AES; + importParam[idx].tag = HKS_TAG_KEY_SIZE; + importParam[idx++].uint32Param = keyLen * BITS_PER_BYTE; + importParam[idx].tag = HKS_TAG_PADDING; + importParam[idx++].uint32Param = HKS_PADDING_NONE; + importParam[idx].tag = HKS_TAG_IS_ALLOWED_WRAP; + importParam[idx++].boolParam = false; + importParam[idx].tag = HKS_TAG_PURPOSE; + importParam[idx++].uint32Param = g_purposeToHksKeyPurpose[purpose]; + importParam[idx].tag = HKS_TAG_BLOCK_MODE; + importParam[idx++].uint32Param = HKS_MODE_GCM; + importParam[idx].tag = HKS_TAG_DIGEST; + importParam[idx++].uint32Param = HKS_DIGEST_SHA256; + AddStorageExtParams(importParam, keyParams->isDeStorage, &idx, keyParams->osAccountId); + res = ConstructParamSet(paramSet, importParam, idx); + HcFree(importParam); + return res; +} + +int32_t CheckImportSymmetricKeyParams(const KeyParams *keyParams, const Uint8Buff *authToken) +{ + int32_t res = CheckKeyParams(keyParams); + if (res != HAL_SUCCESS) { + return res; + } + const Uint8Buff *inParams[] = { authToken }; + const char *paramTags[] = { "authToken" }; + return BaseCheckParams(inParams, paramTags, CAL_ARRAY_SIZE(inParams)); +} diff --git a/deps_adapter/key_management_adapter/interfaces/alg_defs.h b/deps_adapter/key_management_adapter/interfaces/alg_defs.h index 7a8138b929e2c09e96b59350d76cfc2d5cce7d05..15f70630e80e69eec08f75e9509a9b02aaee0249 100644 --- a/deps_adapter/key_management_adapter/interfaces/alg_defs.h +++ b/deps_adapter/key_management_adapter/interfaces/alg_defs.h @@ -49,7 +49,8 @@ typedef enum { KEY_PURPOSE_MAC = 0, KEY_PURPOSE_DERIVE = 1, KEY_PURPOSE_SIGN_VERIFY = 2, - KEY_PURPOSE_KEY_AGREE = 3 + KEY_PURPOSE_KEY_AGREE = 3, + KEY_PURPOSE_KEY_ENCRYPT = 4, } KeyPurpose; typedef enum { diff --git a/deps_adapter/key_management_adapter/interfaces/huks_adapter.h b/deps_adapter/key_management_adapter/interfaces/huks_adapter.h index 21524f2730d2e7c7114afaac11954ab99db5475c..edc7431a1a20ae26afc01688742f479a19dbd42d 100644 --- a/deps_adapter/key_management_adapter/interfaces/huks_adapter.h +++ b/deps_adapter/key_management_adapter/interfaces/huks_adapter.h @@ -17,65 +17,6 @@ #define HUKS_ADAPTER_H #include "alg_defs.h" -#include "hal_error.h" -#include "hc_types.h" - -#define BITS_PER_BYTE 8 -#define ECC_PK_LEN 32 - -#define CAL_ARRAY_SIZE(arr) ((sizeof(arr)) / (sizeof((arr)[0]))) - -#define CHECK_LEN_ZERO_RETURN_ERROR_CODE(len, paramTag) \ - do { \ - if ((len) == 0) { \ - LOGE("%s is invalid length.", (paramTag)); \ - return HAL_ERR_INVALID_LEN; \ - } \ - } while (0) - -#define CHECK_PTR_RETURN_HAL_ERROR_CODE(ptr, paramTag) \ - do { \ - if ((ptr) == NULL) { \ - LOGE("%s is null.", (paramTag)); \ - return HAL_ERR_NULL_PTR; \ - } \ - } while (0) - -#define CHECK_LEN_LOWER_RETURN(len, min, paramTag) \ - do { \ - if ((len) < (min)) { \ - LOGE("%s is invalid length.", (paramTag)); \ - return HAL_ERR_INVALID_LEN; \ - } \ - } while (0) - -#define CHECK_LEN_HIGHER_RETURN(len, max, paramTag) \ - do { \ - if ((len) > (max)) { \ - LOGE("%s is invalid length.", (paramTag)); \ - return HAL_ERR_INVALID_LEN; \ - } \ - } while (0) - -#define CHECK_LEN_EQUAL_RETURN(len, value, paramTag) \ - do { \ - if ((len) != (value)) { \ - LOGE("%s is invalid length.", (paramTag)); \ - return HAL_ERR_INVALID_LEN; \ - } \ - } while (0) - -struct KeyRoleInfo { - uint8_t userType; - uint8_t pairType; - uint8_t reserved1; - uint8_t reserved2; -}; - -union KeyRoleInfoUnion { - struct KeyRoleInfo roleInfoStruct; - uint32_t roleInfo; -}; #ifdef __cplusplus extern "C" { diff --git a/deps_adapter/key_management_adapter/interfaces/huks_adapter_utils.h b/deps_adapter/key_management_adapter/interfaces/huks_adapter_utils.h new file mode 100644 index 0000000000000000000000000000000000000000..f20dd438ed0d5d27bcd084ff44482f92bf984e8b --- /dev/null +++ b/deps_adapter/key_management_adapter/interfaces/huks_adapter_utils.h @@ -0,0 +1,158 @@ +/* + * Copyright (C) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ALG_LOADER_H +#define ALG_LOADER_H + +#include "alg_defs.h" +#include "hks_api.h" +#include "hks_param.h" +#include "hks_type.h" +#include "hal_error.h" +#include "hc_types.h" + +#define BITS_PER_BYTE 8 +#define ECC_PK_LEN 32 + +#define CAL_ARRAY_SIZE(arr) ((sizeof(arr)) / (sizeof((arr)[0]))) + +#define CHECK_LEN_ZERO_RETURN_ERROR_CODE(len, paramTag) \ + do { \ + if ((len) == 0) { \ + LOGE("%s is invalid length.", (paramTag)); \ + return HAL_ERR_INVALID_LEN; \ + } \ + } while (0) + +#define CHECK_PTR_RETURN_HAL_ERROR_CODE(ptr, paramTag) \ + do { \ + if ((ptr) == NULL) { \ + LOGE("%s is null.", (paramTag)); \ + return HAL_ERR_NULL_PTR; \ + } \ + } while (0) + +#define CHECK_LEN_LOWER_RETURN(len, min, paramTag) \ + do { \ + if ((len) < (min)) { \ + LOGE("%s is invalid length.", (paramTag)); \ + return HAL_ERR_INVALID_LEN; \ + } \ + } while (0) + +#define CHECK_LEN_HIGHER_RETURN(len, max, paramTag) \ + do { \ + if ((len) > (max)) { \ + LOGE("%s is invalid length.", (paramTag)); \ + return HAL_ERR_INVALID_LEN; \ + } \ + } while (0) + +#define CHECK_LEN_EQUAL_RETURN(len, value, paramTag) \ + do { \ + if ((len) != (value)) { \ + LOGE("%s is invalid length.", (paramTag)); \ + return HAL_ERR_INVALID_LEN; \ + } \ + } while (0) + +struct KeyRoleInfo { + uint8_t userType; + uint8_t pairType; + uint8_t reserved1; + uint8_t reserved2; +}; + +union KeyRoleInfoUnion { + struct KeyRoleInfo roleInfoStruct; + uint32_t roleInfo; +}; + +#ifdef __cplusplus +extern "C" { +#endif + +int32_t CheckKeyParams(const KeyParams *keyParams); +void FreeParamSet(struct HksParamSet *paramSet); +int32_t ConstructParamSet(struct HksParamSet **out, const struct HksParam *inParam, + const uint32_t inParamNum); +int32_t BigNumExpMod(const Uint8Buff *base, const Uint8Buff *exp, const char *bigNumHex, + Uint8Buff *outNum); +void MoveDeKeyToCe(bool isKeyAlias, int32_t osAccountId, const struct HksBlob *keyAliasBlob); +int32_t ConstructCheckParamSet(bool isDeStorage, int32_t osAccountId, struct HksParamSet **paramSet); +int32_t ConstructDeleteParamSet(bool isDeStorage, int32_t osAccountId, struct HksParamSet **paramSet); +int32_t ConstructHmacParamSet(bool isDeStorage, int32_t osAccountId, bool isAlias, + struct HksParamSet **hmacParamSet); +int32_t CheckHmacParams(const KeyParams *keyParams, const Uint8Buff *message, const Uint8Buff *outHmac); +int32_t ConstructDeriveParamSet(const KeyParams *keyParams, const Uint8Buff *message, + struct HksParamSet **deriveParamSet); +int32_t ConstructFinishParamSet(const KeyParams *keyParams, struct HksParamSet **finishParamSet); +int32_t CheckHmacWithThreeStageParams(const KeyParams *keyParams, const Uint8Buff *message, + const Uint8Buff *outHmac); +int32_t ConstructHkdfParamSet(bool isDeStorage, const KeyParams *keyParams, const Uint8Buff *salt, + const Uint8Buff *keyInfo, struct HksParamSet **paramSet); +int32_t CheckHkdfParams(const KeyParams *keyParams, const Uint8Buff *salt, const Uint8Buff *outHkdf); +int32_t ConstructPseudonymParamSet(const KeyParams *keyParams, const Uint8Buff *pskKeyAlias, + const struct HksBlob *extInfoBlob, uint32_t outLen, struct HksParamSet **paramSet); +int32_t CheckPskParams(const KeyParams *keyParams, const Uint8Buff *pskKeyAlias, const Uint8Buff *outPsk); +int32_t GetExtInfoByParamSet(const struct HksParamSet *outParamSet, Uint8Buff *outExtInfo); +int32_t ConstructGetKeyExtInfoParamSet(const KeyParams *keyParams, struct HksParamSet **paramSet); +int32_t CheckAesGcmEncryptParam(const KeyParams *keyParams, const Uint8Buff *plain, + const GcmParam *encryptInfo, Uint8Buff *outCipher); +int32_t ConstructAesGcmEncryptParamSet(const GcmParam *encryptInfo, const KeyParams *keyParams, + struct HksParamSet **paramSet); +int32_t CheckAesGcmDecryptParam(const KeyParams *keyParams, const Uint8Buff *cipher, + const GcmParam *decryptInfo, Uint8Buff *outPlain); +int32_t ConstructAesGcmDecryptParamSet(const GcmParam *decryptInfo, const KeyParams *keyParams, + struct HksParamSet **paramSet); +int32_t ConstructInitParamsP256(struct HksParamSet **initParamSet, const KeyParams *keyParams); +int32_t ConstructFinishParamsP256(struct HksParamSet **finishParamSet, const KeyParams *keyParams, + const struct HksBlob *sharedKeyAliasBlob); +int32_t ConstructAgreeWithStorageParams(struct HksParamSet **paramSet, uint32_t keyLen, Algorithm algo, + const KeyParams *priKeyParams, const KeyBuff *pubKeyBuff); +int32_t CheckAgreeWithStorageParams(const KeyParams *priKeyParams, const KeyBuff *pubKeyBuff, + uint32_t sharedKeyLen, const Uint8Buff *sharedKeyAlias); +void MoveSharedKeyToCe(const KeyParams *priKeyParams, const struct HksBlob *sharedKeyAlias); +int32_t CheckAgreeParams(const KeyParams *priKeyParams, const KeyBuff *pubKey, const Uint8Buff *sharedKey); +int32_t ConstructAgreeParamSet(const KeyParams *keyParams, Algorithm algo, const Uint8Buff *sharedKey, + struct HksParamSet **paramSet); +int32_t ConstructGenerateKeyPairWithStorageParams(struct HksParamSet **paramSet, Algorithm algo, + uint32_t keyLen, KeyPurpose purpose, const KeyParams *authIdParams); +int32_t CheckGenerateKeyPairParams(const KeyParams *keyParams, const ExtraInfo *exInfo, uint32_t keyLen); +int32_t ConstructGenerateKeyPairParams(struct HksParamSet **paramSet, Algorithm algo, uint32_t keyLen); +int32_t ConstructExportParams(bool isDeStorage, int32_t osAccountId, struct HksParamSet **paramSet); +int32_t CheckExportParams(const KeyParams *keyParams, const Uint8Buff *outPubKey); +int32_t ConstructSignParams(bool isDeStorage, int32_t osAccountId, struct HksParamSet **paramSet, + Algorithm algo); +int32_t CheckSignParams(const KeyParams *keyParams, const Uint8Buff *message, + const Uint8Buff *outSignature); +int32_t ConstructVerifyParams(struct HksParamSet **paramSet, const KeyParams *keyParams, Algorithm algo); +int32_t CheckVerifyParams(const KeyParams *keyParams, const Uint8Buff *message, + const Uint8Buff *signature); +int32_t ConstructImportPublicKeyParams(struct HksParamSet **paramSet, Algorithm algo, uint32_t keyLen, + const KeyParams *authIdParams, const union KeyRoleInfoUnion *roleInfoUnion); +int32_t CheckImportPubKeyParams(const KeyParams *keyParams, const Uint8Buff *pubKey, + const ExtraInfo *exInfo); +bool CheckBigNumCompareParams(const Uint8Buff *a, const Uint8Buff *b, int *res); +int32_t ConstructImportSymmetricKeyParam(struct HksParamSet **paramSet, const KeyParams *keyParams, + uint32_t keyLen, KeyPurpose purpose, const ExtraInfo *exInfo); +int32_t CheckImportSymmetricKeyParams(const KeyParams *keyParams, const Uint8Buff *authToken); + + +#ifdef __cplusplus +} +#endif + +#endif \ No newline at end of file diff --git a/deps_adapter/os_adapter/interfaces/hal_error.h b/deps_adapter/os_adapter/interfaces/hal_error.h index c5156ac7afcced5986172c24967ce0bd6d06ad6b..c4ef82e038e3000c62ee2b44d729a8dd5d7504d6 100644 --- a/deps_adapter/os_adapter/interfaces/hal_error.h +++ b/deps_adapter/os_adapter/interfaces/hal_error.h @@ -37,5 +37,6 @@ enum { HAL_ERR_NOT_SUPPORTED = -22, HAL_ERR_MBEDTLS = -23, HAL_ERR_BASE64_FORMAT = -24, + HAL_ERR_KEY_NOT_EXIST = -25, }; #endif \ No newline at end of file diff --git a/frameworks/inc/ipc_sdk.h b/frameworks/inc/ipc_sdk.h index 98f4a124af67e418cee8a23c7eb68210e9df2a6a..21791032f428851792f6817a9169997b3c15f4b3 100644 --- a/frameworks/inc/ipc_sdk.h +++ b/frameworks/inc/ipc_sdk.h @@ -59,6 +59,11 @@ extern "C" { #define PARAM_TYPE_REQ_JSON 34 #define PARAM_TYPE_PSEUDONYM_ID 35 #define PARAM_TYPE_INDEX_KEY 36 +#define PARAM_TYPE_CRED_ID 37 +#define PARAM_TYPE_CRED_INFO 38 +#define PARAM_TYPE_CRED_INFO_LIST 39 +#define PARAM_TYPE_REQUEST_PARAMS 40 +#define PARAM_TYPE_CRED_VAL 41 enum { IPC_CALL_ID_REG_CB = 1, @@ -93,6 +98,16 @@ enum { IPC_CALL_ID_DA_PROC_DATA, IPC_CALL_ID_DA_AUTH_DEVICE, IPC_CALL_ID_DA_CANCEL_REQUEST, + IPC_CALL_ID_CM_ADD_CREDENTIAL, + IPC_CALL_ID_CM_REG_LISTENER, + IPC_CALL_ID_CM_UNREG_LISTENER, + IPC_CALL_ID_CM_EXPORT_CREDENTIAL, + IPC_CALL_ID_CM_QUERY_CREDENTIAL_BY_PARAMS, + IPC_CALL_ID_CM_QUERY_CREDENTIAL_BY_CRED_ID, + IPC_CALL_ID_CM_DEL_CREDENTIAL, + IPC_CALL_ID_CM_UPDATE_CRED_INFO, + IPC_CALL_ID_CA_AUTH_DEVICE, + IPC_CALL_ID_CA_PROCESS_CRED_DATA, }; #ifdef __cplusplus diff --git a/frameworks/inc/ipc_service_common.h b/frameworks/inc/ipc_service_common.h index a5450c26cb546f15dfaaa415176b981e9c163447..d65495282e0330911d4e7d6902be338b44ca956b 100644 --- a/frameworks/inc/ipc_service_common.h +++ b/frameworks/inc/ipc_service_common.h @@ -60,6 +60,17 @@ int32_t IpcServiceDaAuthDevice(const IpcDataInfo *ipcParams, int32_t paramNum, u int32_t IpcServiceDaProcessData(const IpcDataInfo *ipcParams, int32_t paramNum, uintptr_t outCache); int32_t IpcServiceDaCancelRequest(const IpcDataInfo *ipcParams, int32_t paramNum, uintptr_t outCache); +// Credential Manager Interfaces - IS +int32_t IpcServiceCmAddCredential(const IpcDataInfo *ipcParams, int32_t paramNum, uintptr_t outCache); +int32_t IpcServiceCmRegCredChangeListener(const IpcDataInfo *ipcParams, int32_t paramNum, uintptr_t outCache); +int32_t IpcServiceCmUnRegCredChangeListener(const IpcDataInfo *ipcParams, int32_t paramNum, uintptr_t outCache); +int32_t IpcServiceCmExportCredential(const IpcDataInfo *ipcParams, int32_t paramNum, uintptr_t outCache); +int32_t IpcServiceCmQueryCredentialByParams(const IpcDataInfo *ipcParams, int32_t paramNum, uintptr_t outCache); +int32_t IpcServiceCmQueryCredentialByCredId(const IpcDataInfo *ipcParams, int32_t paramNum, uintptr_t outCache); +int32_t IpcServiceCmDeleteCredential(const IpcDataInfo *ipcParams, int32_t paramNum, uintptr_t outCache); +int32_t IpcServiceCmUpdateCredInfo(const IpcDataInfo *ipcParams, int32_t paramNum, uintptr_t outCache); +int32_t IpcServiceCaAuthDevice(const IpcDataInfo *ipcParams, int32_t paramNum, uintptr_t outCache); +int32_t IpcServiceCaProcessCredData(const IpcDataInfo *ipcParams, int32_t paramNum, uintptr_t outCache); int32_t MainRescInit(void); void DeMainRescInit(void); diff --git a/frameworks/inc/standard/ipc_adapt.h b/frameworks/inc/standard/ipc_adapt.h index 06b1cb33e61c53cdf5c0ea6c4a93680215c268ed..e6aca4ae88328524810a3b7f21060982f3badcaa 100755 --- a/frameworks/inc/standard/ipc_adapt.h +++ b/frameworks/inc/standard/ipc_adapt.h @@ -27,6 +27,8 @@ extern "C" { #define CB_TYPE_DEV_AUTH 1 #define CB_TYPE_TMP_DEV_AUTH 2 #define CB_TYPE_LISTENER 3 +#define CB_TYPE_CRED_LISTENER 4 +#define CB_TYPE_CRED_DEV_AUTH 5 typedef struct { int32_t type; @@ -48,6 +50,9 @@ enum { CB_ID_ON_DEV_UNTRUSTED, CB_ID_ON_LAST_GROUP_DELETED, CB_ID_ON_TRUST_DEV_NUM_CHANGED, + CB_ID_ON_CRED_ADD, + CB_ID_ON_CRED_DELETE, + CB_ID_ON_CRED_UPDATE, }; typedef int32_t (*IpcServiceCall)(const IpcDataInfo *, int32_t, uintptr_t); @@ -91,6 +96,8 @@ void ResetIpcCallBackNodeByNodeId(int32_t nodeIdx); int32_t InitProxyAdapt(void); void UnInitProxyAdapt(void); +void InitDevAuthCredListenerCbCtx(CredChangeListener *ctx); + #ifdef __cplusplus } #endif diff --git a/frameworks/src/IS_ipc_sdk.c b/frameworks/src/IS_ipc_sdk.c new file mode 100644 index 0000000000000000000000000000000000000000..8e604103f14e6c3cfa2df3cedcbc09e209c3d138 --- /dev/null +++ b/frameworks/src/IS_ipc_sdk.c @@ -0,0 +1,792 @@ +/* + * Copyright (C) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "ipc_sdk.h" + +#include "common_defs.h" +#include "device_auth_defines.h" +#include "device_auth.h" +#include "hc_log.h" +#include "hc_mutex.h" + +#include "ipc_adapt.h" +#include "securec.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#define IPC_DATA_CACHES_1 1 +#define IPC_DATA_CACHES_3 3 +#define IPC_DATA_CACHES_4 4 +#define REPLAY_CACHE_NUM(caches) (sizeof(caches) / sizeof(IpcDataInfo)) +#define IPC_APPID_LEN 128 + +#define IS_COMM_DATA_VALID(dPtr, dLen) (((dPtr) != NULL) && ((dLen) > 0) && ((dLen) <= 4096)) + +static const int32_t IPC_RESULT_NUM_1 = 1; + +typedef struct { + uintptr_t inst; + char appId[IPC_APPID_LEN]; +} IpcProxyCbInfo; + +static IpcProxyCbInfo g_ipcCredListenerCbList = { 0 }; +static HcMutex g_ipcMutex; + +static bool IsStrInvalid(const char *str) +{ + return (str == NULL || str[0] == 0); +} + +static void DelIpcCliCallbackCtx(const char *appId, IpcProxyCbInfo *cbCache) +{ + int32_t ret; + + if (cbCache->appId[0] == 0) { + return; + } + (void)LockHcMutex(&g_ipcMutex); + ret = memcmp(appId, cbCache->appId, HcStrlen(cbCache->appId) + 1); + if (ret == 0) { + cbCache->appId[0] = 0; + } + UnlockHcMutex(&g_ipcMutex); + return; +} + +static void AddIpcCliCallbackCtx(const char *appId, uintptr_t cbInst, IpcProxyCbInfo *cbCache) +{ + errno_t eno; + + (void)LockHcMutex(&g_ipcMutex); + eno = memcpy_s(cbCache->appId, IPC_APPID_LEN, appId, HcStrlen(appId) + 1); + if (eno != EOK) { + UnlockHcMutex(&g_ipcMutex); + LOGE("memory copy failed"); + return; + } + cbCache->inst = cbInst; + UnlockHcMutex(&g_ipcMutex); +} + +static void GetIpcReplyByType(const IpcDataInfo *ipcData, + int32_t dataNum, int32_t type, uint8_t *outCache, int32_t *cacheLen) +{ + int32_t i; + errno_t eno; + + for (i = 0; i < dataNum; i++) { + if (ipcData[i].type != type) { + continue; + } + switch (type) { + case PARAM_TYPE_REG_INFO: + case PARAM_TYPE_DEVICE_INFO: + case PARAM_TYPE_GROUP_INFO: + case PARAM_TYPE_CRED_ID: + case PARAM_TYPE_CRED_INFO: + case PARAM_TYPE_CRED_INFO_LIST: + case PARAM_TYPE_CRED_VAL: + case PARAM_TYPE_RETURN_DATA: + *(uint8_t **)outCache = ipcData[i].val; + break; + case PARAM_TYPE_IPC_RESULT: + case PARAM_TYPE_IPC_RESULT_NUM: + case PARAM_TYPE_COMM_DATA: + case PARAM_TYPE_DATA_NUM: + eno = memcpy_s(outCache, *cacheLen, ipcData[i].val, ipcData[i].valSz); + if (eno != EOK) { + break; + } + *cacheLen = ipcData[i].valSz; + break; + default: + LOGE("un-expectation type case"); + break; + } + } + return; +} + +static int32_t EncodeAddCredentialParams(uintptr_t callCtx, int32_t osAccountId, const char *requestParams) +{ + int32_t ret = SetCallRequestParamInfo(callCtx, PARAM_TYPE_OS_ACCOUNT_ID, (const uint8_t *)&osAccountId, + sizeof(osAccountId)); + if (ret != HC_SUCCESS) { + LOGE("set request param failed, ret %d, param id %d", ret, PARAM_TYPE_OS_ACCOUNT_ID); + return HC_ERR_IPC_BUILD_PARAM; + } + ret = SetCallRequestParamInfo(callCtx, PARAM_TYPE_REQUEST_PARAMS, (const uint8_t *)requestParams, + HcStrlen(requestParams) + 1); + if (ret != HC_SUCCESS) { + LOGE("set request param failed, ret %d, param id %d", ret, PARAM_TYPE_REQUEST_PARAMS); + return HC_ERR_IPC_BUILD_PARAM; + } + return HC_SUCCESS; +} + +static int32_t AddCredentialIpcResult(const IpcDataInfo *replies, int32_t cacheNum, char **returnData) +{ + int32_t inOutLen; + int32_t ret; + + inOutLen = sizeof(int32_t); + GetIpcReplyByType(replies, cacheNum, PARAM_TYPE_IPC_RESULT_NUM, (uint8_t *)&ret, &inOutLen); + if ((ret < IPC_RESULT_NUM_1) || (inOutLen != sizeof(int32_t))) { + return HC_ERR_IPC_OUT_DATA_NUM; + } + GetIpcReplyByType(replies, cacheNum, PARAM_TYPE_CRED_ID, (uint8_t *)returnData, NULL); + if (*returnData == NULL) { + return HC_ERR_IPC_OUT_DATA; + } + *returnData = strdup(*returnData); + if (*returnData == NULL) { + return HC_ERR_ALLOC_MEMORY; + } + return HC_SUCCESS; +} + +static int32_t IpcCmAddCredential(int32_t osAccountId, const char *requestParams, char **returnData) +{ + uintptr_t callCtx = 0x0; + int32_t ret; + IpcDataInfo replyCache[IPC_DATA_CACHES_3] = { { 0 } }; + + LOGI("starting ..."); + if (IsStrInvalid(requestParams) || returnData == NULL) { + LOGE("invalid params"); + return HC_ERR_INVALID_PARAMS; + } + ret = CreateCallCtx(&callCtx, NULL); + if (ret != HC_SUCCESS) { + LOGE("CreateCallCtx failed, ret %d", ret); + return HC_ERR_IPC_INIT; + } + ret = EncodeAddCredentialParams(callCtx, osAccountId, requestParams); + if (ret != HC_SUCCESS) { + DestroyCallCtx(&callCtx, NULL); + return ret; + } + ret = DoBinderCall(callCtx, IPC_CALL_ID_CM_ADD_CREDENTIAL, true); + if (ret == HC_ERR_IPC_INTERNAL_FAILED) { + LOGE("ipc call failed"); + DestroyCallCtx(&callCtx, NULL); + return HC_ERR_IPC_PROC_FAILED; + } + DecodeCallReply(callCtx, replyCache, REPLAY_CACHE_NUM(replyCache)); + ret = HC_ERR_IPC_UNKNOW_REPLY; + int32_t inOutLen = sizeof(int32_t); + GetIpcReplyByType(replyCache, REPLAY_CACHE_NUM(replyCache), PARAM_TYPE_IPC_RESULT, (uint8_t *)&ret, &inOutLen); + if (ret != HC_SUCCESS) { + DestroyCallCtx(&callCtx, NULL); + return ret; + } + ret = AddCredentialIpcResult(replyCache, REPLAY_CACHE_NUM(replyCache), returnData); + DestroyCallCtx(&callCtx, NULL); + LOGI("process done, ret %d", ret); + return ret; +} + +static int32_t IpcCmRegChangeListener(const char *appId, CredChangeListener *listener) +{ + uintptr_t callCtx = 0x0; + int32_t ret; + + LOGI("starting ..."); + if (IsStrInvalid(appId) || listener == NULL) { + LOGE("invalid params"); + return HC_ERR_INVALID_PARAMS; + } + ret = CreateCallCtx(&callCtx, NULL); + if (ret != HC_SUCCESS) { + LOGE("CreateCallCtx failed, ret %d", ret); + return HC_ERR_IPC_INIT; + } + ret = SetCallRequestParamInfo(callCtx, PARAM_TYPE_APPID, (const uint8_t *)appId, + HcStrlen(appId) + 1); + if (ret != HC_SUCCESS) { + LOGE("set request param failed, ret %d, param id %d", ret, PARAM_TYPE_APPID); + DestroyCallCtx(&callCtx, NULL); + return HC_ERR_IPC_BUILD_PARAM; + } + ret = SetCallRequestParamInfo(callCtx, PARAM_TYPE_LISTERNER, (const uint8_t *)listener, + sizeof(*listener)); + if (ret != HC_SUCCESS) { + LOGE("set request param failed, ret %d, param id %d", ret, PARAM_TYPE_LISTERNER); + DestroyCallCtx(&callCtx, NULL); + return HC_ERR_IPC_BUILD_PARAM; + } + // why do this ? + SetCbCtxToDataCtx(callCtx, IPC_CALL_BACK_STUB_BIND_ID); + ret = DoBinderCall(callCtx, IPC_CALL_ID_CM_REG_LISTENER, true); + if (ret == HC_SUCCESS) { + AddIpcCliCallbackCtx(appId, 0, &g_ipcCredListenerCbList); + } + DestroyCallCtx(&callCtx, NULL); + LOGI("process done, ret %d", ret); + return (ret == HC_SUCCESS) ? HC_SUCCESS : HC_ERR_IPC_PROC_FAILED; +} + +static int32_t IpcCmUnRegChangeListener(const char *appId) +{ + uintptr_t callCtx = 0x0; + int32_t ret; + + LOGI("starting ..."); + if (IsStrInvalid(appId)) { + LOGE("invalid params"); + return HC_ERR_INVALID_PARAMS; + } + ret = CreateCallCtx(&callCtx, NULL); + if (ret != HC_SUCCESS) { + LOGE("CreateCallCtx failed, ret %d", ret); + return HC_ERR_IPC_INIT; + } + ret = SetCallRequestParamInfo(callCtx, PARAM_TYPE_APPID, (const uint8_t *)appId, + HcStrlen(appId) + 1); + if (ret != HC_SUCCESS) { + LOGE("set request param failed, ret %d, param id %d", ret, PARAM_TYPE_APPID); + DestroyCallCtx(&callCtx, NULL); + return HC_ERR_IPC_BUILD_PARAM; + } + ret = DoBinderCall(callCtx, IPC_CALL_ID_CM_UNREG_LISTENER, true); + if (ret == HC_SUCCESS) { + DelIpcCliCallbackCtx(appId, &g_ipcCredListenerCbList); + } + DestroyCallCtx(&callCtx, NULL); + LOGI("process done, ret %d", ret); + return HC_SUCCESS; +} + +static int32_t EncodeExportCredentialParams(uintptr_t callCtx, int32_t osAccountId, const char *credId) +{ + int32_t ret = SetCallRequestParamInfo(callCtx, PARAM_TYPE_OS_ACCOUNT_ID, (const uint8_t *)&osAccountId, + sizeof(osAccountId)); + if (ret != HC_SUCCESS) { + LOGE("set request param failed, ret %d, param id %d", ret, PARAM_TYPE_OS_ACCOUNT_ID); + return HC_ERR_IPC_BUILD_PARAM; + } + ret = SetCallRequestParamInfo(callCtx, PARAM_TYPE_CRED_ID, (const uint8_t *)credId, + HcStrlen(credId) + 1); + if (ret != HC_SUCCESS) { + LOGE("set request param failed, ret %d, param id %d", ret, PARAM_TYPE_CRED_ID); + return HC_ERR_IPC_BUILD_PARAM; + } + return HC_SUCCESS; +} + +static int32_t ExportCredentialIpcResult(const IpcDataInfo *replies, int32_t cacheNum, char **returnData) +{ + int32_t inOutLen; + int32_t ret; + + inOutLen = sizeof(int32_t); + GetIpcReplyByType(replies, cacheNum, PARAM_TYPE_IPC_RESULT_NUM, (uint8_t *)&ret, &inOutLen); + if ((ret < IPC_RESULT_NUM_1) || (inOutLen != sizeof(int32_t))) { + return HC_ERR_IPC_OUT_DATA_NUM; + } + GetIpcReplyByType(replies, cacheNum, PARAM_TYPE_CRED_VAL, (uint8_t *)returnData, NULL); + if (*returnData == NULL) { + return HC_ERR_IPC_OUT_DATA; + } + *returnData = strdup(*returnData); + if (*returnData == NULL) { + return HC_ERR_ALLOC_MEMORY; + } + return HC_SUCCESS; +} + +static int32_t IpcCmExportCredential(int32_t osAccountId, const char *credId, char **returnData) +{ + uintptr_t callCtx = 0x0; + int32_t ret; + IpcDataInfo replyCache[IPC_DATA_CACHES_3] = { { 0 } }; + + LOGI("starting ..."); + if (IsStrInvalid(credId) || returnData == NULL) { + LOGE("invalid params"); + return HC_ERR_INVALID_PARAMS; + } + ret = CreateCallCtx(&callCtx, NULL); + if (ret != HC_SUCCESS) { + LOGE("CreateCallCtx failed, ret %d", ret); + return HC_ERR_IPC_INIT; + } + ret = EncodeExportCredentialParams(callCtx, osAccountId, credId); + if (ret != HC_SUCCESS) { + DestroyCallCtx(&callCtx, NULL); + return ret; + } + ret = DoBinderCall(callCtx, IPC_CALL_ID_CM_EXPORT_CREDENTIAL, true); + if (ret == HC_ERR_IPC_INTERNAL_FAILED) { + LOGE("ipc call failed"); + DestroyCallCtx(&callCtx, NULL); + return HC_ERR_IPC_PROC_FAILED; + } + DecodeCallReply(callCtx, replyCache, REPLAY_CACHE_NUM(replyCache)); + ret = HC_ERR_IPC_UNKNOW_REPLY; + int32_t inOutLen = sizeof(int32_t); + GetIpcReplyByType(replyCache, REPLAY_CACHE_NUM(replyCache), PARAM_TYPE_IPC_RESULT, (uint8_t *)&ret, &inOutLen); + if (ret != HC_SUCCESS) { + DestroyCallCtx(&callCtx, NULL); + return ret; + } + ret = ExportCredentialIpcResult(replyCache, REPLAY_CACHE_NUM(replyCache), returnData); + DestroyCallCtx(&callCtx, NULL); + LOGI("process done, ret %d", ret); + return ret; +} + +static int32_t SearchCredsIpcResult(const IpcDataInfo *replies, int32_t cacheNum, char **returnCredList) +{ + int32_t inOutLen; + int32_t ret; + + inOutLen = sizeof(int32_t); + GetIpcReplyByType(replies, cacheNum, PARAM_TYPE_IPC_RESULT_NUM, (uint8_t *)&ret, &inOutLen); + if ((ret < IPC_RESULT_NUM_1) || (inOutLen != sizeof(int32_t))) { + return HC_ERR_IPC_OUT_DATA_NUM; + } + GetIpcReplyByType(replies, cacheNum, PARAM_TYPE_CRED_INFO_LIST, (uint8_t *)returnCredList, NULL); + if (*returnCredList == NULL) { + return HC_ERR_IPC_OUT_DATA; + } + *returnCredList = strdup(*returnCredList); + if (*returnCredList == NULL) { + return HC_ERR_ALLOC_MEMORY; + } + return HC_SUCCESS; +} + +static int32_t IpcCmQueryCredByParams(int32_t osAccountId, const char *requestParams, char **returnCredList) +{ + uintptr_t callCtx = 0x0; + IpcDataInfo replyCache[IPC_DATA_CACHES_3] = { { 0 } }; + + LOGI("starting ..."); + if (IsStrInvalid(requestParams) || returnCredList == NULL) { + LOGE("invalid params"); + return HC_ERR_INVALID_PARAMS; + } + int32_t ret = CreateCallCtx(&callCtx, NULL); + if (ret != HC_SUCCESS) { + LOGE("CreateCallCtx failed, ret %d", ret); + return HC_ERR_IPC_INIT; + } + ret = SetCallRequestParamInfo(callCtx, PARAM_TYPE_OS_ACCOUNT_ID, (const uint8_t *)&osAccountId, + sizeof(osAccountId)); + if (ret != HC_SUCCESS) { + LOGE("set request param failed, ret %d, param id %d", ret, PARAM_TYPE_OS_ACCOUNT_ID); + DestroyCallCtx(&callCtx, NULL); + return HC_ERR_IPC_BUILD_PARAM; + } + ret = SetCallRequestParamInfo(callCtx, PARAM_TYPE_QUERY_PARAMS, (const uint8_t *)requestParams, + HcStrlen(requestParams) + 1); + if (ret != HC_SUCCESS) { + LOGE("set request param failed, ret %d, param id %d", ret, PARAM_TYPE_QUERY_PARAMS); + DestroyCallCtx(&callCtx, NULL); + return HC_ERR_IPC_BUILD_PARAM; + } + + ret = DoBinderCall(callCtx, IPC_CALL_ID_CM_QUERY_CREDENTIAL_BY_PARAMS, true); + if (ret == HC_ERR_IPC_INTERNAL_FAILED) { + LOGE("ipc call failed"); + DestroyCallCtx(&callCtx, NULL); + return HC_ERR_IPC_PROC_FAILED; + } + DecodeCallReply(callCtx, replyCache, REPLAY_CACHE_NUM(replyCache)); + ret = HC_ERR_IPC_UNKNOW_REPLY; + int32_t inOutLen = sizeof(int32_t); + GetIpcReplyByType(replyCache, REPLAY_CACHE_NUM(replyCache), PARAM_TYPE_IPC_RESULT, (uint8_t *)&ret, &inOutLen); + if (ret != HC_SUCCESS) { + DestroyCallCtx(&callCtx, NULL); + return ret; + } + ret = SearchCredsIpcResult(replyCache, REPLAY_CACHE_NUM(replyCache), returnCredList); + DestroyCallCtx(&callCtx, NULL); + LOGI("process done, ret %d", ret); + return ret; +} + +static int32_t SearchCredInfoIpcResult(const IpcDataInfo *replies, int32_t cacheNum, char **returnCredInfo) +{ + int32_t inOutLen; + int32_t ret; + + inOutLen = sizeof(int32_t); + GetIpcReplyByType(replies, cacheNum, PARAM_TYPE_IPC_RESULT_NUM, (uint8_t *)&ret, &inOutLen); + if ((ret < IPC_RESULT_NUM_1) || (inOutLen != sizeof(int32_t))) { + return HC_ERR_IPC_OUT_DATA_NUM; + } + GetIpcReplyByType(replies, cacheNum, PARAM_TYPE_CRED_INFO, (uint8_t *)returnCredInfo, NULL); + if (*returnCredInfo == NULL) { + return HC_ERR_IPC_OUT_DATA; + } + *returnCredInfo = strdup(*returnCredInfo); + if (*returnCredInfo == NULL) { + return HC_ERR_ALLOC_MEMORY; + } + return HC_SUCCESS; +} + +static int32_t IpcCmQueryCredInfoByCredId(int32_t osAccountId, const char *credId, char **returnCredInfo) +{ + uintptr_t callCtx = 0x0; + IpcDataInfo replyCache[IPC_DATA_CACHES_3] = { { 0 } }; + + LOGI("starting ..."); + if (IsStrInvalid(credId) || returnCredInfo == NULL) { + LOGE("invalid params"); + return HC_ERR_INVALID_PARAMS; + } + int32_t ret = CreateCallCtx(&callCtx, NULL); + if (ret != HC_SUCCESS) { + LOGE("CreateCallCtx failed, ret %d", ret); + return HC_ERR_IPC_INIT; + } + ret = SetCallRequestParamInfo(callCtx, PARAM_TYPE_OS_ACCOUNT_ID, (const uint8_t *)&osAccountId, + sizeof(osAccountId)); + if (ret != HC_SUCCESS) { + LOGE("set request param failed, ret %d, param id %d", ret, PARAM_TYPE_OS_ACCOUNT_ID); + DestroyCallCtx(&callCtx, NULL); + return HC_ERR_IPC_BUILD_PARAM; + } + ret = SetCallRequestParamInfo(callCtx, PARAM_TYPE_CRED_ID, (const uint8_t *)credId, + HcStrlen(credId) + 1); + if (ret != HC_SUCCESS) { + LOGE("set request param failed, ret %d, param id %d", ret, PARAM_TYPE_QUERY_PARAMS); + DestroyCallCtx(&callCtx, NULL); + return HC_ERR_IPC_BUILD_PARAM; + } + + ret = DoBinderCall(callCtx, IPC_CALL_ID_CM_QUERY_CREDENTIAL_BY_CRED_ID, true); + if (ret == HC_ERR_IPC_INTERNAL_FAILED) { + LOGE("ipc call failed"); + DestroyCallCtx(&callCtx, NULL); + return HC_ERR_IPC_PROC_FAILED; + } + DecodeCallReply(callCtx, replyCache, REPLAY_CACHE_NUM(replyCache)); + ret = HC_ERR_IPC_UNKNOW_REPLY; + int32_t inOutLen = sizeof(int32_t); + GetIpcReplyByType(replyCache, REPLAY_CACHE_NUM(replyCache), PARAM_TYPE_IPC_RESULT, (uint8_t *)&ret, &inOutLen); + if (ret != HC_SUCCESS) { + DestroyCallCtx(&callCtx, NULL); + return ret; + } + ret = SearchCredInfoIpcResult(replyCache, REPLAY_CACHE_NUM(replyCache), returnCredInfo); + LOGI("process done, ret %d", ret); + DestroyCallCtx(&callCtx, NULL); + return ret; +} + +static int32_t EncodeDeleteCredentialParams(uintptr_t callCtx, int32_t osAccountId, const char *appId, + const char *credId) +{ + int32_t ret = SetCallRequestParamInfo(callCtx, PARAM_TYPE_OS_ACCOUNT_ID, (const uint8_t *)&osAccountId, + sizeof(osAccountId)); + if (ret != HC_SUCCESS) { + LOGE("set request param failed, ret %d, param id %d", ret, PARAM_TYPE_OS_ACCOUNT_ID); + return HC_ERR_IPC_BUILD_PARAM; + } + ret = SetCallRequestParamInfo(callCtx, PARAM_TYPE_APPID, (const uint8_t *)appId, HcStrlen(appId) + 1); + if (ret != HC_SUCCESS) { + LOGE("set request param failed, ret %d, param id %d", ret, PARAM_TYPE_APPID); + return HC_ERR_IPC_BUILD_PARAM; + } + ret = SetCallRequestParamInfo(callCtx, PARAM_TYPE_CRED_ID, (const uint8_t *)credId, HcStrlen(credId) + 1); + if (ret != HC_SUCCESS) { + LOGE("set request param failed, ret %d, param id %d", ret, PARAM_TYPE_CRED_ID); + return HC_ERR_IPC_BUILD_PARAM; + } + return HC_SUCCESS; +} + +static int32_t IpcCmDeleteCredential(int32_t osAccountId, const char *appId, const char *credId) +{ + uintptr_t callCtx = 0x0; + int32_t ret; + IpcDataInfo replyCache = { 0 }; + + LOGI("starting ..."); + if (IsStrInvalid(appId) || IsStrInvalid(credId)) { + LOGE("invalid params"); + return HC_ERR_INVALID_PARAMS; + } + ret = CreateCallCtx(&callCtx, NULL); + if (ret != HC_SUCCESS) { + LOGE("CreateCallCtx failed, ret %d", ret); + return HC_ERR_IPC_INIT; + } + ret = EncodeDeleteCredentialParams(callCtx, osAccountId, appId, credId); + if (ret != HC_SUCCESS) { + DestroyCallCtx(&callCtx, NULL); + return ret; + } + ret = DoBinderCall(callCtx, IPC_CALL_ID_CM_DEL_CREDENTIAL, true); + if (ret == HC_ERR_IPC_INTERNAL_FAILED) { + LOGE("ipc call failed"); + DestroyCallCtx(&callCtx, NULL); + return HC_ERR_IPC_PROC_FAILED; + } + DecodeCallReply(callCtx, &replyCache, REPLAY_CACHE_NUM(replyCache)); + ret = HC_ERR_IPC_UNKNOW_REPLY; + int32_t inOutLen = sizeof(int32_t); + GetIpcReplyByType(&replyCache, REPLAY_CACHE_NUM(replyCache), PARAM_TYPE_IPC_RESULT, (uint8_t *)&ret, &inOutLen); + DestroyCallCtx(&callCtx, NULL); + LOGI("process done, ret %d", ret); + return ret; +} + +static int32_t EncodeUpdateParams(uintptr_t callCtx, int32_t osAccountId, const char *credId, const char *appId, + const char *requestParams) +{ + int32_t ret = SetCallRequestParamInfo(callCtx, PARAM_TYPE_OS_ACCOUNT_ID, (const uint8_t *)&osAccountId, + sizeof(osAccountId)); + if (ret != HC_SUCCESS) { + LOGE("set request param failed, ret %d, param id %d", ret, PARAM_TYPE_OS_ACCOUNT_ID); + return HC_ERR_IPC_BUILD_PARAM; + } + ret = SetCallRequestParamInfo(callCtx, PARAM_TYPE_APPID, (const uint8_t *)appId, HcStrlen(appId) + 1); + if (ret != HC_SUCCESS) { + LOGE("set request param failed, ret %d, param id %d", ret, PARAM_TYPE_APPID); + return HC_ERR_IPC_BUILD_PARAM; + } + ret = SetCallRequestParamInfo(callCtx, PARAM_TYPE_CRED_ID, (const uint8_t *)credId, HcStrlen(credId) + 1); + if (ret != HC_SUCCESS) { + LOGE("set request param failed, ret %d, param id %d", ret, PARAM_TYPE_CRED_ID); + return HC_ERR_IPC_BUILD_PARAM; + } + ret = SetCallRequestParamInfo(callCtx, PARAM_TYPE_REQUEST_PARAMS, (const uint8_t *)requestParams, + HcStrlen(requestParams) + 1); + if (ret != HC_SUCCESS) { + LOGE("set request param failed, ret %d, param id %d", ret, PARAM_TYPE_REQUEST_PARAMS); + return HC_ERR_IPC_BUILD_PARAM; + } + return HC_SUCCESS; +} + +static int32_t IpcCmUpdateCredInfo(int32_t osAccountId, const char *appId, const char *credId, + const char *requestParams) +{ + uintptr_t callCtx = 0x0; + int32_t ret; + IpcDataInfo replyCache = { 0 }; + + LOGI("starting ..."); + if (IsStrInvalid(appId) || IsStrInvalid(credId) || IsStrInvalid(requestParams)) { + LOGE("invalid params"); + return HC_ERR_INVALID_PARAMS; + } + ret = CreateCallCtx(&callCtx, NULL); + if (ret != HC_SUCCESS) { + LOGE("CreateCallCtx failed, ret %d", ret); + return HC_ERR_IPC_INIT; + } + ret = EncodeUpdateParams(callCtx, osAccountId, credId, appId, requestParams); + if (ret != HC_SUCCESS) { + DestroyCallCtx(&callCtx, NULL); + return ret; + } + ret = DoBinderCall(callCtx, IPC_CALL_ID_CM_UPDATE_CRED_INFO, true); + if (ret == HC_ERR_IPC_INTERNAL_FAILED) { + LOGE("ipc call failed"); + DestroyCallCtx(&callCtx, NULL); + return HC_ERR_IPC_PROC_FAILED; + } + DecodeCallReply(callCtx, &replyCache, REPLAY_CACHE_NUM(replyCache)); + ret = HC_ERR_IPC_UNKNOW_REPLY; + int32_t inOutLen = sizeof(int32_t); + GetIpcReplyByType(&replyCache, REPLAY_CACHE_NUM(replyCache), PARAM_TYPE_IPC_RESULT, (uint8_t *)&ret, &inOutLen); + DestroyCallCtx(&callCtx, NULL); + LOGI("process done, ret %d", ret); + return ret; +} + +static void InitIpcCmMethods(CredManager *cmMethodObj) +{ + cmMethodObj->addCredential = IpcCmAddCredential; + cmMethodObj->exportCredential = IpcCmExportCredential; + cmMethodObj->registerChangeListener = IpcCmRegChangeListener; + cmMethodObj->unregisterChangeListener = IpcCmUnRegChangeListener; + cmMethodObj->queryCredentialByParams = IpcCmQueryCredByParams; + cmMethodObj->queryCredInfoByCredId = IpcCmQueryCredInfoByCredId; + cmMethodObj->deleteCredential = IpcCmDeleteCredential; + cmMethodObj->updateCredInfo = IpcCmUpdateCredInfo; + return; +} + + +static int32_t EncodeAuthDeviceParams(uintptr_t callCtx, int32_t osAccountId, int64_t authReqId, + const char *authParams, const DeviceAuthCallback *callback) +{ + int32_t ret = SetCallRequestParamInfo(callCtx, PARAM_TYPE_OS_ACCOUNT_ID, (const uint8_t *)&osAccountId, + sizeof(osAccountId)); + if (ret != HC_SUCCESS) { + LOGE("set request param failed, ret %d, param id %d", ret, PARAM_TYPE_OS_ACCOUNT_ID); + return HC_ERR_IPC_BUILD_PARAM; + } + ret = SetCallRequestParamInfo(callCtx, PARAM_TYPE_REQID, (const uint8_t *)(&authReqId), sizeof(authReqId)); + if (ret != HC_SUCCESS) { + LOGE("set request param failed, ret %d, type %d", ret, PARAM_TYPE_REQID); + return HC_ERR_IPC_BUILD_PARAM; + } + ret = SetCallRequestParamInfo(callCtx, PARAM_TYPE_AUTH_PARAMS, (const uint8_t *)authParams, + HcStrlen(authParams) + 1); + if (ret != HC_SUCCESS) { + LOGE("set request param failed, ret %d, type %d", ret, PARAM_TYPE_AUTH_PARAMS); + return HC_ERR_IPC_BUILD_PARAM; + } + ret = SetCallRequestParamInfo(callCtx, PARAM_TYPE_DEV_AUTH_CB, (const uint8_t *)callback, sizeof(*callback)); + if (ret != HC_SUCCESS) { + LOGE("set request param failed, ret %d, type %d", ret, PARAM_TYPE_DEV_AUTH_CB); + return HC_ERR_IPC_BUILD_PARAM; + } + SetCbCtxToDataCtx(callCtx, IPC_CALL_BACK_STUB_AUTH_ID); + return HC_SUCCESS; +} + +static int32_t IpcCmAuthCredential(int32_t osAccountId, int64_t authReqId, const char *authParams, + const DeviceAuthCallback *caCallback) +{ + uintptr_t callCtx = 0x0; + int32_t ret; + int32_t inOutLen; + IpcDataInfo replyCache = { 0 }; + + LOGI("starting ..."); + if (IsStrInvalid(authParams) || (caCallback == NULL)) { + LOGE("invalid params"); + return HC_ERR_INVALID_PARAMS; + } + ret = CreateCallCtx(&callCtx, NULL); + if (ret != HC_SUCCESS) { + LOGE("CreateCallCtx failed, ret %d", ret); + return HC_ERR_IPC_INIT; + } + ret = EncodeAuthDeviceParams(callCtx, osAccountId, authReqId, authParams, caCallback); + if (ret != HC_SUCCESS) { + DestroyCallCtx(&callCtx, NULL); + return ret; + } + ret = DoBinderCall(callCtx, IPC_CALL_ID_CA_AUTH_DEVICE, true); + if (ret == HC_ERR_IPC_INTERNAL_FAILED) { + LOGE("ipc call failed"); + DestroyCallCtx(&callCtx, NULL); + return HC_ERR_IPC_PROC_FAILED; + } + DecodeCallReply(callCtx, &replyCache, REPLAY_CACHE_NUM(replyCache)); + ret = HC_ERR_IPC_UNKNOW_REPLY; + inOutLen = sizeof(int32_t); + GetIpcReplyByType(&replyCache, REPLAY_CACHE_NUM(replyCache), PARAM_TYPE_IPC_RESULT, (uint8_t *)&ret, &inOutLen); + LOGI("process done, ret %d", ret); + DestroyCallCtx(&callCtx, NULL); + return ret; +} + +static int32_t EncodeProcessDataParams(uintptr_t callCtx, int64_t authReqId, + const uint8_t *data, uint32_t dataLen, const DeviceAuthCallback *callback) +{ + int32_t ret = SetCallRequestParamInfo(callCtx, PARAM_TYPE_REQID, (const uint8_t *)(&authReqId), sizeof(authReqId)); + if (ret != HC_SUCCESS) { + LOGE("set request param failed, ret %d, type %d", ret, PARAM_TYPE_REQID); + return HC_ERR_IPC_BUILD_PARAM; + } + ret = SetCallRequestParamInfo(callCtx, PARAM_TYPE_COMM_DATA, (const uint8_t *)data, dataLen); + if (ret != HC_SUCCESS) { + LOGE("set request param failed, ret %d, type %d", ret, PARAM_TYPE_COMM_DATA); + return HC_ERR_IPC_BUILD_PARAM; + } + ret = SetCallRequestParamInfo(callCtx, PARAM_TYPE_DEV_AUTH_CB, (const uint8_t *)callback, sizeof(*callback)); + if (ret != HC_SUCCESS) { + LOGE("set request param failed, ret %d, type %d", ret, PARAM_TYPE_DEV_AUTH_CB); + return HC_ERR_IPC_BUILD_PARAM; + } + SetCbCtxToDataCtx(callCtx, 0x0); + return HC_SUCCESS; +} + +static int32_t IpcCmProcessCredData(int64_t authReqId, const uint8_t *data, uint32_t dataLen, + const DeviceAuthCallback *callback) +{ + uintptr_t callCtx = 0x0; + int32_t ret; + int32_t inOutLen; + IpcDataInfo replyCache = { 0 }; + + LOGI("starting ..."); + if (!IS_COMM_DATA_VALID(data, dataLen) || (callback == NULL)) { + LOGE("invalid params"); + return HC_ERR_INVALID_PARAMS; + } + ret = CreateCallCtx(&callCtx, NULL); + if (ret != HC_SUCCESS) { + LOGE("CreateCallCtx failed, ret %d", ret); + return HC_ERR_IPC_INIT; + } + ret = EncodeProcessDataParams(callCtx, authReqId, data, dataLen, callback); + if (ret != HC_SUCCESS) { + DestroyCallCtx(&callCtx, NULL); + return ret; + } + ret = DoBinderCall(callCtx, IPC_CALL_ID_CA_PROCESS_CRED_DATA, true); + if (ret == HC_ERR_IPC_INTERNAL_FAILED) { + LOGE("ipc call failed"); + DestroyCallCtx(&callCtx, NULL); + return HC_ERR_IPC_PROC_FAILED; + } + DecodeCallReply(callCtx, &replyCache, REPLAY_CACHE_NUM(replyCache)); + ret = HC_ERR_IPC_UNKNOW_REPLY; + inOutLen = sizeof(int32_t); + GetIpcReplyByType(&replyCache, REPLAY_CACHE_NUM(replyCache), PARAM_TYPE_IPC_RESULT, (uint8_t *)&ret, &inOutLen); + LOGI("process done, ret %d", ret); + DestroyCallCtx(&callCtx, NULL); + return ret; +} + +static void InitIpcCaMethods(CredAuthManager *caMethodObj) +{ + caMethodObj->authCredential = IpcCmAuthCredential; + caMethodObj->processCredData = IpcCmProcessCredData; + return; +} + +DEVICE_AUTH_API_PUBLIC const CredManager *GetCredMgrInstance(void) +{ + static CredManager cmInstCtx; + static CredManager *cmInstPtr = NULL; + + if (cmInstPtr == NULL) { + InitIpcCmMethods(&cmInstCtx); + cmInstPtr = &cmInstCtx; + } + return (const CredManager *)(cmInstPtr); +} + +DEVICE_AUTH_API_PUBLIC const CredAuthManager *GetCredAuthInstance(void) +{ + static CredAuthManager caInstCtx; + static CredAuthManager *caInstPtr = NULL; + + if (caInstPtr == NULL) { + InitIpcCaMethods(&caInstCtx); + caInstPtr = &caInstCtx; + } + return (const CredAuthManager *)(caInstPtr); +} + +#ifdef __cplusplus +} +#endif diff --git a/frameworks/src/deviceauth_sa.cpp b/frameworks/src/deviceauth_sa.cpp index f5fb0188833734b622f1c70ca4adda189723f7ea..ea53e929b308af93a759fadab5a85f2a42127cea 100644 --- a/frameworks/src/deviceauth_sa.cpp +++ b/frameworks/src/deviceauth_sa.cpp @@ -38,6 +38,54 @@ namespace OHOS { static const uint32_t RESTORE_CODE = 14701; +using IpcCallMap = struct { + int32_t (*func)(const IpcDataInfo*, int32_t, uintptr_t); + uint32_t id; +}; + +static IpcCallMap g_ipcCallMaps[] = { + {IpcServiceGmRegCallback, IPC_CALL_ID_REG_CB}, + {IpcServiceGmUnRegCallback, IPC_CALL_ID_UNREG_CB}, + {IpcServiceGmRegDataChangeListener, IPC_CALL_ID_REG_LISTENER}, + {IpcServiceGmUnRegDataChangeListener, IPC_CALL_ID_UNREG_LISTENER}, + {IpcServiceGmCreateGroup, IPC_CALL_ID_CREATE_GROUP}, + {IpcServiceGmDelGroup, IPC_CALL_ID_DEL_GROUP}, + {IpcServiceGmAddMemberToGroup, IPC_CALL_ID_ADD_GROUP_MEMBER}, + {IpcServiceGmDelMemberFromGroup, IPC_CALL_ID_DEL_GROUP_MEMBER}, + {IpcServiceGmAddMultiMembersToGroup, IPC_CALL_ID_ADD_MULTI_GROUP_MEMBERS}, + {IpcServiceGmDelMultiMembersFromGroup, IPC_CALL_ID_DEL_MULTI_GROUP_MEMBERS}, + {IpcServiceGmProcessData, IPC_CALL_ID_GM_PROC_DATA}, + {IpcServiceGmApplyRegisterInfo, IPC_CALL_ID_APPLY_REG_INFO}, + {IpcServiceGmCheckAccessToGroup, IPC_CALL_ID_CHECK_ACCESS_TO_GROUP}, + {IpcServiceGmGetPkInfoList, IPC_CALL_ID_GET_PK_INFO_LIST}, + {IpcServiceGmGetGroupInfoById, IPC_CALL_ID_GET_GROUP_INFO}, + {IpcServiceGmGetGroupInfo, IPC_CALL_ID_SEARCH_GROUPS}, + {IpcServiceGmGetJoinedGroups, IPC_CALL_ID_GET_JOINED_GROUPS}, + {IpcServiceGmGetRelatedGroups, IPC_CALL_ID_GET_RELATED_GROUPS}, + {IpcServiceGmGetDeviceInfoById, IPC_CALL_ID_GET_DEV_INFO_BY_ID}, + {IpcServiceGmGetTrustedDevices, IPC_CALL_ID_GET_TRUST_DEVICES}, + {IpcServiceGmIsDeviceInGroup, IPC_CALL_ID_IS_DEV_IN_GROUP}, + {IpcServiceGmCancelRequest, IPC_CALL_GM_CANCEL_REQUEST}, + {IpcServiceGaProcessData, IPC_CALL_ID_GA_PROC_DATA}, + {IpcServiceGaAuthDevice, IPC_CALL_ID_AUTH_DEVICE}, + {IpcServiceGaCancelRequest, IPC_CALL_GA_CANCEL_REQUEST}, + {IpcServiceGaGetRealInfo, IPC_CALL_ID_GET_REAL_INFO}, + {IpcServiceGaGetPseudonymId, IPC_CALL_ID_GET_PSEUDONYM_ID}, + {IpcServiceDaProcessCredential, IPC_CALL_ID_PROCESS_CREDENTIAL}, + {IpcServiceDaAuthDevice, IPC_CALL_ID_DA_AUTH_DEVICE}, + {IpcServiceDaProcessData, IPC_CALL_ID_DA_PROC_DATA}, + {IpcServiceDaCancelRequest, IPC_CALL_ID_DA_CANCEL_REQUEST}, + {IpcServiceCmAddCredential, IPC_CALL_ID_CM_ADD_CREDENTIAL}, + {IpcServiceCmRegCredChangeListener, IPC_CALL_ID_CM_REG_LISTENER}, + {IpcServiceCmUnRegCredChangeListener, IPC_CALL_ID_CM_UNREG_LISTENER}, + {IpcServiceCmExportCredential, IPC_CALL_ID_CM_EXPORT_CREDENTIAL}, + {IpcServiceCmQueryCredentialByParams, IPC_CALL_ID_CM_QUERY_CREDENTIAL_BY_PARAMS}, + {IpcServiceCmQueryCredentialByCredId, IPC_CALL_ID_CM_QUERY_CREDENTIAL_BY_CRED_ID}, + {IpcServiceCmDeleteCredential, IPC_CALL_ID_CM_DEL_CREDENTIAL}, + {IpcServiceCmUpdateCredInfo, IPC_CALL_ID_CM_UPDATE_CRED_INFO}, + {IpcServiceCaAuthDevice, IPC_CALL_ID_CA_AUTH_DEVICE}, + {IpcServiceCaProcessCredData, IPC_CALL_ID_CA_PROCESS_CRED_DATA}, +}; REGISTER_SYSTEM_ABILITY_BY_ID(DeviceAuthAbility, SA_ID_DEVAUTH_SERVICE, true); @@ -68,49 +116,9 @@ __attribute__((no_sanitize("cfi"))) static uint32_t SaSetIpcCallMap( static int32_t SaAddMethodMap(uintptr_t ipcInstance) { uint32_t ret = 0; - using IpcCallMap = struct { - int32_t (*func)(const IpcDataInfo*, int32_t, uintptr_t); - uint32_t id; - }; - - IpcCallMap ipcCallMaps[] = { - {IpcServiceGmRegCallback, IPC_CALL_ID_REG_CB}, - {IpcServiceGmUnRegCallback, IPC_CALL_ID_UNREG_CB}, - {IpcServiceGmRegDataChangeListener, IPC_CALL_ID_REG_LISTENER}, - {IpcServiceGmUnRegDataChangeListener, IPC_CALL_ID_UNREG_LISTENER}, - {IpcServiceGmCreateGroup, IPC_CALL_ID_CREATE_GROUP}, - {IpcServiceGmDelGroup, IPC_CALL_ID_DEL_GROUP}, - {IpcServiceGmAddMemberToGroup, IPC_CALL_ID_ADD_GROUP_MEMBER}, - {IpcServiceGmDelMemberFromGroup, IPC_CALL_ID_DEL_GROUP_MEMBER}, - {IpcServiceGmAddMultiMembersToGroup, IPC_CALL_ID_ADD_MULTI_GROUP_MEMBERS}, - {IpcServiceGmDelMultiMembersFromGroup, IPC_CALL_ID_DEL_MULTI_GROUP_MEMBERS}, - {IpcServiceGmProcessData, IPC_CALL_ID_GM_PROC_DATA}, - {IpcServiceGmApplyRegisterInfo, IPC_CALL_ID_APPLY_REG_INFO}, - {IpcServiceGmCheckAccessToGroup, IPC_CALL_ID_CHECK_ACCESS_TO_GROUP}, - {IpcServiceGmGetPkInfoList, IPC_CALL_ID_GET_PK_INFO_LIST}, - {IpcServiceGmGetGroupInfoById, IPC_CALL_ID_GET_GROUP_INFO}, - {IpcServiceGmGetGroupInfo, IPC_CALL_ID_SEARCH_GROUPS}, - {IpcServiceGmGetJoinedGroups, IPC_CALL_ID_GET_JOINED_GROUPS}, - {IpcServiceGmGetRelatedGroups, IPC_CALL_ID_GET_RELATED_GROUPS}, - {IpcServiceGmGetDeviceInfoById, IPC_CALL_ID_GET_DEV_INFO_BY_ID}, - {IpcServiceGmGetTrustedDevices, IPC_CALL_ID_GET_TRUST_DEVICES}, - {IpcServiceGmIsDeviceInGroup, IPC_CALL_ID_IS_DEV_IN_GROUP}, - {IpcServiceGmCancelRequest, IPC_CALL_GM_CANCEL_REQUEST}, - {IpcServiceGaProcessData, IPC_CALL_ID_GA_PROC_DATA}, - {IpcServiceGaAuthDevice, IPC_CALL_ID_AUTH_DEVICE}, - {IpcServiceGaCancelRequest, IPC_CALL_GA_CANCEL_REQUEST}, - {IpcServiceGaGetRealInfo, IPC_CALL_ID_GET_REAL_INFO}, - {IpcServiceGaGetPseudonymId, IPC_CALL_ID_GET_PSEUDONYM_ID}, - {IpcServiceDaProcessCredential, IPC_CALL_ID_PROCESS_CREDENTIAL}, - {IpcServiceDaAuthDevice, IPC_CALL_ID_DA_AUTH_DEVICE}, - {IpcServiceDaProcessData, IPC_CALL_ID_DA_PROC_DATA}, - {IpcServiceDaCancelRequest, IPC_CALL_ID_DA_CANCEL_REQUEST}, - }; - - for (uint32_t i = 0; i < sizeof(ipcCallMaps)/sizeof(ipcCallMaps[0]); i++) { - ret &= SaSetIpcCallMap(ipcInstance, ipcCallMaps[i].func, ipcCallMaps[i].id); + for (uint32_t i = 0; i < sizeof(g_ipcCallMaps)/sizeof(g_ipcCallMaps[0]); i++) { + ret &= SaSetIpcCallMap(ipcInstance, g_ipcCallMaps[i].func, g_ipcCallMaps[i].id); } - return ret; } diff --git a/frameworks/src/ipc_sdk.c b/frameworks/src/ipc_sdk.c index 26e3f1e7d267df6c448812cf11a3d6a314dc119c..5990c5b5733b69b613f08148f9e8074d96947fb3 100644 --- a/frameworks/src/ipc_sdk.c +++ b/frameworks/src/ipc_sdk.c @@ -97,6 +97,10 @@ static void GetIpcReplyByType(const IpcDataInfo *ipcData, case PARAM_TYPE_REG_INFO: case PARAM_TYPE_DEVICE_INFO: case PARAM_TYPE_GROUP_INFO: + case PARAM_TYPE_CRED_ID: + case PARAM_TYPE_CRED_INFO: + case PARAM_TYPE_CRED_INFO_LIST: + case PARAM_TYPE_CRED_VAL: case PARAM_TYPE_RETURN_DATA: *(uint8_t **)outCache = ipcData[i].val; break; diff --git a/frameworks/src/ipc_service_common.c b/frameworks/src/ipc_service_common.c index a939c91c79233171abe458258e6e40577eec2e60..1680290b46f3fed8c948c6fd75f013e8a0eaf79c 100644 --- a/frameworks/src/ipc_service_common.c +++ b/frameworks/src/ipc_service_common.c @@ -1,5 +1,5 @@ /* - * Copyright (C) 2024-2024 Huawei Device Co., Ltd. + * Copyright (C) 2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -35,6 +35,12 @@ static DeviceAuthCallback g_bindCbAdt = {NULL}; static DeviceAuthCallback g_authCbAdt = {NULL}; static DataChangeListener g_listenCbAdt = {NULL}; +#ifdef DEV_AUTH_IS_ENABLE +static CredManager g_devCredMgrMethod = {NULL}; +static CredChangeListener g_credListenCbAdt = {NULL}; +static CredAuthManager g_credAuthMgrMethod = {NULL}; +#endif + static inline int32_t GetAndValSize32Param(const IpcDataInfo *ipcParams, int32_t paramNum, int32_t paramType, uint8_t *param, int32_t *paramSize) { @@ -1241,13 +1247,419 @@ int32_t IpcServiceDaCancelRequest(const IpcDataInfo *ipcParams, int32_t paramNum return ret; } +#ifdef DEV_AUTH_IS_ENABLE +int32_t IpcServiceCmAddCredential(const IpcDataInfo *ipcParams, int32_t paramNum, uintptr_t outCache) +{ + int32_t callRet; + int32_t ret; + int32_t osAccountId; + int32_t inOutLen; + const char *requestParams = NULL; + char *credId = NULL; + + LOGI("starting ..."); + inOutLen = sizeof(int32_t); + ret = GetAndValSize32Param(ipcParams, paramNum, PARAM_TYPE_OS_ACCOUNT_ID, (uint8_t *)&osAccountId, &inOutLen); + if (ret != HC_SUCCESS) { + LOGE("get param error, type %d", PARAM_TYPE_OS_ACCOUNT_ID); + return ret; + } + ret = GetAndValNullParam(ipcParams, paramNum, PARAM_TYPE_REQUEST_PARAMS, (uint8_t *)&requestParams, NULL); + if (ret != HC_SUCCESS) { + LOGE("get param error, type %d", PARAM_TYPE_REQUEST_PARAMS); + return ret; + } + callRet = g_devCredMgrMethod.addCredential(osAccountId, requestParams, &credId); + ret = IpcEncodeCallReply(outCache, PARAM_TYPE_IPC_RESULT, (const uint8_t *)&callRet, sizeof(int32_t)); + ret += IpcEncodeCallReply(outCache, PARAM_TYPE_IPC_RESULT_NUM, (const uint8_t *)&IPC_RESULT_NUM_1, sizeof(int32_t)); + if (credId != NULL) { + ret += IpcEncodeCallReply(outCache, PARAM_TYPE_CRED_ID, (const uint8_t *)credId, HcStrlen(credId) + 1); + } else { + ret += IpcEncodeCallReply(outCache, PARAM_TYPE_CRED_ID, NULL, 0); + } + g_devCredMgrMethod.destroyInfo(&credId); + LOGI("process done, call ret %d, ipc ret %d", callRet, ret); + return ret; +} + +int32_t IpcServiceCmRegCredChangeListener(const IpcDataInfo *ipcParams, int32_t paramNum, uintptr_t outCache) +{ + int32_t callRet; + int32_t ret; + const char *appId = NULL; + const CredChangeListener *listener = NULL; + static int32_t registered = 0; + int32_t cbObjIdx = -1; + int32_t inOutLen; + LOGI("starting ..."); + inOutLen = sizeof(int32_t); + + ret = GetIpcRequestParamByType(ipcParams, paramNum, PARAM_TYPE_APPID, (uint8_t *)&appId, NULL); + if (ret != HC_SUCCESS) { + LOGE("get param error, type %d", PARAM_TYPE_APPID); + return HC_ERR_IPC_BAD_PARAM; + } + + inOutLen = sizeof(CredChangeListener); + ret = GetIpcRequestParamByType(ipcParams, paramNum, PARAM_TYPE_LISTERNER, (uint8_t *)&listener, &inOutLen); + if ((ret != HC_SUCCESS) || (inOutLen != sizeof(CredChangeListener))) { + LOGE("get param error, type %d", PARAM_TYPE_LISTERNER); + return HC_ERR_IPC_BAD_PARAM; + } + + ret = AddIpcCallBackByAppId(appId, (const uint8_t *)listener, sizeof(CredChangeListener), CB_TYPE_CRED_LISTENER); + if (ret != HC_SUCCESS) { + LOGE("add ipc listener failed"); + return HC_ERROR; + } + + inOutLen = sizeof(int32_t); + ret = GetIpcRequestParamByType(ipcParams, paramNum, PARAM_TYPE_CB_OBJECT, (uint8_t *)&cbObjIdx, &inOutLen); + if (ret != HC_SUCCESS) { + LOGE("get param error, type %d", PARAM_TYPE_CB_OBJECT); + DelIpcCallBackByAppId(appId, CB_TYPE_CRED_LISTENER); + return HC_ERR_IPC_BAD_PARAM; + } + // why to this ? + AddIpcCbObjByAppId(appId, cbObjIdx, CB_TYPE_CRED_LISTENER); + + callRet = HC_SUCCESS; + if (registered == 0) { + InitDevAuthCredListenerCbCtx(&g_credListenCbAdt); + callRet = g_devCredMgrMethod.registerChangeListener(SERVICE_APP_ID, &g_credListenCbAdt); + if (callRet == HC_SUCCESS) { + registered = 1; + } else { + DelIpcCallBackByAppId(appId, CB_TYPE_CRED_LISTENER); + } + } + ret = IpcEncodeCallReply(outCache, PARAM_TYPE_IPC_RESULT, (const uint8_t *)&callRet, sizeof(int32_t)); + LOGI("process done, call ret %d, ipc ret %d", callRet, ret); + return ret; +} + +int32_t IpcServiceCmUnRegCredChangeListener(const IpcDataInfo *ipcParams, int32_t paramNum, uintptr_t outCache) +{ + int32_t callRet = HC_SUCCESS; + int32_t ret; + const char *appId = NULL; + LOGI("starting ..."); + ret = GetIpcRequestParamByType(ipcParams, paramNum, PARAM_TYPE_APPID, (uint8_t *)&appId, NULL); + if (ret != HC_SUCCESS) { + LOGE("get param error, type %d", PARAM_TYPE_APPID); + return HC_ERR_IPC_BAD_PARAM; + } + DelIpcCallBackByAppId(appId, CB_TYPE_CRED_LISTENER); + ret = IpcEncodeCallReply(outCache, PARAM_TYPE_IPC_RESULT, (const uint8_t *)&callRet, sizeof(int32_t)); + LOGI("process done, call ret %d, ipc ret %d", callRet, ret); + return ret; +} + + +int32_t IpcServiceCmExportCredential(const IpcDataInfo *ipcParams, int32_t paramNum, uintptr_t outCache) +{ + int32_t callRet; + int32_t ret; + int32_t osAccountId; + int32_t inOutLen; + const char *credId = NULL; + char *returnCredVal = NULL; + LOGI("starting ..."); + inOutLen = sizeof(int32_t); + ret = GetAndValSize32Param(ipcParams, paramNum, PARAM_TYPE_OS_ACCOUNT_ID, (uint8_t *)&osAccountId, &inOutLen); + if (ret != HC_SUCCESS) { + LOGE("get param error, type %d", PARAM_TYPE_OS_ACCOUNT_ID); + return ret; + } + ret = GetAndValNullParam(ipcParams, paramNum, PARAM_TYPE_CRED_ID, (uint8_t *)&credId, NULL); + if (ret != HC_SUCCESS) { + LOGE("get param error, type %d", PARAM_TYPE_REQUEST_PARAMS); + return ret; + } + callRet = g_devCredMgrMethod.exportCredential(osAccountId, credId, &returnCredVal); + ret = IpcEncodeCallReply(outCache, PARAM_TYPE_IPC_RESULT, (const uint8_t *)&callRet, sizeof(int32_t)); + ret += IpcEncodeCallReply(outCache, PARAM_TYPE_IPC_RESULT_NUM, (const uint8_t *)&IPC_RESULT_NUM_1, sizeof(int32_t)); + if (returnCredVal != NULL) { + ret += IpcEncodeCallReply(outCache, PARAM_TYPE_CRED_VAL, (const uint8_t *)returnCredVal, + HcStrlen(returnCredVal) + 1); + } else { + ret += IpcEncodeCallReply(outCache, PARAM_TYPE_CRED_VAL, NULL, 0); + } + g_devCredMgrMethod.destroyInfo(&returnCredVal); + LOGI("process done, call ret %d, ipc ret %d", callRet, ret); + return ret; +} + +int32_t IpcServiceCmQueryCredentialByParams(const IpcDataInfo *ipcParams, int32_t paramNum, uintptr_t outCache) +{ + int32_t callRet; + int32_t ret; + int32_t osAccountId; + int32_t inOutLen; + const char *requestParams = NULL; + char *returnCredList = NULL; + LOGI("starting ..."); + inOutLen = sizeof(int32_t); + ret = GetAndValSize32Param(ipcParams, paramNum, PARAM_TYPE_OS_ACCOUNT_ID, (uint8_t *)&osAccountId, &inOutLen); + if (ret != HC_SUCCESS) { + LOGE("get param error, type %d", PARAM_TYPE_OS_ACCOUNT_ID); + return ret; + } + ret = GetAndValNullParam(ipcParams, paramNum, PARAM_TYPE_QUERY_PARAMS, (uint8_t *)&requestParams, NULL); + if (ret != HC_SUCCESS) { + LOGE("get param error, type %d", PARAM_TYPE_QUERY_PARAMS); + return ret; + } + callRet = g_devCredMgrMethod.queryCredentialByParams(osAccountId, requestParams, &returnCredList); + ret = IpcEncodeCallReply(outCache, PARAM_TYPE_IPC_RESULT, (const uint8_t *)&callRet, sizeof(int32_t)); + ret += IpcEncodeCallReply(outCache, PARAM_TYPE_IPC_RESULT_NUM, (const uint8_t *)&IPC_RESULT_NUM_1, sizeof(int32_t)); + if (returnCredList != NULL) { + ret += IpcEncodeCallReply(outCache, PARAM_TYPE_CRED_INFO_LIST, (const uint8_t *)returnCredList, + HcStrlen(returnCredList) + 1); + } else { + ret += IpcEncodeCallReply(outCache, PARAM_TYPE_CRED_INFO_LIST, NULL, 0); + } + g_devCredMgrMethod.destroyInfo(&returnCredList); + LOGI("process done, call ret %d, ipc ret %d", callRet, ret); + return ret; +} + +int32_t IpcServiceCmQueryCredentialByCredId(const IpcDataInfo *ipcParams, int32_t paramNum, uintptr_t outCache) +{ + int32_t callRet; + int32_t ret; + int32_t osAccountId; + int32_t inOutLen; + const char *credId = NULL; + char *returnCredInfo = NULL; + LOGI("starting ..."); + inOutLen = sizeof(int32_t); + ret = GetAndValSize32Param(ipcParams, paramNum, PARAM_TYPE_OS_ACCOUNT_ID, (uint8_t *)&osAccountId, &inOutLen); + if (ret != HC_SUCCESS) { + LOGE("get param error, type %d", PARAM_TYPE_OS_ACCOUNT_ID); + return ret; + } + ret = GetAndValNullParam(ipcParams, paramNum, PARAM_TYPE_CRED_ID, (uint8_t *)&credId, NULL); + if (ret != HC_SUCCESS) { + LOGE("get param error, type %d", PARAM_TYPE_CRED_ID); + return ret; + } + callRet = g_devCredMgrMethod.queryCredInfoByCredId(osAccountId, credId, &returnCredInfo); + ret = IpcEncodeCallReply(outCache, PARAM_TYPE_IPC_RESULT, (const uint8_t *)&callRet, sizeof(int32_t)); + ret += IpcEncodeCallReply(outCache, PARAM_TYPE_IPC_RESULT_NUM, (const uint8_t *)&IPC_RESULT_NUM_1, sizeof(int32_t)); + if (returnCredInfo != NULL) { + ret += IpcEncodeCallReply(outCache, PARAM_TYPE_CRED_INFO, (const uint8_t *)returnCredInfo, + HcStrlen(returnCredInfo) + 1); + } else { + ret += IpcEncodeCallReply(outCache, PARAM_TYPE_CRED_INFO, NULL, 0); + } + g_devCredMgrMethod.destroyInfo(&returnCredInfo); + LOGI("process done, call ret %d, ipc ret %d", callRet, ret); + return ret; +} + +int32_t IpcServiceCmDeleteCredential(const IpcDataInfo *ipcParams, int32_t paramNum, uintptr_t outCache) +{ + int32_t callRet; + int32_t ret; + int32_t osAccountId; + int32_t inOutLen; + const char *credId = NULL; + const char *appId = NULL; + LOGI("starting ..."); + inOutLen = sizeof(int32_t); + ret = GetAndValSize32Param(ipcParams, paramNum, PARAM_TYPE_OS_ACCOUNT_ID, (uint8_t *)&osAccountId, &inOutLen); + if (ret != HC_SUCCESS) { + LOGE("get param error, type %d", PARAM_TYPE_OS_ACCOUNT_ID); + return ret; + } + ret = GetAndValNullParam(ipcParams, paramNum, PARAM_TYPE_APPID, (uint8_t *)&appId, NULL); + if (ret != HC_SUCCESS) { + LOGE("get param error, type %d", PARAM_TYPE_APPID); + return ret; + } + ret = GetAndValNullParam(ipcParams, paramNum, PARAM_TYPE_CRED_ID, (uint8_t *)&credId, NULL); + if (ret != HC_SUCCESS) { + LOGE("get param error, type %d", PARAM_TYPE_CRED_ID); + return ret; + } + callRet = g_devCredMgrMethod.deleteCredential(osAccountId, appId, credId); + ret = IpcEncodeCallReply(outCache, PARAM_TYPE_IPC_RESULT, (const uint8_t *)&callRet, sizeof(int32_t)); + LOGI("process done, call ret %d, ipc ret %d", callRet, ret); + return ret; +} + +int32_t IpcServiceCmUpdateCredInfo(const IpcDataInfo *ipcParams, int32_t paramNum, uintptr_t outCache) +{ + int32_t callRet; + int32_t ret; + int32_t osAccountId; + int32_t inOutLen; + const char *credId = NULL; + const char *appId = NULL; + const char *requestParams = NULL; + LOGI("starting ..."); + inOutLen = sizeof(int32_t); + ret = GetAndValSize32Param(ipcParams, paramNum, PARAM_TYPE_OS_ACCOUNT_ID, (uint8_t *)&osAccountId, &inOutLen); + if (ret != HC_SUCCESS) { + LOGE("get param error, type %d", PARAM_TYPE_OS_ACCOUNT_ID); + return ret; + } + ret = GetAndValNullParam(ipcParams, paramNum, PARAM_TYPE_APPID, (uint8_t *)&appId, NULL); + if (ret != HC_SUCCESS) { + LOGE("get param error, type %d", PARAM_TYPE_APPID); + return ret; + } + ret = GetAndValNullParam(ipcParams, paramNum, PARAM_TYPE_CRED_ID, (uint8_t *)&credId, NULL); + if (ret != HC_SUCCESS) { + LOGE("get param error, type %d", PARAM_TYPE_CRED_ID); + return ret; + } + ret = GetAndValNullParam(ipcParams, paramNum, PARAM_TYPE_REQUEST_PARAMS, (uint8_t *)&requestParams, NULL); + if (ret != HC_SUCCESS) { + LOGE("get param error, type %d", PARAM_TYPE_REQUEST_PARAMS); + return ret; + } + callRet = g_devCredMgrMethod.updateCredInfo(osAccountId, appId, credId, requestParams); + ret = IpcEncodeCallReply(outCache, PARAM_TYPE_IPC_RESULT, (const uint8_t *)&callRet, sizeof(int32_t)); + LOGI("process done, call ret %d, ipc ret %d", callRet, ret); + return ret; +} + + +int32_t IpcServiceCaAuthDevice(const IpcDataInfo *ipcParams, int32_t paramNum, uintptr_t outCache) +{ + int32_t ret; + DeviceAuthCallback *caCallback = NULL; + int32_t osAccountId; + int64_t reqId = 0; + const char *authParams = NULL; + int32_t inOutLen; + int32_t cbObjIdx = -1; + + inOutLen = sizeof(int32_t); + ret = GetAndValSize32Param(ipcParams, paramNum, PARAM_TYPE_OS_ACCOUNT_ID, (uint8_t *)&osAccountId, &inOutLen); + if (ret != HC_SUCCESS) { + return ret; + } + inOutLen = sizeof(int64_t); + ret = GetAndValSize64Param(ipcParams, paramNum, PARAM_TYPE_REQID, (uint8_t *)&reqId, &inOutLen); + if (ret != HC_SUCCESS) { + return ret; + } + ret = GetAndValNullParam(ipcParams, paramNum, PARAM_TYPE_AUTH_PARAMS, (uint8_t *)&authParams, NULL); + if (ret != HC_SUCCESS) { + return ret; + } + inOutLen = sizeof(DeviceAuthCallback); + ret = GetAndValSizeCbParam(ipcParams, paramNum, PARAM_TYPE_DEV_AUTH_CB, (uint8_t *)&caCallback, &inOutLen); + if (ret != HC_SUCCESS) { + return ret; + } + + /* add call back */ + ret = AddIpcCallBackByReqId(reqId, (const uint8_t *)caCallback, sizeof(DeviceAuthCallback), CB_TYPE_CRED_DEV_AUTH); + if (ret != HC_SUCCESS) { + return ret; + } + inOutLen = sizeof(int32_t); + ret = GetIpcRequestParamByType(ipcParams, paramNum, PARAM_TYPE_CB_OBJECT, (uint8_t *)&cbObjIdx, &inOutLen); + if (ret != HC_SUCCESS) { + LOGE("get param error, type %d", PARAM_TYPE_CB_OBJECT); + DelIpcCallBackByReqId(reqId, CB_TYPE_CRED_DEV_AUTH, true); + return ret; + } + AddIpcCbObjByReqId(reqId, cbObjIdx, CB_TYPE_CRED_DEV_AUTH); + InitDeviceAuthCbCtx(&g_authCbAdt, CB_TYPE_CRED_DEV_AUTH); + ret = g_credAuthMgrMethod.authCredential(osAccountId, reqId, authParams, &g_authCbAdt); + if (ret != HC_SUCCESS) { + DelIpcCallBackByReqId(reqId, CB_TYPE_CRED_DEV_AUTH, true); + } + return IpcEncodeCallReply(outCache, PARAM_TYPE_IPC_RESULT, (const uint8_t *)&ret, sizeof(int32_t)); +} + + +int32_t IpcServiceCaProcessCredData(const IpcDataInfo *ipcParams, int32_t paramNum, uintptr_t outCache) +{ + int32_t callRet; + int32_t ret; + const DeviceAuthCallback *caCallback = NULL; + int64_t reqId = 0; + uint8_t *data = NULL; + uint32_t dataLen = 0; + int32_t inOutLen; + int32_t cbObjIdx = -1; + + LOGI("starting ..."); + inOutLen = sizeof(int64_t); + ret = GetAndValSize64Param(ipcParams, paramNum, PARAM_TYPE_REQID, (uint8_t *)&reqId, &inOutLen); + if (ret != HC_SUCCESS) { + return ret; + } + ret = GetIpcRequestParamByType(ipcParams, paramNum, PARAM_TYPE_COMM_DATA, (uint8_t *)&data, (int32_t *)&dataLen); + if ((data == NULL) || (dataLen == 0) || (ret != HC_SUCCESS)) { + LOGE("get param error, type %d", PARAM_TYPE_COMM_DATA); + return HC_ERR_IPC_BAD_PARAM; + } + inOutLen = sizeof(DeviceAuthCallback); + ret = GetAndValSizeCbParam(ipcParams, paramNum, PARAM_TYPE_DEV_AUTH_CB, (uint8_t *)&caCallback, &inOutLen); + if (ret != HC_SUCCESS) { + return ret; + } + /* add call back */ + ret = AddIpcCallBackByReqId(reqId, (const uint8_t *)caCallback, sizeof(DeviceAuthCallback), CB_TYPE_CRED_DEV_AUTH); + if (ret != HC_SUCCESS) { + LOGE("add ipc callback failed"); + return ret; + } + inOutLen = sizeof(int32_t); + ret = GetIpcRequestParamByType(ipcParams, paramNum, PARAM_TYPE_CB_OBJECT, (uint8_t *)&cbObjIdx, &inOutLen); + if (ret != HC_SUCCESS) { + LOGE("get param error, type %d", PARAM_TYPE_CB_OBJECT); + DelIpcCallBackByReqId(reqId, CB_TYPE_CRED_DEV_AUTH, true); + return HC_ERR_IPC_BAD_PARAM; + } + AddIpcCbObjByReqId(reqId, cbObjIdx, CB_TYPE_CRED_DEV_AUTH); + InitDeviceAuthCbCtx(&g_authCbAdt, CB_TYPE_CRED_DEV_AUTH); + callRet = g_credAuthMgrMethod.processCredData(reqId, data, dataLen, &g_authCbAdt); + if (callRet != HC_SUCCESS) { + DelIpcCallBackByReqId(reqId, CB_TYPE_CRED_DEV_AUTH, true); + } + return IpcEncodeCallReply(outCache, PARAM_TYPE_IPC_RESULT, (const uint8_t *)&callRet, sizeof(int32_t)); +} +#endif + +#ifdef DEV_AUTH_IS_ENABLE +static int32_t ISIpcInit(void) +{ + const CredManager *cmInst = NULL; + const CredAuthManager *caInst = NULL; + cmInst = GetCredMgrInstance(); + caInst = GetCredAuthInstance(); + if (cmInst == NULL || caInst == NULL) { + DeInitIpcCallBackList(); + LOGE("MainInit, GetGmInstance failed"); + return HC_ERROR; + } + g_devCredMgrMethod = (CredManager)(*cmInst); + g_credAuthMgrMethod = (CredAuthManager)(*caInst); + InitDevAuthCredListenerCbCtx(&g_credListenCbAdt); + int32_t ret = cmInst->registerChangeListener(SERVICE_APP_ID, &g_credListenCbAdt); + if (ret != HC_SUCCESS) { + DeInitIpcCallBackList(); + LOGE("MainInit, register ipc cred listener failed, ret %d", ret); + return HC_ERROR; + } + return HC_SUCCESS; +} +#endif + int32_t MainRescInit(void) { int32_t ret; + LOGI("starting ..."); const DeviceGroupManager *gmInst = NULL; const GroupAuthManager *gaInst = NULL; - - LOGI("starting ..."); ret = InitIpcCallBackList(); if (ret != HC_SUCCESS) { return ret; @@ -1268,7 +1680,13 @@ int32_t MainRescInit(void) LOGE("MainInit, register ipc listener failed, ret %d", ret); return HC_ERROR; } - +#ifdef DEV_AUTH_IS_ENABLE + ret = ISIpcInit(); + if (ret != HC_SUCCESS) { + LOGE("IS ipc init failed."); + return ret; + } +#endif LOGI("process done"); return HC_SUCCESS; } @@ -1278,6 +1696,11 @@ void DeMainRescInit(void) if (g_devGroupMgrMethod.unRegDataChangeListener != NULL) { (void)g_devGroupMgrMethod.unRegDataChangeListener(SERVICE_APP_ID); } +#ifdef DEV_AUTH_IS_ENABLE + if (g_devCredMgrMethod.unregisterChangeListener != NULL) { + (void)g_devCredMgrMethod.unregisterChangeListener(SERVICE_APP_ID); + } +#endif DeInitIpcCallBackList(); } diff --git a/frameworks/src/standard/ipc_adapt.cpp b/frameworks/src/standard/ipc_adapt.cpp index 7d7d1545788b5cd98c80224abdbb7337a9b5a313..7951bf42bf1420eb731510177e6d1304e9f1d3e9 100644 --- a/frameworks/src/standard/ipc_adapt.cpp +++ b/frameworks/src/standard/ipc_adapt.cpp @@ -51,6 +51,7 @@ typedef struct { union { DeviceAuthCallback devAuth; DataChangeListener listener; + CredChangeListener credListener; } cbCtx; int64_t requestId; char appId[BUFF_MAX_SZ]; @@ -633,16 +634,62 @@ __attribute__((no_sanitize("cfi"))) static void OnTrustDevNumChangedStub(Callbac return; } +__attribute__((no_sanitize("cfi"))) static void OnCredAddStub(CallbackParams params) +{ + char *credId = nullptr; + char *credInfo = nullptr; + void (*onCredAddHook)(char *, char *) = nullptr; + onCredAddHook = reinterpret_cast(params.cbHook); + + (void)GetIpcRequestParamByType(params.cbDataCache, params.cacheNum, PARAM_TYPE_CRED_ID, + reinterpret_cast(&credId), nullptr); + (void)GetIpcRequestParamByType(params.cbDataCache, params.cacheNum, PARAM_TYPE_CRED_INFO, + reinterpret_cast(&credInfo), nullptr); + onCredAddHook(credId, credInfo); + return; +} + +__attribute__((no_sanitize("cfi"))) static void OnCredDeleteStub(CallbackParams params) +{ + char *credId = nullptr; + char *credInfo = nullptr; + void (*onCredDeleteHook)(char *, char *) = nullptr; + onCredDeleteHook = reinterpret_cast(params.cbHook); + + (void)GetIpcRequestParamByType(params.cbDataCache, params.cacheNum, PARAM_TYPE_CRED_ID, + reinterpret_cast(&credId), nullptr); + (void)GetIpcRequestParamByType(params.cbDataCache, params.cacheNum, PARAM_TYPE_CRED_INFO, + reinterpret_cast(&credInfo), nullptr); + onCredDeleteHook(credId, credInfo); + return; +} + +__attribute__((no_sanitize("cfi"))) static void OnCredUpdateStub(CallbackParams params) +{ + char *credId = nullptr; + char *credInfo = nullptr; + void (*onCredUpdateHook)(char *, char *) = nullptr; + onCredUpdateHook = reinterpret_cast(params.cbHook); + + (void)GetIpcRequestParamByType(params.cbDataCache, params.cacheNum, PARAM_TYPE_CRED_ID, + reinterpret_cast(&credId), nullptr); + (void)GetIpcRequestParamByType(params.cbDataCache, params.cacheNum, PARAM_TYPE_CRED_INFO, + reinterpret_cast(&credInfo), nullptr); + onCredUpdateHook(credId, credInfo); + return; +} + void ProcCbHook(int32_t callbackId, uintptr_t cbHook, const IpcDataInfo *cbDataCache, int32_t cacheNum, uintptr_t replyCtx) { CallbackStub stubTable[] = { OnTransmitStub, OnSessKeyStub, OnFinishStub, OnErrorStub, OnRequestStub, OnGroupCreatedStub, OnGroupDeletedStub, OnDevBoundStub, - OnDevUnboundStub, OnDevUnTrustStub, OnDelLastGroupStub, OnTrustDevNumChangedStub + OnDevUnboundStub, OnDevUnTrustStub, OnDelLastGroupStub, OnTrustDevNumChangedStub, + OnCredAddStub, OnCredDeleteStub, OnCredUpdateStub, }; MessageParcel *reply = reinterpret_cast(replyCtx); - if ((callbackId < CB_ID_ON_TRANS) || (callbackId > CB_ID_ON_TRUST_DEV_NUM_CHANGED)) { + if ((callbackId < CB_ID_ON_TRANS) || (callbackId > CB_ID_ON_CRED_UPDATE)) { LOGE("Invalid call back id"); return; } @@ -672,7 +719,7 @@ static uint32_t EncodeCallData(MessageParcel &dataParcel, int32_t type, const ui return static_cast(HC_ERROR); } -/* group auth callback adapter */ +/* group or cred auth callback adapter */ static bool GaCbOnTransmitWithType(int64_t requestId, const uint8_t *data, uint32_t dataLen, int32_t type) { int32_t ret = -1; @@ -714,6 +761,11 @@ static bool TmpIpcGaCbOnTransmit(int64_t requestId, const uint8_t *data, uint32_ return GaCbOnTransmitWithType(requestId, data, dataLen, CB_TYPE_TMP_DEV_AUTH); } +static bool IpcCaCbOnTransmit(int64_t requestId, const uint8_t *data, uint32_t dataLen) +{ + return GaCbOnTransmitWithType(requestId, data, dataLen, CB_TYPE_CRED_DEV_AUTH); +} + static void GaCbOnSessionKeyRetWithType(int64_t requestId, const uint8_t *sessKey, uint32_t sessKeyLen, int32_t type) { uint32_t ret; @@ -753,6 +805,12 @@ static void TmpIpcGaCbOnSessionKeyReturned(int64_t requestId, const uint8_t *ses return; } +static void IpcCaCbOnSessionKeyReturned(int64_t requestId, const uint8_t *sessKey, uint32_t sessKeyLen) +{ + GaCbOnSessionKeyRetWithType(requestId, sessKey, sessKeyLen, CB_TYPE_CRED_DEV_AUTH); + return; +} + static void GaCbOnFinishWithType(int64_t requestId, int32_t operationCode, const char *returnData, int32_t type) { uint32_t ret; @@ -798,6 +856,12 @@ static void TmpIpcGaCbOnFinish(int64_t requestId, int32_t operationCode, const c return; } +static void IpcCaCbOnFinish(int64_t requestId, int32_t operationCode, const char *returnData) +{ + GaCbOnFinishWithType(requestId, operationCode, returnData, CB_TYPE_CRED_DEV_AUTH); + return; +} + static void GaCbOnErrorWithType(int64_t requestId, int32_t operationCode, int32_t errorCode, const char *errorReturn, int32_t type) { @@ -845,6 +909,12 @@ static void TmpIpcGaCbOnError(int64_t requestId, int32_t operationCode, int32_t return; } +static void IpcCaCbOnError(int64_t requestId, int32_t operationCode, int32_t errorCode, const char *errorReturn) +{ + GaCbOnErrorWithType(requestId, operationCode, errorCode, errorReturn, CB_TYPE_CRED_DEV_AUTH); + return; +} + static char *GaCbOnRequestWithType(int64_t requestId, int32_t operationCode, const char *reqParams, int32_t type) { int32_t ret = -1; @@ -889,16 +959,16 @@ static char *GaCbOnRequestWithType(int64_t requestId, int32_t operationCode, con return nullptr; } -static bool CanFindCbByReqId(int64_t requestId) +static bool CanFindCbByReqId(int64_t requestId, int32_t type) { std::lock_guard autoLock(g_cbListLock); - IpcCallBackNode *node = GetIpcCallBackByReqId(requestId, CB_TYPE_DEV_AUTH); + IpcCallBackNode *node = GetIpcCallBackByReqId(requestId, type); return (node != nullptr) ? true : false; } static char *IpcGaCbOnRequest(int64_t requestId, int32_t operationCode, const char *reqParams) { - if (!CanFindCbByReqId(requestId)) { + if (!CanFindCbByReqId(requestId, CB_TYPE_DEV_AUTH)) { CJson *reqParamsJson = CreateJsonFromString(reqParams); if (reqParamsJson == nullptr) { LOGE("failed to create json from string!"); @@ -924,6 +994,29 @@ static char *TmpIpcGaCbOnRequest(int64_t requestId, int32_t operationCode, const return GaCbOnRequestWithType(requestId, operationCode, reqParams, CB_TYPE_TMP_DEV_AUTH); } +static char *IpcCaCbOnRequest(int64_t requestId, int32_t operationCode, const char *reqParams) +{ + if (!CanFindCbByReqId(requestId, CB_TYPE_CRED_DEV_AUTH)) { + CJson *reqParamsJson = CreateJsonFromString(reqParams); + if (reqParamsJson == nullptr) { + LOGE("failed to create json from string!"); + return nullptr; + } + const char *callerAppId = GetStringFromJson(reqParamsJson, FIELD_APP_ID); + if (callerAppId == nullptr) { + LOGE("failed to get appId from json object!"); + FreeJson(reqParamsJson); + return nullptr; + } + int32_t ret = AddReqIdByAppId(callerAppId, requestId); + FreeJson(reqParamsJson); + if (ret != HC_SUCCESS) { + return nullptr; + } + } + return GaCbOnRequestWithType(requestId, operationCode, reqParams, CB_TYPE_CRED_DEV_AUTH); +} + namespace { void IpcOnGroupCreated(const char *groupInfo) { @@ -1198,6 +1291,128 @@ void IpcOnTrustedDeviceNumChanged(int32_t curTrustedDeviceNum) } return; } + +void IpcOnCredAdd(const char *credId, const char *credInfo) +{ + int32_t i; + uint32_t ret; + MessageParcel dataParcel; + MessageParcel reply; + CredChangeListener *listener = nullptr; + + std::lock_guard autoLock(g_cbListLock); + if (g_ipcCallBackList.ctx == nullptr) { + LOGE("IpcCallBackList un-initialized"); + return; + } + + if (credId == nullptr) { + LOGE("IpcOnCredAdd failed, params error"); + return; + } + ret = EncodeCallData(dataParcel, PARAM_TYPE_CRED_ID, + reinterpret_cast(credId), HcStrlen(credId) + 1); + ret |= EncodeCallData(dataParcel, PARAM_TYPE_CRED_INFO, + reinterpret_cast(credInfo), HcStrlen(credInfo) + 1); + if (ret != HC_SUCCESS) { + LOGE("IpcGaCbOnRequest, build trans data failed"); + return; + } + + for (i = 0; i < IPC_CALL_BACK_MAX_NODES; i++) { + if (g_ipcCallBackList.ctx[i].cbType == CB_TYPE_CRED_LISTENER) { + listener = &(g_ipcCallBackList.ctx[i].cbCtx.credListener); + if (listener->onCredAdd == nullptr) { + continue; + } + ServiceDevAuth::ActCallback(g_ipcCallBackList.ctx[i].proxyId, CB_ID_ON_CRED_ADD, + false, reinterpret_cast(listener->onCredAdd), dataParcel, reply); + } + } + return; +} + +void IpcOnCredDelete(const char *credId, const char *credInfo) +{ + int32_t i; + uint32_t ret; + MessageParcel dataParcel; + MessageParcel reply; + CredChangeListener *listener = nullptr; + + std::lock_guard autoLock(g_cbListLock); + if (g_ipcCallBackList.ctx == nullptr) { + LOGE("IpcCallBackList un-initialized"); + return; + } + + if (credId == nullptr) { + LOGE("IpcOnCredDelete failed, params error"); + return; + } + + ret = EncodeCallData(dataParcel, PARAM_TYPE_CRED_ID, + reinterpret_cast(credId), HcStrlen(credId) + 1); + ret |= EncodeCallData(dataParcel, PARAM_TYPE_CRED_INFO, + reinterpret_cast(credInfo), HcStrlen(credInfo) + 1); + if (ret != HC_SUCCESS) { + LOGE("IpcGaCbOnRequest, build trans data failed"); + return; + } + + for (i = 0; i < IPC_CALL_BACK_MAX_NODES; i++) { + if (g_ipcCallBackList.ctx[i].cbType == CB_TYPE_CRED_LISTENER) { + listener = &(g_ipcCallBackList.ctx[i].cbCtx.credListener); + if (listener->onCredDelete == nullptr) { + continue; + } + ServiceDevAuth::ActCallback(g_ipcCallBackList.ctx[i].proxyId, CB_ID_ON_CRED_DELETE, + false, reinterpret_cast(listener->onCredDelete), dataParcel, reply); + } + } + return; +} + +void IpcOnCredUpdate(const char *credId, const char *credInfo) +{ + int32_t i; + uint32_t ret; + MessageParcel dataParcel; + MessageParcel reply; + CredChangeListener *listener = nullptr; + + std::lock_guard autoLock(g_cbListLock); + if (g_ipcCallBackList.ctx == nullptr) { + LOGE("IpcCallBackList un-initialized"); + return; + } + + if (credId == nullptr) { + LOGE("IpcOnCredUpdate failed, params error"); + return; + } + + ret = EncodeCallData(dataParcel, PARAM_TYPE_CRED_ID, + reinterpret_cast(credId), HcStrlen(credId) + 1); + ret |= EncodeCallData(dataParcel, PARAM_TYPE_CRED_INFO, + reinterpret_cast(credInfo), HcStrlen(credInfo) + 1); + if (ret != HC_SUCCESS) { + LOGE("IpcGaCbOnRequest, build trans data failed"); + return; + } + + for (i = 0; i < IPC_CALL_BACK_MAX_NODES; i++) { + if (g_ipcCallBackList.ctx[i].cbType == CB_TYPE_CRED_LISTENER) { + listener = &(g_ipcCallBackList.ctx[i].cbCtx.credListener); + if (listener->onCredUpdate == nullptr) { + continue; + } + ServiceDevAuth::ActCallback(g_ipcCallBackList.ctx[i].proxyId, CB_ID_ON_CRED_UPDATE, + false, reinterpret_cast(listener->onCredUpdate), dataParcel, reply); + } + } + return; +} }; void InitDeviceAuthCbCtx(DeviceAuthCallback *ctx, int32_t type) @@ -1219,6 +1434,13 @@ void InitDeviceAuthCbCtx(DeviceAuthCallback *ctx, int32_t type) ctx->onError = TmpIpcGaCbOnError; ctx->onRequest = TmpIpcGaCbOnRequest; } + if (type == CB_TYPE_CRED_DEV_AUTH) { + ctx->onTransmit = IpcCaCbOnTransmit; + ctx->onSessionKeyReturned = IpcCaCbOnSessionKeyReturned; + ctx->onFinish = IpcCaCbOnFinish; + ctx->onError = IpcCaCbOnError; + ctx->onRequest = IpcCaCbOnRequest; + } return; } @@ -1237,6 +1459,17 @@ void InitDevAuthListenerCbCtx(DataChangeListener *ctx) return; } +void InitDevAuthCredListenerCbCtx(CredChangeListener *ctx) +{ + if (ctx == nullptr) { + return; + } + ctx->onCredAdd = IpcOnCredAdd; + ctx->onCredDelete = IpcOnCredDelete; + ctx->onCredUpdate = IpcOnCredUpdate; + return; +} + /* ipc client process adapter */ int32_t CreateCallCtx(uintptr_t *callCtx, uintptr_t *cbCtx) { @@ -1434,7 +1667,8 @@ static bool IsTypeForSettingPtr(int32_t type) PARAM_TYPE_GROUPID, PARAM_TYPE_UDID, PARAM_TYPE_ADD_PARAMS, PARAM_TYPE_DEL_PARAMS, PARAM_TYPE_QUERY_PARAMS, PARAM_TYPE_COMM_DATA, PARAM_TYPE_SESS_KEY, PARAM_TYPE_REQ_INFO, PARAM_TYPE_GROUP_INFO, PARAM_TYPE_AUTH_PARAMS, PARAM_TYPE_REQ_JSON, - PARAM_TYPE_PSEUDONYM_ID, PARAM_TYPE_INDEX_KEY, PARAM_TYPE_ERR_INFO + PARAM_TYPE_PSEUDONYM_ID, PARAM_TYPE_INDEX_KEY, PARAM_TYPE_ERR_INFO, PARAM_TYPE_REQUEST_PARAMS, + PARAM_TYPE_CRED_ID, }; int32_t i; int32_t n = sizeof(typeList) / sizeof(typeList[0]); @@ -1504,7 +1738,9 @@ bool IsCallbackMethod(int32_t methodId) { if ((methodId == IPC_CALL_ID_REG_CB) || (methodId == IPC_CALL_ID_REG_LISTENER) || (methodId == IPC_CALL_ID_DA_AUTH_DEVICE) || (methodId == IPC_CALL_ID_DA_PROC_DATA) || - (methodId == IPC_CALL_ID_GA_PROC_DATA) || (methodId == IPC_CALL_ID_AUTH_DEVICE)) { + (methodId == IPC_CALL_ID_GA_PROC_DATA) || (methodId == IPC_CALL_ID_AUTH_DEVICE) || + (methodId == IPC_CALL_ID_CM_REG_LISTENER) || (methodId == IPC_CALL_ID_CA_AUTH_DEVICE) || + (methodId == IPC_CALL_ID_CA_PROCESS_CRED_DATA)) { return true; } return false; diff --git a/frameworks/src/standard/server/ipc_dev_auth_stub.cpp b/frameworks/src/standard/server/ipc_dev_auth_stub.cpp index 11e88486fdeb05bbc252c09667b6cc6947c72ad9..61414c7b0e97aaf88c30937a4520741f6be53482 100644 --- a/frameworks/src/standard/server/ipc_dev_auth_stub.cpp +++ b/frameworks/src/standard/server/ipc_dev_auth_stub.cpp @@ -29,7 +29,7 @@ #ifdef DEV_AUTH_SERVICE_BUILD #include "account_task_manager.h" -#include "data_manager.h" +#include "group_data_manager.h" #include "hisysevent_adapter.h" #endif diff --git a/interfaces/inner_api/device_auth.h b/interfaces/inner_api/device_auth.h index 970e706806d084eceaba0fe74a25deb0c689157f..669ac235b2b7f0433f6e0b8c737c4dcf9148001c 100644 --- a/interfaces/inner_api/device_auth.h +++ b/interfaces/inner_api/device_auth.h @@ -25,11 +25,15 @@ #define DEVICE_AUTH_API_PUBLIC #endif +#define FIELD_CREDENTIAL_VAL "credentialVal" +#define FIELD_CREDENTIAL_OWNER "credentialOwner" +#define FIELD_PEER_USER_SPACE_ID "peerUserSpaceId" #define FIELD_GROUP_ID "groupId" #define FIELD_GROUP_TYPE "groupType" #define FIELD_GROUP_NAME "groupName" #define FIELD_PEER_DEVICE_ID "peerDeviceId" #define FIELD_IS_ADMIN "isAdmin" +#define FIELD_CRED_TYPE "credType" #define FIELD_CREDENTIAL_TYPE "credentialType" #define FIELD_IS_FORCE_DELETE "isForceDelete" #define FIELD_IS_IGNORE_CHANNEL "isIgnoreChannel" @@ -74,6 +78,22 @@ #define FIELD_PROTOCOL_EXPAND "protocolExpand" #define FIELD_IS_SELF_FROM_UPGRADE "isSelfFromUpgrade" #define FIELD_IS_PEER_FROM_UPGRADE "isPeerFromUpgrade" +#define FIELD_IS_CRED_AUTH "isCredAuth" +#define FIELD_CRED_ID "credId" +#define FIELD_SELF_CRED_ID "selfCredId" +#define FIELD_PEER_CRED_ID "peerCredId" +#define FIELD_SELF_CREDENTIAL_OBJ "selfCredentialObject" +#define FIELD_PEER_CREDENTIAL_OBJ "peerCredentialObject" +#define FIELD_CREDENTIAL_FORMAT "credentialFormat" +#define FIELD_SUBJECT "subject" +#define FIELD_ISSUER "issuer" +#define FIELD_KEY_FORMAT "keyFormat" +#define FIELD_PROOF_TYPE "proofType" +#define FIELD_ALGORITHM_TYPE "algorithmType" +#define FIELD_CRED_OWNER "credOwner" +#define FIELD_AUTHORIZED_ACCOUNT_LIST "authorizedAccountList" +#define FIELD_PROTOCOL_TYPE "protocolType" +#define FIELD_EXTEND_INFO "extendInfo" /** * @brief protocol expand value for bind @@ -200,6 +220,18 @@ typedef struct { void (*onTrustedDeviceNumChanged)(int curTrustedDeviceNum); } DataChangeListener; +/** + * @brief This structure provides the ability to monitor changes in credentials. + */ +typedef struct { + /** Call it when a cred add. */ + void (*onCredAdd)(const char *credId, const char *credInfo); + /** Call it when a cred is delete. */ + void (*onCredDelete)(const char *credId, const char *credInfo); + /** Call it when a cred update. */ + void (*onCredUpdate)(const char *credId, const char *credInfo); +} CredChangeListener; + /** * @brief This structure describes the callbacks that need to be provided by the business. */ @@ -328,6 +360,18 @@ typedef enum { P2P_BIND, } AcquireType; +/** + * @brief This structure provides all the capabilities of credential authentication. + */ +typedef struct { + /** This interface is used to process authentication data. */ + int32_t (*processCredData)(int64_t authReqId, const uint8_t *data, uint32_t dataLen, + const DeviceAuthCallback *gaCallback); + /** This interface is used to initiate authentication between devices. */ + int32_t (*authCredential)(int32_t osAccountId, int64_t authReqId, const char *authParams, + const DeviceAuthCallback *gaCallback); +} CredAuthManager; + #ifdef __cplusplus extern "C" { #endif @@ -432,6 +476,39 @@ DEVICE_AUTH_API_PUBLIC const GroupAuthManager *GetGaInstance(void); */ DEVICE_AUTH_API_PUBLIC const DeviceGroupManager *GetGmInstance(void); +typedef struct { + int32_t (*addCredential)(int32_t osAccountId, const char *requestParams, char **returnData); + + int32_t (*exportCredential)(int32_t osAccountId, const char *credId, char **returnData); + + int32_t (*queryCredentialByParams)(int32_t osAccountId, const char *requestParams, char **returnData); + + int32_t (*queryCredInfoByCredId)(int32_t osAccountId, const char *credId, char **returnData); + + int32_t (*deleteCredential)(int32_t osAccountId, const char *appId, const char *credId); + + int32_t (*updateCredInfo)(int32_t osAccountId, const char *appId, const char *credId, const char *requestParams); + + int32_t (*registerChangeListener)(const char *appId, CredChangeListener *listener); + + int32_t (*unregisterChangeListener)(const char *appId); + + void (*destroyInfo)(char **returnData); +} CredManager; + +DEVICE_AUTH_API_PUBLIC const CredManager *GetCredMgrInstance(void); + +/** + * @brief Get credential authentication instance. + * + * This API is used to get credential authentication instance. + * The InitDeviceAuthService function must be called before using this method. + * + * @return When the method call result is successful, it returns CredAuthManager instance. + * Otherwise, it returns NULL. + */ +DEVICE_AUTH_API_PUBLIC const CredAuthManager *GetCredAuthInstance(void); + #ifdef __cplusplus } #endif diff --git a/interfaces/inner_api/device_auth_defines.h b/interfaces/inner_api/device_auth_defines.h index 5456a41fbd9973b01949641f229da93199bbf4f8..fe18f490deaac5cbb4263574348c14e36ad20bfb 100644 --- a/interfaces/inner_api/device_auth_defines.h +++ b/interfaces/inner_api/device_auth_defines.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021-2023 Huawei Device Co., Ltd. + * Copyright (C) 2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -150,6 +150,52 @@ enum { HC_ERR_CLIENT_CONFIRM_PROTOCOL = 0x00009008, // 36872 HC_ERR_SERVER_CONFIRM_PROTOCOL = 0x00009009, // 36873 + IS_SUCCESS = 0x00000000, // 0 + /* IS interface error */ + IS_ERR_HUKS_GENERATE_KEY_FAILED = 0x00010001, // 65537 + IS_ERR_HUKS_IMPORT_KEY_FAILED = 0x00010002, // 65538 + IS_ERR_HUKS_SHA256_FAILED = 0x00010003, // 65539 + IS_ERR_HUKS_DELETE_FAILED = 0x00010004, // 65540 + IS_ERR_HUKS_KEY_NOT_EXIST = 0x00010005, // 65541 + IS_ERR_HUKS_CHECK_KEY_EXIST_FAILED = 0x00010006, // 65542 + IS_ERR_HUKS_EXPORT_KEY_FAILED = 0x00010007, // 65543 + // IS_ERR_SAVE_CRED_FAILED = 0x00010008, // 65544 + IS_ERR_LOCAL_CRED_NOT_EXIST = 0x00010009, // 65545 + // IS_ERR_LOCAL_CRED_DELETE_FAILED = 0x0001000A, // 65546 + IS_AUTH_ERR_CLIENT_CRED_NOT_EXIST = 0x0001000B, // 65547 + IS_AUTH_ERR_CLIENT_KEY_NOT_EXIST = 0x0001000C, // 65548 + IS_AUTH_ERR_SERVER_CRED_NOT_EXIST = 0x0001000D, // 65549 + IS_AUTH_ERR_SERVER_KEY_NOT_EXIST = 0x0001000E, // 65550 + IS_AUTH_ERR_PIN_NOT_MATCH = 0x0001000F, // 65551 + IS_AUTH_ERR_PROOF_NOT_MATCH = 0x00010010, // 65552 + + // IS json error + IS_ERR_JSON_FAILED = 0x00020001, // 131073 + IS_ERR_JSON_CREATE = 0x00020002, // 131074 + IS_ERR_JSON_GET = 0x00020003, // 131075 + IS_ERR_JSON_ADD = 0x00020004, // 131076 + IS_ERR_PACKAGE_JSON_TO_STRING_FAIL = 0x00020005, // 131077 + + // IS DB error + // IS_ERR_DB = 0x00030001, // 196609 + IS_ERR_BEYOND_LIMIT = 0x00030002, // 196610 + IS_ERR_OS_ACCOUNT_NOT_UNLOCKED = 0x00030003, // 196611 + IS_ERR_SERVICE_NEED_RESTART = 0x00030004, // 196612 + + // IS common error + IS_ERROR = 0x00040001, // 262145 + IS_ERR_INVALID_PARAMS = 0x00040002, // 262146 + // IS_ERR_INVALID_LEN = 0x00040003, // 262147 + IS_ERR_NULL_PTR = 0x00040004, // 262148 + IS_ERR_ALLOC_MEMORY = 0x00040005, // 262149 + IS_ERR_MEMORY_COPY = 0x00040006, // 262150 + IS_ERR_CONVERT_FAILED = 0x00040007, // 262151 + IS_ERR_NOT_SUPPORT = 0x00040008, // 262152 + IS_ERR_INIT_FAILED = 0x00040009, // 262153 + + // IS listener error + IS_ERR_LISTENER_NOT_EXIST = 0x00050001, // 327681 + /* error code used on DAS service */ INVALID_PARAMETERS = 0xF0000001, // -268435455 EXCEED_AUTHORITY = 0xF0000002, // -268435454 diff --git a/interfaces/inner_api/device_auth_ext.h b/interfaces/inner_api/device_auth_ext.h index bc5b5af529ba6b9f14dd550111cb7594db6007c4..aa20084f1b51a6f3aaa1207af685c05c0d43c1a1 100644 --- a/interfaces/inner_api/device_auth_ext.h +++ b/interfaces/inner_api/device_auth_ext.h @@ -132,6 +132,16 @@ typedef struct { void (*notifyAsyncTaskStart)(void); /** This interface is used to notify the account async task is stopped. */ void (*notifyAsyncTaskStop)(void); + /** This interface is used to import credential data. */ + int32_t (*addCredential)(int32_t osAccountId, const char *requestParams, char **returnData); + /** This interface is used to export credential data. */ + int32_t (*exportCredential)(int32_t osAccountId, const char *credId, char **returnData); + /** This interface is used to delete credential data. */ + int32_t (*deleteCredential)(int32_t osAccountId, const char *appId, const char *credId); + /** This interface is used to update cred info. */ + int32_t (*updateCredInfo)(int32_t osAccountId, const char *appId, const char *credId, const char *requestParams); + /** This interface is used to query credential data by cred id. */ + int32_t (*queryCredInfoByCredId)(int32_t osAccountId, const char *credId, char **returnData); } AccountLifecyleExtPlugCtx; #ifdef __cplusplus diff --git a/services/BUILD.gn b/services/BUILD.gn index 02aaa502ad7dbb831469d481b476dd570e5eb86d..4314e90f7b90961aa862f9d0bd2932156068cfad 100644 --- a/services/BUILD.gn +++ b/services/BUILD.gn @@ -170,6 +170,7 @@ if (os_level == "mini" || os_level == "small") { include_dirs += [ "${frameworks_path}/inc/standard", "${dev_frameworks_path}/inc/hiview_adapter", + "${dev_frameworks_path}/inc/permission_adapter", ] if (support_os_account) { @@ -184,10 +185,12 @@ if (os_level == "mini" || os_level == "small") { sources += sa_subscriber_files sources += net_observer_files } + sources += permission_adapter_files sources += hiview_adapter_files defines = deviceauth_defines defines += [ "HILOG_ENABLE" ] defines += [ "DEV_AUTH_HIVIEW_ENABLE" ] + defines += [ "DEV_AUTH_PERMISSION_ENABLE" ] cflags = build_flags cflags += [ "-DDEV_AUTH_WORK_THREAD_STACK_SIZE=${device_auth_hichain_thread_stack_size}", @@ -221,6 +224,7 @@ if (os_level == "mini" || os_level == "small") { deps = [ "${deps_adapter_path}:${hal_module_name}" ] external_deps = [ + "access_token:libaccesstoken_sdk", "bounds_checking_function:libsec_shared", "cJSON:cjson", "c_utils:utils", @@ -265,11 +269,13 @@ if (os_level == "mini" || os_level == "small") { sources = deviceauth_ipc_files sources += permission_adapter_files sources += [ "${frameworks_path}/src/ipc_sdk.c" ] + sources += [ "${frameworks_path}/src/IS_ipc_sdk.c" ] defines = [ "__LINUX__", "HILOG_ENABLE", ] + defines += [ "DEV_AUTH_IS_ENABLE" ] cflags = build_flags cflags += [ "-fPIC" ] if (target_cpu == "arm") { @@ -334,6 +340,7 @@ if (os_level == "mini" || os_level == "small") { defines = [ "HILOG_ENABLE" ] defines += [ "DEV_AUTH_HIVIEW_ENABLE" ] defines += [ "DEV_AUTH_SERVICE_BUILD" ] + defines += [ "DEV_AUTH_IS_ENABLE" ] if (use_musl) { if (musl_use_jemalloc && musl_use_jemalloc_dfx_intf) { @@ -342,7 +349,6 @@ if (os_level == "mini" || os_level == "small") { } sources = deviceauth_ipc_files - sources += permission_adapter_files sources += [ "${frameworks_path}/src/deviceauth_sa.cpp" ] sources += [ "${frameworks_path}/src/ipc_service_common.c" ] @@ -353,7 +359,6 @@ if (os_level == "mini" || os_level == "small") { ] external_deps = [ - "access_token:libaccesstoken_sdk", "bounds_checking_function:libsec_shared", "cJSON:cjson", "c_utils:utils", diff --git a/services/data_manager/cred_data_manager/inc/credential_data_manager.h b/services/data_manager/cred_data_manager/inc/credential_data_manager.h new file mode 100644 index 0000000000000000000000000000000000000000..a1925d563de6ed8c86dbee821dbbf8ced87344f5 --- /dev/null +++ b/services/data_manager/cred_data_manager/inc/credential_data_manager.h @@ -0,0 +1,99 @@ +/* + * Copyright (C) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef CREDENTIAL_DATA_MANAGER_H +#define CREDENTIAL_DATA_MANAGER_H + +#include +#include "hc_string.h" +#include "hc_string_vector.h" +#include "hc_tlv_parser.h" +#include "hc_vector.h" +#include "json_utils.h" + +#define MAX_STRING_LEN 256 + +typedef struct { + /* unique index*/ + HcString credId; + /* device */ + HcString deviceId; + HcString peerUserSpaceId; + uint8_t subject; + /* user */ + HcString userId; + uint8_t issuer; + /* key */ + uint8_t credType; + uint8_t keyFormat; + uint8_t algorithmType; + uint8_t proofType; + /* access permission*/ + StringVector authorizedAccountList; + StringVector authorizedAppList; + StringVector authorizedDeviceList; + uint8_t authorizedScope; + HcString credOwner; + int32_t ownerUid; + /* extention info*/ + HcString extendInfo; +} Credential; +DECLARE_HC_VECTOR(CredentialVec, Credential*) + +typedef struct { + const char *credId; + const char *deviceId; + const char *peerUserSpaceId; + uint8_t subject; + const char *userId; + uint8_t issuer; + uint8_t credType; + uint8_t keyFormat; + uint8_t algorithmType; + uint8_t proofType; + uint8_t authorizedScope; + const char *credOwner; + int32_t ownerUid; +} QueryCredentialParams; + +#ifdef __cplusplus +extern "C" { +#endif + +int32_t InitCredDatabase(void); +void DestroyCredDatabase(void); + +void ReloadOsAccountCredDb(int32_t osAccountId); +int32_t AddCredToDb(int32_t osAccountId, const Credential *credential); +int32_t DelCredential(int32_t osAccountId, const QueryCredentialParams *delParams); +int32_t QueryCredentials(int32_t osAccountId, const QueryCredentialParams *queryParams, + CredentialVec *vec); +int32_t SaveOsAccountCredDb(int32_t osAccountId); + +Credential *DeepCopyCredential(const Credential *credential); + +QueryCredentialParams InitQueryCredentialParams(void); +int32_t GenerateReturnCredInfo(const Credential *credential, CJson *returnJson); + +Credential *CreateCredential(void); +void DestroyCredential(Credential *groupEntry); + +CredentialVec CreateCredentialVec(void); +void ClearCredentialVec(CredentialVec *vec); + +#ifdef __cplusplus +} +#endif +#endif diff --git a/services/data_manager/cred_data_manager/src/credential_data_manager.c b/services/data_manager/cred_data_manager/src/credential_data_manager.c new file mode 100644 index 0000000000000000000000000000000000000000..ecb052a2e789b16f8bad887447367e4563e974fe --- /dev/null +++ b/services/data_manager/cred_data_manager/src/credential_data_manager.c @@ -0,0 +1,1213 @@ +/* + * Copyright (C) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "credential_data_manager.h" + +#include "common_defs.h" +#include "device_auth_defines.h" +#include "hc_dev_info.h" +#include "hc_file.h" +#include "hc_log.h" +#include "hc_mutex.h" +#include "hc_types.h" +#include "securec.h" +#include "hidump_adapter.h" +#include "os_account_adapter.h" +#include "security_label_adapter.h" +#include "account_task_manager.h" +#include "cred_listener.h" + +typedef struct { + DECLARE_TLV_STRUCT(17) + TlvString credId; + TlvString deviceId; + TlvString peerUserSpaceId; + TlvUint8 subject; + TlvString userId; + TlvUint8 issuer; + TlvUint8 credType; + TlvUint8 keyFormat; + TlvUint8 algorithmType; + TlvUint8 proofType; + TlvBuffer authorizedAccountList; + TlvBuffer authorizedAppList; + TlvBuffer authorizedDeviceList; + TlvUint8 authorizedScope; + TlvString credOwner; + TlvInt32 ownerUid; + TlvString extendInfo; +} TlvCredentialElement; +DECLEAR_INIT_FUNC(TlvCredentialElement) +DECLARE_TLV_VECTOR(TlvCredentialVec, TlvCredentialElement) + +typedef struct { + DECLARE_TLV_STRUCT(2) + TlvInt32 version; + TlvCredentialVec credentials; +} HCCredDataBaseV1; +DECLEAR_INIT_FUNC(HCCredDataBaseV1) + +BEGIN_TLV_STRUCT_DEFINE(TlvCredentialElement, 0x0001) + TLV_MEMBER(TlvString, credId, 0x4001) + TLV_MEMBER(TlvString, deviceId, 0x4002) + TLV_MEMBER(TlvString, peerUserSpaceId, 0x4003) + TLV_MEMBER(TlvUint8, subject, 0x4004) + TLV_MEMBER(TlvString, userId, 0x4005) + TLV_MEMBER(TlvUint8, issuer, 0x4006) + TLV_MEMBER(TlvUint8, credType, 0x4007) + TLV_MEMBER(TlvUint8, keyFormat, 0x4008) + TLV_MEMBER(TlvUint8, algorithmType, 0x4009) + TLV_MEMBER(TlvUint8, proofType, 0x400A) + TLV_MEMBER(TlvBuffer, authorizedAccountList, 0x400B) + TLV_MEMBER(TlvBuffer, authorizedAppList, 0x400C) + TLV_MEMBER(TlvBuffer, authorizedDeviceList, 0x400D) + TLV_MEMBER(TlvUint8, authorizedScope, 0x400E) + TLV_MEMBER(TlvString, credOwner, 0x400F) + TLV_MEMBER(TlvInt32, ownerUid, 0x4010) + TLV_MEMBER(TlvString, extendInfo, 0x4011) +END_TLV_STRUCT_DEFINE() +IMPLEMENT_TLV_VECTOR(TlvCredentialVec, TlvCredentialElement, 1) + +BEGIN_TLV_STRUCT_DEFINE(HCCredDataBaseV1, 0x0001) + TLV_MEMBER(TlvInt32, version, 0x6001) + TLV_MEMBER(TlvCredentialVec, credentials, 0x6002) +END_TLV_STRUCT_DEFINE() + +IMPLEMENT_HC_VECTOR(CredentialVec, Credential*, 1) + +typedef struct { + int32_t osAccountId; + CredentialVec credentials; +} OsAccountCredInfo; + +DECLARE_HC_VECTOR(DevAuthCredDb, OsAccountCredInfo) +IMPLEMENT_HC_VECTOR(DevAuthCredDb, OsAccountCredInfo, 1) + +#define MAX_DB_PATH_LEN 256 + +static HcMutex *g_credMutex = NULL; +static DevAuthCredDb g_devauthCredDb; +const uint8_t DEFAULT_CRED_PARAM_VAL = 0; + +static bool EndWithZero(HcParcel *parcel) +{ + const char *p = GetParcelLastChar(parcel); + if (p == NULL) { + return false; + } + return (*p == '\0'); +} + +static bool LoadStringVectorFromParcel(StringVector *vec, HcParcel *parcel) +{ + uint32_t strLen = 0; + do { + if (!ParcelReadUint32(parcel, &strLen)) { + return true; + } + if ((strLen == 0) || (strLen > MAX_STRING_LEN)) { + return false; + } + HcString str = CreateString(); + ClearParcel(&str.parcel); + if (!ParcelReadParcel(parcel, &str.parcel, strLen, false) || + !EndWithZero(&str.parcel)) { + DeleteString(&str); + return false; + } else { + if (vec->pushBack(vec, &str) == NULL) { + DeleteString(&str); + return false; + } + } + } while (1); +} + +static bool SaveStringVectorToParcel(const StringVector *vec, HcParcel *parcel) +{ + uint32_t index; + HcString *str = NULL; + FOR_EACH_HC_VECTOR(*vec, index, str) { + uint32_t len = StringLength(str) + sizeof(char); + if (!ParcelWriteUint32(parcel, len)) { + return false; + } + if (!ParcelWrite(parcel, GetParcelData(&str->parcel), GetParcelDataSize(&str->parcel))) { + return false; + } + } + return true; +} + +static bool GetOsAccountCredInfoPathCe(int32_t osAccountId, char *infoPath, uint32_t pathBufferLen) +{ + const char *beginPath = GetStorageDirPathCe(); + if (beginPath == NULL) { + LOGE("[CRED#DB]: Failed to get the storage path!"); + return false; + } + if (sprintf_s(infoPath, pathBufferLen, "%s/%d/deviceauth/hccredential.dat", beginPath, osAccountId) <= 0) { + LOGE("[CRED#DB]: Failed to generate db file path!"); + return false; + } + return true; +} + +static bool GetOsAccountCredInfoPathDe(int32_t osAccountId, char *infoPath, uint32_t pathBufferLen) +{ + const char *beginPath = GetStorageDirPath(); + if (beginPath == NULL) { + LOGE("[CRED#DB]: Failed to get the storage path dir!"); + return false; + } + int32_t writeByteNum; + if (osAccountId == DEFAULT_OS_ACCOUNT) { + writeByteNum = sprintf_s(infoPath, pathBufferLen, "%s/hccredential.dat", beginPath); + } else { + writeByteNum = sprintf_s(infoPath, pathBufferLen, "%s/hccredential%d.dat", beginPath, osAccountId); + } + if (writeByteNum <= 0) { + LOGE("[CRED#DB]: sprintf_s fail!"); + return false; + } + return true; +} + +static bool GetOsAccountCredInfoPath(int32_t osAccountId, char *infoPath, uint32_t pathBufferLen) +{ + if (IsOsAccountSupported()) { + return GetOsAccountCredInfoPathCe(osAccountId, infoPath, pathBufferLen); + } else { + return GetOsAccountCredInfoPathDe(osAccountId, infoPath, pathBufferLen); + } +} + +static bool GenerateAuthorizedAccountList(const Credential *entry, Credential *returnEntry) +{ + uint32_t index = 0; + HcString *authorizedAccount = NULL; + FOR_EACH_HC_VECTOR(entry->authorizedAccountList, index, authorizedAccount) { + if (authorizedAccount == NULL) { + continue; + } + HcString returnAuthorizedAccount = CreateString(); + if (!StringSet(&returnAuthorizedAccount, *authorizedAccount)) { + DeleteString(&returnAuthorizedAccount); + LOGE("[CRED#DB]: Failed to copy authorizedAccount!"); + return false; + } + if (returnEntry->authorizedAccountList.pushBack(&returnEntry->authorizedAccountList, &returnAuthorizedAccount) + == NULL) { + LOGE("[CRED#DB]: Failed to push authorizedAccount to list!"); + DeleteString(&returnAuthorizedAccount); + return false; + } + } + return true; +} + +bool GenerateCredFromCred(const Credential *entry, Credential *returnEntry) +{ + if (!StringSet(&returnEntry->credId, entry->credId)) { + LOGE("[CRED#DB]: Failed to copy credId!"); + return false; + } + if (!StringSet(&returnEntry->deviceId, entry->deviceId)) { + LOGE("[CRED#DB]: Failed to copy deviceId!"); + return false; + } + if (!StringSet(&returnEntry->peerUserSpaceId, entry->peerUserSpaceId)) { + LOGE("[CRED#DB]: Failed to copy peerUserSpaceId!"); + return false; + } + if (!StringSet(&returnEntry->userId, entry->userId)) { + LOGE("[CRED#DB]: Failed to copy userId!"); + return false; + } + if (!StringSet(&returnEntry->credOwner, entry->credOwner)) { + LOGE("[CRED#DB]: Failed to copy credOwner!"); + return false; + } + if (!GenerateAuthorizedAccountList(entry, returnEntry)) { + return false; + } + if (!StringSet(&returnEntry->extendInfo, entry->extendInfo)) { + LOGE("[CRED#DB]: Failed to copy extendInfo!"); + return false; + } + returnEntry->subject = entry->subject; + returnEntry->authorizedScope = entry->authorizedScope; + returnEntry->credType = entry->credType; + returnEntry->issuer = entry->issuer; + returnEntry->keyFormat = entry->keyFormat; + returnEntry->algorithmType = entry->algorithmType; + returnEntry->proofType = entry->proofType; + returnEntry->ownerUid = entry->ownerUid; + return true; +} + +static bool GenerateCredentialFromTlv(TlvCredentialElement *credential, Credential *entry) +{ + if (!StringSet(&entry->credId, credential->credId.data)) { + LOGE("[CRED#DB]: Failed to load credId from tlv!"); + return false; + } + if (!StringSet(&entry->deviceId, credential->deviceId.data)) { + LOGE("[CRED#DB]: Failed to load deviceId from tlv!"); + return false; + } + if (!StringSet(&entry->peerUserSpaceId, credential->peerUserSpaceId.data)) { + LOGE("[CRED#DB]: Failed to load peerUserSpaceId from tlv!"); + return false; + } + if (!StringSet(&entry->userId, credential->userId.data)) { + LOGE("[CRED#DB]: Failed to load userId from tlv!"); + return false; + } + if (!StringSet(&entry->credOwner, credential->credOwner.data)) { + LOGE("[CRED#DB]: Failed to load credOwner from tlv!"); + return false; + } + if (!LoadStringVectorFromParcel(&entry->authorizedAccountList, &credential->authorizedAccountList.data)) { + LOGE("[CRED#DB]: Failed to load authorizedAccountList from tlv!"); + return false; + } + if (!StringSet(&entry->extendInfo, credential->extendInfo.data)) { + LOGE("[CRED#DB]: Failed to load extendInfo from tlv!"); + return false; + } + entry->subject = credential->subject.data; + entry->authorizedScope = credential->authorizedScope.data; + entry->issuer = credential->issuer.data; + entry->credType = credential->credType.data; + entry->keyFormat = credential->keyFormat.data; + entry->algorithmType = credential->algorithmType.data; + entry->proofType = credential->proofType.data; + entry->ownerUid = credential->ownerUid.data; + return true; +} + +static bool LoadCredentials(HCCredDataBaseV1 *db, CredentialVec *vec) +{ + uint32_t index; + TlvCredentialElement *credentialTlv = NULL; + FOR_EACH_HC_VECTOR(db->credentials.data, index, credentialTlv) { + if (credentialTlv == NULL) { + continue; + } + Credential *entry = CreateCredential(); + if (entry == NULL) { + LOGE("[CRED#DB]: Failed to allocate entry memory!"); + ClearCredentialVec(vec); + return false; + } + if (!GenerateCredentialFromTlv(credentialTlv, entry)) { + DestroyCredential(entry); + ClearCredentialVec(vec); + return false; + } + if (vec->pushBackT(vec, entry) == NULL) { + LOGE("[CRED#DB]: Failed to push entry to vec!"); + DestroyCredential(entry); + ClearCredentialVec(vec); + return false; + } + } + return true; +} + +static bool ReadCredInfoFromParcel(HcParcel *parcel, OsAccountCredInfo *info) +{ + bool ret = false; + HCCredDataBaseV1 dbv1; + TLV_INIT(HCCredDataBaseV1, &dbv1) + if (DecodeTlvMessage((TlvBase *)&dbv1, parcel, false)) { + if (!LoadCredentials(&dbv1, &info->credentials)) { + TLV_DEINIT(dbv1) + return false; + } + ret = true; + } else { + LOGE("[CRED#DB]: Decode Tlv Message Failed!"); + } + TLV_DEINIT(dbv1) + return ret; +} + +static bool ReadParcelFromFile(const char *filePath, HcParcel *parcel) +{ + FileHandle file; + int ret = HcFileOpen(filePath, MODE_FILE_READ, &file); + if (ret != 0) { + LOGE("[CRED#DB]: Failed to open database file!"); + return false; + } + SetSecurityLabel(filePath, SECURITY_LABEL_S2); + int fileSize = HcFileSize(file); + if (fileSize <= 0) { + LOGE("[CRED#DB]: The database file size is invalid!"); + HcFileClose(file); + return false; + } + char *fileData = (char *)HcMalloc(fileSize, 0); + if (fileData == NULL) { + LOGE("[CRED#DB]: Failed to allocate fileData memory!"); + HcFileClose(file); + return false; + } + if (HcFileRead(file, fileData, fileSize) != fileSize) { + LOGE("[CRED#DB]: Read file error!"); + HcFileClose(file); + HcFree(fileData); + return false; + } + HcFileClose(file); + if (!ParcelWrite(parcel, fileData, fileSize)) { + LOGE("[CRED#DB]: parcel write error!"); + HcFree(fileData); + return false; + } + HcFree(fileData); + return true; +} + +static bool SaveParcelToFile(const char *filePath, HcParcel *parcel) +{ + FileHandle file; + int ret = HcFileOpen(filePath, MODE_FILE_WRITE, &file); + if (ret != IS_SUCCESS) { + LOGE("[CRED#DB]: Failed to open database file!"); + return false; + } + SetSecurityLabel(filePath, SECURITY_LABEL_S2); + int fileSize = (int)GetParcelDataSize(parcel); + const char *fileData = GetParcelData(parcel); + int writeSize = HcFileWrite(file, fileData, fileSize); + HcFileClose(file); + if (writeSize == fileSize) { + return true; + } else { + LOGE("[CRED#DB]: write file error!"); + return false; + } +} + +static void LoadOsAccountCredDb(int32_t osAccountId) +{ + char filePath[MAX_DB_PATH_LEN] = { 0 }; + if (!GetOsAccountCredInfoPath(osAccountId, filePath, MAX_DB_PATH_LEN)) { + LOGE("[CRED#DB]: Failed to get os account info path!"); + return; + } + HcParcel parcel = CreateParcel(0, 0); + if (!ReadParcelFromFile(filePath, &parcel)) { + DeleteParcel(&parcel); + return; + } + OsAccountCredInfo info; + info.osAccountId = osAccountId; + info.credentials = CreateCredentialVec(); + if (!ReadCredInfoFromParcel(&parcel, &info)) { + DestroyCredentialVec(&info.credentials); + DeleteParcel(&parcel); + return; + } + DeleteParcel(&parcel); + if (g_devauthCredDb.pushBackT(&g_devauthCredDb, info) == NULL) { + LOGE("[CRED#DB]: Failed to push osAccountCredInfo to cred database!"); + ClearCredentialVec(&info.credentials); + return; + } + LOGI("[CRED#DB]: Load os account cred db successfully! [Id]: %d", osAccountId); +} + +static void RemoveOsAccountCredInfo(int32_t osAccountId) +{ + uint32_t index = 0; + OsAccountCredInfo *info = NULL; + FOR_EACH_HC_VECTOR(g_devauthCredDb, index, info) { + if (info != NULL && info->osAccountId == osAccountId) { + OsAccountCredInfo deleteInfo; + HC_VECTOR_POPELEMENT(&g_devauthCredDb, &deleteInfo, index); + ClearCredentialVec(&deleteInfo.credentials); + return; + } + } +} + +static void OnOsAccountUnlocked(int32_t osAccountId) +{ + (void)LockHcMutex(g_credMutex); + RemoveOsAccountCredInfo(osAccountId); + LoadOsAccountCredDb(osAccountId); + UnlockHcMutex(g_credMutex); +} + +static void OnOsAccountRemoved(int32_t osAccountId) +{ + LOGI("[CRED#DB]: os account is removed, osAccountId: %d", osAccountId); + (void)LockHcMutex(g_credMutex); + RemoveOsAccountCredInfo(osAccountId); + UnlockHcMutex(g_credMutex); +} + +static bool IsOsAccountDataLoaded(int32_t osAccountId) +{ + uint32_t index = 0; + OsAccountCredInfo *info = NULL; + FOR_EACH_HC_VECTOR(g_devauthCredDb, index, info) { + if (info != NULL && info->osAccountId == osAccountId) { + return true; + } + } + return false; +} + +static void LoadDataIfNotLoaded(int32_t osAccountId) +{ + if (IsOsAccountDataLoaded(osAccountId)) { + return; + } + LOGI("[CRED#DB]: data has not been loaded, load it, osAccountId: %d", osAccountId); + LoadOsAccountCredDb(osAccountId); +} + +static OsAccountCredInfo *GetCredInfoByOsAccountId(int32_t osAccountId) +{ + if (IsOsAccountSupported()) { + LoadDataIfNotLoaded(osAccountId); + } + uint32_t index = 0; + OsAccountCredInfo *info = NULL; + FOR_EACH_HC_VECTOR(g_devauthCredDb, index, info) { + if (info != NULL && info->osAccountId == osAccountId) { + return info; + } + } + LOGI("[CRED#DB]: Create a new os account database cache! [Id]: %d", osAccountId); + OsAccountCredInfo newInfo; + newInfo.osAccountId = osAccountId; + newInfo.credentials = CreateCredentialVec(); + OsAccountCredInfo *returnInfo = g_devauthCredDb.pushBackT(&g_devauthCredDb, newInfo); + if (returnInfo == NULL) { + LOGE("[CRED#DB]: Failed to push osAccountInfo to database!"); + DestroyCredentialVec(&newInfo.credentials); + } + return returnInfo; +} + +static void LoadDevAuthCredDb(void) +{ + if (IsOsAccountSupported()) { + return; + } + (void)LockHcMutex(g_credMutex); + StringVector osAccountDbNameVec = CreateStrVector(); + HcFileGetSubFileName(GetStorageDirPath(), &osAccountDbNameVec); + uint32_t index; + HcString *dbName; + FOR_EACH_HC_VECTOR(osAccountDbNameVec, index, dbName) { + int32_t osAccountId; + const char *osAccountIdStr = StringGet(dbName); + if (osAccountIdStr == NULL) { + continue; + } + if (strcmp(osAccountIdStr, "hccredential.dat") == 0) { + LoadOsAccountCredDb(DEFAULT_OS_ACCOUNT); + } else if (sscanf_s(osAccountIdStr, "hccredential%d.dat", &osAccountId) == 1) { + LoadOsAccountCredDb(osAccountId); + } + } + DestroyStrVector(&osAccountDbNameVec); + UnlockHcMutex(g_credMutex); +} + +static bool SetCredentialElement(TlvCredentialElement *element, Credential *entry) +{ + if (!StringSet(&element->credId.data, entry->credId)) { + LOGE("[CRED#DB]: Failed to copy credId!"); + return false; + } + if (!StringSet(&element->deviceId.data, entry->deviceId)) { + LOGE("[CRED#DB]: Failed to copy deviceId!"); + return false; + } + if (!StringSet(&element->peerUserSpaceId.data, entry->peerUserSpaceId)) { + LOGE("[CRED#DB]: Failed to copy peerUserSpaceId!"); + return false; + } + if (!StringSet(&element->userId.data, entry->userId)) { + LOGE("[CRED#DB]: Failed to copy userId!"); + return false; + } + if (!StringSet(&element->credOwner.data, entry->credOwner)) { + LOGE("[CRED#DB]: Failed to copy credOwner!"); + return false; + } + if (!SaveStringVectorToParcel(&entry->authorizedAccountList, &element->authorizedAccountList.data)) { + LOGE("[CRED#DB]: Failed to copy authorizedAccountList!"); + return false; + } + if (!StringSet(&element->extendInfo.data, entry->extendInfo)) { + LOGE("[CRED#DB]: Failed to copy extendInfo!"); + return false; + } + element->subject.data = entry->subject; + element->authorizedScope.data = entry->authorizedScope; + element->issuer.data = entry->issuer; + element->credType.data = entry->credType; + element->keyFormat.data = entry->keyFormat; + element->algorithmType.data = entry->algorithmType; + element->proofType.data = entry->proofType; + element->ownerUid.data = entry->ownerUid; + return true; +} + +static bool SaveCredentials(const CredentialVec *vec, HCCredDataBaseV1 *db) +{ + uint32_t index; + Credential **entry; + FOR_EACH_HC_VECTOR(*vec, index, entry) { + if (entry == NULL || *entry == NULL) { + continue; + } + TlvCredentialElement tmp; + TlvCredentialElement *element = db->credentials.data.pushBack(&db->credentials.data, &tmp); + if (element == NULL) { + return false; + } + TLV_INIT(TlvCredentialElement, element); + if (!SetCredentialElement(element, *entry)) { + TLV_DEINIT((*element)); + return false; + } + } + return true; +} + +static bool SaveCredInfoToParcel(const OsAccountCredInfo *info, HcParcel *parcel) +{ + int32_t ret = false; + HCCredDataBaseV1 dbv1; + TLV_INIT(HCCredDataBaseV1, &dbv1) + dbv1.version.data = 1; + do { + if (!SaveCredentials(&info->credentials, &dbv1)) { + break; + } + if (!EncodeTlvMessage((TlvBase *)&dbv1, parcel)) { + LOGE("[CRED#DB]: Encode Tlv Message failed!"); + break; + } + ret = true; + } while (0); + TLV_DEINIT(dbv1) + return ret; +} + +static bool CompareQueryCredentialParams(const QueryCredentialParams *params, const Credential *entry) +{ + if ((params->deviceId != NULL) && (strcmp(params->deviceId, StringGet(&entry->deviceId)) != 0)) { + return false; + } + if ((params->credOwner != NULL) && (strcmp(params->credOwner, StringGet(&entry->credOwner)) != 0)) { + return false; + } + if ((params->userId != NULL) && (strcmp(params->userId, StringGet(&entry->userId)) != 0)) { + return false; + } + if ((params->credId != NULL) && (strcmp(params->credId, StringGet(&entry->credId)) != 0)) { + return false; + } + if ((params->credType != DEFAULT_CRED_PARAM_VAL) && (params->credType != entry->credType)) { + return false; + } + if ((params->subject != DEFAULT_CRED_PARAM_VAL) && (params->subject != entry->subject)) { + return false; + } + if ((params->issuer != DEFAULT_CRED_PARAM_VAL) && (params->issuer != entry->issuer)) { + return false; + } + if ((params->ownerUid != DEFAULT_CRED_PARAM_VAL) && (params->ownerUid != entry->ownerUid)) { + return false; + } + return true; +} + +static Credential **QueryCredentialPtrIfMatch(const CredentialVec *vec, const QueryCredentialParams *params) +{ + uint32_t index; + Credential **entry; + FOR_EACH_HC_VECTOR(*vec, index, entry) { + if (entry != NULL && *entry != NULL && CompareQueryCredentialParams(params, *entry)) { + return entry; + } + } + return NULL; +} + +static void PostCredAddMsg(const Credential *entry) +{ + if (!IsCredListenerSupported()) { + return; + } + OnCredAdd(StringGet(&entry->credId), NULL); +} + +static void PostCredUpdateMsg(const Credential *entry) +{ + if (!IsCredListenerSupported()) { + return; + } + OnCredUpdate(StringGet(&entry->credId), NULL); +} + +static void PostCredDeleteMsg(const Credential *entry) +{ + if (!IsCredListenerSupported()) { + return; + } + OnCredDelete(StringGet(&entry->credId), NULL); +} + +QueryCredentialParams InitQueryCredentialParams(void) +{ + QueryCredentialParams params = { + .deviceId = NULL, + .credOwner = NULL, + .credId = NULL, + .userId = NULL, + .credType = DEFAULT_CRED_PARAM_VAL, + .ownerUid = DEFAULT_CRED_PARAM_VAL, + .subject = DEFAULT_CRED_PARAM_VAL, + .issuer = DEFAULT_CRED_PARAM_VAL, + }; + return params; +} + +Credential *CreateCredential(void) +{ + Credential *ptr = (Credential *)HcMalloc(sizeof(Credential), 0); + if (ptr == NULL) { + LOGE("[CRED#DB]: Failed to allocate Credential memory!"); + return NULL; + } + ptr->credId = CreateString(); + ptr->deviceId = CreateString(); + ptr->peerUserSpaceId = CreateString(); + ptr->userId = CreateString(); + ptr->credOwner = CreateString(); + ptr->authorizedAccountList = CreateStrVector(); + ptr->authorizedAppList = CreateStrVector(); + ptr->authorizedDeviceList = CreateStrVector(); + ptr->extendInfo = CreateString(); + return ptr; +} + +void DestroyCredential(Credential *credential) +{ + if (credential == NULL) { + return; + } + DeleteString(&credential->credId); + DeleteString(&credential->deviceId); + DeleteString(&credential->peerUserSpaceId); + DeleteString(&credential->userId); + DeleteString(&credential->credOwner); + DestroyStrVector(&credential->authorizedAccountList); + DestroyStrVector(&credential->authorizedAppList); + DestroyStrVector(&credential->authorizedDeviceList); + DeleteString(&credential->extendInfo); + HcFree(credential); +} + +Credential *DeepCopyCredential(const Credential *entry) +{ + Credential *returnEntry = CreateCredential(); + if (returnEntry == NULL) { + return NULL; + } + if (!GenerateCredFromCred(entry, returnEntry)) { + DestroyCredential(returnEntry); + return NULL; + } + return returnEntry; +} + +void ClearCredentialVec(CredentialVec *vec) +{ + uint32_t index; + Credential **entry; + FOR_EACH_HC_VECTOR(*vec, index, entry) { + if (entry == NULL || *entry == NULL) { + continue; + } + DestroyCredential(*entry); + } + DESTROY_HC_VECTOR(CredentialVec, vec); +} + +static int32_t AddCredIdToReturn(const Credential *credInfo, CJson *json) +{ + const char *credId = StringGet(&credInfo->credId); + if (credId == NULL) { + LOGE("[CRED#DB]: Failed to get credId from credInfo!"); + return IS_ERR_NULL_PTR; + } + if (AddStringToJson(json, FIELD_CRED_ID, credId) != IS_SUCCESS) { + LOGE("[CRED#DB]: Failed to add credId to json!"); + return IS_ERR_JSON_ADD; + } + return IS_SUCCESS; +} + +static int32_t AddCredTypeToReturn(const Credential *credInfo, CJson *json) +{ + uint8_t credType = credInfo->credType; + if (AddIntToJson(json, FIELD_CRED_TYPE, credType) != IS_SUCCESS) { + LOGE("[CRED#DB]: Failed to add credType to json!"); + return IS_ERR_JSON_ADD; + } + return IS_SUCCESS; +} + +static int32_t AddUserIdToReturn(const Credential *credInfo, CJson *json) +{ + const char *userId = StringGet(&credInfo->userId); + if (userId == NULL) { + LOGE("[CRED#DB]: Failed to get userId from credInfo!"); + return IS_ERR_NULL_PTR; + } + if (AddStringToJson(json, FIELD_USER_ID, userId) != IS_SUCCESS) { + LOGE("[CRED#DB]: Failed to add userId to json!"); + return IS_ERR_JSON_ADD; + } + return IS_SUCCESS; +} + +static int32_t AddSubjectToReturn(const Credential *credInfo, CJson *json) +{ + uint8_t subject = credInfo->subject; + if (AddIntToJson(json, FIELD_SUBJECT, subject) != IS_SUCCESS) { + LOGE("[CRED#DB]: Failed to add subject to json!"); + return IS_ERR_JSON_ADD; + } + return IS_SUCCESS; +} + +static int32_t AddIssuerToReturn(const Credential *credInfo, CJson *json) +{ + uint8_t issuer = credInfo->issuer; + if (AddIntToJson(json, FIELD_ISSUER, issuer) != IS_SUCCESS) { + LOGE("[CRED#DB]: Failed to add issuer to json!"); + return IS_ERR_JSON_ADD; + } + return IS_SUCCESS; +} + +static int32_t AddKeyFormatToReturn(const Credential *credInfo, CJson *json) +{ + uint8_t keyFormat = credInfo->keyFormat; + if (AddIntToJson(json, FIELD_KEY_FORMAT, keyFormat) != IS_SUCCESS) { + LOGE("[CRED#DB]: Failed to add keyFormat to json!"); + return IS_ERR_JSON_ADD; + } + return IS_SUCCESS; +} + +static int32_t AddProofTypeToReturn(const Credential *credInfo, CJson *json) +{ + uint8_t proofType = credInfo->proofType; + if (AddIntToJson(json, FIELD_PROOF_TYPE, proofType) != IS_SUCCESS) { + LOGE("[CRED#DB]: Failed to add proofType to json!"); + return IS_ERR_JSON_ADD; + } + return IS_SUCCESS; +} + +static int32_t AddAlgorithmTypeToReturn(const Credential *credInfo, CJson *json) +{ + uint8_t algorithmType = credInfo->algorithmType; + if (AddIntToJson(json, FIELD_ALGORITHM_TYPE, algorithmType) != IS_SUCCESS) { + LOGE("[CRED#DB]: Failed to add algorithmType to json!"); + return IS_ERR_JSON_ADD; + } + return IS_SUCCESS; +} + +static int32_t AddDeviceIdToReturn(const Credential *credInfo, CJson *json) +{ + const char *deviceId = StringGet(&credInfo->deviceId); + if (deviceId == NULL) { + LOGE("[CRED#DB]: Failed to get deviceId from credInfo!"); + return IS_ERR_NULL_PTR; + } + if (AddStringToJson(json, FIELD_DEVICE_ID, deviceId) != IS_SUCCESS) { + LOGE("[CRED#DB]: Failed to add deviceId to json!"); + return IS_ERR_JSON_ADD; + } + return IS_SUCCESS; +} + +static int32_t AddCredOwnerToReturn(const Credential *credInfo, CJson *json) +{ + const char *credOwner = StringGet(&credInfo->credOwner); + if (credOwner == NULL) { + LOGE("[CRED#DB]: Failed to get credOwner from credInfo!"); + return IS_ERR_NULL_PTR; + } + if (AddStringToJson(json, FIELD_CRED_OWNER, credOwner) != IS_SUCCESS) { + LOGE("[CRED#DB]: Failed to add credOwner to json!"); + return IS_ERR_JSON_ADD; + } + return IS_SUCCESS; +} + +static int32_t AddExtendInfoToReturn(const Credential *credInfo, CJson *json) +{ + const char *extendInfo = StringGet(&credInfo->extendInfo); + if (extendInfo == NULL) { + LOGE("[CRED#DB]: Failed to get extendInfo from credInfo!"); + return IS_ERR_NULL_PTR; + } + if (AddStringToJson(json, FIELD_EXTEND_INFO, extendInfo) != IS_SUCCESS) { + LOGE("[CRED#DB]: Failed to add extendInfo to json!"); + return IS_ERR_JSON_ADD; + } + return IS_SUCCESS; +} + +static int32_t AddPeerUserSpaceIdToReturn(const Credential *credInfo, CJson *json) +{ + const char *peerUserSpaceId = StringGet(&credInfo->peerUserSpaceId); + if (peerUserSpaceId == NULL) { + LOGE("[CRED#DB]: Failed to get peerUserSpaceId from credInfo!"); + return IS_ERR_NULL_PTR; + } + if (AddStringToJson(json, FIELD_PEER_USER_SPACE_ID, peerUserSpaceId) != IS_SUCCESS) { + LOGE("[CRED#DB]: Failed to add peerUserSpaceId to json!"); + return IS_ERR_JSON_ADD; + } + return IS_SUCCESS; +} + +static int32_t AddAuthorizedAccountListToReturn(const Credential *credInfo, CJson *json) +{ + CJson *arr = CreateJsonArray(); + if (json == NULL) { + LOGE("Failed to allocate json memory!"); + return IS_ERR_JSON_CREATE; + } + uint32_t index = 0; + HcString *authorizedAccount = NULL; + FOR_EACH_HC_VECTOR(credInfo->authorizedAccountList, index, authorizedAccount) { + if (authorizedAccount == NULL) { + continue; + } + if (AddStringToArray(arr, StringGet(authorizedAccount)) != IS_SUCCESS) { + FreeJson(arr); + LOGE("[CRED#DB]: Failed to add authorizedAccount to json!"); + return IS_ERR_JSON_ADD; + } + } + if (AddObjToJson(json, FIELD_AUTHORIZED_ACCOUNT_LIST, arr) != IS_SUCCESS) { + FreeJson(arr); + LOGE("[CRED#DB]: Failed to add authorizedAccountList to json!"); + return IS_ERR_JSON_ADD; + } + FreeJson(arr); + return IS_SUCCESS; +} + +int32_t GenerateReturnCredInfo(const Credential *credential, CJson *returnJson) +{ + int32_t result; + if (((result = AddCredIdToReturn(credential, returnJson)) != IS_SUCCESS) || + ((result = AddDeviceIdToReturn(credential, returnJson)) != IS_SUCCESS) || + ((result = AddPeerUserSpaceIdToReturn(credential, returnJson)) != IS_SUCCESS) || + ((result = AddSubjectToReturn(credential, returnJson)) != IS_SUCCESS) || + ((result = AddUserIdToReturn(credential, returnJson)) != IS_SUCCESS) || + ((result = AddIssuerToReturn(credential, returnJson)) != IS_SUCCESS) || + ((result = AddCredTypeToReturn(credential, returnJson)) != IS_SUCCESS) || + ((result = AddKeyFormatToReturn(credential, returnJson)) != IS_SUCCESS) || + ((result = AddAlgorithmTypeToReturn(credential, returnJson)) != IS_SUCCESS) || + ((result = AddProofTypeToReturn(credential, returnJson)) != IS_SUCCESS) || + ((result = AddCredOwnerToReturn(credential, returnJson)) != IS_SUCCESS) || + ((result = AddAuthorizedAccountListToReturn(credential, returnJson)) != IS_SUCCESS) || + ((result = AddExtendInfoToReturn(credential, returnJson)) != IS_SUCCESS)) { + return result; + } + return IS_SUCCESS; +} + +int32_t AddCredToDb(int32_t osAccountId, const Credential *entry) +{ + LOGI("[CRED#DB]: Start to add a cred to database! [OsAccountId]: %d", osAccountId); + if (entry == NULL) { + LOGE("[CRED#DB]: The input entry is NULL!"); + return IS_ERR_NULL_PTR; + } + (void)LockHcMutex(g_credMutex); + OsAccountCredInfo *info = GetCredInfoByOsAccountId(osAccountId); + if (info == NULL) { + UnlockHcMutex(g_credMutex); + return IS_ERR_INVALID_PARAMS; + } + Credential *newEntry = DeepCopyCredential(entry); + if (newEntry == NULL) { + UnlockHcMutex(g_credMutex); + return IS_ERR_MEMORY_COPY; + } + QueryCredentialParams params = InitQueryCredentialParams(); + params.credId = StringGet(&entry->credId); + Credential **oldEntryPtr = QueryCredentialPtrIfMatch(&info->credentials, ¶ms); + if (oldEntryPtr != NULL) { + DestroyCredential(*oldEntryPtr); + *oldEntryPtr = newEntry; + PostCredUpdateMsg(newEntry); + UnlockHcMutex(g_credMutex); + LOGI("[CRED#DB]: Update an old credential successfully! [credType]: %u", entry->credType); + return IS_SUCCESS; + } + if (info->credentials.pushBackT(&info->credentials, newEntry) == NULL) { + DestroyCredential(newEntry); + UnlockHcMutex(g_credMutex); + LOGE("[CRED#DB]: Failed to push credential to vec!"); + return IS_ERR_MEMORY_COPY; + } + PostCredAddMsg(newEntry); + UnlockHcMutex(g_credMutex); + LOGI("[CRED#DB]: Add a credential to database successfully! [credType]: %u", entry->credType); + return IS_SUCCESS; +} + +int32_t DelCredential(int32_t osAccountId, const QueryCredentialParams *params) +{ + LOGI("[CRED#DB]: Start to delete credential from database! [OsAccountId]: %d", osAccountId); + if (params == NULL) { + LOGE("[CRED#DB]: The input params is NULL!"); + return IS_ERR_NULL_PTR; + } + (void)LockHcMutex(g_credMutex); + OsAccountCredInfo *info = GetCredInfoByOsAccountId(osAccountId); + if (info == NULL) { + UnlockHcMutex(g_credMutex); + return IS_ERR_INVALID_PARAMS; + } + int32_t count = 0; + uint32_t index = 0; + Credential **entry = NULL; + while (index < HC_VECTOR_SIZE(&info->credentials)) { + entry = info->credentials.getp(&info->credentials, index); + if ((entry == NULL) || (*entry == NULL) || (!CompareQueryCredentialParams(params, *entry))) { + index++; + continue; + } + Credential *popEntry; + HC_VECTOR_POPELEMENT(&info->credentials, &popEntry, index); + PostCredDeleteMsg(popEntry); + LOGI("[CRED#DB]: Delete a credential from database successfully! [credType]: %u", popEntry->credType); + DestroyCredential(popEntry); + count++; + } + UnlockHcMutex(g_credMutex); + LOGI("[CRED#DB]: Number of credentials deleted: %d", count); + return IS_SUCCESS; +} + +int32_t QueryCredentials(int32_t osAccountId, const QueryCredentialParams *params, CredentialVec *vec) +{ + if ((params == NULL) || (vec == NULL)) { + LOGE("[CRED#DB]: The input params or vec is NULL!"); + return IS_ERR_NULL_PTR; + } + (void)LockHcMutex(g_credMutex); + OsAccountCredInfo *info = GetCredInfoByOsAccountId(osAccountId); + if (info == NULL) { + UnlockHcMutex(g_credMutex); + return IS_ERR_INVALID_PARAMS; + } + uint32_t index; + Credential **entry; + FOR_EACH_HC_VECTOR(info->credentials, index, entry) { + if (entry != NULL && *entry != NULL && !CompareQueryCredentialParams(params, *entry)) { + continue; + } + Credential *newEntry = DeepCopyCredential(*entry); + if (newEntry == NULL) { + continue; + } + if (vec->pushBackT(vec, newEntry) == NULL) { + LOGE("[CRED#DB]: Failed to push entry to vec!"); + DestroyCredential(newEntry); + } + } + UnlockHcMutex(g_credMutex); + return IS_SUCCESS; +} + +int32_t SaveOsAccountCredDb(int32_t osAccountId) +{ + (void)LockHcMutex(g_credMutex); + OsAccountCredInfo *info = GetCredInfoByOsAccountId(osAccountId); + if (info == NULL) { + UnlockHcMutex(g_credMutex); + return IS_ERR_INVALID_PARAMS; + } + HcParcel parcel = CreateParcel(0, 0); + if (!SaveCredInfoToParcel(info, &parcel)) { + DeleteParcel(&parcel); + UnlockHcMutex(g_credMutex); + return IS_ERR_MEMORY_COPY; + } + char filePath[MAX_DB_PATH_LEN] = { 0 }; + if (!GetOsAccountCredInfoPath(osAccountId, filePath, MAX_DB_PATH_LEN)) { + DeleteParcel(&parcel); + UnlockHcMutex(g_credMutex); + return IS_ERR_CONVERT_FAILED; + } + if (!SaveParcelToFile(filePath, &parcel)) { + DeleteParcel(&parcel); + UnlockHcMutex(g_credMutex); + return IS_ERR_MEMORY_COPY; + } + DeleteParcel(&parcel); + UnlockHcMutex(g_credMutex); + LOGI("[CRED#DB]: Save an os account cred database successfully! [Id]: %d", osAccountId); + return IS_SUCCESS; +} + +#ifdef DEV_AUTH_HIVIEW_ENABLE +static void DumpCredential(int fd, const Credential *credential) +{ + dprintf(fd, "||--------------------------Credential--------------------------| |\n"); + dprintf(fd, "||%-16s = %-46.8s| |\n", "credId", StringGet(&credential->credId)); + dprintf(fd, "||%-16s = %-46.8s| |\n", "deviceId", StringGet(&credential->deviceId)); + dprintf(fd, "||%-16s = %-46.8s| |\n", "peerUserSpaceId", StringGet(&credential->peerUserSpaceId)); + dprintf(fd, "||%-16s = %-46d| |\n", "subject", credential->subject); + dprintf(fd, "||%-16s = %-46.8s| |\n", "userId", StringGet(&credential->userId)); + dprintf(fd, "||%-16s = %-46d| |\n", "issuer", credential->issuer); + dprintf(fd, "||%-16s = %-46d| |\n", "credType", credential->credType); + dprintf(fd, "||%-16s = %-46d| |\n", "keyFormat", credential->keyFormat); + dprintf(fd, "||%-16s = %-46d| |\n", "algorithmType", credential->algorithmType); + dprintf(fd, "||%-16s = %-46d| |\n", "proofType", credential->proofType); + uint32_t index = 0; + HcString *authorizedAccount = NULL; + FOR_EACH_HC_VECTOR(credential->authorizedAccountList, index, authorizedAccount) { + if (authorizedAccount == NULL) { + continue; + } + dprintf(fd, "||%-16s %d = %-46.8s| |\n", "account", index, StringGet(authorizedAccount)); + } + dprintf(fd, "||%-16s = %-46d| |\n", "authorizedScope", credential->authorizedScope); + dprintf(fd, "||%-16s = %-46.8s| |\n", "credOwner", StringGet(&credential->credOwner)); + dprintf(fd, "||%-16s = %-46.8s| |\n", "extendInfo", StringGet(&credential->extendInfo)); + dprintf(fd, "||--------------------------Credential--------------------------| |\n"); +} + +static void DumpDb(int fd, const OsAccountCredInfo *db) +{ + const CredentialVec *credentials = &db->credentials; + dprintf(fd, "|------------------------------------CRED-DataBase-------------------------------------|\n"); + dprintf(fd, "|%-12s = %-67d|\n", "osAccountId", db->osAccountId); + dprintf(fd, "|%-12s = %-67d|\n", "credentialNum", credentials->size(credentials)); + uint32_t index; + Credential **credential; + FOR_EACH_HC_VECTOR(*credentials, index, credential) { + if (credential == NULL || *credential == NULL) { + continue; + } + DumpCredential(fd, *credential); + } + dprintf(fd, "|------------------------------------CRED-DataBase-------------------------------------|\n"); +} + +static void LoadAllAccountsData(void) +{ + int32_t *accountIds = NULL; + uint32_t size = 0; + int32_t ret = GetAllOsAccountIds(&accountIds, &size); + if (ret != IS_SUCCESS) { + LOGE("[CRED#DB]: Failed to get all os account ids, [res]: %d", ret); + return; + } + for (uint32_t index = 0; index < size; index++) { + LoadDataIfNotLoaded(accountIds[index]); + } + HcFree(accountIds); +} + +static void DevAuthDataBaseDump(int fd) +{ + if (g_credMutex == NULL) { + LOGE("[CRED#DB]: Init mutex failed"); + return; + } + (void)LockHcMutex(g_credMutex); + if (IsOsAccountSupported()) { + LoadAllAccountsData(); + } + uint32_t index; + OsAccountCredInfo *info; + FOR_EACH_HC_VECTOR(g_devauthCredDb, index, info) { + if (info == NULL) { + continue; + } + DumpDb(fd, info); + } + UnlockHcMutex(g_credMutex); +} +#endif + +int32_t InitCredDatabase(void) +{ + if (g_credMutex == NULL) { + g_credMutex = (HcMutex *)HcMalloc(sizeof(HcMutex), 0); + if (g_credMutex == NULL) { + LOGE("[CRED#DB]: Alloc cred databaseMutex failed"); + return IS_ERR_ALLOC_MEMORY; + } + if (InitHcMutex(g_credMutex, false) != IS_SUCCESS) { + LOGE("[CRED#DB]: Init mutex failed"); + HcFree(g_credMutex); + g_credMutex = NULL; + return IS_ERR_INIT_FAILED; + } + } + g_devauthCredDb = CREATE_HC_VECTOR(DevAuthCredDb); + AddOsAccountEventCallback(CRED_DATA_CALLBACK, OnOsAccountUnlocked, OnOsAccountRemoved); + LoadDevAuthCredDb(); + DEV_AUTH_REG_CRED_DUMP_FUNC(DevAuthDataBaseDump); + return IS_SUCCESS; +} + +void DestroyCredDatabase(void) +{ + RemoveOsAccountEventCallback(CRED_DATA_CALLBACK); + (void)LockHcMutex(g_credMutex); + uint32_t index; + OsAccountCredInfo *info; + FOR_EACH_HC_VECTOR(g_devauthCredDb, index, info) { + if (info == NULL) { + continue; + } + ClearCredentialVec(&info->credentials); + } + DESTROY_HC_VECTOR(DevAuthCredDb, &g_devauthCredDb); + UnlockHcMutex(g_credMutex); + DestroyHcMutex(g_credMutex); + HcFree(g_credMutex); + g_credMutex = NULL; +} \ No newline at end of file diff --git a/services/data_manager/inc/data_manager.h b/services/data_manager/group_data_manager/inc/group_data_manager.h similarity index 98% rename from services/data_manager/inc/data_manager.h rename to services/data_manager/group_data_manager/inc/group_data_manager.h index b2857412a8f133063db72d5aeb9aa450ab03f58e..c71a85dc982fa10fd4d1973e1313fefdb0135bed 100644 --- a/services/data_manager/inc/data_manager.h +++ b/services/data_manager/group_data_manager/inc/group_data_manager.h @@ -13,8 +13,8 @@ * limitations under the License. */ -#ifndef DATA_MANAGER_H -#define DATA_MANAGER_H +#ifndef GROUP_DATA_MANAGER_H +#define GROUP_DATA_MANAGER_H #include #include "hc_string.h" diff --git a/services/data_manager/src/data_manager.c b/services/data_manager/group_data_manager/src/group_data_manager.c similarity index 99% rename from services/data_manager/src/data_manager.c rename to services/data_manager/group_data_manager/src/group_data_manager.c index 60ecfed3a547bb166a0263b4266f302b27cbb8d5..116ab34a3c7c0bed4a4903b2be6753fa726cef19 100644 --- a/services/data_manager/src/data_manager.c +++ b/services/data_manager/group_data_manager/src/group_data_manager.c @@ -13,7 +13,7 @@ * limitations under the License. */ -#include "data_manager.h" +#include "group_data_manager.h" #include "broadcast_manager.h" #include "common_defs.h" diff --git a/services/device_auth.c b/services/device_auth.c index f19de26442a565a65b84f039ada126039d2d85bb..e0ca8ac72cddfff0c0dbe89a6c17401c7f08b6b8 100644 --- a/services/device_auth.c +++ b/services/device_auth.c @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021-2023 Huawei Device Co., Ltd. + * Copyright (C) 2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -19,8 +19,9 @@ #include "callback_manager.h" #include "channel_manager.h" #include "common_defs.h" -#include "cred_manager.h" -#include "data_manager.h" +#include "ext_plugin_manager.h" +#include "group_data_manager.h" +#include "credential_data_manager.h" #include "dev_auth_module_manager.h" #include "dev_session_mgr.h" #include "group_manager.h" @@ -31,6 +32,7 @@ #include "hc_time.h" #include "hisysevent_adapter.h" #include "hitrace_adapter.h" +#include "identity_service.h" #include "json_utils.h" #include "key_manager.h" #include "os_account_adapter.h" @@ -44,6 +46,8 @@ static GroupAuthManager *g_groupAuthManager = NULL; static DeviceGroupManager *g_groupManagerInstance = NULL; +static CredManager *g_credManager = NULL; +static CredAuthManager *g_credAuthManager = NULL; typedef struct { HcTaskBase base; @@ -173,127 +177,6 @@ static const char *GetPeerUdidFromJson(int32_t osAccountId, const CJson *in) return peerConnDeviceId; } -static int32_t AddGroupInfoToContextByInput(const CJson *receivedMsg, CJson *context) -{ - const char *groupId = GetStringFromJson(receivedMsg, FIELD_GROUP_ID); - if (groupId == NULL) { - LOGE("get groupId from json fail."); - return HC_ERR_JSON_GET; - } - const char *groupName = GetStringFromJson(receivedMsg, FIELD_GROUP_NAME); - if (groupName == NULL) { - LOGE("Failed to get groupName from jsonParams!"); - return HC_ERR_JSON_GET; - } - if (AddStringToJson(context, FIELD_GROUP_ID, groupId) != HC_SUCCESS) { - LOGE("Failed to add groupId to json!"); - return HC_ERR_JSON_FAIL; - } - if (AddIntToJson(context, FIELD_GROUP_TYPE, PEER_TO_PEER_GROUP) != HC_SUCCESS) { - LOGE("Failed to add groupType to json!"); - return HC_ERR_JSON_FAIL; - } - if (AddStringToJson(context, FIELD_GROUP_NAME, groupName) != HC_SUCCESS) { - LOGE("Failed to add groupName to json!"); - return HC_ERR_JSON_FAIL; - } - return HC_SUCCESS; -} - -static int32_t AddDevInfoToContextByInput(CJson *context) -{ - int32_t userType = DEVICE_TYPE_ACCESSORY; - (void)GetIntFromJson(context, FIELD_USER_TYPE, &userType); - const char *authId = GetStringFromJson(context, FIELD_DEVICE_ID); - char udid[INPUT_UDID_LEN] = { 0 }; - if (authId == NULL) { - LOGD("No authId is found. The default value is udid!"); - int32_t res = HcGetUdid((uint8_t *)udid, INPUT_UDID_LEN); - if (res != HC_SUCCESS) { - LOGE("Failed to get local udid! res: %d", res); - return HC_ERR_DB; - } - authId = udid; - } - if (AddStringToJson(context, FIELD_AUTH_ID, authId) != HC_SUCCESS) { - LOGE("Failed to add authId to params!"); - return HC_ERR_JSON_FAIL; - } - if (AddIntToJson(context, FIELD_USER_TYPE, userType) != HC_SUCCESS) { - LOGE("Failed to add userType to params!"); - return HC_ERR_JSON_FAIL; - } - return HC_SUCCESS; -} - -static int32_t AddGroupInfoToContextByDb(const char *groupId, CJson *context) -{ - int32_t osAccountId; - if (GetIntFromJson(context, FIELD_OS_ACCOUNT_ID, &osAccountId) != HC_SUCCESS) { - LOGE("get osAccountId from json fail."); - return HC_ERR_JSON_GET; - } - TrustedGroupEntry *entry = GetGroupEntryById(osAccountId, groupId); - if (entry == NULL) { - LOGE("Failed to get groupEntry from db!"); - return HC_ERR_DB; - } - if (AddStringToJson(context, FIELD_GROUP_ID, StringGet(&entry->id)) != HC_SUCCESS) { - LOGE("Failed to add groupId to json!"); - DestroyGroupEntry(entry); - return HC_ERR_JSON_FAIL; - } - if (AddIntToJson(context, FIELD_GROUP_TYPE, entry->type) != HC_SUCCESS) { - LOGE("Failed to add groupType to json!"); - DestroyGroupEntry(entry); - return HC_ERR_JSON_FAIL; - } - if (AddStringToJson(context, FIELD_GROUP_NAME, StringGet(&entry->name)) != HC_SUCCESS) { - LOGE("Failed to add groupName to json!"); - DestroyGroupEntry(entry); - return HC_ERR_JSON_FAIL; - } - DestroyGroupEntry(entry); - return HC_SUCCESS; -} - -static int32_t AddDevInfoToContextByDb(const char *groupId, CJson *context) -{ - int32_t osAccountId; - if (GetIntFromJson(context, FIELD_OS_ACCOUNT_ID, &osAccountId) != HC_SUCCESS) { - LOGE("get osAccountId from json fail."); - return HC_ERR_JSON_GET; - } - char udid[INPUT_UDID_LEN] = { 0 }; - int32_t res = HcGetUdid((uint8_t *)udid, INPUT_UDID_LEN); - if (res != HC_SUCCESS) { - LOGE("Failed to get local udid! res: %d", res); - return HC_ERR_DB; - } - TrustedDeviceEntry *devAuthParams = CreateDeviceEntry(); - if (devAuthParams == NULL) { - LOGE("Failed to allocate devEntry memory!"); - return HC_ERR_ALLOC_MEMORY; - } - if (GetTrustedDevInfoById(osAccountId, udid, true, groupId, devAuthParams) != HC_SUCCESS) { - LOGE("Failed to obtain the local device information from the database!"); - DestroyDeviceEntry(devAuthParams); - return HC_ERR_DB; - } - if (AddStringToJson(context, FIELD_AUTH_ID, StringGet(&devAuthParams->authId)) != HC_SUCCESS) { - LOGE("Failed to add authId to params!"); - DestroyDeviceEntry(devAuthParams); - return HC_ERR_JSON_FAIL; - } - if (AddIntToJson(context, FIELD_USER_TYPE, devAuthParams->devType) != HC_SUCCESS) { - LOGE("Failed to add userType to params!"); - DestroyDeviceEntry(devAuthParams); - return HC_ERR_JSON_FAIL; - } - DestroyDeviceEntry(devAuthParams); - return HC_SUCCESS; -} - static int32_t GetOpCodeFromContext(const CJson *context) { bool isAdmin = true; @@ -1096,8 +979,95 @@ static int32_t AddDeviceIdToJson(CJson *context, const char *peerUdid) return HC_SUCCESS; } -static int32_t BuildServerAuthContext(int64_t requestId, int32_t opCode, const char *appId, CJson *context, - char **returnPeerUdid) +static int32_t QueryAndAddCredToContext(int32_t osAccountId, CJson *context, const char *credIdKey, + const char *credObjKey) +{ + const char *credId = GetStringFromJson(context, credIdKey); + if (credId == NULL) { + LOGE("get self credential id from json fail."); + return HC_ERR_JSON_GET; + } + char *credDataStr = NULL; + int32_t ret = QueryCredInfoByCredId(osAccountId, credId, &credDataStr); + if (ret != HC_SUCCESS) { + LOGE("No credential found."); + return ret; + } + CJson *credDataJson = CreateJsonFromString(credDataStr); + HcFree(credDataStr); + if (credDataJson == NULL) { + LOGE("Faild to create json from string"); + return HC_ERR_JSON_FAIL; + } + if (AddObjToJson(context, credObjKey, credDataJson) != HC_SUCCESS) { + LOGE("add local credential object to context fail."); + FreeJson(credDataJson); + return HC_ERR_JSON_ADD; + } + FreeJson(credDataJson); + return HC_SUCCESS; +} + +static int32_t QueryAndAddAllCredToContext(int32_t osAccountId, CJson *context) +{ + int32_t res = QueryAndAddCredToContext(osAccountId, context, FIELD_SELF_CRED_ID, FIELD_SELF_CREDENTIAL_OBJ); + if (res != HC_SUCCESS) { + LOGE("Get self credential fail."); + return res; + } + if (true) { + return HC_SUCCESS; + } + res = QueryAndAddCredToContext(osAccountId, context, FIELD_PEER_CRED_ID, FIELD_PEER_CREDENTIAL_OBJ); + if (res != HC_SUCCESS) { + LOGE("Get self credential fail."); + return res; + } + return HC_SUCCESS; +} + +static const char *GetAppIdByContext(const CJson *context, bool isCredAuth) +{ + if (isCredAuth) { + const CJson *json = GetObjFromJson(context, FIELD_SELF_CREDENTIAL_OBJ); + if (json == NULL) { + LOGE("get self credential info from json fail."); + return NULL; + } + const char *appId = GetStringFromJson(json, FIELD_CRED_OWNER); + if (appId == NULL) { + LOGE("get appId from json fail."); + return NULL; + } + return appId; + } + const char *appId = GetStringFromJson(context, FIELD_SERVICE_PKG_NAME); + if (appId == NULL) { + LOGE("get servicePkgName from json fail."); + return NULL; + } + return appId; +} + +static int32_t CheckIsCredAuth(int32_t osAccountId, CJson *context, bool isCredAuth, char **returnPeerUdid) +{ + if (!isCredAuth) { + const char *peerUdid = GetPeerUdidFromJson(osAccountId, context); + if (peerUdid == NULL) { + return HC_ERR_JSON_GET; + } + (void)DeepCopyString(peerUdid, returnPeerUdid); + PRINT_SENSITIVE_DATA("PeerUdid", peerUdid); + if (AddDeviceIdToJson(context, peerUdid) != HC_SUCCESS) { + LOGE("add deviceId to context fail."); + return HC_ERR_JSON_ADD; + } + } + return HC_SUCCESS; +} + +static int32_t BuildServerAuthContext(int64_t requestId, CJson *context, bool isCredAuth, + char **returnPeerUdid, const char **returnAppId) { int32_t res = CheckConfirmationExist(context); if (res != HC_SUCCESS) { @@ -1109,15 +1079,9 @@ static int32_t BuildServerAuthContext(int64_t requestId, int32_t opCode, const c } int32_t osAccountId = ANY_OS_ACCOUNT; (void)GetIntFromJson(context, FIELD_OS_ACCOUNT_ID, &osAccountId); - const char *peerUdid = GetPeerUdidFromJson(osAccountId, context); - if (peerUdid == NULL) { - return HC_ERR_JSON_GET; - } - (void)DeepCopyString(peerUdid, returnPeerUdid); - PRINT_SENSITIVE_DATA("PeerUdid", peerUdid); - if (AddDeviceIdToJson(context, peerUdid) != HC_SUCCESS) { - LOGE("add deviceId to context fail."); - return HC_ERR_JSON_ADD; + res = CheckIsCredAuth(osAccountId, context, isCredAuth, returnPeerUdid); + if (res != HC_SUCCESS) { + return res; } if (AddBoolToJson(context, FIELD_IS_BIND, false) != HC_SUCCESS) { LOGE("add isBind to context fail."); @@ -1127,6 +1091,23 @@ static int32_t BuildServerAuthContext(int64_t requestId, int32_t opCode, const c LOGE("add isClient to context fail."); return HC_ERR_JSON_ADD; } + if (isCredAuth) { + res = QueryAndAddAllCredToContext(osAccountId, context); + if (res != HC_SUCCESS) { + return res; + } + } + const char *appId = GetAppIdByContext(context, isCredAuth); + if (appId == NULL) { + LOGE("get appId Fail."); + FreeJson(context); + return HC_ERR_JSON_GET; + } + *returnAppId = appId; + if (AddBoolToJson(context, FIELD_IS_CRED_AUTH, isCredAuth) != HC_SUCCESS) { + LOGE("add isCredAuth to context fail."); + return HC_ERR_JSON_ADD; + } if (AddInt64StringToJson(context, FIELD_REQUEST_ID, requestId) != HC_SUCCESS) { LOGE("add requestId to context fail."); return HC_ERR_JSON_ADD; @@ -1135,10 +1116,6 @@ static int32_t BuildServerAuthContext(int64_t requestId, int32_t opCode, const c LOGE("add appId to context fail."); return HC_ERR_JSON_ADD; } - if (AddIntToJson(context, FIELD_OPERATION_CODE, opCode) != HC_SUCCESS) { - LOGE("add opCode to context fail."); - return HC_ERR_JSON_ADD; - } return AddChannelInfoToContext(SERVICE_CHANNEL, DEFAULT_CHANNEL_ID, context); } @@ -1189,7 +1166,7 @@ static int32_t BuildServerP2PAuthContext(int64_t requestId, int32_t opCode, cons } static int32_t OpenServerAuthSession(int64_t requestId, const CJson *receivedMsg, const DeviceAuthCallback *callback, - char **returnPeerUdid) + bool isCredAuth, char **returnPeerUdid) { int32_t opCode = AUTH_FORM_ACCOUNT_UNRELATED; if (GetIntFromJson(receivedMsg, FIELD_AUTH_FORM, &opCode) != HC_SUCCESS) { @@ -1209,13 +1186,13 @@ static int32_t OpenServerAuthSession(int64_t requestId, const CJson *receivedMsg LOGE("Failed to create context from string!"); return HC_ERR_JSON_FAIL; } - const char *appId = GetStringFromJson(context, FIELD_SERVICE_PKG_NAME); - if (appId == NULL) { - LOGE("get appId from json fail."); + if (AddIntToJson(context, FIELD_OPERATION_CODE, opCode) != HC_SUCCESS) { + LOGE("add opCode to context fail."); FreeJson(context); - return HC_ERR_JSON_GET; + return HC_ERR_JSON_ADD; } - int32_t res = BuildServerAuthContext(requestId, opCode, appId, context, returnPeerUdid); + const char *appId = NULL; + int32_t res = BuildServerAuthContext(requestId, context, isCredAuth, returnPeerUdid, &appId); if (res != HC_SUCCESS) { FreeJson(context); return res; @@ -1296,7 +1273,7 @@ static int32_t ProcessDataInner(int64_t authReqId, const uint8_t *data, uint32_t } int32_t res; if (!IsSessionExist(authReqId)) { - res = OpenServerAuthSession(authReqId, receivedMsg, gaCallback, returnPeerUdid); + res = OpenServerAuthSession(authReqId, receivedMsg, gaCallback, false, returnPeerUdid); if (res != HC_SUCCESS) { FreeJson(receivedMsg); return res; @@ -1335,6 +1312,155 @@ static int32_t ProcessData(int64_t authReqId, const uint8_t *data, uint32_t data return res; } +static int32_t BuildClientAuthCredContext(int32_t osAccountId, int64_t requestId, const char *appId, CJson *context) +{ + if (AddBoolToJson(context, FIELD_IS_BIND, false) != HC_SUCCESS) { + LOGE("add isBind to context fail."); + return HC_ERR_JSON_ADD; + } + if (AddBoolToJson(context, FIELD_IS_CLIENT, true) != HC_SUCCESS) { + LOGE("add isClient to context fail."); + return HC_ERR_JSON_ADD; + } + if (AddBoolToJson(context, FIELD_IS_CRED_AUTH, true) != HC_SUCCESS) { + LOGE("add isCredAuth to context fail."); + return HC_ERR_JSON_ADD; + } + if (AddIntToJson(context, FIELD_OS_ACCOUNT_ID, osAccountId) != HC_SUCCESS) { + LOGE("add osAccountId to context fail."); + return HC_ERR_JSON_ADD; + } + if (AddInt64StringToJson(context, FIELD_REQUEST_ID, requestId) != HC_SUCCESS) { + LOGE("add requestId to context fail."); + return HC_ERR_JSON_ADD; + } + if (AddStringToJson(context, FIELD_APP_ID, appId) != HC_SUCCESS) { + LOGE("add appId to context fail."); + return HC_ERR_JSON_ADD; + } + if (AddIntToJson(context, FIELD_OPERATION_CODE, AUTH_FORM_IDENTICAL_ACCOUNT) != HC_SUCCESS) { + LOGE("add opCode to context fail."); + return HC_ERR_JSON_ADD; + } + return AddChannelInfoToContext(SERVICE_CHANNEL, DEFAULT_CHANNEL_ID, context); +} + +static int32_t AuthCredentialInner(int32_t osAccountId, int64_t authReqId, const char *authParams, + const DeviceAuthCallback *caCallback, char **returnPeerUdid) +{ + SET_LOG_MODE(TRACE_MODE); + SET_TRACE_ID(authReqId); + ADD_PERFORM_DATA(authReqId, false, true, HcGetCurTimeInMillis()); + LOGI("Begin AuthCredential. [ReqId]: %" PRId64 ", [OsAccountId]: %d", authReqId, osAccountId); + if (authParams == NULL || osAccountId == INVALID_OS_ACCOUNT || caCallback == NULL || + returnPeerUdid == NULL) { + LOGE("The input auth cred params is invalid!"); + return HC_ERR_INVALID_PARAMS; + } + if (!CheckIsForegroundOsAccountId(osAccountId)) { + LOGE("This access is not from the foreground user, rejected it."); + return HC_ERR_CROSS_USER_ACCESS; + } + if (!IsOsAccountUnlocked(osAccountId)) { + LOGE("Os account is not unlocked!"); + return HC_ERR_OS_ACCOUNT_NOT_UNLOCKED; + } + CJson *context = CreateJsonFromString(authParams); + if (context == NULL) { + LOGE("Failed to create json from string!"); + return HC_ERR_JSON_FAIL; + } + int32_t res = QueryAndAddAllCredToContext(osAccountId, context); + if (res != HC_SUCCESS) { + FreeJson(context); + return res; + } + const char *appId = GetAppIdByContext(context, true); + if (appId == NULL) { + LOGE("get appId fail."); + FreeJson(context); + return HC_ERR_JSON_GET; + } + res = BuildClientAuthCredContext(osAccountId, authReqId, appId, context); + if (res != HC_SUCCESS) { + FreeJson(context); + return res; + } + SessionInitParams params = { context, *caCallback }; + res = OpenDevSession(authReqId, appId, ¶ms); + FreeJson(context); + if (res != HC_SUCCESS) { + LOGE("OpenDevSession fail. [Res]: %d", res); + return res; + } + return PushStartSessionTask(authReqId); +} + +int32_t AuthCredential(int32_t osAccountId, int64_t authReqId, const char *authParams, + const DeviceAuthCallback *caCallback) +{ + char *peerUdid = NULL; + int32_t res = AuthCredentialInner(osAccountId, authReqId, authParams, caCallback, &peerUdid); + if (peerUdid != NULL) { + HcFree(peerUdid); + } + return res; +} + +static int32_t ProcessCredDataInner(int64_t authReqId, const uint8_t *data, uint32_t dataLen, + const DeviceAuthCallback *caCallback, char **returnPeerUdid) +{ + SET_LOG_MODE(TRACE_MODE); + SET_TRACE_ID(authReqId); + if (!IsSessionExist(authReqId)) { + ADD_PERFORM_DATA(authReqId, false, false, HcGetCurTimeInMillis()); + } else { + UPDATE_PERFORM_DATA_BY_SELF_INDEX(authReqId, HcGetCurTimeInMillis()); + } + LOGI("[GA] Begin ProcessCredData. [DataLen]: %u, [ReqId]: %" PRId64, dataLen, authReqId); + if ((data == NULL) || (dataLen > MAX_DATA_BUFFER_SIZE)) { + LOGE("Invalid input for ProcessCredData!"); + return HC_ERR_INVALID_PARAMS; + } + CJson *receivedMsg = CreateJsonFromString((const char *)data); + if (receivedMsg == NULL) { + LOGE("Failed to create json from string!"); + return HC_ERR_JSON_FAIL; + } + int32_t res; + if (!IsSessionExist(authReqId)) { + res = OpenServerAuthSession(authReqId, receivedMsg, caCallback, true, returnPeerUdid); + if (res != HC_SUCCESS) { + FreeJson(receivedMsg); + return res; + } + } + if (HasAccountPlugin()) { + res = AddOriginDataForPlugin(receivedMsg, data); + if (res != HC_SUCCESS) { + FreeJson(receivedMsg); + return res; + } + } + res = PushProcSessionTask(authReqId, receivedMsg); + if (res != HC_SUCCESS) { + FreeJson(receivedMsg); + return res; + } + return HC_SUCCESS; +} + +static int32_t ProcessCredData(int64_t authReqId, const uint8_t *data, uint32_t dataLen, + const DeviceAuthCallback *caCallback) +{ + char *peerUdid = NULL; + int32_t res = ProcessCredDataInner(authReqId, data, dataLen, caCallback, &peerUdid); + if (peerUdid != NULL) { + HcFree(peerUdid); + } + return res; +} + static void CancelRequest(int64_t requestId, const char *appId) { SET_LOG_MODE(TRACE_MODE); @@ -1551,6 +1677,46 @@ static void DestroyGmAndGa(void) } } +static int32_t AllocCredentialMgr(void) +{ + if (g_credManager == NULL) { + g_credManager = (CredManager *)HcMalloc(sizeof(CredManager), 0); + if (g_credManager == NULL) { + LOGE("Failed to allocate g_credManager Instance memory!"); + return HC_ERR_ALLOC_MEMORY; + } + } + return HC_SUCCESS; +} + +static void DestroyCredentialMgr(void) +{ + if (g_credManager != NULL) { + HcFree(g_credManager); + g_credManager = NULL; + } +} + +static int32_t AllocCa(void) +{ + if (g_credAuthManager == NULL) { + g_credAuthManager = (CredAuthManager *)HcMalloc(sizeof(CredAuthManager), 0); + if (g_credAuthManager == NULL) { + LOGE("Failed to allocate groupManager Instance memory!"); + return HC_ERR_ALLOC_MEMORY; + } + } + return HC_SUCCESS; +} + +static void DestroyCa(void) +{ + if (g_credAuthManager != NULL) { + HcFree(g_credAuthManager); + g_credAuthManager = NULL; + } +} + static int32_t InitAllModules(void) { int32_t res = GetLoaderInstance()->initAlg(); @@ -1558,32 +1724,29 @@ static int32_t InitAllModules(void) LOGE("[End]: [Service]: Failed to init algorithm module!"); return res; } - res = InitCredMgr(); - if (res != HC_SUCCESS) { + if ((res = InitCredMgr()) != HC_SUCCESS) { LOGE("[End]: [Service]: Failed to init cred mgr!"); return res; } - res = InitModules(); - if (res != HC_SUCCESS) { + if ((res = InitModules()) != HC_SUCCESS) { LOGE("[End]: [Service]: Failed to init all authenticator modules!"); goto CLEAN_CRED; } - res = InitCallbackManager(); - if (res != HC_SUCCESS) { + if ((res = InitCallbackManager()) != HC_SUCCESS) { LOGE("[End]: [Service]: Failed to init callback manage module!"); goto CLEAN_MODULE; } - res = InitGroupManager(); - if (res != HC_SUCCESS) { + if ((InitGroupManager()) != HC_SUCCESS) { goto CLEAN_CALLBACK; } - res = InitDevSessionManager(); - if (res != HC_SUCCESS) { + if ((res = InitIdentityService()) != HC_SUCCESS) { + goto CLEAN_IDENTITY_SERVICE; + } + if ((res = InitDevSessionManager()) != HC_SUCCESS) { goto CLEAN_GROUP_MANAGER; } (void)InitGroupAuthManager(); - res = InitTaskManager(); - if (res != HC_SUCCESS) { + if ((res = InitTaskManager()) != HC_SUCCESS) { LOGE("[End]: [Service]: Failed to init worker thread!"); goto CLEAN_ALL; } @@ -1598,6 +1761,8 @@ CLEAN_MODULE: DestroyModules(); CLEAN_CRED: DestroyCredMgr(); +CLEAN_IDENTITY_SERVICE: + DestroyIdentityService(); return res; } @@ -1704,10 +1869,23 @@ DEVICE_AUTH_API_PUBLIC int InitDeviceAuthService(void) if (res != HC_SUCCESS) { return res; } + res = AllocCa(); + if (res != HC_SUCCESS) { + DestroyGmAndGa(); + return res; + } + res = AllocCredentialMgr(); + if (res != HC_SUCCESS) { + DestroyGmAndGa(); + DestroyCa(); + return res; + } InitOsAccountAdapter(); res = InitAllModules(); if (res != HC_SUCCESS) { DestroyGmAndGa(); + DestroyCa(); + DestroyCredentialMgr(); return res; } INIT_PERFORMANCE_DUMPER(); @@ -1730,7 +1908,10 @@ DEVICE_AUTH_API_PUBLIC void DestroyDeviceAuthService(void) DestroyTaskManager(); DestroyDevSessionManager(); DestroyGroupManager(); + DestroyIdentityService(); DestroyGmAndGa(); + DestroyCa(); + DestroyCredentialMgr(); DestroyModules(); DestroyCredMgr(); DestroyChannelManager(); @@ -1788,3 +1969,35 @@ DEVICE_AUTH_API_PUBLIC const GroupAuthManager *GetGaInstance(void) g_groupAuthManager->getPseudonymId = GetPseudonymId; return g_groupAuthManager; } + +DEVICE_AUTH_API_PUBLIC const CredManager *GetCredMgrInstance(void) +{ + if (g_credManager == NULL) { + LOGE("Service not init"); + return NULL; + } + + g_credManager->addCredential = AddCredential; + g_credManager->exportCredential = ExportCredential; + g_credManager->queryCredentialByParams = QueryCredentialByParams; + g_credManager->queryCredInfoByCredId = QueryCredInfoByCredId; + g_credManager->deleteCredential = DeleteCredential; + g_credManager->updateCredInfo = UpdateCredInfo; + g_credManager->registerChangeListener = RegisterChangeListener; + g_credManager->unregisterChangeListener = UnregisterChangeListener; + g_credManager->destroyInfo = DestroyInfo; + + return g_credManager; +} + +DEVICE_AUTH_API_PUBLIC const CredAuthManager *GetCredAuthInstance(void) +{ + if (g_credAuthManager == NULL) { + LOGE("Service not init."); + return NULL; + } + + g_credAuthManager->processCredData = ProcessCredData; + g_credAuthManager->authCredential = AuthCredential; + return g_credAuthManager; +} \ No newline at end of file diff --git a/services/device_auth.map b/services/device_auth.map index b387dc6e56eb07be33a85df784a25d31740ec77d..6e064cdaf9bbfa80d9414997e8988761e4e53cbd 100644 --- a/services/device_auth.map +++ b/services/device_auth.map @@ -19,6 +19,8 @@ DestroyDeviceAuthService; GetGaInstance; GetGmInstance; + GetCredMgrInstance; + GetCredAuthInstance; ProcessCredential; StartAuthDevice; ProcessAuthDevice; diff --git a/services/deviceauth.gni b/services/deviceauth.gni index 01c32bd31aaceb93ee945acba171a16601f80fca..0c745722b3b4e3bb5c49dacd3d71fe2fdf7d6fd7 100644 --- a/services/deviceauth.gni +++ b/services/deviceauth.gni @@ -16,24 +16,36 @@ import("//base/security/device_auth/deviceauth_env.gni") group_auth_path = "${services_path}/legacy/group_auth" authenticators_path = "${services_path}/legacy/authenticators" protocol_path = "${services_path}/protocol" -cred_manager_path = "${services_path}/cred_manager" -data_manager_path = "${services_path}/data_manager" +ext_plugin_manager_path = "${services_path}/ext_plugin_manager" +group_data_manager_path = "${services_path}/data_manager/group_data_manager" +cred_data_manager_path = "${services_path}/data_manager/cred_data_manager" +cred_listener_path = "${services_path}/identity_service/listener" privacy_enhancement_path = "${services_path}/privacy_enhancement" dev_frameworks_path = "${services_path}/frameworks" group_manager_path = "${services_path}/legacy/group_manager" session_manager_path = "${services_path}/session_manager" -creds_manager_path = "${services_path}/creds_manager" +creds_manager_path = "${services_path}/legacy/creds_manager" mk_agree_path = "${services_path}/mk_agree" -identity_manager_path = "${services_path}/identity_manager" +identity_manager_path = "${services_path}/legacy/identity_manager" +identity_service_path = "${services_path}/identity_service" enable_broadcast = true deviceauth_defines = [] +identity_service_inc = [ "${identity_service_path}/inc" ] +identity_service_files = [ + "${identity_service_path}/src/identity_service.c", + "${identity_service_path}/src/identity_operation.c", + "${identity_service_path}/src/identity_service_impl.c", +] + inc_path = [ "${inner_api_path}", "${frameworks_path}/inc", - "${cred_manager_path}/inc", - "${cred_manager_path}/inc/account_related", - "${data_manager_path}/inc", + "${ext_plugin_manager_path}/inc", + "${ext_plugin_manager_path}/inc/account_related", + "${group_data_manager_path}/inc", + "${cred_data_manager_path}/inc", + "${cred_listener_path}/inc", "${privacy_enhancement_path}/inc", "${group_auth_path}/inc", "${group_auth_path}/inc/account_unrelated_group_auth", @@ -52,6 +64,9 @@ inc_path = [ "${dev_frameworks_path}/inc/security_label_adapter", "${dev_frameworks_path}/inc/account_task_manager", "${authenticators_path}/inc/account_related", + "${authenticators_path}/inc/account_related/auth/iso_auth_task", + "${authenticators_path}/inc/account_related/auth/pake_v2_auth_task", + "${authenticators_path}/inc/account_related/creds_manager", "${authenticators_path}/inc/account_unrelated", "${authenticators_path}/inc/account_unrelated/iso_task", "${authenticators_path}/inc/account_unrelated/iso_task/iso_protocol_task", @@ -81,6 +96,8 @@ inc_path = [ "${mk_agree_path}/inc", ] +inc_path += identity_service_inc + deviceauth_common_files = [ "${services_path}/device_auth.c", "${group_manager_path}/src/group_manager.c", @@ -139,7 +156,7 @@ group_auth_account_unrelated_files = [ "${group_auth_path}/src/group_auth_manage group_auth_account_unrelated_mock_files = [ "${group_auth_path}/src/group_auth_manager/account_unrelated_group_auth_mock/account_unrelated_group_auth_mock.c" ] group_auth_account_related_mock_files = [ "${group_auth_path}/src/group_auth_manager/account_related_group_auth_mock/account_related_group_auth_mock.c" ] -account_related_cred_plugin_mock_files = [ "${cred_manager_path}/src/account_related_mock/account_related_cred_plugin_mock.c" ] +account_related_cred_plugin_mock_files = [ "${ext_plugin_manager_path}/src/account_related_mock/account_related_cred_plugin_mock.c" ] account_auth_plugin_files = [ "${dev_frameworks_path}/src/plugin_adapter/ext_part/account_auth_plugin_proxy.c" ] account_auth_plugin_mock_files = [ "${dev_frameworks_path}/src/plugin_adapter_mock/account_auth_plugin_proxy_mock.c" ] @@ -148,9 +165,13 @@ account_task_manager_files = [ "${dev_frameworks_path}/src/account_task_manager/account_task_manager.c" ] account_task_manager_mock_files = [ "${dev_frameworks_path}/src/account_task_manager_mock/account_task_manager_mock.c" ] -cred_manager_files = [ "${cred_manager_path}/src/cred_manager.c" ] +ext_plugin_manager_files = + [ "${ext_plugin_manager_path}/src/ext_plugin_manager.c" ] -database_manager_files = [ "${data_manager_path}/src/data_manager.c" ] +group_database_manager_files = + [ "${group_data_manager_path}/src/group_data_manager.c" ] +cred_database_manager_files = + [ "${cred_data_manager_path}/src/credential_data_manager.c" ] privacy_enhancement_files = [ "${privacy_enhancement_path}/src/pseudonym_manager.c" ] @@ -271,6 +292,8 @@ broadcast_manager_mock_files = [ "${group_manager_path}/src/broadcast_manager_mock/broadcast_manager_mock.c", ] +cred_listener_files = [ "${cred_listener_path}/src/cred_listener.c" ] + deviceauth_files = dev_frameworks_files + deviceauth_common_files + session_manager_files + creds_manager_files @@ -337,7 +360,8 @@ if (enable_p2p_pake_dl_prime_len_256 == true) { } deviceauth_files += group_auth_files + group_manager_files + - database_manager_files + cred_manager_files + group_database_manager_files + ext_plugin_manager_files + + cred_database_manager_files + identity_service_files account_unrelated_deviceauth = enable_p2p_bind_lite_protocol || enable_p2p_auth_lite_protocol || @@ -406,9 +430,9 @@ if (device_auth_enable_soft_bus_channel == true) { } if (enable_broadcast == true) { - deviceauth_files += broadcast_manager_files + deviceauth_files += broadcast_manager_files + cred_listener_files } else { - deviceauth_files += broadcast_manager_mock_files + deviceauth_files += broadcast_manager_mock_files + cred_listener_files } if (!defined(ohos_lite) && (!defined(global_parts_info) || diff --git a/services/deviceauth_account.gni b/services/deviceauth_account.gni index 42fddb34c1cfc39e3da60b0b3cdde0fc5b916af9..ab30a9b37cc0d801bdbb3772017d68687008beb8 100644 --- a/services/deviceauth_account.gni +++ b/services/deviceauth_account.gni @@ -26,7 +26,7 @@ group_manager_identical_account_files = [ "${deviceauth_account_group_manager_pa group_manager_across_account_files = [ "${deviceauth_account_group_manager_path}/src/group_operation/across_account_group/across_account_group.c" ] group_auth_account_related_files = [ "${deviceauth_account_group_auth_path}/src/group_auth_manager/account_related_group_auth/account_related_group_auth.c" ] -identity_manager_path = "${services_path}/identity_manager" +identity_manager_path = "${services_path}/legacy/identity_manager" account_related_inc_path += [ "${authenticators_path}/inc", "${authenticators_path}/inc/account_related", @@ -50,7 +50,7 @@ authenticators_account_related_files = [ "${authenticators_path}/src/account_related/auth/pake_v2_auth_task/pake_v2_auth_server_task.c", ] -account_related_cred_plugin_files = [ "${services_path}/cred_manager/src/account_related/account_related_cred_plugin.c" ] +account_related_cred_plugin_files = [ "${services_path}/ext_plugin_manager/src/account_related/account_related_cred_plugin.c" ] account_related_creds_manager_files = [ "${identity_manager_path}/src/cert_operation.c" ] diff --git a/services/cred_manager/inc/account_related/account_related_cred_plugin.h b/services/ext_plugin_manager/inc/account_related/account_related_cred_plugin.h similarity index 89% rename from services/cred_manager/inc/account_related/account_related_cred_plugin.h rename to services/ext_plugin_manager/inc/account_related/account_related_cred_plugin.h index 6d98dc724d01de03f510061f92209d41d22f66ff..53db8371bacc0937e08aad8be7faef023a6351c4 100644 --- a/services/cred_manager/inc/account_related/account_related_cred_plugin.h +++ b/services/ext_plugin_manager/inc/account_related/account_related_cred_plugin.h @@ -13,8 +13,8 @@ * limitations under the License. */ -#ifndef ACCOUNT_RELATED_CRED_MANAGER_H -#define ACCOUNT_RELATED_CRED_MANAGER_H +#ifndef ACCOUNT_RELATED_EXT_PLUGIN_MANAGER_H +#define ACCOUNT_RELATED_EXT_PLUGIN_MANAGER_H #include #include "cred_plugin_def.h" diff --git a/services/cred_manager/inc/cred_plugin_def.h b/services/ext_plugin_manager/inc/cred_plugin_def.h similarity index 100% rename from services/cred_manager/inc/cred_plugin_def.h rename to services/ext_plugin_manager/inc/cred_plugin_def.h diff --git a/services/cred_manager/inc/cred_manager.h b/services/ext_plugin_manager/inc/ext_plugin_manager.h similarity index 94% rename from services/cred_manager/inc/cred_manager.h rename to services/ext_plugin_manager/inc/ext_plugin_manager.h index 41657a618d2e75e14e67d7f569f7a27af50a516e..7c8672b4d677bf5d9da57d07d45c7536d2e0e881 100644 --- a/services/cred_manager/inc/cred_manager.h +++ b/services/ext_plugin_manager/inc/ext_plugin_manager.h @@ -13,8 +13,8 @@ * limitations under the License. */ -#ifndef CRED_MANAGER_H -#define CRED_MANAGER_H +#ifndef EXT_PLUGIN_MANAGER_H +#define EXT_PLUGIN_MANAGER_H #include "cred_plugin_def.h" #include "json_utils.h" diff --git a/services/cred_manager/src/account_related/account_related_cred_plugin.c b/services/ext_plugin_manager/src/account_related/account_related_cred_plugin.c similarity index 100% rename from services/cred_manager/src/account_related/account_related_cred_plugin.c rename to services/ext_plugin_manager/src/account_related/account_related_cred_plugin.c diff --git a/services/cred_manager/src/account_related_mock/account_related_cred_plugin_mock.c b/services/ext_plugin_manager/src/account_related_mock/account_related_cred_plugin_mock.c similarity index 100% rename from services/cred_manager/src/account_related_mock/account_related_cred_plugin_mock.c rename to services/ext_plugin_manager/src/account_related_mock/account_related_cred_plugin_mock.c diff --git a/services/cred_manager/src/cred_manager.c b/services/ext_plugin_manager/src/ext_plugin_manager.c similarity index 93% rename from services/cred_manager/src/cred_manager.c rename to services/ext_plugin_manager/src/ext_plugin_manager.c index 368f16408d287fe3e538ceebe2e1a4597a089ab1..233f064e13c9bd3266f0a472be4e0f9896979d64 100644 --- a/services/cred_manager/src/cred_manager.c +++ b/services/ext_plugin_manager/src/ext_plugin_manager.c @@ -13,7 +13,7 @@ * limitations under the License. */ -#include "cred_manager.h" +#include "ext_plugin_manager.h" #include "account_related_cred_plugin.h" #include "device_auth_defines.h" @@ -46,11 +46,7 @@ int32_t InitCredMgr(void) if (plugin != NULL) { int32_t res = plugin->init(); if (res == HC_SUCCESS) { - if (g_credPluginVec.pushBackT(&g_credPluginVec, plugin) == NULL) { - LOGE("[CredMgr]: Failed to push plugin!"); - plugin->destroy(); - return HC_ERR_ALLOC_MEMORY; - } + (void)g_credPluginVec.pushBackT(&g_credPluginVec, plugin); } else { LOGW("[CredMgr]: Init account related cred plugin fail. [Res]: %d", res); } diff --git a/services/frameworks/inc/hiview_adapter/hidump_adapter.h b/services/frameworks/inc/hiview_adapter/hidump_adapter.h index e01a7bd70c8d72eda0ff7d9eefe7b4794f399cb5..f1cae3abc0e35ca0c1822586e4adc316898efd36 100644 --- a/services/frameworks/inc/hiview_adapter/hidump_adapter.h +++ b/services/frameworks/inc/hiview_adapter/hidump_adapter.h @@ -22,18 +22,21 @@ #define PERFORM_DUMP_ARG "performance" typedef void (*DumpCallBack)(int); +typedef void (*CredDumpCallBack)(int); typedef void (*PerformanceDumpCallBack)(int, StringVector *); #ifndef DEV_AUTH_HIVIEW_ENABLE #define DEV_AUTH_DUMP(fd, strArgVec) #define DEV_AUTH_REG_DUMP_FUNC(func) +#define DEV_AUTH_REG_CRED_DUMP_FUNC(func) #define DEV_AUTH_REG_PERFORM_DUMP_FUNC(func) #else #define DEV_AUTH_DUMP(fd, strArgVec) DevAuthDump(fd, strArgVec) #define DEV_AUTH_REG_DUMP_FUNC(func) RegisterDumpFunc(func) +#define DEV_AUTH_REG_CRED_DUMP_FUNC(func) RegisterCredDumpFunc(func) #define DEV_AUTH_REG_PERFORM_DUMP_FUNC(func) RegisterPerformDumpFunc(func) #ifdef __cplusplus @@ -43,6 +46,7 @@ extern "C" { void DevAuthDump(int fd, StringVector *strArgVec); void RegisterDumpFunc(DumpCallBack func); +void RegisterCredDumpFunc(CredDumpCallBack func); void RegisterPerformDumpFunc(PerformanceDumpCallBack func); #ifdef __cplusplus diff --git a/services/frameworks/inc/os_account_adapter/os_account_adapter.h b/services/frameworks/inc/os_account_adapter/os_account_adapter.h index 566ccc142db0752c14afed2be6e5a353fea11d5d..9241f1fb1a5b183041972d8d3542080a7ebccd93 100644 --- a/services/frameworks/inc/os_account_adapter/os_account_adapter.h +++ b/services/frameworks/inc/os_account_adapter/os_account_adapter.h @@ -27,7 +27,8 @@ typedef enum { GROUP_DATA_CALLBACK = 0, ASY_TOKEN_DATA_CALLBACK, SYM_TOKEN_DATA_CALLBACK, - PSEUDONYM_DATA_CALLBACK + PSEUDONYM_DATA_CALLBACK, + CRED_DATA_CALLBACK } EventCallbackId; typedef void (*OsAccountCallbackFunc)(int32_t osAccountId); diff --git a/services/frameworks/inc/permission_adapter/permission_adapter.h b/services/frameworks/inc/permission_adapter/permission_adapter.h index 6009f58e5743b8ee718b91bec9579759f527e9a0..5439b9005374c3539ae761d1b58f6b27882c7969 100644 --- a/services/frameworks/inc/permission_adapter/permission_adapter.h +++ b/services/frameworks/inc/permission_adapter/permission_adapter.h @@ -16,13 +16,14 @@ #ifndef PERMISSION_ADAPTER_H #define PERMISSION_ADAPTER_H -#include +#include #ifdef __cplusplus extern "C" { #endif int32_t CheckPermission(int32_t methodId); +int32_t GetCallingUid(void); #ifdef __cplusplus } diff --git a/services/frameworks/src/hiview_adapter/hidump_adapter.c b/services/frameworks/src/hiview_adapter/hidump_adapter.c index b9f6ae52917e849031a842a964e29f6f57a4a843..30c6a992246be4b6d32051e5b0d34db9f6e589d4 100644 --- a/services/frameworks/src/hiview_adapter/hidump_adapter.c +++ b/services/frameworks/src/hiview_adapter/hidump_adapter.c @@ -18,6 +18,7 @@ #include "string.h" static DumpCallBack g_dumpCallBack = NULL; +static CredDumpCallBack g_credDumpCallBack = NULL; static PerformanceDumpCallBack g_performDumpCallback = NULL; static void DumpByArgs(int fd, StringVector *strArgVec) @@ -42,6 +43,9 @@ void DevAuthDump(int fd, StringVector *strArgVec) if (g_dumpCallBack != NULL) { g_dumpCallBack(fd); } + if (g_credDumpCallBack != NULL) { + g_credDumpCallBack(fd); + } } else { DumpByArgs(fd, strArgVec); } @@ -52,6 +56,11 @@ void RegisterDumpFunc(DumpCallBack func) g_dumpCallBack = func; } +void RegisterCredDumpFunc(CredDumpCallBack func) +{ + g_credDumpCallBack = func; +} + void RegisterPerformDumpFunc(PerformanceDumpCallBack func) { g_performDumpCallback = func; diff --git a/services/frameworks/src/permission_adapter/permission_adapter.cpp b/services/frameworks/src/permission_adapter/permission_adapter.cpp index 00407651ab3b65e60a0ab219e497c1d7b1940b29..42df3bb41a25104e9982018c88b77c7e05aba3d1 100644 --- a/services/frameworks/src/permission_adapter/permission_adapter.cpp +++ b/services/frameworks/src/permission_adapter/permission_adapter.cpp @@ -110,4 +110,9 @@ int32_t CheckPermission(int32_t methodId) return HC_ERROR; } return HC_SUCCESS; +} + +int32_t GetCallingUid(void) +{ + return IPCSkeleton::GetCallingUid(); } \ No newline at end of file diff --git a/services/frameworks/src/plugin_adapter/dynamic_plugin_adapter.c b/services/frameworks/src/plugin_adapter/dynamic_plugin_adapter.c index ed54fc9e16c95fcedaf66eb536edf47cd1a71bd0..fbea63af9279d64008af23cb0c5a52428f3a4a81 100644 --- a/services/frameworks/src/plugin_adapter/dynamic_plugin_adapter.c +++ b/services/frameworks/src/plugin_adapter/dynamic_plugin_adapter.c @@ -18,7 +18,7 @@ #include #include "cred_plugin_def.h" -#include "cred_manager.h" +#include "ext_plugin_manager.h" #include "dev_auth_dynamic_load.h" #include "dev_auth_module_manager.h" #include "device_auth_defines.h" diff --git a/services/frameworks/src/plugin_adapter/ext_part/account_lifecycle_plugin_proxy.c b/services/frameworks/src/plugin_adapter/ext_part/account_lifecycle_plugin_proxy.c index b795ec0617ffd49079909846f8e4dcb2f26defbf..b62c4535a9331cafc74ee0f04ffb6edae0fb990a 100644 --- a/services/frameworks/src/plugin_adapter/ext_part/account_lifecycle_plugin_proxy.c +++ b/services/frameworks/src/plugin_adapter/ext_part/account_lifecycle_plugin_proxy.c @@ -126,6 +126,15 @@ static int32_t InitAccountLifecyclePluginCtx(void) g_accountPluginCtx = NULL; return HC_ERR_INVALID_PARAMS; } + + const CredManager *cmInstace = GetCredMgrInstance(); + if (cmInstace == NULL) { + LOGE("[ACCOUNT_LIFE_PLUGIN]: Cm instance is null."); + HcFree(g_accountPluginCtx); + g_accountPluginCtx = NULL; + return HC_ERR_INVALID_PARAMS; + } + g_accountPluginCtx->createGroup = gmInstace->createGroup; g_accountPluginCtx->deleteGroup = gmInstace->deleteGroup; g_accountPluginCtx->getGroupInfo = gmInstace->getGroupInfo; @@ -135,6 +144,11 @@ static int32_t InitAccountLifecyclePluginCtx(void) g_accountPluginCtx->executeWorkerTask = ExecuteWorkerTask; g_accountPluginCtx->notifyAsyncTaskStart = NotifyAsyncTaskStart; g_accountPluginCtx->notifyAsyncTaskStop = NotifyAsyncTaskStop; + g_accountPluginCtx->addCredential = cmInstace->addCredential; + g_accountPluginCtx->exportCredential = cmInstace->exportCredential; + g_accountPluginCtx->deleteCredential = cmInstace->deleteCredential; + g_accountPluginCtx->updateCredInfo = cmInstace->updateCredInfo; + g_accountPluginCtx->queryCredInfoByCredId = cmInstace->queryCredInfoByCredId; return HC_SUCCESS; } diff --git a/services/frameworks/src/plugin_adapter/static_plugin_adapter.c b/services/frameworks/src/plugin_adapter/static_plugin_adapter.c index 3293f39c76abb11abde51988fb1c307861eb7a57..f6816fb795bc1035d17805e20959f5790fd368b1 100644 --- a/services/frameworks/src/plugin_adapter/static_plugin_adapter.c +++ b/services/frameworks/src/plugin_adapter/static_plugin_adapter.c @@ -16,7 +16,7 @@ #include "plugin_adapter.h" -#include "cred_manager.h" +#include "ext_plugin_manager.h" #include "dev_auth_module_manager.h" #include "device_auth_defines.h" #include "hc_log.h" diff --git a/services/identity_service/inc/identity_operation.h b/services/identity_service/inc/identity_operation.h new file mode 100644 index 0000000000000000000000000000000000000000..d140588f924e56cb1828ffe378f085bff7879dbc --- /dev/null +++ b/services/identity_service/inc/identity_operation.h @@ -0,0 +1,122 @@ +/* + * Copyright (C) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef IDENTITY_OPERATION_H +#define IDENTITY_OPERATION_H + +#include "cred_listener.h" +#include "credential_data_manager.h" +#include "uint8buff_utils.h" + +#define FIELD_CRED_TYPE "credType" +#define FIELD_CREDENTIAL_FORMAT "credentialFormat" +#define FIELD_METHOD "method" +#define FIELD_ALGORITHM_TYPE "algorithmType" +#define FIELD_SUBJECT "subject" +#define FIELD_ISSUER "issuer" +#define FIELD_KEY_VALUE "keyValue" +#define FIELD_DEVICE_ID "deviceId" +#define FIELD_PEER_USER_SPACE_ID "peerUserSpaceId" +#define FIELD_AUTHORIZED_ACCOUNT_LIST "authorizedAccountList" +#define FIELD_AUTHORIZED_SCOPE "authorizedScope" +#define FIELD_CRED_OWNER "credOwner" +#define FIELD_EXTEND_INFO "extendInfo" +#define FIELD_CRED_ID "credId" +#define FIELD_PROOF_TYPE "proofType" +#define FIELD_KEY_FORMAT "keyFormat" +#define FIELD_OS_ACCOUNT_ID "osAccountId" +#define FIELD_INTERFACE_PERMISSION "ohos.permission.ACCESS_DEVICE_AUTH_CRED_MGR" +#define DEFAULT_VAL 0 +#define RAND_NUM_LENGTH 16 +#define PUB_KEY_LENGTH 128 +#define PAKE_ED25519_KEY_PAIR_LEN 32 +#define MAX_INT64_SIZE 20 +#define MAX_CRED_SIZE 5000 +#define SELE_ECC_KEY_LEN 32 +#define AES_128_KEY_LEN 16 +#define DEFAULT_EX_INFO_VAL (-1) + +#ifdef __cplusplus +extern "C" { +#endif + +enum { + METHOD_GENERATE = 1, + METHOD_IMPORT = 2, +}; + +enum { + ACCOUNTT_RELATED = 1, + ACCOUNTT_UNRELATED = 2, +}; + +enum { + SYMMETRIC_KEY = 1, + ASYMMETRIC_PUB_KEY = 2, + ASYMMETRIC_KEY = 3, + X509_CERT = 4, +}; + +enum { + ALGO_TYPE_AES_256 = 1, + ALGO_TYPE_AES_128 = 2, + ALGO_TYPE_P256 = 3, + ALGO_TYPE_ED25519 = 4, +}; + +enum { + SELF_DEVICE = 1, + OTHER_DEVICE = 2, +}; + +enum { + SYSTEM_ACCOUNT = 1, + APP_ACCOUNT = 2, + DOMANIN_ACCOUNT = 3, +}; + +enum { + PROOF_TYPE_PSK = 1, + PROOF_TYPE_PKI = 2, +}; + +enum { + SCOPE_DEVICE = 1, + SCOPE_USER = 2, + SCOPE_APP = 3, +}; + +int32_t AddCredAndSaveDb(int32_t osAccountId, Credential *credential); +int32_t AddKeyValueToHuks(Uint8Buff credIdByte, Credential *credential, int32_t osAccountId, uint8_t method, + Uint8Buff *publicKey); +int32_t AddKeyValueToReturn(Uint8Buff keyValue, char **returnData); +int32_t CheckCredIdExistInHuks(int32_t osAccountId, const char *credId, Uint8Buff *credIdHashBuff); +int32_t DelCredById(int32_t osAccountId, const char *credId); + +int32_t GenerateCredId(Credential *credential, int32_t osAccountId, Uint8Buff *credIdByte, char **credIdStr); +int32_t GenerateReturnEmptyArrayStr(char **returnVec); +int32_t GetCredentialById(int32_t osAccountId, const char *credId, Credential **returnEntry); +int32_t GetCredIdsFromCredVec(CredentialVec credentialVec, CJson *credIdJson, int32_t osAccountId); + +int32_t CheckAndSetCredInfo(Credential *credential, CJson *json, int32_t osAccountId, uint8_t *method, + Uint8Buff *publicKey); +int32_t SetQueryParamsFromJson(QueryCredentialParams *queryParams, CJson *json); +int32_t UpdateInfoFromJson(Credential *credential, CJson *json); + +#ifdef __cplusplus +} +#endif + +#endif // IDENTITY_OPERATION_H diff --git a/services/identity_service/inc/identity_service.h b/services/identity_service/inc/identity_service.h new file mode 100644 index 0000000000000000000000000000000000000000..2eac1de4431c2835af374a4ffef28372b432078e --- /dev/null +++ b/services/identity_service/inc/identity_service.h @@ -0,0 +1,43 @@ +/* + * Copyright (C) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef IDENTITY_SERVICE_H +#define IDENTITY_SERVICE_H + +#include "cred_listener.h" + +int32_t AddCredential(int32_t osAccountId, const char *requestParams, char **returnData); + +int32_t ExportCredential(int32_t osAccountId, const char *credId, char **returnData); + +int32_t QueryCredentialByParams(int32_t osAccountId, const char *requestParams, char **returnData); + +int32_t QueryCredInfoByCredId(int32_t osAccountId, const char *credId, char **returnData); + +int32_t DeleteCredential(int32_t osAccountId, const char *appId, const char *credId); + +int32_t UpdateCredInfo(int32_t osAccountId, const char *appId, const char *credId, const char *requestParams); + +int32_t RegisterChangeListener(const char *appId, CredChangeListener *listener); + +int32_t UnregisterChangeListener(const char *appId); + +void DestroyInfo(char **returnData); + +int32_t InitIdentityService(void); + +void DestroyIdentityService(void); + +#endif // IDENTITY_SERVICE_H \ No newline at end of file diff --git a/services/identity_service/inc/identity_service_impl.h b/services/identity_service/inc/identity_service_impl.h new file mode 100644 index 0000000000000000000000000000000000000000..cd5de90e8d6a7c78aa5dd214ebe093a07d595a47 --- /dev/null +++ b/services/identity_service/inc/identity_service_impl.h @@ -0,0 +1,37 @@ +/* + * Copyright (C) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef IDENTITY_SERVICE_IMPL_H +#define IDENTITY_SERVICE_IMPL_H + +#include "cred_listener.h" + +int32_t AddCredentialImpl(int32_t osAccountId, const char *requestParams, char **returnData); + +int32_t ExportCredentialImpl(int32_t osAccountId, const char *credId, char **returnData); + +int32_t QueryCredentialByParamsImpl(int32_t osAccountId, const char *requestParams, char **returnData); + +int32_t QueryCredInfoByCredIdImpl(int32_t osAccountId, const char *credId, char **returnData); + +int32_t DeleteCredentialImpl(int32_t osAccountId, const char *appId, const char *credId); + +int32_t UpdateCredInfoImpl(int32_t osAccountId, const char *appId, const char *credId, const char *requestParams); + +int32_t RegCredListener(const char *appId, const CredChangeListener *listener); + +int32_t UnRegCredListener(const char *appId); + +#endif // IDENTITY_SERVICE_IMPL_H \ No newline at end of file diff --git a/services/identity_service/listener/inc/cred_listener.h b/services/identity_service/listener/inc/cred_listener.h new file mode 100644 index 0000000000000000000000000000000000000000..d4a259cb1e1da1a8008bcc9c7be986c18ba27e49 --- /dev/null +++ b/services/identity_service/listener/inc/cred_listener.h @@ -0,0 +1,39 @@ +/* + * Copyright (C) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef CRED_LISTENER_H +#define CRED_LISTENER_H + +#include "device_auth.h" + +#ifdef __cplusplus +extern "C" { +#endif + +int32_t InitCredListener(void); +void DestroyCredListener(void); + +void OnCredAdd(const char *credId, const char *credInfo); +void OnCredDelete(const char *credId, const char *credInfo); +void OnCredUpdate(const char *credId, const char *credInfo); +bool IsCredListenerSupported(void); + +int32_t AddCredListener(const char *appId, const CredChangeListener *listener); +int32_t RemoveCredListener(const char *appId); + +#ifdef __cplusplus +} +#endif +#endif diff --git a/services/identity_service/listener/src/cred_listener.c b/services/identity_service/listener/src/cred_listener.c new file mode 100644 index 0000000000000000000000000000000000000000..f809eda86f313044fae342825d9f14127d50394a --- /dev/null +++ b/services/identity_service/listener/src/cred_listener.c @@ -0,0 +1,236 @@ +/* + * Copyright (C) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "cred_listener.h" +#include "common_defs.h" +#include "device_auth_defines.h" +#include "hc_log.h" +#include "hc_mutex.h" +#include "hc_types.h" +#include "hc_vector.h" +#include "securec.h" + +typedef struct { + char *appId; + CredChangeListener *listener; +} CredListenerEntry; + +DECLARE_HC_VECTOR(CredListenerEntryVec, CredListenerEntry); +IMPLEMENT_HC_VECTOR(CredListenerEntryVec, CredListenerEntry, 1); +static CredListenerEntryVec g_credListenerVec; +static HcMutex *g_credListenerMutex = NULL; + +void OnCredAdd(const char *credId, const char *credInfo) +{ + if (credId == NULL) { + LOGE("[CredListener]: The credId is NULL!"); + return; + } + if (credInfo == NULL) { + credInfo = ""; + } + uint32_t index; + CredListenerEntry *entry = NULL; + (void)LockHcMutex(g_credListenerMutex); + FOR_EACH_HC_VECTOR(g_credListenerVec, index, entry) { + if (entry != NULL && entry->listener != NULL && entry->listener->onCredAdd != NULL) { + LOGI("[CredListener]: OnCredAdd! [AppId]: %s", entry->appId); + entry->listener->onCredAdd(credId, credInfo); + } + } + UnlockHcMutex(g_credListenerMutex); +} + +void OnCredDelete(const char *credId, const char *credInfo) +{ + if (credId == NULL) { + LOGE("[CredListener]: The credId is NULL!"); + return; + } + if (credInfo == NULL) { + credInfo = ""; + } + uint32_t index; + CredListenerEntry *entry = NULL; + (void)LockHcMutex(g_credListenerMutex); + FOR_EACH_HC_VECTOR(g_credListenerVec, index, entry) { + if (entry != NULL && entry->listener != NULL && entry->listener->onCredDelete != NULL) { + LOGI("[CredListener]: OnCredDelete! [AppId]: %s", entry->appId); + entry->listener->onCredDelete(credId, credInfo); + } + } + UnlockHcMutex(g_credListenerMutex); +} + +void OnCredUpdate(const char *credId, const char *credInfo) +{ + if (credId == NULL) { + LOGE("[CredListener]: The credId is NULL!"); + return; + } + if (credInfo == NULL) { + credInfo = ""; + } + uint32_t index; + CredListenerEntry *entry = NULL; + (void)LockHcMutex(g_credListenerMutex); + FOR_EACH_HC_VECTOR(g_credListenerVec, index, entry) { + if (entry != NULL && entry->listener != NULL && entry->listener->onCredUpdate != NULL) { + LOGI("[CredListener]: OnCredUpdate! [AppId]: %s", entry->appId); + entry->listener->onCredUpdate(credId, credInfo); + } + } + UnlockHcMutex(g_credListenerMutex); +} +static int32_t UpdateListenerIfExist(const char *appId, const CredChangeListener *listener) +{ + uint32_t index; + (void)LockHcMutex(g_credListenerMutex); + CredListenerEntry *entry = NULL; + FOR_EACH_HC_VECTOR(g_credListenerVec, index, entry) { + if (strcmp(entry->appId, appId) == 0) { + if (memcpy_s(entry->listener, sizeof(CredChangeListener), + listener, sizeof(CredChangeListener)) != IS_SUCCESS) { + UnlockHcMutex(g_credListenerMutex); + LOGE("[CredListener]: Failed to copy listener!"); + return IS_ERR_MEMORY_COPY; + } + UnlockHcMutex(g_credListenerMutex); + LOGI("[CredListener]: Successfully updated a listener. [AppId]: %s", appId); + return IS_SUCCESS; + } + } + UnlockHcMutex(g_credListenerMutex); + return IS_ERR_LISTENER_NOT_EXIST; +} + +static int32_t AddListenerIfNotExist(const char *appId, const CredChangeListener *listener) +{ + uint32_t appIdLen = HcStrlen(appId) + 1; + char *copyAppId = (char *)HcMalloc(appIdLen, 0); + if (copyAppId == NULL) { + LOGE("[CredListener]: Failed to allocate copyAppId memory!"); + return IS_ERR_ALLOC_MEMORY; + } + if (strcpy_s(copyAppId, appIdLen, appId) != IS_SUCCESS) { + LOGE("[CredListener]: Failed to copy appId!"); + HcFree(copyAppId); + return IS_ERR_MEMORY_COPY; + } + CredChangeListener *copyListener = (CredChangeListener *)HcMalloc(sizeof(CredChangeListener), 0); + if (copyListener == NULL) { + LOGE("[CredListener]: Failed to allocate saveCallback memory!"); + HcFree(copyAppId); + return IS_ERR_ALLOC_MEMORY; + } + if (memcpy_s(copyListener, sizeof(CredChangeListener), + listener, sizeof(CredChangeListener)) != IS_SUCCESS) { + LOGE("[CredListener]: Failed to copy listener!"); + HcFree(copyAppId); + HcFree(copyListener); + return IS_ERR_MEMORY_COPY; + } + CredListenerEntry entry; + entry.appId = copyAppId; + entry.listener = copyListener; + (void)LockHcMutex(g_credListenerMutex); + if (g_credListenerVec.pushBack(&g_credListenerVec, &entry) == NULL) { + HcFree(copyAppId); + HcFree(copyListener); + UnlockHcMutex(g_credListenerMutex); + return IS_ERR_MEMORY_COPY; + } + UnlockHcMutex(g_credListenerMutex); + LOGI("[CredListener]: Successfully added a listener. [AppId]: %s", appId); + return IS_SUCCESS; +} + +bool IsCredListenerSupported(void) +{ + return true; +} + +int32_t InitCredListener(void) +{ + if (g_credListenerMutex == NULL) { + g_credListenerMutex = (HcMutex *)HcMalloc(sizeof(HcMutex), 0); + if (g_credListenerMutex == NULL) { + LOGE("[CredListener]: Failed to allocate cred listener mutex memory!"); + return IS_ERR_ALLOC_MEMORY; + } + if (InitHcMutex(g_credListenerMutex, false) != IS_SUCCESS) { + LOGE("[CredListener]: Init mutex failed"); + HcFree(g_credListenerMutex); + g_credListenerMutex = NULL; + return IS_ERR_INIT_FAILED; + } + } + g_credListenerVec = CREATE_HC_VECTOR(CredListenerEntryVec); + LOGI("[CredListener]: Init cred listener module successfully!"); + return IS_SUCCESS; +} + +void DestroyCredListener(void) +{ + (void)LockHcMutex(g_credListenerMutex); + uint32_t index; + CredListenerEntry *entry = NULL; + FOR_EACH_HC_VECTOR(g_credListenerVec, index, entry) { + if (entry == NULL) { + continue; + } + HcFree(entry->appId); + HcFree(entry->listener); + } + DESTROY_HC_VECTOR(CredListenerEntryVec, &g_credListenerVec); + UnlockHcMutex(g_credListenerMutex); + DestroyHcMutex(g_credListenerMutex); + HcFree(g_credListenerMutex); + g_credListenerMutex = NULL; +} + +int32_t AddCredListener(const char *appId, const CredChangeListener *listener) +{ + if ((appId == NULL) || (listener == NULL)) { + LOGE("[CredListener]: The input appId or listener is NULL!"); + return IS_ERR_INVALID_PARAMS; + } + if (UpdateListenerIfExist(appId, listener) == IS_SUCCESS) { + return IS_SUCCESS; + } + return AddListenerIfNotExist(appId, listener); +} + +int32_t RemoveCredListener(const char *appId) +{ + if (appId == NULL) { + LOGE("[CredListener]: The input appId is NULL!"); + return IS_ERR_INVALID_PARAMS; + } + uint32_t index; + CredListenerEntry *entry = NULL; + FOR_EACH_HC_VECTOR(g_credListenerVec, index, entry) { + if (entry != NULL && strcmp(entry->appId, appId) == 0) { + HcFree(entry->appId); + HcFree(entry->listener); + CredListenerEntry tempEntry; + HC_VECTOR_POPELEMENT(&g_credListenerVec, &tempEntry, index); + LOGI("[CredListener]: Successfully removed a cred listener. [AppId]: %s", appId); + return IS_SUCCESS; + } + } + LOGI("[CredListener]: The cred listener does not exist! [AppId]: %s", appId); + return IS_SUCCESS; +} diff --git a/services/identity_service/src/identity_operation.c b/services/identity_service/src/identity_operation.c new file mode 100644 index 0000000000000000000000000000000000000000..94f3988c5224fd54b7a7c830f99dcdb433061257 --- /dev/null +++ b/services/identity_service/src/identity_operation.c @@ -0,0 +1,895 @@ +/* + * Copyright (C) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#include "identity_operation.h" + +#include "alg_defs.h" +#include "alg_loader.h" +#include "clib_error.h" +#include "cred_listener.h" +#include "device_auth.h" +#include "device_auth_defines.h" +#include "hal_error.h" +#include "hc_log.h" +#include "hc_time.h" + +#ifdef DEV_AUTH_PERMISSION_ENABLE +#include "permission_adapter.h" +#endif + +int32_t GetCredentialById(int32_t osAccountId, const char *credId, Credential **returnEntry) +{ + if (credId == NULL) { + LOGE("The input credId is NULL!"); + return IS_ERR_INVALID_PARAMS; + } + uint32_t index; + CredentialVec credentialVec = CreateCredentialVec(); + QueryCredentialParams params = InitQueryCredentialParams(); + params.credId = credId; + int32_t ret = QueryCredentials(osAccountId, ¶ms, &credentialVec); + if (ret != IS_SUCCESS) { + LOGE("Failed to query credentials!"); + ClearCredentialVec(&credentialVec); + return ret; + } + Credential **credential = NULL; + FOR_EACH_HC_VECTOR(credentialVec, index, credential) { + *returnEntry = DeepCopyCredential(*credential); + ClearCredentialVec(&credentialVec); + if (*returnEntry == NULL) { + LOGE("Failed to copy credential!"); + return IS_ERR_ALLOC_MEMORY; + } + return IS_SUCCESS; + } + ClearCredentialVec(&credentialVec); + LOGI("No credential found!"); + return IS_ERR_LOCAL_CRED_NOT_EXIST; +} + +static int32_t int64ToString(int64_t num, char **result) +{ + const int bufferSize = MAX_INT64_SIZE + 1; + *result = (char *)HcMalloc(bufferSize, 0); + if (*result == NULL) { + return IS_ERR_ALLOC_MEMORY; + } + if (sprintf_s(*result, bufferSize, "%" PRId64, num) < 0) { + HcFree(*result); + return IS_ERR_CONVERT_FAILED; + } + return IS_SUCCESS; +} + +static int32_t CombineBaseCredId(const char *credentialOwner, const char *deviceId, char **baseCredIdStr) +{ + if (credentialOwner == NULL || deviceId == NULL) { + LOGE("Invalid input parameters!"); + return IS_ERR_INVALID_PARAMS; + } + char *timeStr = NULL; + int32_t ret = int64ToString(HcGetCurTimeInMillis(), &timeStr); + if (ret != IS_SUCCESS) { + LOGE("Failed to convert time to string!"); + return ret; + } + size_t totalLength = HcStrlen(credentialOwner) + HcStrlen(deviceId) + HcStrlen(timeStr) + 1; + *baseCredIdStr = (char *)HcMalloc(totalLength, 0); + if (*baseCredIdStr == NULL) { + LOGE("Failed to allocate memory for baseCredIdStr!"); + HcFree(timeStr); + HcFree(*baseCredIdStr); + return IS_ERR_ALLOC_MEMORY; + } + + if (strcpy_s(*baseCredIdStr, totalLength, credentialOwner) != EOK) { + LOGE("Failed to copy credentialOwner to baseCredIdStr!"); + HcFree(timeStr); + HcFree(*baseCredIdStr); + return IS_ERR_CONVERT_FAILED; + } + if (strcat_s(*baseCredIdStr, totalLength, deviceId) != EOK) { + LOGE("Failed to concatenate deviceId to baseCredIdStr!"); + HcFree(timeStr); + HcFree(*baseCredIdStr); + return IS_ERR_CONVERT_FAILED; + } + if (strcat_s(*baseCredIdStr, totalLength, timeStr) != EOK) { + LOGE("Failed to concatenate timeStr to baseCredIdStr!"); + HcFree(timeStr); + HcFree(*baseCredIdStr); + return IS_ERR_CONVERT_FAILED; + } + HcFree(timeStr); + + return IS_SUCCESS; +} + +static int32_t Uint8BuffToString(Uint8Buff *byte, char **str) +{ + uint32_t strLen = byte->length * BYTE_TO_HEX_OPER_LENGTH + 1; + *str = (char *)HcMalloc(strLen, 0); + if (*str == NULL) { + LOGE("Failed to malloc str"); + return IS_ERR_ALLOC_MEMORY; + } + int32_t ret = ByteToHexString(byte->val, byte->length, *str, strLen); + if (ret != IS_SUCCESS) { + LOGE("Failed to convert byte to hex string"); + HcFree(*str); + return ret; + } + return IS_SUCCESS; +} + +static int32_t GenerateCredIdInner(const char *credentialOwner, const char *deviceId, + Uint8Buff *credIdByte, char **credIdStr) +{ + char *baseCredIdStr = NULL; + int32_t ret = CombineBaseCredId(credentialOwner, deviceId, &baseCredIdStr); + if (ret != IS_SUCCESS) { + LOGE("Failed to combine credId!"); + return ret; + } + + Uint8Buff baseCredIdBuff = { (uint8_t *)baseCredIdStr, (uint32_t)HcStrlen(baseCredIdStr) }; + ret = GetLoaderInstance()->sha256(&baseCredIdBuff, credIdByte); + HcFree(baseCredIdStr); + if (ret == HAL_ERR_HUKS) { + LOGE("Huks sha256 failed"); + return IS_ERR_HUKS_SHA256_FAILED; + } + if (ret != IS_SUCCESS) { + LOGE("Failed to sha256 credId"); + return ret; + } + ret = Uint8BuffToString(credIdByte, credIdStr); + if (ret != IS_SUCCESS) { + LOGE("Failed to convert credIdByte to credIdStr, ret = %d", ret); + return ret; + } + + return IS_SUCCESS; +} + +int32_t GenerateCredId(Credential *credential, int32_t osAccountId, Uint8Buff *credIdByte, char **credIdStr) +{ + const char *credOwner = StringGet(&credential->credOwner); + const char *deviceId = StringGet(&credential->deviceId); + int32_t ret = GenerateCredIdInner(credOwner, deviceId, credIdByte, credIdStr); + if (ret != IS_SUCCESS) { + LOGE("Failed to generate credId!"); + return ret; + } + + Credential *existedCredential = NULL; + ret = GetCredentialById(osAccountId, *credIdStr, &existedCredential); + DestroyCredential(existedCredential); + + if (ret == IS_SUCCESS) { + LOGW("CredId already exists, regenerate credId"); + HcFree(*credIdStr); + ret = GenerateCredIdInner(credOwner, deviceId, credIdByte, credIdStr); + if (ret != IS_SUCCESS) { + LOGE("Failed to regenerate credId!"); + return ret; + } + } + + if (!StringSetPointer(&credential->credId, *credIdStr)) { + LOGE("Failed to set credId"); + HcFree(*credIdStr); + return IS_ERR_MEMORY_COPY; + } + LOGI("Generate credId success"); + return IS_SUCCESS; +} + +static int32_t CheckOutMaxCredSize(int32_t osAccountId, const char *credOwner) +{ + QueryCredentialParams queryParams = InitQueryCredentialParams(); + queryParams.credOwner = credOwner; + CredentialVec credentialVec = CreateCredentialVec(); + int32_t ret = QueryCredentials(osAccountId, &queryParams, &credentialVec); + if (ret != IS_SUCCESS) { + LOGE("Failed to query credentials"); + ClearCredentialVec(&credentialVec); + return ret; + } + if (credentialVec.size(&credentialVec) > MAX_CRED_SIZE) { + LOGE("The number of credentials exceeds the maximum limit"); + ClearCredentialVec(&credentialVec); + return IS_ERR_BEYOND_LIMIT; + } + ClearCredentialVec(&credentialVec); + return IS_SUCCESS; +} + +static void GetAlgoFromCred(uint8_t algorithmType, Algorithm *algo) +{ + switch (algorithmType) { + case ALGO_TYPE_P256: + *algo = P256; + break; + case ALGO_TYPE_ED25519: + *algo = ED25519; + break; + default: + *algo = AES; + break; + } +} + +int32_t AddKeyValueToHuks(Uint8Buff credIdByte, Credential *credential, int32_t osAccountId, uint8_t method, + Uint8Buff *keyValue) +{ + KeyParams keyParams = { { credIdByte.val, credIdByte.length, true }, false, osAccountId }; + int32_t authId = 0; + Uint8Buff authIdBuff = { (uint8_t *)&authId, sizeof(int32_t) }; + ExtraInfo exInfo = { authIdBuff, DEFAULT_EX_INFO_VAL, DEFAULT_EX_INFO_VAL }; + int32_t ret; + Algorithm algo; + GetAlgoFromCred(credential->algorithmType, &algo); + if (method == METHOD_GENERATE) { + uint32_t keyLen = (credential->algorithmType == ALGO_TYPE_AES_128) ? AES_128_KEY_LEN : SELE_ECC_KEY_LEN; + KeyPurpose purpose = (credential->algorithmType == ALGO_TYPE_ED25519) ? + KEY_PURPOSE_SIGN_VERIFY : KEY_PURPOSE_KEY_AGREE; + ret = GetLoaderInstance()->generateKeyPairWithStorage(&keyParams, keyLen, algo, purpose, &exInfo); + if (ret == HAL_ERR_HUKS) { + LOGE("Huks generateKeyPair failed!"); + return IS_ERR_HUKS_GENERATE_KEY_FAILED; + } + if (ret != IS_SUCCESS) { + LOGE("Failed to generate key pair!"); + return ret; + } + LOGI("Generate key pair success!"); + } + if (method == METHOD_IMPORT) { + ret = GetLoaderInstance()->importPublicKey(&keyParams, keyValue, algo, &exInfo); + if (ret == HAL_ERR_HUKS) { + LOGE("Huks import key failed!"); + return IS_ERR_HUKS_IMPORT_KEY_FAILED; + } + if (ret != IS_SUCCESS) { + LOGE("Failed to import key pair!"); + return ret; + } + LOGI("Import key pair success!"); + } + return IS_SUCCESS; +} + +int32_t CheckCredIdExistInHuks(int32_t osAccountId, const char *credId, Uint8Buff *credIdHashBuff) +{ + int32_t ret = HexStringToByte(credId, credIdHashBuff->val, credIdHashBuff->length); + if (ret != IS_SUCCESS) { + LOGE("Failed to convert credId to byte"); + return ret; + } + + return GetLoaderInstance()->checkKeyExist(credIdHashBuff, false, osAccountId); +} + +int32_t AddCredAndSaveDb(int32_t osAccountId, Credential *credential) +{ + int32_t ret = AddCredToDb(osAccountId, credential); + if (ret != IS_SUCCESS) { + LOGE("Failed to add credential to database"); + return ret; + } + ret = SaveOsAccountCredDb(osAccountId); + if (ret != IS_SUCCESS) { + LOGE("Failed to save CredDb, ret: %d", ret); + return ret; + } + return IS_SUCCESS; +} + + +static bool IsValueInArray(uint8_t value, uint8_t *array, uint32_t length) +{ + for (uint32_t i = 0; i < length; i++) { + if (array[i] == value) { + return true; + } + } + return false; +} + +static int32_t SetAccListFromArray(Credential *credential, CJson *accountList) +{ + int32_t accountListNum = GetItemNum(accountList); + for (int32_t i = 0; i < accountListNum; i++) { + CJson *item = GetItemFromArray(accountList, i); + if (item == NULL) { + LOGE("item is null."); + return IS_ERR_JSON_GET; + } + const char *account = GetStringValue(item); + if (account == NULL) { + LOGE("account is null."); + return IS_ERR_JSON_GET; + } + HcString strAcc = CreateString(); + if (!StringSetPointer(&strAcc, account)) { + LOGE("Failed to set strAcc!"); + DeleteString(&strAcc); + return IS_ERR_MEMORY_COPY; + } + if (credential->authorizedAccountList.pushBackT(&credential->authorizedAccountList, strAcc) == NULL) { + LOGE("Failed to push strAcc!"); + DeleteString(&strAcc); + return IS_ERR_MEMORY_COPY; + } + } + return IS_SUCCESS; +} + +static int32_t SetMethodFromJson(CJson *json, uint8_t *method) +{ + if (GetUint8FromJson(json, FIELD_METHOD, method) != IS_SUCCESS) { + LOGE("Failed to get method from credReqParam"); + return IS_ERR_JSON_GET; + } + + uint8_t methodRange[] = { METHOD_GENERATE, METHOD_IMPORT }; + uint32_t length = sizeof(methodRange) / sizeof(methodRange[0]); + if (!IsValueInArray(*method, methodRange, length)) { + LOGE("method is invalid."); + return IS_ERR_INVALID_PARAMS; + } + return IS_SUCCESS; +} + +static int32_t SetCredType(Credential *credential, CJson *json) +{ + if (GetUint8FromJson(json, FIELD_CRED_TYPE, &credential->credType) != IS_SUCCESS) { + LOGE("Failed to get credential type from credReqParam"); + return IS_ERR_JSON_GET; + } + + uint8_t credTypeRange[] = { ACCOUNTT_RELATED, ACCOUNTT_UNRELATED }; + uint32_t length = sizeof(credTypeRange) / sizeof(credTypeRange[0]); + if (!IsValueInArray(credential->credType, credTypeRange, length)) { + LOGE("credential type is invalid."); + return IS_ERR_INVALID_PARAMS; + } + return IS_SUCCESS; +} + +static int32_t SetKeyFormat(Credential *credential, CJson *json, uint8_t method) +{ + if (GetUint8FromJson(json, FIELD_KEY_FORMAT, &credential->keyFormat) != IS_SUCCESS) { + LOGE("Failed to get key format from credReqParam"); + return IS_ERR_JSON_GET; + } + uint8_t keyFormatRange[] = { SYMMETRIC_KEY, ASYMMETRIC_PUB_KEY, ASYMMETRIC_KEY, X509_CERT}; + uint32_t length = sizeof(keyFormatRange) / sizeof(keyFormatRange[0]); + if (!IsValueInArray(credential->keyFormat, keyFormatRange, length)) { + LOGE("key format is invalid."); + return IS_ERR_INVALID_PARAMS; + } + if (credential->keyFormat == SYMMETRIC_KEY && method != METHOD_IMPORT) { + LOGE("Symmetric key is only supported for import"); + return IS_ERR_INVALID_PARAMS; + } + if (credential->keyFormat == ASYMMETRIC_PUB_KEY && method != METHOD_IMPORT) { + LOGE("Asymmetric public key is only supported for import"); + return IS_ERR_INVALID_PARAMS; + } + if (credential->keyFormat == ASYMMETRIC_KEY && method != METHOD_GENERATE) { + LOGE("Asymmetric key is only supported for generate"); + return IS_ERR_INVALID_PARAMS; + } + return IS_SUCCESS; +} + +static int32_t SetAuthorizedScope(Credential *credential, CJson *json) +{ + if (GetUint8FromJson(json, FIELD_AUTHORIZED_SCOPE, &credential->authorizedScope) != IS_SUCCESS) { + LOGE("Failed to get authorizedScope from credReqParam"); + return IS_ERR_JSON_GET; + } + uint8_t scopeRange[] = { SCOPE_DEVICE, SCOPE_USER, SCOPE_APP }; + uint32_t length = sizeof(scopeRange) / sizeof(scopeRange[0]); + if (!IsValueInArray(credential->authorizedScope, scopeRange, length)) { + LOGE("Invalid authorizedScope"); + return IS_ERR_INVALID_PARAMS; + } + return IS_SUCCESS; +} + +static int32_t SetAlgorithmType(Credential *credential, CJson *json) +{ + if (GetUint8FromJson(json, FIELD_ALGORITHM_TYPE, &credential->algorithmType) != IS_SUCCESS) { + LOGE("Failed to get algorithm type from credReqParam"); + return IS_ERR_JSON_GET; + } + uint8_t algorithmTypeRange[] = { ALGO_TYPE_P256, ALGO_TYPE_ED25519 }; + uint32_t length = sizeof(algorithmTypeRange) / sizeof(algorithmTypeRange[0]); + if (!IsValueInArray(credential->algorithmType, algorithmTypeRange, length)) { + LOGE("Invalid algorithm type"); + return IS_ERR_INVALID_PARAMS; + } + return IS_SUCCESS; +} + +static int32_t SetSubject(Credential *credential, CJson *json) +{ + if (GetUint8FromJson(json, FIELD_SUBJECT, &credential->subject) != IS_SUCCESS) { + LOGE("Failed to get subject from credReqParam"); + return IS_ERR_JSON_GET; + } + uint8_t subjectRange[] = { SELF_DEVICE, OTHER_DEVICE }; + uint32_t length = sizeof(subjectRange) / sizeof(subjectRange[0]); + if (!IsValueInArray(credential->subject, subjectRange, length)) { + LOGE("Invalid subject"); + return IS_ERR_INVALID_PARAMS; + } + return IS_SUCCESS; +} + +static int32_t SetIssuer(Credential *credential, CJson *json) +{ + if (GetUint8FromJson(json, FIELD_ISSUER, &credential->issuer) != IS_SUCCESS) { + LOGW("Failed to get issuer from credReqParam"); + } + if (credential->credType == ACCOUNTT_UNRELATED) { + return IS_SUCCESS; + } + uint8_t issuerRange[] = { SYSTEM_ACCOUNT, APP_ACCOUNT, DOMANIN_ACCOUNT }; + uint32_t length = sizeof(issuerRange) / sizeof(issuerRange[0]); + if (credential->issuer == DEFAULT_VAL || !IsValueInArray(credential->issuer, issuerRange, length)) { + LOGE("Invalid issuer"); + return IS_ERR_INVALID_PARAMS; + } + return IS_SUCCESS; +} + +static int32_t SetDeviceId(Credential *credential, CJson *json) +{ + const char *deviceId = GetStringFromJson(json, FIELD_DEVICE_ID); + if (deviceId == NULL || strcmp(deviceId, "") == 0) { + LOGE("Failed to get deviceId from credReqParam"); + return IS_ERR_JSON_GET; + } + if (!StringSetPointer(&credential->deviceId, deviceId)) { + LOGE("Failed to set deviceId"); + return IS_ERR_MEMORY_COPY; + } + return IS_SUCCESS; +} + +static int32_t SetCredOwner(Credential *credential, CJson *json, int32_t osAccountId) +{ + const char *credOwner = GetStringFromJson(json, FIELD_CRED_OWNER); + if (credOwner == NULL || strcmp(credOwner, "") == 0) { + LOGE("Failed to get credOwner from credReqParam"); + return IS_ERR_JSON_GET; + } + if (!StringSetPointer(&credential->credOwner, credOwner)) { + LOGE("Failed to set credOwner"); + return IS_ERR_MEMORY_COPY; + } + return IS_SUCCESS; +} + +static int32_t SetProofType(Credential *credential, CJson *json) +{ + if (GetUint8FromJson(json, FIELD_PROOF_TYPE, &credential->proofType) != IS_SUCCESS) { + LOGE("Failed to get proofType from credReqParam"); + return IS_ERR_JSON_GET; + } + uint8_t proofTypeRange[] = { PROOF_TYPE_PSK, PROOF_TYPE_PKI }; + uint32_t length = sizeof(proofTypeRange) / sizeof(proofTypeRange[0]); + if (!IsValueInArray(credential->proofType, proofTypeRange, length)) { + LOGE("Invalid proofType"); + return IS_ERR_INVALID_PARAMS; + } + return IS_SUCCESS; +} + +static int32_t SetUserId(Credential *credential, CJson *json) +{ + const char *userId = GetStringFromJson(json, FIELD_USER_ID); + if (credential->credType == ACCOUNTT_RELATED && (userId == NULL || strcmp(userId, "") == 0)) { + LOGE("Invalid params, when credType is account, userId is NULL"); + return IS_ERR_INVALID_PARAMS; + } + if (!StringSetPointer(&credential->userId, userId)) { + LOGW("Failed to set userId"); + } + + return IS_SUCCESS; +} + +static int32_t SetKeyValueFromJson(CJson *json, uint8_t method, Uint8Buff *keyValue) +{ + if (method == METHOD_GENERATE) { + return IS_SUCCESS; + } + const char *keyValueStr = GetStringFromJson(json, FIELD_KEY_VALUE); + if (keyValueStr == NULL || HcStrlen(keyValueStr) <= 0) { + LOGE("Invalid params, when method is imoprt, keyValue is NULL"); + return IS_ERR_INVALID_PARAMS; + } + uint32_t keyValueLen = HcStrlen(keyValueStr) / BYTE_TO_HEX_OPER_LENGTH; + keyValue->length = keyValueLen; + keyValue->val = (uint8_t *)HcMalloc(keyValueLen, 0); + if (keyValue->val == NULL) { + LOGE("Failed to malloc memory for keyValue"); + return IS_ERR_ALLOC_MEMORY; + } + if (GetByteFromJson(json, FIELD_KEY_VALUE, keyValue->val, keyValue->length) != IS_SUCCESS) { + LOGE("set keyValue fail."); + HcFree(keyValue->val); + return IS_ERR_JSON_GET; + } + return IS_SUCCESS; +} + +static int32_t SetPeerUserSpaceId(Credential *credential, CJson *json, uint8_t method) +{ + const char *peerUserSpaceId = GetStringFromJson(json, FIELD_PEER_USER_SPACE_ID); + if (credential->credType == ACCOUNTT_UNRELATED && method == METHOD_IMPORT && + (peerUserSpaceId == NULL || strcmp(peerUserSpaceId, "") == 0)) { + LOGE("Invalid params, when credType is not account and method is import, peer osaccount id is NULL"); + return IS_ERR_INVALID_PARAMS; + } + if (peerUserSpaceId == NULL) { + LOGI("peerUserSpaceId could be NULL when spcical case"); + return IS_SUCCESS; + } + if (!StringSetPointer(&credential->peerUserSpaceId, peerUserSpaceId)) { + LOGW("Failed to set peerUserSpaceId"); + } + return IS_SUCCESS; +} + +static int32_t SetAccList(Credential *credential, CJson *json) +{ + CJson *accountList = GetObjFromJson(json, FIELD_AUTHORIZED_ACCOUNT_LIST); + + if (accountList == NULL) { + LOGW("Failed to get authorized account list from credReqParam"); + return IS_SUCCESS; + } + + int32_t ret = SetAccListFromArray(credential, accountList); + if (ret != IS_SUCCESS) { + LOGE("Failed to set authorized account list from credReqParam"); + return ret; + } + return IS_SUCCESS; +} + +static int32_t SetExtendInfo(Credential *credential, CJson *json) +{ + const char *extendInfo = GetStringFromJson(json, FIELD_EXTEND_INFO); + if (extendInfo == NULL || strcmp(extendInfo, "") == 0) { + LOGW("Failed to get extendInfo from credReqParam"); + } + if (!StringSetPointer(&credential->extendInfo, extendInfo)) { + LOGW("Failed to set extendInfo!"); + } + return IS_SUCCESS; +} + +static int32_t SetRequiredField(Credential *credential, CJson *json, int32_t osAccountId, uint8_t *method) +{ + int32_t ret = SetMethodFromJson(json, method); + if (ret != IS_SUCCESS) { + return ret; + } + + ret = SetCredType(credential, json); + if (ret != IS_SUCCESS) { + return ret; + } + + ret = SetKeyFormat(credential, json, *method); + if (ret != IS_SUCCESS) { + return ret; + } + + ret = SetAuthorizedScope(credential, json); + if (ret != IS_SUCCESS) { + return ret; + } + + ret = SetAlgorithmType(credential, json); + if (ret != IS_SUCCESS) { + return ret; + } + + ret = SetSubject(credential, json); + if (ret != IS_SUCCESS) { + return ret; + } + + ret = SetDeviceId(credential, json); + if (ret != IS_SUCCESS) { + return ret; + } + + ret = SetCredOwner(credential, json, osAccountId); + if (ret != HC_SUCCESS) { + return ret; + } + + ret = SetProofType(credential, json); + if (ret != IS_SUCCESS) { + return ret; + } +#ifdef DEV_AUTH_PERMISSION_ENABLE + credential->ownerUid = GetCallingUid(); + LOGI("UID: %d", credential->ownerUid); +#endif + return IS_SUCCESS; +} + +static int32_t SetSpecialRequiredField(Credential *credential, CJson *json, uint8_t *method, Uint8Buff *keyValue) +{ + int32_t ret = SetUserId(credential, json); + if (ret != IS_SUCCESS) { + return ret; + } + + ret = SetIssuer(credential, json); + if (ret != IS_SUCCESS) { + return ret; + } + + ret = SetKeyValueFromJson(json, *method, keyValue); + if (ret != IS_SUCCESS) { + return ret; + } + + ret = SetPeerUserSpaceId(credential, json, *method); + if (ret != IS_SUCCESS) { + return ret; + } + return IS_SUCCESS; +} + +static int32_t SetOptionalField(Credential *credential, CJson *json) +{ + int32_t ret = SetAccList(credential, json); + if (ret != IS_SUCCESS) { + return ret; + } + + ret = SetExtendInfo(credential, json); + if (ret != IS_SUCCESS) { + return ret; + } + + return IS_SUCCESS; +} + +int32_t CheckAndSetCredInfo(Credential *credential, + CJson *json, int32_t osAccountId, uint8_t *method, Uint8Buff *keyValue) +{ + int32_t ret = SetRequiredField(credential, json, osAccountId, method); + if (ret != IS_SUCCESS) { + return ret; + } + + ret = SetSpecialRequiredField(credential, json, method, keyValue); + if (ret != IS_SUCCESS) { + return ret; + } + + ret = SetOptionalField(credential, json); + if (ret != IS_SUCCESS) { + return ret; + } + + ret = CheckOutMaxCredSize(osAccountId, StringGet(&credential->credOwner)); + if (ret != IS_SUCCESS) { + return ret; + } + + return IS_SUCCESS; +} + +int32_t SetQueryParamsFromJson(QueryCredentialParams *queryParams, CJson *json) +{ + queryParams->credId = GetStringFromJson(json, FIELD_CRED_ID); + + queryParams->deviceId = GetStringFromJson(json, FIELD_DEVICE_ID); + + queryParams->peerUserSpaceId = GetStringFromJson(json, FIELD_PEER_USER_SPACE_ID); + + if (GetUint8FromJson(json, FIELD_SUBJECT, &queryParams->subject) != IS_SUCCESS) { + LOGW("Failed to set query params: subject"); + } + + queryParams->userId = GetStringFromJson(json, FIELD_USER_ID); + + if (GetUint8FromJson(json, FIELD_ISSUER, &queryParams->issuer) != IS_SUCCESS) { + LOGW("Failed to set query params: issuer"); + } + + if (GetUint8FromJson(json, FIELD_CRED_TYPE, &queryParams->credType) != IS_SUCCESS) { + LOGW("Failed to set query params: credType"); + } + + if (GetUint8FromJson(json, FIELD_KEY_FORMAT, &queryParams->keyFormat) != IS_SUCCESS) { + LOGW("Failed to set query params: keyFormat"); + } + + if (GetUint8FromJson(json, FIELD_ALGORITHM_TYPE, &queryParams->algorithmType) != IS_SUCCESS) { + LOGW("Failed to set query params: algorithmType"); + } + + if (GetUint8FromJson(json, FIELD_PROOF_TYPE, &queryParams->proofType) != IS_SUCCESS) { + LOGW("Failed to set query params: proofType"); + } + + if (GetUint8FromJson(json, FIELD_AUTHORIZED_SCOPE, &queryParams->authorizedScope) != IS_SUCCESS) { + LOGW("Failed to set query params: authorizedScope"); + } + + queryParams->credOwner = GetStringFromJson(json, FIELD_CRED_OWNER); + + return IS_SUCCESS; +} + +int32_t GetCredIdsFromCredVec(CredentialVec credentialVec, CJson *credIdJson, int32_t osAccountId) +{ + uint32_t index; + int32_t ret; + Credential **ptr; + FOR_EACH_HC_VECTOR(credentialVec, index, ptr) { + if (*ptr == NULL) { + continue; + } + Credential *credential = (Credential *)(*ptr); + const char *credId = StringGet(&credential->credId); + uint8_t credIdVal[SHA256_LEN] = {0}; + Uint8Buff credIdHashBuff = { credIdVal, SHA256_LEN }; + ret = CheckCredIdExistInHuks(osAccountId, credId, &credIdHashBuff); + if (ret == HAL_ERR_KEY_NOT_EXIST) { + LOGE("Huks key not exist!"); + DelCredById(osAccountId, credId); + continue; + } + if (ret == HAL_ERR_HUKS) { + LOGE("Failed to check key exist in huks"); + continue; + } + if (ret != IS_SUCCESS) { + LOGW("CheckKeyExist failed"); + continue; + } + + ret = AddStringToArray(credIdJson, credId); + if (ret != IS_SUCCESS) { + LOGE("Failed to add credId to json"); + return IS_ERR_JSON_ADD; + } + } + + return IS_SUCCESS; +} + +static int32_t UpdateExtendInfo(Credential *credential, const char *extendInfo) +{ + if (!StringSetPointer(&credential->extendInfo, extendInfo)) { + LOGE("Failed to update extendInfo"); + return IS_ERR_MEMORY_COPY; + } + return IS_SUCCESS; +} + +static int32_t UpdateAccountList(Credential *credential, CJson *accountList) +{ + DestroyStrVector(&credential->authorizedAccountList); + credential->authorizedAccountList = CreateStrVector(); + int32_t ret = SetAccListFromArray(credential, accountList); + if (ret != IS_SUCCESS) { + LOGE("Failed to update authorizedAccountList"); + return ret; + } + return IS_SUCCESS; +} + +int32_t UpdateInfoFromJson(Credential *credential, CJson *json) +{ + const char *extendInfo = GetStringFromJson(json, FIELD_EXTEND_INFO); + CJson *accountList = GetObjFromJson(json, FIELD_AUTHORIZED_ACCOUNT_LIST); + + if (extendInfo == NULL && accountList == NULL) { + LOGE("Failed to set update info: no valid field"); + return IS_ERR_INVALID_PARAMS; + } + + int32_t ret; + + if (extendInfo != NULL) { + ret = UpdateExtendInfo(credential, extendInfo); + if (ret != IS_SUCCESS) { + return ret; + } + } + + if (accountList != NULL) { + ret = UpdateAccountList(credential, accountList); + if (ret != IS_SUCCESS) { + return ret; + } + } + + return IS_SUCCESS; +} + +int32_t DelCredById(int32_t osAccountId, const char *credId) +{ + QueryCredentialParams delParams = InitQueryCredentialParams(); + delParams.credId = credId; + int32_t ret = DelCredential(osAccountId, &delParams); + if (ret != IS_SUCCESS) { + LOGE("Failed to delete credential, ret: %d", ret); + return ret; + } + ret = SaveOsAccountCredDb(osAccountId); + if (ret != IS_SUCCESS) { + LOGE("Failed to save CredDb, ret: %d", ret); + return ret; + } + return IS_SUCCESS; +} + +int32_t AddKeyValueToReturn(Uint8Buff keyValue, char **returnData) +{ + CJson *pubKeyJson = CreateJson(); + if (pubKeyJson == NULL) { + LOGE("Failed to create pubKeyJson"); + return IS_ERR_JSON_CREATE; + } + int32_t ret = AddByteToJson(pubKeyJson, FIELD_KEY_VALUE, keyValue.val, keyValue.length); + if (ret != IS_SUCCESS) { + LOGE("Failed to add key to json"); + FreeJson(pubKeyJson); + return IS_ERR_JSON_ADD; + } + *returnData = PackJsonToString(pubKeyJson); + FreeJson(pubKeyJson); + if (*returnData == NULL) { + LOGE("Failed to pack json to string"); + return IS_ERR_PACKAGE_JSON_TO_STRING_FAIL; + } + return IS_SUCCESS; +} + +int32_t GenerateReturnEmptyArrayStr(char **returnVec) +{ + CJson *json = CreateJsonArray(); + if (json == NULL) { + LOGE("Failed to allocate json memory!"); + return IS_ERR_JSON_CREATE; + } + *returnVec = PackJsonToString(json); + FreeJson(json); + if (*returnVec == NULL) { + LOGE("Failed to convert json to string!"); + return IS_ERR_PACKAGE_JSON_TO_STRING_FAIL; + } + return IS_SUCCESS; +} diff --git a/services/identity_service/src/identity_service.c b/services/identity_service/src/identity_service.c new file mode 100644 index 0000000000000000000000000000000000000000..7c30445c44e9b680238b20789760ce8c964af3d3 --- /dev/null +++ b/services/identity_service/src/identity_service.c @@ -0,0 +1,163 @@ +/* + * Copyright (C) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "identity_service.h" + +#include "common_defs.h" +#include "credential_data_manager.h" +#include "hc_log.h" +#include "identity_service_impl.h" +#include "os_account_adapter.h" + +int32_t AddCredential(int32_t osAccountId, const char *requestParams, char **returnData) +{ + SET_LOG_MODE(TRACE_MODE); + + if (requestParams == NULL || returnData == NULL) { + LOGE("Invalid params"); + return IS_ERR_INVALID_PARAMS; + } + + if (!IsOsAccountUnlocked(osAccountId)) { + LOGE("Os account is not unlocked!"); + return IS_ERR_OS_ACCOUNT_NOT_UNLOCKED; + } + + return AddCredentialImpl(osAccountId, requestParams, returnData); +} + +int32_t ExportCredential(int32_t osAccountId, const char *credId, char **returnData) +{ + SET_LOG_MODE(TRACE_MODE); + + if (credId == NULL || returnData == NULL) { + LOGE("Failed to export credential, invalid params"); + return IS_ERR_INVALID_PARAMS; + } + + if (!IsOsAccountUnlocked(osAccountId)) { + LOGE("Os account is not unlocked!"); + return IS_ERR_OS_ACCOUNT_NOT_UNLOCKED; + } + + return ExportCredentialImpl(osAccountId, credId, returnData); +} + +int32_t QueryCredentialByParams(int32_t osAccountId, const char *requestParams, char **returnData) +{ + SET_LOG_MODE(TRACE_MODE); + + if (requestParams == NULL || returnData == NULL) { + LOGE("Failed to query credential by params, invalid params"); + return IS_ERR_INVALID_PARAMS; + } + + if (!IsOsAccountUnlocked(osAccountId)) { + LOGE("Os account is not unlocked!"); + return IS_ERR_OS_ACCOUNT_NOT_UNLOCKED; + } + + return QueryCredentialByParamsImpl(osAccountId, requestParams, returnData); +} + +int32_t QueryCredInfoByCredId(int32_t osAccountId, const char *credId, char **returnData) +{ + SET_LOG_MODE(TRACE_MODE); + + if (credId == NULL || returnData == NULL) { + LOGE("Failed to query credential info by credId, invalid params"); + return IS_ERR_INVALID_PARAMS; + } + + if (!IsOsAccountUnlocked(osAccountId)) { + LOGE("Os account is not unlocked!"); + return IS_ERR_OS_ACCOUNT_NOT_UNLOCKED; + } + + return QueryCredInfoByCredIdImpl(osAccountId, credId, returnData); +} + +int32_t DeleteCredential(int32_t osAccountId, const char *appId, const char *credId) +{ + SET_LOG_MODE(TRACE_MODE); + + if (appId == NULL || credId == NULL) { + LOGE("Failed to delete credential, invalid params"); + return IS_ERR_INVALID_PARAMS; + } + + if (!IsOsAccountUnlocked(osAccountId)) { + LOGE("Os account is not unlocked!"); + return IS_ERR_OS_ACCOUNT_NOT_UNLOCKED; + } + + return DeleteCredentialImpl(osAccountId, appId, credId); +} + +int32_t UpdateCredInfo(int32_t osAccountId, const char *appId, const char *credId, const char *requestParams) +{ + SET_LOG_MODE(TRACE_MODE); + + if (appId == NULL || credId == NULL || requestParams == NULL) { + LOGE("Failed to update credential, invalid params"); + return IS_ERR_INVALID_PARAMS; + } + + if (!IsOsAccountUnlocked(osAccountId)) { + LOGE("Os account is not unlocked!"); + return IS_ERR_OS_ACCOUNT_NOT_UNLOCKED; + } + + return UpdateCredInfoImpl(osAccountId, appId, credId, requestParams); +} + +int32_t RegisterChangeListener(const char *appId, CredChangeListener *listener) +{ + SET_LOG_MODE(TRACE_MODE); + + return IsCredListenerSupported() ? RegCredListener(appId, listener) : HC_ERR_NOT_SUPPORT; +} + +int32_t UnregisterChangeListener(const char *appId) +{ + SET_LOG_MODE(TRACE_MODE); + + return IsCredListenerSupported() ? UnRegCredListener(appId) : HC_ERR_NOT_SUPPORT; +} + +void DestroyInfo(char **returnData) +{ + if (returnData == NULL || *returnData == NULL) { + return; + } + FreeJsonString(*returnData); + *returnData = NULL; +} + +int32_t InitIdentityService(void) +{ + if (InitCredDatabase() != HC_SUCCESS) { + return IS_ERR_SERVICE_NEED_RESTART; + } + return IsCredListenerSupported() ? InitCredListener() : HC_SUCCESS; +} + +void DestroyIdentityService(void) +{ + if (IsCredListenerSupported()) { + DestroyCredListener(); + } + DestroyCredDatabase(); +} \ No newline at end of file diff --git a/services/identity_service/src/identity_service_impl.c b/services/identity_service/src/identity_service_impl.c new file mode 100644 index 0000000000000000000000000000000000000000..e0bfd9664d1c72c8d0e8b4ffbebfa60e62b299f6 --- /dev/null +++ b/services/identity_service/src/identity_service_impl.c @@ -0,0 +1,320 @@ +/* + * Copyright (C) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "identity_service.h" + +#include "alg_defs.h" +#include "alg_loader.h" +#include "clib_error.h" +#include "common_defs.h" +#include "credential_data_manager.h" +#include "cred_listener.h" +#include "device_auth.h" +#include "device_auth_defines.h" +#include "hal_error.h" +#include "hc_log.h" + +#include "identity_operation.h" + +int32_t AddCredentialImpl(int32_t osAccountId, const char *requestParams, char **returnData) +{ + CJson *reqJson = CreateJsonFromString(requestParams); + if (reqJson == NULL) { + LOGE("Failed to create reqJson from string!"); + return IS_ERR_JSON_CREATE; + } + Credential *credential = CreateCredential(); + if (credential == NULL) { + LOGE("Failed to malloc Credential"); + FreeJson(reqJson); + return IS_ERR_ALLOC_MEMORY; + } + uint8_t method = DEFAULT_VAL; + Uint8Buff keyValue = { NULL, 0 }; + char *credIdStr = NULL; + int32_t ret = CheckAndSetCredInfo(credential, reqJson, osAccountId, &method, &keyValue); + FreeJson(reqJson); + if (ret != IS_SUCCESS) { + DestroyCredential(credential); + return ret; + } + uint8_t credIdByteVal[SHA256_LEN] = { 0 }; + Uint8Buff credIdByte = { credIdByteVal, sizeof(credIdByteVal) }; + if ((ret = GenerateCredId(credential, osAccountId, &credIdByte, &credIdStr)) != IS_SUCCESS) { + HcFree(keyValue.val); + DestroyCredential(credential); + return ret; + } + if ((ret = AddKeyValueToHuks(credIdByte, credential, osAccountId, method, &keyValue)) != IS_SUCCESS) { + HcFree(keyValue.val); + HcFree(credIdStr); + DestroyCredential(credential); + return ret; + } + HcFree(keyValue.val); + if ((ret = AddCredAndSaveDb(osAccountId, credential)) != IS_SUCCESS) { + HcFree(credIdStr); + DestroyCredential(credential); + if (GetLoaderInstance()->deleteKey(&credIdByte, false, osAccountId) != IS_SUCCESS) { + LOGE("Failed to delete key from HUKS"); + } + return ret; + } + DestroyCredential(credential); + if (DeepCopyString(credIdStr, returnData) != EOK) { + LOGE("Failed to return credId"); + HcFree(credIdStr); + return IS_ERR_MEMORY_COPY; + } + HcFree(credIdStr); + return IS_SUCCESS; +} + +int32_t ExportCredentialImpl(int32_t osAccountId, const char *credId, char **returnData) +{ + Credential *credential = NULL; + int32_t ret = GetCredentialById(osAccountId, credId, &credential); + if (ret != IS_SUCCESS) { + LOGE("Failed to get credential by credId, ret = %d", ret); + return ret; + } + DestroyCredential(credential); + + uint8_t credIdVal[SHA256_LEN] = { 0 }; + Uint8Buff credIdHashBuff = { credIdVal, SHA256_LEN }; + ret = CheckCredIdExistInHuks(osAccountId, credId, &credIdHashBuff); + if (ret == HAL_ERR_KEY_NOT_EXIST) { + LOGE("Huks key not exist!"); + DelCredById(osAccountId, credId); + return IS_ERR_HUKS_KEY_NOT_EXIST; + } + if (ret == HAL_ERR_HUKS) { + LOGE("Huks check key exist failed"); + return IS_ERR_HUKS_CHECK_KEY_EXIST_FAILED; + } + if (ret != IS_SUCCESS) { + LOGE("Failed to check key exist in HUKS"); + return ret; + } + + KeyParams keyParams = { { credIdHashBuff.val, credIdHashBuff.length, true }, false, osAccountId }; + uint8_t pubKeyVal[PUB_KEY_LENGTH] = { 0 }; + Uint8Buff keyValue = { pubKeyVal, PUB_KEY_LENGTH }; + ret = GetLoaderInstance()->exportPublicKey(&keyParams, &keyValue); + if (ret == HAL_ERR_HUKS) { + LOGE("Huks export key failed!"); + return IS_ERR_HUKS_EXPORT_KEY_FAILED; + } + if (ret != IS_SUCCESS) { + LOGE("Failed to export key"); + return ret; + } + + ret = AddKeyValueToReturn(keyValue, returnData); + if (ret != IS_SUCCESS) { + LOGE("Failed to add pub key to return"); + return ret; + } + + return IS_SUCCESS; +} + +int32_t QueryCredentialByParamsImpl(int32_t osAccountId, const char *requestParams, char **returnData) +{ + CJson *reqJson = CreateJsonFromString(requestParams); + if (reqJson == NULL) { + LOGE("Failed to create reqJson from string!"); + return IS_ERR_JSON_CREATE; + } + + QueryCredentialParams queryParams = InitQueryCredentialParams(); + SetQueryParamsFromJson(&queryParams, reqJson); + FreeJson(reqJson); + + CredentialVec credentialVec = CreateCredentialVec(); + + int32_t ret = QueryCredentials(osAccountId, &queryParams, &credentialVec); + if (ret != IS_SUCCESS) { + LOGE("Failed to query credentials"); + ClearCredentialVec(&credentialVec); + return ret; + } + if (credentialVec.size(&credentialVec) == 0) { + LOGW("No credential found"); + ClearCredentialVec(&credentialVec); + return GenerateReturnEmptyArrayStr(returnData); + } + + CJson *credIdJson = CreateJsonArray(); + if (credIdJson == NULL) { + LOGE("Failed to create credIdJson object"); + ClearCredentialVec(&credentialVec); + return IS_ERR_JSON_CREATE; + } + + ret = GetCredIdsFromCredVec(credentialVec, credIdJson, osAccountId); + ClearCredentialVec(&credentialVec); + if (ret != IS_SUCCESS) { + LOGE("Failed to get credIds from credentials"); + FreeJson(credIdJson); + return ret; + } + + *returnData = PackJsonToString(credIdJson); + FreeJson(credIdJson); + if (*returnData == NULL) { + LOGE("Failed to pack json to string"); + return IS_ERR_PACKAGE_JSON_TO_STRING_FAIL; + } + + return IS_SUCCESS; +} + +int32_t QueryCredInfoByCredIdImpl(int32_t osAccountId, const char *credId, char **returnData) +{ + Credential *credential = NULL; + int32_t ret = GetCredentialById(osAccountId, credId, &credential); + if (ret != IS_SUCCESS) { + LOGE("Failed to get credential by credId, ret = %d", ret); + return ret; + } + + CJson *credInfoJson = CreateJson(); + if (credInfoJson == NULL) { + LOGE("Failed to create credInfoJson object"); + DestroyCredential(credential); + return IS_ERR_JSON_CREATE; + } + + ret = GenerateReturnCredInfo(credential, credInfoJson); + DestroyCredential(credential); + if (ret != IS_SUCCESS) { + LOGE("Failed to generate return credential info"); + FreeJson(credInfoJson); + return ret; + } + + *returnData = PackJsonToString(credInfoJson); + FreeJson(credInfoJson); + if (*returnData == NULL) { + LOGE("Failed to pack json to string"); + return IS_ERR_PACKAGE_JSON_TO_STRING_FAIL; + } + + return IS_SUCCESS; +} + +int32_t DeleteCredentialImpl(int32_t osAccountId, const char *appId, const char *credId) +{ + Credential *credential = NULL; + int32_t ret = GetCredentialById(osAccountId, credId, &credential); + if (ret != IS_SUCCESS) { + LOGE("Failed to get credential by credId, ret = %d", ret); + return ret; + } + + if (strcmp(StringGet(&credential->credOwner), appId) != 0) { + LOGE("appId is not the same as the appId of the credential"); + DestroyCredential(credential); + return IS_ERR_INVALID_PARAMS; + } + DestroyCredential(credential); + + uint8_t credIdVal[SHA256_LEN] = { 0 }; + Uint8Buff credIdHashBuff = { credIdVal, SHA256_LEN }; + ret = HexStringToByte(credId, credIdHashBuff.val, credIdHashBuff.length); + if (ret != IS_SUCCESS) { + LOGE("Failed to convert credId to byte, error: %d", ret); + return ret; + } + + ret = GetLoaderInstance()->deleteKey(&credIdHashBuff, false, osAccountId); + if (ret == HAL_ERR_HUKS) { + LOGW("Huks delete key failed, error: %d, continue to delete local cred", IS_ERR_HUKS_DELETE_FAILED); + } + + ret = DelCredById(osAccountId, credId); + if (ret != IS_SUCCESS) { + LOGE("Failed to delete local credential"); + return ret; + } + + return IS_SUCCESS; +} + +int32_t UpdateCredInfoImpl(int32_t osAccountId, const char *appId, const char *credId, const char *requestParams) +{ + Credential *credential = NULL; + int32_t ret = GetCredentialById(osAccountId, credId, &credential); + if (ret != IS_SUCCESS) { + LOGE("Failed to get credential by credId, ret: %d", ret); + return ret; + } + + if (strcmp(StringGet(&credential->credOwner), appId) != 0) { + LOGE("appId is not the same as the appId of the credential"); + DestroyCredential(credential); + return IS_ERR_INVALID_PARAMS; + } + + CJson *reqJson = CreateJsonFromString(requestParams); + if (reqJson == NULL) { + LOGE("Failed to create reqJson from string!"); + DestroyCredential(credential); + return IS_ERR_JSON_CREATE; + } + ret = UpdateInfoFromJson(credential, reqJson); + FreeJson(reqJson); + if (ret != IS_SUCCESS) { + LOGE("Failed to set update info"); + DestroyCredential(credential); + return ret; + } + + ret = AddCredAndSaveDb(osAccountId, credential); + DestroyCredential(credential); + if (ret != IS_SUCCESS) { + LOGE("Failed to add credential to db"); + return ret; + } + + return IS_SUCCESS; +} + +int32_t RegCredListener(const char *appId, const CredChangeListener *listener) +{ + if ((appId == NULL) || (listener == NULL)) { + LOGE("The input parameter contains NULL value!"); + return IS_ERR_INVALID_PARAMS; + } + if (!IsCredListenerSupported()) { + LOGE("Broadcast is not supported!"); + return IS_ERR_NOT_SUPPORT; + } + return AddCredListener(appId, listener); +} + +int32_t UnRegCredListener(const char *appId) +{ + if (appId == NULL) { + LOGE("The input parameter contains NULL value!"); + return IS_ERR_INVALID_PARAMS; + } + if (!IsCredListenerSupported()) { + LOGE("Broadcast is not supported!"); + return IS_ERR_NOT_SUPPORT; + } + return RemoveCredListener(appId); +} diff --git a/services/creds_manager/inc/creds_manager.h b/services/legacy/creds_manager/inc/creds_manager.h similarity index 94% rename from services/creds_manager/inc/creds_manager.h rename to services/legacy/creds_manager/inc/creds_manager.h index 9ed1be54a8a1a3793b36f961b21aaa80f4358699..66a2bd5bd79d2362c7480ace189da347c4ee6932 100644 --- a/services/creds_manager/inc/creds_manager.h +++ b/services/legacy/creds_manager/inc/creds_manager.h @@ -32,6 +32,8 @@ int32_t GetCredInfoByPeerCert(const CJson *in, const CertInfo *certInfo, Identit int32_t GetSharedSecretByPeerCert( const CJson *in, const CertInfo *peerCertInfo, ProtocolAlgType protocolType, Uint8Buff *sharedSecret); +//IS +int32_t GetIdentityInfoIS(const CJson *context, IdentityInfo **returnInfo); #ifdef __cplusplus } #endif diff --git a/services/creds_manager/src/creds_manager.c b/services/legacy/creds_manager/src/creds_manager.c similarity index 57% rename from services/creds_manager/src/creds_manager.c rename to services/legacy/creds_manager/src/creds_manager.c index 8d90170e40a3b9720b13012fcdf4d6f2c97e6ae7..751eaf274d98e6da1e091c213b99846c63f8b16d 100644 --- a/services/creds_manager/src/creds_manager.c +++ b/services/legacy/creds_manager/src/creds_manager.c @@ -14,6 +14,11 @@ */ #include "creds_manager.h" +#include "identity_operation.h" +#include "asy_token_manager.h" +#include "cert_operation.h" + +#define FIELD_SP_CMDS "spCmds" #include "hc_log.h" @@ -236,4 +241,187 @@ int32_t GetSharedSecretByPeerCert( return HC_ERR_INVALID_PARAMS; } return authIdentity->getSharedSecretByPeerCert(in, peerCertInfo, protocolType, sharedSecret); +} + +static int32_t GetCertInfoIS(int32_t osAccountId, const CJson *credAuthInfo, CertInfo *certInfo) +{ + const char *userId = GetStringFromJson(credAuthInfo, FIELD_USER_ID); + if (userId == NULL) { + LOGE("Failed to get user ID!"); + return HC_ERR_JSON_GET; + } + + const char *authId = GetStringFromJson(credAuthInfo, FIELD_DEVICE_ID); + if (authId == NULL) { + LOGE("Failed to get auth ID!"); + return HC_ERR_JSON_GET; + } + + AccountToken *token = CreateAccountToken(); + if (token == NULL) { + LOGE("Failed to create account token!"); + return HC_ERR_ALLOC_MEMORY; + } + int32_t ret = GetAccountAuthTokenManager()->getToken(osAccountId, token, userId, authId); + if (ret != HC_SUCCESS) { + LOGE("Failed to get account token!"); + DestroyAccountToken(token); + return ret; + } + ret = GenerateCertInfo(&token->pkInfoStr, &token->pkInfoSignature, certInfo); + DestroyAccountToken(token); + if (ret != HC_SUCCESS) { + LOGE("Failed to generate cert info!"); + return ret; + } + uint32_t signAlg = 0; + if (GetUnsignedIntFromJson(credAuthInfo, FIELD_ALGORITHM_TYPE, &signAlg) != HC_SUCCESS) { + LOGE("Failed to get algorithm type!"); + return HC_ERR_JSON_GET; + } + certInfo->signAlg = signAlg; + certInfo->isPseudonym = true; + return HC_SUCCESS; +} + +static int32_t SetPreShareUrl(const CJson *context, const CJson *credAuthInfo, IdentityInfo *info) +{ + CJson *preShareUrl = CreateJson(); + if (preShareUrl == NULL) { + LOGE("create preShareUrl failed!"); + return HC_ERR_ALLOC_MEMORY; + } + int32_t credType = 0; + if (GetIntFromJson(credAuthInfo, FIELD_CRED_TYPE, &credType) != HC_SUCCESS) { + LOGE("Get cred type failed!"); + FreeJson(preShareUrl); + return HC_ERR_JSON_GET; + } + const char *pinCode = GetStringFromJson(context, FIELD_PIN_CODE); + TrustType trustType; + if (credType == ACCOUNTT_RELATED) { + trustType = TRUST_TYPE_UID; + } else if (pinCode != NULL) { + trustType = TRUST_TYPE_PIN; + } else { + trustType = TRUST_TYPE_P2P; + } + if (AddIntToJson(preShareUrl, PRESHARED_URL_TRUST_TYPE, trustType) != HC_SUCCESS) { + LOGE("Failed to add preshared url trust type!"); + FreeJson(preShareUrl); + return HC_ERR_JSON_ADD; + } + info->proof.preSharedUrl.val = (uint8_t *)PackJsonToString(preShareUrl); + FreeJson(preShareUrl); + if (info->proof.preSharedUrl.val == NULL) { + LOGE("Failed to pack preShareUrl string!"); + return HC_ERR_PACKAGE_JSON_TO_STRING_FAIL; + } + info->proof.preSharedUrl.length = HcStrlen((const char *)info->proof.preSharedUrl.val); + return HC_SUCCESS; +} + +static int32_t SetIdentityProof(const CJson *context, const CJson *credAuthInfo, IdentityInfo *info) +{ + int32_t res = HC_ERROR; + if (info->proofType == PRE_SHARED) { + res = SetPreShareUrl(context, credAuthInfo, info); + if (res != HC_SUCCESS) { + LOGE("Failed to set preshare url"); + } + } else { + int32_t osAccountId = 0; + if (GetIntFromJson(context, FIELD_OS_ACCOUNT_ID, &osAccountId) != HC_SUCCESS) { + LOGE("Failed to get osAccountId!"); + return HC_ERR_JSON_GET; + } + res = GetCertInfoIS(osAccountId, credAuthInfo, &info->proof.certInfo); + if (res != HC_SUCCESS) { + LOGE("Failed to get cert info!"); + } + } + return res; +} + +static int32_t SetProtocolEntityIS(IdentityInfo *info) +{ + ProtocolEntity *entity = (ProtocolEntity *)HcMalloc(sizeof(ProtocolEntity), 0); + if (entity == NULL) { + LOGE("Failed to alloc memory for protocol entity!"); + return HC_ERR_ALLOC_MEMORY; + } + if (info->proofType == PRE_SHARED) { +#ifdef ENABLE_ACCOUNT_AUTH_ISO + entity->protocolType = ALG_ISO; + entity->expandProcessCmds = 0; +#else + LOGE("ISO not support!"); + HcFree(entity); + return HC_ERR_NOT_SUPPORT; +#endif + } else if (info->proofType == CERTIFICATED) { +#ifdef ENABLE_ACCOUNT_AUTH_EC_SPEKE + entity->protocolType = ALG_EC_SPEKE; + entity->expandProcessCmds = 0; +#else + LOGE("ec speke not support!"); + HcFree(entity); + return HC_ERR_NOT_SUPPORT; +#endif + } else { + LOGE("unknown proof type!"); + HcFree(entity); + return HC_ERR_INVALID_PARAMS; + } + if (info->protocolVec.pushBack(&info->protocolVec, (const ProtocolEntity **)&entity) == NULL) { + HcFree(entity); + LOGE("Failed to push protocol entity!"); + return HC_ERR_ALLOC_MEMORY; + } + return HC_SUCCESS; +} + +int32_t GetIdentityInfoIS(const CJson *context, IdentityInfo **returnInfo) +{ + if (context == NULL || returnInfo == NULL) { + LOGE("Invalid input params!"); + return HC_ERR_INVALID_PARAMS; + } + CJson *credAuthInfo = GetObjFromJson(context, FIELD_SELF_CREDENTIAL_OBJ); + if (credAuthInfo == NULL) { + LOGE("Get self credAuthInfo fail."); + return HC_ERR_JSON_GET; + } + IdentityInfo *info = CreateIdentityInfo(); + if (info == NULL) { + LOGE("Failed to alloc memory for IdentityInfo!"); + return HC_ERR_JSON_GET; + } + info->IdInfoType = DEFAULT_ID_TYPE; + int res = HC_ERROR; + do { + uint32_t proofType = 0; + res = GetUnsignedIntFromJson(credAuthInfo, FIELD_PROOF_TYPE, &proofType); + info->proofType = proofType; + if (res != HC_SUCCESS) { + LOGE("Get proofType fail."); + break; + } + res = SetIdentityProof(context, credAuthInfo, info); + if (res != HC_SUCCESS) { + LOGE("Failed to get protocol entity!"); + break; + } + res = SetProtocolEntityIS(info); + if (res != HC_SUCCESS) { + LOGE("Failed to get protocol entity!"); + break; + } + } while (0); + if (res != HC_SUCCESS) { + DestroyIdentityInfo(info); + return res; + } + *returnInfo = info; + return res; } \ No newline at end of file diff --git a/services/legacy/group_auth/inc/account_related_group_auth/account_related_group_auth.h b/services/legacy/group_auth/inc/account_related_group_auth/account_related_group_auth.h index 4d42a6da52668cdf0946a34cccee4e164befc170..8921d647c3a5235d4781d969ccf0dc9eb97c4ff0 100644 --- a/services/legacy/group_auth/inc/account_related_group_auth/account_related_group_auth.h +++ b/services/legacy/group_auth/inc/account_related_group_auth/account_related_group_auth.h @@ -18,7 +18,7 @@ #include #include "base_group_auth.h" -#include "data_manager.h" +#include "group_data_manager.h" typedef void (*GetAccountCandidateGroupFunc)(int32_t osAccountId, const CJson *param, QueryGroupParams *queryParams, GroupEntryVec *vec); diff --git a/services/legacy/group_auth/inc/base_group_auth.h b/services/legacy/group_auth/inc/base_group_auth.h index 3653d73bf97a723fb0d06dc8b34ac0f6d418f723..85c0eb08b6bb59c90af5745ed2e5f4ba50157f16 100644 --- a/services/legacy/group_auth/inc/base_group_auth.h +++ b/services/legacy/group_auth/inc/base_group_auth.h @@ -17,7 +17,7 @@ #define BASE_GROUP_AUTH_H #include -#include "data_manager.h" +#include "group_data_manager.h" #include "compatible_auth_sub_session_defines.h" #include "device_auth.h" #include "json_utils.h" diff --git a/services/legacy/group_auth/inc/group_auth_data_operation.h b/services/legacy/group_auth/inc/group_auth_data_operation.h index fbf17d8de272504c349a64654de8a0b7c37f9b98..886caaad5d669f9a3ee4ab6e3901f7591b09e082 100644 --- a/services/legacy/group_auth/inc/group_auth_data_operation.h +++ b/services/legacy/group_auth/inc/group_auth_data_operation.h @@ -16,7 +16,7 @@ #ifndef GROUP_AUTH_DATA_OPERATION_H #define GROUP_AUTH_DATA_OPERATION_H -#include "data_manager.h" +#include "group_data_manager.h" #ifdef __cplusplus extern "C" { diff --git a/services/legacy/group_manager/inc/broadcast_manager/broadcast_manager.h b/services/legacy/group_manager/inc/broadcast_manager/broadcast_manager.h index d2bb02c395572e4e70c29bb8d54ba41daf5977e8..5bbef1953cd8af47bcf4a9e29a4fd247d590ce2b 100644 --- a/services/legacy/group_manager/inc/broadcast_manager/broadcast_manager.h +++ b/services/legacy/group_manager/inc/broadcast_manager/broadcast_manager.h @@ -16,7 +16,6 @@ #ifndef BROADCAST_MANAGER_H #define BROADCAST_MANAGER_H -#include "data_manager.h" #include "device_auth.h" #ifdef __cplusplus diff --git a/services/legacy/group_manager/inc/group_operation_common.h b/services/legacy/group_manager/inc/group_operation_common.h index f8edf08cc59b15590bab2abeeaf0b9dc551f87cd..69142f8c1d682cef80ec7fab7f4b51266e0ad00a 100644 --- a/services/legacy/group_manager/inc/group_operation_common.h +++ b/services/legacy/group_manager/inc/group_operation_common.h @@ -18,7 +18,7 @@ #include "common_defs.h" #include "string_util.h" -#include "data_manager.h" +#include "group_data_manager.h" #ifdef __cplusplus extern "C" { @@ -105,6 +105,12 @@ TrustedGroupEntry *GetGroupEntryById(int32_t osAccountId, const char *groupId); TrustedDeviceEntry *GetTrustedDeviceEntryById(int32_t osAccountId, const char *deviceId, bool isUdid, const char *groupId); +int32_t AddGroupInfoToContextByDb(const char *groupId, CJson *context); +int32_t AddDevInfoToContextByDb(const char *groupId, CJson *context); + +int32_t AddGroupInfoToContextByInput(const CJson *receivedMsg, CJson *context); +int32_t AddDevInfoToContextByInput(CJson *context); + #ifdef __cplusplus } #endif diff --git a/services/legacy/group_manager/src/broadcast_manager/broadcast_manager.c b/services/legacy/group_manager/src/broadcast_manager/broadcast_manager.c index 59204fc3ff23b33ee2c3b2b907b8266dce30d30d..8f54a82cab04e2bddabc8c24bd1593bccd4c4f53 100644 --- a/services/legacy/group_manager/src/broadcast_manager/broadcast_manager.c +++ b/services/legacy/group_manager/src/broadcast_manager/broadcast_manager.c @@ -16,7 +16,6 @@ #include "broadcast_manager.h" #include "common_defs.h" #include "device_auth_defines.h" -#include "group_operation_common.h" #include "hc_log.h" #include "hc_mutex.h" #include "hc_types.h" diff --git a/services/legacy/group_manager/src/group_manager.c b/services/legacy/group_manager/src/group_manager.c index f26e92e902e27838d77a63b065bca49c457bea72..1717c79fe5413cfd57b5f7bf39c0722807f8a20c 100644 --- a/services/legacy/group_manager/src/group_manager.c +++ b/services/legacy/group_manager/src/group_manager.c @@ -16,7 +16,7 @@ #include "group_manager.h" #include "common_defs.h" -#include "data_manager.h" +#include "group_data_manager.h" #include "group_operation.h" #include "hc_log.h" #include "hitrace_adapter.h" diff --git a/services/legacy/group_manager/src/group_operation/across_account_group/across_account_group.c b/services/legacy/group_manager/src/group_operation/across_account_group/across_account_group.c index a184864fa272c735cf3650e02ce4c69617ad96fc..324a5582547d27c45e6545968f5f8cbe54d710ca 100644 --- a/services/legacy/group_manager/src/group_operation/across_account_group/across_account_group.c +++ b/services/legacy/group_manager/src/group_operation/across_account_group/across_account_group.c @@ -19,8 +19,8 @@ #include "alg_defs.h" #include "callback_manager.h" #include "common_defs.h" -#include "cred_manager.h" -#include "data_manager.h" +#include "ext_plugin_manager.h" +#include "group_data_manager.h" #include "device_auth_defines.h" #include "group_operation_common.h" #include "hc_dev_info.h" diff --git a/services/legacy/group_manager/src/group_operation/group_operation.c b/services/legacy/group_manager/src/group_operation/group_operation.c index 4e5bfdf9661be300a2b9d8555f09fd124aebe7c3..e89cf8b3ebf730aedb3fe71d56b129d354a018a4 100644 --- a/services/legacy/group_manager/src/group_operation/group_operation.c +++ b/services/legacy/group_manager/src/group_operation/group_operation.c @@ -19,8 +19,8 @@ #include "broadcast_manager.h" #include "callback_manager.h" #include "common_defs.h" -#include "cred_manager.h" -#include "data_manager.h" +#include "ext_plugin_manager.h" +#include "group_data_manager.h" #include "dev_auth_module_manager.h" #include "device_auth_defines.h" #include "group_operation_common.h" diff --git a/services/legacy/group_manager/src/group_operation/group_operation_common/group_operation_common.c b/services/legacy/group_manager/src/group_operation/group_operation_common/group_operation_common.c index 5e535fb508598a23ceffc2097b8e62e445a4f9f4..ee02b3c5dafae99e4e9fc2c7385d970186197000 100644 --- a/services/legacy/group_manager/src/group_operation/group_operation_common/group_operation_common.c +++ b/services/legacy/group_manager/src/group_operation/group_operation_common/group_operation_common.c @@ -17,10 +17,9 @@ #include "alg_loader.h" #include "string_util.h" -#include "data_manager.h" +#include "group_data_manager.h" #include "dev_auth_module_manager.h" #include "device_auth_defines.h" -#include "group_operation.h" #include "hal_error.h" #include "hc_dev_info.h" #include "hc_log.h" @@ -1130,4 +1129,125 @@ int32_t GetHashResult(const uint8_t *info, uint32_t infoLen, char *hash, uint32_ HcFree(infoHash.val); HcFree(message.val); return result; +} + +int32_t AddGroupInfoToContextByDb(const char *groupId, CJson *context) +{ + int32_t osAccountId; + if (GetIntFromJson(context, FIELD_OS_ACCOUNT_ID, &osAccountId) != HC_SUCCESS) { + LOGE("get osAccountId from json fail."); + return HC_ERR_JSON_GET; + } + TrustedGroupEntry *entry = GetGroupEntryById(osAccountId, groupId); + if (entry == NULL) { + LOGE("Failed to get groupEntry from db!"); + return HC_ERR_DB; + } + if (AddStringToJson(context, FIELD_GROUP_ID, StringGet(&entry->id)) != HC_SUCCESS) { + LOGE("Failed to add groupId to json!"); + DestroyGroupEntry(entry); + return HC_ERR_JSON_FAIL; + } + if (AddIntToJson(context, FIELD_GROUP_TYPE, entry->type) != HC_SUCCESS) { + LOGE("Failed to add groupType to json!"); + DestroyGroupEntry(entry); + return HC_ERR_JSON_FAIL; + } + if (AddStringToJson(context, FIELD_GROUP_NAME, StringGet(&entry->name)) != HC_SUCCESS) { + LOGE("Failed to add groupName to json!"); + DestroyGroupEntry(entry); + return HC_ERR_JSON_FAIL; + } + DestroyGroupEntry(entry); + return HC_SUCCESS; +} + +int32_t AddDevInfoToContextByDb(const char *groupId, CJson *context) +{ + int32_t osAccountId; + if (GetIntFromJson(context, FIELD_OS_ACCOUNT_ID, &osAccountId) != HC_SUCCESS) { + LOGE("get osAccountId from json fail."); + return HC_ERR_JSON_GET; + } + char udid[INPUT_UDID_LEN] = { 0 }; + int32_t res = HcGetUdid((uint8_t *)udid, INPUT_UDID_LEN); + if (res != HC_SUCCESS) { + LOGE("Failed to get local udid! res: %d", res); + return HC_ERR_DB; + } + TrustedDeviceEntry *devAuthParams = CreateDeviceEntry(); + if (devAuthParams == NULL) { + LOGE("Failed to allocate devEntry memory!"); + return HC_ERR_ALLOC_MEMORY; + } + if (GetTrustedDevInfoById(osAccountId, udid, true, groupId, devAuthParams) != HC_SUCCESS) { + LOGE("Failed to obtain the local device information from the database!"); + DestroyDeviceEntry(devAuthParams); + return HC_ERR_DB; + } + if (AddStringToJson(context, FIELD_AUTH_ID, StringGet(&devAuthParams->authId)) != HC_SUCCESS) { + LOGE("Failed to add authId to params!"); + DestroyDeviceEntry(devAuthParams); + return HC_ERR_JSON_FAIL; + } + if (AddIntToJson(context, FIELD_USER_TYPE, devAuthParams->devType) != HC_SUCCESS) { + LOGE("Failed to add userType to params!"); + DestroyDeviceEntry(devAuthParams); + return HC_ERR_JSON_FAIL; + } + DestroyDeviceEntry(devAuthParams); + return HC_SUCCESS; +} + +int32_t AddGroupInfoToContextByInput(const CJson *receivedMsg, CJson *context) +{ + const char *groupId = GetStringFromJson(receivedMsg, FIELD_GROUP_ID); + if (groupId == NULL) { + LOGE("get groupId from json fail."); + return HC_ERR_JSON_GET; + } + const char *groupName = GetStringFromJson(receivedMsg, FIELD_GROUP_NAME); + if (groupName == NULL) { + LOGE("Failed to get groupName from jsonParams!"); + return HC_ERR_JSON_GET; + } + if (AddStringToJson(context, FIELD_GROUP_ID, groupId) != HC_SUCCESS) { + LOGE("Failed to add groupId to json!"); + return HC_ERR_JSON_FAIL; + } + if (AddIntToJson(context, FIELD_GROUP_TYPE, PEER_TO_PEER_GROUP) != HC_SUCCESS) { + LOGE("Failed to add groupType to json!"); + return HC_ERR_JSON_FAIL; + } + if (AddStringToJson(context, FIELD_GROUP_NAME, groupName) != HC_SUCCESS) { + LOGE("Failed to add groupName to json!"); + return HC_ERR_JSON_FAIL; + } + return HC_SUCCESS; +} + +int32_t AddDevInfoToContextByInput(CJson *context) +{ + int32_t userType = DEVICE_TYPE_ACCESSORY; + (void)GetIntFromJson(context, FIELD_USER_TYPE, &userType); + const char *authId = GetStringFromJson(context, FIELD_DEVICE_ID); + char udid[INPUT_UDID_LEN] = { 0 }; + if (authId == NULL) { + LOGD("No authId is found. The default value is udid!"); + int32_t res = HcGetUdid((uint8_t *)udid, INPUT_UDID_LEN); + if (res != HC_SUCCESS) { + LOGE("Failed to get local udid! res: %d", res); + return HC_ERR_DB; + } + authId = udid; + } + if (AddStringToJson(context, FIELD_AUTH_ID, authId) != HC_SUCCESS) { + LOGE("Failed to add authId to params!"); + return HC_ERR_JSON_FAIL; + } + if (AddIntToJson(context, FIELD_USER_TYPE, userType) != HC_SUCCESS) { + LOGE("Failed to add userType to params!"); + return HC_ERR_JSON_FAIL; + } + return HC_SUCCESS; } \ No newline at end of file diff --git a/services/legacy/group_manager/src/group_operation/identical_account_group/identical_account_group.c b/services/legacy/group_manager/src/group_operation/identical_account_group/identical_account_group.c index 41c390b1fe9bcf78f92847e3a99170c4144d39ba..2fe7524fba23a8d2967577351e67c0368b57684c 100644 --- a/services/legacy/group_manager/src/group_operation/identical_account_group/identical_account_group.c +++ b/services/legacy/group_manager/src/group_operation/identical_account_group/identical_account_group.c @@ -17,8 +17,8 @@ #include "alg_defs.h" #include "callback_manager.h" #include "common_defs.h" -#include "cred_manager.h" -#include "data_manager.h" +#include "ext_plugin_manager.h" +#include "group_data_manager.h" #include "device_auth_defines.h" #include "group_operation_common.h" #include "hc_dev_info.h" diff --git a/services/legacy/group_manager/src/group_operation/peer_to_peer_group/peer_to_peer_group.c b/services/legacy/group_manager/src/group_operation/peer_to_peer_group/peer_to_peer_group.c index 1d3be3850ea53c344ca59a81a41ba3c1a360bee5..89e3e22be799b3822d4002ecb8da43bbc3a38524 100644 --- a/services/legacy/group_manager/src/group_operation/peer_to_peer_group/peer_to_peer_group.c +++ b/services/legacy/group_manager/src/group_operation/peer_to_peer_group/peer_to_peer_group.c @@ -18,7 +18,7 @@ #include "alg_defs.h" #include "callback_manager.h" #include "channel_manager.h" -#include "data_manager.h" +#include "group_data_manager.h" #include "dev_auth_module_manager.h" #include "group_operation_common.h" #include "hc_dev_info.h" diff --git a/services/identity_manager/inc/cert_operation.h b/services/legacy/identity_manager/inc/cert_operation.h similarity index 93% rename from services/identity_manager/inc/cert_operation.h rename to services/legacy/identity_manager/inc/cert_operation.h index bbb0ba130f8136b09cd3d77828a7c26b75eef518..4effd8281abf9f1102c0ae1f98dc25ba4ae4ebe2 100644 --- a/services/identity_manager/inc/cert_operation.h +++ b/services/legacy/identity_manager/inc/cert_operation.h @@ -30,6 +30,7 @@ int32_t GetAccountAsymSharedSecret(int32_t osAccountId, const char *peerUserId, int32_t GetAccountSymSharedSecret(const CJson *in, const CJson *urlJson, Uint8Buff *sharedSecret); int32_t GetAccountAsymCredInfo(int32_t osAccountId, const CertInfo *certInfo, IdentityInfo **returnInfo); int32_t GetAccountSymCredInfoByPeerUrl(const CJson *in, const CJson *urlJson, IdentityInfo *info); +int32_t GenerateCertInfo(const Uint8Buff *pkInfoStr, const Uint8Buff *pkInfoSignature, CertInfo *certInfo); #ifdef __cplusplus } diff --git a/services/identity_manager/inc/identity_common.h b/services/legacy/identity_manager/inc/identity_common.h similarity index 98% rename from services/identity_manager/inc/identity_common.h rename to services/legacy/identity_manager/inc/identity_common.h index c954d726169dceef3cf99a2ca097b1b207272158..6c4e1f6a979b9ae4e6dc77adce23f94c5b445ac9 100644 --- a/services/identity_manager/inc/identity_common.h +++ b/services/legacy/identity_manager/inc/identity_common.h @@ -16,7 +16,7 @@ #ifndef AUTH_IDENTITY_COMMON_H #define AUTH_IDENTITY_COMMON_H -#include "data_manager.h" +#include "group_data_manager.h" #include "hc_vector.h" #include "identity_defines.h" #include "json_utils.h" diff --git a/services/identity_manager/inc/identity_defines.h b/services/legacy/identity_manager/inc/identity_defines.h similarity index 97% rename from services/identity_manager/inc/identity_defines.h rename to services/legacy/identity_manager/inc/identity_defines.h index 2eda36f591a25353cff8205258bf86a51e97c0b1..50e77e1cd4ed043c5a38b3783d53da98f4e2141a 100644 --- a/services/identity_manager/inc/identity_defines.h +++ b/services/legacy/identity_manager/inc/identity_defines.h @@ -56,7 +56,7 @@ typedef enum { KEY_TYPE_SYM, KEY_TYPE_ASYM } KeyType; typedef enum { TRUST_TYPE_PIN, TRUST_TYPE_P2P, TRUST_TYPE_UID } TrustType; -typedef enum { PRE_SHARED, CERTIFICATED } IdentityProofType; +typedef enum { PRE_SHARED = 1, CERTIFICATED = 2 } IdentityProofType; typedef enum { ALG_EC_SPEKE = 0x0001, ALG_DL_SPEKE = 0x0002, ALG_ISO = 0x0004 } ProtocolAlgType; diff --git a/services/identity_manager/inc/identity_manager.h b/services/legacy/identity_manager/inc/identity_manager.h similarity index 100% rename from services/identity_manager/inc/identity_manager.h rename to services/legacy/identity_manager/inc/identity_manager.h diff --git a/services/identity_manager/src/cert_operation.c b/services/legacy/identity_manager/src/cert_operation.c similarity index 98% rename from services/identity_manager/src/cert_operation.c rename to services/legacy/identity_manager/src/cert_operation.c index c0c45a8b57ace9038effb706b139261645706ac5..cd2149a1fb9aac9a7a9e40c0c11906cc224a4b0c 100644 --- a/services/identity_manager/src/cert_operation.c +++ b/services/legacy/identity_manager/src/cert_operation.c @@ -19,7 +19,7 @@ #include "account_related_group_auth.h" #include "alg_loader.h" #include "asy_token_manager.h" -#include "data_manager.h" +#include "group_data_manager.h" #include "group_auth_data_operation.h" #include "group_operation_common.h" #include "hc_log.h" @@ -353,6 +353,12 @@ static int32_t GetSharedSecretForAccountInPake(int32_t osAccountId, const char * int32_t GenerateCertInfo(const Uint8Buff *pkInfoStr, const Uint8Buff *pkInfoSignature, CertInfo *certInfo) { + if (!(IsUint8BuffValid(pkInfoStr, pkInfoStr->length) && + IsUint8BuffValid(pkInfoSignature, pkInfoSignature->length) && + certInfo != NULL)) { + LOGE("input invailed!"); + return HC_ERR_INVALID_PARAMS; + } uint32_t pkInfoLen = pkInfoStr->length; certInfo->pkInfoStr.val = (uint8_t *)HcMalloc(pkInfoLen, 0); if (certInfo->pkInfoStr.val == NULL) { @@ -430,11 +436,7 @@ static int32_t GetAccountAsymIdentityInfo( #else (void)isNeedGeneratePdid; #endif - if (info->protocolVec.pushBack(&info->protocolVec, (const ProtocolEntity **)&ecSpekeEntity) == NULL) { - LOGE("Failed to push ecSpeke entity!"); - HcFree(ecSpekeEntity); - return HC_ERR_ALLOC_MEMORY; - } + info->protocolVec.pushBack(&info->protocolVec, (const ProtocolEntity **)&ecSpekeEntity); #else (void)isNeedGeneratePdid; #endif diff --git a/services/identity_manager/src/credential_operator.c b/services/legacy/identity_manager/src/credential_operator.c similarity index 100% rename from services/identity_manager/src/credential_operator.c rename to services/legacy/identity_manager/src/credential_operator.c diff --git a/services/identity_manager/src/identity_common.c b/services/legacy/identity_manager/src/identity_common.c similarity index 97% rename from services/identity_manager/src/identity_common.c rename to services/legacy/identity_manager/src/identity_common.c index 0eee0054c3b1cee929b18fd31553dc21d0a90548..5052a5571a4d615acbc9427f969f6db878c8679c 100644 --- a/services/identity_manager/src/identity_common.c +++ b/services/legacy/identity_manager/src/identity_common.c @@ -146,6 +146,9 @@ IdentityInfo *CreateIdentityInfo(void) LOGE("Failed to alloc memory for identity info!"); return NULL; } + info->proof.preSharedUrl.val = NULL; + info->proof.certInfo.pkInfoStr.val = NULL; + info->proof.certInfo.pkInfoSignature.val = NULL; info->protocolVec = CreateProtocolEntityVec(); return info; } diff --git a/services/identity_manager/src/identity_group.c b/services/legacy/identity_manager/src/identity_group.c similarity index 97% rename from services/identity_manager/src/identity_group.c rename to services/legacy/identity_manager/src/identity_group.c index 71bb0c81ba5920d11bab91fb2d460eabbbe66268..631670c34d1a6a1539e97d674e396becaa63f462 100644 --- a/services/identity_manager/src/identity_group.c +++ b/services/legacy/identity_manager/src/identity_group.c @@ -112,11 +112,7 @@ static int32_t SetProtocolsToIdentityInfo(int32_t keyType, IdentityInfo *info) return HC_ERR_ALLOC_MEMORY; } entity->protocolType = ALG_EC_SPEKE; - if (info->protocolVec.pushBack(&info->protocolVec, (const ProtocolEntity **)&entity) == NULL) { - LOGE("Failed to push entity!"); - HcFree(entity); - return HC_ERR_ALLOC_MEMORY; - } + info->protocolVec.pushBack(&info->protocolVec, (const ProtocolEntity **)&entity); #else (void)info; #endif @@ -128,11 +124,7 @@ static int32_t SetProtocolsToIdentityInfo(int32_t keyType, IdentityInfo *info) return HC_ERR_ALLOC_MEMORY; } entity->protocolType = ALG_ISO; - if (info->protocolVec.pushBack(&info->protocolVec, (const ProtocolEntity **)&entity) == NULL) { - LOGE("Failed to push entity!"); - HcFree(entity); - return HC_ERR_ALLOC_MEMORY; - } + info->protocolVec.pushBack(&info->protocolVec, (const ProtocolEntity **)&entity); #else (void)info; #endif @@ -256,11 +248,7 @@ static void AddNoPseudonymIdentityInfo(int32_t osAccountId, const TrustedGroupEn return; } info->proof.certInfo.isPseudonym = false; - if (identityInfoVec->pushBack(identityInfoVec, (const IdentityInfo **)&info) == NULL) { - LOGE("Failed to push info!"); - DestroyIdentityInfo(info); - return; - } + identityInfoVec->pushBack(identityInfoVec, (const IdentityInfo **)&info); } static int32_t GetIdentityInfos( @@ -299,11 +287,7 @@ static int32_t GetIdentityInfos( if (info->proofType == CERTIFICATED) { info->proof.certInfo.isPseudonym = true; } - if (identityInfoVec->pushBack(identityInfoVec, (const IdentityInfo **)&info) == NULL) { - LOGE("Failed to push info!"); - DestroyIdentityInfo(info); - return HC_ERR_ALLOC_MEMORY; - } + identityInfoVec->pushBack(identityInfoVec, (const IdentityInfo **)&info); if (info->proofType == CERTIFICATED) { AddNoPseudonymIdentityInfo(osAccountId, groupEntry, deviceId, isUdid, identityInfoVec); } diff --git a/services/identity_manager/src/identity_manager.c b/services/legacy/identity_manager/src/identity_manager.c similarity index 100% rename from services/identity_manager/src/identity_manager.c rename to services/legacy/identity_manager/src/identity_manager.c diff --git a/services/identity_manager/src/identity_p2p.c b/services/legacy/identity_manager/src/identity_p2p.c similarity index 94% rename from services/identity_manager/src/identity_p2p.c rename to services/legacy/identity_manager/src/identity_p2p.c index ee2af8b4d81a30f18fbe336431729304677bdb98..1150561981b732a6b42605bb88bf35ec2a79dc77 100644 --- a/services/identity_manager/src/identity_p2p.c +++ b/services/legacy/identity_manager/src/identity_p2p.c @@ -27,11 +27,7 @@ static int32_t SetProtocolsToIdentityInfo(IdentityInfo *info) } ecSpekeEntity->protocolType = ALG_EC_SPEKE; ecSpekeEntity->expandProcessCmds = 0; - if (info->protocolVec.pushBack(&info->protocolVec, (const ProtocolEntity **)&ecSpekeEntity) == NULL) { - LOGE("Failed to push ecSpeke entity!"); - HcFree(ecSpekeEntity); - return HC_ERR_ALLOC_MEMORY; - } + info->protocolVec.pushBack(&info->protocolVec, (const ProtocolEntity **)&ecSpekeEntity); return HC_SUCCESS; } @@ -106,8 +102,16 @@ static int32_t IsPeerDevicePublicKeyExist(const CJson *in) return ret; } -static int32_t CreateUrlStr(int32_t keyType, char **urlStr) +static int32_t GetCredInfosByPeerIdentity(const CJson *in, IdentityInfoVec *vec) { + int32_t keyType = KEY_TYPE_ASYM; + (void)GetIntFromJson(in, FIELD_KEY_TYPE, &keyType); + + int32_t ret = IsPeerDevicePublicKeyExist(in); + if (ret != HC_SUCCESS) { + LOGE("Failed to get peer device public key!"); + return ret; + } CJson *urlJson = CreateCredUrlJson(PRE_SHARED, keyType, TRUST_TYPE_P2P); if (!urlJson) { LOGE("Failed to create CredUrlJson info!"); @@ -120,33 +124,12 @@ static int32_t CreateUrlStr(int32_t keyType, char **urlStr) } else { LOGI("add isDirectAuth:true into urlJson!"); } - char *str = PackJsonToString(urlJson); + char *urlStr = PackJsonToString(urlJson); FreeJson(urlJson); - if (str == NULL) { + if (urlStr == NULL) { LOGE("Failed to pack url json to string!"); return HC_ERR_PACKAGE_JSON_TO_STRING_FAIL; } - *urlStr = str; - return HC_SUCCESS; -} - -static int32_t GetCredInfosByPeerIdentity(const CJson *in, IdentityInfoVec *vec) -{ - int32_t keyType = KEY_TYPE_ASYM; - (void)GetIntFromJson(in, FIELD_KEY_TYPE, &keyType); - - int32_t ret = IsPeerDevicePublicKeyExist(in); - if (ret != HC_SUCCESS) { - LOGE("Failed to get peer device public key!"); - return ret; - } - - char *urlStr = NULL; - ret = CreateUrlStr(keyType, &urlStr); - if (ret != HC_SUCCESS) { - LOGE("Failed to create url string!"); - return ret; - } IdentityInfo *info = CreateIdentityInfo(); if (info == NULL) { LOGE("Failed to create identity info!"); @@ -168,11 +151,7 @@ static int32_t GetCredInfosByPeerIdentity(const CJson *in, IdentityInfoVec *vec) } info->proofType = PRE_SHARED; info->IdInfoType = P2P_DIRECT_AUTH; - if (vec->pushBack(vec, (const IdentityInfo **)&info) == NULL) { - LOGE("Failed to push info!"); - DestroyIdentityInfo(info); - return HC_ERR_ALLOC_MEMORY; - } + vec->pushBack(vec, (const IdentityInfo **)&info); return HC_SUCCESS; } diff --git a/services/identity_manager/src/identity_pin.c b/services/legacy/identity_manager/src/identity_pin.c similarity index 95% rename from services/identity_manager/src/identity_pin.c rename to services/legacy/identity_manager/src/identity_pin.c index 7e71f2f9500a0cdc32b9f0b602fa16435e572d5a..b8b4c04173b0c7dad5d883dc88c15fd7200adb0b 100644 --- a/services/identity_manager/src/identity_pin.c +++ b/services/legacy/identity_manager/src/identity_pin.c @@ -136,43 +136,33 @@ static int32_t SetProtocolsForDirectAuth(IdentityInfo *info) return HC_SUCCESS; } -static int32_t CreateUrlStr(const CJson *in, char **urlStr) +static int32_t GetCredInfosByPeerIdentity(const CJson *in, IdentityInfoVec *vec) { + IdentityInfo *info = CreateIdentityInfo(); + if (info == NULL) { + LOGE("Failed to create identity info!"); + return HC_ERR_ALLOC_MEMORY; + } CJson *urlJson = CreateCredUrlJson(PRE_SHARED, KEY_TYPE_SYM, TRUST_TYPE_PIN); if (!urlJson) { LOGE("Failed to create CredUrlJson info!"); + DestroyIdentityInfo(info); return HC_ERR_ALLOC_MEMORY; } if (IsDirectAuth(in) && AddBoolToJson(urlJson, FIELD_IS_DIRECT_AUTH, true) != HC_SUCCESS) { LOGE("Failed to isDirectAuth to preshared url!"); FreeJson(urlJson); + DestroyIdentityInfo(info); return HC_ERR_JSON_ADD; } - char *str = PackJsonToString(urlJson); + char *urlStr = PackJsonToString(urlJson); FreeJson(urlJson); - if (str == NULL) { + if (urlStr == NULL) { LOGE("Failed to pack url json to string!"); - return HC_ERR_PACKAGE_JSON_TO_STRING_FAIL; - } - *urlStr = str; - return HC_SUCCESS; -} - -static int32_t GetCredInfosByPeerIdentity(const CJson *in, IdentityInfoVec *vec) -{ - IdentityInfo *info = CreateIdentityInfo(); - if (info == NULL) { - LOGE("Failed to create identity info!"); - return HC_ERR_ALLOC_MEMORY; - } - char *urlStr = NULL; - int32_t ret = CreateUrlStr(in, &urlStr); - if (ret != HC_SUCCESS) { - LOGE("Failed to create url string!"); DestroyIdentityInfo(info); - return ret; + return HC_ERR_PACKAGE_JSON_TO_STRING_FAIL; } - ret = SetPreSharedUrlForProof(urlStr, &info->proof.preSharedUrl); + int32_t ret = SetPreSharedUrlForProof(urlStr, &info->proof.preSharedUrl); FreeJsonString(urlStr); if (ret != HC_SUCCESS) { LOGE("Failed to set preSharedUrl of proof!"); @@ -191,11 +181,7 @@ static int32_t GetCredInfosByPeerIdentity(const CJson *in, IdentityInfoVec *vec) return ret; } info->proofType = PRE_SHARED; - if (vec->pushBack(vec, (const IdentityInfo **)&info) == NULL) { - LOGE("Failed to push info!"); - DestroyIdentityInfo(info); - return HC_ERR_ALLOC_MEMORY; - } + vec->pushBack(vec, (const IdentityInfo **)&info); return HC_SUCCESS; } diff --git a/services/identity_manager/src/mock/cert_operation_mock.c b/services/legacy/identity_manager/src/mock/cert_operation_mock.c similarity index 100% rename from services/identity_manager/src/mock/cert_operation_mock.c rename to services/legacy/identity_manager/src/mock/cert_operation_mock.c diff --git a/services/identity_manager/src/mock/identity_common_mock.c b/services/legacy/identity_manager/src/mock/identity_common_mock.c similarity index 100% rename from services/identity_manager/src/mock/identity_common_mock.c rename to services/legacy/identity_manager/src/mock/identity_common_mock.c diff --git a/services/identity_manager/src/mock/identity_manager_mock.c b/services/legacy/identity_manager/src/mock/identity_manager_mock.c similarity index 100% rename from services/identity_manager/src/mock/identity_manager_mock.c rename to services/legacy/identity_manager/src/mock/identity_manager_mock.c diff --git a/services/session_manager/inc/session/dev_session_def.h b/services/session_manager/inc/session/dev_session_def.h index a7350aea3aa0f8d2a81e81ce58a62ee9ebf4bee7..2801ef0947ebda5998f1b70609fc3f67f366764c 100644 --- a/services/session_manager/inc/session/dev_session_def.h +++ b/services/session_manager/inc/session/dev_session_def.h @@ -23,6 +23,29 @@ #include "dev_session_fwk.h" #include "hc_vector.h" +#define FIELD_DATA "data" +#define FIELD_VR "vr" +#define FIELD_INDEX "index" +#define FIELD_TOTAL "total" +#define FIELD_CRED_URL "credUrl" +#define FIELD_PROTOCOL "protocol" +#define FIELD_CMDS "cmds" +#define FIELD_AUTH_MSG "authMsg" +#define FIELD_AUTH_DATA "authData" +#define FIELD_ABILITY "ability" +#define FIELD_TYPE "type" +#define FIELD_MSG "msg" + +#define FIELD_HAND_SHAKE "handshake" +#define FIELD_AUTH_EVENT "authEvent" +#define FIELD_ID "id" +#define FIELD_TD_CMDS "tdCmds" +#define FIELD_SP_CMDS "spCmds" +#define FIELD_CMD_EVENT "cmdEvent" +#define FIELD_SESSION_FAIL_EVENT "failEvent" + +#define DEV_SESSION_SALT_LEN 32 + typedef struct { int32_t type; const CJson *data; @@ -50,6 +73,7 @@ typedef struct { AuthSubSessionList authSubSessionList; ExpandSubSession *expandSubSession; CompatibleBaseSubSession *compatibleSubSession; + bool isCredAuth; } SessionImpl; #endif diff --git a/services/session_manager/inc/session/v2/dev_session_util.h b/services/session_manager/inc/session/v2/dev_session_util.h index c78daf05466c3ff6069aefec8320215cb9e5f537..1bfcf392f5bf01fd946113ed8f69eded0145a855 100644 --- a/services/session_manager/inc/session/v2/dev_session_util.h +++ b/services/session_manager/inc/session/v2/dev_session_util.h @@ -17,7 +17,7 @@ #define DEV_SESSION_UTIL_H #include "identity_defines.h" -#include "data_manager.h" +#include "group_data_manager.h" #include "json_utils.h" #ifdef __cplusplus @@ -34,6 +34,14 @@ int32_t GetRealPkInfoStr(int32_t osAccountId, const CJson *credInfo, char **retu int32_t AddPkInfoWithPdid(const CJson *context, CJson *credInfo, const char *realPkInfoStr); TrustedDeviceEntry *GetDeviceEntryById(int32_t osAccountId, const char *deviceId, bool isUdid, const char *groupId); +int32_t BuildPeerCertInfo(const char *pkInfoStr, const char *pkInfoSignHexStr, int32_t signAlg, + CertInfo *peerCert); +void DestroyCertInfo(CertInfo *certInfo); +int32_t GetPeerCertInfo(CJson *context, const CJson *credInfo, CertInfo *peerCert); +int32_t CalSalt(Uint8Buff *salt); +int32_t GetSelfUserId(int32_t osAccountId, char *userId, uint32_t userIdLen); +int32_t AddMsgToSessionMsg(int32_t eventType, const CJson *msg, CJson *sessionMsg); +bool IsPeerSameUserId(int32_t osAccountId, const char *peerUserId); #ifdef __cplusplus } diff --git a/services/session_manager/src/session/dev_session_fwk.c b/services/session_manager/src/session/dev_session_fwk.c index 96461070939e722889be87771118b5ef2def7766..19c2b9e7ac9c9f25efb93535fe5f45da7ad7b2d3 100644 --- a/services/session_manager/src/session/dev_session_fwk.c +++ b/services/session_manager/src/session/dev_session_fwk.c @@ -25,7 +25,7 @@ #include "compatible_sub_session.h" #include "compatible_bind_sub_session_util.h" #include "compatible_auth_sub_session_util.h" -#include "data_manager.h" +#include "group_data_manager.h" #include "dev_session_v2.h" #include "hc_dev_info.h" #include "hc_log.h" @@ -34,10 +34,6 @@ #include "performance_dumper.h" #include "hisysevent_adapter.h" -#define FIELD_MSG "msg" -#define FIELD_TYPE "type" -#define FIELD_DATA "data" - static int32_t StartV1Session(SessionImpl *impl, CJson **sendMsg) { bool isBind = true; @@ -376,7 +372,7 @@ static int32_t StartSession(DevSession *self) bool isDirectAuth = false; bool isDeviceLevel = false; (void)GetBoolFromJson(impl->context, FIELD_IS_DIRECT_AUTH, &isDirectAuth); - if (!isDirectAuth) { + if (!isDirectAuth && !impl->isCredAuth) { (void)GetBoolFromJson(impl->context, FIELD_IS_DEVICE_LEVEL, &isDeviceLevel); res = StartV1Session(impl, &sendMsg); if ((res != HC_SUCCESS) @@ -658,16 +654,18 @@ static char *GetSessionReturnData(const SessionImpl *impl) LOGW("allocate returnData memory fail."); return NULL; } - const char *groupId = GetStringFromJson(impl->context, FIELD_GROUP_ID); - if (groupId == NULL) { - LOGW("get groupId from context fail."); - FreeJson(returnData); - return NULL; - } - if (AddStringToJson(returnData, FIELD_GROUP_ID, groupId) != HC_SUCCESS) { - LOGW("add groupId to returnData fail."); - FreeJson(returnData); - return NULL; + if (!impl->isCredAuth) { + const char *groupId = GetStringFromJson(impl->context, FIELD_GROUP_ID); + if (groupId == NULL) { + LOGW("get groupId from context fail."); + FreeJson(returnData); + return NULL; + } + if (AddStringToJson(returnData, FIELD_GROUP_ID, groupId) != HC_SUCCESS) { + LOGW("add groupId to returnData fail."); + FreeJson(returnData); + return NULL; + } } char *returnDataStr = PackJsonToString(returnData); FreeJson(returnData); @@ -762,10 +760,13 @@ static int32_t BuildDevSessionByContext(const CJson *context, SessionImpl *sessi LOGE("get isClient from context fail."); return HC_ERR_JSON_GET; } + bool isCredAuth = false; + (void)GetBoolFromJson(context, FIELD_IS_CRED_AUTH, &isCredAuth); session->base.opCode = opCode; session->channelType = channelType; session->channelId = channelId; session->isClient = isClient; + session->isCredAuth = isCredAuth; return HC_SUCCESS; } diff --git a/services/session_manager/src/session/v1/compatible_auth_sub_session/compatible_auth_sub_session_common.c b/services/session_manager/src/session/v1/compatible_auth_sub_session/compatible_auth_sub_session_common.c index d188e2f96fe1eee899e7b7dcf528b9591f1dc688..c46e88d577071eabb590b425bf42b12a8610030a 100644 --- a/services/session_manager/src/session/v1/compatible_auth_sub_session/compatible_auth_sub_session_common.c +++ b/services/session_manager/src/session/v1/compatible_auth_sub_session/compatible_auth_sub_session_common.c @@ -19,7 +19,7 @@ #include "account_related_group_auth.h" #include "account_task_manager.h" #include "compatible_auth_sub_session_util.h" -#include "data_manager.h" +#include "group_data_manager.h" #include "dev_auth_module_manager.h" #include "group_auth_data_operation.h" #include "hc_log.h" diff --git a/services/session_manager/src/session/v2/auth_sub_session/protocol_lib/ec_speke_protocol.c b/services/session_manager/src/session/v2/auth_sub_session/protocol_lib/ec_speke_protocol.c index 2c4d6aaca900ce3395b614c06112bdd9d99e40f2..f9b8a4f827abecd2c97a3bf9d6af624c70048b95 100644 --- a/services/session_manager/src/session/v2/auth_sub_session/protocol_lib/ec_speke_protocol.c +++ b/services/session_manager/src/session/v2/auth_sub_session/protocol_lib/ec_speke_protocol.c @@ -35,7 +35,6 @@ #define EC_SPEKE_PRIVATE_KEY_OR_MASK_LOW 0x40 // event field define -#define FIELD_PROTOCOL_TYPE "protocolType" #define FIELD_EVENT "event" #define FIELD_PROTOCOL_DATA "protocolData" #define FIELD_ERR_CODE "errCode" diff --git a/services/session_manager/src/session/v2/auth_sub_session/protocol_lib/iso_protocol.c b/services/session_manager/src/session/v2/auth_sub_session/protocol_lib/iso_protocol.c index 6b2bd50335de883469856fa6a30c1f6041fe979a..d1ede663ba97ea921fe94c1c0e31d05d7bead25f 100644 --- a/services/session_manager/src/session/v2/auth_sub_session/protocol_lib/iso_protocol.c +++ b/services/session_manager/src/session/v2/auth_sub_session/protocol_lib/iso_protocol.c @@ -41,7 +41,6 @@ #define FIELD_TOKEN_SERVER "tokenS" #define FIELD_AUTH_RESULT_MAC "authResultMac" -#define FIELD_PROTOCOL_TYPE "protocolType" #define FIELD_EVENT "event" #define FIELD_PROTOCOL_DATA "protocolData" #define FIELD_ERR_CODE "errCode" diff --git a/services/session_manager/src/session/v2/dev_session_util.c b/services/session_manager/src/session/v2/dev_session_util.c index d0525b549fa1f330426be830ee2c1378a3f97686..0ca0b4260c8da9980f76760f964df456d9e81cf9 100644 --- a/services/session_manager/src/session/v2/dev_session_util.c +++ b/services/session_manager/src/session/v2/dev_session_util.c @@ -15,10 +15,13 @@ #include "dev_session_util.h" +#include #include "alg_loader.h" #include "hc_log.h" #include "pseudonym_manager.h" +#include "dev_session_def.h" + #define AUTH_ID_LEN 32 #define FIELD_AUTH_ID_CLIENT "authIdC" #define FIELD_AUTH_ID_SERVER "authIdS" @@ -540,4 +543,202 @@ TrustedDeviceEntry *GetDeviceEntryById(int32_t osAccountId, const char *deviceId } ClearDeviceEntryVec(&deviceEntryVec); return NULL; +} + +int32_t BuildPeerCertInfo(const char *pkInfoStr, const char *pkInfoSignHexStr, int32_t signAlg, + CertInfo *peerCert) +{ + if ((pkInfoStr == NULL) || (pkInfoSignHexStr == NULL) || (peerCert == NULL)) { + LOGE("The input contains null ptr!"); + return HC_ERR_NULL_PTR; + } + Uint8Buff pkInfoStrBuff = { (uint8_t *)pkInfoStr, HcStrlen(pkInfoStr) + 1 }; + uint32_t pkInfoSignatureLen = HcStrlen(pkInfoSignHexStr) / BYTE_TO_HEX_OPER_LENGTH; + if (DeepCopyUint8Buff(&pkInfoStrBuff, &peerCert->pkInfoStr) != HC_SUCCESS) { + LOGE("copy pkInfoStr fail."); + return HC_ERR_ALLOC_MEMORY; + } + if (InitUint8Buff(&peerCert->pkInfoSignature, pkInfoSignatureLen) != HC_SUCCESS) { + LOGE("allocate pkInfoSignature memory fail."); + ClearFreeUint8Buff(&peerCert->pkInfoStr); + return HC_ERR_ALLOC_MEMORY; + } + if (HexStringToByte(pkInfoSignHexStr, peerCert->pkInfoSignature.val, + peerCert->pkInfoSignature.length) != HC_SUCCESS) { + LOGE("get pkInfoSignature from json fail."); + ClearFreeUint8Buff(&peerCert->pkInfoStr); + ClearFreeUint8Buff(&peerCert->pkInfoSignature); + return HC_ERR_JSON_ADD; + } + peerCert->signAlg = signAlg; + return HC_SUCCESS; +} + +void DestroyCertInfo(CertInfo *certInfo) +{ + ClearFreeUint8Buff(&certInfo->pkInfoSignature); + ClearFreeUint8Buff(&certInfo->pkInfoStr); +} + +int32_t GetPeerCertInfo(CJson *context, const CJson *credInfo, CertInfo *peerCert) +{ + if ((context == NULL) || (credInfo == NULL) || (peerCert == NULL)) { + LOGE("The input contains null ptr!"); + return HC_ERR_NULL_PTR; + } + int32_t osAccountId = 0; + if (GetIntFromJson(context, FIELD_OS_ACCOUNT_ID, &osAccountId) != HC_SUCCESS) { + LOGE("Failed to get osAccountId!"); + return HC_ERR_JSON_GET; + } + int32_t signAlg; + if (GetIntFromJson(credInfo, FIELD_SIGN_ALG, &signAlg) != HC_SUCCESS) { + LOGE("get signAlg from json fail."); + return HC_ERR_JSON_ADD; + } + char *pkInfoStr = NULL; + int32_t res = GetRealPkInfoStr(osAccountId, credInfo, &pkInfoStr, &peerCert->isPseudonym); + if (res != HC_SUCCESS) { + LOGE("Failed to get real pkInfo string!"); + return res; + } + const char *pkInfoSignHexStr = GetStringFromJson(credInfo, FIELD_PK_INFO_SIGNATURE); + if (pkInfoSignHexStr == NULL) { + LOGE("get pkInfoSignature from json fail."); + HcFree(pkInfoStr); + return HC_ERR_JSON_GET; + } + res = BuildPeerCertInfo(pkInfoStr, pkInfoSignHexStr, signAlg, peerCert); + HcFree(pkInfoStr); + return res; +} + +static int32_t GetSaltMsg(Uint8Buff *saltMsg) +{ + uint8_t randomVal[DEV_SESSION_SALT_LEN] = { 0 }; + Uint8Buff random = { randomVal, DEV_SESSION_SALT_LEN }; + int32_t res = GetLoaderInstance()->generateRandom(&random); + if (res != HC_SUCCESS) { + LOGE("generate random failed, res: %d", res); + return res; + } + clock_t times = 0; + if (memcpy_s(saltMsg->val, saltMsg->length, random.val, random.length) != EOK) { + LOGE("memcpy random failed."); + return HC_ERR_MEMORY_COPY; + } + if (memcpy_s(saltMsg->val + random.length, saltMsg->length - random.length, ×, sizeof(clock_t)) != EOK) { + LOGE("memcpy times failed."); + return HC_ERR_MEMORY_COPY; + } + return HC_SUCCESS; +} + +int32_t CalSalt(Uint8Buff *salt) +{ + if ((salt == NULL) || (salt->val == NULL)) { + LOGE("The input contains null ptr!"); + return HC_ERR_NULL_PTR; + } + uint32_t saltMsgLen = DEV_SESSION_SALT_LEN + sizeof(clock_t); + Uint8Buff saltMsg = { NULL, 0 }; + if (InitUint8Buff(&saltMsg, saltMsgLen) != HC_SUCCESS) { + LOGE("allocate saltMsg memory fail."); + return HC_ERR_ALLOC_MEMORY; + } + int32_t res = GetSaltMsg(&saltMsg); + if (res != HC_SUCCESS) { + FreeUint8Buff(&saltMsg); + return res; + } + res = GetLoaderInstance()->sha256(&saltMsg, salt); + FreeUint8Buff(&saltMsg); + if (res != HC_SUCCESS) { + LOGE("sha256 for session salt failed."); + return res; + } + return HC_SUCCESS; +} + +int32_t GetSelfUserId(int32_t osAccountId, char *userId, uint32_t userIdLen) +{ + if (userId == NULL) { + LOGE("The input is null ptr!"); + return HC_ERR_NULL_PTR; + } + GroupEntryVec accountVec = CreateGroupEntryVec(); + QueryGroupParams queryParams = InitQueryGroupParams(); + queryParams.groupType = IDENTICAL_ACCOUNT_GROUP; + do { + if (QueryGroups(osAccountId, &queryParams, &accountVec) != HC_SUCCESS) { + LOGD("No identical-account group in db, no identical-account auth!"); + break; + } + uint32_t index = 0; + TrustedGroupEntry **ptr = NULL; + while (index < accountVec.size(&accountVec)) { + ptr = accountVec.getp(&accountVec, index); + if ((ptr == NULL) || (*ptr == NULL)) { + index++; + continue; + } + if (memcpy_s(userId, userIdLen, StringGet(&(*ptr)->userId), StringLength(&(*ptr)->userId)) != EOK) { + LOGE("copy fail"); + ClearGroupEntryVec(&accountVec); + return HC_ERROR; + } + index++; + } + } while (0); + ClearGroupEntryVec(&accountVec); + return HC_SUCCESS; +} + +int32_t AddMsgToSessionMsg(int32_t eventType, const CJson *msg, CJson *sessionMsg) +{ + if ((msg == NULL) || (sessionMsg == NULL)) { + LOGE("The input contains null ptr!"); + return HC_ERR_NULL_PTR; + } + CJson *event = CreateJson(); + if (event == NULL) { + LOGE("allocate event memory fail."); + return HC_ERR_ALLOC_MEMORY; + } + if (AddIntToJson(event, FIELD_TYPE, eventType) != HC_SUCCESS) { + LOGE("add eventType to event fail."); + FreeJson(event); + return HC_ERR_JSON_ADD; + } + if (AddObjToJson(event, FIELD_DATA, msg) != HC_SUCCESS) { + LOGE("add msg to event fail."); + FreeJson(event); + return HC_ERR_JSON_ADD; + } + if (AddObjToArray(sessionMsg, event) != HC_SUCCESS) { + LOGE("add event to sessionMsg fail."); + FreeJson(event); + return HC_ERR_JSON_ADD; + } + return HC_SUCCESS; +} + +bool IsPeerSameUserId(int32_t osAccountId, const char *peerUserId) +{ + if (peerUserId == NULL) { + LOGE("The input is null ptr!"); + return HC_ERR_NULL_PTR; + } + GroupEntryVec groupVec = CreateGroupEntryVec(); + QueryGroupParams queryParams = InitQueryGroupParams(); + queryParams.groupType = IDENTICAL_ACCOUNT_GROUP; + if (QueryGroups(osAccountId, &queryParams, &groupVec) != HC_SUCCESS || groupVec.size(&groupVec) <= 0) { + LOGE("get identical account group from db fail."); + ClearGroupEntryVec(&groupVec); + return false; + } + TrustedGroupEntry *groupEntry = groupVec.get(&groupVec, 0); + bool isSame = (strcmp(StringGet(&(groupEntry->userId)), peerUserId) == 0); + ClearGroupEntryVec(&groupVec); + return isSame; } \ No newline at end of file diff --git a/services/session_manager/src/session/v2/dev_session_v2.c b/services/session_manager/src/session/v2/dev_session_v2.c index 443252fcf467d065daf159a4a29bad39d3b2c032..272979e55684fe38059d5f405a1cf3be6b3fdd8f 100644 --- a/services/session_manager/src/session/v2/dev_session_v2.c +++ b/services/session_manager/src/session/v2/dev_session_v2.c @@ -16,13 +16,12 @@ #include "dev_session_v2.h" #include -#include #include "alg_loader.h" #include "callback_manager.h" #include "channel_manager.h" #include "common_defs.h" #include "creds_manager.h" -#include "data_manager.h" +#include "group_data_manager.h" #include "dev_session_util.h" #include "hc_dev_info.h" #include "hc_log.h" @@ -42,29 +41,9 @@ #include "save_trusted_info.h" #include "group_auth_data_operation.h" #include "group_operation_common.h" - -#define FIELD_DATA "data" -#define FIELD_VR "vr" -#define FIELD_INDEX "index" -#define FIELD_TOTAL "total" -#define FIELD_CRED_URL "credUrl" -#define FIELD_PROTOCOL "protocol" -#define FIELD_CMDS "cmds" -#define FIELD_AUTH_MSG "authMsg" -#define FIELD_AUTH_DATA "authData" -#define FIELD_ABILITY "ability" -#define FIELD_TYPE "type" - -#define FIELD_HAND_SHAKE "handshake" -#define FIELD_AUTH_EVENT "authEvent" -#define FIELD_ID "id" -#define FIELD_TD_CMDS "tdCmds" -#define FIELD_SP_CMDS "spCmds" -#define FIELD_CMD_EVENT "cmdEvent" -#define FIELD_SESSION_FAIL_EVENT "failEvent" +#include "account_task_manager.h" #define USER_ID_LEN 65 -#define DEV_SESSION_SALT_LEN 32 #define VERSION_2_0_0 "2.0.0" IMPLEMENT_HC_VECTOR(EventList, SessionEvent, 3) @@ -300,31 +279,6 @@ static int32_t RestartSession(SessionImpl *impl, JumpPolicy *policy) return HC_SUCCESS; } -static int32_t AddMsgToSessionMsg(int32_t eventType, const CJson *msg, CJson *sessionMsg) -{ - CJson *event = CreateJson(); - if (event == NULL) { - LOGE("allocate event memory fail."); - return HC_ERR_ALLOC_MEMORY; - } - if (AddIntToJson(event, FIELD_TYPE, eventType) != HC_SUCCESS) { - LOGE("add eventType to event fail."); - FreeJson(event); - return HC_ERR_JSON_ADD; - } - if (AddObjToJson(event, FIELD_DATA, msg) != HC_SUCCESS) { - LOGE("add msg to event fail."); - FreeJson(event); - return HC_ERR_JSON_ADD; - } - if (AddObjToArray(sessionMsg, event) != HC_SUCCESS) { - LOGE("add event to sessionMsg fail."); - FreeJson(event); - return HC_ERR_JSON_ADD; - } - return HC_SUCCESS; -} - static void ErrorInformPeer(int32_t errorCode, CJson *sessionMsg) { CJson *errMsg = CreateJson(); @@ -583,66 +537,6 @@ static int32_t GetPreSharedCredInfo(SessionImpl *impl, const CJson *credInfo, Id return HC_SUCCESS; } -static int32_t BuildPeerCertInfo(const char *pkInfoStr, const char *pkInfoSignHexStr, int32_t signAlg, - CertInfo *peerCert) -{ - Uint8Buff pkInfoStrBuff = { (uint8_t *)pkInfoStr, HcStrlen(pkInfoStr) + 1 }; - uint32_t pkInfoSignatureLen = HcStrlen(pkInfoSignHexStr) / BYTE_TO_HEX_OPER_LENGTH; - if (DeepCopyUint8Buff(&pkInfoStrBuff, &peerCert->pkInfoStr) != HC_SUCCESS) { - LOGE("copy pkInfoStr fail."); - return HC_ERR_ALLOC_MEMORY; - } - if (InitUint8Buff(&peerCert->pkInfoSignature, pkInfoSignatureLen) != HC_SUCCESS) { - LOGE("allocate pkInfoSignature memory fail."); - ClearFreeUint8Buff(&peerCert->pkInfoStr); - return HC_ERR_ALLOC_MEMORY; - } - if (HexStringToByte(pkInfoSignHexStr, peerCert->pkInfoSignature.val, - peerCert->pkInfoSignature.length) != HC_SUCCESS) { - LOGE("get pkInfoSignature from json fail."); - ClearFreeUint8Buff(&peerCert->pkInfoStr); - ClearFreeUint8Buff(&peerCert->pkInfoSignature); - return HC_ERR_JSON_ADD; - } - peerCert->signAlg = signAlg; - return HC_SUCCESS; -} - -static void DestroyCertInfo(CertInfo *certInfo) -{ - ClearFreeUint8Buff(&certInfo->pkInfoSignature); - ClearFreeUint8Buff(&certInfo->pkInfoStr); -} - -static int32_t GetPeerCertInfo(CJson *context, const CJson *credInfo, CertInfo *peerCert) -{ - int32_t osAccountId; - if (GetIntFromJson(context, FIELD_OS_ACCOUNT_ID, &osAccountId) != HC_SUCCESS) { - LOGE("Failed to get osAccountId!"); - return HC_ERR_JSON_GET; - } - int32_t signAlg; - if (GetIntFromJson(credInfo, FIELD_SIGN_ALG, &signAlg) != HC_SUCCESS) { - LOGE("get signAlg from json fail."); - return HC_ERR_JSON_ADD; - } - char *pkInfoStr = NULL; - int32_t res = GetRealPkInfoStr(osAccountId, credInfo, &pkInfoStr, &peerCert->isPseudonym); - if (res != HC_SUCCESS) { - LOGE("Failed to get real pkInfo string!"); - return res; - } - const char *pkInfoSignHexStr = GetStringFromJson(credInfo, FIELD_PK_INFO_SIGNATURE); - if (pkInfoSignHexStr == NULL) { - LOGE("get pkInfoSignature from json fail."); - HcFree(pkInfoStr); - return HC_ERR_JSON_GET; - } - res = BuildPeerCertInfo(pkInfoStr, pkInfoSignHexStr, signAlg, peerCert); - HcFree(pkInfoStr); - return res; -} - static int32_t GetCertCredInfo(SessionImpl *impl, const CJson *credInfo, IdentityInfo **selfCred) { int32_t res = CheckPeerPkInfoForPdid(impl->context, credInfo); @@ -667,36 +561,6 @@ static int32_t GetCertCredInfo(SessionImpl *impl, const CJson *credInfo, Identit return HC_SUCCESS; } -static int32_t GetSelfUserId(int32_t osAccountId, char *userId, uint32_t userIdLen) -{ - GroupEntryVec accountVec = CreateGroupEntryVec(); - QueryGroupParams queryParams = InitQueryGroupParams(); - queryParams.groupType = IDENTICAL_ACCOUNT_GROUP; - do { - if (QueryGroups(osAccountId, &queryParams, &accountVec) != HC_SUCCESS) { - LOGD("No identical-account group in db, no identical-account auth!"); - break; - } - uint32_t index = 0; - TrustedGroupEntry **ptr = NULL; - while (index < accountVec.size(&accountVec)) { - ptr = accountVec.getp(&accountVec, index); - if ((ptr == NULL) || (*ptr == NULL)) { - index++; - continue; - } - if (memcpy_s(userId, userIdLen, StringGet(&(*ptr)->userId), StringLength(&(*ptr)->userId)) != EOK) { - LOGE("copy fail"); - ClearGroupEntryVec(&accountVec); - return HC_ERROR; - } - index++; - } - } while (0); - ClearGroupEntryVec(&accountVec); - return HC_SUCCESS; -} - static int32_t GetSelfCredByInput(SessionImpl *impl, const CJson *inputData) { int32_t credType; @@ -722,49 +586,6 @@ static int32_t GetSelfCredByInput(SessionImpl *impl, const CJson *inputData) return HC_SUCCESS; } -static int32_t GetSaltMsg(Uint8Buff *saltMsg) -{ - uint8_t randomVal[DEV_SESSION_SALT_LEN] = { 0 }; - Uint8Buff random = { randomVal, DEV_SESSION_SALT_LEN }; - int32_t res = GetLoaderInstance()->generateRandom(&random); - if (res != HC_SUCCESS) { - LOGE("generate random failed, res: %d", res); - return res; - } - clock_t times = 0; - if (memcpy_s(saltMsg->val, saltMsg->length, random.val, random.length) != EOK) { - LOGE("memcpy random failed."); - return HC_ERR_MEMORY_COPY; - } - if (memcpy_s(saltMsg->val + random.length, saltMsg->length - random.length, ×, sizeof(clock_t)) != EOK) { - LOGE("memcpy times failed."); - return HC_ERR_MEMORY_COPY; - } - return HC_SUCCESS; -} - -static int32_t CalSalt(Uint8Buff *salt) -{ - uint32_t saltMsgLen = DEV_SESSION_SALT_LEN + sizeof(clock_t); - Uint8Buff saltMsg = { NULL, 0 }; - if (InitUint8Buff(&saltMsg, saltMsgLen) != HC_SUCCESS) { - LOGE("allocate saltMsg memory fail."); - return HC_ERR_ALLOC_MEMORY; - } - int32_t res = GetSaltMsg(&saltMsg); - if (res != HC_SUCCESS) { - FreeUint8Buff(&saltMsg); - return res; - } - res = GetLoaderInstance()->sha256(&saltMsg, salt); - FreeUint8Buff(&saltMsg); - if (res != HC_SUCCESS) { - LOGE("sha256 for session salt failed."); - return res; - } - return HC_SUCCESS; -} - static int32_t GenerateDevSessionSalt(SessionImpl *impl) { if (InitUint8Buff(&impl->salt, DEV_SESSION_SALT_LEN) != HC_SUCCESS) { @@ -1014,8 +835,8 @@ static int32_t CreateIsoSubSession(SessionImpl *impl, const IdentityInfo *cred, static int32_t CreateDlSpekeSubSession(SessionImpl *impl, const IdentityInfo *cred, AuthSubSession **returnSubSession) { - if (cred->proofType == CERTIFICATED) { - LOGE("Cert credential not support."); + if (impl->isCredAuth || cred->proofType == CERTIFICATED) { + LOGE("IS or Cert credential not support."); return HC_ERR_UNSUPPORTED_VERSION; } int32_t osAccountId; @@ -1197,22 +1018,6 @@ static int32_t AddAuthInfoToContextByDb(SessionImpl *impl, const char *selfUdid, return AddDevInfoToContext(impl, osAccountId, groupId, selfUdid); } -static bool IsPeerSameUserId(int32_t osAccountId, const char *peerUserId) -{ - GroupEntryVec groupVec = CreateGroupEntryVec(); - QueryGroupParams queryParams = InitQueryGroupParams(); - queryParams.groupType = IDENTICAL_ACCOUNT_GROUP; - if (QueryGroups(osAccountId, &queryParams, &groupVec) != HC_SUCCESS || groupVec.size(&groupVec) <= 0) { - LOGE("get identical account group from db fail."); - ClearGroupEntryVec(&groupVec); - return false; - } - TrustedGroupEntry *groupEntry = groupVec.get(&groupVec, 0); - bool isSame = (strcmp(StringGet(&(groupEntry->userId)), peerUserId) == 0); - ClearGroupEntryVec(&groupVec); - return isSame; -} - static int32_t AddAcrossAccountAuthInfoToContext(SessionImpl *impl, int32_t osAccountId, const char *peerUserId) { GroupEntryVec groupVec = CreateGroupEntryVec(); @@ -1288,6 +1093,25 @@ static int32_t AddAuthInfoToContextByCert(SessionImpl *impl) } } +static int32_t AddAuthInfoToContextIS(SessionImpl *impl, IdentityInfo *cred) +{ + if (cred->proofType == PRE_SHARED) { + return HC_SUCCESS; + } + char selfUdid[INPUT_UDID_LEN] = { 0 }; + int32_t res = HcGetUdid((uint8_t *)selfUdid, INPUT_UDID_LEN); + if (res != HC_SUCCESS) { + LOGE("Failed to get local udid!"); + return res; + } + PRINT_SENSITIVE_DATA("SelfUdid", selfUdid); + if (AddStringToJson(impl->context, FIELD_AUTH_ID, selfUdid) != HC_SUCCESS) { + LOGE("add selfAuthId to json fail."); + return HC_ERR_JSON_ADD; + } + return HC_SUCCESS; +} + static int32_t AddAuthInfoToContextByCred(SessionImpl *impl, IdentityInfo *cred) { char selfUdid[INPUT_UDID_LEN] = { 0 }; @@ -1361,7 +1185,8 @@ static int32_t ClientCreateAuthSubSessionByCred(SessionImpl *impl, IdentityInfo LOGE("The credential does not have a valid protocol."); return HC_ERR_UNSUPPORTED_VERSION; } - int32_t res = AddAuthInfoToContextByCred(impl, cred); + int32_t res = impl->isCredAuth? AddAuthInfoToContextIS(impl, cred) + : AddAuthInfoToContextByCred(impl, cred); if (res != HC_SUCCESS) { return res; } @@ -1376,11 +1201,30 @@ static int32_t ClientCreateAuthSubSessionByCred(SessionImpl *impl, IdentityInfo return HC_SUCCESS; } +static int32_t GetCredInfoIS(SessionImpl *impl) +{ + IdentityInfo *info = NULL; + int32_t res = GetIdentityInfoIS(impl->context, &info); + if (res != HC_SUCCESS) { + LOGE("Get Identity by credAuthInfo fail."); + return res; + } + if (impl->credList.pushBack(&impl->credList, (const IdentityInfo **)&info) == NULL) { + DestroyIdentityInfo(info); + LOGE("Failed to push protocol entity!"); + return HC_ERR_ALLOC_MEMORY; + } + impl->credCurIndex = 0; + impl->credTotalNum = 1; + return HC_SUCCESS; +} + static int32_t ProcStartEventInner(SessionImpl *impl, CJson *sessionMsg) { int32_t res; if (impl->credTotalNum == 0) { - res = GetAllCredsWithPeer(impl); + res = impl->isCredAuth ? GetCredInfoIS(impl) + : GetAllCredsWithPeer(impl); if (res != HC_SUCCESS) { LOGE("get all credentials with peer device fail."); return res; @@ -1445,6 +1289,11 @@ static int32_t GetSharedSecret(SessionImpl *impl, const CJson *inputData, Identi if (res != HC_SUCCESS) { return res; } + if (impl->isCredAuth && (!HasAccountPlugin())) { + LOGE("The account plugin used by IS is missing!"); + return HC_ERR_NOT_SUPPORT; + } + // verify and set psk "SHARED_KEY_ALIAS" res = GetSharedSecretByPeerCert(impl->context, &peerCert, impl->protocolEntity.protocolType, psk); DestroyCertInfo(&peerCert); return res; @@ -1489,7 +1338,8 @@ static int32_t ServerCreateAuthSubSessionByCred(SessionImpl *impl, const CJson * if (res != HC_SUCCESS) { return res; } - res = AddAuthInfoToContextByCred(impl, cred); + res = impl->isCredAuth? AddAuthInfoToContextIS(impl, cred) + : AddAuthInfoToContextByCred(impl, cred); if (res != HC_SUCCESS) { return res; } @@ -1738,7 +1588,7 @@ static int32_t ProcHandshakeReqEventInner(SessionImpl *impl, SessionEvent *input if (res != HC_SUCCESS) { return res; } - res = GetSelfCredByInput(impl, inputEvent->data); + res = impl->isCredAuth ? GetCredInfoIS(impl) : GetSelfCredByInput(impl, inputEvent->data); if (res != HC_SUCCESS) { LOGE("get cred by input fail."); return res; @@ -1750,9 +1600,11 @@ static int32_t ProcHandshakeReqEventInner(SessionImpl *impl, SessionEvent *input LOGE("Failed to add isDirectAuth to context!"); return HC_ERR_JSON_ADD; } - res = SetPeerAuthIdToContextIfNeeded(impl->context, selfCred); - if (res != HC_SUCCESS) { - return res; + if (!impl->isCredAuth) { + res = SetPeerAuthIdToContextIfNeeded(impl->context, selfCred); + if (res != HC_SUCCESS) { + return res; + } } res = CredNegotiate(impl, inputEvent->data, selfCred); if (res != HC_SUCCESS) { diff --git a/services/session_manager/src/session/v2/expand_sub_session/expand_process_lib/save_trusted_info.c b/services/session_manager/src/session/v2/expand_sub_session/expand_process_lib/save_trusted_info.c index b3d4d862af4c0b1eb2184925c995d0f682149aba..eeda7d03ad37a2384130d848d21e90f4d2583252 100644 --- a/services/session_manager/src/session/v2/expand_sub_session/expand_process_lib/save_trusted_info.c +++ b/services/session_manager/src/session/v2/expand_sub_session/expand_process_lib/save_trusted_info.c @@ -16,7 +16,7 @@ #include "save_trusted_info.h" #include "common_defs.h" -#include "data_manager.h" +#include "group_data_manager.h" #include "device_auth_defines.h" #include "hc_dev_info.h" #include "hc_log.h" diff --git a/test/fuzztest/authenticators/account_related/auth/isoauthtask_fuzzer/BUILD.gn b/test/fuzztest/authenticators/account_related/auth/isoauthtask_fuzzer/BUILD.gn index 6fa0ee5d6465bec7bd44fca50229ea7d9236ecf7..3e0a8b642c37bf7d98deaaffc3be9c913e9558c2 100644 --- a/test/fuzztest/authenticators/account_related/auth/isoauthtask_fuzzer/BUILD.gn +++ b/test/fuzztest/authenticators/account_related/auth/isoauthtask_fuzzer/BUILD.gn @@ -47,9 +47,11 @@ ohos_fuzztest("IsoAuthTaskFuzzTest") { } sources += hiview_adapter_files sources += identity_manager_files + sources += permission_adapter_files defines = deviceauth_defines defines += [ "HILOG_ENABLE" ] defines += [ "DEV_AUTH_HIVIEW_ENABLE" ] + defines += [ "DEV_AUTH_PERMISSION_ENABLE" ] cflags = [ "-g", "-O0", @@ -76,6 +78,7 @@ ohos_fuzztest("IsoAuthTaskFuzzTest") { } deps = [ "${deps_adapter_path}:${hal_module_test_name}" ] external_deps = [ + "access_token:libaccesstoken_sdk", "cJSON:cjson", "c_utils:utils", "dsoftbus:softbus_client", diff --git a/test/fuzztest/authenticators/account_unrelated/pake/standardexchangetask_fuzzer/BUILD.gn b/test/fuzztest/authenticators/account_unrelated/pake/standardexchangetask_fuzzer/BUILD.gn index 4e00371fa03bde345b4356336f6cc4263cd56c07..b48024ee9aeef60edc1e952043611283e643dabc 100644 --- a/test/fuzztest/authenticators/account_unrelated/pake/standardexchangetask_fuzzer/BUILD.gn +++ b/test/fuzztest/authenticators/account_unrelated/pake/standardexchangetask_fuzzer/BUILD.gn @@ -44,6 +44,8 @@ ohos_fuzztest("StandardExchangeTaskFuzzTest") { sources += deviceauth_files sources += identity_manager_files sources += permission_adapter_files + defines = [ "DEV_AUTH_PERMISSION_ENABLE" ] + if (support_os_account) { sources += account_subscriber_files sources += sa_subscriber_files diff --git a/test/fuzztest/creds_manager/credsmanager_fuzzer/BUILD.gn b/test/fuzztest/creds_manager/credsmanager_fuzzer/BUILD.gn index d474b854992a376c18b5083e1e486ee6aac14ada..0638fe349da540c2ad07b7883673ef086653a32b 100644 --- a/test/fuzztest/creds_manager/credsmanager_fuzzer/BUILD.gn +++ b/test/fuzztest/creds_manager/credsmanager_fuzzer/BUILD.gn @@ -32,6 +32,7 @@ ohos_fuzztest("CredsManagerFuzzTest") { "${inner_api_path}", "${frameworks_path}/inc/standard", "${tdd_framework_path}/common/inc", + "${dev_frameworks_path}/inc/permission_adapter", "${dev_frameworks_path}/inc/hiview_adapter", ] include_dirs += identity_manager_inc @@ -57,6 +58,7 @@ ohos_fuzztest("CredsManagerFuzzTest") { sources += [ "${key_management_adapter_path}/impl/src/common/mbedtls_ec_adapter.c", "${key_management_adapter_path}/impl/src/huks_adapter.c", + "${key_management_adapter_path}/impl/src/huks_adapter_utils.c", "${key_management_adapter_path}/impl/src/standard/crypto_hash_to_point.c", "${key_management_adapter_path}/impl/src/standard/huks_adapter_diff_impl.c", "${os_adapter_path}/impl/src/hc_log.c", diff --git a/test/fuzztest/devauth_fuzzer/BUILD.gn b/test/fuzztest/devauth_fuzzer/BUILD.gn index 3e3f7b36ccb8dbd16ce6af3ecdcde1a0cbc652bc..34b5fb0028c06907d03b3de095f6e88cd4fd2e9b 100644 --- a/test/fuzztest/devauth_fuzzer/BUILD.gn +++ b/test/fuzztest/devauth_fuzzer/BUILD.gn @@ -54,6 +54,7 @@ ohos_fuzztest("DevAuthFuzzTest") { defines = [ "HILOG_ENABLE" ] defines += [ "DEV_AUTH_HIVIEW_ENABLE" ] defines += [ "DEV_AUTH_FUZZ_TEST" ] + defines += [ "DEV_AUTH_PERMISSION_ENABLE" ] cflags = [ "-g", "-O0", diff --git a/test/fuzztest/devauthcb_fuzzer/BUILD.gn b/test/fuzztest/devauthcb_fuzzer/BUILD.gn index 4a79e0ba652d8a001251aa45a2bde92f1a4430e6..39a10635b562e971c07b85be111a6c2dc9202f15 100644 --- a/test/fuzztest/devauthcb_fuzzer/BUILD.gn +++ b/test/fuzztest/devauthcb_fuzzer/BUILD.gn @@ -36,6 +36,7 @@ ohos_fuzztest("DevAuthCbFuzzTest") { sources += permission_adapter_files defines = [ "HILOG_ENABLE" ] defines += [ "DEV_AUTH_HIVIEW_ENABLE" ] + defines += [ "DEV_AUTH_PERMISSION_ENABLE" ] defines += [ "DEV_AUTH_FUZZ_TEST" ] cflags = [ "-g", diff --git a/test/fuzztest/devauthfunc_fuzzer/BUILD.gn b/test/fuzztest/devauthfunc_fuzzer/BUILD.gn index 6cea50fca8ecf53331c6b3b90887a0c8fbe274a5..025d1645751aa7de8b181889164b866e48ecdb9d 100644 --- a/test/fuzztest/devauthfunc_fuzzer/BUILD.gn +++ b/test/fuzztest/devauthfunc_fuzzer/BUILD.gn @@ -31,6 +31,7 @@ ohos_fuzztest("DevAuthFuncFuzzTest") { ".", "../../unittest/deviceauth/include", "../../unittest/deviceauth/unit_test/include", + "${dev_frameworks_path}/inc/permission_adapter", "${dev_frameworks_path}/inc/hiview_adapter", ] @@ -39,6 +40,7 @@ ohos_fuzztest("DevAuthFuncFuzzTest") { sources += [ "${key_management_adapter_path}/impl/src/common/mbedtls_ec_adapter.c", "${key_management_adapter_path}/impl/src/huks_adapter.c", + "${key_management_adapter_path}/impl/src/huks_adapter_utils.c", "${key_management_adapter_path}/impl/src/standard/crypto_hash_to_point.c", "${key_management_adapter_path}/impl/src/standard/huks_adapter_diff_impl.c", "${os_adapter_path}/impl/src/hc_log.c", @@ -53,8 +55,11 @@ ohos_fuzztest("DevAuthFuncFuzzTest") { sources += dev_frameworks_files sources += deviceauth_common_files - sources += database_manager_files - sources += cred_manager_files + sources += identity_service_files + sources += cred_listener_files + sources += group_database_manager_files + sources += cred_database_manager_files + sources += ext_plugin_manager_files sources += session_manager_files sources += session_v1_files sources += session_v2_files diff --git a/test/fuzztest/device_auth_service/devauthservaddmembertogroup_fuzzer/BUILD.gn b/test/fuzztest/device_auth_service/devauthservaddmembertogroup_fuzzer/BUILD.gn index 3048a764957db0c0699d93b9cdb33cea8433a01e..e54ff933a75c35fa08756f03db94d511c4158114 100644 --- a/test/fuzztest/device_auth_service/devauthservaddmembertogroup_fuzzer/BUILD.gn +++ b/test/fuzztest/device_auth_service/devauthservaddmembertogroup_fuzzer/BUILD.gn @@ -27,6 +27,7 @@ ohos_fuzztest("DevAuthServAddMemberToGroupFuzzTest") { include_dirs = inc_path + hals_inc_path include_dirs += [ "${frameworks_path}/inc/standard", + "${dev_frameworks_path}/inc/permission_adapter", "${dev_frameworks_path}/inc/hiview_adapter", ] sources = [ "devauthservaddmembertogroup_fuzzer.cpp" ] diff --git a/test/fuzztest/device_auth_service/devauthservaddmultimemberstogroup_fuzzer/BUILD.gn b/test/fuzztest/device_auth_service/devauthservaddmultimemberstogroup_fuzzer/BUILD.gn index 39e7d3991568a7d7afb64e1e5dbe30fb5dfc7bb0..c4f381738e96109b506bf830000b088253fc5a01 100644 --- a/test/fuzztest/device_auth_service/devauthservaddmultimemberstogroup_fuzzer/BUILD.gn +++ b/test/fuzztest/device_auth_service/devauthservaddmultimemberstogroup_fuzzer/BUILD.gn @@ -27,6 +27,7 @@ ohos_fuzztest("DevAuthServAddMultiMembersToGroupFuzzTest") { include_dirs = inc_path + hals_inc_path include_dirs += [ "${frameworks_path}/inc/standard", + "${dev_frameworks_path}/inc/permission_adapter", "${dev_frameworks_path}/inc/hiview_adapter", ] sources = [ "devauthservaddmultimemberstogroup_fuzzer.cpp" ] diff --git a/test/fuzztest/device_auth_service/devauthservauthdevice_fuzzer/BUILD.gn b/test/fuzztest/device_auth_service/devauthservauthdevice_fuzzer/BUILD.gn index 1b9cf6b22c9fe6937a99ac7b58e5eb10b56b3b4a..c922e451fbeefe99c2f28c8295c3200f78f7bf13 100644 --- a/test/fuzztest/device_auth_service/devauthservauthdevice_fuzzer/BUILD.gn +++ b/test/fuzztest/device_auth_service/devauthservauthdevice_fuzzer/BUILD.gn @@ -27,6 +27,7 @@ ohos_fuzztest("DevAuthServAuthDeviceFuzzTest") { include_dirs = inc_path + hals_inc_path include_dirs += [ "${frameworks_path}/inc/standard", + "${dev_frameworks_path}/inc/permission_adapter", "${dev_frameworks_path}/inc/hiview_adapter", ] sources = [ "devauthservauthdevice_fuzzer.cpp" ] diff --git a/test/fuzztest/device_auth_service/devauthservcancelauthrequest_fuzzer/BUILD.gn b/test/fuzztest/device_auth_service/devauthservcancelauthrequest_fuzzer/BUILD.gn index d9c2ee11b995634236f2c1f03821cb4589d9dd63..0d2d16c1f2eda887c63b66fdf600db479db6c47f 100644 --- a/test/fuzztest/device_auth_service/devauthservcancelauthrequest_fuzzer/BUILD.gn +++ b/test/fuzztest/device_auth_service/devauthservcancelauthrequest_fuzzer/BUILD.gn @@ -27,6 +27,7 @@ ohos_fuzztest("DevAuthServCancelAuthRequestFuzzTest") { include_dirs = inc_path + hals_inc_path include_dirs += [ "${frameworks_path}/inc/standard", + "${dev_frameworks_path}/inc/permission_adapter", "${dev_frameworks_path}/inc/hiview_adapter", ] sources = [ "devauthservcancelauthrequest_fuzzer.cpp" ] diff --git a/test/fuzztest/device_auth_service/devauthservcancelbindrequest_fuzzer/BUILD.gn b/test/fuzztest/device_auth_service/devauthservcancelbindrequest_fuzzer/BUILD.gn index 96a95ac6cc58956fea0e62faf19949b25776fbf9..4a90719746fb1133b390384c0d4ea2e4f1647d2d 100644 --- a/test/fuzztest/device_auth_service/devauthservcancelbindrequest_fuzzer/BUILD.gn +++ b/test/fuzztest/device_auth_service/devauthservcancelbindrequest_fuzzer/BUILD.gn @@ -27,6 +27,7 @@ ohos_fuzztest("DevAuthServCancelBindRequestFuzzTest") { include_dirs = inc_path + hals_inc_path include_dirs += [ "${frameworks_path}/inc/standard", + "${dev_frameworks_path}/inc/permission_adapter", "${dev_frameworks_path}/inc/hiview_adapter", ] sources = [ "devauthservcancelbindrequest_fuzzer.cpp" ] diff --git a/test/fuzztest/device_auth_service/devauthservcheckaccesstogroup_fuzzer/BUILD.gn b/test/fuzztest/device_auth_service/devauthservcheckaccesstogroup_fuzzer/BUILD.gn index ada01b523b6dabeb9a9868a440eeb658e26337f9..1abba39b87f93f0d1f4040ed21d70f4a86a0ebeb 100644 --- a/test/fuzztest/device_auth_service/devauthservcheckaccesstogroup_fuzzer/BUILD.gn +++ b/test/fuzztest/device_auth_service/devauthservcheckaccesstogroup_fuzzer/BUILD.gn @@ -26,6 +26,7 @@ ohos_fuzztest("DevAuthServCheckAccessToGroupFuzzTest") { fuzz_config_file = "${deviceauth_path}/test/fuzztest/device_auth_service/devauthservcheckaccesstogroup_fuzzer" include_dirs = inc_path + hals_inc_path include_dirs += [ + "${dev_frameworks_path}/inc/permission_adapter", "${frameworks_path}/inc/standard", "${dev_frameworks_path}/inc/hiview_adapter", ] diff --git a/test/fuzztest/device_auth_service/devauthservcreategroup_fuzzer/BUILD.gn b/test/fuzztest/device_auth_service/devauthservcreategroup_fuzzer/BUILD.gn index 1929a2d646451b7264a8616c05b562d4330e704b..c0e6edb3393f795919a5a7b5e2c21774e0309b87 100644 --- a/test/fuzztest/device_auth_service/devauthservcreategroup_fuzzer/BUILD.gn +++ b/test/fuzztest/device_auth_service/devauthservcreategroup_fuzzer/BUILD.gn @@ -27,6 +27,7 @@ ohos_fuzztest("DevAuthServCreateGroupFuzzTest") { include_dirs = inc_path + hals_inc_path include_dirs += [ "${frameworks_path}/inc/standard", + "${dev_frameworks_path}/inc/permission_adapter", "${dev_frameworks_path}/inc/hiview_adapter", ] sources = [ "devauthservcreategroup_fuzzer.cpp" ] diff --git a/test/fuzztest/device_auth_service/devauthservdeletegroup_fuzzer/BUILD.gn b/test/fuzztest/device_auth_service/devauthservdeletegroup_fuzzer/BUILD.gn index 4c8973fc353c8b20368c522d9e41a60ff4e650b0..19463acd2d6c69c66fb7c62d11c2efc5fe631447 100644 --- a/test/fuzztest/device_auth_service/devauthservdeletegroup_fuzzer/BUILD.gn +++ b/test/fuzztest/device_auth_service/devauthservdeletegroup_fuzzer/BUILD.gn @@ -27,6 +27,7 @@ ohos_fuzztest("DevAuthServDeleteGroupFuzzTest") { include_dirs = inc_path + hals_inc_path include_dirs += [ "${frameworks_path}/inc/standard", + "${dev_frameworks_path}/inc/permission_adapter", "${dev_frameworks_path}/inc/hiview_adapter", ] sources = [ "devauthservdeletegroup_fuzzer.cpp" ] diff --git a/test/fuzztest/device_auth_service/devauthservdeletememberfromgroup_fuzzer/BUILD.gn b/test/fuzztest/device_auth_service/devauthservdeletememberfromgroup_fuzzer/BUILD.gn index d031074702a30c180a7d5253f2f139e19ba8b6e1..564ec372350cd19199437fbf532fe13fc0d7c71e 100644 --- a/test/fuzztest/device_auth_service/devauthservdeletememberfromgroup_fuzzer/BUILD.gn +++ b/test/fuzztest/device_auth_service/devauthservdeletememberfromgroup_fuzzer/BUILD.gn @@ -27,6 +27,7 @@ ohos_fuzztest("DevAuthServDeleteMemberFromGroupFuzzTest") { include_dirs = inc_path + hals_inc_path include_dirs += [ "${frameworks_path}/inc/standard", + "${dev_frameworks_path}/inc/permission_adapter", "${dev_frameworks_path}/inc/hiview_adapter", ] sources = [ "devauthservdeletememberfromgroup_fuzzer.cpp" ] diff --git a/test/fuzztest/device_auth_service/devauthservdeletemultimembersfromgroup_fuzzer/BUILD.gn b/test/fuzztest/device_auth_service/devauthservdeletemultimembersfromgroup_fuzzer/BUILD.gn index ed34ccf5107447270fcff47a8edac9109db1cbb8..0fc36667ae26aa3417833513266b4e5d6eb3e633 100644 --- a/test/fuzztest/device_auth_service/devauthservdeletemultimembersfromgroup_fuzzer/BUILD.gn +++ b/test/fuzztest/device_auth_service/devauthservdeletemultimembersfromgroup_fuzzer/BUILD.gn @@ -27,6 +27,7 @@ ohos_fuzztest("DevAuthServDeleteMultiMembersFromGroupFuzzTest") { include_dirs = inc_path + hals_inc_path include_dirs += [ "${frameworks_path}/inc/standard", + "${dev_frameworks_path}/inc/permission_adapter", "${dev_frameworks_path}/inc/hiview_adapter", ] sources = [ "devauthservdeletemultimembersfromgroup_fuzzer.cpp" ] diff --git a/test/fuzztest/device_auth_service/devauthservgetdeviceinfobyid_fuzzer/BUILD.gn b/test/fuzztest/device_auth_service/devauthservgetdeviceinfobyid_fuzzer/BUILD.gn index a96a879221445011c5156fef404393d4d8df3289..120baab7474b1eda420564a20383834a53b9df3c 100644 --- a/test/fuzztest/device_auth_service/devauthservgetdeviceinfobyid_fuzzer/BUILD.gn +++ b/test/fuzztest/device_auth_service/devauthservgetdeviceinfobyid_fuzzer/BUILD.gn @@ -27,6 +27,7 @@ ohos_fuzztest("DevAuthServGetDeviceInfoByIdFuzzTest") { include_dirs = inc_path + hals_inc_path include_dirs += [ "${frameworks_path}/inc/standard", + "${dev_frameworks_path}/inc/permission_adapter", "${dev_frameworks_path}/inc/hiview_adapter", ] sources = [ "devauthservgetdeviceinfobyid_fuzzer.cpp" ] diff --git a/test/fuzztest/device_auth_service/devauthservgetgroupinfo_fuzzer/BUILD.gn b/test/fuzztest/device_auth_service/devauthservgetgroupinfo_fuzzer/BUILD.gn index 9eab574671ad07678a2c2d27f925db2b878661c5..9e8bf848f7caf72795a1ab63a79363a88fae001c 100644 --- a/test/fuzztest/device_auth_service/devauthservgetgroupinfo_fuzzer/BUILD.gn +++ b/test/fuzztest/device_auth_service/devauthservgetgroupinfo_fuzzer/BUILD.gn @@ -27,6 +27,7 @@ ohos_fuzztest("DevAuthServGetGroupInfoFuzzTest") { include_dirs = inc_path + hals_inc_path include_dirs += [ "${frameworks_path}/inc/standard", + "${dev_frameworks_path}/inc/permission_adapter", "${dev_frameworks_path}/inc/hiview_adapter", ] sources = [ "devauthservgetgroupinfo_fuzzer.cpp" ] diff --git a/test/fuzztest/device_auth_service/devauthservgetgroupinfobyid_fuzzer/BUILD.gn b/test/fuzztest/device_auth_service/devauthservgetgroupinfobyid_fuzzer/BUILD.gn index 83121c6f25b6a2466b839f001fc4e5bc527ec1e2..f93c1f5727a750125b360bf9a8400ae73ed78a6e 100644 --- a/test/fuzztest/device_auth_service/devauthservgetgroupinfobyid_fuzzer/BUILD.gn +++ b/test/fuzztest/device_auth_service/devauthservgetgroupinfobyid_fuzzer/BUILD.gn @@ -27,6 +27,7 @@ ohos_fuzztest("DevAuthServGetGroupInfoByIdFuzzTest") { include_dirs = inc_path + hals_inc_path include_dirs += [ "${frameworks_path}/inc/standard", + "${dev_frameworks_path}/inc/permission_adapter", "${dev_frameworks_path}/inc/hiview_adapter", ] sources = [ "devauthservgetgroupinfobyid_fuzzer.cpp" ] diff --git a/test/fuzztest/device_auth_service/devauthservgetjoinedgroups_fuzzer/BUILD.gn b/test/fuzztest/device_auth_service/devauthservgetjoinedgroups_fuzzer/BUILD.gn index 03bdbc1d4e879334358c3b89077421cee7464e01..a9104c8abeafbbef6112ef9bfde316d504aee326 100644 --- a/test/fuzztest/device_auth_service/devauthservgetjoinedgroups_fuzzer/BUILD.gn +++ b/test/fuzztest/device_auth_service/devauthservgetjoinedgroups_fuzzer/BUILD.gn @@ -27,6 +27,7 @@ ohos_fuzztest("DevAuthServGetJoinedGroupsFuzzTest") { include_dirs = inc_path + hals_inc_path include_dirs += [ "${frameworks_path}/inc/standard", + "${dev_frameworks_path}/inc/permission_adapter", "${dev_frameworks_path}/inc/hiview_adapter", ] sources = [ "devauthservgetjoinedgroups_fuzzer.cpp" ] diff --git a/test/fuzztest/device_auth_service/devauthservgetpkinfolist_fuzzer/BUILD.gn b/test/fuzztest/device_auth_service/devauthservgetpkinfolist_fuzzer/BUILD.gn index cf253a9261652d47fc618e88975b308bf4f09423..88195369f3fa0ade39481c17a63c056da0ae8aa9 100644 --- a/test/fuzztest/device_auth_service/devauthservgetpkinfolist_fuzzer/BUILD.gn +++ b/test/fuzztest/device_auth_service/devauthservgetpkinfolist_fuzzer/BUILD.gn @@ -27,6 +27,7 @@ ohos_fuzztest("DevAuthServGetPkInfoListFuzzTest") { include_dirs = inc_path + hals_inc_path include_dirs += [ "${frameworks_path}/inc/standard", + "${dev_frameworks_path}/inc/permission_adapter", "${dev_frameworks_path}/inc/hiview_adapter", ] sources = [ "devauthservgetpkinfolist_fuzzer.cpp" ] diff --git a/test/fuzztest/device_auth_service/devauthservgetregisterinfo_fuzzer/BUILD.gn b/test/fuzztest/device_auth_service/devauthservgetregisterinfo_fuzzer/BUILD.gn index 472cd24d6924a9099be842c9260ebfb70ac6f5d9..c0b4582d5cbcf650824f63726afeeae40d9464cd 100644 --- a/test/fuzztest/device_auth_service/devauthservgetregisterinfo_fuzzer/BUILD.gn +++ b/test/fuzztest/device_auth_service/devauthservgetregisterinfo_fuzzer/BUILD.gn @@ -27,6 +27,7 @@ ohos_fuzztest("DevAuthServGetRegisterInfoFuzzTest") { include_dirs = inc_path + hals_inc_path include_dirs += [ "${frameworks_path}/inc/standard", + "${dev_frameworks_path}/inc/permission_adapter", "${dev_frameworks_path}/inc/hiview_adapter", ] sources = [ "devauthservgetregisterinfo_fuzzer.cpp" ] diff --git a/test/fuzztest/device_auth_service/devauthservgetrelatedgroups_fuzzer/BUILD.gn b/test/fuzztest/device_auth_service/devauthservgetrelatedgroups_fuzzer/BUILD.gn index e07a02bdb9658615bf0a315a0209242dec010e8f..bee3ced82240b01e9278fd5ddf6541747d846284 100644 --- a/test/fuzztest/device_auth_service/devauthservgetrelatedgroups_fuzzer/BUILD.gn +++ b/test/fuzztest/device_auth_service/devauthservgetrelatedgroups_fuzzer/BUILD.gn @@ -27,6 +27,7 @@ ohos_fuzztest("DevAuthServGetRelatedGroupsFuzzTest") { include_dirs = inc_path + hals_inc_path include_dirs += [ "${frameworks_path}/inc/standard", + "${dev_frameworks_path}/inc/permission_adapter", "${dev_frameworks_path}/inc/hiview_adapter", ] sources = [ "devauthservgetrelatedgroups_fuzzer.cpp" ] diff --git a/test/fuzztest/device_auth_service/devauthservgettrusteddevices_fuzzer/BUILD.gn b/test/fuzztest/device_auth_service/devauthservgettrusteddevices_fuzzer/BUILD.gn index 823231eb739d0ea1e81a9e81a1317460ef9fcf93..8f0e6c2b5fbcf355b0851a47f15a63c705250446 100644 --- a/test/fuzztest/device_auth_service/devauthservgettrusteddevices_fuzzer/BUILD.gn +++ b/test/fuzztest/device_auth_service/devauthservgettrusteddevices_fuzzer/BUILD.gn @@ -27,6 +27,7 @@ ohos_fuzztest("DevAuthServGetTrustedDevicesFuzzTest") { include_dirs = inc_path + hals_inc_path include_dirs += [ "${frameworks_path}/inc/standard", + "${dev_frameworks_path}/inc/permission_adapter", "${dev_frameworks_path}/inc/hiview_adapter", ] sources = [ "devauthservgettrusteddevices_fuzzer.cpp" ] diff --git a/test/fuzztest/device_auth_service/devauthservisdeviceingroup_fuzzer/BUILD.gn b/test/fuzztest/device_auth_service/devauthservisdeviceingroup_fuzzer/BUILD.gn index 646c161846cbcc7f4163b004b92f36bfa430c411..14b17be5895789c5873198e2ddb19f11bfbb2faa 100644 --- a/test/fuzztest/device_auth_service/devauthservisdeviceingroup_fuzzer/BUILD.gn +++ b/test/fuzztest/device_auth_service/devauthservisdeviceingroup_fuzzer/BUILD.gn @@ -27,6 +27,7 @@ ohos_fuzztest("DevAuthServIsDeviceInGroupFuzzTest") { include_dirs = inc_path + hals_inc_path include_dirs += [ "${frameworks_path}/inc/standard", + "${dev_frameworks_path}/inc/permission_adapter", "${dev_frameworks_path}/inc/hiview_adapter", ] sources = [ "devauthservisdeviceingroup_fuzzer.cpp" ] diff --git a/test/fuzztest/device_auth_service/devauthservprocessauthdata_fuzzer/BUILD.gn b/test/fuzztest/device_auth_service/devauthservprocessauthdata_fuzzer/BUILD.gn index 2be01315a3c70c1d0949400f17f07111e3d8c63b..d5652b6c78dd82b70c88a8ea8d754d51b7ff77ca 100644 --- a/test/fuzztest/device_auth_service/devauthservprocessauthdata_fuzzer/BUILD.gn +++ b/test/fuzztest/device_auth_service/devauthservprocessauthdata_fuzzer/BUILD.gn @@ -27,6 +27,7 @@ ohos_fuzztest("DevAuthServProcessAuthDataFuzzTest") { include_dirs = inc_path + hals_inc_path include_dirs += [ "${frameworks_path}/inc/standard", + "${dev_frameworks_path}/inc/permission_adapter", "${dev_frameworks_path}/inc/hiview_adapter", ] sources = [ "devauthservprocessauthdata_fuzzer.cpp" ] diff --git a/test/fuzztest/device_auth_service/devauthservprocessbinddata_fuzzer/BUILD.gn b/test/fuzztest/device_auth_service/devauthservprocessbinddata_fuzzer/BUILD.gn index 9280cbf54a80a79bb8db2b0581effc6be844c554..97490bb519510f4770702685b287dad072e1c2a8 100644 --- a/test/fuzztest/device_auth_service/devauthservprocessbinddata_fuzzer/BUILD.gn +++ b/test/fuzztest/device_auth_service/devauthservprocessbinddata_fuzzer/BUILD.gn @@ -27,6 +27,7 @@ ohos_fuzztest("DevAuthServProcessBindDataFuzzTest") { include_dirs = inc_path + hals_inc_path include_dirs += [ "${frameworks_path}/inc/standard", + "${dev_frameworks_path}/inc/permission_adapter", "${dev_frameworks_path}/inc/hiview_adapter", ] sources = [ "devauthservprocessbinddata_fuzzer.cpp" ] diff --git a/test/fuzztest/device_auth_service/devauthservregcallback_fuzzer/BUILD.gn b/test/fuzztest/device_auth_service/devauthservregcallback_fuzzer/BUILD.gn index 7740199853c216b4107de1520c58a604f5529042..d6e295b99f9dcb3f7c65c96f14dee6b1e4b51907 100644 --- a/test/fuzztest/device_auth_service/devauthservregcallback_fuzzer/BUILD.gn +++ b/test/fuzztest/device_auth_service/devauthservregcallback_fuzzer/BUILD.gn @@ -27,6 +27,7 @@ ohos_fuzztest("DevAuthServRegCallbackFuzzTest") { include_dirs = inc_path + hals_inc_path include_dirs += [ "${frameworks_path}/inc/standard", + "${dev_frameworks_path}/inc/permission_adapter", "${dev_frameworks_path}/inc/hiview_adapter", ] sources = [ "devauthservregcallback_fuzzer.cpp" ] diff --git a/test/fuzztest/device_auth_service/devauthservregdatachangelistener_fuzzer/BUILD.gn b/test/fuzztest/device_auth_service/devauthservregdatachangelistener_fuzzer/BUILD.gn index b624c18f52624f3cfa3bb42df5db802bc9f9140c..f22b3b03ebf2819dc30db15ef6fc6b4d81a32771 100644 --- a/test/fuzztest/device_auth_service/devauthservregdatachangelistener_fuzzer/BUILD.gn +++ b/test/fuzztest/device_auth_service/devauthservregdatachangelistener_fuzzer/BUILD.gn @@ -27,6 +27,7 @@ ohos_fuzztest("DevAuthServRegDataChangeListenerFuzzTest") { include_dirs = inc_path + hals_inc_path include_dirs += [ "${frameworks_path}/inc/standard", + "${dev_frameworks_path}/inc/permission_adapter", "${dev_frameworks_path}/inc/hiview_adapter", ] sources = [ "devauthservregdatachangelistener_fuzzer.cpp" ] diff --git a/test/fuzztest/device_auth_service/devauthservunregcallback_fuzzer/BUILD.gn b/test/fuzztest/device_auth_service/devauthservunregcallback_fuzzer/BUILD.gn index a74da57afcbd34c8b33ae88e73b90fd51c284580..9b72777134dd5f9fdbb7f153935de64d6b6dd1a1 100644 --- a/test/fuzztest/device_auth_service/devauthservunregcallback_fuzzer/BUILD.gn +++ b/test/fuzztest/device_auth_service/devauthservunregcallback_fuzzer/BUILD.gn @@ -27,6 +27,7 @@ ohos_fuzztest("DevAuthServUnregCallbackFuzzTest") { include_dirs = inc_path + hals_inc_path include_dirs += [ "${frameworks_path}/inc/standard", + "${dev_frameworks_path}/inc/permission_adapter", "${dev_frameworks_path}/inc/hiview_adapter", ] sources = [ "devauthservunregcallback_fuzzer.cpp" ] diff --git a/test/fuzztest/device_auth_service/devauthservunregdatachangelistener_fuzzer/BUILD.gn b/test/fuzztest/device_auth_service/devauthservunregdatachangelistener_fuzzer/BUILD.gn index 88b13742f2a66244e0f95f6debfbd2a1cd899cec..43e0ae91e5d770a012a05e9eb4beb8be001feb71 100644 --- a/test/fuzztest/device_auth_service/devauthservunregdatachangelistener_fuzzer/BUILD.gn +++ b/test/fuzztest/device_auth_service/devauthservunregdatachangelistener_fuzzer/BUILD.gn @@ -27,6 +27,7 @@ ohos_fuzztest("DevAuthServUnregDataChangeListenerFuzzTest") { include_dirs = inc_path + hals_inc_path include_dirs += [ "${frameworks_path}/inc/standard", + "${dev_frameworks_path}/inc/permission_adapter", "${dev_frameworks_path}/inc/hiview_adapter", ] sources = [ "devauthservunregdatachangelistener_fuzzer.cpp" ] diff --git a/test/fuzztest/group_auth/account_related/accountrelatedgroupauth_fuzzer/BUILD.gn b/test/fuzztest/group_auth/account_related/accountrelatedgroupauth_fuzzer/BUILD.gn index 6be5aad3756c4c3c2195b9cbe9b9d1ffa81e02bc..386a64738e9e4818600da2072f6223f0ceb2f403 100644 --- a/test/fuzztest/group_auth/account_related/accountrelatedgroupauth_fuzzer/BUILD.gn +++ b/test/fuzztest/group_auth/account_related/accountrelatedgroupauth_fuzzer/BUILD.gn @@ -31,6 +31,7 @@ ohos_fuzztest("AccountRelatedGroupAuthFuzzTest") { include_dirs += [ ".", + "${dev_frameworks_path}/inc/permission_adapter", "${dev_frameworks_path}/inc/hiview_adapter", ] if (support_os_account) { @@ -42,6 +43,7 @@ ohos_fuzztest("AccountRelatedGroupAuthFuzzTest") { sources += [ "${key_management_adapter_path}/impl/src/common/mbedtls_ec_adapter.c", "${key_management_adapter_path}/impl/src/huks_adapter.c", + "${key_management_adapter_path}/impl/src/huks_adapter_utils.c", "${key_management_adapter_path}/impl/src/standard/crypto_hash_to_point.c", "${key_management_adapter_path}/impl/src/standard/huks_adapter_diff_impl.c", "${os_adapter_path}/impl/src/hc_log.c", @@ -57,9 +59,12 @@ ohos_fuzztest("AccountRelatedGroupAuthFuzzTest") { sources += identity_manager_files sources += dev_frameworks_files sources += deviceauth_common_files - sources += database_manager_files - sources += cred_manager_files + sources += group_database_manager_files + sources += cred_database_manager_files + sources += ext_plugin_manager_files sources += session_manager_files + sources += identity_service_files + sources += cred_listener_files sources += session_v1_files sources += session_v2_files sources += iso_protocol_files diff --git a/test/fuzztest/group_auth/account_related/accountrelatedgroupauth_fuzzer/accountrelatedgroupauth_fuzzer.cpp b/test/fuzztest/group_auth/account_related/accountrelatedgroupauth_fuzzer/accountrelatedgroupauth_fuzzer.cpp index 642220984258fee941c8e1f0c03531c88b3a48dc..a16380fc0776708d426305b863e06131afa7ce15 100644 --- a/test/fuzztest/group_auth/account_related/accountrelatedgroupauth_fuzzer/accountrelatedgroupauth_fuzzer.cpp +++ b/test/fuzztest/group_auth/account_related/accountrelatedgroupauth_fuzzer/accountrelatedgroupauth_fuzzer.cpp @@ -25,7 +25,7 @@ #include "hc_string.h" #include "group_auth_data_operation.h" #include "account_related_group_auth.h" -#include "data_manager.h" +#include "group_data_manager.h" namespace OHOS { #define NUM_TWO 2 diff --git a/test/fuzztest/group_manage/groupoperationcommon_fuzzer/BUILD.gn b/test/fuzztest/group_manage/groupoperationcommon_fuzzer/BUILD.gn index f1637153bbf73dfcb276a3a4cbf901800f95e881..485759e59bd26b81c209720b0b467a4b2683f290 100644 --- a/test/fuzztest/group_manage/groupoperationcommon_fuzzer/BUILD.gn +++ b/test/fuzztest/group_manage/groupoperationcommon_fuzzer/BUILD.gn @@ -31,6 +31,7 @@ ohos_fuzztest("GroupOperationCommonFuzzTest") { "${inner_api_path}", "${frameworks_path}/inc/standard", "${tdd_framework_path}/common/inc", + "${dev_frameworks_path}/inc/permission_adapter", "${dev_frameworks_path}/inc/hiview_adapter", ] include_dirs += identity_manager_inc @@ -54,6 +55,7 @@ ohos_fuzztest("GroupOperationCommonFuzzTest") { sources += [ "${key_management_adapter_path}/impl/src/common/mbedtls_ec_adapter.c", "${key_management_adapter_path}/impl/src/huks_adapter.c", + "${key_management_adapter_path}/impl/src/huks_adapter_utils.c", "${key_management_adapter_path}/impl/src/standard/crypto_hash_to_point.c", "${key_management_adapter_path}/impl/src/standard/huks_adapter_diff_impl.c", "${os_adapter_path}/impl/src/hc_log.c", diff --git a/test/fuzztest/group_manage/groupoperationcommon_fuzzer/groupoperationcommon_fuzzer.cpp b/test/fuzztest/group_manage/groupoperationcommon_fuzzer/groupoperationcommon_fuzzer.cpp index b1f7a1482d494a705c6171f13044246c96ee3dc7..2e2008af31277f309784a7823db3e69456f1d3e8 100644 --- a/test/fuzztest/group_manage/groupoperationcommon_fuzzer/groupoperationcommon_fuzzer.cpp +++ b/test/fuzztest/group_manage/groupoperationcommon_fuzzer/groupoperationcommon_fuzzer.cpp @@ -22,7 +22,7 @@ #include "hc_dev_info.h" #include "json_utils.h" #include "securec.h" -#include "data_manager.h" +#include "group_data_manager.h" namespace OHOS { static const char *NORMAL_STR = "abc"; diff --git a/test/fuzztest/protocol/dlspeke_fuzzer/BUILD.gn b/test/fuzztest/protocol/dlspeke_fuzzer/BUILD.gn index 914039643c83b614b07792f1cc47620789fe3639..793bcb66b91244e4d97864fec8059396afda3191 100644 --- a/test/fuzztest/protocol/dlspeke_fuzzer/BUILD.gn +++ b/test/fuzztest/protocol/dlspeke_fuzzer/BUILD.gn @@ -43,6 +43,7 @@ ohos_fuzztest("DLSpekeFuzzTest") { defines = [ "ENABLE_P2P_BIND_DL_SPEKE" ] defines += [ "HILOG_ENABLE" ] defines += [ "DEV_AUTH_HIVIEW_ENABLE" ] + defines += [ "DEV_AUTH_PERMISSION_ENABLE" ] defines += [ "DEV_AUTH_FUZZ_TEST" ] cflags = [ "-g", diff --git a/test/fuzztest/protocol/ecspeke_fuzzer/BUILD.gn b/test/fuzztest/protocol/ecspeke_fuzzer/BUILD.gn index 4ca8dd24d6cea29a1dad0fb517d424b269009ad4..7d4a95e32f980942f483ac0281114d9ca4d51591 100644 --- a/test/fuzztest/protocol/ecspeke_fuzzer/BUILD.gn +++ b/test/fuzztest/protocol/ecspeke_fuzzer/BUILD.gn @@ -43,6 +43,7 @@ ohos_fuzztest("ECSpekeFuzzTest") { defines = [ "ENABLE_EC_SPEKE" ] defines += [ "HILOG_ENABLE" ] defines += [ "DEV_AUTH_HIVIEW_ENABLE" ] + defines += [ "DEV_AUTH_PERMISSION_ENABLE" ] defines += [ "DEV_AUTH_FUZZ_TEST" ] cflags = [ "-g", diff --git a/test/fuzztest/protocol/iso_fuzzer/BUILD.gn b/test/fuzztest/protocol/iso_fuzzer/BUILD.gn index 9b33805d2c7080db0c97ec7a61e550b34f26d517..63aabd591ca51300be764a4be4835e3daccd7b27 100644 --- a/test/fuzztest/protocol/iso_fuzzer/BUILD.gn +++ b/test/fuzztest/protocol/iso_fuzzer/BUILD.gn @@ -42,6 +42,7 @@ ohos_fuzztest("IsoFuzzTest") { defines = [ "ENABLE_ISO" ] defines += [ "HILOG_ENABLE" ] + defines += [ "DEV_AUTH_PERMISSION_ENABLE" ] defines += [ "DEV_AUTH_HIVIEW_ENABLE" ] defines += [ "DEV_AUTH_FUZZ_TEST" ] cflags = [ diff --git a/test/fuzztest/session_manager/session/v2/auth_sub_session/authsubsession_fuzzer/BUILD.gn b/test/fuzztest/session_manager/session/v2/auth_sub_session/authsubsession_fuzzer/BUILD.gn index d20ebadaa42c074f0bbee9cbc4bd58078e14425f..777142dea9acf6f109c2c918f6388026a76fc9d8 100644 --- a/test/fuzztest/session_manager/session/v2/auth_sub_session/authsubsession_fuzzer/BUILD.gn +++ b/test/fuzztest/session_manager/session/v2/auth_sub_session/authsubsession_fuzzer/BUILD.gn @@ -56,7 +56,7 @@ ohos_fuzztest("AuthSubSessionFuzzTest") { "${dev_frameworks_path}/inc/os_account_adapter", "${dev_frameworks_path}/inc/plugin_adapter", "${protocol_path}/inc/pake_protocol", - "${data_manager_path}/inc", + "${group_data_manager_path}/inc", "${session_manager_path}/inc/session/v1", "${session_manager_path}/inc/session/v1/compatible_auth_sub_session", "${group_auth_path}/inc/account_related_group_auth", @@ -70,8 +70,8 @@ ohos_fuzztest("AuthSubSessionFuzzTest") { "${group_manager_path}/inc/broadcast_manager", "${privacy_enhancement_path}/inc", "${mk_agree_path}/inc", - "${services_path}/cred_manager/inc/account_related", - "${services_path}/cred_manager/inc", + "${services_path}/ext_plugin_manager/inc/account_related", + "${services_path}/ext_plugin_manager/inc", "${protocol_path}/inc", "${session_manager_path}/inc/session/v2/auth_sub_session/protocol_lib", ] @@ -84,7 +84,6 @@ ohos_fuzztest("AuthSubSessionFuzzTest") { "${authenticators_path}/src/account_related/creds_manager/sym_token_manager.c", "${authenticators_path}/src/account_unrelated/common/das_task_common.c", "${authenticators_path}/src/account_unrelated/creds_manager/das_standard_token_manager.c", - "${data_manager_path}/src/data_manager.c", "${deps_adapter_path}/os_adapter/impl/src/linux/hc_types.c", "${dev_frameworks_path}/src/account_task_manager/account_task_manager.c", "${dev_frameworks_path}/src/os_account_adapter_mock/os_account_adapter_mock.cpp", @@ -92,6 +91,7 @@ ohos_fuzztest("AuthSubSessionFuzzTest") { "${dev_frameworks_path}/src/security_label_adapter_mock/security_label_adapter_mock.c", "${deviceauth_account_group_auth_path}/src/group_auth_manager/account_related_group_auth/account_related_group_auth.c", "${group_auth_path}/src/group_auth_manager/group_auth_common/group_auth_data_operation.c", + "${group_data_manager_path}/src/group_data_manager.c", "${group_manager_path}/src/broadcast_manager_mock/broadcast_manager_mock.c", "${group_manager_path}/src/group_operation/group_operation_common/group_operation_common.c", "${identity_manager_path}/src/cert_operation.c", diff --git a/test/fuzztest/session_manager/session/v2/expand_sub_session/expand_process_lib/authcodeimport_fuzzer/BUILD.gn b/test/fuzztest/session_manager/session/v2/expand_sub_session/expand_process_lib/authcodeimport_fuzzer/BUILD.gn index 34d559cc0842b068c3575de9a98cdabcdc37f5a2..6c87ed7b06dca0ac3a26d744e4d1f9976326d05f 100644 --- a/test/fuzztest/session_manager/session/v2/expand_sub_session/expand_process_lib/authcodeimport_fuzzer/BUILD.gn +++ b/test/fuzztest/session_manager/session/v2/expand_sub_session/expand_process_lib/authcodeimport_fuzzer/BUILD.gn @@ -52,7 +52,7 @@ ohos_fuzztest("AuthCodeImportFuzzTest") { "${dev_frameworks_path}/inc/os_account_adapter", "${dev_frameworks_path}/inc/plugin_adapter", "${protocol_path}/inc/pake_protocol", - "${data_manager_path}/inc", + "${group_data_manager_path}/inc", "${session_manager_path}/inc/session/v1", "${session_manager_path}/inc/session/v1/compatible_auth_sub_session", "${group_auth_path}/inc/account_related_group_auth", @@ -66,8 +66,8 @@ ohos_fuzztest("AuthCodeImportFuzzTest") { "${group_manager_path}/inc/broadcast_manager", "${privacy_enhancement_path}/inc", "${mk_agree_path}/inc", - "${services_path}/cred_manager/inc/account_related", - "${services_path}/cred_manager/inc", + "${services_path}/ext_plugin_manager/inc/account_related", + "${services_path}/ext_plugin_manager/inc", "${protocol_path}/inc", ] sources += identity_manager_files @@ -77,7 +77,6 @@ ohos_fuzztest("AuthCodeImportFuzzTest") { "${authenticators_path}/src/account_related/creds_manager/sym_token_manager.c", "${authenticators_path}/src/account_unrelated/common/das_task_common.c", "${authenticators_path}/src/account_unrelated/creds_manager/das_standard_token_manager.c", - "${data_manager_path}/src/data_manager.c", "${deps_adapter_path}/os_adapter/impl/src/linux/hc_types.c", "${dev_frameworks_path}/src/account_task_manager/account_task_manager.c", "${dev_frameworks_path}/src/os_account_adapter_mock/os_account_adapter_mock.cpp", @@ -85,6 +84,7 @@ ohos_fuzztest("AuthCodeImportFuzzTest") { "${dev_frameworks_path}/src/security_label_adapter_mock/security_label_adapter_mock.c", "${deviceauth_account_group_auth_path}/src/group_auth_manager/account_related_group_auth/account_related_group_auth.c", "${group_auth_path}/src/group_auth_manager/group_auth_common/group_auth_data_operation.c", + "${group_data_manager_path}/src/group_data_manager.c", "${group_manager_path}/src/broadcast_manager_mock/broadcast_manager_mock.c", "${group_manager_path}/src/group_operation/group_operation_common/group_operation_common.c", "${identity_manager_path}/src/cert_operation.c", diff --git a/test/fuzztest/session_manager/session/v2/expand_sub_session/expand_process_lib/pubkeyexchange_fuzzer/BUILD.gn b/test/fuzztest/session_manager/session/v2/expand_sub_session/expand_process_lib/pubkeyexchange_fuzzer/BUILD.gn index 0a5d7e17a4aad091f2a01f625b4efdb542375026..6579a37aae5ae6b8bb68593b81f834041a0a1145 100644 --- a/test/fuzztest/session_manager/session/v2/expand_sub_session/expand_process_lib/pubkeyexchange_fuzzer/BUILD.gn +++ b/test/fuzztest/session_manager/session/v2/expand_sub_session/expand_process_lib/pubkeyexchange_fuzzer/BUILD.gn @@ -55,7 +55,7 @@ ohos_fuzztest("PubkeyExchangeFuzzTest") { "${dev_frameworks_path}/inc/os_account_adapter", "${dev_frameworks_path}/inc/plugin_adapter", "${protocol_path}/inc/pake_protocol", - "${data_manager_path}/inc", + "${group_data_manager_path}/inc", "${session_manager_path}/inc/session/v1", "${session_manager_path}/inc/session/v1/compatible_auth_sub_session", "${group_auth_path}/inc/account_related_group_auth", @@ -69,8 +69,8 @@ ohos_fuzztest("PubkeyExchangeFuzzTest") { "${group_manager_path}/inc/broadcast_manager", "${privacy_enhancement_path}/inc", "${mk_agree_path}/inc", - "${services_path}/cred_manager/inc/account_related", - "${services_path}/cred_manager/inc", + "${services_path}/ext_plugin_manager/inc/account_related", + "${services_path}/ext_plugin_manager/inc", "${protocol_path}/inc", ] sources += identity_manager_files @@ -80,7 +80,6 @@ ohos_fuzztest("PubkeyExchangeFuzzTest") { "${authenticators_path}/src/account_related/creds_manager/sym_token_manager.c", "${authenticators_path}/src/account_unrelated/common/das_task_common.c", "${authenticators_path}/src/account_unrelated/creds_manager/das_standard_token_manager.c", - "${data_manager_path}/src/data_manager.c", "${deps_adapter_path}/os_adapter/impl/src/linux/hc_types.c", "${dev_frameworks_path}/src/account_task_manager/account_task_manager.c", "${dev_frameworks_path}/src/os_account_adapter_mock/os_account_adapter_mock.cpp", @@ -88,6 +87,7 @@ ohos_fuzztest("PubkeyExchangeFuzzTest") { "${dev_frameworks_path}/src/security_label_adapter_mock/security_label_adapter_mock.c", "${deviceauth_account_group_auth_path}/src/group_auth_manager/account_related_group_auth/account_related_group_auth.c", "${group_auth_path}/src/group_auth_manager/group_auth_common/group_auth_data_operation.c", + "${group_data_manager_path}/src/group_data_manager.c", "${group_manager_path}/src/broadcast_manager_mock/broadcast_manager_mock.c", "${group_manager_path}/src/group_operation/group_operation_common/group_operation_common.c", "${identity_manager_path}/src/cert_operation.c", diff --git a/test/fuzztest/session_manager/session/v2/expand_sub_session/expand_process_lib/savetrustedinfo_fuzzer/BUILD.gn b/test/fuzztest/session_manager/session/v2/expand_sub_session/expand_process_lib/savetrustedinfo_fuzzer/BUILD.gn index aa005f25c13b1d63e2d9ccc26174ff02e281834f..feeb1aff9f7d3dec89dd41b3c3ef4735b869a211 100644 --- a/test/fuzztest/session_manager/session/v2/expand_sub_session/expand_process_lib/savetrustedinfo_fuzzer/BUILD.gn +++ b/test/fuzztest/session_manager/session/v2/expand_sub_session/expand_process_lib/savetrustedinfo_fuzzer/BUILD.gn @@ -53,7 +53,7 @@ ohos_fuzztest("SaveTrustedInfoFuzzTest") { "${dev_frameworks_path}/inc/os_account_adapter", "${dev_frameworks_path}/inc/plugin_adapter", "${protocol_path}/inc/pake_protocol", - "${data_manager_path}/inc", + "${group_data_manager_path}/inc", "${session_manager_path}/inc/session/v1", "${session_manager_path}/inc/session/v1/compatible_auth_sub_session", "${group_auth_path}/inc/account_related_group_auth", @@ -67,8 +67,8 @@ ohos_fuzztest("SaveTrustedInfoFuzzTest") { "${group_manager_path}/inc/broadcast_manager", "${privacy_enhancement_path}/inc", "${mk_agree_path}/inc", - "${services_path}/cred_manager/inc/account_related", - "${services_path}/cred_manager/inc", + "${services_path}/ext_plugin_manager/inc/account_related", + "${services_path}/ext_plugin_manager/inc", "${protocol_path}/inc", ] sources += identity_manager_files @@ -79,7 +79,6 @@ ohos_fuzztest("SaveTrustedInfoFuzzTest") { "${authenticators_path}/src/account_related/creds_manager/sym_token_manager.c", "${authenticators_path}/src/account_unrelated/common/das_task_common.c", "${authenticators_path}/src/account_unrelated/creds_manager/das_standard_token_manager.c", - "${data_manager_path}/src/data_manager.c", "${deps_adapter_path}/os_adapter/impl/src/linux/hc_types.c", "${dev_frameworks_path}/src/account_task_manager/account_task_manager.c", "${dev_frameworks_path}/src/os_account_adapter_mock/os_account_adapter_mock.cpp", @@ -87,6 +86,7 @@ ohos_fuzztest("SaveTrustedInfoFuzzTest") { "${dev_frameworks_path}/src/security_label_adapter_mock/security_label_adapter_mock.c", "${deviceauth_account_group_auth_path}/src/group_auth_manager/account_related_group_auth/account_related_group_auth.c", "${group_auth_path}/src/group_auth_manager/group_auth_common/group_auth_data_operation.c", + "${group_data_manager_path}/src/group_data_manager.c", "${group_manager_path}/src/broadcast_manager_mock/broadcast_manager_mock.c", "${group_manager_path}/src/group_operation/group_operation_common/group_operation_common.c", "${identity_manager_path}/src/cert_operation.c", diff --git a/test/fuzztest/session_manager/session/v2/expand_sub_session/expand_process_lib/savetrustedinfo_fuzzer/savetrustedinfo_fuzzer.cpp b/test/fuzztest/session_manager/session/v2/expand_sub_session/expand_process_lib/savetrustedinfo_fuzzer/savetrustedinfo_fuzzer.cpp index a7e14ab019322cf3dafb25069058a62e8d1c0487..e9274032b00f29cb9ba806ef35adbbc4104f5171 100644 --- a/test/fuzztest/session_manager/session/v2/expand_sub_session/expand_process_lib/savetrustedinfo_fuzzer/savetrustedinfo_fuzzer.cpp +++ b/test/fuzztest/session_manager/session/v2/expand_sub_session/expand_process_lib/savetrustedinfo_fuzzer/savetrustedinfo_fuzzer.cpp @@ -17,7 +17,7 @@ #include "device_auth_defines.h" #include "common_defs.h" -#include "data_manager.h" +#include "group_data_manager.h" #include "device_auth.h" #include "hc_types.h" #include "hc_dev_info.h" diff --git a/test/fuzztest/session_manager/session/v2/expand_sub_session/expandsubsession_fuzzer/BUILD.gn b/test/fuzztest/session_manager/session/v2/expand_sub_session/expandsubsession_fuzzer/BUILD.gn index 795b701292c50ff533ca0a4203954742c23684fe..d42eea882aa8a09817d188f9363a9f9f1433e957 100644 --- a/test/fuzztest/session_manager/session/v2/expand_sub_session/expandsubsession_fuzzer/BUILD.gn +++ b/test/fuzztest/session_manager/session/v2/expand_sub_session/expandsubsession_fuzzer/BUILD.gn @@ -59,7 +59,7 @@ ohos_fuzztest("ExpandSubSessionFuzzTest") { "${dev_frameworks_path}/inc/os_account_adapter", "${dev_frameworks_path}/inc/plugin_adapter", "${protocol_path}/inc/pake_protocol", - "${data_manager_path}/inc", + "${group_data_manager_path}/inc", "${session_manager_path}/inc/session/v1", "${session_manager_path}/inc/session/v1/compatible_auth_sub_session", "${group_auth_path}/inc/account_related_group_auth", @@ -73,8 +73,8 @@ ohos_fuzztest("ExpandSubSessionFuzzTest") { "${group_manager_path}/inc/broadcast_manager", "${privacy_enhancement_path}/inc", "${mk_agree_path}/inc", - "${services_path}/cred_manager/inc/account_related", - "${services_path}/cred_manager/inc", + "${services_path}/ext_plugin_manager/inc/account_related", + "${services_path}/ext_plugin_manager/inc", "${protocol_path}/inc", ] sources += identity_manager_files @@ -84,7 +84,6 @@ ohos_fuzztest("ExpandSubSessionFuzzTest") { "${authenticators_path}/src/account_related/creds_manager/sym_token_manager.c", "${authenticators_path}/src/account_unrelated/common/das_task_common.c", "${authenticators_path}/src/account_unrelated/creds_manager/das_standard_token_manager.c", - "${data_manager_path}/src/data_manager.c", "${deps_adapter_path}/os_adapter/impl/src/linux/hc_types.c", "${dev_frameworks_path}/src/account_task_manager/account_task_manager.c", "${dev_frameworks_path}/src/os_account_adapter_mock/os_account_adapter_mock.cpp", @@ -92,6 +91,7 @@ ohos_fuzztest("ExpandSubSessionFuzzTest") { "${dev_frameworks_path}/src/security_label_adapter_mock/security_label_adapter_mock.c", "${deviceauth_account_group_auth_path}/src/group_auth_manager/account_related_group_auth/account_related_group_auth.c", "${group_auth_path}/src/group_auth_manager/group_auth_common/group_auth_data_operation.c", + "${group_data_manager_path}/src/group_data_manager.c", "${group_manager_path}/src/broadcast_manager_mock/broadcast_manager_mock.c", "${group_manager_path}/src/group_operation/group_operation_common/group_operation_common.c", "${identity_manager_path}/src/cert_operation.c", diff --git a/test/unittest/deviceauth/BUILD.gn b/test/unittest/deviceauth/BUILD.gn index 38eb15336d76b30813ff349996e5c256602f9ee4..a7dba50c6aad6de66fa2c2882f61c15a410f90c0 100644 --- a/test/unittest/deviceauth/BUILD.gn +++ b/test/unittest/deviceauth/BUILD.gn @@ -27,6 +27,7 @@ ohos_unittest("deviceauth_llt") { include_dirs += [ "./include", "./unit_test/include", + "${dev_frameworks_path}/inc/permission_adapter", "${dev_frameworks_path}/inc/hiview_adapter", ] @@ -37,6 +38,7 @@ ohos_unittest("deviceauth_llt") { sources += [ "${key_management_adapter_path}/impl/src/common/mbedtls_ec_adapter.c", "${key_management_adapter_path}/impl/src/huks_adapter.c", + "${key_management_adapter_path}/impl/src/huks_adapter_utils.c", "${key_management_adapter_path}/impl/src/standard/crypto_hash_to_point.c", "${key_management_adapter_path}/impl/src/standard/huks_adapter_diff_impl.c", "${os_adapter_path}/impl/src/hc_log.c", @@ -51,8 +53,11 @@ ohos_unittest("deviceauth_llt") { sources += dev_frameworks_files sources += deviceauth_common_files - sources += database_manager_files - sources += cred_manager_files + sources += group_database_manager_files + sources += cred_database_manager_files + sources += cred_listener_files + sources += identity_service_files + sources += ext_plugin_manager_files sources += session_manager_files sources += session_v1_files sources += session_v2_mock_files @@ -148,6 +153,7 @@ ohos_unittest("device_auth_func_test") { include_dirs += [ "./include", "./unit_test/include", + "${dev_frameworks_path}/inc/permission_adapter", "${dev_frameworks_path}/inc/hiview_adapter", ] @@ -156,6 +162,7 @@ ohos_unittest("device_auth_func_test") { sources += [ "${key_management_adapter_path}/impl/src/common/mbedtls_ec_adapter.c", "${key_management_adapter_path}/impl/src/huks_adapter.c", + "${key_management_adapter_path}/impl/src/huks_adapter_utils.c", "${key_management_adapter_path}/impl/src/standard/crypto_hash_to_point.c", "${key_management_adapter_path}/impl/src/standard/huks_adapter_diff_impl.c", "${os_adapter_path}/impl/src/hc_log.c", @@ -170,9 +177,12 @@ ohos_unittest("device_auth_func_test") { sources += dev_frameworks_files sources += deviceauth_common_files - sources += database_manager_files - sources += cred_manager_files + sources += group_database_manager_files + sources += cred_database_manager_files + sources += ext_plugin_manager_files sources += session_manager_files + sources += cred_listener_files + sources += identity_service_files sources += session_v1_files sources += session_v2_files sources += iso_protocol_files @@ -289,6 +299,7 @@ ohos_unittest("device_auth_interface_test") { sources += [ "${key_management_adapter_path}/impl/src/common/mbedtls_ec_adapter.c", "${key_management_adapter_path}/impl/src/huks_adapter.c", + "${key_management_adapter_path}/impl/src/huks_adapter_utils.c", "${key_management_adapter_path}/impl/src/standard/crypto_hash_to_point.c", "${key_management_adapter_path}/impl/src/standard/huks_adapter_diff_impl.c", "${os_adapter_path}/impl/src/hc_log.c", @@ -303,8 +314,9 @@ ohos_unittest("device_auth_interface_test") { sources += dev_frameworks_files sources += deviceauth_common_files - sources += database_manager_files - sources += cred_manager_files + sources += group_database_manager_files + sources += cred_database_manager_files + sources += ext_plugin_manager_files sources += session_manager_files sources += session_v1_files sources += session_v2_files @@ -361,6 +373,7 @@ ohos_unittest("device_auth_interface_test") { "ENABLE_P2P_AUTH_EC_SPEKE", "ENABLE_PSEUDONYM", "DEV_AUTH_HIVIEW_ENABLE", + "DEV_AUTH_PERMISSION_ENABLE", ] sources += identity_manager_files @@ -404,6 +417,7 @@ ohos_unittest("deviceauth_unit_test") { include_dirs += [ "./include", "./unit_test/include", + "${dev_frameworks_path}/inc/permission_adapter", "${dev_frameworks_path}/inc/hiview_adapter", ] @@ -411,6 +425,7 @@ ohos_unittest("deviceauth_unit_test") { sources += [ "${key_management_adapter_path}/impl/src/common/mbedtls_ec_adapter.c", "${key_management_adapter_path}/impl/src/huks_adapter.c", + "${key_management_adapter_path}/impl/src/huks_adapter_utils.c", "${key_management_adapter_path}/impl/src/standard/crypto_hash_to_point.c", "${key_management_adapter_path}/impl/src/standard/huks_adapter_diff_impl.c", "${os_adapter_path}/impl/src/hc_log.c", @@ -426,9 +441,12 @@ ohos_unittest("deviceauth_unit_test") { sources += identity_manager_files sources += dev_frameworks_files sources += deviceauth_common_files - sources += database_manager_files - sources += cred_manager_files + sources += group_database_manager_files + sources += cred_database_manager_files + sources += ext_plugin_manager_files sources += session_manager_files + sources += identity_service_files + sources += cred_listener_files sources += session_v1_files sources += session_v2_files sources += iso_protocol_files @@ -494,6 +512,7 @@ ohos_unittest("deviceauth_unit_test") { deps = [] external_deps = [ + "access_token:libaccesstoken_sdk", "cJSON:cjson", "c_utils:utils", "googletest:gmock_main", diff --git a/test/unittest/deviceauth/source/deviceauth_interface_test.cpp b/test/unittest/deviceauth/source/deviceauth_interface_test.cpp index f67863e6d029df2113a15ca093bdaefc1e067f64..1c922d5e5193f69771f760d55d30babdf9d52457 100644 --- a/test/unittest/deviceauth/source/deviceauth_interface_test.cpp +++ b/test/unittest/deviceauth/source/deviceauth_interface_test.cpp @@ -27,7 +27,7 @@ #include "json_utils.h" #include "alg_loader.h" #include "mk_agree_task.h" -#include "cred_manager.h" +#include "ext_plugin_manager.h" #include "channel_manager.h" #include "soft_bus_channel.h" #include "dev_auth_module_manager.h" @@ -411,7 +411,7 @@ static int32_t ProcessCredTest(int32_t osAccountId, int32_t cmdId, CJson *in, CJ HWTEST_F(DeviceAuthInterfaceTest, DeviceAuthInterfaceTest008, TestSize.Level0) { - // cred_manager.c interface test + // ext_plugin_manager.c interface test int32_t res = InitCredMgr(); ASSERT_EQ(res, HC_SUCCESS); res = ProcCred(0, DEFAULT_OS_ACCOUNT, 0, nullptr, nullptr); diff --git a/test/unittest/deviceauth/source/group_operation_common_test.cpp b/test/unittest/deviceauth/source/group_operation_common_test.cpp index 9ee6f1d9120111475c5f15cc671e640919c77ed7..8faabda5425f20ca158b6b673fe70cda2735cde5 100644 --- a/test/unittest/deviceauth/source/group_operation_common_test.cpp +++ b/test/unittest/deviceauth/source/group_operation_common_test.cpp @@ -23,7 +23,7 @@ #include "hc_dev_info.h" #include "json_utils.h" #include "securec.h" -#include "data_manager.h" +#include "group_data_manager.h" using namespace std; using namespace testing::ext; diff --git a/test/unittest/deviceauth/unit_test/include/account_related_group_auth_dir_test.h b/test/unittest/deviceauth/unit_test/include/account_related_group_auth_dir_test.h index 3944ccd55c015c57adcbb7cbe1496432abf1e3e1..a77b071ea5530775b84dc4d081f8b746196c27f4 100644 --- a/test/unittest/deviceauth/unit_test/include/account_related_group_auth_dir_test.h +++ b/test/unittest/deviceauth/unit_test/include/account_related_group_auth_dir_test.h @@ -34,7 +34,7 @@ extern "C" #include "hc_string.h" #include "group_auth_data_operation.h" #include "account_related_group_auth.h" -#include "data_manager.h" +#include "group_data_manager.h" #ifdef __cpluscplus } diff --git a/test/unittest/tdd_framework/tdd_helper/BUILD.gn b/test/unittest/tdd_framework/tdd_helper/BUILD.gn index 941fe501ba783328d3d4a01bbafc222464a15fcf..b4868b8660b86ac703fc8adb67efc6bfd3424362 100644 --- a/test/unittest/tdd_framework/tdd_helper/BUILD.gn +++ b/test/unittest/tdd_framework/tdd_helper/BUILD.gn @@ -28,6 +28,7 @@ ohos_static_library("device_auth_test_hal") { sources += [ "${key_management_adapter_path}/impl/src/common/mbedtls_ec_adapter.c", "${key_management_adapter_path}/impl/src/huks_adapter.c", + "${key_management_adapter_path}/impl/src/huks_adapter_utils.c", "${key_management_adapter_path}/impl/src/standard/crypto_hash_to_point.c", "${key_management_adapter_path}/impl/src/standard/huks_adapter_diff_impl.c", "${os_adapter_path}/impl/src/hc_log.c", diff --git a/test/unittest/tdd_framework/unit_test/services/creds_manager/BUILD.gn b/test/unittest/tdd_framework/unit_test/services/creds_manager/BUILD.gn index 99587a251203c281a06f06ea7ea7408983f4b9ff..f0cec9676e6e7980269a1dc7424eb3800a4490c4 100644 --- a/test/unittest/tdd_framework/unit_test/services/creds_manager/BUILD.gn +++ b/test/unittest/tdd_framework/unit_test/services/creds_manager/BUILD.gn @@ -21,6 +21,7 @@ ohos_unittest("creds_manager_test") { include_dirs = inc_path + hals_inc_path include_dirs += [ "${dev_frameworks_path}/inc/hiview_adapter", + "${dev_frameworks_path}/inc/permission_adapter", "${tdd_framework_path}/common/inc", ] @@ -44,6 +45,7 @@ ohos_unittest("creds_manager_test") { sources += [ "${key_management_adapter_path}/impl/src/common/mbedtls_ec_adapter.c", "${key_management_adapter_path}/impl/src/huks_adapter.c", + "${key_management_adapter_path}/impl/src/huks_adapter_utils.c", "${key_management_adapter_path}/impl/src/standard/crypto_hash_to_point.c", "${key_management_adapter_path}/impl/src/standard/huks_adapter_diff_impl.c", "${os_adapter_path}/impl/src/hc_log.c", diff --git a/test/unittest/tdd_framework/unit_test/services/frameworks/os_account_adapter/BUILD.gn b/test/unittest/tdd_framework/unit_test/services/frameworks/os_account_adapter/BUILD.gn index 358010d389628e39a41876b3a70742e1b24f259f..bac82fa3193058a294fe6e5a2d04ef496722ab35 100644 --- a/test/unittest/tdd_framework/unit_test/services/frameworks/os_account_adapter/BUILD.gn +++ b/test/unittest/tdd_framework/unit_test/services/frameworks/os_account_adapter/BUILD.gn @@ -22,6 +22,7 @@ if (support_os_account) { include_dirs = inc_path + hals_inc_path include_dirs += [ "${dev_frameworks_path}/inc/hiview_adapter", + "${dev_frameworks_path}/inc/permission_adapter", "${tdd_framework_path}/common/inc", ] include_dirs += [ "${dev_frameworks_path}/inc/account_subscriber" ] @@ -42,6 +43,7 @@ if (support_os_account) { sources += [ "${key_management_adapter_path}/impl/src/common/mbedtls_ec_adapter.c", "${key_management_adapter_path}/impl/src/huks_adapter.c", + "${key_management_adapter_path}/impl/src/huks_adapter_utils.c", "${key_management_adapter_path}/impl/src/standard/crypto_hash_to_point.c", "${key_management_adapter_path}/impl/src/standard/huks_adapter_diff_impl.c", "${os_adapter_path}/impl/src/hc_log.c", diff --git a/test/unittest/tdd_framework/unit_test/services/session_manager/session/v2/expand_sub_session/BUILD.gn b/test/unittest/tdd_framework/unit_test/services/session_manager/session/v2/expand_sub_session/BUILD.gn index 82e1c50fd25c82cd59a6357760ad5c0777521651..ef56ae2148a2c04c79a98dc14fcf6c65d5f746d9 100644 --- a/test/unittest/tdd_framework/unit_test/services/session_manager/session/v2/expand_sub_session/BUILD.gn +++ b/test/unittest/tdd_framework/unit_test/services/session_manager/session/v2/expand_sub_session/BUILD.gn @@ -32,8 +32,8 @@ ohos_unittest("expand_sub_session_test") { "${group_manager_path}/inc/broadcast_manager", "${privacy_enhancement_path}/inc", "${mk_agree_path}/inc", - "${services_path}/cred_manager/inc/account_related", - "${services_path}/cred_manager/inc", + "${services_path}/ext_plugin_manager/inc/account_related", + "${services_path}/ext_plugin_manager/inc", "${protocol_path}/inc", ] @@ -52,13 +52,13 @@ ohos_unittest("expand_sub_session_test") { "${authenticators_path}/src/account_related/creds_manager/sym_token_manager.c", "${authenticators_path}/src/account_unrelated/common/das_task_common.c", "${authenticators_path}/src/account_unrelated/creds_manager/das_standard_token_manager.c", - "${data_manager_path}/src/data_manager.c", "${dev_frameworks_path}/src/account_task_manager/account_task_manager.c", "${dev_frameworks_path}/src/os_account_adapter_mock/os_account_adapter_mock.cpp", "${dev_frameworks_path}/src/plugin_adapter/ext_part/account_auth_plugin_proxy.c", "${dev_frameworks_path}/src/security_label_adapter_mock/security_label_adapter_mock.c", "${deviceauth_account_group_auth_path}/src/group_auth_manager/account_related_group_auth/account_related_group_auth.c", "${group_auth_path}/src/group_auth_manager/group_auth_common/group_auth_data_operation.c", + "${group_data_manager_path}/src/group_data_manager.c", "${group_manager_path}/src/broadcast_manager_mock/broadcast_manager_mock.c", "${group_manager_path}/src/group_operation/group_operation_common/group_operation_common.c", "${identity_manager_path}/src/cert_operation.c", @@ -74,7 +74,7 @@ ohos_unittest("expand_sub_session_test") { "${dev_frameworks_path}/inc/os_account_adapter", "${dev_frameworks_path}/inc/plugin_adapter", "${protocol_path}/inc/pake_protocol", - "${data_manager_path}/inc", + "${group_data_manager_path}/inc", "${session_manager_path}/inc/session/v1", "${session_manager_path}/inc/session/v1/compatible_auth_sub_session", "${group_auth_path}/inc/account_related_group_auth", diff --git a/test/unittest/tdd_framework/unit_test/services/session_manager/session/v2/expand_sub_session/expand_process_lib/BUILD.gn b/test/unittest/tdd_framework/unit_test/services/session_manager/session/v2/expand_sub_session/expand_process_lib/BUILD.gn index a1cff271c03127eff62fa77b4f25a56e528a945b..0cb4d6366dcff6cd5e787e91e544b44db5af5532 100644 --- a/test/unittest/tdd_framework/unit_test/services/session_manager/session/v2/expand_sub_session/expand_process_lib/BUILD.gn +++ b/test/unittest/tdd_framework/unit_test/services/session_manager/session/v2/expand_sub_session/expand_process_lib/BUILD.gn @@ -43,7 +43,7 @@ ohos_unittest("auth_code_import_test") { "${dev_frameworks_path}/inc/os_account_adapter", "${dev_frameworks_path}/inc/plugin_adapter", "${protocol_path}/inc/pake_protocol", - "${data_manager_path}/inc", + "${group_data_manager_path}/inc", "${session_manager_path}/inc/session/v1", "${session_manager_path}/inc/session/v1/compatible_auth_sub_session", "${group_auth_path}/inc/account_related_group_auth", @@ -57,8 +57,8 @@ ohos_unittest("auth_code_import_test") { "${group_manager_path}/inc/broadcast_manager", "${privacy_enhancement_path}/inc", "${mk_agree_path}/inc", - "${services_path}/cred_manager/inc/account_related", - "${services_path}/cred_manager/inc", + "${services_path}/ext_plugin_manager/inc/account_related", + "${services_path}/ext_plugin_manager/inc", "${protocol_path}/inc", ] sources += identity_manager_files @@ -67,13 +67,13 @@ ohos_unittest("auth_code_import_test") { "${authenticators_path}/src/account_related/creds_manager/sym_token_manager.c", "${authenticators_path}/src/account_unrelated/common/das_task_common.c", "${authenticators_path}/src/account_unrelated/creds_manager/das_standard_token_manager.c", - "${data_manager_path}/src/data_manager.c", "${dev_frameworks_path}/src/account_task_manager/account_task_manager.c", "${dev_frameworks_path}/src/os_account_adapter_mock/os_account_adapter_mock.cpp", "${dev_frameworks_path}/src/plugin_adapter/ext_part/account_auth_plugin_proxy.c", "${dev_frameworks_path}/src/security_label_adapter_mock/security_label_adapter_mock.c", "${deviceauth_account_group_auth_path}/src/group_auth_manager/account_related_group_auth/account_related_group_auth.c", "${group_auth_path}/src/group_auth_manager/group_auth_common/group_auth_data_operation.c", + "${group_data_manager_path}/src/group_data_manager.c", "${group_manager_path}/src/broadcast_manager_mock/broadcast_manager_mock.c", "${group_manager_path}/src/group_operation/group_operation_common/group_operation_common.c", "${identity_manager_path}/src/cert_operation.c", @@ -119,8 +119,8 @@ ohos_unittest("pub_key_exchange_test") { "${group_manager_path}/inc/broadcast_manager", "${privacy_enhancement_path}/inc", "${mk_agree_path}/inc", - "${services_path}/cred_manager/inc/account_related", - "${services_path}/cred_manager/inc", + "${services_path}/ext_plugin_manager/inc/account_related", + "${services_path}/ext_plugin_manager/inc", "${protocol_path}/inc", ] @@ -131,13 +131,13 @@ ohos_unittest("pub_key_exchange_test") { "${authenticators_path}/src/account_related/creds_manager/sym_token_manager.c", "${authenticators_path}/src/account_unrelated/common/das_task_common.c", "${authenticators_path}/src/account_unrelated/creds_manager/das_standard_token_manager.c", - "${data_manager_path}/src/data_manager.c", "${dev_frameworks_path}/src/account_task_manager/account_task_manager.c", "${dev_frameworks_path}/src/os_account_adapter_mock/os_account_adapter_mock.cpp", "${dev_frameworks_path}/src/plugin_adapter/ext_part/account_auth_plugin_proxy.c", "${dev_frameworks_path}/src/security_label_adapter_mock/security_label_adapter_mock.c", "${deviceauth_account_group_auth_path}/src/group_auth_manager/account_related_group_auth/account_related_group_auth.c", "${group_auth_path}/src/group_auth_manager/group_auth_common/group_auth_data_operation.c", + "${group_data_manager_path}/src/group_data_manager.c", "${group_manager_path}/src/broadcast_manager_mock/broadcast_manager_mock.c", "${group_manager_path}/src/group_operation/group_operation_common/group_operation_common.c", "${identity_manager_path}/src/cert_operation.c", @@ -153,7 +153,7 @@ ohos_unittest("pub_key_exchange_test") { "${dev_frameworks_path}/inc/os_account_adapter", "${dev_frameworks_path}/inc/plugin_adapter", "${protocol_path}/inc/pake_protocol", - "${data_manager_path}/inc", + "${group_data_manager_path}/inc", "${session_manager_path}/inc/session/v1", "${session_manager_path}/inc/session/v1/compatible_auth_sub_session", "${group_auth_path}/inc/account_related_group_auth", @@ -187,7 +187,7 @@ ohos_unittest("save_trusted_info_test") { include_dirs += hals_inc_path include_dirs += [ "${inner_api_path}", - "${data_manager_path}/inc", + "${group_data_manager_path}/inc", "${dev_frameworks_path}/inc/", "${dev_frameworks_path}/inc/hiview_adapter", "${frameworks_path}/inc/standard", @@ -207,7 +207,8 @@ ohos_unittest("save_trusted_info_test") { sources = broadcast_manager_mock_files sources += account_auth_plugin_mock_files sources += account_task_manager_mock_files - sources += database_manager_files + sources += group_database_manager_files + sources += cred_database_manager_files sources += save_trusted_info_files sources += privacy_enhancement_mock_files sources += mk_agree_mock_files diff --git a/test/unittest/tdd_framework/unit_test/services/session_manager/session/v2/expand_sub_session/expand_process_lib/save_trusted_info_test.cpp b/test/unittest/tdd_framework/unit_test/services/session_manager/session/v2/expand_sub_session/expand_process_lib/save_trusted_info_test.cpp index ba35fb7b7379f3c670c7517a27e0a7bc8138ae9c..574c16baffc2d91a4301f4aaad5e29dbb996ad1a 100644 --- a/test/unittest/tdd_framework/unit_test/services/session_manager/session/v2/expand_sub_session/expand_process_lib/save_trusted_info_test.cpp +++ b/test/unittest/tdd_framework/unit_test/services/session_manager/session/v2/expand_sub_session/expand_process_lib/save_trusted_info_test.cpp @@ -16,7 +16,7 @@ #include #include #include "common_defs.h" -#include "data_manager.h" +#include "group_data_manager.h" #include "device_auth.h" #include "device_auth_defines.h" #include "dev_info_mock.h"