From dcbbd2b5dd8ee6e33e2e4b53232253e401824a43 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=BC=A0=E8=B7=83=E8=80=80?= Date: Fri, 28 Feb 2025 14:06:27 +0800 Subject: [PATCH] add identity service 2.0. MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 张跃耀 --- .vscode/settings.json | 5 + default_config/mini/config.gni | 1 + default_config/small/config.gni | 1 + default_config/standard/config.gni | 1 + frameworks/inc/ipc_sdk_defines.h | 3 + frameworks/inc/ipc_service_common.h | 3 + frameworks/src/deviceauth_sa.cpp | 3 + frameworks/src/identity_service_ipc_sdk.c | 247 ++++++ frameworks/src/ipc_service_common.c | 108 +++ interfaces/inner_api/device_auth.h | 19 +- services/BUILD.gn | 1 + .../inc/credential_data_manager.h | 2 - .../src/credential_data_manager.c | 164 ++-- .../src/mock/credential_data_manager_mock.c | 107 +++ services/device_auth.c | 224 ++--- services/deviceauth.gni | 16 + .../permission_adapter/permission_adapter.cpp | 13 +- .../identity_service/inc/identity_operation.h | 98 +-- .../identity_service/inc/identity_service.h | 6 + .../inc/identity_service_defines.h | 113 +++ .../inc/identity_service_impl.h | 6 + .../listener/src/mock/cred_listener_mock.c | 66 ++ .../session/inc/cred_session_util.h | 31 + .../session/src/cred_session_util.c | 416 ++++++++++ .../session/src/mock/cred_session_util_mock.c | 41 + .../identity_service/src/identity_operation.c | 566 ++++++++++--- .../identity_service/src/identity_service.c | 49 ++ .../src/identity_service_impl.c | 322 +++++++- .../src/mock/identity_operation_mock.c | 228 +++++ .../src/mock/identity_service_mock.c | 119 +++ .../legacy/creds_manager/inc/creds_manager.h | 2 - .../legacy/creds_manager/src/creds_manager.c | 257 +----- .../identity_manager/inc/cert_operation.h | 2 +- .../identity_manager/inc/identity_manager.h | 2 + .../identity_manager/src/cert_operation.c | 10 +- .../identity_manager/src/identity_cred.c | 777 ++++++++++++++++++ .../identity_manager/src/identity_manager.c | 2 + .../identity_manager/src/identity_pin.c | 18 +- .../src/mock/identity_cred_mock.c | 21 + .../src/mock/identity_manager_mock.c | 5 + .../inc/session/v2/dev_session_util.h | 2 +- .../src/session/v2/dev_session_util.c | 26 +- .../src/session/v2/dev_session_v2.c | 117 +-- .../auth/isoauthtask_fuzzer/BUILD.gn | 1 + .../pake/standardexchangetask_fuzzer/BUILD.gn | 1 + .../credsmanager_fuzzer/BUILD.gn | 1 + test/fuzztest/devauth_fuzzer/BUILD.gn | 1 + test/fuzztest/devauthfunc_fuzzer/BUILD.gn | 1 + .../BUILD.gn | 1 + .../BUILD.gn | 1 + .../devauthservauthdevice_fuzzer/BUILD.gn | 1 + .../BUILD.gn | 1 + .../BUILD.gn | 1 + .../BUILD.gn | 1 + .../devauthservcreategroup_fuzzer/BUILD.gn | 1 + .../devauthservdeletegroup_fuzzer/BUILD.gn | 1 + .../BUILD.gn | 1 + .../BUILD.gn | 1 + .../BUILD.gn | 1 + .../devauthservgetgroupinfo_fuzzer/BUILD.gn | 1 + .../BUILD.gn | 1 + .../BUILD.gn | 1 + .../devauthservgetpkinfolist_fuzzer/BUILD.gn | 1 + .../BUILD.gn | 1 + .../BUILD.gn | 1 + .../BUILD.gn | 1 + .../BUILD.gn | 1 + .../BUILD.gn | 1 + .../BUILD.gn | 1 + .../devauthservregcallback_fuzzer/BUILD.gn | 1 + .../BUILD.gn | 1 + .../devauthservunregcallback_fuzzer/BUILD.gn | 1 + .../BUILD.gn | 1 + .../accountrelatedgroupauth_fuzzer/BUILD.gn | 1 + .../groupoperationcommon_fuzzer/BUILD.gn | 1 + .../identityservice_fuzzer.cpp | 34 +- .../authsubsession_fuzzer/BUILD.gn | 1 + .../authcodeimport_fuzzer/BUILD.gn | 1 + .../pubkeyexchange_fuzzer/BUILD.gn | 1 + .../savetrustedinfo_fuzzer/BUILD.gn | 1 + .../expandsubsession_fuzzer/BUILD.gn | 1 + test/unittest/deviceauth/BUILD.gn | 4 + .../source/deviceauth_func_test.cpp | 6 + .../deviceauth_identity_service_test.cpp | 398 ++++++++- .../unit_test/services/creds_manager/BUILD.gn | 1 + .../frameworks/os_account_adapter/BUILD.gn | 1 + .../session/v2/expand_sub_session/BUILD.gn | 1 + .../expand_process_lib/BUILD.gn | 3 + 88 files changed, 3903 insertions(+), 802 deletions(-) create mode 100644 .vscode/settings.json create mode 100644 services/data_manager/cred_data_manager/src/mock/credential_data_manager_mock.c create mode 100644 services/identity_service/inc/identity_service_defines.h create mode 100644 services/identity_service/listener/src/mock/cred_listener_mock.c create mode 100644 services/identity_service/session/inc/cred_session_util.h create mode 100644 services/identity_service/session/src/cred_session_util.c create mode 100644 services/identity_service/session/src/mock/cred_session_util_mock.c create mode 100644 services/identity_service/src/mock/identity_operation_mock.c create mode 100644 services/identity_service/src/mock/identity_service_mock.c create mode 100644 services/legacy/identity_manager/src/identity_cred.c create mode 100644 services/legacy/identity_manager/src/mock/identity_cred_mock.c diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 00000000..f5866065 --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,5 @@ +{ + "files.associations": { + "identity_operation.c": "cpp" + } +} \ No newline at end of file diff --git a/default_config/mini/config.gni b/default_config/mini/config.gni index 58d6d604..e417ac46 100644 --- a/default_config/mini/config.gni +++ b/default_config/mini/config.gni @@ -36,4 +36,5 @@ declare_args() { max_auth_session_count = 10 device_auth_hichain_thread_stack_size = 8192 + enable_identity_service = false } diff --git a/default_config/small/config.gni b/default_config/small/config.gni index 4ca161a0..ecb97ca4 100644 --- a/default_config/small/config.gni +++ b/default_config/small/config.gni @@ -35,4 +35,5 @@ declare_args() { max_auth_session_count = 10 device_auth_hichain_thread_stack_size = 102400 + enable_identity_service = false } diff --git a/default_config/standard/config.gni b/default_config/standard/config.gni index 751b7375..0c42edd4 100644 --- a/default_config/standard/config.gni +++ b/default_config/standard/config.gni @@ -35,4 +35,5 @@ declare_args() { max_auth_session_count = 10 device_auth_hichain_thread_stack_size = 102400 + enable_identity_service = true } diff --git a/frameworks/inc/ipc_sdk_defines.h b/frameworks/inc/ipc_sdk_defines.h index acb486f5..8800ae9a 100644 --- a/frameworks/inc/ipc_sdk_defines.h +++ b/frameworks/inc/ipc_sdk_defines.h @@ -99,6 +99,9 @@ enum { IPC_CALL_ID_DA_AUTH_DEVICE, IPC_CALL_ID_DA_CANCEL_REQUEST, IPC_CALL_ID_CM_ADD_CREDENTIAL, + IPC_CALL_ID_CM_AGREE_CREDENTIAL, + IPC_CALL_ID_CM_DEL_CRED_BY_PARAMS, + IPC_CALL_ID_CM_BATCH_UPDATE_CREDENTIALS, IPC_CALL_ID_CM_REG_LISTENER, IPC_CALL_ID_CM_UNREG_LISTENER, IPC_CALL_ID_CM_EXPORT_CREDENTIAL, diff --git a/frameworks/inc/ipc_service_common.h b/frameworks/inc/ipc_service_common.h index d6549528..4aa83f79 100644 --- a/frameworks/inc/ipc_service_common.h +++ b/frameworks/inc/ipc_service_common.h @@ -69,6 +69,9 @@ int32_t IpcServiceCmQueryCredentialByParams(const IpcDataInfo *ipcParams, int32_ 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 IpcServiceCmAgreeCredential(const IpcDataInfo *ipcParams, int32_t paramNum, uintptr_t outCache); +int32_t IpcServiceCmDelCredByParams(const IpcDataInfo *ipcParams, int32_t paramNum, uintptr_t outCache); +int32_t IpcServiceCmBatchUpdateCredentials(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); diff --git a/frameworks/src/deviceauth_sa.cpp b/frameworks/src/deviceauth_sa.cpp index 78daa2e0..78c35b0f 100644 --- a/frameworks/src/deviceauth_sa.cpp +++ b/frameworks/src/deviceauth_sa.cpp @@ -83,6 +83,9 @@ static IpcCallMap g_ipcCallMaps[] = { {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}, + {IpcServiceCmAgreeCredential, IPC_CALL_ID_CM_AGREE_CREDENTIAL}, + {IpcServiceCmDelCredByParams, IPC_CALL_ID_CM_DEL_CRED_BY_PARAMS}, + {IpcServiceCmBatchUpdateCredentials, IPC_CALL_ID_CM_BATCH_UPDATE_CREDENTIALS}, {IpcServiceCaAuthDevice, IPC_CALL_ID_CA_AUTH_DEVICE}, {IpcServiceCaProcessCredData, IPC_CALL_ID_CA_PROCESS_CRED_DATA}, }; diff --git a/frameworks/src/identity_service_ipc_sdk.c b/frameworks/src/identity_service_ipc_sdk.c index a06edb10..115e40e3 100644 --- a/frameworks/src/identity_service_ipc_sdk.c +++ b/frameworks/src/identity_service_ipc_sdk.c @@ -160,6 +160,27 @@ static int32_t AddCredentialIpcResult(const IpcDataInfo *replies, int32_t cacheN return HC_SUCCESS; } +static int32_t AgreeCredentialIpcResult(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; @@ -603,6 +624,229 @@ static int32_t IpcCmUpdateCredInfo(int32_t osAccountId, const char *credId, cons return ret; } +static int32_t EncodeAgreeCredentialParams(uintptr_t callCtx, int32_t osAccountId, const char *selfCredId, + 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_CRED_ID, (const uint8_t *)selfCredId, HcStrlen(selfCredId) + 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 IpcCmAgreeCredential(int32_t osAccountId, const char *selfCredId, const char *requestParams, + char **returnData) +{ + uintptr_t callCtx = 0x0; + int32_t ret; + IpcDataInfo replyCache[IPC_DATA_CACHES_3] = { { 0 } }; + + LOGI("starting ..."); + if (IsStrInvalid(selfCredId) || 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 = EncodeAgreeCredentialParams(callCtx, osAccountId, selfCredId, requestParams); + if (ret != HC_SUCCESS) { + DestroyCallCtx(&callCtx, NULL); + return ret; + } + ret = DoBinderCall(callCtx, IPC_CALL_ID_CM_AGREE_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 = AgreeCredentialIpcResult(replyCache, REPLAY_CACHE_NUM(replyCache), returnData); + DestroyCallCtx(&callCtx, NULL); + LOGI("process done, ret %d", ret); + return ret; +} + +static int32_t EncodeDelCredByParams(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 DelCredByParamsIpcResult(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_INFO_LIST, (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 IpcCmDelCredByParams(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 = EncodeDelCredByParams(callCtx, osAccountId, requestParams); + if (ret != HC_SUCCESS) { + DestroyCallCtx(&callCtx, NULL); + return ret; + } + ret = DoBinderCall(callCtx, IPC_CALL_ID_CM_DEL_CRED_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 = DelCredByParamsIpcResult(replyCache, REPLAY_CACHE_NUM(replyCache), returnData); + DestroyCallCtx(&callCtx, NULL); + LOGI("process done, ret %d", ret); + return ret; +} + +static int32_t EncodeBatchUpdateParam(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 BatchUpdateCredIpcResult(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_INFO_LIST, (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 IpcCmBatchUpdateCredentials(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 = EncodeBatchUpdateParam(callCtx, osAccountId, requestParams); + if (ret != HC_SUCCESS) { + DestroyCallCtx(&callCtx, NULL); + return ret; + } + ret = DoBinderCall(callCtx, IPC_CALL_ID_CM_BATCH_UPDATE_CREDENTIALS, 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 = BatchUpdateCredIpcResult(replyCache, REPLAY_CACHE_NUM(replyCache), returnData); + DestroyCallCtx(&callCtx, NULL); + LOGI("process done, ret %d", ret); + return ret; +} + static void InitIpcCmMethods(CredManager *cmMethodObj) { cmMethodObj->addCredential = IpcCmAddCredential; @@ -613,6 +857,9 @@ static void InitIpcCmMethods(CredManager *cmMethodObj) cmMethodObj->queryCredInfoByCredId = IpcCmQueryCredInfoByCredId; cmMethodObj->deleteCredential = IpcCmDeleteCredential; cmMethodObj->updateCredInfo = IpcCmUpdateCredInfo; + cmMethodObj->agreeCredential = IpcCmAgreeCredential; + cmMethodObj->deleteCredByParams = IpcCmDelCredByParams; + cmMethodObj->batchUpdateCredentials = IpcCmBatchUpdateCredentials; return; } diff --git a/frameworks/src/ipc_service_common.c b/frameworks/src/ipc_service_common.c index aa8231a0..6b095675 100644 --- a/frameworks/src/ipc_service_common.c +++ b/frameworks/src/ipc_service_common.c @@ -1513,6 +1513,114 @@ int32_t IpcServiceCmUpdateCredInfo(const IpcDataInfo *ipcParams, int32_t paramNu return ret; } +int32_t IpcServiceCmAgreeCredential(const IpcDataInfo *ipcParams, int32_t paramNum, uintptr_t outCache) +{ + int32_t callRet; + int32_t ret; + int32_t osAccountId; + int32_t inOutLen; + const char *selfCredId = NULL; + const char *requestParams = NULL; + char *agreeCredId = 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 *)&selfCredId, 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.agreeCredential(osAccountId, selfCredId, requestParams, &agreeCredId); + 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 (agreeCredId != NULL) { + ret += IpcEncodeCallReply(outCache, PARAM_TYPE_CRED_ID, (const uint8_t *)agreeCredId, + HcStrlen(agreeCredId) + 1); + } else { + ret += IpcEncodeCallReply(outCache, PARAM_TYPE_CRED_ID, NULL, 0); + } + g_devCredMgrMethod.destroyInfo(&agreeCredId); + LOGI("process done, call ret %d, ipc ret %d", callRet, ret); + return ret; +} + +int32_t IpcServiceCmDelCredByParams(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_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.deleteCredByParams(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 IpcServiceCmBatchUpdateCredentials(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_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.batchUpdateCredentials(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 IpcServiceCaAuthDevice(const IpcDataInfo *ipcParams, int32_t paramNum, uintptr_t outCache) { diff --git a/interfaces/inner_api/device_auth.h b/interfaces/inner_api/device_auth.h index aa629f4c..da666120 100644 --- a/interfaces/inner_api/device_auth.h +++ b/interfaces/inner_api/device_auth.h @@ -80,10 +80,7 @@ #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_OBJ "credentialObject" #define FIELD_CREDENTIAL_FORMAT "credentialFormat" #define FIELD_SUBJECT "subject" #define FIELD_ISSUER "issuer" @@ -94,6 +91,13 @@ #define FIELD_AUTHORIZED_ACCOUNT_LIST "authorizedAccountList" #define FIELD_PROTOCOL_TYPE "protocolType" #define FIELD_EXTEND_INFO "extendInfo" +#define FIELD_AUTHORIZED_DEVICE_LIST "authorizedDeviceList" +#define FIELD_AUTHORIZED_APP_LIST "authorizedAppList" +#define FIELD_ACROSS_ACCOUNT_CRED_ID "acrossAccountCredId" +#define FIELD_DEVICE_ID_HASH "deviceIdHash" +#define FIELD_USER_ID_HASH "userIdHash" +#define FIELD_BASE_INFO "baseInfo" +#define FIELD_UPDATE_LISTS "updateLists" /** * @brief protocol expand value for bind @@ -489,10 +493,17 @@ typedef struct { int32_t (*updateCredInfo)(int32_t osAccountId, const char *credId, const char *requestParams); + int32_t (*agreeCredential)(int32_t osAccountId, const char *selfCredId, const char *requestParams, + char **returnData); + int32_t (*registerChangeListener)(const char *appId, CredChangeListener *listener); int32_t (*unregisterChangeListener)(const char *appId); + int32_t (*deleteCredByParams)(int32_t osAccountId, const char *requestParams, char **returnData); + + int32_t (*batchUpdateCredentials)(int32_t osAccountId, const char *requestParams, char **returnData); + void (*destroyInfo)(char **returnData); } CredManager; diff --git a/services/BUILD.gn b/services/BUILD.gn index eec3de75..d4f0cb5d 100644 --- a/services/BUILD.gn +++ b/services/BUILD.gn @@ -32,6 +32,7 @@ if (os_level == "mini" || os_level == "small") { "${dev_frameworks_path}/inc/hiview_adapter", ] sources = deviceauth_files + sources += identity_service_mock_files defines = [ "HILOG_ENABLE" ] defines += deviceauth_defines 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 index 446d2a37..0c54a646 100644 --- a/services/data_manager/cred_data_manager/inc/credential_data_manager.h +++ b/services/data_manager/cred_data_manager/inc/credential_data_manager.h @@ -18,7 +18,6 @@ #include #include "hc_string_vector.h" -#include "cred_tlv_parser.h" #include "json_utils.h" #define MAX_STRING_LEN 256 @@ -73,7 +72,6 @@ extern "C" { 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, 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 index a75259d4..3386fea1 100644 --- a/services/data_manager/cred_data_manager/src/credential_data_manager.c +++ b/services/data_manager/cred_data_manager/src/credential_data_manager.c @@ -28,6 +28,7 @@ #include "security_label_adapter.h" #include "account_task_manager.h" #include "cred_listener.h" +#include "cred_tlv_parser.h" typedef struct { DECLARE_CRED_TLV_STRUCT(17) @@ -194,24 +195,24 @@ static bool GetOsAccountCredInfoPath(int32_t osAccountId, char *infoPath, uint32 } } -static bool GenerateAuthorizedAccountList(const Credential *entry, Credential *returnEntry) +static bool GenerateAuthorizedAppList(const Credential *entry, Credential *returnEntry) { uint32_t index = 0; - HcString *authorizedAccount = NULL; - FOR_EACH_HC_VECTOR(entry->authorizedAccountList, index, authorizedAccount) { - if (authorizedAccount == NULL) { + HcString *authorizedApp = NULL; + FOR_EACH_HC_VECTOR(entry->authorizedAppList, index, authorizedApp) { + if (authorizedApp == NULL) { continue; } - HcString returnAuthorizedAccount = CreateString(); - if (!StringSet(&returnAuthorizedAccount, *authorizedAccount)) { - DeleteString(&returnAuthorizedAccount); - LOGE("[CRED#DB]: Failed to copy authorizedAccount!"); + HcString returnAuthorizedApp = CreateString(); + if (!StringSet(&returnAuthorizedApp, *authorizedApp)) { + DeleteString(&returnAuthorizedApp); + LOGE("[CRED#DB]: Failed to copy authorizedApp!"); return false; } - if (returnEntry->authorizedAccountList.pushBack(&returnEntry->authorizedAccountList, &returnAuthorizedAccount) + if (returnEntry->authorizedAppList.pushBack(&returnEntry->authorizedAppList, &returnAuthorizedApp) == NULL) { - LOGE("[CRED#DB]: Failed to push authorizedAccount to list!"); - DeleteString(&returnAuthorizedAccount); + LOGE("[CRED#DB]: Failed to push authorizedApp to list!"); + DeleteString(&returnAuthorizedApp); return false; } } @@ -240,7 +241,7 @@ bool GenerateCredFromCred(const Credential *entry, Credential *returnEntry) LOGE("[CRED#DB]: Failed to copy credOwner!"); return false; } - if (!GenerateAuthorizedAccountList(entry, returnEntry)) { + if (!GenerateAuthorizedAppList(entry, returnEntry)) { return false; } if (!StringSet(&returnEntry->extendInfo, entry->extendInfo)) { @@ -284,6 +285,14 @@ static bool GenerateCredentialFromTlv(TlvCredentialElement *credential, Credenti LOGE("[CRED#DB]: Failed to load authorizedAccountList from tlv!"); return false; } + if (!LoadStringVectorFromParcel(&entry->authorizedDeviceList, &credential->authorizedDeviceList.data)) { + LOGE("[CRED#DB]: Failed to load authorizedDeviceList from tlv!"); + return false; + } + if (!LoadStringVectorFromParcel(&entry->authorizedAppList, &credential->authorizedAppList.data)) { + LOGE("[CRED#DB]: Failed to load authorizedAppList from tlv!"); + return false; + } if (!StringSet(&entry->extendInfo, credential->extendInfo.data)) { LOGE("[CRED#DB]: Failed to load extendInfo from tlv!"); return false; @@ -560,6 +569,14 @@ static bool SetCredentialElement(TlvCredentialElement *element, Credential *entr LOGE("[CRED#DB]: Failed to copy authorizedAccountList!"); return false; } + if (!SaveStringVectorToParcel(&entry->authorizedDeviceList, &element->authorizedDeviceList.data)) { + LOGE("[CRED#DB]: Failed to copy authorizedDeviceList!"); + return false; + } + if (!SaveStringVectorToParcel(&entry->authorizedAppList, &element->authorizedAppList.data)) { + LOGE("[CRED#DB]: Failed to copy authorizedAppList!"); + return false; + } if (!StringSet(&element->extendInfo.data, entry->extendInfo)) { LOGE("[CRED#DB]: Failed to copy extendInfo!"); return false; @@ -658,30 +675,6 @@ static Credential **QueryCredentialPtrIfMatch(const CredentialVec *vec, const Qu 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 = { @@ -903,7 +896,7 @@ static int32_t AddPeerUserSpaceIdToReturn(const Credential *credInfo, CJson *jso return IS_SUCCESS; } -static int32_t AddAuthorizedAccountListToReturn(const Credential *credInfo, CJson *json) +static int32_t AddAuthorizedAppListToReturn(const Credential *credInfo, CJson *json) { CJson *arr = CreateJsonArray(); if (json == NULL) { @@ -911,20 +904,20 @@ static int32_t AddAuthorizedAccountListToReturn(const Credential *credInfo, CJso return IS_ERR_JSON_CREATE; } uint32_t index = 0; - HcString *authorizedAccount = NULL; - FOR_EACH_HC_VECTOR(credInfo->authorizedAccountList, index, authorizedAccount) { - if (authorizedAccount == NULL) { + HcString *authorizedApp = NULL; + FOR_EACH_HC_VECTOR(credInfo->authorizedAppList, index, authorizedApp) { + if (authorizedApp == NULL) { continue; } - if (AddStringToArray(arr, StringGet(authorizedAccount)) != IS_SUCCESS) { + if (AddStringToArray(arr, StringGet(authorizedApp)) != IS_SUCCESS) { FreeJson(arr); - LOGE("[CRED#DB]: Failed to add authorizedAccount to json!"); + LOGE("[CRED#DB]: Failed to add authorizedApp to json!"); return IS_ERR_JSON_ADD; } } - if (AddObjToJson(json, FIELD_AUTHORIZED_ACCOUNT_LIST, arr) != IS_SUCCESS) { + if (AddObjToJson(json, FIELD_AUTHORIZED_APP_LIST, arr) != IS_SUCCESS) { FreeJson(arr); - LOGE("[CRED#DB]: Failed to add authorizedAccountList to json!"); + LOGE("[CRED#DB]: Failed to add authorizedApp to json!"); return IS_ERR_JSON_ADD; } FreeJson(arr); @@ -945,13 +938,86 @@ int32_t GenerateReturnCredInfo(const Credential *credential, CJson *returnJson) ((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 = AddAuthorizedAppListToReturn(credential, returnJson)) != IS_SUCCESS) || ((result = AddExtendInfoToReturn(credential, returnJson)) != IS_SUCCESS)) { return result; } return IS_SUCCESS; } +static int32_t GenerateCredChangedInfo(const Credential *entry, char **returnCredInfo) +{ + CJson *credInfo = CreateJson(); + if (AddCredTypeToReturn(entry, credInfo) != IS_SUCCESS) { + LOGE("add cretype to json failed."); + FreeJson(credInfo); + return IS_ERR_JSON_ADD; + } + if (AddDeviceIdToReturn(entry, credInfo) != IS_SUCCESS) { + LOGE("add deviceId to json failed."); + FreeJson(credInfo); + return IS_ERR_JSON_ADD; + } + if (AddUserIdToReturn(entry, credInfo) != IS_SUCCESS) { + LOGE("add userId to json failed."); + FreeJson(credInfo); + return IS_ERR_JSON_ADD; + } + if (AddSubjectToReturn(entry, credInfo) != IS_SUCCESS) { + LOGE("add userId to json failed."); + FreeJson(credInfo); + return IS_ERR_JSON_ADD; + } + char *credInfoJsonStr = PackJsonToString(credInfo); + FreeJson(credInfo); + if (credInfoJsonStr == NULL) { + LOGE("pack json to string failed."); + return IS_ERR_ALLOC_MEMORY; + } + *returnCredInfo = credInfoJsonStr; + return IS_SUCCESS; +} + + +static void PostCredAddMsg(const Credential *entry) +{ + if (!IsCredListenerSupported()) { + return; + } + char *returnCredInfo = NULL; + if (GenerateCredChangedInfo(entry, &returnCredInfo) != IS_SUCCESS) { + return; + } + OnCredAdd(StringGet(&entry->credId), returnCredInfo); + FreeJsonString(returnCredInfo); +} + +static void PostCredUpdateMsg(const Credential *entry) +{ + if (!IsCredListenerSupported()) { + return; + } + char *returnCredInfo = NULL; + if (GenerateCredChangedInfo(entry, &returnCredInfo) != IS_SUCCESS) { + return; + } + OnCredUpdate(StringGet(&entry->credId), returnCredInfo); + FreeJsonString(returnCredInfo); +} + +static void PostCredDeleteMsg(const Credential *entry) +{ + if (!IsCredListenerSupported()) { + return; + } + char *returnCredInfo = NULL; + if (GenerateCredChangedInfo(entry, &returnCredInfo) != IS_SUCCESS) { + return; + } + OnCredDelete(StringGet(&entry->credId), returnCredInfo); + FreeJsonString(returnCredInfo); +} + int32_t AddCredToDb(int32_t osAccountId, const Credential *entry) { LOGI("[CRED#DB]: Start to add a cred to database! [OsAccountId]: %d", osAccountId); @@ -1104,12 +1170,12 @@ static void DumpCredential(int fd, const Credential *credential) dprintf(fd, "||%-16s = %-43d| |\n", "algorithmType", credential->algorithmType); dprintf(fd, "||%-16s = %-43d| |\n", "proofType", credential->proofType); uint32_t index = 0; - HcString *authorizedAccount = NULL; - FOR_EACH_HC_VECTOR(credential->authorizedAccountList, index, authorizedAccount) { - if (authorizedAccount == NULL) { + HcString *authorizedApp = NULL; + FOR_EACH_HC_VECTOR(credential->authorizedAppList, index, authorizedApp) { + if (authorizedApp == NULL) { continue; } - dprintf(fd, "||%-16s %d = %-43.8s| |\n", "account", index, StringGet(authorizedAccount)); + dprintf(fd, "||%-16s %d = %-43.8s| |\n", "app", index, StringGet(authorizedApp)); } dprintf(fd, "||%-16s = %-43d| |\n", "authorizedScope", credential->authorizedScope); dprintf(fd, "||%-16s = %-43.8s| |\n", "credOwner", StringGet(&credential->credOwner)); diff --git a/services/data_manager/cred_data_manager/src/mock/credential_data_manager_mock.c b/services/data_manager/cred_data_manager/src/mock/credential_data_manager_mock.c new file mode 100644 index 00000000..d526f7d3 --- /dev/null +++ b/services/data_manager/cred_data_manager/src/mock/credential_data_manager_mock.c @@ -0,0 +1,107 @@ +/* + * 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_types.h" +#include "securec.h" + +static const uint8_t DEFAULT_CRED_PARAM_VAL = 0; + +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) +{ + return NULL; +} + +void DestroyCredential(Credential *credential) +{ + (void)credential; + return; +} + +Credential *DeepCopyCredential(const Credential *entry) +{ + (void)entry; + return NULL; +} + +void ClearCredentialVec(CredentialVec *vec) +{ + (void)vec; + return; +} + +int32_t GenerateReturnCredInfo(const Credential *credential, CJson *returnJson) +{ + (void)credential; + (void)returnJson; + return IS_ERR_NOT_SUPPORT; +} + +int32_t AddCredToDb(int32_t osAccountId, const Credential *entry) +{ + (void)osAccountId; + (void)entry; + return IS_ERR_NOT_SUPPORT; +} + +int32_t DelCredential(int32_t osAccountId, const QueryCredentialParams *params) +{ + (void)osAccountId; + (void)params; + return IS_ERR_NOT_SUPPORT; +} + +int32_t QueryCredentials(int32_t osAccountId, const QueryCredentialParams *params, CredentialVec *vec) +{ + (void)osAccountId; + (void)params; + (void)vec; + return IS_ERR_NOT_SUPPORT; +} + +int32_t SaveOsAccountCredDb(int32_t osAccountId) +{ + (void)osAccountId; + return IS_ERR_NOT_SUPPORT; +} + +int32_t InitCredDatabase(void) +{ + return IS_ERR_NOT_SUPPORT; +} + +void DestroyCredDatabase(void) +{ + return; +} \ No newline at end of file diff --git a/services/device_auth.c b/services/device_auth.c index 6eec5578..75841d2b 100644 --- a/services/device_auth.c +++ b/services/device_auth.c @@ -31,7 +31,6 @@ #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" @@ -42,17 +41,17 @@ #include "identity_manager.h" #include "group_auth_manager.h" #include "account_task_manager.h" -#ifdef DEV_AUTH_IS_ENABLE + +#include "identity_service.h" +#include "cred_session_util.h" #include "credential_data_manager.h" -#endif +#include "identity_service_defines.h" static GroupAuthManager *g_groupAuthManager = NULL; static DeviceGroupManager *g_groupManagerInstance = NULL; -#ifdef DEV_AUTH_IS_ENABLE static CredManager *g_credManager = NULL; static CredAuthManager *g_credAuthManager = NULL; -#endif #define CLEAN_CRED 1 #define CLEAN_MODULE 2 @@ -1023,72 +1022,19 @@ static int32_t AddDeviceIdToJson(CJson *context, const char *peerUdid) return HC_SUCCESS; } -#ifdef DEV_AUTH_IS_ENABLE -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) +static int32_t BuildServerAuthContext(int64_t requestId, int32_t opCode, const char *appId, CJson *context, + char **returnPeerUdid) { - int32_t res = QueryAndAddCredToContext(osAccountId, context, FIELD_SELF_CRED_ID, FIELD_SELF_CREDENTIAL_OBJ); + int32_t res = CheckConfirmationExist(context); if (res != HC_SUCCESS) { - LOGE("Get self credential fail."); return res; } - return HC_SUCCESS; -} -#endif - -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; + res = AddOsAccountIdToContextIfValid(context); + if (res != HC_SUCCESS) { + return res; } - return appId; -} - -static int32_t AddPeerUdid(int32_t osAccountId, CJson *context, char **returnPeerUdid) -{ + 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; @@ -1099,27 +1045,6 @@ static int32_t AddPeerUdid(int32_t osAccountId, CJson *context, char **returnPee 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) { - return res; - } - res = AddOsAccountIdToContextIfValid(context); - if (res != HC_SUCCESS) { - return res; - } - int32_t osAccountId = ANY_OS_ACCOUNT; - (void)GetIntFromJson(context, FIELD_OS_ACCOUNT_ID, &osAccountId); - if (!isCredAuth) { - if ((res = AddPeerUdid(osAccountId, context, returnPeerUdid)) != HC_SUCCESS) { - return res; - } - } if (AddBoolToJson(context, FIELD_IS_BIND, false) != HC_SUCCESS) { LOGE("add isBind to context fail."); return HC_ERR_JSON_ADD; @@ -1128,21 +1053,6 @@ static int32_t BuildServerAuthContext(int64_t requestId, CJson *context, bool is LOGE("add isClient to context fail."); return HC_ERR_JSON_ADD; } -#ifdef DEV_AUTH_IS_ENABLE - if (isCredAuth && (res = QueryAndAddAllCredToContext(osAccountId, context)) != HC_SUCCESS) { - return res; - } -#endif - const char *appId = GetAppIdByContext(context, isCredAuth); - if (appId == NULL) { - LOGE("get appId Fail."); - 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; @@ -1151,6 +1061,10 @@ static int32_t BuildServerAuthContext(int64_t requestId, CJson *context, bool is 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); } @@ -1205,7 +1119,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, - bool isCredAuth, char **returnPeerUdid) + char **returnPeerUdid) { int32_t opCode = AUTH_FORM_ACCOUNT_UNRELATED; if (GetIntFromJson(receivedMsg, FIELD_AUTH_FORM, &opCode) != HC_SUCCESS) { @@ -1225,13 +1139,13 @@ static int32_t OpenServerAuthSession(int64_t requestId, const CJson *receivedMsg LOGE("Failed to create context from string!"); return HC_ERR_JSON_FAIL; } - if (AddIntToJson(context, FIELD_OPERATION_CODE, opCode) != HC_SUCCESS) { - LOGE("add opCode to context fail."); + const char *appId = GetStringFromJson(context, FIELD_SERVICE_PKG_NAME); + if (appId == NULL) { + LOGE("get appId from json fail."); FreeJson(context); - return HC_ERR_JSON_ADD; + return HC_ERR_JSON_GET; } - const char *appId = NULL; - int32_t res = BuildServerAuthContext(requestId, context, isCredAuth, returnPeerUdid, &appId); + int32_t res = BuildServerAuthContext(requestId, opCode, appId, context, returnPeerUdid); if (res != HC_SUCCESS) { FreeJson(context); return res; @@ -1312,7 +1226,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, false, returnPeerUdid); + res = OpenServerAuthSession(authReqId, receivedMsg, gaCallback, returnPeerUdid); if (res != HC_SUCCESS) { FreeJson(receivedMsg); return res; @@ -1351,38 +1265,42 @@ static int32_t ProcessData(int64_t authReqId, const uint8_t *data, uint32_t data return res; } -#ifdef DEV_AUTH_IS_ENABLE -static int32_t BuildClientAuthCredContext(int32_t osAccountId, int64_t requestId, const char *appId, CJson *context) +static int32_t OpenServerCredSession(int64_t requestId, const CJson *receivedMsg, const DeviceAuthCallback *callback, + char **returnPeerUdid) { - 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; + int32_t opCode = AUTH_FORM_ACCOUNT_UNRELATED; + if (GetIntFromJson(receivedMsg, FIELD_AUTH_FORM, &opCode) != HC_SUCCESS) { + if (GetIntFromJson(receivedMsg, FIELD_OP_CODE, &opCode) != HC_SUCCESS) { + opCode = AUTH_FORM_INVALID_TYPE; + LOGW("use default opCode."); + } } - if (AddInt64StringToJson(context, FIELD_REQUEST_ID, requestId) != HC_SUCCESS) { - LOGE("add requestId to context fail."); - return HC_ERR_JSON_ADD; + char *returnDataStr = ProcessRequestCallback(requestId, opCode, NULL, callback); + if (returnDataStr == NULL) { + LOGE("The OnRequest callback is fail!"); + return HC_ERR_REQ_REJECTED; } - if (AddStringToJson(context, FIELD_APP_ID, appId) != HC_SUCCESS) { - LOGE("add appId to context fail."); - return HC_ERR_JSON_ADD; + CJson *context = CreateJsonFromString(returnDataStr); + FreeJsonString(returnDataStr); + if (context == NULL) { + LOGE("Failed to create context from string!"); + return HC_ERR_JSON_FAIL; } - if (AddIntToJson(context, FIELD_OPERATION_CODE, AUTH_FORM_IDENTICAL_ACCOUNT) != HC_SUCCESS) { + if (AddIntToJson(context, FIELD_OPERATION_CODE, opCode) != HC_SUCCESS) { LOGE("add opCode to context fail."); + FreeJson(context); return HC_ERR_JSON_ADD; } - return AddChannelInfoToContext(SERVICE_CHANNEL, DEFAULT_CHANNEL_ID, context); + const char *appId = NULL; + int32_t res = BuildServerCredContext(requestId, context, returnPeerUdid, &appId); + if (res != HC_SUCCESS) { + FreeJson(context); + return res; + } + SessionInitParams params = { context, *callback }; + res = OpenDevSession(requestId, appId, ¶ms); + FreeJson(context); + return res; } static int32_t AuthCredentialInner(int32_t osAccountId, int64_t authReqId, const char *authParams, @@ -1410,18 +1328,8 @@ static int32_t AuthCredentialInner(int32_t osAccountId, int64_t authReqId, const 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); + const char *appId = NULL; + int32_t res = BuildClientCredContext(osAccountId, authReqId, context, &appId); if (res != HC_SUCCESS) { FreeJson(context); return res; @@ -1469,7 +1377,7 @@ static int32_t ProcessCredDataInner(int64_t authReqId, const uint8_t *data, uint } int32_t res; if (!IsSessionExist(authReqId)) { - res = OpenServerAuthSession(authReqId, receivedMsg, caCallback, true, returnPeerUdid); + res = OpenServerCredSession(authReqId, receivedMsg, caCallback, returnPeerUdid); if (res != HC_SUCCESS) { FreeJson(receivedMsg); return res; @@ -1500,7 +1408,6 @@ static int32_t ProcessCredData(int64_t authReqId, const uint8_t *data, uint32_t } return res; } -#endif static void CancelRequest(int64_t requestId, const char *appId) { @@ -1718,7 +1625,6 @@ static void DestroyGmAndGa(void) } } -#ifdef DEV_AUTH_IS_ENABLE static int32_t AllocCredentialMgr(void) { if (g_credManager == NULL) { @@ -1758,7 +1664,6 @@ static void DestroyCa(void) g_credAuthManager = NULL; } } -#endif static void CleanAllModules(int32_t type) { @@ -1767,9 +1672,7 @@ static void CleanAllModules(int32_t type) DestroyDevSessionManager(); // fallthrough case CLEAN_IDENTITY_SERVICE: -#ifdef DEV_AUTH_IS_ENABLE DestroyIdentityService(); -#endif // fallthrough case CLEAN_GROUP_MANAGER: DestroyGroupManager(); @@ -1815,13 +1718,11 @@ static int32_t InitAllModules(void) CleanAllModules(CLEAN_CALLBACK); break; } -#ifdef DEV_AUTH_IS_ENABLE if ((res = InitIdentityService()) != HC_SUCCESS) { LOGE("[End]: [Service]: Failed to init IS module!"); CleanAllModules(CLEAN_GROUP_MANAGER); break; } -#endif if ((res = InitDevSessionManager()) != HC_SUCCESS) { LOGE("[End]: [Service]: Failed to init dev session manager module!"); CleanAllModules(CLEAN_IDENTITY_SERVICE); @@ -1940,7 +1841,6 @@ DEVICE_AUTH_API_PUBLIC int InitDeviceAuthService(void) if (res != HC_SUCCESS) { return res; } -#ifdef DEV_AUTH_IS_ENABLE res = AllocCa(); if (res != HC_SUCCESS) { DestroyGmAndGa(); @@ -1952,15 +1852,12 @@ DEVICE_AUTH_API_PUBLIC int InitDeviceAuthService(void) DestroyCa(); return res; } -#endif InitOsAccountAdapter(); res = InitAllModules(); if (res != HC_SUCCESS) { DestroyGmAndGa(); -#ifdef DEV_AUTH_IS_ENABLE DestroyCa(); DestroyCredentialMgr(); -#endif return res; } INIT_PERFORMANCE_DUMPER(); @@ -1980,16 +1877,12 @@ DEVICE_AUTH_API_PUBLIC void DestroyDeviceAuthService(void) } DestroyTaskManager(); DestroyDevSessionManager(); -#ifdef DEV_AUTH_IS_ENABLE DestroyIdentityService(); -#endif DestroyGroupManager(); DestroyGmAndGa(); DestroyAccountTaskManager(); -#ifdef DEV_AUTH_IS_ENABLE DestroyCa(); DestroyCredentialMgr(); -#endif DestroyModules(); DestroyCredMgr(); DestroyChannelManager(); @@ -2049,7 +1942,6 @@ DEVICE_AUTH_API_PUBLIC const GroupAuthManager *GetGaInstance(void) return g_groupAuthManager; } -#ifdef DEV_AUTH_IS_ENABLE DEVICE_AUTH_API_PUBLIC const CredManager *GetCredMgrInstance(void) { if (g_credManager == NULL) { @@ -2063,8 +1955,11 @@ DEVICE_AUTH_API_PUBLIC const CredManager *GetCredMgrInstance(void) g_credManager->queryCredInfoByCredId = QueryCredInfoByCredId; g_credManager->deleteCredential = DeleteCredential; g_credManager->updateCredInfo = UpdateCredInfo; + g_credManager->agreeCredential = AgreeCredential; g_credManager->registerChangeListener = RegisterChangeListener; g_credManager->unregisterChangeListener = UnregisterChangeListener; + g_credManager->deleteCredByParams = DeleteCredByParams; + g_credManager->batchUpdateCredentials = BatchUpdateCredentials; g_credManager->destroyInfo = DestroyInfo; return g_credManager; @@ -2080,5 +1975,4 @@ DEVICE_AUTH_API_PUBLIC const CredAuthManager *GetCredAuthInstance(void) g_credAuthManager->processCredData = ProcessCredData; g_credAuthManager->authCredential = AuthCredential; return g_credAuthManager; -} -#endif \ No newline at end of file +} \ No newline at end of file diff --git a/services/deviceauth.gni b/services/deviceauth.gni index d900dca0..b3796e8f 100644 --- a/services/deviceauth.gni +++ b/services/deviceauth.gni @@ -20,6 +20,7 @@ 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" +cred_session_path = "${services_path}/identity_service/session" privacy_enhancement_path = "${services_path}/privacy_enhancement" dev_frameworks_path = "${services_path}/frameworks" group_manager_path = "${services_path}/legacy/group_manager" @@ -35,6 +36,7 @@ identity_service_inc = [ "${identity_service_path}/inc", "${cred_data_manager_path}/inc", "${cred_listener_path}/inc", + "${cred_session_path}/inc", ] identity_service_files = [ "${identity_service_path}/src/identity_service.c", @@ -43,6 +45,14 @@ identity_service_files = [ "${cred_data_manager_path}/src/credential_data_manager.c", "${cred_data_manager_path}/src/cred_tlv_parser.c", "${cred_listener_path}/src/cred_listener.c", + "${cred_session_path}/src/cred_session_util.c", +] +identity_service_mock_files = [ + "${identity_service_path}/src/mock/identity_service_mock.c", + "${identity_service_path}/src/mock/identity_operation_mock.c", + "${cred_data_manager_path}/src/mock/credential_data_manager_mock.c", + "${cred_listener_path}/src/mock/cred_listener_mock.c", + "${cred_session_path}/src/mock/cred_session_util_mock.c", ] inc_path = [ @@ -491,6 +501,12 @@ if (enable_session_v2 == true) { "${identity_manager_path}/src/identity_p2p.c", "${identity_manager_path}/src/identity_pin.c", ] + if (enable_identity_service) { + identity_manager_files += [ "${identity_manager_path}/src/identity_cred.c" ] + } else { + identity_manager_files += + [ "${identity_manager_path}/src/mock/identity_cred_mock.c" ] + } } else { identity_manager_files = [ "${identity_manager_path}/src/mock/identity_manager_mock.c", diff --git a/services/frameworks/src/permission_adapter/permission_adapter.cpp b/services/frameworks/src/permission_adapter/permission_adapter.cpp index a2816e94..86b3c278 100644 --- a/services/frameworks/src/permission_adapter/permission_adapter.cpp +++ b/services/frameworks/src/permission_adapter/permission_adapter.cpp @@ -115,4 +115,15 @@ int32_t CheckPermission(int32_t methodId) int32_t GetCallingUid(void) { return IPCSkeleton::GetCallingUid(); -} \ No newline at end of file +} + +int32_t CheckInterfacePermission(const char *permission) +{ + AccessTokenID accessTokenId = IPCSkeleton::GetCallingTokenID(); + int result = AccessTokenKit::VerifyAccessToken(accessTokenId, permission); + if (result != PERMISSION_GRANTED) { + LOGE("The permission is not granted!"); + return HC_ERROR; + } + return HC_SUCCESS; +} diff --git a/services/identity_service/inc/identity_operation.h b/services/identity_service/inc/identity_operation.h index e1ce680f..5c55e9e8 100644 --- a/services/identity_service/inc/identity_operation.h +++ b/services/identity_service/inc/identity_operation.h @@ -20,100 +20,42 @@ #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 KEY_VALUE_MAX_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(int32_t osAccountId, Uint8Buff credIdByte, Credential *credential, uint8_t method, - Uint8Buff publicKey); +int32_t AddKeyValueToHuks(int32_t osAccountId, Uint8Buff *credIdByte, Credential *credential, 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 AddUpdateInfoToJson(QueryCredentialParams *queryParams, CJson *baseInfoJson); +int32_t GetValidKeyAlias(int32_t osAccountId, const char *credId, Uint8Buff *credIdHashBuff); int32_t CheckOwnerUidPermission(Credential *credential); +int32_t CheckAndDelInvalidCred(int32_t osAccountId, const char *selfCredId, Uint8Buff *selfCredIdByte); +int32_t ComputePskAndDelInvalidKey(int32_t osAccountId, uint8_t credAlgo, + Uint8Buff *selfCredIdByte, Uint8Buff *peerKeyAlias, Uint8Buff *agreeCredIdByte); int32_t DelCredById(int32_t osAccountId, const char *credId); +int32_t EraseUpdateCredIdInSelfVec(CredentialVec *updateCredVec, CredentialVec *selfCredVec); int32_t GenerateCredId(int32_t osAccountId, Credential *credential, Uint8Buff *credIdByte); +int32_t GenerateCredKeyAlias(const char *credId, const char *deviceId, Uint8Buff *alias); 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 GetCredIdsFromCredVec(int32_t osAccountId, CJson *reqJson, CredentialVec *credentialVec, CJson *credIdJson); +int32_t GetQueryJsonStr(CJson *baseInfoJson, char **queryJsonStr); +int32_t GetUpdateCredVec(int32_t osAccountId, CJson *updateInfo, + QueryCredentialParams *queryParams, CredentialVec *updateCredVec); +int32_t ImportAgreeKeyValue(int32_t osAccountId, Credential *agreeCredential, Uint8Buff *keyValue, + Uint8Buff *peerKeyAlias); +bool IsCredHashMatch(Credential *credential, CJson *reqJson); int32_t CheckAndSetCredInfo(int32_t osAccountId, Credential *credential, CJson *json, uint8_t *method, Uint8Buff *publicKey); +int32_t SetAgreeCredInfo(int32_t osAccountId, CJson *reqJson, + Credential *agreeCredential, Uint8Buff *keyValue, Uint8Buff *agreeCredIdByte); int32_t SetQueryParamsFromJson(QueryCredentialParams *queryParams, CJson *json); +int32_t SetRequiredParamsFromJson(QueryCredentialParams *queryParams, CJson *baseInfoJson); +int32_t SetUpdateToQueryParams(CJson *json, QueryCredentialParams *queryParams); int32_t UpdateInfoFromJson(Credential *credential, CJson *json); #ifdef __cplusplus diff --git a/services/identity_service/inc/identity_service.h b/services/identity_service/inc/identity_service.h index aa786cb8..a884b9f7 100644 --- a/services/identity_service/inc/identity_service.h +++ b/services/identity_service/inc/identity_service.h @@ -28,8 +28,14 @@ int32_t QueryCredInfoByCredId(int32_t osAccountId, const char *credId, char **re int32_t DeleteCredential(int32_t osAccountId, const char *credId); +int32_t DeleteCredByParams(int32_t osAccountId, const char *requestParams, char **returnData); + int32_t UpdateCredInfo(int32_t osAccountId, const char *credId, const char *requestParams); +int32_t BatchUpdateCredentials(int32_t osAccountId, const char *requestParams, char **returnData); + +int32_t AgreeCredential(int32_t osAccountId, const char *selfCredId, const char *requestParams, char **returnData); + int32_t RegisterChangeListener(const char *appId, CredChangeListener *listener); int32_t UnregisterChangeListener(const char *appId); diff --git a/services/identity_service/inc/identity_service_defines.h b/services/identity_service/inc/identity_service_defines.h new file mode 100644 index 00000000..75cd04ac --- /dev/null +++ b/services/identity_service/inc/identity_service_defines.h @@ -0,0 +1,113 @@ +/* + * 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_DEFINES_H +#define IDENTITY_SERVICE_DEFINES_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_DEVICE_LIST "authorizedDeviceList" +#define FIELD_AUTHORIZED_APP_LIST "authorizedAppList" +#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_BASE_CRED_INFO "baseCredInfo" +#define FIELD_ADD_CRED_PARAM_LIST "addCredParamList" +#define FIELD_CRED_ID_LIST "credIdList" +#define FIELD_BASE_INFO "baseInfo" +#define FIELD_UPDATE_LISTS "updateLists" +#define FIELD_INTERFACE_PERMISSION "ohos.permission.ACCESS_DEVICE_AUTH_CRED_MGR" +#define DEFAULT_VAL 0 +#define RAND_NUM_LENGTH 16 +#define KEY_VALUE_MAX_LENGTH 128 +#define PAKE_ED25519_KEY_PAIR_LEN 32 +#define MAX_INT64_SIZE 20 +#define MAX_CRED_SIZE 5000 +#define ALGO_KEY_LEN 32 +#define AES_128_KEY_LEN 16 +#define PSK_LEN 32 +#define DEFAULT_EX_INFO_VAL (-1) +#define UPDATE_MATCHED_NUM_ZERO 0 +#define UPDATE_MATCHED_NUM_ONE 1 + +#ifdef __cplusplus +extern "C" { +#endif + + +enum { + METHOD_GENERATE = 1, + METHOD_IMPORT = 2, +}; + +enum { + ACCOUNT_RELATED = 1, + ACCOUNT_UNRELATED = 2, + ACCOUNT_SHARED = 3, +}; + +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 { + SUBJECT_MASTER_CONTROLLER = 1, + SUBJECT_ACCESSORY_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, +}; + +#ifdef __cplusplus +} +#endif + +#endif \ 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 index f0af57e3..2f57c1b9 100644 --- a/services/identity_service/inc/identity_service_impl.h +++ b/services/identity_service/inc/identity_service_impl.h @@ -28,8 +28,14 @@ int32_t QueryCredInfoByCredIdImpl(int32_t osAccountId, const char *credId, char int32_t DeleteCredentialImpl(int32_t osAccountId, const char *credId); +int32_t DeleteCredByParamsImpl(int32_t osAccountId, const char *requestParams, char **returnData); + int32_t UpdateCredInfoImpl(int32_t osAccountId, const char *credId, const char *requestParams); +int32_t BatchUpdateCredsImpl(int32_t osAccountId, const char *requestParams, char **returnData); + +int32_t AgreeCredentialImpl(int32_t osAccountId, const char *selfCredId, const char *requestParams, char **returnData); + int32_t RegCredListener(const char *appId, const CredChangeListener *listener); int32_t UnRegCredListener(const char *appId); diff --git a/services/identity_service/listener/src/mock/cred_listener_mock.c b/services/identity_service/listener/src/mock/cred_listener_mock.c new file mode 100644 index 00000000..38191e98 --- /dev/null +++ b/services/identity_service/listener/src/mock/cred_listener_mock.c @@ -0,0 +1,66 @@ +/* + * 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_types.h" +#include "securec.h" + +void OnCredAdd(const char *credId, const char *credInfo) +{ + (void)credId; + (void)credInfo; +} + +void OnCredDelete(const char *credId, const char *credInfo) +{ + (void)credId; + (void)credInfo; +} + +void OnCredUpdate(const char *credId, const char *credInfo) +{ + (void)credId; + (void)credInfo; +} + +bool IsCredListenerSupported(void) +{ + return false; +} + +int32_t InitCredListener(void) +{ + return IS_ERR_NOT_SUPPORT; +} + +void DestroyCredListener(void) +{ + return; +} + +int32_t AddCredListener(const char *appId, const CredChangeListener *listener) +{ + (void)appId; + (void)listener; + return IS_ERR_NOT_SUPPORT; +} + +int32_t RemoveCredListener(const char *appId) +{ + (void)appId; + return IS_ERR_NOT_SUPPORT; +} diff --git a/services/identity_service/session/inc/cred_session_util.h b/services/identity_service/session/inc/cred_session_util.h new file mode 100644 index 00000000..a1506d0d --- /dev/null +++ b/services/identity_service/session/inc/cred_session_util.h @@ -0,0 +1,31 @@ +/* + * 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_SESSION_H +#define CRED_SESSION_H + +#include "json_utils.h" + +#ifdef __cplusplus +extern "C" { +#endif + +int32_t BuildClientCredContext(int32_t osAccountId, int64_t requestId, CJson *context, const char **returnAppId); +int32_t BuildServerCredContext(int64_t requestId, CJson *context, char **returnPeerUdid, const char **returnAppId); + +#ifdef __cplusplus +} +#endif +#endif diff --git a/services/identity_service/session/src/cred_session_util.c b/services/identity_service/session/src/cred_session_util.c new file mode 100644 index 00000000..40588397 --- /dev/null +++ b/services/identity_service/session/src/cred_session_util.c @@ -0,0 +1,416 @@ +/* + * 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_session_util.h" + +#include "hc_log.h" +#include "identity_service.h" +#include "device_auth.h" +#include "common_defs.h" +#include "device_auth_defines.h" +#include "hc_types.h" +#include "hc_dev_info.h" +#include "json_utils.h" +#include "os_account_adapter.h" +#include "identity_service_defines.h" + +static int32_t AddChannelInfoToContext(int32_t channelType, int64_t channelId, CJson *context) +{ + if (AddIntToJson(context, FIELD_CHANNEL_TYPE, channelType) != HC_SUCCESS) { + LOGE("add channelType to context fail."); + return HC_ERR_JSON_ADD; + } + if (AddByteToJson(context, FIELD_CHANNEL_ID, (uint8_t *)&channelId, sizeof(int64_t)) != HC_SUCCESS) { + LOGE("add channelId to context fail."); + return HC_ERR_JSON_ADD; + } + return HC_SUCCESS; +} + +static int32_t AddCredIdToContextIfNeeded(CJson *context) +{ + CJson *credJson = GetObjFromJson(context, FIELD_CREDENTIAL_OBJ); + if (credJson == NULL) { + LOGE("Get self credential fail."); + return HC_ERR_JSON_GET; + } + uint8_t credType = ACCOUNT_RELATED; + if (GetUint8FromJson(context, FIELD_CRED_TYPE, &credType) != HC_SUCCESS) { + LOGE("Get credential type fail."); + return HC_ERR_JSON_GET; + } + if (credType != ACCOUNT_SHARED) { + LOGI("No need to add across account credential id to context"); + return HC_SUCCESS; + } + const char *credId = GetStringFromJson(context, FIELD_CRED_ID); + if (AddStringToJson(context, FIELD_ACROSS_ACCOUNT_CRED_ID, credId) != HC_SUCCESS) { + LOGE("add across account credential id to context fail."); + return HC_ERR_JSON_ADD; + } + return HC_SUCCESS; +} + +static int32_t CheckConfirmationExist(const CJson *context) +{ + uint32_t confirmation = REQUEST_REJECTED; + if (GetUnsignedIntFromJson(context, FIELD_CONFIRMATION, &confirmation) != HC_SUCCESS) { + LOGE("Failed to get confimation from json!"); + return HC_ERR_JSON_GET; + } + if (confirmation == REQUEST_ACCEPTED) { + LOGI("The service accepts this request!"); + } else { + LOGW("The service rejects this request!"); + } + return HC_SUCCESS; +} + +static const char *GetAppIdByContext(const CJson *context) +{ + const char *pinCode = GetStringFromJson(context, FIELD_PIN_CODE); + if (pinCode == NULL) { + const CJson *json = GetObjFromJson(context, FIELD_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 QueryAndAddSelfCredToContext(int32_t osAccountId, CJson *context) +{ + const char *credId = GetStringFromJson(context, FIELD_CRED_ID); + 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, FIELD_CREDENTIAL_OBJ, credDataJson) != HC_SUCCESS) { + LOGE("add local credential object to context fail."); + FreeJson(credDataJson); + return HC_ERR_JSON_ADD; + } + FreeJson(credDataJson); + return HC_SUCCESS; +} + +static bool CheckIsCredBind(CJson *context) +{ + const char *pinCode = GetStringFromJson(context, FIELD_PIN_CODE); + bool isBind = true; + if (pinCode == NULL || HcStrlen(pinCode) == 0) { + isBind = false; + } + return isBind; +} + +static int32_t AddAuthIdToCredContext(CJson *context) +{ + 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; + } + return HC_SUCCESS; +} + +static int32_t BuildClientCredBindContext(int32_t osAccountId, int64_t requestId, + CJson *context, const char **returnAppId) +{ + const char *appId = GetAppIdByContext(context); + if (appId == NULL) { + LOGE("get appId fail."); + return HC_ERR_JSON_GET; + } + if (AddBoolToJson(context, FIELD_IS_BIND, true) != 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_ACCOUNT_UNRELATED) != HC_SUCCESS) { + LOGE("add opCode to context fail."); + return HC_ERR_JSON_ADD; + } + if (AddAuthIdToCredContext(context)) { + return HC_ERR_JSON_ADD; + } + *returnAppId = appId; + return AddChannelInfoToContext(SERVICE_CHANNEL, DEFAULT_CHANNEL_ID, context); +} + +static int32_t SetContextOpCode(CJson *context) +{ + uint8_t credType = ACCOUNT_UNRELATED; + if (GetUint8FromJson(context, FIELD_CRED_TYPE, &credType) != HC_SUCCESS) { + LOGE("get int from json failed!"); + return HC_ERR_JSON_GET; + } + switch (credType) { + case ACCOUNT_RELATED: + if (AddIntToJson(context, FIELD_OPERATION_CODE, AUTH_FORM_IDENTICAL_ACCOUNT) != HC_SUCCESS) { + LOGE("add identical account code to context fail."); + return HC_ERR_JSON_ADD; + } + break; + case ACCOUNT_SHARED: + if (AddIntToJson(context, FIELD_OPERATION_CODE, AUTH_FORM_ACROSS_ACCOUNT) != HC_SUCCESS) { + LOGE("add across account code to context fail."); + return HC_ERR_JSON_ADD; + } + break; + default: + LOGE("unsupport cred type."); + return HC_ERR_UNSUPPORTED_OPCODE; + } + return HC_SUCCESS; +} + +static int32_t BuildClientCredAuthContext(int32_t osAccountId, int64_t requestId, + CJson *context, const char **returnAppId) +{ + int32_t res = QueryAndAddSelfCredToContext(osAccountId, context); + if (res != HC_SUCCESS) { + return res; + } + const char *appId = GetAppIdByContext(context); + if (appId == NULL) { + LOGE("get appId fail."); + return HC_ERR_JSON_GET; + } + 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 (SetContextOpCode(context) != HC_SUCCESS) { + LOGE("add opCode to context fail."); + return HC_ERR_JSON_ADD; + } + if (AddCredIdToContextIfNeeded(context) != HC_SUCCESS) { + LOGE("add across account credential id to context fail."); + return HC_ERR_JSON_ADD; + } + *returnAppId = appId; + return AddChannelInfoToContext(SERVICE_CHANNEL, DEFAULT_CHANNEL_ID, context); +} + +int32_t BuildClientCredContext(int32_t osAccountId, int64_t requestId, CJson *context, const char **returnAppId) +{ + if (context == NULL) { + LOGE("input context is null ptr!"); + return HC_ERR_INVALID_PARAMS; + } + if (CheckIsCredBind(context)) { + return BuildClientCredBindContext(osAccountId, requestId, context, returnAppId); + } + return BuildClientCredAuthContext(osAccountId, requestId, context, returnAppId); +} + +static int32_t AddOsAccountIdToContextIfValid(CJson *context) +{ + int32_t osAccountId = ANY_OS_ACCOUNT; + (void)GetIntFromJson(context, FIELD_OS_ACCOUNT_ID, &osAccountId); + osAccountId = DevAuthGetRealOsAccountLocalId(osAccountId); + LOGI("[OsAccountId]: %d", osAccountId); + if (osAccountId == INVALID_OS_ACCOUNT) { + 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; + } + if (AddIntToJson(context, FIELD_OS_ACCOUNT_ID, osAccountId) != HC_SUCCESS) { + LOGE("add operationCode to context fail."); + return HC_ERR_JSON_ADD; + } + return HC_SUCCESS; +} + +static int32_t BuildServerCredBindContext(int64_t requestId, CJson *context, + char **returnPeerUdid, const char **returnAppId) +{ + int32_t res = CheckConfirmationExist(context); + if (res != HC_SUCCESS) { + return res; + } + res = AddOsAccountIdToContextIfValid(context); + if (res != HC_SUCCESS) { + return res; + } + if (AddBoolToJson(context, FIELD_IS_BIND, true) != HC_SUCCESS) { + LOGE("add isBind to context fail."); + return HC_ERR_JSON_ADD; + } + if (AddBoolToJson(context, FIELD_IS_CLIENT, false) != HC_SUCCESS) { + LOGE("add isClient to context fail."); + return HC_ERR_JSON_ADD; + } + const char *appId = GetAppIdByContext(context); + if (appId == NULL) { + LOGE("get appId Fail."); + return HC_ERR_JSON_GET; + } + if (AddBoolToJson(context, FIELD_IS_CRED_AUTH, true) != 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; + } + if (AddStringToJson(context, FIELD_APP_ID, appId) != HC_SUCCESS) { + LOGE("add appId to context fail."); + return HC_ERR_JSON_ADD; + } + if (AddAuthIdToCredContext(context)) { + return HC_ERR_JSON_ADD; + } + *returnAppId = appId; + return AddChannelInfoToContext(SERVICE_CHANNEL, DEFAULT_CHANNEL_ID, context); +} + +static int32_t BuildServerCredAuthContext(int64_t requestId, CJson *context, + char **returnPeerUdid, const char **returnAppId) +{ + int32_t res = CheckConfirmationExist(context); + if (res != HC_SUCCESS) { + return res; + } + res = AddOsAccountIdToContextIfValid(context); + if (res != HC_SUCCESS) { + return res; + } + int32_t osAccountId = ANY_OS_ACCOUNT; + (void)GetIntFromJson(context, FIELD_OS_ACCOUNT_ID, &osAccountId); + 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, false) != HC_SUCCESS) { + LOGE("add isClient to context fail."); + return HC_ERR_JSON_ADD; + } + if (((res = QueryAndAddSelfCredToContext(osAccountId, context)) != HC_SUCCESS || + (res = AddCredIdToContextIfNeeded(context) != HC_SUCCESS))) { + return res; + } + const char *appId = GetAppIdByContext(context); + if (appId == NULL) { + LOGE("get appId Fail."); + return HC_ERR_JSON_GET; + } + if (AddBoolToJson(context, FIELD_IS_CRED_AUTH, true) != 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; + } + if (AddStringToJson(context, FIELD_APP_ID, appId) != HC_SUCCESS) { + LOGE("add appId to context fail."); + return HC_ERR_JSON_ADD; + } + *returnAppId = appId; + return AddChannelInfoToContext(SERVICE_CHANNEL, DEFAULT_CHANNEL_ID, context); +} + +int32_t BuildServerCredContext(int64_t requestId, CJson *context, char **returnPeerUdid, const char **returnAppId) +{ + if (context == NULL) { + LOGE("input context is null ptr!"); + return HC_ERR_INVALID_PARAMS; + } + if (CheckIsCredBind(context)) { + return BuildServerCredBindContext(requestId, context, returnPeerUdid, returnAppId); + } + return BuildServerCredAuthContext(requestId, context, returnPeerUdid, returnAppId); +} diff --git a/services/identity_service/session/src/mock/cred_session_util_mock.c b/services/identity_service/session/src/mock/cred_session_util_mock.c new file mode 100644 index 00000000..9545bdd0 --- /dev/null +++ b/services/identity_service/session/src/mock/cred_session_util_mock.c @@ -0,0 +1,41 @@ +/* + * 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_session_util.h" + +#include "hc_log.h" +#include "common_defs.h" +#include "device_auth_defines.h" +#include "hc_types.h" +#include "json_utils.h" +#include "identity_service_defines.h" + +int32_t BuildClientCredContext(int32_t osAccountId, int64_t requestId, CJson *context, const char **returnAppId) +{ + (void)osAccountId; + (void)requestId; + (void)context; + (void)returnAppId; + return IS_ERR_NOT_SUPPORT; +} + +int32_t BuildServerCredContext(int64_t requestId, CJson *context, char **returnPeerUdid, const char **returnAppId) +{ + (void)requestId; + (void)context; + (void)returnPeerUdid; + (void)returnAppId; + return IS_ERR_NOT_SUPPORT; +} diff --git a/services/identity_service/src/identity_operation.c b/services/identity_service/src/identity_operation.c index aa66cc29..7e1f1d59 100644 --- a/services/identity_service/src/identity_operation.c +++ b/services/identity_service/src/identity_operation.c @@ -25,6 +25,7 @@ #include "hal_error.h" #include "hc_log.h" #include "hc_time.h" +#include "identity_service_defines.h" #ifdef DEV_AUTH_PERMISSION_ENABLE #include "permission_adapter.h" @@ -311,10 +312,9 @@ static int32_t GenerateKeyValue(int32_t osAccountId, return IS_SUCCESS; } LOGI("The keyValue corresponding to the credId does not exist in HUKS, generate keyValue."); - 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; - int32_t ret = GetLoaderInstance()->generateKeyPairWithStorage(&keyParams, keyLen, algo, purpose, &exInfo); + uint32_t keyLen = (credential->algorithmType == ALGO_TYPE_AES_128) ? AES_128_KEY_LEN : ALGO_KEY_LEN; + int32_t ret = GetLoaderInstance()->generateKeyPairWithStorage(&keyParams, keyLen, algo, + KEY_PURPOSE_KEY_AGREE, &exInfo); if (ret == HAL_ERR_HUKS) { LOGE("Huks generateKeyPair failed!"); return IS_ERR_HUKS_GENERATE_KEY_FAILED; @@ -327,9 +327,18 @@ static int32_t GenerateKeyValue(int32_t osAccountId, return IS_SUCCESS; } -static int32_t ImportKeyValue(KeyParams keyParams, Uint8Buff keyValue, Algorithm algo, ExtraInfo exInfo) +static int32_t ImportKeyValue(KeyParams keyParams, + Uint8Buff *keyValue, Algorithm algo, ExtraInfo exInfo, uint8_t subject) { - int32_t ret = GetLoaderInstance()->importPublicKey(&keyParams, &keyValue, algo, &exInfo); + int32_t ret; + + if (algo == AES) { + KeyPurpose keyPurpose = subject == SUBJECT_MASTER_CONTROLLER ? KEY_PURPOSE_MAC : KEY_PURPOSE_DERIVE; + ret = GetLoaderInstance()->importSymmetricKey(&keyParams, keyValue, keyPurpose, &exInfo); + } else { + ret = GetLoaderInstance()->importPublicKey(&keyParams, keyValue, algo, &exInfo); + } + if (ret == HAL_ERR_HUKS) { LOGE("Huks import key failed!"); return IS_ERR_HUKS_IMPORT_KEY_FAILED; @@ -342,40 +351,51 @@ static int32_t ImportKeyValue(KeyParams keyParams, Uint8Buff keyValue, Algorithm return IS_SUCCESS; } -int32_t AddKeyValueToHuks(int32_t osAccountId, Uint8Buff credIdByte, Credential *credential, uint8_t method, - Uint8Buff keyValue) +int32_t AddKeyValueToHuks(int32_t osAccountId, Uint8Buff *credIdByte, Credential *credential, uint8_t method, + Uint8Buff *keyValue) { - int32_t ret; - KeyParams keyParams = { { credIdByte.val, credIdByte.length, true }, false, osAccountId }; + if (credential->credType == ACCOUNT_SHARED && keyValue->val == NULL) { + return IS_SUCCESS; + } + 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 }; Algorithm algo = GetAlgoFromCred(credential->algorithmType); - - if (method == METHOD_GENERATE) { - ret = GenerateKeyValue(osAccountId, credential, keyParams, algo, exInfo); - if (ret != IS_SUCCESS) { - return ret; - } - } - if (method == METHOD_IMPORT) { - ret = ImportKeyValue(keyParams, keyValue, algo, exInfo); - if (ret != IS_SUCCESS) { - return ret; - } + switch (method) { + case METHOD_GENERATE: + return GenerateKeyValue(osAccountId, credential, keyParams, algo, exInfo); + case METHOD_IMPORT: + return ImportKeyValue(keyParams, keyValue, algo, exInfo, credential->subject); + default: + return IS_ERR_INVALID_PARAMS; } - return IS_SUCCESS; } -int32_t CheckCredIdExistInHuks(int32_t osAccountId, const char *credId, Uint8Buff *credIdHashBuff) +int32_t GetValidKeyAlias(int32_t osAccountId, const char *credId, Uint8Buff *credIdHashBuff) { - int32_t ret = HexStringToByte(credId, credIdHashBuff->val, credIdHashBuff->length); + uint32_t credIdByteLen = HcStrlen(credId) / BYTE_TO_HEX_OPER_LENGTH; + Uint8Buff returnCredIdByte = { NULL, credIdByteLen }; + returnCredIdByte.val = (uint8_t *)HcMalloc(credIdByteLen, 0); + if (returnCredIdByte.val == NULL) { + LOGE("Failed to malloc credIdByteLen"); + return IS_ERR_ALLOC_MEMORY; + } + int32_t ret = HexStringToByte(credId, returnCredIdByte.val, returnCredIdByte.length); if (ret != IS_SUCCESS) { LOGE("Failed to convert credId to byte, invalid credId, ret = %d", ret); + HcFree(returnCredIdByte.val); return IS_ERR_INVALID_HEX_STRING; } - return GetLoaderInstance()->checkKeyExist(credIdHashBuff, false, osAccountId); + ret = GetLoaderInstance()->checkKeyExist(&returnCredIdByte, false, osAccountId); + if (ret != IS_SUCCESS) { + HcFree(returnCredIdByte.val); + return ret; + } + credIdHashBuff->val = returnCredIdByte.val; + credIdHashBuff->length = credIdByteLen; + return IS_SUCCESS; } int32_t AddCredAndSaveDb(int32_t osAccountId, Credential *credential) @@ -404,29 +424,29 @@ static bool IsValueInArray(uint8_t value, uint8_t *array, uint32_t length) return false; } -static int32_t SetAccListFromArray(Credential *credential, CJson *accountList) +static int32_t SetVectorFromList(StringVector *dataVector, CJson *dataList) { - int32_t accountListNum = GetItemNum(accountList); - for (int32_t i = 0; i < accountListNum; i++) { - CJson *item = GetItemFromArray(accountList, i); + int32_t dataListNum = GetItemNum(dataList); + for (int32_t i = 0; i < dataListNum; i++) { + CJson *item = GetItemFromArray(dataList, 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."); + const char *data = GetStringValue(item); + if (data == NULL) { + LOGE("the data of list is null."); return IS_ERR_JSON_GET; } - HcString strAcc = CreateString(); - if (!StringSetPointer(&strAcc, account)) { - LOGE("Failed to set strAcc!"); - DeleteString(&strAcc); + HcString strData = CreateString(); + if (!StringSetPointer(&strData, data)) { + LOGE("Failed to set strData!"); + DeleteString(&strData); return IS_ERR_MEMORY_COPY; } - if (credential->authorizedAccountList.pushBackT(&credential->authorizedAccountList, strAcc) == NULL) { - LOGE("Failed to push strAcc!"); - DeleteString(&strAcc); + if (dataVector->pushBackT(dataVector, strData) == NULL) { + LOGE("Failed to push strData to vector!"); + DeleteString(&strData); return IS_ERR_MEMORY_COPY; } } @@ -435,10 +455,12 @@ static int32_t SetAccListFromArray(Credential *credential, CJson *accountList) static int32_t SetMethodFromJson(CJson *json, uint8_t *method) { - if (GetUint8FromJson(json, FIELD_METHOD, method) != IS_SUCCESS) { + int32_t methodInt32 = DEFAULT_VAL; + if (GetIntFromJson(json, FIELD_METHOD, &methodInt32) != IS_SUCCESS) { LOGE("Failed to get method from credReqParam"); return IS_ERR_JSON_GET; } + *method = (uint8_t)methodInt32; uint8_t methodRange[] = { METHOD_GENERATE, METHOD_IMPORT }; uint32_t length = sizeof(methodRange) / sizeof(methodRange[0]); @@ -456,7 +478,7 @@ static int32_t SetCredType(Credential *credential, CJson *json) return IS_ERR_JSON_GET; } - uint8_t credTypeRange[] = { ACCOUNTT_RELATED, ACCOUNTT_UNRELATED }; + uint8_t credTypeRange[] = { ACCOUNT_RELATED, ACCOUNT_UNRELATED, ACCOUNT_SHARED }; uint32_t length = sizeof(credTypeRange) / sizeof(credTypeRange[0]); if (!IsValueInArray(credential->credType, credTypeRange, length)) { LOGE("credential type is invalid."); @@ -513,7 +535,7 @@ static int32_t SetAlgorithmType(Credential *credential, CJson *json) LOGE("Failed to get algorithm type from credReqParam"); return IS_ERR_JSON_GET; } - uint8_t algorithmTypeRange[] = { ALGO_TYPE_P256, ALGO_TYPE_ED25519 }; + uint8_t algorithmTypeRange[] = { ALGO_TYPE_AES_256, ALGO_TYPE_P256, ALGO_TYPE_ED25519 }; uint32_t length = sizeof(algorithmTypeRange) / sizeof(algorithmTypeRange[0]); if (!IsValueInArray(credential->algorithmType, algorithmTypeRange, length)) { LOGE("Invalid algorithm type"); @@ -528,7 +550,7 @@ static int32_t SetSubject(Credential *credential, CJson *json) LOGE("Failed to get subject from credReqParam"); return IS_ERR_JSON_GET; } - uint8_t subjectRange[] = { SELF_DEVICE, OTHER_DEVICE }; + uint8_t subjectRange[] = { SUBJECT_MASTER_CONTROLLER, SUBJECT_ACCESSORY_DEVICE }; uint32_t length = sizeof(subjectRange) / sizeof(subjectRange[0]); if (!IsValueInArray(credential->subject, subjectRange, length)) { LOGE("Invalid subject"); @@ -542,7 +564,7 @@ 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) { + if (credential->credType == ACCOUNT_UNRELATED) { return IS_SUCCESS; } uint8_t issuerRange[] = { SYSTEM_ACCOUNT, APP_ACCOUNT, DOMANIN_ACCOUNT }; @@ -600,7 +622,7 @@ static int32_t SetProofType(Credential *credential, CJson *json) 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)) { + if (credential->credType == ACCOUNT_RELATED && (userId == NULL || strcmp(userId, "") == 0)) { LOGE("Invalid params, when credType is account, userId is NULL"); return IS_ERR_INVALID_PARAMS; } @@ -614,9 +636,12 @@ static int32_t SetUserId(Credential *credential, CJson *json) return IS_SUCCESS; } -static int32_t SetKeyValueFromJson(CJson *json, uint8_t method, Uint8Buff *keyValue) +static int32_t SetKeyValueFromJson(CJson *json, Credential *credential, uint8_t method, Uint8Buff *keyValue) { const char *keyValueStr = GetStringFromJson(json, FIELD_KEY_VALUE); + if (credential->credType == ACCOUNT_SHARED && keyValueStr == NULL) { + return IS_SUCCESS; + } if (method == METHOD_GENERATE) { if (HcStrlen(keyValueStr) > 0) { LOGE("Invalid params, when method is generate, keyValue should not be passed in"); @@ -647,7 +672,7 @@ static int32_t SetKeyValueFromJson(CJson *json, uint8_t method, Uint8Buff *keyVa 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 && + if (credential->credType == ACCOUNT_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; @@ -661,18 +686,20 @@ static int32_t SetPeerUserSpaceId(Credential *credential, CJson *json, uint8_t m return IS_SUCCESS; } -static int32_t SetAccList(Credential *credential, CJson *json) +static int32_t SetAppList(Credential *credential, CJson *json) { - CJson *accountList = GetObjFromJson(json, FIELD_AUTHORIZED_ACCOUNT_LIST); - - if (accountList == NULL) { - LOGW("Failed to get authorized account list from credReqParam"); + CJson *appList = GetObjFromJson(json, FIELD_AUTHORIZED_APP_LIST); + if (appList == NULL) { + if (credential->authorizedScope == SCOPE_APP) { + LOGE("when authorizedScope is APP, authorizedAppList is required"); + return IS_ERR_INVALID_PARAMS; + } return IS_SUCCESS; } - int32_t ret = SetAccListFromArray(credential, accountList); + int32_t ret = SetVectorFromList(&credential->authorizedAppList, appList); if (ret != IS_SUCCESS) { - LOGE("Failed to set authorized account list from credReqParam"); + LOGE("Failed to set authorized app list from credReqParam"); return ret; } return IS_SUCCESS; @@ -746,7 +773,7 @@ static int32_t SetRequiredField(Credential *credential, CJson *json, uint8_t *me } ret = SetCredOwner(credential, json); - if (ret != HC_SUCCESS) { + if (ret != IS_SUCCESS) { return ret; } @@ -773,36 +800,33 @@ static int32_t SetSpecialRequiredField(Credential *credential, CJson *json, uint return ret; } - ret = SetKeyValueFromJson(json, *method, keyValue); + ret = SetKeyValueFromJson(json, credential, *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) { + HcFree(keyValue->val); return ret; } - ret = SetExtendInfo(credential, json); + ret = SetAppList(credential, json); if (ret != IS_SUCCESS) { + HcFree(keyValue->val); return ret; } + return IS_SUCCESS; +} - ret = SetCredIdFromJson(credential, json); +static int32_t SetOptionalField(Credential *credential, CJson *json) +{ + int32_t ret = SetExtendInfo(credential, json); if (ret != IS_SUCCESS) { return ret; } - return IS_SUCCESS; + return SetCredIdFromJson(credential, json); } int32_t CheckAndSetCredInfo(int32_t osAccountId, @@ -820,11 +844,14 @@ int32_t CheckAndSetCredInfo(int32_t osAccountId, ret = SetOptionalField(credential, json); if (ret != IS_SUCCESS) { + HcFree(keyValue->val); return ret; } ret = CheckOutMaxCredSize(osAccountId, StringGet(&credential->credOwner)); - + if (ret != IS_SUCCESS) { + HcFree(keyValue->val); + } return ret; } @@ -871,38 +898,118 @@ int32_t SetQueryParamsFromJson(QueryCredentialParams *queryParams, CJson *json) return IS_SUCCESS; } -int32_t GetCredIdsFromCredVec(CredentialVec credentialVec, CJson *credIdJson, int32_t osAccountId) +static int32_t IsOriginalStrHashMatch(const char *originalStr, const char *subHashedStr) +{ + Uint8Buff originalStrBuffer = { (uint8_t *)originalStr, (uint32_t)HcStrlen(originalStr) }; + uint8_t hashedStrBytes[SHA256_LEN] = { 0 }; + Uint8Buff hashedStrBuffer = { hashedStrBytes, sizeof(hashedStrBytes) }; + int32_t result = GetLoaderInstance()->sha256(&originalStrBuffer, &hashedStrBuffer); + if (result != IS_SUCCESS) { + LOGE("sha256 failed, ret:%d", result); + return result; + } + uint32_t hashedStrHexLength = SHA256_LEN * BYTE_TO_HEX_OPER_LENGTH + 1; + char *hashedStrHex = (char *)HcMalloc(hashedStrHexLength, 0); + if (hashedStrHex == NULL) { + LOGE("malloc hashedStrHex string failed"); + return IS_ERR_ALLOC_MEMORY; + } + result = ByteToHexString(hashedStrBytes, SHA256_LEN, hashedStrHex, hashedStrHexLength); + if (result != IS_SUCCESS) { + LOGE("Byte to hexString failed, ret:%d", result); + HcFree(hashedStrHex); + return result; + } + char *upperSubHashedStr = NULL; + result = ToUpperCase(subHashedStr, &upperSubHashedStr); + if (result != IS_SUCCESS) { + LOGE("Failed to convert the input sub hashed string to upper case!"); + HcFree(hashedStrHex); + return result; + } + if (strstr((const char *)hashedStrHex, upperSubHashedStr) != NULL) { + LOGI("Original string hash is match!"); + HcFree(hashedStrHex); + HcFree(upperSubHashedStr); + return IS_SUCCESS; + } + HcFree(hashedStrHex); + HcFree(upperSubHashedStr); + return IS_ERROR; +} + +bool IsCredHashMatch(Credential *credential, CJson *reqJson) +{ + const char *deviceIdHash = GetStringFromJson(reqJson, FIELD_DEVICE_ID_HASH); + if (deviceIdHash != NULL && + IsOriginalStrHashMatch(StringGet(&credential->deviceId), deviceIdHash) != IS_SUCCESS) { + return false; + } + + const char *userIdHash = GetStringFromJson(reqJson, FIELD_USER_ID_HASH); + if (userIdHash != NULL && + IsOriginalStrHashMatch(StringGet(&credential->userId), userIdHash) != IS_SUCCESS) { + return false; + } + + return true; +} + +static int32_t CheckCredKeyExist(int32_t osAccountId, const Credential *credential, const char *credId) +{ + // ACCOUNT_SHARED type dose not need check key + if (credential->credType == ACCOUNT_SHARED) { + return HC_SUCCESS; + } + uint32_t credIdByteLen = HcStrlen(credId) / BYTE_TO_HEX_OPER_LENGTH; + Uint8Buff credIdByte = { NULL, credIdByteLen }; + credIdByte.val = (uint8_t *)HcMalloc(credIdByteLen, 0); + if (credIdByte.val == NULL) { + LOGE("Failed to malloc credIdByteLen"); + return IS_ERR_ALLOC_MEMORY; + } + int32_t ret = HexStringToByte(credId, credIdByte.val, credIdByte.length); + if (ret != IS_SUCCESS) { + LOGE("Failed to convert credId to byte, invalid credId, ret = %d", ret); + HcFree(credIdByte.val); + return IS_ERR_INVALID_HEX_STRING; + } + ret = GetLoaderInstance()->checkKeyExist(&credIdByte, false, osAccountId); + HcFree(credIdByte.val); + switch (ret) { + // delete invaild credId + case HAL_ERR_KEY_NOT_EXIST: + LOGE("Huks key not exist!"); + DelCredById(osAccountId, credId); + break; + case HAL_ERR_HUKS: + LOGE("Failed to check key exist in huks"); + break; + case IS_SUCCESS: + break; + default: + LOGE("CheckKeyExist failed"); + break; + } + return ret; +} + +int32_t GetCredIdsFromCredVec(int32_t osAccountId, CJson *reqJson, CredentialVec *credentialVec, CJson *credIdJson) { uint32_t index; int32_t ret; Credential **ptr; - FOR_EACH_HC_VECTOR(credentialVec, index, ptr) { + FOR_EACH_HC_VECTOR(*credentialVec, index, ptr) { if (*ptr == NULL) { continue; } Credential *credential = (Credential *)(*ptr); const char *credId = StringGet(&credential->credId); - uint32_t credIdByteLen = HcStrlen(credId) / BYTE_TO_HEX_OPER_LENGTH; - Uint8Buff credIdByte = { NULL, credIdByteLen }; - credIdByte.val = (uint8_t *)HcMalloc(credIdByteLen, 0); - if (credIdByte.val == NULL) { - LOGE("Failed to malloc credIdByte"); - return IS_ERR_ALLOC_MEMORY; - } - - ret = CheckCredIdExistInHuks(osAccountId, credId, &credIdByte); - HcFree(credIdByte.val); - if (ret == HAL_ERR_KEY_NOT_EXIST) { - LOGE("Huks key not exist!"); - DelCredById(osAccountId, credId); + if (CheckCredKeyExist(osAccountId, credential, credId) != IS_SUCCESS) { + LOGE("CredKey not Exist!"); continue; } - if (ret == HAL_ERR_HUKS) { - LOGE("Failed to check key exist in huks"); - continue; - } - if (ret != IS_SUCCESS) { - LOGW("CheckKeyExist failed"); + if (!IsCredHashMatch(credential, reqJson)) { continue; } @@ -925,13 +1032,13 @@ static int32_t UpdateExtendInfo(Credential *credential, const char *extendInfo) return IS_SUCCESS; } -static int32_t UpdateAccountList(Credential *credential, CJson *accountList) +static int32_t UpdateAppList(Credential *credential, CJson *appList) { - DestroyStrVector(&credential->authorizedAccountList); - credential->authorizedAccountList = CreateStrVector(); - int32_t ret = SetAccListFromArray(credential, accountList); + DestroyStrVector(&credential->authorizedAppList); + credential->authorizedAppList = CreateStrVector(); + int32_t ret = SetVectorFromList(&credential->authorizedAppList, appList); if (ret != IS_SUCCESS) { - LOGE("Failed to update authorizedAccountList"); + LOGE("Failed to update authorizedAppList"); return ret; } return IS_SUCCESS; @@ -940,9 +1047,9 @@ static int32_t UpdateAccountList(Credential *credential, CJson *accountList) int32_t UpdateInfoFromJson(Credential *credential, CJson *json) { const char *extendInfo = GetStringFromJson(json, FIELD_EXTEND_INFO); - CJson *accountList = GetObjFromJson(json, FIELD_AUTHORIZED_ACCOUNT_LIST); + CJson *appList = GetObjFromJson(json, FIELD_AUTHORIZED_APP_LIST); - if (extendInfo == NULL && accountList == NULL) { + if (extendInfo == NULL && appList == NULL) { LOGE("Failed to set update info: no valid field"); return IS_ERR_INVALID_PARAMS; } @@ -956,14 +1063,11 @@ int32_t UpdateInfoFromJson(Credential *credential, CJson *json) } } - if (accountList != NULL) { - ret = UpdateAccountList(credential, accountList); - if (ret != IS_SUCCESS) { - return ret; - } + if (appList != NULL) { + ret = UpdateAppList(credential, appList); } - return IS_SUCCESS; + return ret; } int32_t DelCredById(int32_t osAccountId, const char *credId) @@ -1034,3 +1138,257 @@ int32_t CheckOwnerUidPermission(Credential *credential) #endif return IS_SUCCESS; } + +int32_t GenerateCredKeyAlias(const char *credId, const char *deviceId, Uint8Buff *alias) +{ + if ((credId == NULL) || (deviceId == NULL) || (alias == NULL)) { + LOGE("Invalid input params"); + return IS_ERR_NULL_PTR; + } + uint32_t credIdLen = HcStrlen(credId); + uint32_t deviceIdLen = HcStrlen(deviceId); + uint32_t aliasStrLen = credIdLen + deviceIdLen + 1; + uint8_t *aliasStr = (uint8_t *)HcMalloc(aliasStrLen, 0); + if (aliasStr == NULL) { + LOGE("Failed to malloc for key aliasStr."); + return IS_ERR_ALLOC_MEMORY; + } + Uint8Buff aliasBuff = { + aliasStr, + aliasStrLen + }; + if (memcpy_s(aliasBuff.val, aliasBuff.length, credId, credIdLen) != EOK) { + LOGE("Failed to copy credId."); + HcFree(aliasStr); + return IS_ERR_MEMORY_COPY; + } + if (memcpy_s(aliasBuff.val + credIdLen, deviceIdLen, + deviceId, deviceIdLen) != EOK) { + LOGE("Failed to copy deviceId."); + HcFree(aliasStr); + return IS_ERR_MEMORY_COPY; + } + int32_t ret = GetLoaderInstance()->sha256(&aliasBuff, alias); + HcFree(aliasStr); + if (ret != HAL_SUCCESS) { + LOGE("Compute alias failed"); + } + return ret; +} + +static int32_t ComputeAndSavePskInner(int32_t osAccountId, uint8_t credAlgo, const Uint8Buff *selfKeyAlias, + const Uint8Buff *peerKeyAlias, Uint8Buff *sharedKeyAlias) +{ + KeyParams selfKeyParams = { { selfKeyAlias->val, selfKeyAlias->length, true }, false, osAccountId }; + uint8_t peerPubKeyVal[KEY_VALUE_MAX_LENGTH] = { 0 }; + Uint8Buff peerPubKeyBuff = { peerPubKeyVal, KEY_VALUE_MAX_LENGTH }; + KeyParams keyParams = { { peerKeyAlias->val, peerKeyAlias->length, true }, false, osAccountId }; + int32_t res = GetLoaderInstance()->exportPublicKey(&keyParams, &peerPubKeyBuff); + if (res != IS_SUCCESS) { + LOGE("Failed to export peer public key!"); + return res; + } + KeyBuff peerKeyBuff = { peerPubKeyBuff.val, peerPubKeyBuff.length, false }; + Algorithm algo = GetAlgoFromCred(credAlgo); + res = GetLoaderInstance()->agreeSharedSecretWithStorage(&selfKeyParams, &peerKeyBuff, algo, + PSK_LEN, sharedKeyAlias); + if (res != IS_SUCCESS) { + LOGE("Agree psk failed."); + } + return res; +} + +int32_t SetAgreeCredInfo(int32_t osAccountId, CJson *reqJson, + Credential *agreeCredential, Uint8Buff *keyValue, Uint8Buff *agreeCredIdByte) +{ + if (AddIntToJson(reqJson, FIELD_METHOD, METHOD_IMPORT) != IS_SUCCESS) { + LOGE("Failed to add method to json!"); + return IS_ERR_JSON_ADD; + } + uint8_t method = DEFAULT_VAL; + int32_t ret = CheckAndSetCredInfo(osAccountId, agreeCredential, reqJson, &method, keyValue); + if (ret != IS_SUCCESS) { + return ret; + } + if ((ret = GenerateCredId(osAccountId, agreeCredential, agreeCredIdByte)) != IS_SUCCESS) { + HcFree(keyValue->val); + return ret; + } + return IS_SUCCESS; +} + +int32_t ImportAgreeKeyValue(int32_t osAccountId, Credential *agreeCredential, Uint8Buff *keyValue, + Uint8Buff *peerKeyAlias) +{ + int32_t ret = GenerateCredKeyAlias( + StringGet(&agreeCredential->credId), StringGet(&agreeCredential->deviceId), peerKeyAlias); + if (ret != IS_SUCCESS) { + LOGE("Failed to generate peer key alias!"); + return ret; + } + ret = AddKeyValueToHuks(osAccountId, peerKeyAlias, agreeCredential, METHOD_IMPORT, keyValue); + if (ret != IS_SUCCESS) { + LOGE("Failed to add peer key value to huks!"); + return ret; + } + return IS_SUCCESS; +} + +int32_t CheckAndDelInvalidCred(int32_t osAccountId, const char *selfCredId, Uint8Buff *selfCredIdByte) +{ + int32_t ret = GetValidKeyAlias(osAccountId, selfCredId, selfCredIdByte); + if (ret == HAL_ERR_KEY_NOT_EXIST) { + LOGE("Huks key not exist!"); + DelCredById(osAccountId, selfCredId); + 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; + } + return IS_SUCCESS; +} + +int32_t ComputePskAndDelInvalidKey(int32_t osAccountId, uint8_t credAlgo, Uint8Buff *selfCredIdByte, + Uint8Buff *peerKeyAlias, Uint8Buff *agreeCredIdByte) +{ + int32_t ret = ComputeAndSavePskInner(osAccountId, credAlgo, selfCredIdByte, peerKeyAlias, agreeCredIdByte); + if (ret != IS_SUCCESS) { + LOGE("Failed to compute and save psk!"); + return ret; + } + ret = GetLoaderInstance()->deleteKey(peerKeyAlias, false, osAccountId); + if (ret != IS_SUCCESS) { + LOGE("Failed to delete key from HUKS"); + return ret; + } + return IS_SUCCESS; +} + +int32_t SetRequiredParamsFromJson(QueryCredentialParams *queryParams, CJson *baseInfoJson) +{ + if (GetUint8FromJson(baseInfoJson, FIELD_CRED_TYPE, &(queryParams->credType)) != IS_SUCCESS) { + LOGE("Failed to set query params: credType"); + return IS_ERR_JSON_GET; + } + if (queryParams->credType != ACCOUNT_SHARED) { + LOGE("Not support for credType %d, only support for ACCOUNT_SHARED", queryParams->credType); + return IS_ERR_NOT_SUPPORT; + } + const char *credOwner = GetStringFromJson(baseInfoJson, FIELD_CRED_OWNER); + if (credOwner == NULL || strcmp(credOwner, "") == 0) { + LOGE("Failed to set query params: credOwner"); + return IS_ERR_JSON_GET; + } + queryParams->credOwner = credOwner; + return IS_SUCCESS; +} + +int32_t SetUpdateToQueryParams(CJson *json, QueryCredentialParams *queryParams) +{ + const char *userId = GetStringFromJson(json, FIELD_USER_ID); + if (userId == NULL || strcmp(userId, "") == 0) { + LOGE("Failed to set query params: userId"); + return IS_ERR_JSON_GET; + } + queryParams->userId = userId; + const char *deviceId = GetStringFromJson(json, FIELD_DEVICE_ID); + if (deviceId == NULL || strcmp(deviceId, "") == 0) { + LOGE("Failed to set query params: deviceId"); + return IS_ERR_JSON_GET; + } + queryParams->deviceId = deviceId; + return IS_SUCCESS; +} + +static int32_t EraseCredIdInVec(const char *credId, CredentialVec *credVec) +{ + uint32_t index = 0; + Credential **item; + while (index < credVec->size(credVec)) { + item = credVec->getp(credVec, index); + if (item == NULL || *item == NULL) { + index++; + continue; + } + const char *itemCredId = StringGet(&(*item)->credId); + if (itemCredId != NULL && strcmp(credId, itemCredId) == 0) { + credVec->eraseElement(credVec, item, index); + return IS_SUCCESS; + } + index++; + } + return IS_ERROR; +} + +int32_t AddUpdateInfoToJson(QueryCredentialParams *queryParams, CJson *baseInfoJson) +{ + if (AddStringToJson(baseInfoJson, FIELD_USER_ID, queryParams->userId) != IS_SUCCESS) { + LOGE("add userId to baseInfoJson fail."); + return IS_ERR_JSON_ADD; + } + if (AddStringToJson(baseInfoJson, FIELD_DEVICE_ID, queryParams->deviceId) != IS_SUCCESS) { + LOGE("add deviceId to baseInfoJson fail."); + return IS_ERR_JSON_ADD; + } + if (AddIntToJson(baseInfoJson, FIELD_METHOD, METHOD_IMPORT) != IS_SUCCESS) { + LOGE("Failed to add method to baseInfoJson!"); + return IS_ERR_JSON_ADD; + } + return IS_SUCCESS; +} + +int32_t EraseUpdateCredIdInSelfVec(CredentialVec *updateCredVec, CredentialVec *selfCredVec) +{ + Credential **cred = updateCredVec->getp(updateCredVec, 0); + if (cred == NULL || *cred == NULL) { + LOGE("Failed to get first cred"); + return IS_ERR_NULL_PTR; + } + const char *updateCredId = StringGet(&(*cred)->credId); + if (updateCredId == NULL) { + LOGE("Failed to get updateCredId"); + return IS_ERR_NULL_PTR; + } + return EraseCredIdInVec(updateCredId, selfCredVec); +} + +int32_t GetQueryJsonStr(CJson *baseInfoJson, char **queryJsonStr) +{ + const char *credOwner = GetStringFromJson(baseInfoJson, FIELD_CRED_OWNER); + if (credOwner == NULL) { + LOGE("Failed to get credOwner"); + return IS_ERR_INVALID_PARAMS; + } + CJson *queryJson = CreateJson(); + if (queryJson == NULL) { + LOGE("Failed to create queryJson"); + return IS_ERR_JSON_CREATE; + } + if (AddStringToJson(queryJson, FIELD_CRED_OWNER, credOwner)) { + FreeJson(queryJson); + return IS_ERR_JSON_ADD; + } + *queryJsonStr = PackJsonToString(queryJson); + FreeJson(queryJson); + if (*queryJsonStr == NULL) { + LOGE("Failed to pack queryJson to string"); + return IS_ERR_PACKAGE_JSON_TO_STRING_FAIL; + } + return IS_SUCCESS; +} + +int32_t GetUpdateCredVec(int32_t osAccountId, CJson *updateInfo, + QueryCredentialParams *queryParams, CredentialVec *updateCredVec) +{ + int32_t ret = SetUpdateToQueryParams(updateInfo, queryParams); + if (ret != IS_SUCCESS) { + LOGE("Failed to set updateLists to query params"); + return ret; + } + return QueryCredentials(osAccountId, queryParams, updateCredVec); +} diff --git a/services/identity_service/src/identity_service.c b/services/identity_service/src/identity_service.c index 7f3824cc..728b097b 100644 --- a/services/identity_service/src/identity_service.c +++ b/services/identity_service/src/identity_service.c @@ -106,6 +106,22 @@ int32_t DeleteCredential(int32_t osAccountId, const char *credId) return DeleteCredentialImpl(osAccountId, credId); } +int32_t DeleteCredByParams(int32_t osAccountId, const char *requestParams, char **returnData) +{ + SET_LOG_MODE(TRACE_MODE); + + if (requestParams == NULL || returnData == NULL) { + LOGE("Failed to batch delete credential, NULL params!"); + return IS_ERR_INVALID_PARAMS; + } + + if (!IsOsAccountUnlocked(osAccountId)) { + LOGE("Os account is not unlocked!"); + return IS_ERR_OS_ACCOUNT_NOT_UNLOCKED; + } + return DeleteCredByParamsImpl(osAccountId, requestParams, returnData); +} + int32_t UpdateCredInfo(int32_t osAccountId, const char *credId, const char *requestParams) { SET_LOG_MODE(TRACE_MODE); @@ -123,6 +139,39 @@ int32_t UpdateCredInfo(int32_t osAccountId, const char *credId, const char *requ return UpdateCredInfoImpl(osAccountId, credId, requestParams); } +int32_t BatchUpdateCredentials(int32_t osAccountId, const char *requestParams, char **returnData) +{ + SET_LOG_MODE(TRACE_MODE); + + if (requestParams == NULL || returnData == NULL) { + LOGE("Failed to batch update credential, NULL params!"); + return IS_ERR_INVALID_PARAMS; + } + + if (!IsOsAccountUnlocked(osAccountId)) { + LOGE("Os account is not unlocked!"); + return IS_ERR_OS_ACCOUNT_NOT_UNLOCKED; + } + return BatchUpdateCredsImpl(osAccountId, requestParams, returnData); +} + +int32_t AgreeCredential(int32_t osAccountId, const char *selfCredId, const char *requestParams, char **returnData) +{ + SET_LOG_MODE(TRACE_MODE); + + if (selfCredId == NULL || requestParams == NULL || returnData == NULL) { + LOGE("Failed to agree credential, NULL params!"); + return IS_ERR_INVALID_PARAMS; + } + + if (!IsOsAccountUnlocked(osAccountId)) { + LOGE("Os account is not unlocked!"); + return IS_ERR_OS_ACCOUNT_NOT_UNLOCKED; + } + + return AgreeCredentialImpl(osAccountId, selfCredId, requestParams, returnData); +} + int32_t RegisterChangeListener(const char *appId, CredChangeListener *listener) { SET_LOG_MODE(TRACE_MODE); diff --git a/services/identity_service/src/identity_service_impl.c b/services/identity_service/src/identity_service_impl.c index 46f53d91..4a112391 100644 --- a/services/identity_service/src/identity_service_impl.c +++ b/services/identity_service/src/identity_service_impl.c @@ -13,20 +13,20 @@ * limitations under the License. */ -#include "identity_service.h" +#include "identity_service_impl.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" +#include "identity_service_defines.h" static int32_t AddCredentialImplInner(int32_t osAccountId, CJson *reqJson, Credential *credential, char **returnData) @@ -42,7 +42,7 @@ static int32_t AddCredentialImplInner(int32_t osAccountId, CJson *reqJson, Crede HcFree(keyValue.val); return ret; } - if ((ret = AddKeyValueToHuks(osAccountId, credIdByte, credential, method, keyValue)) != IS_SUCCESS) { + if ((ret = AddKeyValueToHuks(osAccountId, &credIdByte, credential, method, &keyValue)) != IS_SUCCESS) { HcFree(keyValue.val); HcFree(credIdByte.val); return ret; @@ -91,29 +91,20 @@ int32_t ExportCredentialImpl(int32_t osAccountId, const char *credId, char **ret } DestroyCredential(credential); - uint32_t credIdByteLen = HcStrlen(credId) / BYTE_TO_HEX_OPER_LENGTH; - Uint8Buff credIdByte = { NULL, credIdByteLen }; - credIdByte.val = (uint8_t *)HcMalloc(credIdByteLen, 0); - if (credIdByte.val == NULL) { - LOGE("Failed to malloc credIdByte"); - return IS_ERR_ALLOC_MEMORY; - } + Uint8Buff credIdByte = { NULL, 0 }; - ret = CheckCredIdExistInHuks(osAccountId, credId, &credIdByte); + ret = GetValidKeyAlias(osAccountId, credId, &credIdByte); if (ret == HAL_ERR_KEY_NOT_EXIST) { LOGE("Huks key not exist!"); DelCredById(osAccountId, credId); - HcFree(credIdByte.val); return IS_ERR_HUKS_KEY_NOT_EXIST; } if (ret == HAL_ERR_HUKS) { LOGE("Huks check key exist failed"); - HcFree(credIdByte.val); return IS_ERR_HUKS_CHECK_KEY_EXIST_FAILED; } if (ret != IS_SUCCESS) { LOGE("Failed to check key exist in HUKS"); - HcFree(credIdByte.val); return ret; } @@ -152,14 +143,15 @@ int32_t QueryCredentialByParamsImpl(int32_t osAccountId, const char *requestPara CredentialVec credentialVec = CreateCredentialVec(); int32_t ret = QueryCredentials(osAccountId, &queryParams, &credentialVec); - FreeJson(reqJson); if (ret != IS_SUCCESS) { LOGE("Failed to query credentials"); + FreeJson(reqJson); ClearCredentialVec(&credentialVec); return ret; } if (credentialVec.size(&credentialVec) == 0) { LOGW("No credential found"); + FreeJson(reqJson); ClearCredentialVec(&credentialVec); return GenerateReturnEmptyArrayStr(returnData); } @@ -167,14 +159,15 @@ int32_t QueryCredentialByParamsImpl(int32_t osAccountId, const char *requestPara CJson *credIdJson = CreateJsonArray(); if (credIdJson == NULL) { LOGE("Failed to create credIdJson object"); + FreeJson(reqJson); ClearCredentialVec(&credentialVec); return IS_ERR_JSON_CREATE; } - ret = GetCredIdsFromCredVec(credentialVec, credIdJson, osAccountId); + ret = GetCredIdsFromCredVec(osAccountId, reqJson, &credentialVec, credIdJson); + FreeJson(reqJson); ClearCredentialVec(&credentialVec); if (ret != IS_SUCCESS) { - LOGE("Failed to get credIds from credentials"); FreeJson(credIdJson); return ret; } @@ -267,6 +260,78 @@ int32_t DeleteCredentialImpl(int32_t osAccountId, const char *credId) return IS_SUCCESS; } +static int32_t DelCredsWithHash(int32_t osAccountId, CJson *reqJson, CredentialVec *credentialVec, CJson *credIdJson) +{ + Credential **ptr; + uint32_t index; + int32_t ret = IS_SUCCESS; + FOR_EACH_HC_VECTOR(*credentialVec, index, ptr) { + if (*ptr == NULL) { + continue; + } + Credential *credential = (Credential *)(*ptr); + const char *credId = StringGet(&credential->credId); + if (credId == NULL) { + LOGE("Failed to get credId"); + continue; + } + + if (!IsCredHashMatch(credential, reqJson)) { + continue; + } + + ret = AddStringToArray(credIdJson, credId); + if (ret != IS_SUCCESS) { + LOGE("Failed to add credId to json"); + return IS_ERR_JSON_ADD; + } + ret = DeleteCredentialImpl(osAccountId, credId); + } + return ret; +} + +int32_t DeleteCredByParamsImpl(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 delParams = InitQueryCredentialParams(); + SetQueryParamsFromJson(&delParams, reqJson); + CredentialVec credentialVec = CreateCredentialVec(); + + int32_t ret = QueryCredentials(osAccountId, &delParams, &credentialVec); + if (ret != IS_SUCCESS) { + LOGE("Failed to query credentials"); + FreeJson(reqJson); + ClearCredentialVec(&credentialVec); + return ret; + } + CJson *credIdJson = CreateJsonArray(); + if (credIdJson == NULL) { + LOGE("Failed to create credIdJson"); + FreeJson(reqJson); + ClearCredentialVec(&credentialVec); + return IS_ERR_JSON_CREATE; + } + ret = DelCredsWithHash(osAccountId, reqJson, &credentialVec, credIdJson); + FreeJson(reqJson); + ClearCredentialVec(&credentialVec); + if (ret != IS_SUCCESS) { + LOGE("Failed to get and delete credential in vec"); + 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 ret; +} + int32_t UpdateCredInfoImpl(int32_t osAccountId, const char *credId, const char *requestParams) { Credential *credential = NULL; @@ -306,6 +371,229 @@ int32_t UpdateCredInfoImpl(int32_t osAccountId, const char *credId, const char * return IS_SUCCESS; } +static int32_t AddUpdateCred(int32_t osAccountId, CJson *baseInfoJson, QueryCredentialParams *queryParams) +{ + int32_t ret = AddUpdateInfoToJson(queryParams, baseInfoJson); + if (ret != IS_SUCCESS) { + LOGE("Failed to add update info to json"); + return ret; + } + char *addCredReq = PackJsonToString(baseInfoJson); + if (addCredReq == NULL) { + LOGE("Failed to pack baseInfoJson to addCredReq"); + return IS_ERR_PACKAGE_JSON_TO_STRING_FAIL; + } + char *addRetStr = NULL; + ret = AddCredentialImpl(osAccountId, addCredReq, &addRetStr); + HcFree(addCredReq); + HcFree(addRetStr); + return ret; +} + +static int32_t DelCredInVec(int32_t osAccountId, CredentialVec *credVec) +{ + uint32_t index; + Credential **ptr; + int32_t ret = IS_SUCCESS; + FOR_EACH_HC_VECTOR(*credVec, index, ptr) { + if (*ptr == NULL) { + continue; + } + Credential *credential = (Credential *)(*ptr); + const char *credId = StringGet(&credential->credId); + if (credId == NULL) { + continue; + } + ret = DeleteCredentialImpl(osAccountId, credId); + if (ret != IS_SUCCESS) { + LOGE("Failed to delete credential, ret = %d", ret); + return ret; + } + } + return IS_SUCCESS; +} + +static int32_t ProcessAbnormalCreds(int32_t osAccountId, CJson *baseInfoJson, QueryCredentialParams *queryParams) +{ + int32_t ret = DelCredential(osAccountId, queryParams); + if (ret != IS_SUCCESS) { + LOGE("Failed to delete abnormal credentials, ret = %d", ret); + return ret; + } + return AddUpdateCred(osAccountId, baseInfoJson, queryParams); +} + +static int32_t HandleUpdateCredsBySize(int32_t osAccountId, CJson *baseInfoJson, + QueryCredentialParams *queryParams, CredentialVec *updateCredVec, CredentialVec *selfCredVec) +{ + int32_t ret = IS_ERROR; + uint32_t updateMatchSize = updateCredVec->size(updateCredVec); + switch (updateMatchSize) { + case UPDATE_MATCHED_NUM_ZERO: + ret = AddUpdateCred(osAccountId, baseInfoJson, queryParams); // == 0 need add + break; + case UPDATE_MATCHED_NUM_ONE: + ret = EraseUpdateCredIdInSelfVec(updateCredVec, selfCredVec); // update info exists in self vec + break; + default: + ret = ProcessAbnormalCreds(osAccountId, baseInfoJson, queryParams); // > 1 need del old + break; + } + return ret; +} + +static int32_t ProcessUpdateInfo(int32_t osAccountId, CJson *updateInfoList, + CJson *baseInfoJson, QueryCredentialParams *queryParams, CredentialVec *selfCredVec) +{ + int32_t ret = IS_SUCCESS; + int32_t updateInfoNum = GetItemNum(updateInfoList); + for (int32_t i = 0; i < updateInfoNum; i++) { + CJson *item = GetItemFromArray(updateInfoList, i); // shallow copy + if (item == NULL) { + LOGE("updateInfoList item is NULL"); + return IS_ERR_JSON_GET; + } + CredentialVec updateCredVec = CreateCredentialVec(); + ret = GetUpdateCredVec(osAccountId, item, queryParams, &updateCredVec); + if (ret != IS_SUCCESS) { + ClearCredentialVec(&updateCredVec); + return ret; + } + ret = HandleUpdateCredsBySize(osAccountId, baseInfoJson, queryParams, &updateCredVec, selfCredVec); + ClearCredentialVec(&updateCredVec); + if (ret != IS_SUCCESS) { + return ret; + } + } + return ret; +} + +static int32_t GetCurrentCredIds(int32_t osAccountId, CJson *baseInfoJson, char **returnData) +{ + char *queryStr = NULL; + int32_t ret = GetQueryJsonStr(baseInfoJson, &queryStr); + if (ret != IS_SUCCESS) { + return ret; + } + ret = QueryCredentialByParamsImpl(osAccountId, queryStr, returnData); + HcFree(queryStr); + return ret; +} + +static int32_t BatchUpdateCredsImplInner(int32_t osAccountId, + CJson *baseInfoJson, CJson *updateInfoList, char **returnData) +{ + QueryCredentialParams queryParams = InitQueryCredentialParams(); + int32_t ret = SetRequiredParamsFromJson(&queryParams, baseInfoJson); + if (ret != IS_SUCCESS) { + return ret; + } + + CredentialVec selfCredVec = CreateCredentialVec(); + ret = QueryCredentials(osAccountId, &queryParams, &selfCredVec); + if (ret != IS_SUCCESS) { + ClearCredentialVec(&selfCredVec); + return ret; + } + + ret = ProcessUpdateInfo(osAccountId, updateInfoList, baseInfoJson, &queryParams, &selfCredVec); + if (ret != IS_SUCCESS) { + ClearCredentialVec(&selfCredVec); + return ret; + } + + ret = DelCredInVec(osAccountId, &selfCredVec); + ClearCredentialVec(&selfCredVec); + if (ret != IS_SUCCESS) { + return ret; + } + return GetCurrentCredIds(osAccountId, baseInfoJson, returnData); +} + +int32_t BatchUpdateCredsImpl(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; + } + CJson *baseInfoJson = GetObjFromJson(reqJson, FIELD_BASE_INFO); + CJson *updateInfoList = GetObjFromJson(reqJson, FIELD_UPDATE_LISTS); + if (baseInfoJson == NULL || updateInfoList == NULL) { + LOGE("baseInfoJson or updateLists is NULL"); + FreeJson(reqJson); + return IS_ERR_INVALID_PARAMS; + } + int32_t ret = BatchUpdateCredsImplInner(osAccountId, baseInfoJson, updateInfoList, returnData); + FreeJson(reqJson); + return ret; +} + +static int32_t AgreeCredentialImplInner(int32_t osAccountId, const char *selfCredId, + CJson *reqJson, Credential *agreeCredential, char **returnData) +{ + Uint8Buff keyValue = { NULL, 0 }; + Uint8Buff agreeCredIdByte = { NULL, 0 }; + int32_t ret = SetAgreeCredInfo(osAccountId, reqJson, agreeCredential, &keyValue, &agreeCredIdByte); + if (ret != IS_SUCCESS) { + return ret; + } + + uint8_t peerKeyAliasVal[SHA256_LEN] = { 0 }; + Uint8Buff peerKeyAlias = { peerKeyAliasVal, SHA256_LEN }; + ret = ImportAgreeKeyValue(osAccountId, agreeCredential, &keyValue, &peerKeyAlias); + if (ret != IS_SUCCESS) { + HcFree(keyValue.val); + HcFree(agreeCredIdByte.val); + return ret; + } + + Uint8Buff selfCredIdByte = { NULL, 0 }; + ret = CheckAndDelInvalidCred(osAccountId, selfCredId, &selfCredIdByte); + if (ret != IS_SUCCESS) { + HcFree(keyValue.val); + HcFree(agreeCredIdByte.val); + return ret; + } + + ret = ComputePskAndDelInvalidKey(osAccountId, + agreeCredential->algorithmType, &selfCredIdByte, &peerKeyAlias, &agreeCredIdByte); + HcFree(keyValue.val); + HcFree(selfCredIdByte.val); + HcFree(agreeCredIdByte.val); + if (ret != IS_SUCCESS) { + return ret; + } + ret = AddCredAndSaveDb(osAccountId, agreeCredential); + if (ret != IS_SUCCESS) { + return ret; + } + if (DeepCopyString(StringGet(&agreeCredential->credId), returnData) != EOK) { + LOGE("Failed to return credId"); + return IS_ERR_MEMORY_COPY; + } + return IS_SUCCESS; +} + +int32_t AgreeCredentialImpl(int32_t osAccountId, const char *selfCredId, 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 *agreeCredential = CreateCredential(); + if (agreeCredential == NULL) { + LOGE("Failed to malloc agreeCredential"); + FreeJson(reqJson); + return IS_ERR_ALLOC_MEMORY; + } + int32_t ret = AgreeCredentialImplInner(osAccountId, selfCredId, reqJson, agreeCredential, returnData); + FreeJson(reqJson); + DestroyCredential(agreeCredential); + return ret; +} + int32_t RegCredListener(const char *appId, const CredChangeListener *listener) { if ((appId == NULL) || (listener == NULL)) { diff --git a/services/identity_service/src/mock/identity_operation_mock.c b/services/identity_service/src/mock/identity_operation_mock.c new file mode 100644 index 00000000..4c3bc633 --- /dev/null +++ b/services/identity_service/src/mock/identity_operation_mock.c @@ -0,0 +1,228 @@ +/* + * 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 "device_auth.h" +#include "device_auth_defines.h" +#include "hal_error.h" +#include "hc_log.h" +#include "identity_service_defines.h" + +int32_t GetCredentialById(int32_t osAccountId, const char *credId, Credential **returnEntry) +{ + (void)osAccountId; + (void)credId; + (void)returnEntry; + return IS_ERR_NOT_SUPPORT; +} + +int32_t GenerateCredId(int32_t osAccountId, Credential *credential, Uint8Buff *credIdByte) +{ + (void)osAccountId; + (void)credential; + (void)credIdByte; + return IS_ERR_NOT_SUPPORT; +} + +int32_t AddKeyValueToHuks(int32_t osAccountId, Uint8Buff *credIdByte, Credential *credential, uint8_t method, + Uint8Buff *keyValue) +{ + (void)osAccountId; + (void)credential; + (void)credIdByte; + (void)method; + (void)keyValue; + return IS_ERR_NOT_SUPPORT; +} + +int32_t GetValidKeyAlias(int32_t osAccountId, const char *credId, Uint8Buff *credIdHashBuff) +{ + (void)osAccountId; + (void)credId; + (void)credIdHashBuff; + return IS_ERR_NOT_SUPPORT; +} + +int32_t AddCredAndSaveDb(int32_t osAccountId, Credential *credential) +{ + (void)osAccountId; + (void)credential; + return IS_ERR_NOT_SUPPORT; +} + +int32_t CheckAndSetCredInfo(int32_t osAccountId, + Credential *credential, CJson *json, uint8_t *method, Uint8Buff *keyValue) +{ + (void)osAccountId; + (void)credential; + (void)json; + (void)method; + (void)keyValue; + return IS_ERR_NOT_SUPPORT; +} + +int32_t SetQueryParamsFromJson(QueryCredentialParams *queryParams, CJson *json) +{ + (void)queryParams; + (void)json; + return IS_ERR_NOT_SUPPORT; +} + +int32_t GetCredIdsFromCredVec(int32_t osAccountId, CJson *reqJson, CredentialVec *credentialVec, CJson *credIdJson) +{ + (void)osAccountId; + (void)reqJson; + (void)credentialVec; + (void)credIdJson; + return IS_ERR_NOT_SUPPORT; +} + +int32_t UpdateInfoFromJson(Credential *credential, CJson *json) +{ + (void)credential; + (void)json; + return IS_ERR_NOT_SUPPORT; +} + +int32_t DelCredById(int32_t osAccountId, const char *credId) +{ + (void)osAccountId; + (void)credId; + return IS_ERR_NOT_SUPPORT; +} + +int32_t AddKeyValueToReturn(Uint8Buff keyValue, char **returnData) +{ + (void)keyValue; + (void)returnData; + return IS_ERR_NOT_SUPPORT; +} + +int32_t GenerateReturnEmptyArrayStr(char **returnVec) +{ + (void)returnVec; + return IS_ERR_NOT_SUPPORT; +} + +int32_t CheckOwnerUidPermission(Credential *credential) +{ + (void)credential; + return IS_ERR_NOT_SUPPORT; +} + +int32_t GenerateCredKeyAlias(const char *credId, const char *deviceId, Uint8Buff *alias) +{ + (void)credId; + (void)deviceId; + (void)alias; + return IS_ERR_NOT_SUPPORT; +} + +int32_t SetAgreeCredInfo(int32_t osAccountId, CJson *reqJson, + Credential *agreeCredential, Uint8Buff *keyValue, Uint8Buff *agreeCredIdByte) +{ + (void)osAccountId; + (void)reqJson; + (void)agreeCredential; + (void)keyValue; + (void)agreeCredIdByte; + return IS_ERR_NOT_SUPPORT; +} + +int32_t ImportAgreeKeyValue(int32_t osAccountId, Credential *agreeCredential, Uint8Buff *keyValue, + Uint8Buff *peerKeyAlias) +{ + (void)osAccountId; + (void)agreeCredential; + (void)keyValue; + (void)peerKeyAlias; + return IS_ERR_NOT_SUPPORT; +} + +int32_t CheckAndDelInvalidCred(int32_t osAccountId, const char *selfCredId, Uint8Buff *selfCredIdByte) +{ + (void)osAccountId; + (void)selfCredId; + (void)selfCredIdByte; + return IS_ERR_NOT_SUPPORT; +} + +int32_t ComputePskAndDelInvalidKey(int32_t osAccountId, uint8_t credAlgo, Uint8Buff *selfCredIdByte, + Uint8Buff *peerKeyAlias, Uint8Buff *agreeCredIdByte) +{ + (void)osAccountId; + (void)credAlgo; + (void)selfCredIdByte; + (void)peerKeyAlias; + (void)agreeCredIdByte; + return IS_ERR_NOT_SUPPORT; +} + +int32_t SetRequiredParamsFromJson(QueryCredentialParams *queryParams, CJson *baseInfoJson) +{ + (void)queryParams; + (void)baseInfoJson; + return IS_ERR_NOT_SUPPORT; +} + +int32_t SetUpdateToQueryParams(CJson *json, QueryCredentialParams *queryParams) +{ + (void)json; + (void)queryParams; + return IS_ERR_NOT_SUPPORT; +} + +int32_t AddUpdateInfoToJson(QueryCredentialParams *queryParams, CJson *baseInfoJson) +{ + (void)queryParams; + (void)baseInfoJson; + return IS_ERR_NOT_SUPPORT; +} + +int32_t EraseUpdateCredIdInSelfVec(CredentialVec *updateCredVec, CredentialVec *selfCredVec) +{ + (void)updateCredVec; + (void)selfCredVec; + return IS_ERR_NOT_SUPPORT; +} + +int32_t GetQueryJsonStr(CJson *baseInfoJson, char **queryJsonStr) +{ + (void)baseInfoJson; + (void)queryJsonStr; + return IS_ERR_NOT_SUPPORT; +} + +int32_t GetUpdateCredVec(int32_t osAccountId, CJson *updateInfo, + QueryCredentialParams *queryParams, CredentialVec *updateCredVec) +{ + (void)osAccountId; + (void)updateInfo; + (void)queryParams; + (void)updateCredVec; + return IS_ERR_NOT_SUPPORT; +} + +bool IsCredHashMatch(Credential *credential, CJson *reqJson) +{ + (void)credential; + (void)reqJson; + return false; +} diff --git a/services/identity_service/src/mock/identity_service_mock.c b/services/identity_service/src/mock/identity_service_mock.c new file mode 100644 index 00000000..d6cb51bf --- /dev/null +++ b/services/identity_service/src/mock/identity_service_mock.c @@ -0,0 +1,119 @@ +/* + * 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" + +int32_t AddCredential(int32_t osAccountId, const char *requestParams, char **returnData) +{ + (void)osAccountId; + (void)requestParams; + (void)returnData; + return IS_ERR_NOT_SUPPORT; +} + +int32_t ExportCredential(int32_t osAccountId, const char *credId, char **returnData) +{ + (void)osAccountId; + (void)credId; + (void)returnData; + return IS_ERR_NOT_SUPPORT; +} + +int32_t QueryCredentialByParams(int32_t osAccountId, const char *requestParams, char **returnData) +{ + (void)osAccountId; + (void)requestParams; + (void)returnData; + return IS_ERR_NOT_SUPPORT; +} + +int32_t QueryCredInfoByCredId(int32_t osAccountId, const char *credId, char **returnData) +{ + (void)osAccountId; + (void)credId; + (void)returnData; + return IS_ERR_NOT_SUPPORT; +} + +int32_t DeleteCredential(int32_t osAccountId, const char *credId) +{ + (void)osAccountId; + (void)credId; + return IS_ERR_NOT_SUPPORT; +} + +int32_t DeleteCredByParams(int32_t osAccountId, const char *requestParams, char **returnData) +{ + (void)osAccountId; + (void)requestParams; + (void)returnData; + return IS_ERR_NOT_SUPPORT; +} + +int32_t UpdateCredInfo(int32_t osAccountId, const char *credId, const char *requestParams) +{ + (void)osAccountId; + (void)credId; + (void)requestParams; + return IS_ERR_NOT_SUPPORT; +} + +int32_t AgreeCredential(int32_t osAccountId, const char *selfCredId, const char *requestParams, char **returnData) +{ + (void)osAccountId; + (void)selfCredId; + (void)requestParams; + (void)returnData; + return IS_ERR_NOT_SUPPORT; +} + +int32_t BatchUpdateCredentials(int32_t osAccountId, const char *requestParams, char **returnData) +{ + (void)osAccountId; + (void)requestParams; + (void)returnData; + return IS_ERR_NOT_SUPPORT; +} + +int32_t RegisterChangeListener(const char *appId, CredChangeListener *listener) +{ + (void)appId; + (void)listener; + return IS_ERR_NOT_SUPPORT; +} + +int32_t UnregisterChangeListener(const char *appId) +{ + (void)appId; + return IS_ERR_NOT_SUPPORT; +} + +void DestroyInfo(char **returnData) +{ + (void)returnData; + return; +} + +int32_t InitIdentityService(void) +{ + return IS_SUCCESS; +} + +void DestroyIdentityService(void) +{ + return; +} \ No newline at end of file diff --git a/services/legacy/creds_manager/inc/creds_manager.h b/services/legacy/creds_manager/inc/creds_manager.h index b2b31c06..9ed1be54 100644 --- a/services/legacy/creds_manager/inc/creds_manager.h +++ b/services/legacy/creds_manager/inc/creds_manager.h @@ -32,8 +32,6 @@ 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 ISGetIdentityInfo(const CJson *context, bool isPseudonym, IdentityInfo **returnInfo); #ifdef __cplusplus } #endif diff --git a/services/legacy/creds_manager/src/creds_manager.c b/services/legacy/creds_manager/src/creds_manager.c index 8e699038..4bee2f4c 100644 --- a/services/legacy/creds_manager/src/creds_manager.c +++ b/services/legacy/creds_manager/src/creds_manager.c @@ -14,7 +14,6 @@ */ #include "creds_manager.h" -#include "identity_operation.h" #include "asy_token_manager.h" #include "cert_operation.h" #include "pseudonym_manager.h" @@ -77,7 +76,9 @@ static const AuthIdentity *getAuthIdentity(const CJson *in, const Uint8Buff *pre if (IsDirectAuth(in)) { identityType = AUTH_IDENTITY_TYPE_P2P; } else { - identityType = AUTH_IDENTITY_TYPE_GROUP; + bool isCredAuth = false; + (void)GetBoolFromJson(in, FIELD_IS_CRED_AUTH, &isCredAuth); + identityType = isCredAuth ? AUTH_IDENTITY_TYPE_CRED : AUTH_IDENTITY_TYPE_GROUP; } } LOGD("AuthIdentityType: %d", identityType); @@ -103,7 +104,9 @@ int32_t GetCredInfosByPeerIdentity(CJson *in, IdentityInfoVec *vec) if (IsDirectAuth(in)) { identityType = AUTH_IDENTITY_TYPE_P2P; } else { - identityType = AUTH_IDENTITY_TYPE_GROUP; + bool isCredAuth = false; + (void)GetBoolFromJson(in, FIELD_IS_CRED_AUTH, &isCredAuth); + identityType = isCredAuth ? AUTH_IDENTITY_TYPE_CRED : AUTH_IDENTITY_TYPE_GROUP; } } if (identityType == AUTH_IDENTITY_TYPE_INVALID) { @@ -208,7 +211,10 @@ int32_t GetCredInfoByPeerCert(const CJson *in, const CertInfo *certInfo, Identit authIdentityTest->getCredInfoByPeerCert(in, certInfo, returnInfo); #endif - const AuthIdentity *authIdentity = GetAuthIdentityByType(AUTH_IDENTITY_TYPE_GROUP); + bool isCredAuth = false; + (void)GetBoolFromJson(in, FIELD_IS_CRED_AUTH, &isCredAuth); + AuthIdentityType identityType = isCredAuth ? AUTH_IDENTITY_TYPE_CRED : AUTH_IDENTITY_TYPE_GROUP; + const AuthIdentity *authIdentity = GetAuthIdentityByType(identityType); if (authIdentity == NULL) { return HC_ERR_INVALID_PARAMS; } @@ -237,247 +243,12 @@ int32_t GetSharedSecretByPeerCert( authIdentityTest->getSharedSecretByPeerCert(in, peerCertInfo, protocolType, sharedSecret); #endif - const AuthIdentity *authIdentity = GetAuthIdentityByType(AUTH_IDENTITY_TYPE_GROUP); + bool isCredAuth = false; + (void)GetBoolFromJson(in, FIELD_IS_CRED_AUTH, &isCredAuth); + AuthIdentityType identityType = isCredAuth ? AUTH_IDENTITY_TYPE_CRED : AUTH_IDENTITY_TYPE_GROUP; + const AuthIdentity *authIdentity = GetAuthIdentityByType(identityType); if (authIdentity == NULL) { return HC_ERR_INVALID_PARAMS; } return authIdentity->getSharedSecretByPeerCert(in, peerCertInfo, protocolType, sharedSecret); -} - -static int32_t ConvertISProofTypeToCertType(uint32_t protocolType, IdentityProofType *returnType) -{ - if (protocolType == PROOF_TYPE_PSK) { - *returnType = PRE_SHARED; - return HC_SUCCESS; - } else if (protocolType == PROOF_TYPE_PKI) { - *returnType = CERTIFICATED; - return HC_SUCCESS; - } - return HC_ERR_NOT_SUPPORT; -} - -static int32_t ConvertISAlgToCertAlg(uint32_t alg, Algorithm *returnAlg) -{ - if (alg == ALGO_TYPE_P256) { - *returnAlg = P256; - return HC_SUCCESS; - } - return HC_ERR_NOT_SUPPORT; -} - -static int32_t ISSetISOEntity(IdentityInfo *info) -{ -#ifdef ENABLE_ACCOUNT_AUTH_ISO - ProtocolEntity *entity = (ProtocolEntity *)HcMalloc(sizeof(ProtocolEntity), 0); - if (entity == NULL) { - LOGE("Failed to alloc memory for ISO protocol entity!"); - return HC_ERR_ALLOC_MEMORY; - } - entity->protocolType = ALG_ISO; - entity->expandProcessCmds = 0; - 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; -#else - (void)info; - LOGE("ISO not support!"); - return HC_ERR_NOT_SUPPORT; -#endif -} - -static int32_t ISSetEcSpekeEntity(IdentityInfo *info, bool isNeedRefreshPseudonymId) -{ -#ifdef ENABLE_ACCOUNT_AUTH_EC_SPEKE - ProtocolEntity *entity = (ProtocolEntity *)HcMalloc(sizeof(ProtocolEntity), 0); - if (entity == NULL) { - LOGE("Failed to alloc memory for ec-speke protocol entity!"); - return HC_ERR_ALLOC_MEMORY; - } - entity->protocolType = ALG_EC_SPEKE; - entity->expandProcessCmds = 0; -#ifdef ENABLE_PSEUDONYM - if (isNeedRefreshPseudonymId) { - entity->expandProcessCmds |= CMD_MK_AGREE; - } -#else - (void)isNeedRefreshPseudonymId; -#endif - 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; -#else - (void)info; - (void)isNeedRefreshPseudonymId; - LOGE("ec speke not support!"); - return HC_ERR_NOT_SUPPORT; -#endif -} - -static int32_t ISSetCertInfoAndEntity(int32_t osAccountId, const CJson *credAuthInfo, - bool isPseudonym, IdentityInfo *info) -{ - 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 res = GetAccountAuthTokenManager()->getToken(osAccountId, token, userId, authId); - if (res != HC_SUCCESS) { - LOGE("Failed to get account token!"); - DestroyAccountToken(token); - return res; - } - res = GenerateCertInfo(&token->pkInfoStr, &token->pkInfoSignature, &info->proof.certInfo); - DestroyAccountToken(token); - if (res != HC_SUCCESS) { - LOGE("Failed to generate cert info!"); - return res; - } - uint32_t signAlg = 0; - if (GetUnsignedIntFromJson(credAuthInfo, FIELD_ALGORITHM_TYPE, &signAlg) != HC_SUCCESS) { - LOGE("Failed to get algorithm type!"); - return HC_ERR_JSON_GET; - } - res = ConvertISAlgToCertAlg(signAlg, &info->proof.certInfo.signAlg); - if (res != HC_SUCCESS) { - LOGE("unsupport algorithm type!"); - return res; - } - info->proof.certInfo.isPseudonym = isPseudonym; - bool isNeedRefreshPseudonymId = GetPseudonymInstance() - ->isNeedRefreshPseudonymId(osAccountId, userId); - res = ISSetEcSpekeEntity(info, isNeedRefreshPseudonymId); - if (res != HC_SUCCESS) { - LOGE("Failed to set protocol entity!"); - return res; - } - return HC_SUCCESS; -} - -static int32_t ISSetPreShareUrlAndEntity(const CJson *context, const CJson *credAuthInfo, IdentityInfo *info) -{ - int32_t res = ISSetISOEntity(info); - if (res != HC_SUCCESS) { - LOGE("Failed to set protocol entity!"); - return res; - } - 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 ISSetCertProofAndEntity(const CJson *context, const CJson *credAuthInfo, - bool isPseudonym, IdentityInfo *info) -{ - int32_t res = HC_ERROR; - if (info->proofType == PRE_SHARED) { - res = ISSetPreShareUrlAndEntity(context, credAuthInfo, info); - if (res != HC_SUCCESS) { - LOGE("Failed to set preshare url"); - } - } else if (info->proofType == CERTIFICATED) { - 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 = ISSetCertInfoAndEntity(osAccountId, credAuthInfo, isPseudonym, info); - if (res != HC_SUCCESS) { - LOGE("Failed to get cert info!"); - } - } else { - res = HC_ERR_NOT_SUPPORT; - LOGE("unknown proof type!"); - } - return res; -} - -int32_t ISGetIdentityInfo(const CJson *context, bool isPseudonym, 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); - if (res != HC_SUCCESS) { - LOGE("Get proofType fail."); - break; - } - res = ConvertISProofTypeToCertType(proofType, &info->proofType); - if (res != HC_SUCCESS) { - LOGE("unsupport proof type!"); - break; - } - res = ISSetCertProofAndEntity(context, credAuthInfo, isPseudonym, info); - if (res != HC_SUCCESS) { - LOGE("Failed to set cert proof and 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/identity_manager/inc/cert_operation.h b/services/legacy/identity_manager/inc/cert_operation.h index 4effd828..bbc791b1 100644 --- a/services/legacy/identity_manager/inc/cert_operation.h +++ b/services/legacy/identity_manager/inc/cert_operation.h @@ -25,7 +25,7 @@ extern "C" { int32_t AddCertInfoToJson(const CertInfo *certInfo, CJson *out); int32_t GetAccountRelatedCredInfo( int32_t osAccountId, const char *groupId, const char *deviceId, bool isUdid, IdentityInfo *info); -int32_t GetAccountAsymSharedSecret(int32_t osAccountId, const char *peerUserId, const CertInfo *peerCertInfo, +int32_t GetAccountAsymSharedSecret(int32_t osAccountId, const char *credId, const CertInfo *peerCertInfo, Uint8Buff *sharedSecret); int32_t GetAccountSymSharedSecret(const CJson *in, const CJson *urlJson, Uint8Buff *sharedSecret); int32_t GetAccountAsymCredInfo(int32_t osAccountId, const CertInfo *certInfo, IdentityInfo **returnInfo); diff --git a/services/legacy/identity_manager/inc/identity_manager.h b/services/legacy/identity_manager/inc/identity_manager.h index 4c718ad6..b6f9b2c2 100644 --- a/services/legacy/identity_manager/inc/identity_manager.h +++ b/services/legacy/identity_manager/inc/identity_manager.h @@ -37,6 +37,7 @@ typedef enum { AUTH_IDENTITY_TYPE_GROUP, AUTH_IDENTITY_TYPE_PIN, AUTH_IDENTITY_TYPE_P2P, + AUTH_IDENTITY_TYPE_CRED, } AuthIdentityType; typedef struct { @@ -64,6 +65,7 @@ typedef struct { const AuthIdentity *GetGroupAuthIdentity(void); const AuthIdentity *GetPinAuthIdentity(void); const AuthIdentity *GetP2pAuthIdentity(void); +const AuthIdentity *GetCredAuthIdentity(void); const AuthIdentity *GetAuthIdentityByType(AuthIdentityType type); const CredentialOperator *GetCredentialOperator(void); const AuthIdentityManager *GetAuthIdentityManager(void); diff --git a/services/legacy/identity_manager/src/cert_operation.c b/services/legacy/identity_manager/src/cert_operation.c index 91cb55f4..b0864648 100644 --- a/services/legacy/identity_manager/src/cert_operation.c +++ b/services/legacy/identity_manager/src/cert_operation.c @@ -663,7 +663,7 @@ int32_t GetAccountRelatedCredInfo( } static int32_t GetSharedSecretByPeerCertFromPlugin( - int32_t osAccountId, const char *peerUserId, const CertInfo *peerCertInfo, Uint8Buff *sharedSecret) + int32_t osAccountId, const char *credId, const CertInfo *peerCertInfo, Uint8Buff *sharedSecret) { CJson *input = CreateJson(); if (input == NULL) { @@ -677,8 +677,8 @@ static int32_t GetSharedSecretByPeerCertFromPlugin( return HC_ERR_JSON_CREATE; } int32_t res = HC_ERR_JSON_ADD; - if ((peerUserId != NULL) && (AddStringToJson(input, FIELD_PEER_USER_ID, peerUserId) != HC_SUCCESS)) { - LOGE("peer user id eixsts, but add peer user id to json failed!"); + if ((credId != NULL) && (AddStringToJson(input, FIELD_ACROSS_ACCOUNT_CRED_ID, credId) != HC_SUCCESS)) { + LOGE("across account cred eixsts, but add cred id to json failed!"); goto ERR; } GOTO_ERR_AND_SET_RET(AddCertInfoToJson(peerCertInfo, input), res); @@ -707,7 +707,7 @@ ERR: return res; } -int32_t GetAccountAsymSharedSecret(int32_t osAccountId, const char *peerUserId, const CertInfo *peerCertInfo, +int32_t GetAccountAsymSharedSecret(int32_t osAccountId, const char *credId, const CertInfo *peerCertInfo, Uint8Buff *sharedSecret) { if (peerCertInfo == NULL || sharedSecret == NULL) { @@ -715,7 +715,7 @@ int32_t GetAccountAsymSharedSecret(int32_t osAccountId, const char *peerUserId, return HC_ERR_INVALID_PARAMS; } if (HasAccountPlugin()) { - return GetSharedSecretByPeerCertFromPlugin(osAccountId, peerUserId, peerCertInfo, sharedSecret); + return GetSharedSecretByPeerCertFromPlugin(osAccountId, credId, peerCertInfo, sharedSecret); } TrustedDeviceEntry *deviceEntry = CreateDeviceEntry(); if (deviceEntry == NULL) { diff --git a/services/legacy/identity_manager/src/identity_cred.c b/services/legacy/identity_manager/src/identity_cred.c new file mode 100644 index 00000000..f94198a3 --- /dev/null +++ b/services/legacy/identity_manager/src/identity_cred.c @@ -0,0 +1,777 @@ +/* + * 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 "alg_defs.h" +#include "alg_loader.h" +#include "hc_log.h" +#include "identity_manager.h" +#include "asy_token_manager.h" +#include "pseudonym_manager.h" +#include "identity_service_defines.h" +#include "identity_operation.h" +#include "cert_operation.h" +#include "hal_error.h" +#include "account_module_defines.h" + +static int32_t CreateUrlStr(uint8_t credType, int32_t keyType, char **urlStr) +{ + TrustType trustType = TRUST_TYPE_P2P; + if (credType != ACCOUNT_UNRELATED) { + trustType = TRUST_TYPE_UID; + } + CJson *urlJson = CreateCredUrlJson(PRE_SHARED, keyType, trustType); + if (!urlJson) { + LOGE("Failed to create CredUrlJson info!"); + return HC_ERR_ALLOC_MEMORY; + } + char *str = PackJsonToString(urlJson); + FreeJson(urlJson); + if (str == 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 ConvertISProofTypeToCertType(uint32_t protocolType, IdentityProofType *returnType) +{ + if (protocolType == PROOF_TYPE_PSK) { + *returnType = PRE_SHARED; + return HC_SUCCESS; + } else if (protocolType == PROOF_TYPE_PKI) { + *returnType = CERTIFICATED; + return HC_SUCCESS; + } + return HC_ERR_NOT_SUPPORT; +} + +static int32_t ConvertISAlgToCertAlg(uint32_t alg, Algorithm *returnAlg) +{ + if (alg == ALGO_TYPE_P256) { + *returnAlg = P256; + return HC_SUCCESS; + } + return HC_ERR_NOT_SUPPORT; +} + +static int32_t ISSetISOEntity(IdentityInfo *info) +{ +#ifdef ENABLE_ACCOUNT_AUTH_ISO + ProtocolEntity *entity = (ProtocolEntity *)HcMalloc(sizeof(ProtocolEntity), 0); + if (entity == NULL) { + LOGE("Failed to alloc memory for ISO protocol entity!"); + return HC_ERR_ALLOC_MEMORY; + } + entity->protocolType = ALG_ISO; + entity->expandProcessCmds = 0; + 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; +#else + (void)info; + LOGE("ISO not support!"); + return HC_ERR_NOT_SUPPORT; +#endif +} + +static int32_t ISSetEcSpekeEntity(IdentityInfo *info, bool isNeedRefreshPseudonymId) +{ +#ifdef ENABLE_ACCOUNT_AUTH_EC_SPEKE + ProtocolEntity *entity = (ProtocolEntity *)HcMalloc(sizeof(ProtocolEntity), 0); + if (entity == NULL) { + LOGE("Failed to alloc memory for ec-speke protocol entity!"); + return HC_ERR_ALLOC_MEMORY; + } + entity->protocolType = ALG_EC_SPEKE; + entity->expandProcessCmds = 0; +#ifdef ENABLE_PSEUDONYM + if (isNeedRefreshPseudonymId) { + entity->expandProcessCmds |= CMD_MK_AGREE; + } +#else + (void)isNeedRefreshPseudonymId; +#endif + 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; +#else + (void)info; + (void)isNeedRefreshPseudonymId; + LOGE("ec speke not support!"); + return HC_ERR_NOT_SUPPORT; +#endif +} + +static int32_t CreateUserIdHashHexString(const CJson *credAuthInfo, char **returnUserIdHash) +{ + const char *userId = GetStringFromJson(credAuthInfo, FIELD_USER_ID); + if (userId == NULL) { + LOGE("Failed to get user ID!"); + return HC_ERR_JSON_GET; + } + Uint8Buff userIdBuf = { (uint8_t *)userId, (uint32_t)HcStrlen(userId) }; + uint8_t userIdHashByte[SHA256_LEN] = { 0 }; + Uint8Buff userIdHashBuf = { userIdHashByte, sizeof(userIdHashByte) }; + int32_t res = GetLoaderInstance()->sha256(&userIdBuf, &userIdHashBuf); + if (res != HC_SUCCESS) { + LOGE("sha256 failed, res:%d", res); + return res; + } + uint32_t userIdHashLen = SHA256_LEN * BYTE_TO_HEX_OPER_LENGTH + 1; + char *userIdHash = (char *)HcMalloc(userIdHashLen, 0); + if (userIdHash == NULL) { + LOGE("malloc userIdHash string failed"); + return HC_ERR_ALLOC_MEMORY; + } + res = ByteToHexString(userIdHashByte, SHA256_LEN, userIdHash, userIdHashLen); + if (res != HC_SUCCESS) { + LOGE("Byte to hexString failed, res:%d", res); + HcFree(userIdHash); + } + //replace userId plain to hash hex string + if (AddStringToJson(credAuthInfo, FIELD_USER_ID, userIdHash) != HC_SUCCESS) { + LOGE("Failed to add userIdHash"); + return HC_ERR_JSON_ADD; + } + *returnUserIdHash = userIdHash; + return res; +} + +static int32_t ISSetCertInfoAndEntity(int32_t osAccountId, const CJson *credAuthInfo, + bool isPseudonym, IdentityInfo *info) +{ + 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; + } + char *userIdHash = NULL; + int32_t res = CreateUserIdHashHexString(credAuthInfo, &userIdHash); + if (res != HC_SUCCESS) { + return res; + } + res = GetAccountAuthTokenManager()->getToken(osAccountId, token, userIdHash, authId); + HcFree(userIdHash); + if (res != HC_SUCCESS) { + LOGE("Failed to get account token!"); + DestroyAccountToken(token); + return res; + } + res = GenerateCertInfo(&token->pkInfoStr, &token->pkInfoSignature, &info->proof.certInfo); + DestroyAccountToken(token); + if (res != HC_SUCCESS) { + LOGE("Failed to generate cert info!"); + return res; + } + uint32_t signAlg = 0; + if (GetUnsignedIntFromJson(credAuthInfo, FIELD_ALGORITHM_TYPE, &signAlg) != HC_SUCCESS) { + LOGE("Failed to get algorithm type!"); + return HC_ERR_JSON_GET; + } + res = ConvertISAlgToCertAlg(signAlg, &info->proof.certInfo.signAlg); + if (res != HC_SUCCESS) { + LOGE("unsupport algorithm type!"); + return res; + } + info->proof.certInfo.isPseudonym = isPseudonym; + bool isNeedRefreshPseudonymId = GetPseudonymInstance()->isNeedRefreshPseudonymId(osAccountId, userIdHash); + res = ISSetEcSpekeEntity(info, isNeedRefreshPseudonymId); + if (res != HC_SUCCESS) { + LOGE("Failed to set protocol entity!"); + return res; + } + return HC_SUCCESS; +} + +static int32_t ISSetPreShareUrlAndEntity(const CJson *credAuthInfo, IdentityInfo *info) +{ + uint8_t credType = ACCOUNT_UNRELATED; + if (GetUint8FromJson(credAuthInfo, FIELD_CRED_TYPE, &credType) != HC_SUCCESS) { + LOGE("get int from json failed!"); + return HC_ERR_JSON_GET; + } + uint8_t keyFormat; + if (GetUint8FromJson(credAuthInfo, FIELD_KEY_FORMAT, &keyFormat) != HC_SUCCESS) { + LOGE("get int from json failed!"); + return HC_ERR_JSON_GET; + } + int32_t res = HC_ERROR; + KeyType keyType; + if (keyFormat == SYMMETRIC_KEY) { + res = ISSetISOEntity(info); + keyType = KEY_TYPE_SYM; + } else if (keyFormat == ASYMMETRIC_KEY || keyFormat == ASYMMETRIC_PUB_KEY) { + res = ISSetEcSpekeEntity(info, false); + keyType = KEY_TYPE_ASYM; + } + if (res != HC_SUCCESS) { + return res; + } + char *urlStr = NULL; + res = CreateUrlStr(credType, keyType, &urlStr); + if (res != HC_SUCCESS) { + LOGE("Failed to create url string!"); + return res; + } + res = SetPreSharedUrlForProof(urlStr, &info->proof.preSharedUrl); + FreeJsonString(urlStr); + if (res != HC_SUCCESS) { + LOGE("Failed to set preSharedUrl of proof!"); + return res; + } + info->proofType = PRE_SHARED; + return HC_SUCCESS; +} + +static int32_t ISSetCertProofAndEntity(const CJson *context, const CJson *credAuthInfo, + bool isPseudonym, IdentityInfo *info) +{ + int32_t res = HC_ERROR; + if (info->proofType == PRE_SHARED) { + res = ISSetPreShareUrlAndEntity(credAuthInfo, info); + if (res != HC_SUCCESS) { + LOGE("Failed to set preshared url"); + } + } else if (info->proofType == CERTIFICATED) { + 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 = ISSetCertInfoAndEntity(osAccountId, credAuthInfo, isPseudonym, info); + if (res != HC_SUCCESS) { + LOGE("Failed to get cert info!"); + } + } else { + res = HC_ERR_NOT_SUPPORT; + LOGE("unknown proof type!"); + } + return res; +} + +static int32_t ISGetIdentityInfo(const CJson *context, bool isPseudonym, IdentityInfo **returnInfo) +{ + CJson *credAuthInfo = GetObjFromJson(context, FIELD_CREDENTIAL_OBJ); + if (credAuthInfo == NULL) { + LOGE("Get self credAuthInfo fail."); + return HC_ERR_JSON_GET; + } + uint32_t proofType = 0; + int32_t res = GetUnsignedIntFromJson(credAuthInfo, FIELD_PROOF_TYPE, &proofType); + if (res != HC_SUCCESS) { + LOGE("Get proofType fail."); + return res; + } + if (isPseudonym && proofType != PROOF_TYPE_PKI) { + return HC_SUCCESS; + } + IdentityInfo *info = CreateIdentityInfo(); + if (info == NULL) { + LOGE("Failed to alloc memory for IdentityInfo!"); + return HC_ERR_JSON_GET; + } + info->IdInfoType = DEFAULT_ID_TYPE; + do { + res = ConvertISProofTypeToCertType(proofType, &info->proofType); + if (res != HC_SUCCESS) { + LOGE("unsupport proof type!"); + break; + } + res = ISSetCertProofAndEntity(context, credAuthInfo, isPseudonym, info); + if (res != HC_SUCCESS) { + LOGE("Failed to set cert proof and protocol entity!"); + break; + } + } while (0); + if (res != HC_SUCCESS) { + DestroyIdentityInfo(info); + return res; + } + *returnInfo = info; + return HC_SUCCESS; +} + +static int32_t AddIdentityInfoToVec(const CJson *in, bool isPseudonym, IdentityInfoVec *vec) +{ + IdentityInfo *info = NULL; + int32_t res = ISGetIdentityInfo(in, isPseudonym, &info); + if (res != HC_SUCCESS) { + LOGE("Get Identity by credAuthInfo fail."); + return res; + } + if (info == NULL) { + return HC_SUCCESS; + } + if (vec->pushBack(vec, (const IdentityInfo **)&info) == NULL) { + DestroyIdentityInfo(info); + LOGE("Failed to push protocol entity!"); + return HC_ERR_ALLOC_MEMORY; + } + return HC_SUCCESS; +} + +static int32_t GetCredInfosByPeerIdentity(const CJson *in, IdentityInfoVec *vec) +{ + if (in == NULL || vec == NULL) { + LOGE("Invalid input params!"); + return HC_ERR_INVALID_PARAMS; + } + int32_t res = HC_ERROR; +#ifdef ENABLE_PSEUDONYM + //try enable pseudonym + res = AddIdentityInfoToVec(in, true, vec); + if (res != HC_SUCCESS) { + LOGE("add identity info to vec failed."); + return res; + } +#endif + res = AddIdentityInfoToVec(in, false, vec); + if (res != HC_SUCCESS) { + LOGE("add identity info to vec failed."); + return res; + } + return HC_SUCCESS; +} + +static int32_t GetCredInfoByPeerUrl(const CJson *in, const Uint8Buff *presharedUrl, IdentityInfo **returnInfo) +{ + if (in == NULL || presharedUrl == NULL || returnInfo == NULL) { + LOGE("Invalid input params!"); + return HC_ERR_INVALID_PARAMS; + } + IdentityInfo *info = NULL; + int32_t res = ISGetIdentityInfo(in, false, &info); + if (res != HC_SUCCESS) { + LOGE("Get Identity by credAuthInfo fail."); + return res; + } + if (memcmp(presharedUrl->val, (*returnInfo)->proof.preSharedUrl.val, presharedUrl->length) != 0) { + DestroyIdentityInfo(info); + LOGE("peer presharedUrl is not equal."); + return HC_ERR_MEMORY_COMPARE; + } + *returnInfo = info; + return HC_SUCCESS; +} + +static int32_t ComputeHkdfKeyAlias(const CJson *in, int32_t osAccountId, Uint8Buff *credIdByte, Uint8Buff *sharedSecret) +{ + uint8_t *pskVal = (uint8_t *)HcMalloc(PAKE_PSK_LEN, 0); + if (pskVal == NULL) { + LOGE("Failed to alloc memory for psk!"); + return HC_ERR_ALLOC_MEMORY; + } + Uint8Buff pskBuff = { pskVal, PAKE_PSK_LEN }; + uint8_t *nonceVal = (uint8_t *)HcMalloc(PAKE_NONCE_LEN, 0); + if (nonceVal == NULL) { + LOGE("Failed to alloc memory for nonce!"); + HcFree(pskVal); + return HC_ERR_ALLOC_MEMORY; + } + Uint8Buff nonceBuff = { nonceVal, PAKE_NONCE_LEN }; + int32_t ret = GetByteFromJson(in, FIELD_NONCE, nonceBuff.val, nonceBuff.length); + if (ret != HC_SUCCESS) { + LOGE("Failed to get nonce!"); + HcFree(pskVal); + HcFree(nonceVal); + return HC_ERR_JSON_GET; + } + Uint8Buff keyInfo = { (uint8_t *)TMP_AUTH_KEY_FACTOR, HcStrlen(TMP_AUTH_KEY_FACTOR) }; + KeyParams keyAliasParams = { { credIdByte->val, credIdByte->length, true }, false, osAccountId }; + ret = GetLoaderInstance()->computeHkdf(&keyAliasParams, &nonceBuff, &keyInfo, &pskBuff); + HcFree(nonceVal); + if (ret != HC_SUCCESS) { + LOGE("Failed to compute hkdf for psk!"); + HcFree(pskVal); + return ret; + } + + ret = ConvertPsk(&pskBuff, sharedSecret); + HcFree(pskVal); + if (ret != HC_SUCCESS) { + LOGE("Failed to convert psk!"); + } + return ret; +} + +static int32_t ComputeAuthToken(int32_t osAccountId, const char *userId, const Uint8Buff keyAlias, Uint8Buff *authToken) +{ + authToken->val = (uint8_t *)HcMalloc(AUTH_TOKEN_SIZE, 0); + if (authToken->val == NULL) { + LOGE("Failed to alloc memory for auth token!"); + return HC_ERR_ALLOC_MEMORY; + } + authToken->length = AUTH_TOKEN_SIZE; + Uint8Buff userIdBuff = { (uint8_t *)userId, HcStrlen(userId) }; + Uint8Buff challenge = { (uint8_t *)KEY_INFO_PERSISTENT_TOKEN, HcStrlen(KEY_INFO_PERSISTENT_TOKEN) }; + KeyParams keyAliasParams = { { keyAlias.val, keyAlias.length, true }, false, osAccountId }; + int32_t ret = GetLoaderInstance()->computeHkdf(&keyAliasParams, &userIdBuff, &challenge, authToken); + if (ret != HC_SUCCESS) { + LOGE("Failed to computeHkdf from authCode to authToken!"); + FreeBuffData(authToken); + } + return ret; +} + +static int32_t GenerateAuthTokenForAccessory(int32_t osAccountId, const char *credId, const CJson *credAuthInfo, + Uint8Buff *authToken) +{ + const char *userIdSelf = GetStringFromJson(credAuthInfo, FIELD_USER_ID); + if (userIdSelf == NULL) { + LOGE("Failed to get self user ID!"); + return HC_ERR_JSON_GET; + } + Uint8Buff credIdByte = { NULL, 0 }; + int32_t ret = GetValidKeyAlias(osAccountId, credId, &credIdByte); + 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; + } + ret = ComputeAuthToken(osAccountId, userIdSelf, credIdByte, authToken); + FreeBuffData(&credIdByte); + return ret; +} + +static int32_t GenerateTokenAliasForController(int32_t osAccountId, const char *credId, Uint8Buff *authToken) +{ + int32_t ret = GetValidKeyAlias(osAccountId, credId, authToken); + 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; + } + return HC_SUCCESS; +} + +static int32_t GenerateAuthTokenByDevType(int32_t osAccountId, const CJson *in, Uint8Buff *authToken, + bool *isTokenStored) +{ + const char *credId = GetStringFromJson(in, FIELD_CRED_ID); + if (credId == NULL) { + LOGE("Failed to get cred ID!"); + return HC_ERR_JSON_GET; + } + const CJson *credAuthInfo = GetObjFromJson(in, FIELD_CREDENTIAL_OBJ); + if (credAuthInfo == NULL) { + LOGE("Get credAuthInfo fail."); + return HC_ERR_JSON_GET; + } + uint8_t localDevType = SUBJECT_ACCESSORY_DEVICE; + if (GetUint8FromJson(credAuthInfo, FIELD_SUBJECT, &localDevType) != HC_SUCCESS) { + LOGE("Failed to get subject!"); + return HC_ERR_JSON_GET; + } + int32_t ret = HC_ERROR; + if (localDevType == SUBJECT_ACCESSORY_DEVICE) { + *isTokenStored = false; + ret = GenerateAuthTokenForAccessory(osAccountId, credId, credAuthInfo, authToken); + } else { + ret = GenerateTokenAliasForController(osAccountId, credId, authToken); + } + return ret; +} + +static int32_t ISGetAccountSymSharedSecret(const CJson *in, Uint8Buff *sharedSecret) +{ + if (in == NULL || sharedSecret == NULL) { + LOGE("Invalid input params!"); + return HC_ERR_INVALID_PARAMS; + } + int32_t osAccountId; + if (GetIntFromJson(in, FIELD_OS_ACCOUNT_ID, &osAccountId) != HC_SUCCESS) { + LOGE("Failed to get osAccountId!"); + return HC_ERR_JSON_GET; + } + bool isTokenStored = true; + Uint8Buff authToken = { NULL, 0 }; + int32_t ret = GenerateAuthTokenByDevType(osAccountId, in, &authToken, &isTokenStored); + if (ret != HC_SUCCESS) { + LOGE("Failed to generate auth token!"); + return ret; + } + uint8_t seed[SEED_SIZE] = { 0 }; + Uint8Buff seedBuff = { seed, SEED_SIZE }; + ret = GetByteFromJson(in, FIELD_SEED, seed, SEED_SIZE); + if (ret != HC_SUCCESS) { + LOGE("Failed to get seed!"); + FreeBuffData(&authToken); + return HC_ERR_JSON_GET; + } + sharedSecret->val = (uint8_t *)HcMalloc(ISO_PSK_LEN, 0); + if (sharedSecret->val == NULL) { + LOGE("Failed to alloc sharedSecret memory!"); + FreeBuffData(&authToken); + return HC_ERR_ALLOC_MEMORY; + } + sharedSecret->length = ISO_PSK_LEN; + KeyParams keyParams = { { authToken.val, authToken.length, isTokenStored }, false, osAccountId }; + ret = GetLoaderInstance()->computeHmac(&keyParams, &seedBuff, sharedSecret); + FreeBuffData(&authToken); + if (ret != HC_SUCCESS) { + LOGE("ComputeHmac for psk failed, ret: %d.", ret); + FreeBuffData(sharedSecret); + } + return ret; +} + +static int32_t AuthGeneratePsk(const CJson *in, const Uint8Buff *seed, Uint8Buff *sharedSecret) +{ + int32_t osAccountId = INVALID_OS_ACCOUNT; + if (GetIntFromJson(in, FIELD_OS_ACCOUNT_ID, &osAccountId) != HC_SUCCESS) { + LOGE("Failed to get osAccountId!"); + return HC_ERR_JSON_GET; + } + const char *credId = GetStringFromJson(in, FIELD_CRED_ID); + if (credId == NULL) { + LOGE("Failed to get cred ID!"); + return HC_ERR_JSON_GET; + } + Uint8Buff credIdByte = { NULL, 0 }; + int32_t ret = GetValidKeyAlias(osAccountId, credId, &credIdByte); + 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 keyAliasParams = { { credIdByte.val, credIdByte.length, true }, false, osAccountId }; + ret = GetLoaderInstance()->computeHmac(&keyAliasParams, seed, sharedSecret); + FreeBuffData(&credIdByte); + return ret; +} + +static int32_t GetSharedSecretForP2pInIso(const CJson *in, Uint8Buff *sharedSecret) +{ + uint8_t *seedVal = (uint8_t *)HcMalloc(SEED_LEN, 0); + if (seedVal == NULL) { + LOGE("Failed to alloc memory for seed!"); + return HC_ERR_ALLOC_MEMORY; + } + Uint8Buff seedBuff = { seedVal, SEED_LEN }; + int32_t ret = GetByteFromJson(in, FIELD_SEED, seedBuff.val, seedBuff.length); + if (ret != HC_SUCCESS) { + LOGE("Failed to get seed!"); + HcFree(seedVal); + return HC_ERR_JSON_GET; + } + uint8_t *pskVal = (uint8_t *)HcMalloc(ISO_PSK_LEN, 0); + if (pskVal == NULL) { + LOGE("Failed to alloc memory for psk!"); + HcFree(seedVal); + return HC_ERR_ALLOC_MEMORY; + } + sharedSecret->val = pskVal; + sharedSecret->length = ISO_PSK_LEN; + ret = AuthGeneratePsk(in, &seedBuff, sharedSecret); + HcFree(seedVal); + if (ret != HC_SUCCESS) { + LOGE("Failed to generate psk!"); + FreeBuffData(sharedSecret); + } + return ret; +} + +static int32_t GetSharedSecretForP2pInPake(const CJson *in, Uint8Buff *sharedSecret) +{ + const char *credId = GetStringFromJson(in, FIELD_CRED_ID); + if (credId == NULL) { + LOGE("get credId from json failed"); + return HC_ERR_JSON_GET; + } + int32_t osAccountId; + if (GetIntFromJson(in, FIELD_OS_ACCOUNT_ID, &osAccountId) != HC_SUCCESS) { + LOGE("Failed to get osAccountId!"); + return HC_ERR_JSON_GET; + } + uint32_t credIdByteLen = HcStrlen(credId) / BYTE_TO_HEX_OPER_LENGTH; + Uint8Buff credIdByte = { NULL, credIdByteLen }; + credIdByte.val = (uint8_t *)HcMalloc(credIdByteLen, 0); + if (credIdByte.val == NULL) { + LOGE("Failed to malloc credIdByteLen"); + return IS_ERR_ALLOC_MEMORY; + } + int32_t ret = HexStringToByte(credId, credIdByte.val, credIdByte.length); + if (ret != IS_SUCCESS) { + LOGE("Failed to convert credId to byte, invalid credId, ret = %d", ret); + HcFree(credIdByte.val); + return IS_ERR_INVALID_HEX_STRING; + } + LOGI("psk alias: %x %x %x %x****.", credIdByte.val[DEV_AUTH_ZERO], credIdByte.val[DEV_AUTH_ONE], + credIdByte.val[DEV_AUTH_TWO], credIdByte.val[DEV_AUTH_THREE]); + + ret = GetLoaderInstance()->checkKeyExist(&credIdByte, false, osAccountId); + if (ret != HC_SUCCESS) { + HcFree(credIdByte.val); + LOGE("psk not exist"); + return ret; + } + ret = ComputeHkdfKeyAlias(in, osAccountId, &credIdByte, sharedSecret); + HcFree(credIdByte.val); + if (ret != HC_SUCCESS) { + LOGE("compute hkdf key alias failed."); + FreeBuffData(sharedSecret); + } + return ret; +} + +static int32_t GetSharedSecretForP2p( + const CJson *in, ProtocolAlgType protocolType, Uint8Buff *sharedSecret) +{ + int32_t ret; + if (protocolType == ALG_ISO) { + ret = GetSharedSecretForP2pInIso(in, sharedSecret); + LOGI("get shared secret for p2p in iso result: %d", ret); + } else { + ret = GetSharedSecretForP2pInPake(in, sharedSecret); + LOGI("get shared secret for p2p in pake result: %d", ret); + } + return ret; +} + +static int32_t GetSharedSecretForUid( + const CJson *in, ProtocolAlgType protocolType, Uint8Buff *sharedSecret) +{ + if (protocolType != ALG_ISO) { + LOGE("protocol type is not iso, not supported!"); + return HC_ERR_INVALID_PARAMS; + } + return ISGetAccountSymSharedSecret(in, sharedSecret); +} + +static int32_t GetSharedSecretByUrl( + const CJson *in, const Uint8Buff *presharedUrl, ProtocolAlgType protocolType, Uint8Buff *sharedSecret) +{ + if (in == NULL || presharedUrl == NULL || sharedSecret == NULL) { + LOGE("Invalid input params!"); + return HC_ERR_INVALID_PARAMS; + } + + CJson *urlJson = CreateJsonFromString((const char *)presharedUrl->val); + if (urlJson == NULL) { + LOGE("Failed to create url json!"); + return HC_ERR_JSON_CREATE; + } + + int32_t trustType = 0; + if (GetIntFromJson(urlJson, PRESHARED_URL_TRUST_TYPE, &trustType) != HC_SUCCESS) { + LOGE("Failed to get trust type!"); + FreeJson(urlJson); + return HC_ERR_JSON_GET; + } + FreeJson(urlJson); + + int32_t ret; + switch (trustType) { + case TRUST_TYPE_P2P: + ret = GetSharedSecretForP2p(in, protocolType, sharedSecret); + break; + case TRUST_TYPE_UID: + ret = GetSharedSecretForUid(in, protocolType, sharedSecret); + break; + default: + LOGE("Invalid trust type!"); + ret = HC_ERR_INVALID_PARAMS; + break; + } + return ret; +} + +static int32_t GetCredInfoByPeerCert(const CJson *in, const CertInfo *certInfo, IdentityInfo **returnInfo) +{ + if (in == NULL || certInfo == NULL || returnInfo == NULL) { + LOGE("Invalid input params!"); + return HC_ERR_INVALID_PARAMS; + } + IdentityInfo *info = NULL; + int32_t res = ISGetIdentityInfo(in, certInfo->isPseudonym, &info); + if (res != HC_SUCCESS) { + LOGE("Get Identity by credAuthInfo fail."); + return res; + } + *returnInfo = info; + return HC_SUCCESS; +} + +static int32_t GetSharedSecretByPeerCert( + const CJson *in, const CertInfo *peerCertInfo, ProtocolAlgType protocolType, Uint8Buff *sharedSecret) +{ + if (in == NULL || peerCertInfo == NULL || sharedSecret == NULL) { + LOGE("Invalid input params!"); + return HC_ERR_INVALID_PARAMS; + } + if (protocolType != ALG_EC_SPEKE) { + LOGE("protocol type is not ec speke, not support!"); + return HC_ERR_INVALID_PARAMS; + } + int32_t osAccountId = INVALID_OS_ACCOUNT; + if (GetIntFromJson(in, FIELD_OS_ACCOUNT_ID, &osAccountId) != HC_SUCCESS) { + LOGE("Failed to get osAccountId!"); + return HC_ERR_JSON_GET; + } + const char *credId = GetStringFromJson(in, FIELD_ACROSS_ACCOUNT_CRED_ID); + if (credId != NULL) { + LOGI("across account credential Id exists."); + } + return GetAccountAsymSharedSecret(osAccountId, credId, peerCertInfo, sharedSecret); +} + +static const AuthIdentity g_authIdentity = { + .getCredInfosByPeerIdentity = GetCredInfosByPeerIdentity, + .getCredInfoByPeerUrl = GetCredInfoByPeerUrl, + .getSharedSecretByUrl = GetSharedSecretByUrl, + .getCredInfoByPeerCert = GetCredInfoByPeerCert, + .getSharedSecretByPeerCert = GetSharedSecretByPeerCert, +}; + +const AuthIdentity *GetCredAuthIdentity(void) +{ + return &g_authIdentity; +} diff --git a/services/legacy/identity_manager/src/identity_manager.c b/services/legacy/identity_manager/src/identity_manager.c index 574a0e44..1947a14f 100644 --- a/services/legacy/identity_manager/src/identity_manager.c +++ b/services/legacy/identity_manager/src/identity_manager.c @@ -44,6 +44,8 @@ const AuthIdentity *GetAuthIdentityByType(AuthIdentityType type) return GetPinAuthIdentity(); case AUTH_IDENTITY_TYPE_P2P: return GetP2pAuthIdentity(); + case AUTH_IDENTITY_TYPE_CRED: + return GetCredAuthIdentity(); default: LOGE("unknow AuthIdentityType: %d", type); return NULL; diff --git a/services/legacy/identity_manager/src/identity_pin.c b/services/legacy/identity_manager/src/identity_pin.c index 7e71f2f9..d44198e5 100644 --- a/services/legacy/identity_manager/src/identity_pin.c +++ b/services/legacy/identity_manager/src/identity_pin.c @@ -40,7 +40,7 @@ static int32_t SetDlSpekeProtocol(IdentityInfo *info) #endif } -static int32_t SetIsoProtocol(IdentityInfo *info) +static int32_t SetIsoProtocol(const CJson *in, IdentityInfo *info) { #ifdef ENABLE_P2P_BIND_ISO ProtocolEntity *isoEntity = (ProtocolEntity *)HcMalloc(sizeof(ProtocolEntity), 0); @@ -49,7 +49,9 @@ static int32_t SetIsoProtocol(IdentityInfo *info) return HC_ERR_ALLOC_MEMORY; } isoEntity->protocolType = ALG_ISO; - isoEntity->expandProcessCmds = CMD_IMPORT_AUTH_CODE | CMD_ADD_TRUST_DEVICE; + bool isCredAuth = false; + (void)GetBoolFromJson(in, FIELD_IS_CRED_AUTH, &isCredAuth); + isoEntity->expandProcessCmds = isCredAuth ? 0 : CMD_IMPORT_AUTH_CODE | CMD_ADD_TRUST_DEVICE; if (info->protocolVec.pushBack(&info->protocolVec, (const ProtocolEntity **)&isoEntity) == NULL) { LOGE("Failed to push iso entity!"); HcFree(isoEntity); @@ -62,27 +64,27 @@ static int32_t SetIsoProtocol(IdentityInfo *info) #endif } -static int32_t SetLiteProtocols(IdentityInfo *info) +static int32_t SetLiteProtocols(const CJson *in, IdentityInfo *info) { int32_t res = SetDlSpekeProtocol(info); if (res != HC_SUCCESS) { return res; } - return SetIsoProtocol(info); + return SetIsoProtocol(in, info); } static int32_t SetLiteProtocolsForPinType(const CJson *in, IdentityInfo *info) { #ifndef ENABLE_P2P_BIND_LITE_PROTOCOL_CHECK (void)in; - return SetLiteProtocols(info); + return SetLiteProtocols(in, info); #else int32_t protocolExpandVal = INVALID_PROTOCOL_EXPAND_VALUE; (void)GetIntFromJson(in, FIELD_PROTOCOL_EXPAND, &protocolExpandVal); int32_t res = HC_SUCCESS; if (protocolExpandVal == LITE_PROTOCOL_STANDARD_MODE || protocolExpandVal == LITE_PROTOCOL_COMPATIBILITY_MODE) { - res = SetLiteProtocols(info); + res = SetLiteProtocols(in, info); } return res; #endif @@ -97,7 +99,9 @@ static int32_t SetProtocolsForPinType(const CJson *in, IdentityInfo *info) return HC_ERR_ALLOC_MEMORY; } ecSpekeEntity->protocolType = ALG_EC_SPEKE; - ecSpekeEntity->expandProcessCmds = CMD_EXCHANGE_PK | CMD_ADD_TRUST_DEVICE; + bool isCredAuth = false; + (void)GetBoolFromJson(in, FIELD_IS_CRED_AUTH, &isCredAuth); + ecSpekeEntity->expandProcessCmds = isCredAuth ? 0 : CMD_EXCHANGE_PK | CMD_ADD_TRUST_DEVICE; if (info->protocolVec.pushBack(&info->protocolVec, (const ProtocolEntity **)&ecSpekeEntity) == NULL) { LOGE("Failed to push ec speke entity!"); HcFree(ecSpekeEntity); diff --git a/services/legacy/identity_manager/src/mock/identity_cred_mock.c b/services/legacy/identity_manager/src/mock/identity_cred_mock.c new file mode 100644 index 00000000..9f1f7912 --- /dev/null +++ b/services/legacy/identity_manager/src/mock/identity_cred_mock.c @@ -0,0 +1,21 @@ +/* + * Copyright (C) 2023 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_manager.h" + +const AuthIdentity *GetCredAuthIdentity(void) +{ + return NULL; +} diff --git a/services/legacy/identity_manager/src/mock/identity_manager_mock.c b/services/legacy/identity_manager/src/mock/identity_manager_mock.c index b6910224..e413e21a 100644 --- a/services/legacy/identity_manager/src/mock/identity_manager_mock.c +++ b/services/legacy/identity_manager/src/mock/identity_manager_mock.c @@ -59,6 +59,11 @@ const AuthIdentity *GetP2pAuthIdentity(void) return NULL; } +const AuthIdentity *GetCredAuthIdentity(void) +{ + return NULL; +} + const CredentialOperator *GetCredentialOperator(void) { return NULL; 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 a9c163b3..f92573b4 100644 --- a/services/session_manager/inc/session/v2/dev_session_util.h +++ b/services/session_manager/inc/session/v2/dev_session_util.h @@ -25,7 +25,7 @@ extern "C" { #endif int32_t FillPeerAuthIdIfNeeded(bool isClient, const CJson *context, CJson *inputData); -int32_t SetPeerAuthIdToContextIfNeeded(CJson *context, const IdentityInfo *info); +int32_t SetPeerAuthIdToContextIfNeeded(CJson *context, bool isCredAuth, const IdentityInfo *info); bool IsP2pAuth(const IdentityInfo *info); int32_t SetPeerInfoToContext(CJson *context, const CJson *inputData); int32_t ReplaceAuthIdWithRandom(CJson *authData); 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 f43581d4..150789b1 100644 --- a/services/session_manager/src/session/v2/dev_session_util.c +++ b/services/session_manager/src/session/v2/dev_session_util.c @@ -72,7 +72,7 @@ static int32_t GetUserIdByGroup(const CJson *context, int32_t osAccountId, char static int32_t GetUserIdByISInfo(const CJson *context, char **returnUserId) { - CJson *credAuthInfo = GetObjFromJson(context, FIELD_SELF_CREDENTIAL_OBJ); + CJson *credAuthInfo = GetObjFromJson(context, FIELD_CREDENTIAL_OBJ); if (credAuthInfo == NULL) { LOGE("Get self credAuthInfo fail."); return HC_ERR_JSON_GET; @@ -282,6 +282,25 @@ static int32_t SetPeerAuthIdByDb(CJson *context, const char *groupId) return HC_SUCCESS; } +static int32_t SetPeerAuthIdByCredAuthInfo(CJson *context) +{ + CJson *credAuthInfo = GetObjFromJson(context, FIELD_CREDENTIAL_OBJ); + if (credAuthInfo == NULL) { + LOGE("Get self credAuthInfo fail."); + return HC_ERR_JSON_GET; + } + const char *peerAuthId = GetStringFromJson(context, FIELD_DEVICE_ID); + if (peerAuthId == NULL) { + LOGE("Get peer authId fail."); + return HC_ERR_JSON_GET; + } + if (AddStringToJson(context, FIELD_PEER_AUTH_ID, peerAuthId) != HC_SUCCESS) { + LOGE("Failed to add peer authId to context!"); + return HC_ERR_JSON_ADD; + } + return HC_SUCCESS; +} + int32_t FillPeerAuthIdIfNeeded(bool isClient, const CJson *context, CJson *inputData) { const char *peerAuthId = GetStringFromJson(context, FIELD_PEER_AUTH_ID); @@ -332,7 +351,7 @@ bool IsP2pAuth(const IdentityInfo *info) return trustType == TRUST_TYPE_P2P; } -int32_t SetPeerAuthIdToContextIfNeeded(CJson *context, const IdentityInfo *info) +int32_t SetPeerAuthIdToContextIfNeeded(CJson *context, bool isCredAuth, const IdentityInfo *info) { if (!IsP2pAuth(info)) { LOGI("Not p2p auth, no need to set peer authId!"); @@ -344,6 +363,9 @@ int32_t SetPeerAuthIdToContextIfNeeded(CJson *context, const IdentityInfo *info) if (isDirectAuth) { return HC_SUCCESS; } + if (isCredAuth) { + return SetPeerAuthIdByCredAuthInfo(context); + } CJson *urlJson = CreateJsonFromString((const char *)info->proof.preSharedUrl.val); if (urlJson == NULL) { LOGE("Failed to create urlJson!"); 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 eb372333..120ddd92 100644 --- a/services/session_manager/src/session/v2/dev_session_v2.c +++ b/services/session_manager/src/session/v2/dev_session_v2.c @@ -1094,11 +1094,8 @@ static int32_t AddAuthInfoToContextByCert(SessionImpl *impl) } } -static int32_t AddAuthInfoToContextIS(SessionImpl *impl, IdentityInfo *cred) +static int32_t ISAddAuthInfoToContext(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) { @@ -1106,8 +1103,30 @@ static int32_t AddAuthInfoToContextIS(SessionImpl *impl, IdentityInfo *cred) return res; } PRINT_SENSITIVE_DATA("SelfUdid", selfUdid); + if (cred->proofType == CERTIFICATED) { + if (AddStringToJson(impl->context, FIELD_AUTH_ID, selfUdid) != HC_SUCCESS) { + LOGE("add selfAuthId to json fail."); + return HC_ERR_JSON_ADD; + } + return HC_SUCCESS; + } + CJson *urlJson = CreateJsonFromString((const char *)cred->proof.preSharedUrl.val); + if (urlJson == NULL) { + LOGE("create urlJson from string fail."); + return HC_ERR_JSON_CREATE; + } + int32_t trustType; + if (GetIntFromJson(urlJson, PRESHARED_URL_TRUST_TYPE, &trustType) != HC_SUCCESS) { + LOGE("Failed to get trust type!"); + FreeJson(urlJson); + return HC_ERR_JSON_GET; + } + FreeJson(urlJson); + if (trustType == TRUST_TYPE_PIN) { + return HC_SUCCESS; + } if (AddStringToJson(impl->context, FIELD_AUTH_ID, selfUdid) != HC_SUCCESS) { - LOGE("add selfAuthId to json fail."); + LOGE("Failed to add authId to params!"); return HC_ERR_JSON_ADD; } return HC_SUCCESS; @@ -1186,7 +1205,7 @@ static int32_t ClientCreateAuthSubSessionByCred(SessionImpl *impl, IdentityInfo LOGE("The credential does not have a valid protocol."); return HC_ERR_UNSUPPORTED_VERSION; } - int32_t res = impl->isCredAuth? AddAuthInfoToContextIS(impl, cred) + int32_t res = impl->isCredAuth? ISAddAuthInfoToContext(impl, cred) : AddAuthInfoToContextByCred(impl, cred); if (res != HC_SUCCESS) { return res; @@ -1202,81 +1221,11 @@ static int32_t ClientCreateAuthSubSessionByCred(SessionImpl *impl, IdentityInfo return HC_SUCCESS; } -static int32_t ISClientGetCredInfo(SessionImpl *impl) -{ - IdentityInfo *info = NULL; - int32_t res = HC_ERROR; -#ifdef ENABLE_PSEUDONYM - //try enable pseudonym - res = ISGetIdentityInfo(impl->context, true, &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; - } - info = NULL; -#endif - res = ISGetIdentityInfo(impl->context, false, &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; - } - uint32_t credNum = HC_VECTOR_SIZE(&impl->credList); - if (credNum == 0) { - LOGE("No valid credentials with peer."); - return HC_ERR_INIT_FAILED; - } - impl->credCurIndex = 0; - impl->credTotalNum = credNum; - return HC_SUCCESS; -} - -static int32_t ISServerGetCredInfo(SessionImpl *impl, const CJson *inputData) -{ - const CJson *pkInfoStr = GetObjFromJson(inputData, FIELD_PK_INFO); - if (pkInfoStr == NULL) { - LOGE("Failed to get pkInfo!"); - return HC_ERR_JSON_GET; - } - const char *pdid = GetStringFromJson(pkInfoStr, FIELD_PSEUDONYM_ID); - bool isPseudonym = (pdid != NULL); - IdentityInfo *info = NULL; - int32_t res = ISGetIdentityInfo(impl->context, isPseudonym, &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; - } - - uint32_t credNum = HC_VECTOR_SIZE(&impl->credList); - if (credNum == 0) { - LOGE("No valid credentials with peer."); - return HC_ERR_INIT_FAILED; - } - impl->credCurIndex = 0; - impl->credTotalNum = credNum; - return HC_SUCCESS; -} - static int32_t ProcStartEventInner(SessionImpl *impl, CJson *sessionMsg) { int32_t res; if (impl->credTotalNum == 0) { - res = impl->isCredAuth ? ISClientGetCredInfo(impl) - : GetAllCredsWithPeer(impl); + res = GetAllCredsWithPeer(impl); if (res != HC_SUCCESS) { LOGE("get all credentials with peer device fail."); return res; @@ -1390,7 +1339,7 @@ static int32_t ServerCreateAuthSubSessionByCred(SessionImpl *impl, const CJson * if (res != HC_SUCCESS) { return res; } - res = impl->isCredAuth? AddAuthInfoToContextIS(impl, cred) + res = impl->isCredAuth? ISAddAuthInfoToContext(impl, cred) : AddAuthInfoToContextByCred(impl, cred); if (res != HC_SUCCESS) { return res; @@ -1640,7 +1589,7 @@ static int32_t ProcHandshakeReqEventInner(SessionImpl *impl, SessionEvent *input if (res != HC_SUCCESS) { return res; } - res = impl->isCredAuth ? ISServerGetCredInfo(impl, inputEvent->data) : GetSelfCredByInput(impl, inputEvent->data); + res = GetSelfCredByInput(impl, inputEvent->data); if (res != HC_SUCCESS) { LOGE("get cred by input fail."); return res; @@ -1652,11 +1601,9 @@ static int32_t ProcHandshakeReqEventInner(SessionImpl *impl, SessionEvent *input LOGE("Failed to add isDirectAuth to context!"); return HC_ERR_JSON_ADD; } - if (!impl->isCredAuth) { - res = SetPeerAuthIdToContextIfNeeded(impl->context, selfCred); - if (res != HC_SUCCESS) { - return res; - } + res = SetPeerAuthIdToContextIfNeeded(impl->context, impl->isCredAuth, selfCred); + if (res != HC_SUCCESS) { + return res; } res = CredNegotiate(impl, inputEvent->data, selfCred); if (res != HC_SUCCESS) { @@ -1714,7 +1661,7 @@ static int32_t ProcHandshakeRspEventInner(SessionImpl *impl, SessionEvent *input LOGE("Failed to add isDirectAuth to context!"); return HC_ERR_JSON_ADD; } - int32_t res = SetPeerAuthIdToContextIfNeeded(impl->context, selfCred); + int32_t res = SetPeerAuthIdToContextIfNeeded(impl->context, impl->isCredAuth, selfCred); if (res != HC_SUCCESS) { return res; } 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 58a81cee..846fc6dd 100644 --- a/test/fuzztest/authenticators/account_related/auth/isoauthtask_fuzzer/BUILD.gn +++ b/test/fuzztest/authenticators/account_related/auth/isoauthtask_fuzzer/BUILD.gn @@ -39,6 +39,7 @@ ohos_fuzztest("IsoAuthTaskFuzzTest") { include_dirs += identity_manager_inc sources = [ "isoauthtask_fuzzer.cpp" ] + sources += identity_service_mock_files sources += deviceauth_files if (support_os_account) { sources += account_subscriber_files 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 b48024ee..6f858337 100644 --- a/test/fuzztest/authenticators/account_unrelated/pake/standardexchangetask_fuzzer/BUILD.gn +++ b/test/fuzztest/authenticators/account_unrelated/pake/standardexchangetask_fuzzer/BUILD.gn @@ -41,6 +41,7 @@ ohos_fuzztest("StandardExchangeTaskFuzzTest") { sources = [ "standardexchangetask_fuzzer.cpp" ] sources += deviceauth_ipc_files + sources += identity_service_mock_files sources += deviceauth_files sources += identity_manager_files sources += permission_adapter_files diff --git a/test/fuzztest/creds_manager/credsmanager_fuzzer/BUILD.gn b/test/fuzztest/creds_manager/credsmanager_fuzzer/BUILD.gn index 0638fe34..1f184582 100644 --- a/test/fuzztest/creds_manager/credsmanager_fuzzer/BUILD.gn +++ b/test/fuzztest/creds_manager/credsmanager_fuzzer/BUILD.gn @@ -38,6 +38,7 @@ ohos_fuzztest("CredsManagerFuzzTest") { include_dirs += identity_manager_inc sources = [ "credsmanager_fuzzer.cpp" ] + sources += identity_service_mock_files sources += deviceauth_files sources += hal_common_files sources += hiview_adapter_files diff --git a/test/fuzztest/devauth_fuzzer/BUILD.gn b/test/fuzztest/devauth_fuzzer/BUILD.gn index 34b5fb00..d70ea561 100644 --- a/test/fuzztest/devauth_fuzzer/BUILD.gn +++ b/test/fuzztest/devauth_fuzzer/BUILD.gn @@ -43,6 +43,7 @@ ohos_fuzztest("DevAuthFuzzTest") { sources += permission_adapter_files sources += [ "${frameworks_path}/src/ipc_service_common.c" ] sources += [ "${frameworks_path}/src/ipc_service_lite.c" ] + sources += identity_service_mock_files sources += deviceauth_files if (support_os_account) { sources += account_subscriber_files diff --git a/test/fuzztest/devauthfunc_fuzzer/BUILD.gn b/test/fuzztest/devauthfunc_fuzzer/BUILD.gn index b3bdd10f..dbdd9876 100644 --- a/test/fuzztest/devauthfunc_fuzzer/BUILD.gn +++ b/test/fuzztest/devauthfunc_fuzzer/BUILD.gn @@ -55,6 +55,7 @@ ohos_fuzztest("DevAuthFuncFuzzTest") { sources += dev_frameworks_files sources += deviceauth_common_files + sources += identity_service_mock_files sources += group_database_manager_files sources += ext_plugin_manager_files sources += session_manager_files diff --git a/test/fuzztest/device_auth_service/devauthservaddmembertogroup_fuzzer/BUILD.gn b/test/fuzztest/device_auth_service/devauthservaddmembertogroup_fuzzer/BUILD.gn index e54ff933..c4edc3ef 100644 --- a/test/fuzztest/device_auth_service/devauthservaddmembertogroup_fuzzer/BUILD.gn +++ b/test/fuzztest/device_auth_service/devauthservaddmembertogroup_fuzzer/BUILD.gn @@ -31,6 +31,7 @@ ohos_fuzztest("DevAuthServAddMemberToGroupFuzzTest") { "${dev_frameworks_path}/inc/hiview_adapter", ] sources = [ "devauthservaddmembertogroup_fuzzer.cpp" ] + sources += identity_service_mock_files sources += deviceauth_files sources += hiview_adapter_files if (device_auth_enable_soft_bus_channel == true) { diff --git a/test/fuzztest/device_auth_service/devauthservaddmultimemberstogroup_fuzzer/BUILD.gn b/test/fuzztest/device_auth_service/devauthservaddmultimemberstogroup_fuzzer/BUILD.gn index c4f38173..f4e20b37 100644 --- a/test/fuzztest/device_auth_service/devauthservaddmultimemberstogroup_fuzzer/BUILD.gn +++ b/test/fuzztest/device_auth_service/devauthservaddmultimemberstogroup_fuzzer/BUILD.gn @@ -31,6 +31,7 @@ ohos_fuzztest("DevAuthServAddMultiMembersToGroupFuzzTest") { "${dev_frameworks_path}/inc/hiview_adapter", ] sources = [ "devauthservaddmultimemberstogroup_fuzzer.cpp" ] + sources += identity_service_mock_files sources += deviceauth_files sources += hiview_adapter_files if (device_auth_enable_soft_bus_channel == true) { diff --git a/test/fuzztest/device_auth_service/devauthservauthdevice_fuzzer/BUILD.gn b/test/fuzztest/device_auth_service/devauthservauthdevice_fuzzer/BUILD.gn index c922e451..a1b0e11a 100644 --- a/test/fuzztest/device_auth_service/devauthservauthdevice_fuzzer/BUILD.gn +++ b/test/fuzztest/device_auth_service/devauthservauthdevice_fuzzer/BUILD.gn @@ -31,6 +31,7 @@ ohos_fuzztest("DevAuthServAuthDeviceFuzzTest") { "${dev_frameworks_path}/inc/hiview_adapter", ] sources = [ "devauthservauthdevice_fuzzer.cpp" ] + sources += identity_service_mock_files sources += deviceauth_files sources += hiview_adapter_files if (device_auth_enable_soft_bus_channel == true) { diff --git a/test/fuzztest/device_auth_service/devauthservcancelauthrequest_fuzzer/BUILD.gn b/test/fuzztest/device_auth_service/devauthservcancelauthrequest_fuzzer/BUILD.gn index 0d2d16c1..b3d48db1 100644 --- a/test/fuzztest/device_auth_service/devauthservcancelauthrequest_fuzzer/BUILD.gn +++ b/test/fuzztest/device_auth_service/devauthservcancelauthrequest_fuzzer/BUILD.gn @@ -31,6 +31,7 @@ ohos_fuzztest("DevAuthServCancelAuthRequestFuzzTest") { "${dev_frameworks_path}/inc/hiview_adapter", ] sources = [ "devauthservcancelauthrequest_fuzzer.cpp" ] + sources += identity_service_mock_files sources += deviceauth_files sources += hiview_adapter_files if (device_auth_enable_soft_bus_channel == true) { diff --git a/test/fuzztest/device_auth_service/devauthservcancelbindrequest_fuzzer/BUILD.gn b/test/fuzztest/device_auth_service/devauthservcancelbindrequest_fuzzer/BUILD.gn index 4a907197..999e35f8 100644 --- a/test/fuzztest/device_auth_service/devauthservcancelbindrequest_fuzzer/BUILD.gn +++ b/test/fuzztest/device_auth_service/devauthservcancelbindrequest_fuzzer/BUILD.gn @@ -31,6 +31,7 @@ ohos_fuzztest("DevAuthServCancelBindRequestFuzzTest") { "${dev_frameworks_path}/inc/hiview_adapter", ] sources = [ "devauthservcancelbindrequest_fuzzer.cpp" ] + sources += identity_service_mock_files sources += deviceauth_files sources += hiview_adapter_files if (device_auth_enable_soft_bus_channel == true) { diff --git a/test/fuzztest/device_auth_service/devauthservcheckaccesstogroup_fuzzer/BUILD.gn b/test/fuzztest/device_auth_service/devauthservcheckaccesstogroup_fuzzer/BUILD.gn index 1abba39b..ba9ad6f6 100644 --- a/test/fuzztest/device_auth_service/devauthservcheckaccesstogroup_fuzzer/BUILD.gn +++ b/test/fuzztest/device_auth_service/devauthservcheckaccesstogroup_fuzzer/BUILD.gn @@ -31,6 +31,7 @@ ohos_fuzztest("DevAuthServCheckAccessToGroupFuzzTest") { "${dev_frameworks_path}/inc/hiview_adapter", ] sources = [ "devauthservcheckaccesstogroup_fuzzer.cpp" ] + sources += identity_service_mock_files sources += deviceauth_files sources += hiview_adapter_files if (device_auth_enable_soft_bus_channel == true) { diff --git a/test/fuzztest/device_auth_service/devauthservcreategroup_fuzzer/BUILD.gn b/test/fuzztest/device_auth_service/devauthservcreategroup_fuzzer/BUILD.gn index c0e6edb3..80332d3b 100644 --- a/test/fuzztest/device_auth_service/devauthservcreategroup_fuzzer/BUILD.gn +++ b/test/fuzztest/device_auth_service/devauthservcreategroup_fuzzer/BUILD.gn @@ -31,6 +31,7 @@ ohos_fuzztest("DevAuthServCreateGroupFuzzTest") { "${dev_frameworks_path}/inc/hiview_adapter", ] sources = [ "devauthservcreategroup_fuzzer.cpp" ] + sources += identity_service_mock_files sources += deviceauth_files sources += hiview_adapter_files if (device_auth_enable_soft_bus_channel == true) { diff --git a/test/fuzztest/device_auth_service/devauthservdeletegroup_fuzzer/BUILD.gn b/test/fuzztest/device_auth_service/devauthservdeletegroup_fuzzer/BUILD.gn index 19463acd..ead73668 100644 --- a/test/fuzztest/device_auth_service/devauthservdeletegroup_fuzzer/BUILD.gn +++ b/test/fuzztest/device_auth_service/devauthservdeletegroup_fuzzer/BUILD.gn @@ -31,6 +31,7 @@ ohos_fuzztest("DevAuthServDeleteGroupFuzzTest") { "${dev_frameworks_path}/inc/hiview_adapter", ] sources = [ "devauthservdeletegroup_fuzzer.cpp" ] + sources += identity_service_mock_files sources += deviceauth_files sources += hiview_adapter_files if (device_auth_enable_soft_bus_channel == true) { diff --git a/test/fuzztest/device_auth_service/devauthservdeletememberfromgroup_fuzzer/BUILD.gn b/test/fuzztest/device_auth_service/devauthservdeletememberfromgroup_fuzzer/BUILD.gn index 564ec372..24eaa674 100644 --- a/test/fuzztest/device_auth_service/devauthservdeletememberfromgroup_fuzzer/BUILD.gn +++ b/test/fuzztest/device_auth_service/devauthservdeletememberfromgroup_fuzzer/BUILD.gn @@ -31,6 +31,7 @@ ohos_fuzztest("DevAuthServDeleteMemberFromGroupFuzzTest") { "${dev_frameworks_path}/inc/hiview_adapter", ] sources = [ "devauthservdeletememberfromgroup_fuzzer.cpp" ] + sources += identity_service_mock_files sources += deviceauth_files sources += hiview_adapter_files if (device_auth_enable_soft_bus_channel == true) { diff --git a/test/fuzztest/device_auth_service/devauthservdeletemultimembersfromgroup_fuzzer/BUILD.gn b/test/fuzztest/device_auth_service/devauthservdeletemultimembersfromgroup_fuzzer/BUILD.gn index 0fc36667..f35aa9fc 100644 --- a/test/fuzztest/device_auth_service/devauthservdeletemultimembersfromgroup_fuzzer/BUILD.gn +++ b/test/fuzztest/device_auth_service/devauthservdeletemultimembersfromgroup_fuzzer/BUILD.gn @@ -31,6 +31,7 @@ ohos_fuzztest("DevAuthServDeleteMultiMembersFromGroupFuzzTest") { "${dev_frameworks_path}/inc/hiview_adapter", ] sources = [ "devauthservdeletemultimembersfromgroup_fuzzer.cpp" ] + sources += identity_service_mock_files sources += deviceauth_files sources += hiview_adapter_files if (device_auth_enable_soft_bus_channel == true) { diff --git a/test/fuzztest/device_auth_service/devauthservgetdeviceinfobyid_fuzzer/BUILD.gn b/test/fuzztest/device_auth_service/devauthservgetdeviceinfobyid_fuzzer/BUILD.gn index 120baab7..80a3f412 100644 --- a/test/fuzztest/device_auth_service/devauthservgetdeviceinfobyid_fuzzer/BUILD.gn +++ b/test/fuzztest/device_auth_service/devauthservgetdeviceinfobyid_fuzzer/BUILD.gn @@ -31,6 +31,7 @@ ohos_fuzztest("DevAuthServGetDeviceInfoByIdFuzzTest") { "${dev_frameworks_path}/inc/hiview_adapter", ] sources = [ "devauthservgetdeviceinfobyid_fuzzer.cpp" ] + sources += identity_service_mock_files sources += deviceauth_files sources += hiview_adapter_files if (device_auth_enable_soft_bus_channel == true) { diff --git a/test/fuzztest/device_auth_service/devauthservgetgroupinfo_fuzzer/BUILD.gn b/test/fuzztest/device_auth_service/devauthservgetgroupinfo_fuzzer/BUILD.gn index 9e8bf848..ef6b68f7 100644 --- a/test/fuzztest/device_auth_service/devauthservgetgroupinfo_fuzzer/BUILD.gn +++ b/test/fuzztest/device_auth_service/devauthservgetgroupinfo_fuzzer/BUILD.gn @@ -31,6 +31,7 @@ ohos_fuzztest("DevAuthServGetGroupInfoFuzzTest") { "${dev_frameworks_path}/inc/hiview_adapter", ] sources = [ "devauthservgetgroupinfo_fuzzer.cpp" ] + sources += identity_service_mock_files sources += deviceauth_files sources += hiview_adapter_files if (device_auth_enable_soft_bus_channel == true) { diff --git a/test/fuzztest/device_auth_service/devauthservgetgroupinfobyid_fuzzer/BUILD.gn b/test/fuzztest/device_auth_service/devauthservgetgroupinfobyid_fuzzer/BUILD.gn index f93c1f57..80d036b3 100644 --- a/test/fuzztest/device_auth_service/devauthservgetgroupinfobyid_fuzzer/BUILD.gn +++ b/test/fuzztest/device_auth_service/devauthservgetgroupinfobyid_fuzzer/BUILD.gn @@ -31,6 +31,7 @@ ohos_fuzztest("DevAuthServGetGroupInfoByIdFuzzTest") { "${dev_frameworks_path}/inc/hiview_adapter", ] sources = [ "devauthservgetgroupinfobyid_fuzzer.cpp" ] + sources += identity_service_mock_files sources += deviceauth_files sources += hiview_adapter_files if (device_auth_enable_soft_bus_channel == true) { diff --git a/test/fuzztest/device_auth_service/devauthservgetjoinedgroups_fuzzer/BUILD.gn b/test/fuzztest/device_auth_service/devauthservgetjoinedgroups_fuzzer/BUILD.gn index a9104c8a..0d8908e7 100644 --- a/test/fuzztest/device_auth_service/devauthservgetjoinedgroups_fuzzer/BUILD.gn +++ b/test/fuzztest/device_auth_service/devauthservgetjoinedgroups_fuzzer/BUILD.gn @@ -31,6 +31,7 @@ ohos_fuzztest("DevAuthServGetJoinedGroupsFuzzTest") { "${dev_frameworks_path}/inc/hiview_adapter", ] sources = [ "devauthservgetjoinedgroups_fuzzer.cpp" ] + sources += identity_service_mock_files sources += deviceauth_files sources += hiview_adapter_files if (device_auth_enable_soft_bus_channel == true) { diff --git a/test/fuzztest/device_auth_service/devauthservgetpkinfolist_fuzzer/BUILD.gn b/test/fuzztest/device_auth_service/devauthservgetpkinfolist_fuzzer/BUILD.gn index 88195369..41a870e2 100644 --- a/test/fuzztest/device_auth_service/devauthservgetpkinfolist_fuzzer/BUILD.gn +++ b/test/fuzztest/device_auth_service/devauthservgetpkinfolist_fuzzer/BUILD.gn @@ -31,6 +31,7 @@ ohos_fuzztest("DevAuthServGetPkInfoListFuzzTest") { "${dev_frameworks_path}/inc/hiview_adapter", ] sources = [ "devauthservgetpkinfolist_fuzzer.cpp" ] + sources += identity_service_mock_files sources += deviceauth_files sources += hiview_adapter_files if (device_auth_enable_soft_bus_channel == true) { diff --git a/test/fuzztest/device_auth_service/devauthservgetregisterinfo_fuzzer/BUILD.gn b/test/fuzztest/device_auth_service/devauthservgetregisterinfo_fuzzer/BUILD.gn index c0b4582d..5a399cbf 100644 --- a/test/fuzztest/device_auth_service/devauthservgetregisterinfo_fuzzer/BUILD.gn +++ b/test/fuzztest/device_auth_service/devauthservgetregisterinfo_fuzzer/BUILD.gn @@ -31,6 +31,7 @@ ohos_fuzztest("DevAuthServGetRegisterInfoFuzzTest") { "${dev_frameworks_path}/inc/hiview_adapter", ] sources = [ "devauthservgetregisterinfo_fuzzer.cpp" ] + sources += identity_service_mock_files sources += deviceauth_files sources += hiview_adapter_files if (device_auth_enable_soft_bus_channel == true) { diff --git a/test/fuzztest/device_auth_service/devauthservgetrelatedgroups_fuzzer/BUILD.gn b/test/fuzztest/device_auth_service/devauthservgetrelatedgroups_fuzzer/BUILD.gn index bee3ced8..81083fda 100644 --- a/test/fuzztest/device_auth_service/devauthservgetrelatedgroups_fuzzer/BUILD.gn +++ b/test/fuzztest/device_auth_service/devauthservgetrelatedgroups_fuzzer/BUILD.gn @@ -31,6 +31,7 @@ ohos_fuzztest("DevAuthServGetRelatedGroupsFuzzTest") { "${dev_frameworks_path}/inc/hiview_adapter", ] sources = [ "devauthservgetrelatedgroups_fuzzer.cpp" ] + sources += identity_service_mock_files sources += deviceauth_files sources += hiview_adapter_files if (device_auth_enable_soft_bus_channel == true) { diff --git a/test/fuzztest/device_auth_service/devauthservgettrusteddevices_fuzzer/BUILD.gn b/test/fuzztest/device_auth_service/devauthservgettrusteddevices_fuzzer/BUILD.gn index 8f0e6c2b..fab1839e 100644 --- a/test/fuzztest/device_auth_service/devauthservgettrusteddevices_fuzzer/BUILD.gn +++ b/test/fuzztest/device_auth_service/devauthservgettrusteddevices_fuzzer/BUILD.gn @@ -31,6 +31,7 @@ ohos_fuzztest("DevAuthServGetTrustedDevicesFuzzTest") { "${dev_frameworks_path}/inc/hiview_adapter", ] sources = [ "devauthservgettrusteddevices_fuzzer.cpp" ] + sources += identity_service_mock_files sources += deviceauth_files sources += hiview_adapter_files if (device_auth_enable_soft_bus_channel == true) { diff --git a/test/fuzztest/device_auth_service/devauthservisdeviceingroup_fuzzer/BUILD.gn b/test/fuzztest/device_auth_service/devauthservisdeviceingroup_fuzzer/BUILD.gn index 14b17be5..dfecb3a0 100644 --- a/test/fuzztest/device_auth_service/devauthservisdeviceingroup_fuzzer/BUILD.gn +++ b/test/fuzztest/device_auth_service/devauthservisdeviceingroup_fuzzer/BUILD.gn @@ -31,6 +31,7 @@ ohos_fuzztest("DevAuthServIsDeviceInGroupFuzzTest") { "${dev_frameworks_path}/inc/hiview_adapter", ] sources = [ "devauthservisdeviceingroup_fuzzer.cpp" ] + sources += identity_service_mock_files sources += deviceauth_files sources += hiview_adapter_files if (device_auth_enable_soft_bus_channel == true) { diff --git a/test/fuzztest/device_auth_service/devauthservprocessauthdata_fuzzer/BUILD.gn b/test/fuzztest/device_auth_service/devauthservprocessauthdata_fuzzer/BUILD.gn index d5652b6c..d71f68b0 100644 --- a/test/fuzztest/device_auth_service/devauthservprocessauthdata_fuzzer/BUILD.gn +++ b/test/fuzztest/device_auth_service/devauthservprocessauthdata_fuzzer/BUILD.gn @@ -31,6 +31,7 @@ ohos_fuzztest("DevAuthServProcessAuthDataFuzzTest") { "${dev_frameworks_path}/inc/hiview_adapter", ] sources = [ "devauthservprocessauthdata_fuzzer.cpp" ] + sources += identity_service_mock_files sources += deviceauth_files sources += hiview_adapter_files if (device_auth_enable_soft_bus_channel == true) { diff --git a/test/fuzztest/device_auth_service/devauthservprocessbinddata_fuzzer/BUILD.gn b/test/fuzztest/device_auth_service/devauthservprocessbinddata_fuzzer/BUILD.gn index 97490bb5..e6dac9a4 100644 --- a/test/fuzztest/device_auth_service/devauthservprocessbinddata_fuzzer/BUILD.gn +++ b/test/fuzztest/device_auth_service/devauthservprocessbinddata_fuzzer/BUILD.gn @@ -31,6 +31,7 @@ ohos_fuzztest("DevAuthServProcessBindDataFuzzTest") { "${dev_frameworks_path}/inc/hiview_adapter", ] sources = [ "devauthservprocessbinddata_fuzzer.cpp" ] + sources += identity_service_mock_files sources += deviceauth_files sources += hiview_adapter_files if (device_auth_enable_soft_bus_channel == true) { diff --git a/test/fuzztest/device_auth_service/devauthservregcallback_fuzzer/BUILD.gn b/test/fuzztest/device_auth_service/devauthservregcallback_fuzzer/BUILD.gn index d6e295b9..786a4f4e 100644 --- a/test/fuzztest/device_auth_service/devauthservregcallback_fuzzer/BUILD.gn +++ b/test/fuzztest/device_auth_service/devauthservregcallback_fuzzer/BUILD.gn @@ -31,6 +31,7 @@ ohos_fuzztest("DevAuthServRegCallbackFuzzTest") { "${dev_frameworks_path}/inc/hiview_adapter", ] sources = [ "devauthservregcallback_fuzzer.cpp" ] + sources += identity_service_mock_files sources += deviceauth_files sources += hiview_adapter_files if (device_auth_enable_soft_bus_channel == true) { diff --git a/test/fuzztest/device_auth_service/devauthservregdatachangelistener_fuzzer/BUILD.gn b/test/fuzztest/device_auth_service/devauthservregdatachangelistener_fuzzer/BUILD.gn index f22b3b03..575b63e9 100644 --- a/test/fuzztest/device_auth_service/devauthservregdatachangelistener_fuzzer/BUILD.gn +++ b/test/fuzztest/device_auth_service/devauthservregdatachangelistener_fuzzer/BUILD.gn @@ -31,6 +31,7 @@ ohos_fuzztest("DevAuthServRegDataChangeListenerFuzzTest") { "${dev_frameworks_path}/inc/hiview_adapter", ] sources = [ "devauthservregdatachangelistener_fuzzer.cpp" ] + sources += identity_service_mock_files sources += deviceauth_files sources += hiview_adapter_files if (device_auth_enable_soft_bus_channel == true) { diff --git a/test/fuzztest/device_auth_service/devauthservunregcallback_fuzzer/BUILD.gn b/test/fuzztest/device_auth_service/devauthservunregcallback_fuzzer/BUILD.gn index 9b727771..3682f62d 100644 --- a/test/fuzztest/device_auth_service/devauthservunregcallback_fuzzer/BUILD.gn +++ b/test/fuzztest/device_auth_service/devauthservunregcallback_fuzzer/BUILD.gn @@ -31,6 +31,7 @@ ohos_fuzztest("DevAuthServUnregCallbackFuzzTest") { "${dev_frameworks_path}/inc/hiview_adapter", ] sources = [ "devauthservunregcallback_fuzzer.cpp" ] + sources += identity_service_mock_files sources += deviceauth_files sources += hiview_adapter_files if (device_auth_enable_soft_bus_channel == true) { diff --git a/test/fuzztest/device_auth_service/devauthservunregdatachangelistener_fuzzer/BUILD.gn b/test/fuzztest/device_auth_service/devauthservunregdatachangelistener_fuzzer/BUILD.gn index 43e0ae91..60495976 100644 --- a/test/fuzztest/device_auth_service/devauthservunregdatachangelistener_fuzzer/BUILD.gn +++ b/test/fuzztest/device_auth_service/devauthservunregdatachangelistener_fuzzer/BUILD.gn @@ -31,6 +31,7 @@ ohos_fuzztest("DevAuthServUnregDataChangeListenerFuzzTest") { "${dev_frameworks_path}/inc/hiview_adapter", ] sources = [ "devauthservunregdatachangelistener_fuzzer.cpp" ] + sources += identity_service_mock_files sources += deviceauth_files sources += hiview_adapter_files if (device_auth_enable_soft_bus_channel == true) { 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 2a72ce74..271e9a12 100644 --- a/test/fuzztest/group_auth/account_related/accountrelatedgroupauth_fuzzer/BUILD.gn +++ b/test/fuzztest/group_auth/account_related/accountrelatedgroupauth_fuzzer/BUILD.gn @@ -58,6 +58,7 @@ ohos_fuzztest("AccountRelatedGroupAuthFuzzTest") { include_dirs += identity_manager_inc sources += identity_manager_files sources += dev_frameworks_files + sources += identity_service_mock_files sources += deviceauth_common_files sources += group_database_manager_files sources += ext_plugin_manager_files diff --git a/test/fuzztest/group_manage/groupoperationcommon_fuzzer/BUILD.gn b/test/fuzztest/group_manage/groupoperationcommon_fuzzer/BUILD.gn index 485759e5..f6d57ba6 100644 --- a/test/fuzztest/group_manage/groupoperationcommon_fuzzer/BUILD.gn +++ b/test/fuzztest/group_manage/groupoperationcommon_fuzzer/BUILD.gn @@ -41,6 +41,7 @@ ohos_fuzztest("GroupOperationCommonFuzzTest") { include_dirs += [ "${dev_frameworks_path}/inc/net_observer" ] } sources = [ "groupoperationcommon_fuzzer.cpp" ] + sources += identity_service_mock_files sources += deviceauth_files sources += hal_common_files sources += hiview_adapter_files diff --git a/test/fuzztest/identityservice_fuzzer/identityservice_fuzzer.cpp b/test/fuzztest/identityservice_fuzzer/identityservice_fuzzer.cpp index c08cc34a..665cc4eb 100644 --- a/test/fuzztest/identityservice_fuzzer/identityservice_fuzzer.cpp +++ b/test/fuzztest/identityservice_fuzzer/identityservice_fuzzer.cpp @@ -49,100 +49,100 @@ static const char *ADD_PARAMS = "{\"credType\":1,\"keyFormat\":4,\"algorithmType\":3,\"subject\":1,\"issuer\":1," "\"proofType\":1,\"method\":1,\"authorizedScope\":1,\"userId\":\"TestUserId\"," "\"deviceId\":\"TestDeviceId\",\"credOwner\":\"TestAppId\"," - "\"authorizedAccoutList\":[\"TestName1\",\"TestName2\",\"TestName3\"]," + "\"authorizedAppList\":[\"TestName1\",\"TestName2\",\"TestName3\"]," "\"peerUserSpaceId\":100,\"extendInfo\":\"\"}"; static const char *ADD_PARAMS1 = "{\"credType\":0,\"keyFormat\":4,\"algorithmType\":3,\"subject\":1,\"issuer\":1," "\"proofType\":1,\"method\":1,\"authorizedScope\":1,\"userId\":\"TestUserId\"," "\"deviceId\":\"TestDeviceId\",\"credOwner\":\"TestAppId\"," - "\"authorizedAccoutList\":[\"TestName1\",\"TestName2\",\"TestName3\"]," + "\"authorizedAppList\":[\"TestName1\",\"TestName2\",\"TestName3\"]," "\"peerUserSpaceId\":100,\"extendInfo\":\"\"}"; static const char *ADD_PARAMS2 = "{\"credType\":1,\"keyFormat\":0,\"algorithmType\":3,\"subject\":1,\"issuer\":1," "\"proofType\":1,\"method\":1,\"authorizedScope\":1,\"userId\":\"TestUserId\"," "\"deviceId\":\"TestDeviceId\",\"credOwner\":\"TestAppId\"," - "\"authorizedAccoutList\":[\"TestName1\",\"TestName2\",\"TestName3\"]," + "\"authorizedAppList\":[\"TestName1\",\"TestName2\",\"TestName3\"]," "\"peerUserSpaceId\":100,\"extendInfo\":\"\"}"; static const char *ADD_PARAMS3 = "{\"credType\":1,\"keyFormat\":4,\"algorithmType\":0,\"subject\":1,\"issuer\":1," "\"proofType\":1,\"method\":1,\"authorizedScope\":1,\"userId\":\"TestUserId\"," "\"deviceId\":\"TestDeviceId\",\"credOwner\":\"TestAppId\"," - "\"authorizedAccoutList\":[\"TestName1\",\"TestName2\",\"TestName3\"]," + "\"authorizedAppList\":[\"TestName1\",\"TestName2\",\"TestName3\"]," "\"peerUserSpaceId\":100,\"extendInfo\":\"\"}"; static const char *ADD_PARAMS4 = "{\"credType\":1,\"keyFormat\":4,\"algorithmType\":3,\"subject\":0,\"issuer\":1," "\"proofType\":1,\"method\":1,\"authorizedScope\":1,\"userId\":\"TestUserId\"," "\"deviceId\":\"TestDeviceId\",\"credOwner\":\"TestAppId\"," - "\"authorizedAccoutList\":[\"TestName1\",\"TestName2\",\"TestName3\"]," + "\"authorizedAppList\":[\"TestName1\",\"TestName2\",\"TestName3\"]," "\"peerUserSpaceId\":100,\"extendInfo\":\"\"}"; static const char *ADD_PARAMS5 = "{\"credType\":1,\"keyFormat\":4,\"algorithmType\":3,\"subject\":1,\"issuer\":0," "\"proofType\":1,\"method\":1,\"authorizedScope\":1,\"userId\":\"TestUserId\"," "\"deviceId\":\"TestDeviceId\",\"credOwner\":\"TestAppId\"," - "\"authorizedAccoutList\":[\"TestName1\",\"TestName2\",\"TestName3\"]," + "\"authorizedAppList\":[\"TestName1\",\"TestName2\",\"TestName3\"]," "\"peerUserSpaceId\":100,\"extendInfo\":\"\"}"; static const char *ADD_PARAMS6 = "{\"credType\":1,\"keyFormat\":4,\"algorithmType\":3,\"subject\":1,\"issuer\":1," "\"proofType\":0,\"method\":1,\"authorizedScope\":1,\"userId\":\"TestUserId\"," "\"deviceId\":\"TestDeviceId\",\"credOwner\":\"TestAppId\"," - "\"authorizedAccoutList\":[\"TestName1\",\"TestName2\",\"TestName3\"]," + "\"authorizedAppList\":[\"TestName1\",\"TestName2\",\"TestName3\"]," "\"peerUserSpaceId\":100,\"extendInfo\":\"\"}"; static const char *ADD_PARAMS7 = "{\"credType\":1,\"keyFormat\":4,\"algorithmType\":3,\"subject\":1,\"issuer\":1," "\"proofType\":1,\"method\":0,\"authorizedScope\":1,\"userId\":\"TestUserId\"," "\"keyValue\":\"TestKeyValue\",\"deviceId\":\"TestDeviceId\",\"credOwner\":\"TestAppId\"," - "\"authorizedAccoutList\":[\"TestName1\",\"TestName2\",\"TestName3\"]," + "\"authorizedAppList\":[\"TestName1\",\"TestName2\",\"TestName3\"]," "\"peerUserSpaceId\":100,\"extendInfo\":\"\"}"; static const char *ADD_PARAMS8 = "{\"credType\":1,\"keyFormat\":4,\"algorithmType\":3,\"subject\":1,\"issuer\":1," "\"proofType\":1,\"method\":1,\"authorizedScope\":0,\"userId\":\"TestUserId\"," "\"deviceId\":\"TestDeviceId\",\"credOwner\":\"TestAppId\"," - "\"authorizedAccoutList\":[\"TestName1\",\"TestName2\",\"TestName3\"]," + "\"authorizedAppList\":[\"TestName1\",\"TestName2\",\"TestName3\"]," "\"peerUserSpaceId\":100,\"extendInfo\":\"\"}"; static const char *ADD_PARAMS9 = "{\"credType\":1,\"keyFormat\":4,\"algorithmType\":3,\"subject\":1,\"issuer\":1," "\"proofType\":1,\"method\":1,\"authorizedScope\":1,\"userId\":\"TestUserId\"," "\"credOwner\":\"TestAppId\"," - "\"authorizedAccoutList\":[\"TestName1\",\"TestName2\",\"TestName3\"]," + "\"authorizedAppList\":[\"TestName1\",\"TestName2\",\"TestName3\"]," "\"peerUserSpaceId\":100,\"extendInfo\":\"\"}"; static const char *ADD_PARAMS10 = "{\"credType\":1,\"keyFormat\":4,\"algorithmType\":3,\"subject\":1,\"issuer\":1," "\"proofType\":1,\"method\":1,\"authorizedScope\":1,\"userId\":\"TestUserId\"," "\"deviceId\":\"TestDeviceId\"," - "\"authorizedAccoutList\":[\"TestName1\",\"TestName2\",\"TestName3\"]," + "\"authorizedAppList\":[\"TestName1\",\"TestName2\",\"TestName3\"]," "\"peerUserSpaceId\":100,\"extendInfo\":\"\"}"; static const char *ADD_PARAMS11 = "{\"credType\":1,\"keyFormat\":4,\"algorithmType\":3,\"subject\":1,\"issuer\":1," "\"proofType\":1,\"method\":1,\"authorizedScope\":1," "\"deviceId\":\"TestDeviceId\",\"credOwner\":\"TestAppId\"," - "\"authorizedAccoutList\":[\"TestName1\",\"TestName2\",\"TestName3\"]," + "\"authorizedAppList\":[\"TestName1\",\"TestName2\",\"TestName3\"]," "\"peerUserSpaceId\":100,\"extendInfo\":\"\"}"; static const char *ADD_PARAMS12 = "{\"credType\":1,\"keyFormat\":4,\"algorithmType\":3,\"subject\":1,\"issuer\":1," "\"proofType\":1,\"method\":2,\"authorizedScope\":1,\"userId\":\"TestUserId\"," "\"deviceId\":\"TestDeviceId\",\"credOwner\":\"TestAppId\"," - "\"authorizedAccoutList\":[\"TestName1\",\"TestName2\",\"TestName3\"]," + "\"authorizedAppList\":[\"TestName1\",\"TestName2\",\"TestName3\"]," "\"peerUserSpaceId\":100,\"extendInfo\":\"\"}"; static const char *ADD_PARAMS13 = "{\"credType\":2,\"keyFormat\":4,\"algorithmType\":3,\"subject\":1,\"issuer\":1," "\"proofType\":1,\"method\":2,\"authorizedScope\":1,\"userId\":\"TestUserId\"," "\"keyValue\":\"9A9A9A9A\",\"deviceId\":\"TestDeviceId\",\"credOwner\":\"TestAppId\"," - "\"authorizedAccoutList\":[\"TestName1\",\"TestName2\",\"TestName3\"]," + "\"authorizedAppList\":[\"TestName1\",\"TestName2\",\"TestName3\"]," "\"peerUserSpaceId\":100,\"extendInfo\":\"\"}"; static const char *ADD_PARAMS14 = "{\"credType\":1,\"keyFormat\":4,\"algorithmType\":3,\"subject\":1,\"issuer\":1," "\"proofType\":1,\"method\":1,\"authorizedScope\":1,\"userId\":\"TestUserId\"," "\"deviceId\":\"TestDeviceId\",\"credOwner\":\"TestAppId1\"," - "\"authorizedAccoutList\":[\"TestName1\",\"TestName2\",\"TestName3\"]," + "\"authorizedAppList\":[\"TestName1\",\"TestName2\",\"TestName3\"]," "\"peerUserSpaceId\":100,\"extendInfo\":\"\"}"; static const char *ADD_PARAMS15 = "{\"credType\":1,\"keyFormat\":4,\"algorithmType\":3,\"subject\":1,\"issuer\":1," "\"proofType\":1,\"method\":1,\"authorizedScope\":1,\"userId\":\"TestUserId\"," "\"keyValue\":\"TestKeyValue\",\"deviceId\":\"TestDeviceId\",\"credOwner\":\"TestAppId\"," - "\"authorizedAccoutList\":[\"TestName1\",\"TestName2\",\"TestName3\"]," + "\"authorizedAppList\":[\"TestName1\",\"TestName2\",\"TestName3\"]," "\"peerUserSpaceId\":100,\"extendInfo\":\"\"}"; static const char *REQUEST_PARAMS = - "{\"authorizedScope\":1, \"authorizedAccoutList\":[\"TestName1\",\"TestName2\",\"TestName3\"," + "{\"authorizedScope\":1, \"authorizedAppList\":[\"TestName1\",\"TestName2\",\"TestName3\"," "\"TestName4\"],\"extendInfo\":\"\"}"; static const char *QUERY_PARAMS = "{\"deviceId\":\"TestDeviceId\"}"; 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 777142de..fccc9dcb 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 @@ -48,6 +48,7 @@ ohos_fuzztest("AuthSubSessionFuzzTest") { } deps = [ "${deps_adapter_path}:${hal_module_test_name}" ] include_dirs += identity_manager_inc + include_dirs += identity_service_inc include_dirs += [ "${dev_frameworks_path}/inc", "${group_manager_path}/inc", 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 6c87ed7b..e55e4dc4 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 @@ -44,6 +44,7 @@ ohos_fuzztest("AuthCodeImportFuzzTest") { } deps = [ "${deps_adapter_path}:${hal_module_test_name}" ] include_dirs += identity_manager_inc + include_dirs += identity_service_inc include_dirs += [ "${dev_frameworks_path}/inc", "${group_manager_path}/inc", 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 6579a37a..25ad8387 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 @@ -47,6 +47,7 @@ ohos_fuzztest("PubkeyExchangeFuzzTest") { } deps = [ "${deps_adapter_path}:${hal_module_test_name}" ] include_dirs += identity_manager_inc + include_dirs += identity_service_inc include_dirs += [ "${dev_frameworks_path}/inc", "${group_manager_path}/inc", 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 feeb1aff..06fde4d5 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 @@ -45,6 +45,7 @@ ohos_fuzztest("SaveTrustedInfoFuzzTest") { } deps = [ "${deps_adapter_path}:${hal_module_test_name}" ] include_dirs += identity_manager_inc + include_dirs += identity_service_inc include_dirs += [ "${dev_frameworks_path}/inc", "${group_manager_path}/inc", 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 d42eea88..9bdf81a8 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 @@ -51,6 +51,7 @@ ohos_fuzztest("ExpandSubSessionFuzzTest") { } deps = [ "${deps_adapter_path}:${hal_module_test_name}" ] include_dirs += identity_manager_inc + include_dirs += identity_service_inc include_dirs += [ "${dev_frameworks_path}/inc", "${group_manager_path}/inc", diff --git a/test/unittest/deviceauth/BUILD.gn b/test/unittest/deviceauth/BUILD.gn index 7aaf691e..16e2e664 100644 --- a/test/unittest/deviceauth/BUILD.gn +++ b/test/unittest/deviceauth/BUILD.gn @@ -52,6 +52,7 @@ ohos_unittest("deviceauth_llt") { ] sources += dev_frameworks_files + sources += identity_service_mock_files sources += deviceauth_common_files sources += group_database_manager_files sources += ext_plugin_manager_files @@ -173,6 +174,7 @@ ohos_unittest("device_auth_func_test") { ] sources += dev_frameworks_files + sources += identity_service_mock_files sources += deviceauth_common_files sources += group_database_manager_files sources += ext_plugin_manager_files @@ -439,6 +441,7 @@ ohos_unittest("device_auth_interface_test") { ] sources += dev_frameworks_files + sources += identity_service_mock_files sources += deviceauth_common_files sources += group_database_manager_files sources += ext_plugin_manager_files @@ -564,6 +567,7 @@ ohos_unittest("deviceauth_unit_test") { include_dirs += identity_manager_inc sources += identity_manager_files + sources += identity_service_mock_files sources += dev_frameworks_files sources += deviceauth_common_files sources += group_database_manager_files diff --git a/test/unittest/deviceauth/source/deviceauth_func_test.cpp b/test/unittest/deviceauth/source/deviceauth_func_test.cpp index c204f29a..431b9466 100644 --- a/test/unittest/deviceauth/source/deviceauth_func_test.cpp +++ b/test/unittest/deviceauth/source/deviceauth_func_test.cpp @@ -1962,4 +1962,10 @@ HWTEST_F(DeviceAuthFuncTest, DeviceAuthFuncTest010, TestSize.Level0) AddDemoMember(); ASSERT_EQ(g_asyncStatus, ASYNC_STATUS_ERROR); } + +HWTEST_F(DeviceAuthFuncTest, DeviceAuthFuncTest011, TestSize.Level0) +{ + const CredAuthManager *cm = GetCredAuthInstance(); + ASSERT_NE(cm, nullptr); +} } // namespace diff --git a/test/unittest/deviceauth/source/deviceauth_identity_service_test.cpp b/test/unittest/deviceauth/source/deviceauth_identity_service_test.cpp index 664336f4..51426921 100644 --- a/test/unittest/deviceauth/source/deviceauth_identity_service_test.cpp +++ b/test/unittest/deviceauth/source/deviceauth_identity_service_test.cpp @@ -34,6 +34,7 @@ #include "hc_log.h" #include "hc_types.h" #include "../../../../services/identity_service/src/identity_operation.c" +#include "../../../../services/identity_service/src/identity_service_impl.c" #include "cred_listener.h" using namespace std; @@ -58,104 +59,133 @@ static const char *ADD_PARAMS = "{\"credType\":1,\"keyFormat\":4,\"algorithmType\":3,\"subject\":1,\"issuer\":1," "\"proofType\":1,\"method\":1,\"authorizedScope\":1,\"userId\":\"TestUserId\"," "\"deviceId\":\"TestDeviceId\",\"credOwner\":\"TestAppId\"," - "\"authorizedAccoutList\":[\"TestName1\",\"TestName2\",\"TestName3\"]," + "\"authorizedAppList\":[\"TestName1\",\"TestName2\",\"TestName3\"]," "\"peerUserSpaceId\":100,\"extendInfo\":\"\"}"; static const char *ADD_PARAMS1 = "{\"credType\":0,\"keyFormat\":4,\"algorithmType\":3,\"subject\":1,\"issuer\":1," "\"proofType\":1,\"method\":1,\"authorizedScope\":1,\"userId\":\"TestUserId\"," "\"deviceId\":\"TestDeviceId\",\"credOwner\":\"TestAppId\"," - "\"authorizedAccoutList\":[\"TestName1\",\"TestName2\",\"TestName3\"]," + "\"authorizedAppList\":[\"TestName1\",\"TestName2\",\"TestName3\"]," "\"peerUserSpaceId\":100,\"extendInfo\":\"\"}"; static const char *ADD_PARAMS2 = "{\"credType\":1,\"keyFormat\":0,\"algorithmType\":3,\"subject\":1,\"issuer\":1," "\"proofType\":1,\"method\":1,\"authorizedScope\":1,\"userId\":\"TestUserId\"," "\"deviceId\":\"TestDeviceId\",\"credOwner\":\"TestAppId\"," - "\"authorizedAccoutList\":[\"TestName1\",\"TestName2\",\"TestName3\"]," + "\"authorizedAppList\":[\"TestName1\",\"TestName2\",\"TestName3\"]," "\"peerUserSpaceId\":100,\"extendInfo\":\"\"}"; static const char *ADD_PARAMS3 = "{\"credType\":1,\"keyFormat\":4,\"algorithmType\":0,\"subject\":1,\"issuer\":1," "\"proofType\":1,\"method\":1,\"authorizedScope\":1,\"userId\":\"TestUserId\"," "\"deviceId\":\"TestDeviceId\",\"credOwner\":\"TestAppId\"," - "\"authorizedAccoutList\":[\"TestName1\",\"TestName2\",\"TestName3\"]," + "\"authorizedAppList\":[\"TestName1\",\"TestName2\",\"TestName3\"]," "\"peerUserSpaceId\":100,\"extendInfo\":\"\"}"; static const char *ADD_PARAMS4 = "{\"credType\":1,\"keyFormat\":4,\"algorithmType\":3,\"subject\":0,\"issuer\":1," "\"proofType\":1,\"method\":1,\"authorizedScope\":1,\"userId\":\"TestUserId\"," "\"deviceId\":\"TestDeviceId\",\"credOwner\":\"TestAppId\"," - "\"authorizedAccoutList\":[\"TestName1\",\"TestName2\",\"TestName3\"]," + "\"authorizedAppList\":[\"TestName1\",\"TestName2\",\"TestName3\"]," "\"peerUserSpaceId\":100,\"extendInfo\":\"\"}"; static const char *ADD_PARAMS5 = "{\"credType\":1,\"keyFormat\":4,\"algorithmType\":3,\"subject\":1,\"issuer\":0," "\"proofType\":1,\"method\":1,\"authorizedScope\":1,\"userId\":\"TestUserId\"," "\"deviceId\":\"TestDeviceId\",\"credOwner\":\"TestAppId\"," - "\"authorizedAccoutList\":[\"TestName1\",\"TestName2\",\"TestName3\"]," + "\"authorizedAppList\":[\"TestName1\",\"TestName2\",\"TestName3\"]," "\"peerUserSpaceId\":100,\"extendInfo\":\"\"}"; static const char *ADD_PARAMS6 = "{\"credType\":1,\"keyFormat\":4,\"algorithmType\":3,\"subject\":1,\"issuer\":1," "\"proofType\":0,\"method\":1,\"authorizedScope\":1,\"userId\":\"TestUserId\"," "\"deviceId\":\"TestDeviceId\",\"credOwner\":\"TestAppId\"," - "\"authorizedAccoutList\":[\"TestName1\",\"TestName2\",\"TestName3\"]," + "\"authorizedAppList\":[\"TestName1\",\"TestName2\",\"TestName3\"]," "\"peerUserSpaceId\":100,\"extendInfo\":\"\"}"; static const char *ADD_PARAMS7 = "{\"credType\":1,\"keyFormat\":4,\"algorithmType\":3,\"subject\":1,\"issuer\":1," "\"proofType\":1,\"method\":0,\"authorizedScope\":1,\"userId\":\"TestUserId\"," "\"keyValue\":\"TestKeyValue\",\"deviceId\":\"TestDeviceId\",\"credOwner\":\"TestAppId\"," - "\"authorizedAccoutList\":[\"TestName1\",\"TestName2\",\"TestName3\"]," + "\"authorizedAppList\":[\"TestName1\",\"TestName2\",\"TestName3\"]," "\"peerUserSpaceId\":100,\"extendInfo\":\"\"}"; static const char *ADD_PARAMS8 = "{\"credType\":1,\"keyFormat\":4,\"algorithmType\":3,\"subject\":1,\"issuer\":1," "\"proofType\":1,\"method\":1,\"authorizedScope\":0,\"userId\":\"TestUserId\"," "\"deviceId\":\"TestDeviceId\",\"credOwner\":\"TestAppId\"," - "\"authorizedAccoutList\":[\"TestName1\",\"TestName2\",\"TestName3\"]," + "\"authorizedAppList\":[\"TestName1\",\"TestName2\",\"TestName3\"]," "\"peerUserSpaceId\":100,\"extendInfo\":\"\"}"; static const char *ADD_PARAMS9 = "{\"credType\":1,\"keyFormat\":4,\"algorithmType\":3,\"subject\":1,\"issuer\":1," "\"proofType\":1,\"method\":1,\"authorizedScope\":1,\"userId\":\"TestUserId\"," "\"credOwner\":\"TestAppId\"," - "\"authorizedAccoutList\":[\"TestName1\",\"TestName2\",\"TestName3\"]," + "\"authorizedAppList\":[\"TestName1\",\"TestName2\",\"TestName3\"]," "\"peerUserSpaceId\":100,\"extendInfo\":\"\"}"; static const char *ADD_PARAMS10 = "{\"credType\":1,\"keyFormat\":4,\"algorithmType\":3,\"subject\":1,\"issuer\":1," "\"proofType\":1,\"method\":1,\"authorizedScope\":1,\"userId\":\"TestUserId\"," "\"deviceId\":\"TestDeviceId\"," - "\"authorizedAccoutList\":[\"TestName1\",\"TestName2\",\"TestName3\"]," + "\"authorizedAppList\":[\"TestName1\",\"TestName2\",\"TestName3\"]," "\"peerUserSpaceId\":100,\"extendInfo\":\"\"}"; static const char *ADD_PARAMS11 = "{\"credType\":1,\"keyFormat\":4,\"algorithmType\":3,\"subject\":1,\"issuer\":1," "\"proofType\":1,\"method\":1,\"authorizedScope\":1," "\"deviceId\":\"TestDeviceId\",\"credOwner\":\"TestAppId\"," - "\"authorizedAccoutList\":[\"TestName1\",\"TestName2\",\"TestName3\"]," + "\"authorizedAppList\":[\"TestName1\",\"TestName2\",\"TestName3\"]," "\"peerUserSpaceId\":100,\"extendInfo\":\"\"}"; static const char *ADD_PARAMS12 = "{\"credType\":1,\"keyFormat\":4,\"algorithmType\":3,\"subject\":1,\"issuer\":1," "\"proofType\":1,\"method\":2,\"authorizedScope\":1,\"userId\":\"TestUserId\"," "\"deviceId\":\"TestDeviceId\",\"credOwner\":\"TestAppId\"," - "\"authorizedAccoutList\":[\"TestName1\",\"TestName2\",\"TestName3\"]," + "\"authorizedAppList\":[\"TestName1\",\"TestName2\",\"TestName3\"]," "\"peerUserSpaceId\":100,\"extendInfo\":\"\"}"; static const char *ADD_PARAMS13 = "{\"credType\":2,\"keyFormat\":4,\"algorithmType\":3,\"subject\":1,\"issuer\":1," "\"proofType\":1,\"method\":2,\"authorizedScope\":1,\"userId\":\"TestUserId\"," "\"keyValue\":\"9A9A9A9A\",\"deviceId\":\"TestDeviceId\",\"credOwner\":\"TestAppId\"," - "\"authorizedAccoutList\":[\"TestName1\",\"TestName2\",\"TestName3\"]," + "\"authorizedAppList\":[\"TestName1\",\"TestName2\",\"TestName3\"]," "\"peerUserSpaceId\":100,\"extendInfo\":\"\"}"; static const char *ADD_PARAMS14 = "{\"credType\":1,\"keyFormat\":4,\"algorithmType\":3,\"subject\":1,\"issuer\":1," "\"proofType\":1,\"method\":1,\"authorizedScope\":1,\"userId\":\"TestUserId\"," "\"deviceId\":\"TestDeviceId\",\"credOwner\":\"TestAppId1\"," - "\"authorizedAccoutList\":[\"TestName1\",\"TestName2\",\"TestName3\"]," + "\"authorizedAppList\":[\"TestName1\",\"TestName2\",\"TestName3\"]," "\"peerUserSpaceId\":100,\"extendInfo\":\"\"}"; static const char *ADD_PARAMS15 = "{\"credType\":1,\"keyFormat\":4,\"algorithmType\":3,\"subject\":1,\"issuer\":1," "\"proofType\":1,\"method\":1,\"authorizedScope\":1,\"userId\":\"TestUserId\"," "\"keyValue\":\"TestKeyValue\",\"deviceId\":\"TestDeviceId\",\"credOwner\":\"TestAppId\"," - "\"authorizedAccoutList\":[\"TestName1\",\"TestName2\",\"TestName3\"]," + "\"authorizedAppList\":[\"TestName1\",\"TestName2\",\"TestName3\"]," "\"peerUserSpaceId\":100,\"extendInfo\":\"\"}"; +static const char *ADD_PARAMS16 = + "{\"credId\":\"14993DDA9D\",\"credType\":1,\"keyFormat\":4,\"algorithmType\":3,\"subject\":1,\"issuer\":1," + "\"proofType\":1,\"method\":1,\"authorizedScope\":1,\"userId\":\"TestUserId\"," + "\"deviceId\":\"TestDeviceId\",\"credOwner\":\"TestAppId\"," + "\"peerUserSpaceId\":\"100\",\"extendInfo\":\"\"}"; +static const char *ADD_PARAMS17 = + "{\"credType\":2,\"keyFormat\":4,\"algorithmType\":3,\"subject\":1," + "\"proofType\":1,\"method\":1,\"authorizedScope\":1," + "\"deviceId\":\"TestDeviceId\",\"credOwner\":\"TestAppId\"}"; +static const char *ADD_PARAMS18 = + "{\"credType\":3,\"keyFormat\":4,\"algorithmType\":3,\"subject\":1,\"issuer\":1," + "\"proofType\":1,\"method\":1,\"authorizedScope\":1,\"userId\":\"TestUserId0\"," + "\"deviceId\":\"TestDeviceId0\",\"credOwner\":\"TestAppId\"}"; static const char *REQUEST_PARAMS = - "{\"authorizedScope\":1, \"authorizedAccoutList\":[\"TestName1\",\"TestName2\",\"TestName3\"," + "{\"authorizedScope\":1, \"authorizedAppList\":[\"TestName1\",\"TestName2\",\"TestName3\"," "\"TestName4\"],\"extendInfo\":\"\"}"; +static const char *AGREE_PARAMS = + "{\"credType\":2, \"deviceId\":\"TestDeviceId\",\"credOwner\":\"TestAppId\",\"subject\":1," + "\"keyFormat\":2,\"proofType\":1,\"authorizedScope\":1,\"algorithmType\":3,\"peerUserSpaceId\":\"100\"," + "\"keyValue\":\"3059301306072a8648ce3d020106082a8648ce3d030107034200043bb1f8107c6306bddcdb70cd9fee0e581" + "5bbd305184871cd2880657eb2cc88aeece1a7f076d9fff7e1114e3bc9dfa45b061b2755b46fc282ef59763b4c0288bd\"}"; +static const char *BATCH_UPDATE_PARAMS = + "{\"baseInfo\":{\"credType\":3,\"keyFormat\":2,\"algorithmType\":3,\"subject\":2,\"authorizedScope\":2," + "\"issuer\":1,\"proofType\":2,\"credOwner\":\"TestAppId\"}," + "\"updateLists\":[{\"userId\":\"TestUserId\",\"deviceId\":\"TestDeviceId\"}]}"; +static const char *BATCH_UPDATE_PARAMS1 = + "{\"baseInfo\":{\"credType\":1,\"keyFormat\":2,\"algorithmType\":3,\"subject\":2,\"authorizedScope\":2," + "\"issuer\":1,\"proofType\":2,\"credOwner\":\"TestAppId\"}," + "\"updateLists\":[{\"userId\":\"TestUserId\",\"deviceId\":\"TestDeviceId\"}]}"; + static const char *QUERY_PARAMS = "{\"deviceId\":\"TestDeviceId\"}"; static const char *QUERY_PARAMS1 = "{\"deviceId\":\"TestDeviceId1\"}"; +static const char *DEL_PARAMS = "{\"credOwner\":\"TestAppId\"}"; +static const char *DEL_PARAMS1 = "{\"credOwner\":\"TestAppId\",\"userIdHash\":\"12D2\",\"deviceIdHash\":\"12D2\"}"; enum CredListenerStatus { CRED_LISTENER_INIT = 0, CRED_LISTENER_ON_ADD = 1, @@ -414,6 +444,18 @@ HWTEST_F(CredMgrAddCredentialTest, CredMgrAddCredentialTest017, TestSize.Level0) EXPECT_EQ(ret, IS_ERR_KEYVALUE_METHOD_CONFLICT); } +HWTEST_F(CredMgrAddCredentialTest, CredMgrAddCredentialTest018, TestSize.Level0) +{ + const CredManager *cm = GetCredMgrInstance(); + ASSERT_NE(cm, nullptr); + char *credId = nullptr; + int32_t ret = cm->addCredential(DEFAULT_OS_ACCOUNT, ADD_PARAMS16, &credId); + EXPECT_EQ(ret, IS_SUCCESS); + ret = cm->deleteCredential(DEFAULT_OS_ACCOUNT, credId); + HcFree(credId); + EXPECT_EQ(ret, IS_SUCCESS); +} + class CredMgrExportCredentialTest : public testing::Test { public: static void SetUpTestCase(); @@ -888,6 +930,214 @@ HWTEST_F(CredMgrUnRegCredListenerTest, CredMgrUnRegCredListenerTest003, TestSize EXPECT_EQ(ret, IS_ERR_INVALID_PARAMS); } +class CredMgrAgreeCredentialTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); +}; + + +void CredMgrAgreeCredentialTest::SetUpTestCase() {} +void CredMgrAgreeCredentialTest::TearDownTestCase() {} + +void CredMgrAgreeCredentialTest::SetUp() +{ + DeleteDatabase(); + int ret = InitDeviceAuthService(); + EXPECT_EQ(ret, IS_SUCCESS); +} + +void CredMgrAgreeCredentialTest::TearDown() +{ + DestroyDeviceAuthService(); +} + +HWTEST_F(CredMgrAgreeCredentialTest, CredMgrAgreeCredentialTest001, TestSize.Level0) +{ + const CredManager *cm = GetCredMgrInstance(); + ASSERT_NE(cm, nullptr); + char *selfCredId = nullptr; + int32_t ret = cm->addCredential(DEFAULT_OS_ACCOUNT, ADD_PARAMS17, &selfCredId); + EXPECT_EQ(ret, IS_SUCCESS); + char *returnData = nullptr; + ret = cm->agreeCredential(DEFAULT_OS_ACCOUNT, selfCredId, AGREE_PARAMS, &returnData); + HcFree(selfCredId); + HcFree(returnData); + EXPECT_EQ(ret, IS_SUCCESS); +} + +HWTEST_F(CredMgrAgreeCredentialTest, CredMgrAgreeCredentialTest002, TestSize.Level0) +{ + const CredManager *cm = GetCredMgrInstance(); + ASSERT_NE(cm, nullptr); + char *returnData = nullptr; + int32_t ret = cm->agreeCredential(DEFAULT_OS_ACCOUNT, nullptr, AGREE_PARAMS, &returnData); + EXPECT_EQ(ret, IS_ERR_INVALID_PARAMS); +} + +HWTEST_F(CredMgrAgreeCredentialTest, CredMgrAgreeCredentialTest003, TestSize.Level0) +{ + const CredManager *cm = GetCredMgrInstance(); + ASSERT_NE(cm, nullptr); + char *returnData = nullptr; + int32_t ret = cm->agreeCredential(DEFAULT_OS_ACCOUNT, TEST_CRED_ID, nullptr, &returnData); + EXPECT_EQ(ret, IS_ERR_INVALID_PARAMS); +} + +HWTEST_F(CredMgrAgreeCredentialTest, CredMgrAgreeCredentialTest004, TestSize.Level0) +{ + const CredManager *cm = GetCredMgrInstance(); + ASSERT_NE(cm, nullptr); + int32_t ret = cm->agreeCredential(DEFAULT_OS_ACCOUNT, TEST_CRED_ID, AGREE_PARAMS, nullptr); + EXPECT_EQ(ret, IS_ERR_INVALID_PARAMS); +} + + +class CredMgrBatchUpdateCredsTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); +}; + +void CredMgrBatchUpdateCredsTest::SetUpTestCase() {} +void CredMgrBatchUpdateCredsTest::TearDownTestCase() {} + +void CredMgrBatchUpdateCredsTest::SetUp() +{ + DeleteDatabase(); + int ret = InitDeviceAuthService(); + EXPECT_EQ(ret, IS_SUCCESS); +} + +void CredMgrBatchUpdateCredsTest::TearDown() +{ + DestroyDeviceAuthService(); +} + +HWTEST_F(CredMgrBatchUpdateCredsTest, CredMgrBatchUpdateCredsTest001, TestSize.Level0) +{ + const CredManager *cm = GetCredMgrInstance(); + ASSERT_NE(cm, nullptr); + char *returnData = nullptr; + int32_t ret = cm->batchUpdateCredentials(DEFAULT_OS_ACCOUNT, BATCH_UPDATE_PARAMS, &returnData); + HcFree(returnData); + EXPECT_EQ(ret, IS_SUCCESS); +} + +HWTEST_F(CredMgrBatchUpdateCredsTest, CredMgrBatchUpdateCredsTest002, TestSize.Level0) +{ + const CredManager *cm = GetCredMgrInstance(); + ASSERT_NE(cm, nullptr); + char *returnData = nullptr; + int32_t ret = cm->batchUpdateCredentials(DEFAULT_OS_ACCOUNT, nullptr, &returnData); + EXPECT_EQ(ret, IS_ERR_INVALID_PARAMS); +} + +HWTEST_F(CredMgrBatchUpdateCredsTest, CredMgrBatchUpdateCredsTest003, TestSize.Level0) +{ + const CredManager *cm = GetCredMgrInstance(); + ASSERT_NE(cm, nullptr); + char *returnData = nullptr; + int32_t ret = cm->batchUpdateCredentials(DEFAULT_OS_ACCOUNT, BATCH_UPDATE_PARAMS1, &returnData); + EXPECT_EQ(ret, IS_ERR_NOT_SUPPORT); +} + +HWTEST_F(CredMgrBatchUpdateCredsTest, CredMgrBatchUpdateCredsTest004, TestSize.Level0) +{ + const CredManager *cm = GetCredMgrInstance(); + ASSERT_NE(cm, nullptr); + int32_t ret = cm->batchUpdateCredentials(DEFAULT_OS_ACCOUNT, BATCH_UPDATE_PARAMS, nullptr); + EXPECT_EQ(ret, IS_ERR_INVALID_PARAMS); +} + +HWTEST_F(CredMgrBatchUpdateCredsTest, CredMgrBatchUpdateCredsTest005, TestSize.Level0) +{ + const CredManager *cm = GetCredMgrInstance(); + ASSERT_NE(cm, nullptr); + char *credId = nullptr; + int32_t ret = cm->addCredential(DEFAULT_OS_ACCOUNT, ADD_PARAMS18, &credId); + HcFree(credId); + EXPECT_EQ(ret, IS_SUCCESS); + char *returnData = nullptr; + ret = cm->batchUpdateCredentials(DEFAULT_OS_ACCOUNT, BATCH_UPDATE_PARAMS, &returnData); + HcFree(returnData); + EXPECT_EQ(ret, IS_SUCCESS); +} + +class CredMgrDelCredByParamsTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); +}; + +void CredMgrDelCredByParamsTest::SetUpTestCase() {} +void CredMgrDelCredByParamsTest::TearDownTestCase() {} + +void CredMgrDelCredByParamsTest::SetUp() +{ + DeleteDatabase(); + int ret = InitDeviceAuthService(); + EXPECT_EQ(ret, IS_SUCCESS); +} + +void CredMgrDelCredByParamsTest::TearDown() +{ + DestroyDeviceAuthService(); +} + +HWTEST_F(CredMgrDelCredByParamsTest, CredMgrDelCredByParamsTest001, TestSize.Level0) +{ + const CredManager *cm = GetCredMgrInstance(); + ASSERT_NE(cm, nullptr); + char *credId = nullptr; + int32_t ret = cm->addCredential(DEFAULT_OS_ACCOUNT, ADD_PARAMS, &credId); + HcFree(credId); + EXPECT_EQ(ret, IS_SUCCESS); + char *returnData = nullptr; + ret = cm->deleteCredByParams(DEFAULT_OS_ACCOUNT, DEL_PARAMS, &returnData); + HcFree(returnData); + EXPECT_EQ(ret, IS_SUCCESS); +} + +HWTEST_F(CredMgrDelCredByParamsTest, CredMgrDelCredByParamsTest002, TestSize.Level0) +{ + const CredManager *cm = GetCredMgrInstance(); + ASSERT_NE(cm, nullptr); + char *returnData = nullptr; + int32_t ret = cm->deleteCredByParams(DEFAULT_OS_ACCOUNT, nullptr, &returnData); + EXPECT_EQ(ret, IS_ERR_INVALID_PARAMS); +} + +HWTEST_F(CredMgrDelCredByParamsTest, CredMgrDelCredByParamsTest003, TestSize.Level0) +{ + const CredManager *cm = GetCredMgrInstance(); + ASSERT_NE(cm, nullptr); + int32_t ret = cm->deleteCredByParams(DEFAULT_OS_ACCOUNT, DEL_PARAMS, nullptr); + EXPECT_EQ(ret, IS_ERR_INVALID_PARAMS); +} + +HWTEST_F(CredMgrDelCredByParamsTest, CredMgrDelCredByParamsTest004, TestSize.Level0) +{ + const CredManager *cm = GetCredMgrInstance(); + ASSERT_NE(cm, nullptr); + char *credId = nullptr; + int32_t ret = cm->addCredential(DEFAULT_OS_ACCOUNT, ADD_PARAMS, &credId); + HcFree(credId); + EXPECT_EQ(ret, IS_SUCCESS); + char *returnData = nullptr; + ret = cm->deleteCredByParams(DEFAULT_OS_ACCOUNT, DEL_PARAMS1, &returnData); + HcFree(returnData); + EXPECT_EQ(ret, IS_SUCCESS); +} + +} + class CredListenerTest : public testing::Test { public: static void SetUpTestCase(); @@ -970,7 +1220,7 @@ HWTEST_F(IdentityOperationTest, IdentityOperationTest002, TestSize.Level0) HWTEST_F(IdentityOperationTest, IdentityOperationTest003, TestSize.Level0) { Credential *credetial = CreateCredential(); - int32_t ret = SetAccListFromArray(credetial, nullptr); + int32_t ret = SetVectorFromList(&credetial->authorizedAppList, nullptr); DestroyCredential(credetial); EXPECT_EQ(ret, IS_SUCCESS); } @@ -1007,6 +1257,8 @@ HWTEST_F(IdentityOperationTest, IdentityOperationTest006, TestSize.Level0) EXPECT_EQ(ret, IS_SUCCESS); ret = SetKeyFormat(credetial, json, METHOD_IMPORT); EXPECT_NE(ret, IS_SUCCESS); + DestroyCredential(credetial); + FreeJson(json); } HWTEST_F(IdentityOperationTest, IdentityOperationTest007, TestSize.Level0) @@ -1014,4 +1266,112 @@ HWTEST_F(IdentityOperationTest, IdentityOperationTest007, TestSize.Level0) int32_t ret = SetAuthorizedScope(nullptr, nullptr); EXPECT_NE(ret, IS_SUCCESS); } -} \ No newline at end of file + +HWTEST_F(IdentityOperationTest, IdentityOperationTest008, TestSize.Level0) +{ + int32_t ret = GetCredentialById(DEFAULT_OS_ACCOUNT_ID, nullptr, nullptr); + EXPECT_NE(ret, IS_SUCCESS); +} + +HWTEST_F(IdentityOperationTest, IdentityOperationTest009, TestSize.Level0) +{ + int32_t ret = CombineBaseCredId(nullptr, nullptr, nullptr); + EXPECT_NE(ret, IS_SUCCESS); +} + +HWTEST_F(IdentityOperationTest, IdentityOperationTest010, TestSize.Level0) +{ + int32_t ret = Sha256BaseCredId(nullptr, nullptr, nullptr); + EXPECT_NE(ret, IS_SUCCESS); +} + +class IdentityServiceImplTest : public testing::Test { + public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); + }; + + void IdentityServiceImplTest::SetUpTestCase() {} + void IdentityServiceImplTest::TearDownTestCase() {} + + void IdentityServiceImplTest::SetUp() + { + DeleteDatabase(); + int ret = InitDeviceAuthService(); + EXPECT_EQ(ret, IS_SUCCESS); + } + + void IdentityServiceImplTest::TearDown() + { + DestroyDeviceAuthService(); + } + + HWTEST_F(IdentityServiceImplTest, IdentityServiceImplTest001, TestSize.Level0) + { + int32_t ret = AddCredentialImpl(DEFAULT_OS_ACCOUNT_ID, nullptr, nullptr); + EXPECT_NE(ret, IS_SUCCESS); + } + + HWTEST_F(IdentityServiceImplTest, IdentityServiceImplTest002, TestSize.Level0) + { + int32_t ret = ExportCredentialImpl(DEFAULT_OS_ACCOUNT_ID, nullptr, nullptr); + EXPECT_NE(ret, IS_SUCCESS); + } + + HWTEST_F(IdentityServiceImplTest, IdentityServiceImplTest003, TestSize.Level0) + { + int32_t ret = QueryCredentialByParamsImpl(DEFAULT_OS_ACCOUNT_ID, nullptr, nullptr); + EXPECT_NE(ret, IS_SUCCESS); + } + + HWTEST_F(IdentityServiceImplTest, IdentityServiceImplTest004, TestSize.Level0) + { + int32_t ret = QueryCredInfoByCredIdImpl(DEFAULT_OS_ACCOUNT_ID, nullptr, nullptr); + EXPECT_NE(ret, IS_SUCCESS); + } + + HWTEST_F(IdentityServiceImplTest, IdentityServiceImplTest005, TestSize.Level0) + { + int32_t ret = DeleteCredentialImpl(DEFAULT_OS_ACCOUNT_ID, nullptr); + EXPECT_NE(ret, IS_SUCCESS); + } + + HWTEST_F(IdentityServiceImplTest, IdentityServiceImplTest006, TestSize.Level0) + { + int32_t ret = DeleteCredByParamsImpl(DEFAULT_OS_ACCOUNT_ID, nullptr, nullptr); + EXPECT_NE(ret, IS_SUCCESS); + } + + HWTEST_F(IdentityServiceImplTest, IdentityServiceImplTest007, TestSize.Level0) + { + int32_t ret = UpdateCredInfoImpl(DEFAULT_OS_ACCOUNT_ID, nullptr, nullptr); + EXPECT_NE(ret, IS_SUCCESS); + } + + HWTEST_F(IdentityServiceImplTest, IdentityServiceImplTest008, TestSize.Level0) + { + QueryCredentialParams queryParam; + int32_t ret = AddUpdateCred(DEFAULT_OS_ACCOUNT_ID, nullptr, &queryParam); + EXPECT_NE(ret, IS_SUCCESS); + } + + HWTEST_F(IdentityServiceImplTest, IdentityServiceImplTest009, TestSize.Level0) + { + QueryCredentialParams queryParam; + int32_t ret = ProcessAbnormalCreds(DEFAULT_OS_ACCOUNT_ID, nullptr, &queryParam); + EXPECT_NE(ret, IS_SUCCESS); + } + + HWTEST_F(IdentityServiceImplTest, IdentityServiceImplTest010, TestSize.Level0) + { + int32_t ret = BatchUpdateCredsImpl(DEFAULT_OS_ACCOUNT_ID, nullptr, nullptr); + EXPECT_NE(ret, IS_SUCCESS); + } + + HWTEST_F(IdentityServiceImplTest, IdentityServiceImplTest011, TestSize.Level0) + { + int32_t ret = AgreeCredentialImpl(DEFAULT_OS_ACCOUNT_ID, nullptr, nullptr, nullptr); + EXPECT_NE(ret, IS_SUCCESS); + } 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 f0cec967..c8dd280f 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 @@ -26,6 +26,7 @@ ohos_unittest("creds_manager_test") { ] sources = deviceauth_files + sources += identity_service_mock_files sources += [ "creds_manager_test.cpp" ] sources += hal_common_files sources += hiview_adapter_files 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 bac82fa3..cc7f4c28 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 @@ -30,6 +30,7 @@ if (support_os_account) { include_dirs += [ "${dev_frameworks_path}/inc/net_observer" ] sources = deviceauth_files + sources += identity_service_mock_files sources += hal_common_files sources += hiview_adapter_files sources -= soft_bus_channel_files 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 ef56ae21..2a907f41 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 @@ -36,6 +36,7 @@ ohos_unittest("expand_sub_session_test") { "${services_path}/ext_plugin_manager/inc", "${protocol_path}/inc", ] + include_dirs += identity_service_inc include_dirs += [ "${tdd_framework_path}/tdd_helper/exception_controller/inc", 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 00da31c5..b111e6c5 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 @@ -35,6 +35,7 @@ ohos_unittest("auth_code_import_test") { sources += [ "auth_code_import_test.cpp" ] include_dirs += identity_manager_inc + include_dirs += identity_service_inc include_dirs += [ "${dev_frameworks_path}/inc", "${group_manager_path}/inc", @@ -144,6 +145,7 @@ ohos_unittest("pub_key_exchange_test") { "${mk_agree_path}/src/mock/key_manager_mock.c", "${privacy_enhancement_path}/src/mock/pseudonym_manager_mock.c", ] + include_dirs += identity_service_inc include_dirs += identity_manager_inc include_dirs += [ "${dev_frameworks_path}/inc", @@ -196,6 +198,7 @@ ohos_unittest("save_trusted_info_test") { "${mk_agree_path}/inc", "${privacy_enhancement_path}/inc", ] + include_dirs += identity_service_inc include_dirs += [ "${tdd_framework_path}/tdd_helper/exception_controller/inc", -- Gitee