支持应用级绑定

Signed-off-by: yanglijun294 <yanglijun@huawei.com>
This commit is contained in:
yanglijun294
2023-12-01 10:34:26 +08:00
parent d4ca3432a5
commit cd49bd12a2
186 changed files with 8455 additions and 4598 deletions
+7
View File
@@ -24,6 +24,9 @@ extern "C" {
#define IPC_CALL_BACK_STUB_AUTH_ID 0
#define IPC_CALL_BACK_STUB_BIND_ID 1
#define IPC_CALL_BACK_STUB_DIRECT_AUTH_ID 2
#define IPC_CALL_CONTEXT_INIT 0x0
/* params type for ipc call */
#define PARAM_TYPE_APPID 1
@@ -91,6 +94,10 @@ enum {
IPC_CALL_GA_CANCEL_REQUEST,
IPC_CALL_ID_GET_REAL_INFO,
IPC_CALL_ID_GET_PSEUDONYM_ID,
IPC_CALL_ID_PROCESS_CREDENTIAL,
IPC_CALL_ID_DA_PROC_DATA,
IPC_CALL_ID_DA_AUTH_DEVICE,
IPC_CALL_ID_DA_CANCEL_REQUEST,
};
#ifdef __cplusplus
+199
View File
@@ -1765,6 +1765,205 @@ static void InitIpcGaMethods(GroupAuthManager *gaMethodObj)
return;
}
DEVICE_AUTH_API_PUBLIC int32_t ProcessCredential(int32_t operationCode, const char *reqJsonStr, char **returnData)
{
uintptr_t callCtx = IPC_CALL_CONTEXT_INIT;
int32_t ret;
IpcDataInfo replyCache = { 0 };
LOGI("starting ...");
if (IsStrInvalid(reqJsonStr) || (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 = SetCallRequestParamInfo(
callCtx, PARAM_TYPE_OPCODE, (const uint8_t *)&operationCode, sizeof(operationCode));
if (ret != HC_SUCCESS) {
LOGE("set request param failed, ret %d, param id %d", ret, PARAM_TYPE_OPCODE);
DestroyCallCtx(&callCtx, NULL);
return HC_ERR_IPC_BUILD_PARAM;
}
ret =
SetCallRequestParamInfo(callCtx, PARAM_TYPE_REQ_JSON, (const uint8_t *)reqJsonStr, strlen(reqJsonStr) + 1);
if (ret != HC_SUCCESS) {
LOGE("set request param failed, ret %d, param id %d", ret, PARAM_TYPE_REQ_JSON);
DestroyCallCtx(&callCtx, NULL);
return HC_ERR_IPC_BUILD_PARAM;
}
ret = DoBinderCall(callCtx, IPC_CALL_ID_PROCESS_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 = GetIpcReplyByTypeInner(&replyCache, REPLAY_CACHE_NUM(replyCache), returnData);
if (ret != HC_SUCCESS) {
LOGE("GetIpcReplyByType failed, ret %d", ret);
}
DestroyCallCtx(&callCtx, NULL);
return ret;
}
DEVICE_AUTH_API_PUBLIC int32_t ProcessAuthDevice(
int64_t requestId, const char *authParams, const DeviceAuthCallback *callback)
{
uintptr_t callCtx = IPC_CALL_CONTEXT_INIT;
int32_t ret;
int32_t inOutLen;
IpcDataInfo replyCache = { 0 };
LOGI("starting ...");
if (IsStrInvalid(authParams) || (callback == NULL)) {
LOGE("invalid params");
return HC_ERR_INVALID_PARAMS;
}
ret = CreateCallCtx(&callCtx, NULL);
if (ret != HC_SUCCESS) {
LOGE("CreateCallCtx failed, ret %d", ret);
return HC_ERR_IPC_INIT;
}
ret = SetCallRequestParamInfo(callCtx, PARAM_TYPE_REQID, (const uint8_t *)(&requestId), sizeof(requestId));
if (ret != HC_SUCCESS) {
LOGE("set request param failed, ret %d, type %d", ret, PARAM_TYPE_REQID);
DestroyCallCtx(&callCtx, NULL);
return HC_ERR_IPC_BUILD_PARAM;
}
ret = SetCallRequestParamInfo(
callCtx, PARAM_TYPE_AUTH_PARAMS, (const uint8_t *)authParams, strlen(authParams) + 1);
if (ret != HC_SUCCESS) {
LOGE("set request param failed, ret %d, type %d", ret, PARAM_TYPE_AUTH_PARAMS);
DestroyCallCtx(&callCtx, NULL);
return HC_ERR_IPC_BUILD_PARAM;
}
ret = SetCallRequestParamInfo(callCtx, PARAM_TYPE_DEV_AUTH_CB, (const uint8_t *)callback, sizeof(*callback));
if (ret != HC_SUCCESS) {
LOGE("set request param failed, ret %d, type %d", ret, PARAM_TYPE_DEV_AUTH_CB);
DestroyCallCtx(&callCtx, NULL);
return HC_ERR_IPC_BUILD_PARAM;
}
SetCbCtxToDataCtx(callCtx, IPC_CALL_BACK_STUB_DIRECT_AUTH_ID);
ret = DoBinderCall(callCtx, IPC_CALL_ID_DA_PROC_DATA, true);
if (ret == HC_ERR_IPC_INTERNAL_FAILED) {
LOGE("ipc call failed");
DestroyCallCtx(&callCtx, NULL);
return HC_ERR_IPC_PROC_FAILED;
}
DecodeCallReply(callCtx, &replyCache, REPLAY_CACHE_NUM(replyCache));
ret = HC_ERR_IPC_UNKNOW_REPLY;
inOutLen = sizeof(int32_t);
GetIpcReplyByType(
&replyCache, REPLAY_CACHE_NUM(replyCache), PARAM_TYPE_IPC_RESULT, (uint8_t *)&ret, &inOutLen);
LOGI("process done, ret %d", ret);
DestroyCallCtx(&callCtx, NULL);
return ret;
}
DEVICE_AUTH_API_PUBLIC int32_t StartAuthDevice(
int64_t authReqId, const char *authParams, const DeviceAuthCallback *callback)
{
uintptr_t callCtx = IPC_CALL_CONTEXT_INIT;
int32_t ret;
int32_t inOutLen;
IpcDataInfo replyCache = { 0 };
LOGI("starting ...");
if (IsStrInvalid(authParams) || (callback == NULL)) {
LOGE("invalid params");
return HC_ERR_INVALID_PARAMS;
}
ret = CreateCallCtx(&callCtx, NULL);
if (ret != HC_SUCCESS) {
LOGE("CreateCallCtx failed, ret %d", ret);
return HC_ERR_IPC_INIT;
}
ret = SetCallRequestParamInfo(callCtx, PARAM_TYPE_REQID, (const uint8_t *)(&authReqId), sizeof(authReqId));
if (ret != HC_SUCCESS) {
LOGE("set request param failed, ret %d, type %d", ret, PARAM_TYPE_REQID);
DestroyCallCtx(&callCtx, NULL);
return HC_ERR_IPC_BUILD_PARAM;
}
ret = SetCallRequestParamInfo(
callCtx, PARAM_TYPE_AUTH_PARAMS, (const uint8_t *)authParams, strlen(authParams) + 1);
if (ret != HC_SUCCESS) {
LOGE("set request param failed, ret %d, type %d", ret, PARAM_TYPE_AUTH_PARAMS);
DestroyCallCtx(&callCtx, NULL);
return HC_ERR_IPC_BUILD_PARAM;
}
ret = SetCallRequestParamInfo(callCtx, PARAM_TYPE_DEV_AUTH_CB, (const uint8_t *)callback, sizeof(*callback));
if (ret != HC_SUCCESS) {
LOGE("set request param failed, ret %d, type %d", ret, PARAM_TYPE_DEV_AUTH_CB);
DestroyCallCtx(&callCtx, NULL);
return HC_ERR_IPC_BUILD_PARAM;
}
SetCbCtxToDataCtx(callCtx, IPC_CALL_BACK_STUB_DIRECT_AUTH_ID);
ret = DoBinderCall(callCtx, IPC_CALL_ID_DA_AUTH_DEVICE, true);
if (ret == HC_ERR_IPC_INTERNAL_FAILED) {
LOGE("ipc call failed");
DestroyCallCtx(&callCtx, NULL);
return HC_ERR_IPC_PROC_FAILED;
}
DecodeCallReply(callCtx, &replyCache, REPLAY_CACHE_NUM(replyCache));
ret = HC_ERR_IPC_UNKNOW_REPLY;
inOutLen = sizeof(int32_t);
GetIpcReplyByType(
&replyCache, REPLAY_CACHE_NUM(replyCache), PARAM_TYPE_IPC_RESULT, (uint8_t *)&ret, &inOutLen);
LOGI("process done, ret %d", ret);
DestroyCallCtx(&callCtx, NULL);
return ret;
}
DEVICE_AUTH_API_PUBLIC int32_t CancelAuthRequest(int64_t requestId, const char *authParams)
{
uintptr_t callCtx = IPC_CALL_CONTEXT_INIT;
int32_t ret;
int32_t inOutLen;
IpcDataInfo replyCache = { 0 };
LOGI("starting ...");
if (IsStrInvalid(authParams)) {
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_NULL_PTR;
}
ret = SetCallRequestParamInfo(callCtx, PARAM_TYPE_REQID, (const uint8_t *)(&requestId), sizeof(requestId));
if (ret != HC_SUCCESS) {
LOGE("set request param failed, ret %d, type %d", ret, PARAM_TYPE_REQID);
DestroyCallCtx(&callCtx, NULL);
return HC_ERR_NULL_PTR;
}
ret = SetCallRequestParamInfo(
callCtx, PARAM_TYPE_AUTH_PARAMS, (const uint8_t *)authParams, strlen(authParams) + 1);
if (ret != HC_SUCCESS) {
LOGE("set request param failed, ret %d, param id %d", ret, PARAM_TYPE_AUTH_PARAMS);
DestroyCallCtx(&callCtx, NULL);
return HC_ERR_NULL_PTR;
}
ret = DoBinderCall(callCtx, IPC_CALL_ID_DA_CANCEL_REQUEST, true);
if (ret != HC_SUCCESS) {
LOGE("ipc call failed");
DestroyCallCtx(&callCtx, NULL);
return HC_ERR_IPC_PROC_FAILED;
}
DecodeCallReply(callCtx, &replyCache, REPLAY_CACHE_NUM(replyCache));
ret = HC_ERR_IPC_UNKNOW_REPLY;
inOutLen = sizeof(int32_t);
GetIpcReplyByType(
&replyCache, REPLAY_CACHE_NUM(replyCache), PARAM_TYPE_IPC_RESULT, (uint8_t *)&ret, &inOutLen);
LOGI("process done, ret %d", ret);
DestroyCallCtx(&callCtx, NULL);
return ret;
}
DEVICE_AUTH_API_PUBLIC int InitDeviceAuthService(void)
{
InitHcMutex(&g_ipcMutex);
+167
View File
@@ -1110,6 +1110,167 @@ static int32_t IpcServiceGaGetPseudonymId(const IpcDataInfo *ipcParams, int32_t
return ret;
}
static int32_t IpcServiceDaProcessCredential(const IpcDataInfo *ipcParams, int32_t paramNum, uintptr_t outCache)
{
int32_t ret;
int32_t operationCode = 0;
const char *reqJsonStr = NULL;
char *returnData = NULL;
LOGI("starting ...");
int32_t inOutLen = sizeof(int32_t);
ret = GetIpcRequestParamByType(ipcParams, paramNum, PARAM_TYPE_OPCODE, (uint8_t *)&operationCode, &inOutLen);
if ((inOutLen != sizeof(int32_t)) || (ret != HC_SUCCESS)) {
LOGE("get param error, type %d", PARAM_TYPE_OPCODE);
return HC_ERR_IPC_BAD_PARAM;
}
ret = GetIpcRequestParamByType(ipcParams, paramNum, PARAM_TYPE_REQ_JSON, (uint8_t *)&reqJsonStr, NULL);
if ((reqJsonStr == NULL) || (ret != HC_SUCCESS)) {
LOGE("get param error, type %d", PARAM_TYPE_REQ_JSON);
return HC_ERR_IPC_BAD_PARAM;
}
ret = ProcessCredential(operationCode, reqJsonStr, &returnData);
if (ret != HC_SUCCESS) {
LOGI("call ProcessCredential failed %d", ret);
}
if (returnData != NULL) {
ret = IpcEncodeCallReplay(
outCache, PARAM_TYPE_RETURN_DATA, (const uint8_t *)returnData, strlen(returnData) + 1);
HcFree(returnData);
} else {
ret = IpcEncodeCallReplay(outCache, PARAM_TYPE_RETURN_DATA, NULL, 0);
}
LOGI("process done, ipc ret %d", ret);
return ret;
}
static int32_t IpcServiceDaProcessData(const IpcDataInfo *ipcParams, int32_t paramNum, uintptr_t outCache)
{
int32_t callRet;
int32_t ret;
const DeviceAuthCallback *callback = NULL;
int64_t authReqId = 0;
const char *authParams = NULL;
int32_t inOutLen;
int32_t cbObjIdx = -1;
LOGI("starting ...");
inOutLen = sizeof(authReqId);
ret = GetIpcRequestParamByType(ipcParams, paramNum, PARAM_TYPE_REQID, (uint8_t *)&authReqId, &inOutLen);
if ((inOutLen != sizeof(authReqId)) || (ret != HC_SUCCESS)) {
LOGE("get param error, type %d", PARAM_TYPE_REQID);
return HC_ERR_IPC_BAD_PARAM;
}
ret = GetIpcRequestParamByType(ipcParams, paramNum, PARAM_TYPE_AUTH_PARAMS, (uint8_t *)&authParams, NULL);
if ((authParams == NULL) || (ret != HC_SUCCESS)) {
LOGE("get param error, type %d", PARAM_TYPE_AUTH_PARAMS);
return HC_ERR_IPC_BAD_PARAM;
}
ret = GetIpcRequestParamByType(ipcParams, paramNum, PARAM_TYPE_DEV_AUTH_CB, (uint8_t *)&callback, NULL);
if (ret != HC_SUCCESS) {
LOGE("get param error, type %d", PARAM_TYPE_DEV_AUTH_CB);
return ret;
}
ret = AddIpcCallBackByReqId(
authReqId, (const uint8_t *)callback, sizeof(DeviceAuthCallback), CB_TYPE_TMP_DEV_AUTH);
if (ret != HC_SUCCESS) {
LOGE("add ipc callback failed");
return HC_ERROR;
}
inOutLen = sizeof(cbObjIdx);
ret = GetIpcRequestParamByType(ipcParams, paramNum, PARAM_TYPE_CB_OBJECT, (uint8_t *)&cbObjIdx, &inOutLen);
if (ret != HC_SUCCESS) {
LOGE("get param error, type %d", PARAM_TYPE_CB_OBJECT);
DelIpcCallBackByReqId(authReqId, CB_TYPE_TMP_DEV_AUTH, true);
return ret;
}
AddIpcCbObjByReqId(authReqId, cbObjIdx, CB_TYPE_TMP_DEV_AUTH);
InitDeviceAuthCbCtx(&g_authCbAdt, CB_TYPE_TMP_DEV_AUTH);
callRet = ProcessAuthDevice(authReqId, authParams, &g_authCbAdt);
if (callRet != HC_SUCCESS) {
DelIpcCallBackByReqId(authReqId, CB_TYPE_TMP_DEV_AUTH, true);
}
ret = IpcEncodeCallReplay(outCache, PARAM_TYPE_IPC_RESULT, (const uint8_t *)&callRet, sizeof(int32_t));
LOGI("process done, call ret %d, ipc ret %d", callRet, ret);
return ret;
}
static int32_t IpcServiceDaAuthDevice(const IpcDataInfo *ipcParams, int32_t paramNum, uintptr_t outCache)
{
int32_t callRet;
int32_t ret;
DeviceAuthCallback *callback = NULL;
int64_t authReqId = 0;
const char *authParams = NULL;
int32_t inOutLen;
int32_t cbObjIdx = -1;
LOGI("starting ...");
inOutLen = sizeof(authReqId);
ret = GetIpcRequestParamByType(ipcParams, paramNum, PARAM_TYPE_REQID, (uint8_t *)&authReqId, &inOutLen);
if ((inOutLen != sizeof(authReqId)) || (ret != HC_SUCCESS)) {
LOGE("get param error, type %d", PARAM_TYPE_REQID);
return HC_ERR_IPC_BAD_PARAM;
}
ret = GetIpcRequestParamByType(ipcParams, paramNum, PARAM_TYPE_AUTH_PARAMS, (uint8_t *)&authParams, NULL);
if ((authParams == NULL) || (ret != HC_SUCCESS)) {
LOGE("get param error, type %d", PARAM_TYPE_AUTH_PARAMS);
return HC_ERR_IPC_BAD_PARAM;
}
ret = GetIpcRequestParamByType(ipcParams, paramNum, PARAM_TYPE_DEV_AUTH_CB, (uint8_t *)&callback, NULL);
if (ret != HC_SUCCESS) {
LOGE("get param error, type %d", PARAM_TYPE_DEV_AUTH_CB);
return ret;
}
ret = AddIpcCallBackByReqId(
authReqId, (const uint8_t *)callback, sizeof(DeviceAuthCallback), CB_TYPE_TMP_DEV_AUTH);
if (ret != HC_SUCCESS) {
LOGE("add ipc callback failed");
return HC_ERROR;
}
inOutLen = sizeof(cbObjIdx);
ret = GetIpcRequestParamByType(ipcParams, paramNum, PARAM_TYPE_CB_OBJECT, (uint8_t *)&cbObjIdx, &inOutLen);
if (ret != HC_SUCCESS) {
LOGE("get param error, type %d", PARAM_TYPE_CB_OBJECT);
DelIpcCallBackByReqId(authReqId, CB_TYPE_TMP_DEV_AUTH, true);
return ret;
}
AddIpcCbObjByReqId(authReqId, cbObjIdx, CB_TYPE_TMP_DEV_AUTH);
InitDeviceAuthCbCtx(&g_authCbAdt, CB_TYPE_TMP_DEV_AUTH);
callRet = StartAuthDevice(authReqId, authParams, &g_authCbAdt);
if (callRet != HC_SUCCESS) {
DelIpcCallBackByReqId(authReqId, CB_TYPE_TMP_DEV_AUTH, true);
}
ret = IpcEncodeCallReplay(outCache, PARAM_TYPE_IPC_RESULT, (const uint8_t *)&callRet, sizeof(int32_t));
LOGI("process done, call ret %d, ipc ret %d", callRet, ret);
return ret;
}
static int32_t IpcServiceDaCancelRequest(const IpcDataInfo *ipcParams, int32_t paramNum, uintptr_t outCache)
{
int32_t ret;
int64_t requestId = 0;
const char *authParams = NULL;
LOGI("starting ...");
int32_t inOutLen = sizeof(int64_t);
ret = GetIpcRequestParamByType(ipcParams, paramNum, PARAM_TYPE_REQID, (uint8_t *)&requestId, &inOutLen);
if ((inOutLen != sizeof(requestId)) || (ret != HC_SUCCESS)) {
LOGE("get param error, type %d", PARAM_TYPE_REQID);
return HC_ERR_IPC_BAD_PARAM;
}
ret = GetIpcRequestParamByType(ipcParams, paramNum, PARAM_TYPE_AUTH_PARAMS, (uint8_t *)&authParams, NULL);
if ((authParams == NULL) || (ret != HC_SUCCESS)) {
LOGE("get param error, type %d", PARAM_TYPE_AUTH_PARAMS);
return HC_ERR_IPC_BAD_PARAM;
}
ret = CancelAuthRequest(requestId, authParams);
DelIpcCallBackByReqId(requestId, CB_TYPE_TMP_DEV_AUTH, true);
ret = IpcEncodeCallReplay(outCache, PARAM_TYPE_IPC_RESULT, (const uint8_t *)&ret, sizeof(int32_t));
LOGI("process done, ipc ret %d", ret);
return ret;
}
int32_t AddMethodMap(uintptr_t ipcInstance)
{
uint32_t ret;
@@ -1144,6 +1305,12 @@ int32_t AddMethodMap(uintptr_t ipcInstance)
ret &= SetIpcCallMap(ipcInstance, IpcServiceGaCancelRequest, IPC_CALL_GA_CANCEL_REQUEST);
ret &= SetIpcCallMap(ipcInstance, IpcServiceGaGetRealInfo, IPC_CALL_ID_GET_REAL_INFO);
ret &= SetIpcCallMap(ipcInstance, IpcServiceGaGetPseudonymId, IPC_CALL_ID_GET_PSEUDONYM_ID);
// Direct Auth Interfaces
ret &= SetIpcCallMap(ipcInstance, IpcServiceDaProcessCredential, IPC_CALL_ID_PROCESS_CREDENTIAL);
ret &= SetIpcCallMap(ipcInstance, IpcServiceDaAuthDevice, IPC_CALL_ID_DA_AUTH_DEVICE);
ret &= SetIpcCallMap(ipcInstance, IpcServiceDaProcessData, IPC_CALL_ID_DA_PROC_DATA);
ret &= SetIpcCallMap(ipcInstance, IpcServiceDaCancelRequest, IPC_CALL_ID_DA_CANCEL_REQUEST);
LOGI("process done, ret %u", ret);
return ret;
}
+7 -3
View File
@@ -33,10 +33,10 @@ using namespace OHOS;
namespace {
static const int32_t BUFF_MAX_SZ = 128;
static const int32_t IPC_CALL_BACK_MAX_NODES = 64;
static const int32_t IPC_CALL_BACK_STUB_NODES = 2;
static const int32_t IPC_CALL_BACK_STUB_NODES = 3;
}
static sptr<StubDevAuthCb> g_sdkCbStub[IPC_CALL_BACK_STUB_NODES] = { nullptr, nullptr };
static sptr<StubDevAuthCb> g_sdkCbStub[IPC_CALL_BACK_STUB_NODES] = { nullptr, nullptr, nullptr };
typedef void (*CallbackStub)(uintptr_t, const IpcDataInfo *, int32_t, MessageParcel &);
typedef struct {
@@ -1509,6 +1509,7 @@ int32_t GetIpcRequestParamByType(const IpcDataInfo *ipcParams, int32_t paramNum,
bool IsCallbackMethod(int32_t methodId)
{
if ((methodId == IPC_CALL_ID_REG_CB) || (methodId == IPC_CALL_ID_REG_LISTENER) ||
(methodId == IPC_CALL_ID_DA_AUTH_DEVICE) || (methodId == IPC_CALL_ID_DA_PROC_DATA) ||
(methodId == IPC_CALL_ID_GA_PROC_DATA) || (methodId == IPC_CALL_ID_AUTH_DEVICE)) {
return true;
}
@@ -1519,6 +1520,7 @@ void UnInitProxyAdapt(void)
{
g_sdkCbStub[IPC_CALL_BACK_STUB_AUTH_ID] = nullptr;
g_sdkCbStub[IPC_CALL_BACK_STUB_BIND_ID] = nullptr;
g_sdkCbStub[IPC_CALL_BACK_STUB_DIRECT_AUTH_ID] = nullptr;
return;
}
@@ -1526,7 +1528,9 @@ int32_t InitProxyAdapt(void)
{
g_sdkCbStub[IPC_CALL_BACK_STUB_AUTH_ID] = new(std::nothrow) StubDevAuthCb;
g_sdkCbStub[IPC_CALL_BACK_STUB_BIND_ID] = new(std::nothrow) StubDevAuthCb;
if (!g_sdkCbStub[IPC_CALL_BACK_STUB_AUTH_ID] || !g_sdkCbStub[IPC_CALL_BACK_STUB_BIND_ID]) {
g_sdkCbStub[IPC_CALL_BACK_STUB_DIRECT_AUTH_ID] = new(std::nothrow) StubDevAuthCb;
if (!g_sdkCbStub[IPC_CALL_BACK_STUB_AUTH_ID] || !g_sdkCbStub[IPC_CALL_BACK_STUB_BIND_ID] ||
!g_sdkCbStub[IPC_CALL_BACK_STUB_DIRECT_AUTH_ID]) {
LOGE("alloc callback stub object failed");
UnInitProxyAdapt();
return HC_ERR_ALLOC_MEMORY;
+99
View File
@@ -65,6 +65,9 @@
#define FIELD_EXPIRE_TIME "expireTime"
#define FIELD_IS_DELETE_ALL "isDeleteAll"
#define FIELD_OS_ACCOUNT_ID "osAccountId"
#define FIELD_ACQURIED_TYPE "acquireType"
#define FIELD_CRED_OP_FLAG "flag"
#define FIELD_CRED_OP_RESULT "result"
#define FIELD_AUTH_CODE "authCode"
#define FIELD_DEVICE_LIST "deviceList"
#define FIELD_IS_UDID_HASH "isUdidHash"
@@ -285,10 +288,106 @@ typedef struct {
void (*destroyInfo)(char **returnInfo);
} DeviceGroupManager;
/**
* @brief This enum provides all the operationCode of interface ProcessCredential.
*/
enum {
/** invalid operationCode for initialize */
CRED_OP_INVALID = -1,
/** operationCode for ProcessCredential to query credential */
CRED_OP_QUERY,
/** operationCode for ProcessCredential to create credential */
CRED_OP_CREATE,
/** operationCode for ProcessCredential to import credential */
CRED_OP_IMPORT,
/** operationCode for ProcessCredential to delete credential */
CRED_OP_DELETE,
};
/**
* @brief This enum provides all the flag of reqJsion for interface ProcessCredential.
*/
enum {
/** invalid flag for initialize */
RETURN_FLAG_INVALID = -1,
/** flag for only return result */
RETURN_FLAG_DEFAULT,
/** flag for return result and publicKey */
RETURN_FLAG_PUBLIC_KEY,
};
/**
* @brief This enum provides all the acquireType of interface StartAuthDevice & ProcessAuthDevice.
*/
typedef enum {
/** invalid acquireType for initialize */
ACQUIRE_TYPE_INVALID = -1,
/** acquireType for p2p bind */
P2P_BIND,
} AcquireType;
#ifdef __cplusplus
extern "C" {
#endif
/**
* @brief Process Credential data.
*
* This API is used to process Credential data.
*
* @param operationCode: use one of CRED_OP_QUERY|CRED_OP_CREATE|CRED_OP_IMPORT|CRED_OP_DELETE
* @param requestParams: json string contains group of osAccountId|deviceId|serviceType|acquireType|flag
* @param returnData: json string contains group of result|publicKey
*
* @return When the ipc call is successful, it returns HC_SUCCESS.
* Otherwise, it returns other values.
*/
DEVICE_AUTH_API_PUBLIC int32_t ProcessCredential(
int32_t operationCode, const char *requestParams, char **returnData);
/**
* @brief Start to auth device.
*
* This API is used to start to auth device.
*
* @param requestId: id of a request
* @param authParams: json string contains group of osAccountId|deviceId|serviceType|acquireType|pinCode
* @param callbak: callback object
*
* @return When the ipc call is successful, it returns HC_SUCCESS.
* Otherwise, it returns other values.
*/
DEVICE_AUTH_API_PUBLIC int32_t StartAuthDevice(
int64_t requestId, const char *authParams, const DeviceAuthCallback *callbak);
/**
* @brief Process auth device data.
*
* This API is used to process auth device data.
*
* @param requestId: id of a request
* @param authParams: json string contains group of osAccountId|data
* @param callbak: callback object
*
* @return When the ipc call is successful, it returns HC_SUCCESS.
* Otherwise, it returns other values.
*/
DEVICE_AUTH_API_PUBLIC int32_t ProcessAuthDevice(
int64_t requestId, const char *authParams, const DeviceAuthCallback *callbak);
/**
* @brief Cancle auth device request.
*
* This API is used to cancle auth device request.
*
* @param requestId: id of a request
* @param authParams: json string contains osAccountId or NULL
*
* @return When the ipc call is successful, it returns HC_SUCCESS.
* Otherwise, it returns other values.
*/
DEVICE_AUTH_API_PUBLIC int32_t CancelAuthRequest(int64_t requestId, const char *authParams);
/**
* @brief Initialize device auth service.
*
@@ -96,6 +96,7 @@ enum {
HC_ERR_GENERATE_RANDOM = 0x00004011, // 16401
HC_ERR_STATUS = 0x00004012, // 16402
HC_ERR_STEP = 0x00004013, // 16403
HC_ERR_IDENTITY_DUPLICATED = 0x00004014, // 16404
/* error code for group , 0x00005000 ~ 0x00005FFF */
HC_ERR_ACCESS_DENIED = 0x00005001, // 20481
+7
View File
@@ -34,6 +34,10 @@ if (os_level == "mini" || os_level == "small") {
sources = deviceauth_files
defines = [ "HILOG_ENABLE" ]
defines += deviceauth_defines
sources += identity_manager_files
include_dirs += identity_manager_inc
deps = [
"${deps_adapter_path}:${hal_module_name}",
"//build/lite/config/component/cJSON:cjson_shared",
@@ -199,6 +203,9 @@ if (os_level == "mini" || os_level == "small") {
]
}
sources += identity_manager_files
include_dirs += identity_manager_inc
branch_protector_ret = "pac_ret"
sanitize = {
cfi = true
+5 -5
View File
@@ -16,7 +16,7 @@
#ifndef CREDS_MANAGER_H
#define CREDS_MANAGER_H
#include "creds_manager_defines.h"
#include "identity_manager.h"
#include "json_utils.h"
#ifdef __cplusplus
@@ -26,11 +26,11 @@ extern "C" {
int32_t AddCertInfoToJson(const CertInfo *certInfo, CJson *out);
int32_t GetCredInfosByPeerIdentity(const CJson *in, IdentityInfoVec *vec);
int32_t GetCredInfoByPeerUrl(const CJson *in, const Uint8Buff *presharedUrl, IdentityInfo **returnInfo);
int32_t GetSharedSecretByUrl(const CJson *in, const Uint8Buff *presharedUrl, ProtocolAlgType protocolType,
Uint8Buff *sharedSecret);
int32_t GetSharedSecretByUrl(
const CJson *in, const Uint8Buff *presharedUrl, ProtocolAlgType protocolType, Uint8Buff *sharedSecret);
int32_t GetCredInfoByPeerCert(const CJson *in, const CertInfo *certInfo, IdentityInfo **returnInfo);
int32_t GetSharedSecretByPeerCert(const CJson *in, const CertInfo *peerCertInfo, ProtocolAlgType protocolType,
Uint8Buff *sharedSecret);
int32_t GetSharedSecretByPeerCert(
const CJson *in, const CertInfo *peerCertInfo, ProtocolAlgType protocolType, Uint8Buff *sharedSecret);
#ifdef __cplusplus
}
File diff suppressed because it is too large Load Diff
@@ -1,381 +0,0 @@
/*
* 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 "creds_operation_utils.h"
#include "common_defs.h"
#include "creds_manager_defines.h"
#include "device_auth.h"
#include "device_auth_defines.h"
#include "group_auth_data_operation.h"
#include "hc_dev_info.h"
#include "hc_log.h"
#include "hc_types.h"
#include "json_utils.h"
#include "string_util.h"
IMPLEMENT_HC_VECTOR(ProtocolEntityVec, ProtocolEntity*, 1)
IMPLEMENT_HC_VECTOR(IdentityInfoVec, IdentityInfo*, 1)
static int32_t SetDlSpekeProtocol(IdentityInfo *info)
{
#ifdef ENABLE_P2P_BIND_DL_SPEKE
ProtocolEntity *dlSpekeEntity = (ProtocolEntity *)HcMalloc(sizeof(ProtocolEntity), 0);
if (dlSpekeEntity == NULL) {
LOGE("Failed to alloc memory for dl speke entity!");
return HC_ERR_ALLOC_MEMORY;
}
dlSpekeEntity->protocolType = ALG_DL_SPEKE;
dlSpekeEntity->expandProcessCmds = CMD_IMPORT_AUTH_CODE | CMD_ADD_TRUST_DEVICE;
if (info->protocolVec.pushBack(&info->protocolVec, (const ProtocolEntity **)&dlSpekeEntity) == NULL) {
LOGE("Failed to push dl speke entity!");
HcFree(dlSpekeEntity);
return HC_ERR_ALLOC_MEMORY;
}
return HC_SUCCESS;
#else
(void)info;
return HC_SUCCESS;
#endif
}
static int32_t SetIsoProtocol(IdentityInfo *info)
{
#ifdef ENABLE_P2P_BIND_ISO
ProtocolEntity *isoEntity = (ProtocolEntity *)HcMalloc(sizeof(ProtocolEntity), 0);
if (isoEntity == NULL) {
LOGE("Failed to alloc memory for iso entity!");
return HC_ERR_ALLOC_MEMORY;
}
isoEntity->protocolType = ALG_ISO;
isoEntity->expandProcessCmds = 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);
return HC_ERR_ALLOC_MEMORY;
}
return HC_SUCCESS;
#else
(void)info;
return HC_SUCCESS;
#endif
}
static int32_t SetLiteProtocols(IdentityInfo *info)
{
int32_t res = SetDlSpekeProtocol(info);
if (res != HC_SUCCESS) {
return res;
}
return SetIsoProtocol(info);
}
static int32_t SetLiteProtocolsForPinType(const CJson *in, IdentityInfo *info)
{
#ifndef ENABLE_P2P_BIND_LITE_PROTOCOL_CHECK
(void)in;
return SetLiteProtocols(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);
}
return res;
#endif
}
static int32_t SetProtocolsForPinType(const CJson *in, IdentityInfo *info)
{
#ifdef ENABLE_P2P_BIND_EC_SPEKE
ProtocolEntity *ecSpekeEntity = (ProtocolEntity *)HcMalloc(sizeof(ProtocolEntity), 0);
if (ecSpekeEntity == NULL) {
LOGE("Failed to alloc memory for ec speke entity!");
return HC_ERR_ALLOC_MEMORY;
}
ecSpekeEntity->protocolType = ALG_EC_SPEKE;
ecSpekeEntity->expandProcessCmds = 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);
return HC_ERR_ALLOC_MEMORY;
}
#endif
return SetLiteProtocolsForPinType(in, info);
}
static int32_t SetProtocolsForUidType(IdentityInfo *info)
{
#ifdef ENABLE_ACCOUNT_AUTH_ISO
ProtocolEntity *entity = (ProtocolEntity *)HcMalloc(sizeof(ProtocolEntity), 0);
if (entity == NULL) {
LOGE("Failed to alloc memory for entity!");
return HC_ERR_ALLOC_MEMORY;
}
entity->protocolType = ALG_ISO;
entity->expandProcessCmds = CMD_ADD_TRUST_DEVICE;
info->protocolVec.pushBack(&info->protocolVec, (const ProtocolEntity **)&entity);
#else
(void)info;
#endif
return HC_SUCCESS;
}
static int32_t SetProtocolsForP2pType(int32_t keyType, IdentityInfo *info)
{
if (keyType == KEY_TYPE_ASYM) {
#ifdef ENABLE_P2P_AUTH_EC_SPEKE
ProtocolEntity *entity = (ProtocolEntity *)HcMalloc(sizeof(ProtocolEntity), 0);
if (entity == NULL) {
LOGE("Failed to alloc memory for entity!");
return HC_ERR_ALLOC_MEMORY;
}
entity->protocolType = ALG_EC_SPEKE;
info->protocolVec.pushBack(&info->protocolVec, (const ProtocolEntity **)&entity);
#else
(void)info;
#endif
} else {
#ifdef ENABLE_P2P_AUTH_ISO
ProtocolEntity *entity = (ProtocolEntity *)HcMalloc(sizeof(ProtocolEntity), 0);
if (entity == NULL) {
LOGE("Failed to alloc memory for entity!");
return HC_ERR_ALLOC_MEMORY;
}
entity->protocolType = ALG_ISO;
info->protocolVec.pushBack(&info->protocolVec, (const ProtocolEntity **)&entity);
#else
(void)info;
#endif
}
return HC_SUCCESS;
}
static int32_t SetPreSharedUrlForProof(const char *urlStr, Uint8Buff *preSharedUrl)
{
uint32_t urlLen = HcStrlen(urlStr);
preSharedUrl->val = (uint8_t *)HcMalloc(urlLen + 1, 0);
if (preSharedUrl->val == NULL) {
LOGE("Failed to alloc preSharedUrl memory!");
return HC_ERR_ALLOC_MEMORY;
}
if (memcpy_s(preSharedUrl->val, urlLen + 1, urlStr, urlLen) != EOK) {
LOGE("Failed to copy url string to preSharedUrl");
HcFree(preSharedUrl->val);
preSharedUrl->val = NULL;
return HC_ERR_MEMORY_COPY;
}
preSharedUrl->length = urlLen + 1;
return HC_SUCCESS;
}
static int32_t SetProtocolsForPresharedCred(int32_t trustType, int32_t keyType, IdentityInfo *info)
{
if (trustType == TRUST_TYPE_UID) {
return SetProtocolsForUidType(info);
} else {
return SetProtocolsForP2pType(keyType, info);
}
}
int32_t GetSelfDeviceEntry(int32_t osAccountId, const char *groupId, TrustedDeviceEntry *deviceEntry)
{
char selfUdid[INPUT_UDID_LEN] = { 0 };
int32_t ret = HcGetUdid((uint8_t *)selfUdid, INPUT_UDID_LEN);
if (ret != HC_SUCCESS) {
LOGE("Failed to get local udid!");
return ret;
}
return GaGetTrustedDeviceEntryById(osAccountId, selfUdid, true, groupId, deviceEntry);
}
const char *GetPeerDevIdFromJson(const CJson *in, bool *isUdid)
{
const char *deviceId = GetStringFromJson(in, FIELD_PEER_UDID);
if (deviceId != NULL) {
*isUdid = true;
return deviceId;
}
return GetStringFromJson(in, FIELD_PEER_AUTH_ID);
}
int32_t GetPeerDeviceEntry(int32_t osAccountId, const CJson *in, const char *groupId,
TrustedDeviceEntry *returnDeviceEntry)
{
bool isUdid = false;
const char *peerDeviceId = GetPeerDevIdFromJson(in, &isUdid);
if (peerDeviceId == NULL) {
LOGE("Failed to get peer deviceId!");
return HC_ERR_JSON_GET;
}
return GaGetTrustedDeviceEntryById(osAccountId, peerDeviceId, isUdid, groupId, returnDeviceEntry);
}
int32_t GetIdentityInfoForPinType(const CJson *in, IdentityInfo *info)
{
CJson *urlJson = CreateJson();
if (urlJson == NULL) {
LOGE("Failed to create url json!");
return HC_ERR_JSON_CREATE;
}
if (AddIntToJson(urlJson, PRESHARED_URL_CREDENTIAL_TYPE, PRE_SHARED) != HC_SUCCESS) {
LOGE("Failed to add credential type!");
FreeJson(urlJson);
return HC_ERR_JSON_ADD;
}
if (AddIntToJson(urlJson, PRESHARED_URL_KEY_TYPE, KEY_TYPE_SYM) != HC_SUCCESS) {
LOGE("Failed to add key type!");
FreeJson(urlJson);
return HC_ERR_JSON_ADD;
}
if (AddIntToJson(urlJson, PRESHARED_URL_TRUST_TYPE, TRUST_TYPE_PIN) != HC_SUCCESS) {
LOGE("Failed to add trust type!");
FreeJson(urlJson);
return HC_ERR_JSON_ADD;
}
char *urlStr = PackJsonToString(urlJson);
FreeJson(urlJson);
if (urlStr == NULL) {
LOGE("Failed to pack url json to string!");
return HC_ERR_PACKAGE_JSON_TO_STRING_FAIL;
}
int32_t ret = SetPreSharedUrlForProof(urlStr, &info->proof.preSharedUrl);
FreeJsonString(urlStr);
if (ret != HC_SUCCESS) {
LOGE("Failed to set preSharedUrl of proof!");
return ret;
}
ret = SetProtocolsForPinType(in, info);
if (ret != HC_SUCCESS) {
LOGE("Failed to set protocols!");
return ret;
}
info->proofType = PRE_SHARED;
return ret;
}
int32_t GetIdentityInfoByType(int32_t keyType, int32_t trustType, const char *groupId, IdentityInfo *info)
{
CJson *urlJson = CreateJson();
if (urlJson == NULL) {
LOGE("Failed to create url json!");
return HC_ERR_JSON_CREATE;
}
if (AddIntToJson(urlJson, PRESHARED_URL_CREDENTIAL_TYPE, PRE_SHARED) != HC_SUCCESS) {
LOGE("Failed to add credential type!");
FreeJson(urlJson);
return HC_ERR_JSON_ADD;
}
if (AddIntToJson(urlJson, PRESHARED_URL_KEY_TYPE, keyType) != HC_SUCCESS) {
LOGE("Failed to add key type!");
FreeJson(urlJson);
return HC_ERR_JSON_ADD;
}
if (AddIntToJson(urlJson, PRESHARED_URL_TRUST_TYPE, trustType) != HC_SUCCESS) {
LOGE("Failed to add trust type!");
FreeJson(urlJson);
return HC_ERR_JSON_ADD;
}
if ((trustType == TRUST_TYPE_P2P || trustType == TRUST_TYPE_UID) &&
AddStringToJson(urlJson, FIELD_GROUP_ID, groupId) != HC_SUCCESS) {
LOGE("Failed to add group id!");
FreeJson(urlJson);
return HC_ERR_JSON_ADD;
}
char *urlStr = PackJsonToString(urlJson);
FreeJson(urlJson);
if (urlStr == NULL) {
LOGE("Failed to pack url json to string!");
return HC_ERR_PACKAGE_JSON_TO_STRING_FAIL;
}
int32_t ret = SetPreSharedUrlForProof(urlStr, &info->proof.preSharedUrl);
FreeJsonString(urlStr);
if (ret != HC_SUCCESS) {
LOGE("Failed to set preSharedUrl of proof!");
return ret;
}
ret = SetProtocolsForPresharedCred(trustType, keyType, info);
if (ret != HC_SUCCESS) {
LOGE("Failed to set protocols!");
return ret;
}
info->proofType = PRE_SHARED;
return ret;
}
void FreeBuffData(Uint8Buff *buff)
{
if (buff == NULL) {
return;
}
HcFree(buff->val);
buff->val = NULL;
buff->length = 0;
}
IdentityInfo *CreateIdentityInfo(void)
{
IdentityInfo *info = (IdentityInfo *)HcMalloc(sizeof(IdentityInfo), 0);
if (info == NULL) {
LOGE("Failed to alloc memory for identity info!");
return NULL;
}
info->protocolVec = CreateProtocolEntityVec();
return info;
}
void DestroyIdentityInfo(IdentityInfo *info)
{
if (info == NULL) {
return;
}
FreeBuffData(&info->proof.preSharedUrl);
FreeBuffData(&info->proof.certInfo.pkInfoStr);
FreeBuffData(&info->proof.certInfo.pkInfoSignature);
ClearProtocolEntityVec(&info->protocolVec);
HcFree(info);
}
void ClearIdentityInfoVec(IdentityInfoVec *vec)
{
uint32_t index;
IdentityInfo **info;
FOR_EACH_HC_VECTOR(*vec, index, info) {
DestroyIdentityInfo(*info);
}
DESTROY_HC_VECTOR(IdentityInfoVec, vec);
}
void ClearProtocolEntityVec(ProtocolEntityVec *vec)
{
uint32_t index;
ProtocolEntity **entity;
FOR_EACH_HC_VECTOR(*vec, index, entity) {
HcFree(*entity);
}
DESTROY_HC_VECTOR(ProtocolEntityVec, vec);
}
+272 -1
View File
@@ -39,6 +39,7 @@
#include "pseudonym_manager.h"
#include "task_manager.h"
#include "performance_dumper.h"
#include "identity_manager.h"
static GroupAuthManager *g_groupAuthManager = NULL;
static DeviceGroupManager *g_groupManagerInstance = NULL;
@@ -154,7 +155,7 @@ static const char *GetPeerUdidFromJson(int32_t osAccountId, const CJson *in)
{
const char *peerConnDeviceId = GetStringFromJson(in, FIELD_PEER_CONN_DEVICE_ID);
if (peerConnDeviceId == NULL) {
LOGE("get peerConnDeviceId from json fail.");
LOGI("get peerConnDeviceId from json fail.");
return NULL;
}
bool isUdidHash = false;
@@ -855,6 +856,32 @@ static int32_t BuildClientAuthContext(int32_t osAccountId, int64_t requestId, co
return AddChannelInfoToContext(SERVICE_CHANNEL, DEFAULT_CHANNEL_ID, context);
}
static int32_t BuildP2PBindContext(CJson *context)
{
int32_t acquireType = -1;
if (GetIntFromJson(context, FIELD_ACQURIED_TYPE, &acquireType) != HC_SUCCESS) {
LOGE("Failed to get acquireType from reqJsonStr!");
return HC_ERR_JSON_FAIL;
}
if ((acquireType == P2P_BIND) && AddBoolToJson(context, FIELD_IS_DIRECT_AUTH, true) != HC_SUCCESS) {
LOGE("add isDirectAuth to context fail.");
return HC_ERR_JSON_ADD;
}
if (AddIntToJson(context, FIELD_OPERATION_CODE, acquireType) != HC_SUCCESS) {
LOGE("add opCode to context fail.");
return HC_ERR_JSON_ADD;
}
const char *serviceType = GetStringFromJson(context, FIELD_SERVICE_TYPE);
if (serviceType == NULL) {
if ((acquireType == P2P_BIND) &&
AddStringToJson(context, FIELD_SERVICE_TYPE, DEFAULT_SERVICE_TYPE) != HC_SUCCESS) {
LOGE("add serviceType to context fail.");
return HC_ERR_JSON_ADD;
}
}
return HC_SUCCESS;
}
static int32_t AuthDevice(int32_t osAccountId, int64_t authReqId, const char *authParams,
const DeviceAuthCallback *gaCallback)
{
@@ -967,6 +994,58 @@ static int32_t BuildServerAuthContext(int64_t requestId, int32_t opCode, const c
return AddChannelInfoToContext(SERVICE_CHANNEL, DEFAULT_CHANNEL_ID, context);
}
static int32_t BuildServerP2PAuthContext(int64_t requestId, int32_t opCode, const char *appId, CJson *context)
{
int32_t osAccountId = ANY_OS_ACCOUNT;
(void)GetIntFromJson(context, FIELD_OS_ACCOUNT_ID, &osAccountId);
osAccountId = DevAuthGetRealOsAccountLocalId(osAccountId);
if (osAccountId == INVALID_OS_ACCOUNT) {
return HC_ERR_INVALID_PARAMS;
}
if (!IsOsAccountUnlocked(osAccountId)) {
LOGE("Os account is not unlocked!");
return HC_ERR_OS_ACCOUNT_NOT_UNLOCKED;
}
const char *peerUdid = GetStringFromJson(context, FIELD_PEER_CONN_DEVICE_ID);
const char *pinCode = GetStringFromJson(context, FIELD_PIN_CODE);
if (peerUdid == NULL && pinCode == NULL) {
LOGE("need peerConnDeviceId or pinCode!");
return HC_ERR_JSON_GET;
}
if (peerUdid != NULL) {
PRINT_SENSITIVE_DATA("PeerUdid", peerUdid);
if (AddDeviceIdToJson(context, peerUdid) != HC_SUCCESS) {
LOGE("add deviceId to context fail.");
return HC_ERR_JSON_ADD;
}
}
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 (AddIntToJson(context, FIELD_OS_ACCOUNT_ID, osAccountId) != HC_SUCCESS) {
LOGE("add operationCode 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, opCode) != HC_SUCCESS) {
LOGE("add opCode to context fail.");
return HC_ERR_JSON_ADD;
}
return AddChannelInfoToContext(SERVICE_CHANNEL, DEFAULT_CHANNEL_ID, context);
}
static int32_t OpenServerAuthSession(int64_t requestId, const CJson *receivedMsg, const DeviceAuthCallback *callback)
{
int32_t opCode = AUTH_FORM_ACCOUNT_UNRELATED;
@@ -1009,6 +1088,59 @@ static int32_t OpenServerAuthSession(int64_t requestId, const CJson *receivedMsg
return res;
}
static int32_t OpenServerAuthSessionForP2P(
int64_t requestId, const CJson *receivedMsg, const DeviceAuthCallback *callback)
{
int32_t opCode = P2P_BIND;
if (GetIntFromJson(receivedMsg, FIELD_OP_CODE, &opCode) != HC_SUCCESS) {
opCode = P2P_BIND;
LOGW("use default opCode.");
}
char *returnDataStr = ProcessRequestCallback(requestId, opCode, NULL, callback);
if (returnDataStr == NULL) {
LOGE("The OnRequest callback is fail!");
return HC_ERR_REQ_REJECTED;
}
CJson *context = CreateJsonFromString(returnDataStr);
FreeJsonString(returnDataStr);
if (context == NULL) {
LOGE("Failed to create context from string!");
return HC_ERR_JSON_FAIL;
}
if (AddBoolToJson(context, FIELD_IS_DIRECT_AUTH, true) != HC_SUCCESS) {
LOGE("Failed to add isDirectAuth to context!");
FreeJson(context);
return HC_ERR_JSON_ADD;
}
const char *pkgName = GetStringFromJson(context, FIELD_SERVICE_PKG_NAME);
if (pkgName == NULL && AddStringToJson(context, FIELD_SERVICE_PKG_NAME, DEFAULT_PACKAGE_NAME) != HC_SUCCESS) {
LOGE("Failed to add default package name to context!");
FreeJson(context);
return HC_ERR_JSON_ADD;
}
const char *serviceType = GetStringFromJson(context, FIELD_SERVICE_TYPE);
if (serviceType == NULL && AddStringToJson(context, FIELD_SERVICE_TYPE, DEFAULT_SERVICE_TYPE) != HC_SUCCESS) {
LOGE("Failed to add default package name to context!");
FreeJson(context);
return HC_ERR_JSON_ADD;
}
const char *appId = pkgName != NULL ? pkgName : DEFAULT_PACKAGE_NAME;
int32_t res = CheckAcceptRequest(context);
if (res != HC_SUCCESS) {
FreeJson(context);
return res;
}
res = BuildServerP2PAuthContext(requestId, opCode, appId, context);
if (res != HC_SUCCESS) {
FreeJson(context);
return res;
}
SessionInitParams params = { context, *callback };
res = OpenDevSession(requestId, appId, &params);
FreeJson(context);
return res;
}
static int32_t ProcessData(int64_t authReqId, const uint8_t *data, uint32_t dataLen,
const DeviceAuthCallback *gaCallback)
{
@@ -1092,6 +1224,145 @@ static int32_t GetPseudonymId(int32_t osAccountId, const char *indexKey, char **
return pseudonymInstance->getPseudonymId(osAccountId, indexKey, pseudonymId);
}
DEVICE_AUTH_API_PUBLIC int32_t ProcessCredential(int32_t operationCode, const char *reqJsonStr, char **returnData)
{
if (reqJsonStr == NULL || returnData == NULL) {
LOGE("Invalid params!");
return HC_ERR_INVALID_PARAMS;
}
const CredentialOperator *credOperator = GetCredentialOperator();
if (credOperator == NULL) {
LOGE("credOperator is null!");
return HC_ERR_NOT_SUPPORT;
}
int32_t res = HC_ERR_UNSUPPORTED_OPCODE;
switch (operationCode) {
case CRED_OP_QUERY:
res = credOperator->queryCredential(reqJsonStr, returnData);
break;
case CRED_OP_CREATE:
res = credOperator->genarateCredential(reqJsonStr, returnData);
break;
case CRED_OP_IMPORT:
res = credOperator->importCredential(reqJsonStr, returnData);
break;
case CRED_OP_DELETE:
res = credOperator->deleteCredential(reqJsonStr, returnData);
break;
default:
LOGE("invalid opCode: %d", operationCode);
break;
}
return res;
}
DEVICE_AUTH_API_PUBLIC int32_t ProcessAuthDevice(
int64_t authReqId, const char *authParams, const DeviceAuthCallback *callback)
{
SET_LOG_MODE(TRACE_MODE);
SET_TRACE_ID(authReqId);
LOGI("[DA] Begin ProcessAuthDevice [ReqId]: %" PRId64, authReqId);
if (authParams == NULL) {
LOGE("Invalid input for ProcessData!");
return HC_ERR_INVALID_PARAMS;
}
CJson *json = CreateJsonFromString(authParams);
if (json == NULL) {
LOGE("Failed to create json from string!");
return HC_ERR_JSON_FAIL;
}
const char *data = GetStringFromJson(json, "data");
if (data == NULL) {
LOGE("Failed to get received data from parameter!");
FreeJson(json);
return HC_ERR_INVALID_PARAMS;
}
CJson *receivedMsg = CreateJsonFromString(data);
FreeJson(json);
if (receivedMsg == NULL) {
LOGE("Failed to create json from string!");
return HC_ERR_JSON_FAIL;
}
int32_t res;
if (!IsSessionExist(authReqId)) {
res = OpenServerAuthSessionForP2P(authReqId, receivedMsg, callback);
if (res != HC_SUCCESS) {
FreeJson(receivedMsg);
return res;
}
}
res = PushProcSessionTask(authReqId, receivedMsg);
if (res != HC_SUCCESS) {
FreeJson(receivedMsg);
return res;
}
return HC_SUCCESS;
}
DEVICE_AUTH_API_PUBLIC int32_t StartAuthDevice(
int64_t authReqId, const char *authParams, const DeviceAuthCallback *callback)
{
SET_LOG_MODE(TRACE_MODE);
SET_TRACE_ID(authReqId);
LOGI("StartAuthDevice. [ReqId]:%" PRId64, authReqId);
if ((authParams == NULL) || (callback == NULL)) {
LOGE("The input auth params is invalid!");
return HC_ERR_INVALID_PARAMS;
}
CJson *context = CreateJsonFromString(authParams);
if (context == NULL) {
LOGE("Failed to create json from string!");
return HC_ERR_JSON_FAIL;
}
int32_t osAccountId = INVALID_OS_ACCOUNT;
if (GetIntFromJson(context, FIELD_OS_ACCOUNT_ID, &osAccountId) != HC_SUCCESS) {
LOGE("Failed to get osAccountId from json!");
FreeJson(context);
return HC_ERR_JSON_FAIL;
}
osAccountId = DevAuthGetRealOsAccountLocalId(osAccountId);
if (osAccountId == INVALID_OS_ACCOUNT) {
FreeJson(context);
return HC_ERR_INVALID_PARAMS;
}
int32_t res = BuildClientAuthContext(osAccountId, authReqId, DEFAULT_PACKAGE_NAME, context);
if (res != HC_SUCCESS) {
FreeJson(context);
return res;
}
res = BuildP2PBindContext(context);
if (res != HC_SUCCESS) {
FreeJson(context);
return res;
}
SessionInitParams params = { context, *callback };
res = OpenDevSession(authReqId, DEFAULT_PACKAGE_NAME, &params);
FreeJson(context);
if (res != HC_SUCCESS) {
LOGE("OpenDevSession fail. [Res]: %d", res);
return res;
}
return PushStartSessionTask(authReqId);
}
DEVICE_AUTH_API_PUBLIC int32_t CancelAuthRequest(int64_t requestId, const char *authParams)
{
SET_LOG_MODE(TRACE_MODE);
SET_TRACE_ID(requestId);
if (authParams == NULL) {
LOGE("Invalid authParams!");
return HC_ERR_INVALID_PARAMS;
}
LOGI("cancel request. [ReqId]: %" PRId64, requestId);
CancelDevSession(requestId, DEFAULT_PACKAGE_NAME);
return HC_SUCCESS;
}
static int32_t AllocGmAndGa(void)
{
if (g_groupManagerInstance == NULL) {
+4
View File
@@ -19,6 +19,10 @@
DestroyDeviceAuthService;
GetGaInstance;
GetGmInstance;
ProcessCredential;
StartAuthDevice;
ProcessAuthDevice;
CancelAuthRequest;
local:
*;
};
+29 -9
View File
@@ -13,18 +13,18 @@
import("//base/security/device_auth/deviceauth_env.gni")
group_auth_path = "${services_path}/group_auth"
authenticators_path = "${services_path}/authenticators"
group_auth_path = "${services_path}/legacy/group_auth"
authenticators_path = "${services_path}/legacy/authenticators"
protocol_path = "${services_path}/protocol"
cred_manager_path = "${services_path}/cred_manager"
data_manager_path = "${services_path}/data_manager"
privacy_enhancement_path = "${services_path}/privacy_enhancement"
dev_frameworks_path = "${services_path}/frameworks"
group_manager_path = "${services_path}/group_manager"
group_manager_path = "${services_path}/legacy/group_manager"
session_manager_path = "${services_path}/session_manager"
creds_manager_path = "${services_path}/creds_manager"
mk_agree_path = "${services_path}/mk_agree"
identity_manager_path = "${services_path}/identity_manager"
enable_broadcast = true
deviceauth_defines = []
@@ -198,11 +198,9 @@ auth_code_import_files = [ "${session_manager_path}/src/session/v2/expand_sub_se
pub_key_exchange_files = [ "${session_manager_path}/src/session/v2/expand_sub_session/expand_process_lib/pub_key_exchange.c" ]
save_trusted_info_files = [ "${session_manager_path}/src/session/v2/expand_sub_session/expand_process_lib/save_trusted_info.c" ]
creds_manager_files = [
"${creds_manager_path}/src/creds_manager.c",
"${creds_manager_path}/src/creds_operation_utils.c",
]
account_related_creds_manager_mock_files = [ "${creds_manager_path}/src/account_related_mock/account_related_creds_manager_mock.c" ]
creds_manager_files = [ "${creds_manager_path}/src/creds_manager.c" ]
account_related_creds_manager_mock_files =
[ "${identity_manager_path}/src/mock/cert_operation_mock.c" ]
group_manager_peer_to_peer_files = [ "${group_manager_path}/src/group_operation/peer_to_peer_group/peer_to_peer_group.c" ]
group_manager_peer_to_peer_mock_files = [ "${group_manager_path}/src/group_operation/peer_to_peer_group_mock/peer_to_peer_group_mock.c" ]
@@ -447,3 +445,25 @@ deviceauth_ipc_files = [
"${frameworks_path}/src/${ipc_adapt_path}/ipc_callback_proxy.${ipc_src_suffix}",
"${frameworks_path}/src/${ipc_adapt_path}/ipc_callback_stub.${ipc_src_suffix}",
]
identity_manager_inc = [ "${identity_manager_path}/inc" ]
declare_args() {
identity_manager_files = []
}
if (defined(ohos_lite)) {
identity_manager_files = [
"${identity_manager_path}/src/mock/identity_manager_mock.c",
"${identity_manager_path}/src/mock/identity_common_mock.c",
]
} else {
identity_manager_files = [
"${identity_manager_path}/src/identity_manager.c",
"${identity_manager_path}/src/credential_operator.c",
"${identity_manager_path}/src/identity_common.c",
"${identity_manager_path}/src/identity_group.c",
"${identity_manager_path}/src/identity_p2p.c",
"${identity_manager_path}/src/identity_pin.c",
]
}
+23 -22
View File
@@ -19,40 +19,41 @@ account_related_defines = [
]
account_related_inc_path = []
deviceauth_account_group_manager_path = "${services_path}/group_manager"
deviceauth_account_group_auth_path = "${services_path}/group_auth"
deviceauth_account_group_manager_path = "${services_path}/legacy/group_manager"
deviceauth_account_group_auth_path = "${services_path}/legacy/group_auth"
authenticators_path = "${services_path}/legacy/authenticators"
group_manager_identical_account_files = [ "${deviceauth_account_group_manager_path}/src/group_operation/identical_account_group/identical_account_group.c" ]
group_manager_across_account_files = [ "${deviceauth_account_group_manager_path}/src/group_operation/across_account_group/across_account_group.c" ]
group_auth_account_related_files = [ "${deviceauth_account_group_auth_path}/src/group_auth_manager/account_related_group_auth/account_related_group_auth.c" ]
identity_manager_path = "${services_path}/identity_manager"
account_related_inc_path += [
"${services_path}/authenticators/inc",
"${services_path}/authenticators/inc/account_related",
"${services_path}/authenticators/inc/account_related/auth/iso_auth_task",
"${services_path}/authenticators/inc/account_related/auth/pake_v2_auth_task",
"${services_path}/authenticators/inc/account_related/creds_manager",
"${authenticators_path}/inc",
"${authenticators_path}/inc/account_related",
"${authenticators_path}/inc/account_related/auth/iso_auth_task",
"${authenticators_path}/inc/account_related/auth/pake_v2_auth_task",
"${authenticators_path}/inc/account_related/creds_manager",
]
authenticators_account_related_files = [
"${services_path}/authenticators/src/account_related/account_module.c",
"${services_path}/authenticators/src/account_related/account_multi_task_manager.c",
"${services_path}/authenticators/src/account_related/account_task_main.c",
"${services_path}/authenticators/src/account_related/account_version_util.c",
"${services_path}/authenticators/src/account_related/creds_manager/asy_token_manager.c",
"${services_path}/authenticators/src/account_related/creds_manager/sym_token_manager.c",
"${services_path}/authenticators/src/account_related/auth/iso_auth_task/iso_auth_client_task.c",
"${services_path}/authenticators/src/account_related/auth/iso_auth_task/iso_auth_server_task.c",
"${services_path}/authenticators/src/account_related/auth/iso_auth_task/iso_auth_task_common.c",
"${services_path}/authenticators/src/account_related/auth/pake_v2_auth_task/pake_v2_auth_task_common.c",
"${services_path}/authenticators/src/account_related/auth/pake_v2_auth_task/pake_v2_auth_client_task.c",
"${services_path}/authenticators/src/account_related/auth/pake_v2_auth_task/pake_v2_auth_server_task.c",
"${authenticators_path}/src/account_related/account_module.c",
"${authenticators_path}/src/account_related/account_multi_task_manager.c",
"${authenticators_path}/src/account_related/account_task_main.c",
"${authenticators_path}/src/account_related/account_version_util.c",
"${authenticators_path}/src/account_related/creds_manager/asy_token_manager.c",
"${authenticators_path}/src/account_related/creds_manager/sym_token_manager.c",
"${authenticators_path}/src/account_related/auth/iso_auth_task/iso_auth_client_task.c",
"${authenticators_path}/src/account_related/auth/iso_auth_task/iso_auth_server_task.c",
"${authenticators_path}/src/account_related/auth/iso_auth_task/iso_auth_task_common.c",
"${authenticators_path}/src/account_related/auth/pake_v2_auth_task/pake_v2_auth_task_common.c",
"${authenticators_path}/src/account_related/auth/pake_v2_auth_task/pake_v2_auth_client_task.c",
"${authenticators_path}/src/account_related/auth/pake_v2_auth_task/pake_v2_auth_server_task.c",
]
account_related_cred_plugin_files = [ "${services_path}/cred_manager/src/account_related/account_related_cred_plugin.c" ]
account_related_creds_manager_files = [ "${services_path}/creds_manager/src/account_related/account_related_creds_manager.c" ]
account_related_creds_manager_files =
[ "${identity_manager_path}/src/cert_operation.c" ]
account_related_files =
group_auth_account_related_files + group_manager_identical_account_files +
+5
View File
@@ -70,8 +70,10 @@
#define FIELD_IS_BIND "isBind"
#define FIELD_IS_FORCE_DELETE "isForceDelete"
#define FIELD_IS_CREDENTIAL_EXISTS "isCredentialExists"
#define FIELD_IS_DIRECT_AUTH "isDirectAuth"
#define FIELD_KCF_DATA "kcfData"
#define FIELD_KEY_TYPE "keyType"
#define FIELD_TRUST_TYPE "trustType"
#define FIELD_MESSAGE "message"
#define FIELD_GROUP_ERROR_MSG "groupErrorMsg"
#define FIELD_MIN_VERSION "minVersion"
@@ -144,6 +146,9 @@
#define DEFAULT_REQUEST_ID 0
#define DEFAULT_CHANNEL_ID (-1)
#define DEFAULT_EXPIRE_TIME 90
#define DEFAULT_SERVICE_TYPE "service.type.default"
#define SERVICE_TYPE_IMPORT "service.type.import"
#define DEFAULT_PACKAGE_NAME "deviceauth_service"
#define GROUP_MANAGER_PACKAGE_NAME "com.huawei.devicegroupmanage"
#define DM_APP_ID "ohos.distributedhardware.devicemanager"
#define SOFTBUS_APP_ID "softbus_auth"
@@ -34,6 +34,13 @@ using namespace OHOS::Security::AccessToken;
#define PROC_NAME_SOFT_BUS "softbus_server"
#define PROC_NAME_DEVICE_SECURITY_LEVEL "dslm_service"
static unordered_map<int32_t, vector<string>> g_apiAccessWhitelist = {
{ IPC_CALL_ID_PROCESS_CREDENTIAL, { PROC_NAME_DEVICE_MANAGER } },
{ IPC_CALL_ID_DA_AUTH_DEVICE, { PROC_NAME_DEVICE_MANAGER, PROC_NAME_SOFT_BUS } },
{ IPC_CALL_ID_DA_PROC_DATA, { PROC_NAME_DEVICE_MANAGER, PROC_NAME_SOFT_BUS } },
{ IPC_CALL_ID_DA_CANCEL_REQUEST, { PROC_NAME_DEVICE_MANAGER, PROC_NAME_SOFT_BUS } },
};
static unordered_map<int32_t, vector<string>> g_apiAccessConfig = {
{ IPC_CALL_ID_REG_CB, { PROC_NAME_DEVICE_MANAGER } },
{ IPC_CALL_ID_UNREG_CB, { PROC_NAME_DEVICE_MANAGER } },
@@ -61,6 +68,23 @@ static bool IsProcessAllowAccess(const string &processName, int32_t methodId)
g_apiAccessConfig[methodId].end();
}
static bool IsProcessInWhitelist(const string& processName, int32_t methodId)
{
if (g_apiAccessWhitelist.find(methodId) == g_apiAccessWhitelist.end()) {
return true;
}
int32_t ret = find(g_apiAccessWhitelist[methodId].begin(), g_apiAccessWhitelist[methodId].end(), processName) !=
g_apiAccessWhitelist[methodId].end();
if (ret) {
LOGI("%s %d", processName.c_str(), ret);
} else {
LOGE("Access Denied: Process(%s) not in access whitlist", processName.c_str());
return false;
}
return true;
}
int32_t CheckPermission(int32_t methodId)
{
AccessTokenID tokenId = IPCSkeleton::GetCallingTokenID();
@@ -78,6 +102,12 @@ int32_t CheckPermission(int32_t methodId)
LOGE("Check permission(APL3=SYSTEM_CORE or APL2=SYSTEM_BASIC) failed! APL: %d", findInfo.apl);
return HC_ERROR;
}
if (!IsProcessInWhitelist(findInfo.processName, methodId)) {
LOGE("Check permission(Access Whitelist) failed!");
return HC_ERROR;
}
if (!IsProcessAllowAccess(findInfo.processName, methodId)) {
LOGE("Check permission(Interface Access List) failed!");
return HC_ERROR;
@@ -13,18 +13,18 @@
* limitations under the License.
*/
#ifndef ACCOUNT_RELATED_CREDS_MANAGER_H
#define ACCOUNT_RELATED_CREDS_MANAGER_H
#ifndef CERT_OPERATION_H
#define CERT_OPERATION_H
#include "creds_manager_defines.h"
#include "identity_defines.h"
#include "json_utils.h"
#ifdef __cplusplus
extern "C" {
#endif
int32_t GetAccountRelatedCredInfo(int32_t osAccountId, const char *groupId, const char *deviceId,
bool isUdid, IdentityInfo *info);
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 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);
@@ -13,23 +13,28 @@
* limitations under the License.
*/
#ifndef CREDS_OPERATION_UTILS_H
#define CREDS_OPERATION_UTILS_H
#ifndef AUTH_IDENTITY_COMMON_H
#define AUTH_IDENTITY_COMMON_H
#include "creds_manager_defines.h"
#include "data_manager.h"
#include "hc_vector.h"
#include "identity_defines.h"
#include "json_utils.h"
#ifdef __cplusplus
extern "C" {
#endif
int32_t ConvertPsk(const Uint8Buff *srcPsk, Uint8Buff *sharedSecret);
int32_t SetPreSharedUrlForProof(const char *urlStr, Uint8Buff *preSharedUrl);
CJson *CreateCredUrlJson(int32_t credentailType, int32_t keyType, int32_t trustType);
#if 1
int32_t GetSelfDeviceEntry(int32_t osAccountId, const char *groupId, TrustedDeviceEntry *deviceEntry);
const char *GetPeerDevIdFromJson(const CJson *in, bool *isUdid);
int32_t GetPeerDeviceEntry(int32_t osAccountId, const CJson *in, const char *groupId,
TrustedDeviceEntry *returnDeviceEntry);
int32_t GetIdentityInfoForPinType(const CJson *in, IdentityInfo *info);
int32_t GetIdentityInfoByType(int32_t keyType, int32_t trustType, const char *groupId, IdentityInfo *info);
int32_t GetPeerDeviceEntry(
int32_t osAccountId, const CJson *in, const char *groupId, TrustedDeviceEntry *returnDeviceEntry);
void FreeBuffData(Uint8Buff *buff);
IdentityInfo *CreateIdentityInfo(void);
@@ -40,6 +45,7 @@ void ClearIdentityInfoVec(IdentityInfoVec *vec);
ProtocolEntityVec CreateProtocolEntityVec(void);
void ClearProtocolEntityVec(ProtocolEntityVec *vec);
#endif
#ifdef __cplusplus
}
@@ -13,8 +13,8 @@
* limitations under the License.
*/
#ifndef CREDS_MANAGER_DEFINES_H
#define CREDS_MANAGER_DEFINES_H
#ifndef AUTH_IDENTITY_DEFINE_H
#define AUTH_IDENTITY_DEFINE_H
#include "alg_defs.h"
#include "hc_vector.h"
@@ -27,6 +27,7 @@
#define SHARED_KEY_ALIAS "sharedKeyAlias"
#define KEY_INFO_PERSISTENT_TOKEN "persistent_token"
#define TMP_AUTH_KEY_FACTOR "hichain_tmp_auth_enc_key"
#define ASCII_CASE_DIFFERENCE_VALUE 32
#define P256_SHARED_SECRET_KEY_SIZE 32
#define AUTH_TOKEN_SIZE 32
@@ -36,32 +37,42 @@
#define ISO_PSK_LEN 32
#define SEED_LEN 32
#define ISO_KEY_ALIAS_LEN 32
#define KEY_TYPE_PAIR_LEN 2
#define PAKE_ED25519_KEY_PAIR_LEN 32
#define PAKE_ED25519_KEY_STR_LEN 64
#define AUTH_CODE_LEN 32
#define KEY_ALIAS_LEN 32
#define PACKAGE_NAME_MAX_LEN 256
#define SERVICE_TYPE_MAX_LEN 256
#define AUTH_ID_MAX_LEN 64
#ifdef __cplusplus
extern "C" {
#endif
typedef enum {
KEY_TYPE_SYM,
KEY_TYPE_ASYM
} KeyType;
typedef enum { KEY_TYPE_SYM, KEY_TYPE_ASYM } KeyType;
typedef enum { TRUST_TYPE_PIN, TRUST_TYPE_P2P, TRUST_TYPE_UID } TrustType;
typedef enum { PRE_SHARED, CERTIFICATED } IdentityProofType;
typedef enum { ALG_EC_SPEKE = 0x0001, ALG_DL_SPEKE = 0x0002, ALG_ISO = 0x0004 } ProtocolAlgType;
typedef enum {
TRUST_TYPE_PIN,
TRUST_TYPE_P2P,
TRUST_TYPE_UID
} TrustType;
KEY_ALIAS_ACCESSOR_PK = 0,
KEY_ALIAS_CONTROLLER_PK = 1,
KEY_ALIAS_LT_KEY_PAIR = 2,
KEY_ALIAS_KEK = 3,
KEY_ALIAS_DEK = 4,
KEY_ALIAS_TMP = 5,
KEY_ALIAS_PSK = 6,
KEY_ALIAS_AUTH_TOKEN = 7,
KEY_ALIAS_P2P_AUTH = 8,
typedef enum {
PRE_SHARED,
CERTIFICATED
} IdentityProofType;
KEY_ALIAS_TYPE_END
} KeyAliasType; // 0 ~ 2^8-1, don't change the order
typedef enum {
ALG_EC_SPEKE = 0x0001,
ALG_DL_SPEKE = 0x0002,
ALG_ISO = 0x0004
} ProtocolAlgType;
uint8_t *GetKeyTypePair(KeyAliasType keyAliasType);
typedef enum {
CMD_EXCHANGE_PK = 0x0001,
@@ -70,11 +81,16 @@ typedef enum {
CMD_MK_AGREE = 0x0008,
} ExpandProcessCmd;
typedef enum {
DEFAULT_ID_TYPE = 0,
P2P_DIRECT_AUTH = 1,
} IdentityInfoType;
typedef struct {
ProtocolAlgType protocolType;
uint32_t expandProcessCmds;
} ProtocolEntity;
DECLARE_HC_VECTOR(ProtocolEntityVec, ProtocolEntity*)
DECLARE_HC_VECTOR(ProtocolEntityVec, ProtocolEntity *)
typedef struct {
Uint8Buff pkInfoStr;
@@ -92,8 +108,9 @@ typedef struct {
IdentityProofType proofType;
IdentityProof proof;
ProtocolEntityVec protocolVec;
int32_t IdInfoType;
} IdentityInfo;
DECLARE_HC_VECTOR(IdentityInfoVec, IdentityInfo*)
DECLARE_HC_VECTOR(IdentityInfoVec, IdentityInfo *)
#ifdef __cplusplus
}
@@ -0,0 +1,75 @@
/*
* 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.
*/
#ifndef AUTH_IDENTITY_MANAGER_H
#define AUTH_IDENTITY_MANAGER_H
#include "alg_defs.h"
#include "alg_loader.h"
#include "common_defs.h"
#include "das_task_common.h"
#include "device_auth_defines.h"
#include "hc_log.h"
#include "hc_types.h"
#include "identity_common.h"
#include "identity_defines.h"
#include "json_utils.h"
#include "securec.h"
#ifdef __cplusplus
extern "C" {
#endif
typedef enum {
AUTH_IDENTITY_TYPE_INVALID = -1,
AUTH_IDENTITY_TYPE_GROUP,
AUTH_IDENTITY_TYPE_PIN,
AUTH_IDENTITY_TYPE_P2P,
} AuthIdentityType;
typedef struct {
int32_t (*getCredInfosByPeerIdentity)(const CJson *in, IdentityInfoVec *vec);
int32_t (*getCredInfoByPeerUrl)(const CJson *in, const Uint8Buff *presharedUrl, IdentityInfo **returnInfo);
int32_t (*getSharedSecretByUrl)(
const CJson *in, const Uint8Buff *presharedUrl, ProtocolAlgType protocolType, Uint8Buff *sharedSecret);
int32_t (*getCredInfoByPeerCert)(const CJson *in, const CertInfo *certInfo, IdentityInfo **returnInfo);
int32_t (*getSharedSecretByPeerCert)(
const CJson *in, const CertInfo *peerCertInfo, ProtocolAlgType protocolType, Uint8Buff *sharedSecret);
} AuthIdentity;
typedef struct {
int32_t (*queryCredential)(const char *reqJsonStr, char **returnData);
int32_t (*genarateCredential)(const char *reqJsonStr, char **returnData);
int32_t (*importCredential)(const char *reqJsonStr, char **returnData);
int32_t (*deleteCredential)(const char *reqJsonStr, char **returnData);
} CredentialOperator;
typedef struct {
const AuthIdentity *(*getAuthIdentityByType)(AuthIdentityType type);
const CredentialOperator *(*getCredentialOperator)(void);
} AuthIdentityManager;
const AuthIdentity *GetGroupAuthIdentity(void);
const AuthIdentity *GetPinAuthIdentity(void);
const AuthIdentity *GetP2pAuthIdentity(void);
const AuthIdentity *GetAuthIdentityByType(AuthIdentityType type);
const CredentialOperator *GetCredentialOperator(void);
const AuthIdentityManager *GetAuthIdentityManager(void);
#ifdef __cplusplus
}
#endif
#endif // AUTH_IDENTITY_MANAGER_H
@@ -13,24 +13,115 @@
* limitations under the License.
*/
#include "account_related_creds_manager.h"
#include "cert_operation.h"
#include "account_auth_plugin_proxy.h"
#include "account_related_group_auth.h"
#include "alg_loader.h"
#include "asy_token_manager.h"
#include "creds_manager.h"
#include "creds_operation_utils.h"
#include "data_manager.h"
#include "group_auth_data_operation.h"
#include "group_operation_common.h"
#include "hc_log.h"
#include "hc_types.h"
#include "identity_common.h"
#include "pseudonym_manager.h"
#include "sym_token_manager.h"
#define FIELD_SHARED_SECRET "sharedSecret"
static int32_t SetProtocolsForUidType(IdentityInfo *info)
{
#ifdef ENABLE_ACCOUNT_AUTH_ISO
ProtocolEntity *entity = (ProtocolEntity *)HcMalloc(sizeof(ProtocolEntity), 0);
if (entity == NULL) {
LOGE("Failed to alloc memory for entity!");
return HC_ERR_ALLOC_MEMORY;
}
entity->protocolType = ALG_ISO;
entity->expandProcessCmds = CMD_ADD_TRUST_DEVICE;
info->protocolVec.pushBack(&info->protocolVec, (const ProtocolEntity **)&entity);
#else
(void)info;
#endif
return HC_SUCCESS;
}
static int32_t GetIdentityInfoByType(int32_t keyType, int32_t trustType, const char *groupId, IdentityInfo *info)
{
CJson *urlJson = CreateJson();
if (urlJson == NULL) {
LOGE("Failed to create url json!");
return HC_ERR_JSON_CREATE;
}
if (AddIntToJson(urlJson, PRESHARED_URL_CREDENTIAL_TYPE, PRE_SHARED) != HC_SUCCESS) {
LOGE("Failed to add credential type!");
FreeJson(urlJson);
return HC_ERR_JSON_ADD;
}
if (AddIntToJson(urlJson, PRESHARED_URL_KEY_TYPE, keyType) != HC_SUCCESS) {
LOGE("Failed to add key type!");
FreeJson(urlJson);
return HC_ERR_JSON_ADD;
}
if (AddIntToJson(urlJson, PRESHARED_URL_TRUST_TYPE, trustType) != HC_SUCCESS) {
LOGE("Failed to add trust type!");
FreeJson(urlJson);
return HC_ERR_JSON_ADD;
}
if ((trustType == TRUST_TYPE_P2P || trustType == TRUST_TYPE_UID) &&
AddStringToJson(urlJson, FIELD_GROUP_ID, groupId) != HC_SUCCESS) {
LOGE("Failed to add group id!");
FreeJson(urlJson);
return HC_ERR_JSON_ADD;
}
char *urlStr = PackJsonToString(urlJson);
FreeJson(urlJson);
if (urlStr == NULL) {
LOGE("Failed to pack url json to string!");
return HC_ERR_PACKAGE_JSON_TO_STRING_FAIL;
}
int32_t ret = SetPreSharedUrlForProof(urlStr, &info->proof.preSharedUrl);
FreeJsonString(urlStr);
if (ret != HC_SUCCESS) {
LOGE("Failed to set preSharedUrl of proof!");
return ret;
}
ret = SetProtocolsForUidType(info);
if (ret != HC_SUCCESS) {
LOGE("Failed to set protocols!");
return ret;
}
info->proofType = PRE_SHARED;
return ret;
}
int32_t AddCertInfoToJson(const CertInfo *certInfo, CJson *out)
{
if (certInfo == NULL || out == NULL) {
LOGE("Invalid cert info or out!");
return HC_ERR_INVALID_PARAMS;
}
if (AddIntToJson(out, FIELD_SIGN_ALG, certInfo->signAlg) != HC_SUCCESS) {
LOGE("add sign alg to json failed!");
return HC_ERR_JSON_ADD;
}
if (AddStringToJson(out, FIELD_PK_INFO, (const char *)certInfo->pkInfoStr.val) != HC_SUCCESS) {
LOGE("add pk info str to json failed!");
return HC_ERR_JSON_ADD;
}
if (AddByteToJson(out, FIELD_PK_INFO_SIGNATURE, certInfo->pkInfoSignature.val,
certInfo->pkInfoSignature.length) != HC_SUCCESS) {
LOGE("add pk info sign to json failed!");
return HC_ERR_JSON_ADD;
}
return HC_SUCCESS;
}
static TrustedGroupEntry *GetSelfGroupEntryByPeerCert(int32_t osAccountId, const CertInfo *certInfo)
{
CJson *peerPkInfoJson = CreateJsonFromString((const char *)certInfo->pkInfoStr.val);
@@ -65,7 +156,8 @@ static TrustedGroupEntry *GetSelfGroupEntryByPeerCert(int32_t osAccountId, const
}
GroupEntryVec groupEntryVec = CreateGroupEntryVec();
QueryGroupParams queryParams = InitQueryGroupParams();
((AccountRelatedGroupAuth *)groupAuth)->getAccountCandidateGroup(osAccountId, param, &queryParams, &groupEntryVec);
((AccountRelatedGroupAuth *)groupAuth)
->getAccountCandidateGroup(osAccountId, param, &queryParams, &groupEntryVec);
FreeJson(param);
if (groupEntryVec.size(&groupEntryVec) == 0) {
LOGE("group not found by peer user id!");
@@ -77,8 +169,8 @@ static TrustedGroupEntry *GetSelfGroupEntryByPeerCert(int32_t osAccountId, const
return returnEntry;
}
static int32_t GetSelfDeviceEntryByPeerCert(int32_t osAccountId, const CertInfo *certInfo,
TrustedDeviceEntry *deviceEntry)
static int32_t GetSelfDeviceEntryByPeerCert(
int32_t osAccountId, const CertInfo *certInfo, TrustedDeviceEntry *deviceEntry)
{
TrustedGroupEntry *groupEntry = GetSelfGroupEntryByPeerCert(osAccountId, certInfo);
if (groupEntry == NULL) {
@@ -98,18 +190,15 @@ static int32_t VerifyPeerCertInfo(const char *selfUserId, const char *selfAuthId
LOGE("Failed to alloc memory for key alias value!");
return HC_ERR_ALLOC_MEMORY;
}
Uint8Buff keyAlias = {
.val = keyAliasValue,
.length = SHA256_LEN
};
Uint8Buff keyAlias = { .val = keyAliasValue, .length = SHA256_LEN };
int32_t ret = GetAccountAuthTokenManager()->generateKeyAlias(selfUserId, selfAuthId, &keyAlias, true);
if (ret != HC_SUCCESS) {
LOGE("Failed to generate server pk alias!");
HcFree(keyAliasValue);
return ret;
}
ret = GetLoaderInstance()->verify(&keyAlias, &certInfo->pkInfoStr, certInfo->signAlg,
&certInfo->pkInfoSignature, true);
ret = GetLoaderInstance()->verify(
&keyAlias, &certInfo->pkInfoStr, certInfo->signAlg, &certInfo->pkInfoSignature, true);
HcFree(keyAliasValue);
if (ret != HC_SUCCESS) {
return HC_ERR_VERIFY_FAILED;
@@ -148,8 +237,8 @@ static int32_t GetPeerPubKeyFromCert(const CertInfo *peerCertInfo, Uint8Buff *pe
return HC_SUCCESS;
}
static int32_t GetSharedSecretForAccountInPake(const char *userId, const char *authId,
const CertInfo *peerCertInfo, Uint8Buff *sharedSecret)
static int32_t GetSharedSecretForAccountInPake(
const char *userId, const char *authId, const CertInfo *peerCertInfo, Uint8Buff *sharedSecret)
{
uint8_t *priAliasVal = (uint8_t *)HcMalloc(SHA256_LEN, 0);
if (priAliasVal == NULL) {
@@ -162,22 +251,14 @@ static int32_t GetSharedSecretForAccountInPake(const char *userId, const char *a
HcFree(priAliasVal);
return ret;
}
KeyBuff priAliasKeyBuff = {
.key = aliasBuff.val,
.keyLen = aliasBuff.length,
.isAlias = true
};
Uint8Buff peerPkBuff = { 0 };
KeyBuff priAliasKeyBuff = { .key = aliasBuff.val, .keyLen = aliasBuff.length, .isAlias = true };
Uint8Buff peerPkBuff = { 0 };
ret = GetPeerPubKeyFromCert(peerCertInfo, &peerPkBuff);
if (ret != HC_SUCCESS) {
HcFree(priAliasVal);
return ret;
}
KeyBuff publicKeyBuff = {
.key = peerPkBuff.val,
.keyLen = peerPkBuff.length,
.isAlias = false
};
KeyBuff publicKeyBuff = { .key = peerPkBuff.val, .keyLen = peerPkBuff.length, .isAlias = false };
uint32_t sharedKeyAliasLen = HcStrlen(SHARED_KEY_ALIAS) + 1;
sharedSecret->val = (uint8_t *)HcMalloc(sharedKeyAliasLen, 0);
@@ -189,8 +270,8 @@ static int32_t GetSharedSecretForAccountInPake(const char *userId, const char *a
}
sharedSecret->length = sharedKeyAliasLen;
(void)memcpy_s(sharedSecret->val, sharedKeyAliasLen, SHARED_KEY_ALIAS, sharedKeyAliasLen);
ret = GetLoaderInstance()->agreeSharedSecretWithStorage(&priAliasKeyBuff, &publicKeyBuff,
P256, P256_SHARED_SECRET_KEY_SIZE, sharedSecret);
ret = GetLoaderInstance()->agreeSharedSecretWithStorage(
&priAliasKeyBuff, &publicKeyBuff, P256, P256_SHARED_SECRET_KEY_SIZE, sharedSecret);
HcFree(priAliasVal);
ClearFreeUint8Buff(&peerPkBuff);
if (ret != HC_SUCCESS) {
@@ -255,8 +336,8 @@ static int32_t GetCertInfo(int32_t osAccountId, const char *userId, const char *
return HC_SUCCESS;
}
static int32_t GetAccountAsymIdentityInfo(int32_t osAccountId, const char *userId, const char *authId,
IdentityInfo *info, bool isNeedGeneratePdid)
static int32_t GetAccountAsymIdentityInfo(
int32_t osAccountId, const char *userId, const char *authId, IdentityInfo *info, bool isNeedGeneratePdid)
{
int32_t ret = GetCertInfo(osAccountId, userId, authId, &info->proof.certInfo);
if (ret != HC_SUCCESS) {
@@ -288,8 +369,7 @@ static int32_t GetAccountAsymIdentityInfo(int32_t osAccountId, const char *userI
return HC_SUCCESS;
}
static int32_t GetLocalDeviceType(int32_t osAccountId, const CJson *in, const char *groupId,
int32_t *localDevType)
static int32_t GetLocalDeviceType(int32_t osAccountId, const CJson *in, const char *groupId, int32_t *localDevType)
{
TrustedDeviceEntry *deviceEntry = CreateDeviceEntry();
if (deviceEntry == NULL) {
@@ -353,8 +433,8 @@ static int32_t GenerateAuthTokenForAccessory(int32_t osAccountId, const char *gr
return ret;
}
static int32_t GenerateTokenAliasForController(int32_t osAccountId, const CJson *in, const char *groupId,
Uint8Buff *authTokenAlias)
static int32_t GenerateTokenAliasForController(
int32_t osAccountId, const CJson *in, const char *groupId, Uint8Buff *authTokenAlias)
{
TrustedDeviceEntry *deviceEntry = CreateDeviceEntry();
if (deviceEntry == NULL) {
@@ -385,8 +465,8 @@ static int32_t GenerateTokenAliasForController(int32_t osAccountId, const CJson
return ret;
}
static int32_t GenerateAuthTokenByDevType(const CJson *in, const CJson *urlJson, Uint8Buff *authToken,
bool *isTokenStored)
static int32_t GenerateAuthTokenByDevType(
const CJson *in, const CJson *urlJson, Uint8Buff *authToken, bool *isTokenStored)
{
int32_t osAccountId = INVALID_OS_ACCOUNT;
if (GetIntFromJson(in, FIELD_OS_ACCOUNT_ID, &osAccountId) != HC_SUCCESS) {
@@ -413,8 +493,8 @@ static int32_t GenerateAuthTokenByDevType(const CJson *in, const CJson *urlJson,
return ret;
}
static int32_t GetSelfAccountIdentityInfo(int32_t osAccountId, const char *groupId, IdentityInfo *info,
bool isNeedGeneratePdid)
static int32_t GetSelfAccountIdentityInfo(
int32_t osAccountId, const char *groupId, IdentityInfo *info, bool isNeedGeneratePdid)
{
TrustedDeviceEntry *deviceEntry = CreateDeviceEntry();
if (deviceEntry == NULL) {
@@ -462,8 +542,8 @@ static bool isNeedGeneratePdidByPeerCert(int32_t osAccountId, const CertInfo *ce
#endif
}
int32_t GetAccountRelatedCredInfo(int32_t osAccountId, const char *groupId, const char *deviceId,
bool isUdid, IdentityInfo *info)
int32_t GetAccountRelatedCredInfo(
int32_t osAccountId, const char *groupId, const char *deviceId, bool isUdid, IdentityInfo *info)
{
if (groupId == NULL || deviceId == NULL || info == NULL) {
LOGE("Invalid input params!");
@@ -501,8 +581,8 @@ int32_t GetAccountRelatedCredInfo(int32_t osAccountId, const char *groupId, cons
}
}
static int32_t GetSharedSecretByPeerCertFromPlugin(int32_t osAccountId, const CertInfo *peerCertInfo,
Uint8Buff *sharedSecret)
static int32_t GetSharedSecretByPeerCertFromPlugin(
int32_t osAccountId, const CertInfo *peerCertInfo, Uint8Buff *sharedSecret)
{
CJson *input = CreateJson();
if (input == NULL) {
@@ -0,0 +1,667 @@
/*
* 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 "alg_defs.h"
#include "alg_loader.h"
#include "das_standard_token_manager.h"
#include "hc_dev_info.h"
#include "hc_log.h"
#include "identity_manager.h"
#include "os_account_adapter.h"
typedef struct {
int32_t osAccountId;
int32_t acquireType;
char *deviceId;
int32_t flag;
Uint8Buff *publicKey;
char *serviceType;
} CredentialRequestParamT;
static int32_t CombineServiceId(const Uint8Buff *pkgName, const Uint8Buff *serviceType, Uint8Buff *serviceId)
{
int32_t res = HC_SUCCESS;
Uint8Buff serviceIdPlain = { NULL, 0 };
serviceIdPlain.length = pkgName->length + serviceType->length;
serviceIdPlain.val = (uint8_t *)HcMalloc(serviceIdPlain.length, 0);
if (serviceIdPlain.val == NULL) {
LOGE("malloc serviceIdPlain.val failed.");
res = HC_ERR_ALLOC_MEMORY;
goto ERR;
}
if (memcpy_s(serviceIdPlain.val, serviceIdPlain.length, pkgName->val, pkgName->length) != EOK) {
LOGE("Copy service id: pkgName failed.");
res = HC_ERR_MEMORY_COPY;
goto ERR;
}
if (memcpy_s(serviceIdPlain.val + pkgName->length, serviceIdPlain.length - pkgName->length, serviceType->val,
serviceType->length) != EOK) {
LOGE("Copy service id: serviceType failed.");
res = HC_ERR_MEMORY_COPY;
goto ERR;
}
res = GetLoaderInstance()->sha256(&serviceIdPlain, serviceId);
if (res != HC_SUCCESS) {
LOGE("Service id Sha256 failed.");
goto ERR;
}
ERR:
HcFree(serviceIdPlain.val);
return res;
}
static int32_t CombineKeyAlias(
const Uint8Buff *serviceId, const Uint8Buff *keyType, const Uint8Buff *authId, Uint8Buff *keyAliasHash)
{
int32_t res = HC_SUCCESS;
Uint8Buff keyAliasBuff = { NULL, 0 };
keyAliasBuff.length = serviceId->length + authId->length + keyType->length;
keyAliasBuff.val = (uint8_t *)HcMalloc(keyAliasBuff.length, 0);
if (keyAliasBuff.val == NULL) {
LOGE("Malloc mem failed.");
return HC_ERR_ALLOC_MEMORY;
}
uint32_t totalLen = keyAliasBuff.length;
uint32_t usedLen = 0;
if (memcpy_s(keyAliasBuff.val, totalLen, serviceId->val, serviceId->length) != EOK) {
LOGE("Copy serviceId failed.");
res = HC_ERR_MEMORY_COPY;
goto ERR;
}
usedLen = usedLen + serviceId->length;
if (memcpy_s(keyAliasBuff.val + usedLen, totalLen - usedLen, keyType->val, keyType->length) != EOK) {
LOGE("Copy keyType failed.");
res = HC_ERR_MEMORY_COPY;
goto ERR;
}
usedLen = usedLen + keyType->length;
if (memcpy_s(keyAliasBuff.val + usedLen, totalLen - usedLen, authId->val, authId->length) != EOK) {
LOGE("Copy authId failed.");
res = HC_ERR_MEMORY_COPY;
goto ERR;
}
res = GetLoaderInstance()->sha256(&keyAliasBuff, keyAliasHash);
if (res != HC_SUCCESS) {
LOGE("Sha256 failed.");
goto ERR;
}
ERR:
HcFree(keyAliasBuff.val);
return res;
}
static int32_t CombineKeyAliasForPake(
const Uint8Buff *serviceId, const Uint8Buff *keyType, const Uint8Buff *authId, Uint8Buff *outKeyAlias)
{
int32_t res;
Uint8Buff keyAliasHash = { NULL, SHA256_LEN };
char *outKeyAliasHex = NULL;
if (outKeyAlias->length != SHA256_LEN * BYTE_TO_HEX_OPER_LENGTH) {
res = HC_ERR_INVALID_LEN;
goto ERR;
}
keyAliasHash.val = (uint8_t *)HcMalloc(keyAliasHash.length, 0);
if (keyAliasHash.val == NULL) {
LOGE("Malloc keyAliasHash failed");
res = HC_ERR_ALLOC_MEMORY;
goto ERR;
}
res = CombineKeyAlias(serviceId, keyType, authId, &keyAliasHash);
if (res != HC_SUCCESS) {
LOGE("CombineKeyAlias failed.");
goto ERR;
}
uint32_t outKeyAliasHexLen = keyAliasHash.length * BYTE_TO_HEX_OPER_LENGTH + 1;
outKeyAliasHex = (char *)HcMalloc(outKeyAliasHexLen, 0);
res = ByteToHexString(keyAliasHash.val, keyAliasHash.length, outKeyAliasHex, outKeyAliasHexLen);
if (res != HC_SUCCESS) {
LOGE("ByteToHexString failed");
goto ERR;
}
if (memcpy_s(outKeyAlias->val, outKeyAlias->length, outKeyAliasHex, strlen(outKeyAliasHex)) != EOK) {
LOGE("memcpy outkeyalias failed.");
res = HC_ERR_MEMORY_COPY;
goto ERR;
}
ERR:
HcFree(keyAliasHash.val);
HcFree(outKeyAliasHex);
return res;
}
static int32_t GenerateKeyAliasInner(
const char *pkgName, const char *serviceType, const char *authId, int keyAliasType, Uint8Buff *outKeyAlias)
{
CHECK_PTR_RETURN_ERROR_CODE(pkgName, "pkgName");
CHECK_PTR_RETURN_ERROR_CODE(serviceType, "serviceType");
CHECK_PTR_RETURN_ERROR_CODE(authId, "authId");
CHECK_PTR_RETURN_ERROR_CODE(outKeyAlias, "outKeyAlias");
if (strlen(pkgName) == 0 || strlen(serviceType) == 0 || strlen(authId) == 0) {
LOGE("Invalid zero length params exist.");
return HC_ERR_INVALID_LEN;
}
Uint8Buff pkgNameBuff = { (uint8_t *)pkgName, strlen(pkgName) };
Uint8Buff serviceTypeBuff = { (uint8_t *)serviceType, strlen(serviceType) };
Uint8Buff authIdBuff = { NULL, HcStrlen(authId) };
authIdBuff.val = (uint8_t *)HcMalloc(authIdBuff.length, 0);
if (authIdBuff.val == NULL) {
LOGE("Failed to allocate authIdBuff memory!");
return HC_ERR_ALLOC_MEMORY;
}
if (memcpy_s(authIdBuff.val, authIdBuff.length, authId, authIdBuff.length) != EOK) {
LOGE("Failed to copy authId!");
HcFree(authIdBuff.val);
return HC_ERR_MEMORY_COPY;
}
if (pkgNameBuff.length > PACKAGE_NAME_MAX_LEN || serviceTypeBuff.length > SERVICE_TYPE_MAX_LEN ||
authIdBuff.length > AUTH_ID_MAX_LEN || keyAliasType >= KEY_ALIAS_TYPE_END) {
LOGE("Out of length params exist.");
HcFree(authIdBuff.val);
return HC_ERR_INVALID_LEN;
}
int32_t res;
Uint8Buff serviceId = { NULL, SHA256_LEN };
serviceId.val = (uint8_t *)HcMalloc(serviceId.length, 0);
if (serviceId.val == NULL) {
LOGE("Malloc for serviceId failed.");
HcFree(authIdBuff.val);
HcFree(serviceId.val);
return HC_ERR_ALLOC_MEMORY;
}
res = CombineServiceId(&pkgNameBuff, &serviceTypeBuff, &serviceId);
if (res != HC_SUCCESS) {
LOGE("CombineServiceId failed, res: %x.", res);
HcFree(authIdBuff.val);
HcFree(serviceId.val);
return res;
}
Uint8Buff keyTypeBuff = { GetKeyTypePair(keyAliasType), KEY_TYPE_PAIR_LEN };
res = CombineKeyAliasForPake(&serviceId, &keyTypeBuff, &authIdBuff, outKeyAlias);
if (res != HC_SUCCESS) {
LOGE("CombineKeyAlias failed, keyType: %d, res: %d", keyAliasType, res);
HcFree(authIdBuff.val);
HcFree(serviceId.val);
return res;
}
HcFree(authIdBuff.val);
HcFree(serviceId.val);
return res;
}
static void FreeCredParam(CredentialRequestParamT *param)
{
if (param) {
HcFree(param->deviceId);
param->deviceId = NULL;
HcFree(param->serviceType);
param->serviceType = NULL;
if (param->publicKey) {
if (param->publicKey->val) {
HcFree(param->publicKey->val);
}
HcFree(param->publicKey);
param->publicKey = NULL;
}
HcFree(param);
param = NULL;
}
}
static int32_t DecodeServiceTypeAndPublicKey(CredentialRequestParamT *param, CJson *reqJson)
{
if (!param || !reqJson) {
LOGE("reqJson and param must not null ! ");
return HC_ERR_INVALID_PARAMS;
}
const char *serviceType = GetStringFromJson(reqJson, FIELD_SERVICE_TYPE);
if (serviceType == NULL) {
param->serviceType = strdup(DEFAULT_SERVICE_TYPE);
} else {
param->serviceType = strdup(serviceType);
}
const char *publicKeyStr = GetStringFromJson(reqJson, FIELD_PUBLIC_KEY);
if (publicKeyStr != NULL && HcStrlen(publicKeyStr) > 0) {
if (HcStrlen(publicKeyStr) > PAKE_ED25519_KEY_STR_LEN) {
LOGE("public key longer then %d.", PAKE_ED25519_KEY_STR_LEN);
return HC_ERR_INVALID_LEN;
}
param->publicKey = (Uint8Buff *)HcMalloc(sizeof(Uint8Buff), 0);
int32_t res = InitUint8Buff(param->publicKey, PAKE_ED25519_KEY_PAIR_LEN);
if (res != HC_SUCCESS) {
LOGE("allocate publicKey memory fail. res: %d", res);
return HC_ERR_ALLOC_MEMORY;
}
if (GetByteFromJson(reqJson, FIELD_PUBLIC_KEY, param->publicKey->val, param->publicKey->length) !=
HC_SUCCESS) {
LOGE("get authPkC from reqJson fail.");
return HC_ERR_JSON_GET;
} else {
LOGI("decode publicKey success.");
}
} else {
param->publicKey = NULL;
}
return HC_SUCCESS;
}
static CredentialRequestParamT *DecodeRequestParam(const char *reqJsonStr)
{
if (!reqJsonStr) {
LOGE("reqJsonStr must not null ! ");
return NULL;
}
CredentialRequestParamT *param = (CredentialRequestParamT *)HcMalloc(sizeof(CredentialRequestParamT), 0);
if (param == NULL) {
LOGE("Failed to ALLOC!");
return NULL;
}
CJson *json = CreateJsonFromString(reqJsonStr);
if (json == NULL) {
LOGE("Failed to create json from string!");
FreeCredParam(param);
param = NULL;
goto ERR;
}
if (GetIntFromJson(json, FIELD_OS_ACCOUNT_ID, &param->osAccountId) != HC_SUCCESS) {
LOGE("Failed to get osAccountId from reqJsonStr!");
FreeCredParam(param);
param = NULL;
goto ERR;
}
if (GetIntFromJson(json, FIELD_ACQURIED_TYPE, &param->acquireType) != HC_SUCCESS) {
LOGE("Failed to get acquireType from reqJsonStr!");
FreeCredParam(param);
param = NULL;
goto ERR;
}
if (GetIntFromJson(json, FIELD_CRED_OP_FLAG, &param->flag) != HC_SUCCESS) {
LOGI("reqJsonStr not contains flag!");
}
const char *deviceId = GetStringFromJson(json, FIELD_DEVICE_ID);
if (deviceId == NULL) {
LOGE("Failed to get deviceId from reqJsonStr!");
FreeCredParam(param);
param = NULL;
goto ERR;
} else {
param->deviceId = strdup(deviceId);
}
if (DecodeServiceTypeAndPublicKey(param, json) != HC_SUCCESS) {
LOGE("Failed to DecodeServiceTypeAndPublicKey from reqJsonStr!");
goto ERR;
}
ERR:
FreeJson(json);
return param;
}
static int32_t PackPublicKeyToJson(
CJson *out, int32_t osAccountId, int32_t keyType, const char *authId, const char *serviceType)
{
osAccountId = DevAuthGetRealOsAccountLocalId(osAccountId);
if ((authId == NULL) || (osAccountId == INVALID_OS_ACCOUNT)) {
LOGE("Invalid input parameters!");
return HC_ERR_INVALID_PARAMS;
}
Uint8Buff authIdBuff = { (uint8_t *)authId, HcStrlen(authId) };
uint8_t returnPkBytes[PUBLIC_KEY_MAX_LENGTH] = { 0 };
Uint8Buff returnPkBuff = { returnPkBytes, PUBLIC_KEY_MAX_LENGTH };
int32_t res = GetStandardTokenManagerInstance()->getPublicKey(
DEFAULT_PACKAGE_NAME, serviceType, &authIdBuff, keyType, &returnPkBuff);
if (res != HC_SUCCESS) {
LOGE("Failed to getPublicKey!");
return HC_ERR_LOCAL_IDENTITY_NOT_EXIST;
}
char returnPkHexStr[SHA256_LEN * BYTE_TO_HEX_OPER_LENGTH + 1] = { 0 };
res = ByteToHexString(returnPkBuff.val, returnPkBuff.length, returnPkHexStr, sizeof(returnPkHexStr));
if (res != HC_SUCCESS) {
LOGE("Failed to get hex str for pk!");
return HC_ERR_HASH_FAIL;
}
if (AddStringToJson(out, FIELD_PUBLIC_KEY, (const char *)returnPkHexStr) != HC_SUCCESS) {
LOGE("Failed to ADD pubKey to returnData!");
return HC_ERR_JSON_ADD;
}
return HC_SUCCESS;
}
static char *PackResultToJson(CJson *out, int32_t res)
{
if (out == NULL) {
LOGE("param is null !");
return NULL;
}
if (AddIntToJson(out, FIELD_CRED_OP_RESULT, res) != HC_SUCCESS) {
LOGE("Failed to set result to json");
return NULL;
}
return PackJsonToString(out);
}
static int32_t QueryCredential(const char *reqJsonStr, char **returnData)
{
int32_t res;
CJson *out = CreateJson();
if (out == NULL) {
LOGE("Failed to CreateJson!");
return HC_ERR_JSON_CREATE;
}
CredentialRequestParamT *param = DecodeRequestParam(reqJsonStr);
if (param == NULL) {
LOGE("Failed to DecodeCredParam from reqJsonStr!");
res = HC_ERR_JSON_GET;
goto ERR;
}
int32_t osAccountId = param->osAccountId;
int32_t keyType = (param->acquireType == P2P_BIND) ? KEY_ALIAS_P2P_AUTH : param->acquireType;
const char *serviceType = param->serviceType;
const char *authId = param->deviceId;
int32_t flag = param->flag;
osAccountId = DevAuthGetRealOsAccountLocalId(osAccountId);
if ((authId == NULL) || (osAccountId == INVALID_OS_ACCOUNT)) {
LOGE("Invalid input parameters!");
res = HC_ERR_INVALID_PARAMS;
goto ERR;
}
const AlgLoader *loader = GetLoaderInstance();
uint8_t keyAliasVal[PAKE_KEY_ALIAS_LEN] = { 0 };
Uint8Buff keyAliasBuff = { keyAliasVal, PAKE_KEY_ALIAS_LEN };
res = GenerateKeyAliasInner(DEFAULT_PACKAGE_NAME, serviceType, authId, keyType, &keyAliasBuff);
if (res != HC_SUCCESS) {
LOGE("Failed to generate identity keyPair alias!");
goto ERR;
}
LOGI("KeyPair alias(HEX): %x%x%x%x****.", keyAliasVal[DEV_AUTH_ZERO], keyAliasVal[DEV_AUTH_ONE],
keyAliasVal[DEV_AUTH_TWO], keyAliasVal[DEV_AUTH_THREE]);
res = loader->checkKeyExist(&keyAliasBuff);
if (res != HC_SUCCESS) {
LOGD("Key pair not exist.");
res = HC_ERR_LOCAL_IDENTITY_NOT_EXIST;
goto ERR;
}
if (RETURN_FLAG_PUBLIC_KEY == flag) {
res = PackPublicKeyToJson(out, osAccountId, keyType, authId, serviceType);
if (res != HC_SUCCESS) {
LOGD("PackPublicKeyToJson failed");
goto ERR;
}
}
ERR:
if (returnData) {
*returnData = PackResultToJson(out, res);
}
FreeJson(out);
FreeCredParam(param);
return res;
}
static int32_t GenarateCredential(const char *reqJsonStr, char **returnData)
{
int32_t res;
CJson *out = CreateJson();
if (out == NULL) {
LOGE("Failed to CreateJson!");
return HC_ERR_JSON_CREATE;
}
CredentialRequestParamT *param = DecodeRequestParam(reqJsonStr);
if (param == NULL) {
LOGE("Failed to DecodeCredParam from reqJsonStr!");
res = HC_ERR_INVALID_PARAMS;
goto ERR;
}
int32_t osAccountId = param->osAccountId;
int32_t keyType = (param->acquireType == P2P_BIND) ? KEY_ALIAS_P2P_AUTH : param->acquireType;
const char *serviceType = param->serviceType;
const char *authId = param->deviceId;
int32_t flag = param->flag;
osAccountId = DevAuthGetRealOsAccountLocalId(osAccountId);
if ((authId == NULL) || (osAccountId == INVALID_OS_ACCOUNT)) {
LOGE("Invalid input parameters!");
res = HC_ERR_INVALID_PARAMS;
goto ERR;
}
const AlgLoader *loader = GetLoaderInstance();
uint8_t keyAliasVal[PAKE_KEY_ALIAS_LEN] = { 0 };
Uint8Buff keyAliasBuff = { keyAliasVal, PAKE_KEY_ALIAS_LEN };
res = GenerateKeyAliasInner(DEFAULT_PACKAGE_NAME, serviceType, authId, keyType, &keyAliasBuff);
if (res != HC_SUCCESS) {
LOGE("Failed to generate identity keyPair alias!");
goto ERR;
}
LOGI("KeyPair alias(HEX): %x%x%x%x****.", keyAliasVal[DEV_AUTH_ZERO], keyAliasVal[DEV_AUTH_ONE],
keyAliasVal[DEV_AUTH_TWO], keyAliasVal[DEV_AUTH_THREE]);
res = loader->checkKeyExist(&keyAliasBuff);
if (res == HC_SUCCESS) {
LOGD("Key pair already exist.");
res = HC_ERR_IDENTITY_DUPLICATED;
goto ERR;
}
Uint8Buff authIdBuff = { (uint8_t *)authId, HcStrlen(authId) };
res = GetStandardTokenManagerInstance()->registerLocalIdentity(
DEFAULT_PACKAGE_NAME, serviceType, &authIdBuff, keyType);
if (res != HC_SUCCESS) {
LOGE("Failed to registerLocalIdentity!");
goto ERR;
}
if (RETURN_FLAG_PUBLIC_KEY == flag) {
res = PackPublicKeyToJson(out, osAccountId, keyType, authId, serviceType);
if (res != HC_SUCCESS) {
LOGE("PackPublicKeyToJson failed");
goto ERR;
}
}
ERR:
if (returnData) {
*returnData = PackResultToJson(out, res);
}
FreeJson(out);
FreeCredParam(param);
return res;
}
static int32_t ComputeAndSavePsk(const char *peerServiceType, const char *peerAuthId, int keyType)
{
uint8_t selfKeyAliasVal[PAKE_KEY_ALIAS_LEN] = { 0 };
Uint8Buff selfKeyAlias = { selfKeyAliasVal, PAKE_KEY_ALIAS_LEN };
uint8_t peerKeyAliasVal[PAKE_KEY_ALIAS_LEN] = { 0 };
Uint8Buff peerKeyAlias = { peerKeyAliasVal, PAKE_KEY_ALIAS_LEN };
char selfAuthId[INPUT_UDID_LEN] = { 0 };
int32_t res = HcGetUdid((uint8_t *)selfAuthId, INPUT_UDID_LEN);
if (res != HC_SUCCESS) {
LOGE("Failed to get local udid! res: %d", res);
return HC_ERR_DB;
}
res = GenerateKeyAliasInner(DEFAULT_PACKAGE_NAME, DEFAULT_SERVICE_TYPE, selfAuthId, keyType, &selfKeyAlias);
if (res != HC_SUCCESS) {
LOGE("generateKeyAlias self failed");
return res;
}
LOGI("selfKeyAlias(HEX): %x%x%x%x****", selfKeyAliasVal[DEV_AUTH_ZERO], selfKeyAliasVal[DEV_AUTH_ONE],
selfKeyAliasVal[DEV_AUTH_TWO], selfKeyAliasVal[DEV_AUTH_THREE]);
res = GenerateKeyAliasInner(DEFAULT_PACKAGE_NAME, peerServiceType, peerAuthId, keyType, &peerKeyAlias);
if (res != HC_SUCCESS) {
LOGE("generateKeyAlias peer failed");
return res;
}
LOGI("peerKeyAlias(HEX): %x%x%x%x****", peerKeyAliasVal[DEV_AUTH_ZERO], peerKeyAliasVal[DEV_AUTH_ONE],
peerKeyAliasVal[DEV_AUTH_TWO], peerKeyAliasVal[DEV_AUTH_THREE]);
res = GetLoaderInstance()->checkKeyExist(&selfKeyAlias);
if (res != HC_SUCCESS) {
LOGE("self auth keyPair not exist .");
return res;
}
res = GetLoaderInstance()->checkKeyExist(&peerKeyAlias);
if (res != HC_SUCCESS) {
LOGE("peer auth pubKey not exist");
return res;
}
uint8_t sharedKeyAliasVal[PAKE_KEY_ALIAS_LEN] = { 0 };
Uint8Buff sharedKeyAlias = { sharedKeyAliasVal, PAKE_KEY_ALIAS_LEN };
res = GenerateKeyAliasInner(DEFAULT_PACKAGE_NAME, peerServiceType, peerAuthId, KEY_ALIAS_PSK, &sharedKeyAlias);
if (res != HC_SUCCESS) {
LOGE("generateKeyAlias psk failed");
return res;
}
LOGI("psk alias(HEX): %x%x%x%x****", sharedKeyAliasVal[DEV_AUTH_ZERO], sharedKeyAliasVal[DEV_AUTH_ONE],
sharedKeyAliasVal[DEV_AUTH_TWO], sharedKeyAliasVal[DEV_AUTH_THREE]);
KeyBuff selfKeyAliasBuff = { selfKeyAlias.val, selfKeyAlias.length, true };
KeyBuff peerKeyAliasBuff = { peerKeyAlias.val, peerKeyAlias.length, true };
return GetLoaderInstance()->agreeSharedSecretWithStorage(
&selfKeyAliasBuff, &peerKeyAliasBuff, ED25519, PAKE_PSK_LEN, &sharedKeyAlias);
}
static int32_t ImportCredential(const char *reqJsonStr, char **returnData)
{
int32_t res;
CJson *out = CreateJson();
if (out == NULL) {
LOGE("Failed to CreateJson!");
return HC_ERR_JSON_CREATE;
}
CredentialRequestParamT *param = DecodeRequestParam(reqJsonStr);
if (param == NULL || param->publicKey == NULL) {
LOGE("Failed to DecodeCredParam from reqJsonStr!");
res = HC_ERR_JSON_GET;
goto ERR;
}
int32_t osAccountId = param->osAccountId;
int32_t keyType = (param->acquireType == P2P_BIND) ? KEY_ALIAS_P2P_AUTH : param->acquireType;
const char *serviceType = param->serviceType;
const char *authId = param->deviceId;
Uint8Buff *publicKey = param->publicKey;
osAccountId = DevAuthGetRealOsAccountLocalId(osAccountId);
if ((authId == NULL) || (osAccountId == INVALID_OS_ACCOUNT)) {
LOGE("Invalid input parameters!");
return HC_ERR_INVALID_PARAMS;
}
const AlgLoader *loader = GetLoaderInstance();
uint8_t keyAliasVal[PAKE_KEY_ALIAS_LEN] = { 0 };
Uint8Buff keyAliasBuff = { keyAliasVal, PAKE_KEY_ALIAS_LEN };
res = GenerateKeyAliasInner(DEFAULT_PACKAGE_NAME, serviceType, authId, keyType, &keyAliasBuff);
if (res != HC_SUCCESS) {
LOGE("Failed to generate identity keyPair alias!");
goto ERR;
}
LOGI("KeyPair alias(HEX): %x%x%x%x****.", keyAliasVal[DEV_AUTH_ZERO], keyAliasVal[DEV_AUTH_ONE],
keyAliasVal[DEV_AUTH_TWO], keyAliasVal[DEV_AUTH_THREE]);
res = loader->checkKeyExist(&keyAliasBuff);
if (res == HC_SUCCESS) {
LOGD("Key pair already exist.");
res = HC_ERR_IDENTITY_DUPLICATED;
goto ERR;
}
Uint8Buff authIdBuff = { (uint8_t *)authId, strlen(authId) };
ExtraInfo exInfo = { authIdBuff, keyType, PAIR_TYPE_BIND };
res = loader->importPublicKey(&keyAliasBuff, publicKey, ED25519, &exInfo);
if (res != HC_SUCCESS) {
LOGE("Failed to importPublicKey!");
goto ERR;
}
res = ComputeAndSavePsk(serviceType, authId, keyType);
if (res != HC_SUCCESS) {
LOGE("Failed to ComputeAndSavePsk!");
goto ERR;
}
ERR:
if (returnData) {
*returnData = PackResultToJson(out, res);
}
FreeJson(out);
FreeCredParam(param);
return res;
}
static int32_t DeleteCredential(const char *reqJsonStr, char **returnData)
{
int32_t res;
CJson *out = CreateJson();
if (out == NULL) {
LOGE("Failed to CreateJson!");
return HC_ERR_JSON_CREATE;
}
CredentialRequestParamT *param = DecodeRequestParam(reqJsonStr);
if (param == NULL) {
LOGE("Failed to DecodeCredParam from reqJsonStr!");
res = HC_ERR_JSON_GET;
goto ERR;
}
int32_t osAccountId = param->osAccountId;
int32_t keyType = (param->acquireType == P2P_BIND) ? KEY_ALIAS_P2P_AUTH : param->acquireType;
const char *serviceType = param->serviceType;
const char *authId = param->deviceId;
osAccountId = DevAuthGetRealOsAccountLocalId(osAccountId);
if ((authId == NULL) || (osAccountId == INVALID_OS_ACCOUNT)) {
LOGE("Invalid input parameters!");
res = HC_ERR_INVALID_PARAMS;
goto ERR;
}
Uint8Buff authIdBuff = { (uint8_t *)authId, strlen(authId) };
res = GetStandardTokenManagerInstance()->unregisterLocalIdentity(
DEFAULT_PACKAGE_NAME, serviceType, &authIdBuff, KEY_ALIAS_PSK);
if (res != HC_SUCCESS) {
LOGE("Failed to delete psk!");
goto ERR;
}
LOGI("Psk deleted successfully!");
res = GetStandardTokenManagerInstance()->unregisterLocalIdentity(
DEFAULT_PACKAGE_NAME, serviceType, &authIdBuff, keyType);
if (res != HC_SUCCESS) {
LOGE("Failed to delete identity keyPair!");
goto ERR;
}
LOGI("PubKey deleted successfully!");
ERR:
if (returnData) {
*returnData = PackResultToJson(out, res);
}
FreeJson(out);
FreeCredParam(param);
return res;
}
static const CredentialOperator g_credentialOperator = {
.queryCredential = QueryCredential,
.genarateCredential = GenarateCredential,
.importCredential = ImportCredential,
.deleteCredential = DeleteCredential,
};
const CredentialOperator *GetCredentialOperator(void)
{
return &g_credentialOperator;
}
@@ -0,0 +1,189 @@
/*
* 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 "group_auth_data_operation.h"
#include "hc_dev_info.h"
#include "hc_log.h"
#include "hc_vector.h"
#include "identity_manager.h"
static void UpperToLowercase(Uint8Buff *hex)
{
for (uint32_t i = 0; i < hex->length; i++) {
if (hex->val[i] >= 'A' && hex->val[i] <= 'F') {
hex->val[i] += ASCII_CASE_DIFFERENCE_VALUE;
}
}
}
int32_t ConvertPsk(const Uint8Buff *srcPsk, Uint8Buff *sharedSecret)
{
uint32_t len = PAKE_PSK_LEN * BYTE_TO_HEX_OPER_LENGTH;
sharedSecret->val = (uint8_t *)HcMalloc(len + 1, 0);
if (sharedSecret->val == NULL) {
LOGE("Failed to alloc memory for sharedSecret!");
return HC_ERR_ALLOC_MEMORY;
}
if (ByteToHexString(srcPsk->val, srcPsk->length, (char *)sharedSecret->val, len + 1) != HC_SUCCESS) {
LOGE("Convert psk from byte to hex string failed!");
HcFree(sharedSecret->val);
return HC_ERR_CONVERT_FAILED;
}
sharedSecret->length = len;
(void)UpperToLowercase(sharedSecret);
return HC_SUCCESS;
}
int32_t SetPreSharedUrlForProof(const char *urlStr, Uint8Buff *preSharedUrl)
{
uint32_t urlLen = HcStrlen(urlStr);
preSharedUrl->val = (uint8_t *)HcMalloc(urlLen + 1, 0);
if (preSharedUrl->val == NULL) {
LOGE("Failed to alloc preSharedUrl memory!");
return HC_ERR_ALLOC_MEMORY;
}
if (memcpy_s(preSharedUrl->val, urlLen + 1, urlStr, urlLen) != EOK) {
LOGE("Failed to copy url string to preSharedUrl");
HcFree(preSharedUrl->val);
preSharedUrl->val = NULL;
return HC_ERR_MEMORY_COPY;
}
preSharedUrl->length = urlLen + 1;
return HC_SUCCESS;
}
CJson *CreateCredUrlJson(int32_t credentailType, int32_t keyType, int32_t trustType)
{
CJson *urlJson = CreateJson();
if (urlJson == NULL) {
LOGE("Failed to create url json!");
return NULL;
}
if (AddIntToJson(urlJson, PRESHARED_URL_CREDENTIAL_TYPE, credentailType) != HC_SUCCESS) {
LOGE("Failed to add credential type!");
FreeJson(urlJson);
return NULL;
}
if (AddIntToJson(urlJson, PRESHARED_URL_KEY_TYPE, keyType) != HC_SUCCESS) {
LOGE("Failed to add key type!");
FreeJson(urlJson);
return NULL;
}
if (AddIntToJson(urlJson, PRESHARED_URL_TRUST_TYPE, trustType) != HC_SUCCESS) {
LOGE("Failed to add trust type!");
FreeJson(urlJson);
return NULL;
}
return urlJson;
}
#if 1
IMPLEMENT_HC_VECTOR(ProtocolEntityVec, ProtocolEntity *, 1)
IMPLEMENT_HC_VECTOR(IdentityInfoVec, IdentityInfo *, 1)
int32_t GetSelfDeviceEntry(int32_t osAccountId, const char *groupId, TrustedDeviceEntry *deviceEntry)
{
char selfUdid[INPUT_UDID_LEN] = { 0 };
int32_t ret = HcGetUdid((uint8_t *)selfUdid, INPUT_UDID_LEN);
if (ret != HC_SUCCESS) {
LOGE("Failed to get local udid!");
return ret;
}
return GaGetTrustedDeviceEntryById(osAccountId, selfUdid, true, groupId, deviceEntry);
}
const char *GetPeerDevIdFromJson(const CJson *in, bool *isUdid)
{
const char *deviceId = GetStringFromJson(in, FIELD_PEER_UDID);
if (deviceId != NULL) {
*isUdid = true;
return deviceId;
}
return GetStringFromJson(in, FIELD_PEER_AUTH_ID);
}
int32_t GetPeerDeviceEntry(
int32_t osAccountId, const CJson *in, const char *groupId, TrustedDeviceEntry *returnDeviceEntry)
{
bool isUdid = false;
const char *peerDeviceId = GetPeerDevIdFromJson(in, &isUdid);
if (peerDeviceId == NULL) {
LOGE("Failed to get peer deviceId!");
return HC_ERR_JSON_GET;
}
return GaGetTrustedDeviceEntryById(osAccountId, peerDeviceId, isUdid, groupId, returnDeviceEntry);
}
void FreeBuffData(Uint8Buff *buff)
{
if (buff == NULL) {
return;
}
HcFree(buff->val);
buff->val = NULL;
buff->length = 0;
}
IdentityInfo *CreateIdentityInfo(void)
{
IdentityInfo *info = (IdentityInfo *)HcMalloc(sizeof(IdentityInfo), 0);
if (info == NULL) {
LOGE("Failed to alloc memory for identity info!");
return NULL;
}
info->protocolVec = CreateProtocolEntityVec();
return info;
}
void DestroyIdentityInfo(IdentityInfo *info)
{
if (info == NULL) {
return;
}
FreeBuffData(&info->proof.preSharedUrl);
FreeBuffData(&info->proof.certInfo.pkInfoStr);
FreeBuffData(&info->proof.certInfo.pkInfoSignature);
ClearProtocolEntityVec(&info->protocolVec);
HcFree(info);
}
void ClearIdentityInfoVec(IdentityInfoVec *vec)
{
uint32_t index;
IdentityInfo **info;
FOR_EACH_HC_VECTOR(*vec, index, info)
{
DestroyIdentityInfo(*info);
}
DESTROY_HC_VECTOR(IdentityInfoVec, vec);
}
void ClearProtocolEntityVec(ProtocolEntityVec *vec)
{
uint32_t index;
ProtocolEntity **entity;
FOR_EACH_HC_VECTOR(*vec, index, entity)
{
HcFree(*entity);
}
DESTROY_HC_VECTOR(ProtocolEntityVec, vec);
}
#endif
@@ -0,0 +1,808 @@
/*
* 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 "account_auth_plugin_proxy.h"
#include "account_related_group_auth.h"
#include "alg_defs.h"
#include "alg_loader.h"
#include "cert_operation.h"
#include "group_auth_data_operation.h"
#include "group_operation_common.h"
#include "hc_log.h"
#include "identity_manager.h"
static int32_t GetAccountRelatedCandidateGroups(
int32_t osAccountId, const CJson *in, bool isDeviceLevel, GroupEntryVec *vec)
{
BaseGroupAuth *groupAuth = GetAccountRelatedGroupAuth();
if (groupAuth == NULL) {
return HC_ERR_NULL_PTR;
}
QueryGroupParams queryParams = InitQueryGroupParams();
if (!isDeviceLevel) {
queryParams.groupVisibility = GROUP_VISIBILITY_PUBLIC;
}
((AccountRelatedGroupAuth *)groupAuth)->getAccountCandidateGroup(osAccountId, in, &queryParams, vec);
// All return success, only notify the plugin.
if (HasAccountAuthPlugin() == HC_SUCCESS && vec->size(vec) == 0) {
CJson *input = CreateJson();
if (input == NULL) {
return HC_SUCCESS;
}
CJson *output = CreateJson();
if (output == NULL) {
FreeJson(input);
return HC_SUCCESS;
}
int32_t ret = ExcuteCredMgrCmd(osAccountId, QUERY_SELF_CREDENTIAL_INFO, input, output);
if (ret != HC_SUCCESS) {
LOGE("Account cred is empty.");
}
FreeJson(input);
FreeJson(output);
}
return HC_SUCCESS;
}
static int32_t GetAccountUnrelatedCandidateGroups(int32_t osAccountId, bool isDeviceLevel, GroupEntryVec *vec)
{
QueryGroupParams queryParams = InitQueryGroupParams();
queryParams.groupType = PEER_TO_PEER_GROUP;
if (!isDeviceLevel) {
queryParams.groupVisibility = GROUP_VISIBILITY_PUBLIC;
}
return QueryGroups(osAccountId, &queryParams, vec);
}
static void GetGroupInfoByGroupId(int32_t osAccountId, const char *groupId, GroupEntryVec *groupEntryVec)
{
QueryGroupParams queryParams = InitQueryGroupParams();
queryParams.groupId = groupId;
int32_t ret = QueryGroups(osAccountId, &queryParams, groupEntryVec);
if (ret != HC_SUCCESS) {
LOGE("Failed to query groups for groupId: %s!", groupId);
}
}
static void GetCandidateGroups(int32_t osAccountId, const CJson *in, GroupEntryVec *groupEntryVec)
{
bool isDeviceLevel = false;
(void)GetBoolFromJson(in, FIELD_IS_DEVICE_LEVEL, &isDeviceLevel);
int32_t ret = GetAccountRelatedCandidateGroups(osAccountId, in, isDeviceLevel, groupEntryVec);
if (ret != HC_SUCCESS) {
LOGE("Failed to get account related groups!");
}
ret = GetAccountUnrelatedCandidateGroups(osAccountId, isDeviceLevel, groupEntryVec);
if (ret != HC_SUCCESS) {
LOGE("Failed to get p2p groups!");
}
}
static bool IsDeviceInGroup(
int32_t osAccountId, int32_t groupType, const char *deviceId, const char *groupId, bool isUdid)
{
if (isUdid) {
return GaIsDeviceInGroup(groupType, osAccountId, deviceId, NULL, groupId);
} else {
return GaIsDeviceInGroup(groupType, osAccountId, NULL, deviceId, groupId);
}
}
static int32_t SetProtocolsToIdentityInfo(int32_t keyType, IdentityInfo *info)
{
if (keyType == KEY_TYPE_ASYM) {
#ifdef ENABLE_P2P_AUTH_EC_SPEKE
ProtocolEntity *entity = (ProtocolEntity *)HcMalloc(sizeof(ProtocolEntity), 0);
if (entity == NULL) {
LOGE("Failed to alloc memory for entity!");
return HC_ERR_ALLOC_MEMORY;
}
entity->protocolType = ALG_EC_SPEKE;
info->protocolVec.pushBack(&info->protocolVec, (const ProtocolEntity **)&entity);
#else
(void)info;
#endif
} else {
#ifdef ENABLE_P2P_AUTH_ISO
ProtocolEntity *entity = (ProtocolEntity *)HcMalloc(sizeof(ProtocolEntity), 0);
if (entity == NULL) {
LOGE("Failed to alloc memory for entity!");
return HC_ERR_ALLOC_MEMORY;
}
entity->protocolType = ALG_ISO;
info->protocolVec.pushBack(&info->protocolVec, (const ProtocolEntity **)&entity);
#else
(void)info;
#endif
}
return HC_SUCCESS;
}
static bool IsP2pAuthTokenExist(const TrustedDeviceEntry *deviceEntry)
{
Uint8Buff pkgNameBuff = { (uint8_t *)GROUP_MANAGER_PACKAGE_NAME, strlen(GROUP_MANAGER_PACKAGE_NAME) };
const char *serviceType = StringGet(&deviceEntry->serviceType);
Uint8Buff serviceTypeBuff = { (uint8_t *)serviceType, strlen(serviceType) };
const char *peerAuthId = StringGet(&deviceEntry->authId);
Uint8Buff peerAuthIdBuff = { (uint8_t *)peerAuthId, strlen(peerAuthId) };
uint8_t keyAliasVal[ISO_KEY_ALIAS_LEN] = { 0 };
Uint8Buff keyAlias = { keyAliasVal, ISO_KEY_ALIAS_LEN };
int32_t ret =
GenerateKeyAlias(&pkgNameBuff, &serviceTypeBuff, KEY_ALIAS_AUTH_TOKEN, &peerAuthIdBuff, &keyAlias);
if (ret != HC_SUCCESS) {
LOGE("Failed to generate key alias!");
return false;
}
ret = GetLoaderInstance()->checkKeyExist(&keyAlias);
if (ret != HC_SUCCESS) {
LOGE("auth token not exist!");
return false;
}
return true;
}
static int32_t GetAccountUnrelatedIdentityInfo(
int32_t osAccountId, const char *groupId, const char *deviceId, bool isUdid, IdentityInfo *info)
{
TrustedDeviceEntry *deviceEntry = CreateDeviceEntry();
if (deviceEntry == NULL) {
LOGE("Failed to create deviceEntry!");
return HC_ERR_ALLOC_MEMORY;
}
int32_t ret = GaGetTrustedDeviceEntryById(osAccountId, deviceId, isUdid, groupId, deviceEntry);
if (ret != HC_SUCCESS) {
LOGE("Failed to get device entry!");
DestroyDeviceEntry(deviceEntry);
return ret;
}
int32_t keyType = IsP2pAuthTokenExist(deviceEntry) ? KEY_TYPE_SYM : KEY_TYPE_ASYM;
DestroyDeviceEntry(deviceEntry);
CJson *urlJson = CreateCredUrlJson(PRE_SHARED, keyType, TRUST_TYPE_P2P);
if (!urlJson) {
LOGE("Failed to create CredUrlJson info!");
return HC_ERR_ALLOC_MEMORY;
}
if (AddStringToJson(urlJson, FIELD_GROUP_ID, groupId) != HC_SUCCESS) {
LOGE("Failed to add group id!");
FreeJson(urlJson);
return HC_ERR_JSON_ADD;
}
char *urlStr = PackJsonToString(urlJson);
FreeJson(urlJson);
if (urlStr == NULL) {
LOGE("Failed to pack url json to string!");
return HC_ERR_PACKAGE_JSON_TO_STRING_FAIL;
}
ret = SetPreSharedUrlForProof(urlStr, &info->proof.preSharedUrl);
FreeJsonString(urlStr);
if (ret != HC_SUCCESS) {
LOGE("Failed to set preSharedUrl of proof!");
return ret;
}
ret = SetProtocolsToIdentityInfo(keyType, info);
if (ret != HC_SUCCESS) {
LOGE("Failed to set protocols!");
return ret;
}
info->proofType = PRE_SHARED;
if (ret != HC_SUCCESS) {
LOGE("Failed to get p2p identity by key type!");
}
return ret;
}
static int32_t GetIdentityInfo(int32_t osAccountId, const TrustedGroupEntry *groupEntry, const char *deviceId,
bool isUdid, IdentityInfo **returnInfo)
{
IdentityInfo *info = CreateIdentityInfo();
if (info == NULL) {
LOGE("Failed to create identity info!");
return HC_ERR_ALLOC_MEMORY;
}
int32_t ret;
const char *groupId = StringGet(&groupEntry->id);
if (groupEntry->type == PEER_TO_PEER_GROUP) {
ret = GetAccountUnrelatedIdentityInfo(osAccountId, groupId, deviceId, isUdid, info);
} else {
ret = GetAccountRelatedCredInfo(osAccountId, groupId, deviceId, isUdid, info);
}
if (ret != HC_SUCCESS) {
LOGE("Failed to get identity info!");
DestroyIdentityInfo(info);
return ret;
}
*returnInfo = info;
return HC_SUCCESS;
}
static void AddNoPseudonymIdentityInfo(int32_t osAccountId, const TrustedGroupEntry *groupEntry,
const char *deviceId, bool isUdid, IdentityInfoVec *identityInfoVec)
{
IdentityInfo *info = NULL;
if (GetIdentityInfo(osAccountId, groupEntry, deviceId, isUdid, &info) != HC_SUCCESS) {
return;
}
info->proof.certInfo.isPseudonym = false;
identityInfoVec->pushBack(identityInfoVec, (const IdentityInfo **)&info);
}
static int32_t GetIdentityInfos(
int32_t osAccountId, const CJson *in, const GroupEntryVec *groupEntryVec, IdentityInfoVec *identityInfoVec)
{
const char *pkgName = GetStringFromJson(in, FIELD_SERVICE_PKG_NAME);
if (pkgName == NULL) {
LOGE("Failed to get service package name!");
return HC_ERR_JSON_GET;
}
bool isUdid = false;
const char *deviceId = GetPeerDevIdFromJson(in, &isUdid);
if (deviceId == NULL) {
LOGE("Failed to get peer device id!");
return HC_ERR_JSON_GET;
}
uint32_t index;
TrustedGroupEntry **ptr = NULL;
FOR_EACH_HC_VECTOR(*groupEntryVec, index, ptr)
{
const TrustedGroupEntry *groupEntry = (TrustedGroupEntry *)(*ptr);
const char *groupId = StringGet(&(groupEntry->id));
if (groupId == NULL) {
continue;
}
if (!GaIsGroupAccessible(osAccountId, groupId, pkgName)) {
continue;
}
if (!IsDeviceInGroup(osAccountId, groupEntry->type, deviceId, groupId, isUdid)) {
continue;
}
IdentityInfo *info = NULL;
if (GetIdentityInfo(osAccountId, groupEntry, deviceId, isUdid, &info) != HC_SUCCESS) {
continue;
}
if (info->proofType == CERTIFICATED) {
info->proof.certInfo.isPseudonym = true;
}
identityInfoVec->pushBack(identityInfoVec, (const IdentityInfo **)&info);
if (info->proofType == CERTIFICATED) {
AddNoPseudonymIdentityInfo(osAccountId, groupEntry, deviceId, isUdid, identityInfoVec);
}
}
LOGI("The identity info size is: %u", identityInfoVec->size(identityInfoVec));
return HC_SUCCESS;
}
static int32_t GetCredInfosByPeerIdentity(const CJson *in, IdentityInfoVec *identityInfoVec)
{
int32_t osAccountId = INVALID_OS_ACCOUNT;
int32_t ret;
if (GetIntFromJson(in, FIELD_OS_ACCOUNT_ID, &osAccountId) != HC_SUCCESS) {
LOGE("Failed to get osAccountId!");
return HC_ERR_JSON_GET;
}
const char *groupId = GetStringFromJson(in, FIELD_GROUP_ID);
if (groupId == NULL) {
groupId = GetStringFromJson(in, FIELD_SERVICE_TYPE);
}
GroupEntryVec groupEntryVec = CreateGroupEntryVec();
if (groupId == NULL) {
GetCandidateGroups(osAccountId, in, &groupEntryVec);
} else {
GetGroupInfoByGroupId(osAccountId, groupId, &groupEntryVec);
}
bool isDeviceLevel = false;
(void)GetBoolFromJson(in, FIELD_IS_DEVICE_LEVEL, &isDeviceLevel);
if (groupEntryVec.size(&groupEntryVec) == 0) {
if (isDeviceLevel) {
// device level auth still has the chance to try p2p direct auth
// so, do not report error here.
LOGI("No satisfied candidate group!");
} else {
LOGE("No satisfied candidate group!");
}
ClearGroupEntryVec(&groupEntryVec);
return HC_ERR_NO_CANDIDATE_GROUP;
}
ret = GetIdentityInfos(osAccountId, in, &groupEntryVec, identityInfoVec);
ClearGroupEntryVec(&groupEntryVec);
return ret;
}
static int32_t CheckAndGetP2pCredInfo(const CJson *in, const CJson *urlJson, IdentityInfo *info)
{
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 *groupId = GetStringFromJson(urlJson, FIELD_GROUP_ID);
if (groupId == NULL) {
LOGE("Failed to get groupId!");
return HC_ERR_JSON_GET;
}
int32_t ret = CheckGroupExist(osAccountId, groupId);
if (ret != HC_SUCCESS) {
LOGE("group not exist!");
return ret;
}
TrustedDeviceEntry *deviceEntry = CreateDeviceEntry();
if (deviceEntry == NULL) {
LOGE("Failed to create device entry!");
return HC_ERR_ALLOC_MEMORY;
}
ret = GetPeerDeviceEntry(osAccountId, in, groupId, deviceEntry);
DestroyDeviceEntry(deviceEntry);
if (ret != HC_SUCCESS) {
LOGE("peer device not found!");
return ret;
}
int32_t keyType = 0;
if (GetIntFromJson(urlJson, PRESHARED_URL_KEY_TYPE, &keyType) != HC_SUCCESS) {
LOGE("Failed to get trust type!");
return HC_ERR_JSON_GET;
}
char *urlStr = PackJsonToString(urlJson);
if (urlStr == NULL) {
LOGE("Failed to pack url json to string!");
return HC_ERR_PACKAGE_JSON_TO_STRING_FAIL;
}
ret = SetPreSharedUrlForProof(urlStr, &info->proof.preSharedUrl);
FreeJsonString(urlStr);
if (ret != HC_SUCCESS) {
LOGE("Failed to set preSharedUrl of proof!");
return ret;
}
ret = SetProtocolsToIdentityInfo(keyType, info);
if (ret != HC_SUCCESS) {
LOGE("Failed to set protocols!");
return ret;
}
info->proofType = PRE_SHARED;
if (ret != HC_SUCCESS) {
LOGE("Failed to get p2p identity info by key type!");
}
return ret;
}
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;
}
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;
}
IdentityInfo *info = CreateIdentityInfo();
if (info == NULL) {
LOGE("Failed to create identity info!");
return HC_ERR_ALLOC_MEMORY;
}
int32_t ret;
switch (trustType) {
case TRUST_TYPE_UID:
ret = GetAccountSymCredInfoByPeerUrl(in, urlJson, info);
break;
case TRUST_TYPE_P2P:
ret = CheckAndGetP2pCredInfo(in, urlJson, info);
break;
default:
LOGE("Invalid trust type!");
ret = HC_ERR_INVALID_PARAMS;
break;
}
FreeJson(urlJson);
*returnInfo = info;
return ret;
}
static int32_t GenerateKeyAliasInIso(const CJson *in, const char *groupId, uint8_t *keyAlias, uint32_t keyAliasLen)
{
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;
}
TrustedDeviceEntry *deviceEntry = CreateDeviceEntry();
if (deviceEntry == NULL) {
LOGE("Failed to create device entry!");
return HC_ERR_ALLOC_MEMORY;
}
int32_t ret = GetPeerDeviceEntry(osAccountId, in, groupId, deviceEntry);
if (ret != HC_SUCCESS) {
LOGE("Failed to get peer device entry!");
DestroyDeviceEntry(deviceEntry);
return ret;
}
Uint8Buff pkgNameBuff = { (uint8_t *)GROUP_MANAGER_PACKAGE_NAME,
(uint32_t)strlen(GROUP_MANAGER_PACKAGE_NAME) };
const char *serviceType = StringGet(&deviceEntry->serviceType);
Uint8Buff serviceTypeBuff = { (uint8_t *)serviceType, (uint32_t)strlen(serviceType) };
const char *peerAuthId = StringGet(&deviceEntry->authId);
Uint8Buff peerAuthIdBuff = { (uint8_t *)peerAuthId, (uint32_t)strlen(peerAuthId) };
Uint8Buff outKeyAlias = { keyAlias, keyAliasLen };
ret = GenerateKeyAlias(&pkgNameBuff, &serviceTypeBuff, KEY_ALIAS_AUTH_TOKEN, &peerAuthIdBuff, &outKeyAlias);
DestroyDeviceEntry(deviceEntry);
return ret;
}
static int32_t AuthGeneratePsk(
const CJson *in, const char *groupId, const Uint8Buff *seed, Uint8Buff *sharedSecret)
{
uint8_t keyAlias[ISO_KEY_ALIAS_LEN] = { 0 };
int ret = GenerateKeyAliasInIso(in, groupId, keyAlias, sizeof(keyAlias));
if (ret != HC_SUCCESS) {
LOGE("Failed to generate key alias in iso!");
return ret;
}
Uint8Buff keyAliasBuf = { keyAlias, sizeof(keyAlias) };
return GetLoaderInstance()->computeHmac(&keyAliasBuf, seed, sharedSecret, true);
}
static int32_t GetSharedSecretForP2pInIso(const CJson *in, const char *groupId, 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, groupId, &seedBuff, sharedSecret);
HcFree(seedVal);
if (ret != HC_SUCCESS) {
LOGE("Failed to generate psk!");
FreeBuffData(sharedSecret);
}
return ret;
}
static int32_t GetSelfAuthIdAndUserType(
int32_t osAccountId, const char *groupId, Uint8Buff *authIdBuff, int32_t *userType)
{
TrustedDeviceEntry *deviceEntry = CreateDeviceEntry();
if (deviceEntry == NULL) {
LOGE("Failed to create device entry!");
return HC_ERR_ALLOC_MEMORY;
}
int32_t ret = GetSelfDeviceEntry(osAccountId, groupId, deviceEntry);
if (ret != HC_SUCCESS) {
LOGE("Failed to get self device entry!");
DestroyDeviceEntry(deviceEntry);
return ret;
}
const char *selfAuthId = StringGet(&deviceEntry->authId);
uint32_t authIdLen = strlen(selfAuthId);
authIdBuff->val = (uint8_t *)HcMalloc(authIdLen + 1, 0);
if (authIdBuff->val == NULL) {
LOGE("Failed to alloc memory for authId!");
DestroyDeviceEntry(deviceEntry);
return HC_ERR_ALLOC_MEMORY;
}
if (memcpy_s(authIdBuff->val, authIdLen + 1, selfAuthId, authIdLen) != EOK) {
LOGE("Failed to copy authId!");
HcFree(authIdBuff->val);
authIdBuff->val = NULL;
DestroyDeviceEntry(deviceEntry);
return HC_ERR_MEMORY_COPY;
}
authIdBuff->length = authIdLen;
*userType = deviceEntry->devType;
DestroyDeviceEntry(deviceEntry);
return HC_SUCCESS;
}
static int32_t ComputeAndSavePsk(int32_t osAccountId, const char *groupId,
const TrustedDeviceEntry *peerDeviceEntry, const Uint8Buff *sharedKeyAlias)
{
Uint8Buff selfAuthIdBuff = { NULL, 0 };
int32_t selfUserType = 0;
int32_t ret = GetSelfAuthIdAndUserType(osAccountId, groupId, &selfAuthIdBuff, &selfUserType);
if (ret != HC_SUCCESS) {
LOGE("Failed to get self auth id and user type!");
return ret;
}
Uint8Buff pkgNameBuff = { (uint8_t *)GROUP_MANAGER_PACKAGE_NAME, strlen(GROUP_MANAGER_PACKAGE_NAME) };
const char *serviceType = StringGet(&peerDeviceEntry->serviceType);
Uint8Buff serviceTypeBuff = { (uint8_t *)serviceType, strlen(serviceType) };
KeyAliasType keyType = (KeyAliasType)selfUserType;
uint8_t selfKeyAliasVal[PAKE_KEY_ALIAS_LEN] = { 0 };
Uint8Buff selfKeyAlias = { selfKeyAliasVal, PAKE_KEY_ALIAS_LEN };
ret = GenerateKeyAlias(&pkgNameBuff, &serviceTypeBuff, keyType, &selfAuthIdBuff, &selfKeyAlias);
HcFree(selfAuthIdBuff.val);
if (ret != HC_SUCCESS) {
LOGE("Failed to generate self key alias!");
return ret;
}
#ifdef DEV_AUTH_FUNC_TEST
KeyAliasType keyTypePeer = KEY_ALIAS_LT_KEY_PAIR;
#else
KeyAliasType keyTypePeer = (KeyAliasType)peerDeviceEntry->devType;
#endif
const char *peerAuthId = StringGet(&peerDeviceEntry->authId);
Uint8Buff peerAuthIdBuff = { (uint8_t *)peerAuthId, strlen(peerAuthId) };
uint8_t peerKeyAliasVal[PAKE_KEY_ALIAS_LEN] = { 0 };
Uint8Buff peerKeyAlias = { peerKeyAliasVal, PAKE_KEY_ALIAS_LEN };
ret = GenerateKeyAlias(&pkgNameBuff, &serviceTypeBuff, keyTypePeer, &peerAuthIdBuff, &peerKeyAlias);
if (ret != HC_SUCCESS) {
LOGE("Failed to generate peer key alias!");
return ret;
}
ret = GetLoaderInstance()->checkKeyExist(&selfKeyAlias);
if (ret != HC_SUCCESS) {
LOGE("self auth keyPair not exist!");
return ret;
}
ret = GetLoaderInstance()->checkKeyExist(&peerKeyAlias);
if (ret != HC_SUCCESS) {
LOGE("peer auth pubKey not exist!");
return ret;
}
KeyBuff selfKeyAliasBuff = { selfKeyAlias.val, selfKeyAlias.length, true };
KeyBuff peerKeyAliasBuff = { peerKeyAlias.val, peerKeyAlias.length, true };
return GetLoaderInstance()->agreeSharedSecretWithStorage(
&selfKeyAliasBuff, &peerKeyAliasBuff, ED25519, PAKE_PSK_LEN, sharedKeyAlias);
}
static int32_t GeneratePskAliasAndCheckExist(const CJson *in, const char *groupId, Uint8Buff *pskKeyAlias)
{
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;
}
TrustedDeviceEntry *deviceEntry = CreateDeviceEntry();
if (deviceEntry == NULL) {
LOGE("Failed to create device entry!");
return HC_ERR_ALLOC_MEMORY;
}
int32_t ret = GetPeerDeviceEntry(osAccountId, in, groupId, deviceEntry);
if (ret != HC_SUCCESS) {
LOGE("Failed to get peer device entry!");
DestroyDeviceEntry(deviceEntry);
return ret;
}
Uint8Buff pkgNameBuff = { (uint8_t *)GROUP_MANAGER_PACKAGE_NAME, strlen(GROUP_MANAGER_PACKAGE_NAME) };
const char *serviceType = StringGet(&deviceEntry->serviceType);
Uint8Buff serviceTypeBuff = { (uint8_t *)serviceType, strlen(serviceType) };
const char *peerAuthId = StringGet(&deviceEntry->authId);
Uint8Buff peerAuthIdBuff = { (uint8_t *)peerAuthId, strlen(peerAuthId) };
ret = GenerateKeyAlias(&pkgNameBuff, &serviceTypeBuff, KEY_ALIAS_PSK, &peerAuthIdBuff, pskKeyAlias);
if (ret != HC_SUCCESS) {
LOGE("Failed to generate psk key alias!");
DestroyDeviceEntry(deviceEntry);
return ret;
}
LOGI("psk alias: %x %x %x %x****.", pskKeyAlias->val[DEV_AUTH_ZERO], pskKeyAlias->val[DEV_AUTH_ONE],
pskKeyAlias->val[DEV_AUTH_TWO], pskKeyAlias->val[DEV_AUTH_THREE]);
if (GetLoaderInstance()->checkKeyExist(pskKeyAlias) != HC_SUCCESS) {
ret = ComputeAndSavePsk(osAccountId, groupId, deviceEntry, pskKeyAlias);
}
DestroyDeviceEntry(deviceEntry);
return ret;
}
static int32_t GetSharedSecretForP2pInPake(const CJson *in, const char *groupId, Uint8Buff *sharedSecret)
{
uint8_t pskKeyAliasVal[PAKE_KEY_ALIAS_LEN] = { 0 };
Uint8Buff pskKeyAlias = { pskKeyAliasVal, PAKE_KEY_ALIAS_LEN };
int32_t ret = GeneratePskAliasAndCheckExist(in, groupId, &pskKeyAlias);
if (ret != HC_SUCCESS) {
LOGE("Failed to generate key alias for psk!");
return ret;
}
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 };
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, strlen(TMP_AUTH_KEY_FACTOR) };
ret = GetLoaderInstance()->computeHkdf(&pskKeyAlias, &nonceBuff, &keyInfo, &pskBuff, true);
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 GetSharedSecretForP2p(
const CJson *in, const CJson *urlJson, ProtocolAlgType protocolType, Uint8Buff *sharedSecret)
{
const char *groupId = GetStringFromJson(urlJson, FIELD_GROUP_ID);
if (groupId == NULL) {
LOGE("Failed to get groupId!");
return HC_ERR_JSON_GET;
}
int32_t ret;
if (protocolType == ALG_ISO) {
ret = GetSharedSecretForP2pInIso(in, groupId, sharedSecret);
LOGI("get shared secret for p2p in iso result: %d", ret);
} else {
ret = GetSharedSecretForP2pInPake(in, groupId, sharedSecret);
LOGI("get shared secret for p2p in pake result: %d", ret);
}
return ret;
}
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;
}
int32_t ret;
switch (trustType) {
case TRUST_TYPE_P2P:
ret = GetSharedSecretForP2p(in, urlJson, protocolType, sharedSecret);
break;
case TRUST_TYPE_UID:
if (protocolType != ALG_ISO) {
LOGE("protocol type is not iso, not supported!");
ret = HC_ERR_INVALID_PARAMS;
} else {
ret = GetAccountSymSharedSecret(in, urlJson, sharedSecret);
}
break;
default:
LOGE("Invalid trust type!");
ret = HC_ERR_INVALID_PARAMS;
break;
}
FreeJson(urlJson);
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;
}
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;
}
int32_t res = GetAccountAsymCredInfo(osAccountId, certInfo, returnInfo);
if (res != HC_SUCCESS) {
LOGE("Failed to get account asym cred info!");
return res;
}
if (certInfo->isPseudonym) {
(*returnInfo)->proof.certInfo.isPseudonym = true;
} else {
(*returnInfo)->proof.certInfo.isPseudonym = false;
}
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;
}
return GetAccountAsymSharedSecret(osAccountId, peerCertInfo, sharedSecret);
}
static const AuthIdentity g_authIdentity = {
.getCredInfosByPeerIdentity = GetCredInfosByPeerIdentity,
.getCredInfoByPeerUrl = GetCredInfoByPeerUrl,
.getSharedSecretByUrl = GetSharedSecretByUrl,
.getCredInfoByPeerCert = GetCredInfoByPeerCert,
.getSharedSecretByPeerCert = GetSharedSecretByPeerCert,
};
const AuthIdentity *GetGroupAuthIdentity(void)
{
return &g_authIdentity;
}
@@ -0,0 +1,61 @@
/*
* 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"
#include "hc_log.h"
/* in order to expand to uint16_t */
static const uint8_t KEY_TYPE_PAIRS[KEY_ALIAS_TYPE_END][KEY_TYPE_PAIR_LEN] = {
{ 0x00, 0x00 }, /* ACCESSOR_PK */
{ 0x00, 0x01 }, /* CONTROLLER_PK */
{ 0x00, 0x02 }, /* ed25519 KEYPAIR */
{ 0x00, 0x03 }, /* KEK, key encryption key, used only by DeviceAuthService */
{ 0x00, 0x04 }, /* DEK, data encryption key, used only by upper apps */
{ 0x00, 0x05 }, /* key tmp */
{ 0x00, 0x06 }, /* PSK, preshared key index */
{ 0x00, 0x07 }, /* AUTHTOKEN */
{ 0x00, 0x08 } /* P2P_AUTH */
};
uint8_t *GetKeyTypePair(KeyAliasType keyAliasType)
{
return (uint8_t *)KEY_TYPE_PAIRS[keyAliasType];
}
const AuthIdentity *GetAuthIdentityByType(AuthIdentityType type)
{
switch (type) {
case AUTH_IDENTITY_TYPE_GROUP:
return GetGroupAuthIdentity();
case AUTH_IDENTITY_TYPE_PIN:
return GetPinAuthIdentity();
case AUTH_IDENTITY_TYPE_P2P:
return GetP2pAuthIdentity();
default:
LOGE("unknow AuthIdentityType: %d", type);
return NULL;
}
}
static const AuthIdentityManager g_identityManager = {
.getAuthIdentityByType = GetAuthIdentityByType,
.getCredentialOperator = GetCredentialOperator,
};
const AuthIdentityManager *GetAuthIdentityManager(void)
{
return &g_identityManager;
}
@@ -0,0 +1,333 @@
/*
* 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 "alg_defs.h"
#include "alg_loader.h"
#include "hc_log.h"
#include "identity_manager.h"
static int32_t SetProtocolsToIdentityInfo(IdentityInfo *info)
{
ProtocolEntity *ecSpekeEntity = (ProtocolEntity *)HcMalloc(sizeof(ProtocolEntity), 0);
if (ecSpekeEntity == NULL) {
LOGE("Failed to alloc memory for ec speke entity!");
return HC_ERR_ALLOC_MEMORY;
}
ecSpekeEntity->protocolType = ALG_EC_SPEKE;
ecSpekeEntity->expandProcessCmds = 0;
info->protocolVec.pushBack(&info->protocolVec, (const ProtocolEntity **)&ecSpekeEntity);
return HC_SUCCESS;
}
static int32_t IsPeerDevicePublicKeyExist(const CJson *in)
{
int32_t osAccountId = INVALID_OS_ACCOUNT;
if (GetIntFromJson(in, FIELD_OS_ACCOUNT_ID, &osAccountId) != HC_SUCCESS) {
LOGE("Failed to get osAccountId from context!");
return HC_ERR_JSON_GET;
}
const char *peerConnDeviceId = GetStringFromJson(in, FIELD_PEER_CONN_DEVICE_ID);
if (peerConnDeviceId == NULL) {
LOGE("Failed to get peerConnDeviceId from context, need peerConnDeviceId!");
return HC_ERR_JSON_GET;
}
int32_t acquireType = P2P_BIND;
if (GetIntFromJson(in, FIELD_ACQURIED_TYPE, &acquireType) != HC_SUCCESS) {
LOGI("Failed to get acquireType from context!");
}
CJson *paramsJson = CreateJson();
if (paramsJson == NULL) {
LOGE("alloc memory error!");
return HC_ERR_ALLOC_MEMORY;
}
if (AddIntToJson(paramsJson, FIELD_OS_ACCOUNT_ID, osAccountId) != HC_SUCCESS) {
LOGE("add osAccountId to json error!");
FreeJson(paramsJson);
return HC_ERR_JSON_ADD;
}
if (AddIntToJson(paramsJson, FIELD_ACQURIED_TYPE, acquireType) != HC_SUCCESS) {
LOGE("add acquireType to json error!");
FreeJson(paramsJson);
return HC_ERR_JSON_ADD;
}
if (AddIntToJson(paramsJson, FIELD_CRED_OP_FLAG, RETURN_FLAG_DEFAULT) != HC_SUCCESS) {
LOGE("add flag to json error!");
FreeJson(paramsJson);
return HC_ERR_JSON_ADD;
}
if (AddStringToJson(paramsJson, FIELD_DEVICE_ID, peerConnDeviceId) != HC_SUCCESS) {
LOGE("add device id to json error!");
FreeJson(paramsJson);
return HC_ERR_JSON_ADD;
}
const char *requestParams = PackJsonToString(paramsJson);
FreeJson(paramsJson);
const CredentialOperator *credOperator = GetCredentialOperator();
if (credOperator == NULL) {
LOGE("credOperator is null!");
return HC_ERR_NOT_SUPPORT;
}
return credOperator->queryCredential(requestParams, NULL);
}
static int32_t GetCredInfosByPeerIdentity(const CJson *in, IdentityInfoVec *vec)
{
int32_t keyType = KEY_TYPE_ASYM;
(void)GetIntFromJson(in, FIELD_KEY_TYPE, &keyType);
int32_t ret = IsPeerDevicePublicKeyExist(in);
if (ret != HC_SUCCESS) {
LOGE("Failed to get peer device public key!");
return ret;
}
CJson *urlJson = CreateCredUrlJson(PRE_SHARED, keyType, TRUST_TYPE_P2P);
if (!urlJson) {
LOGE("Failed to create CredUrlJson info!");
return HC_ERR_ALLOC_MEMORY;
}
if (AddBoolToJson(urlJson, FIELD_IS_DIRECT_AUTH, true) != HC_SUCCESS) {
LOGE("Failed to add isDirectAuth to preshared url!");
FreeJson(urlJson);
return HC_ERR_JSON_ADD;
} else {
LOGI("add isDirectAuth:true into urlJson!");
}
char *urlStr = PackJsonToString(urlJson);
FreeJson(urlJson);
if (urlStr == NULL) {
LOGE("Failed to pack url json to string!");
return HC_ERR_PACKAGE_JSON_TO_STRING_FAIL;
}
IdentityInfo *info = CreateIdentityInfo();
if (info == NULL) {
LOGE("Failed to create identity info!");
return HC_ERR_ALLOC_MEMORY;
}
ret = SetPreSharedUrlForProof(urlStr, &info->proof.preSharedUrl);
FreeJsonString(urlStr);
if (ret != HC_SUCCESS) {
LOGE("Failed to set preSharedUrl of proof!");
return ret;
}
ret = SetProtocolsToIdentityInfo(info);
if (ret != HC_SUCCESS) {
LOGE("Failed to set protocols!");
return ret;
}
info->proofType = PRE_SHARED;
info->IdInfoType = P2P_DIRECT_AUTH;
vec->pushBack(vec, (const IdentityInfo **)&info);
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 = CreateIdentityInfo();
if (info == NULL) {
LOGE("Failed to create identity info!");
return HC_ERR_ALLOC_MEMORY;
}
int32_t ret = SetPreSharedUrlForProof((const char *)presharedUrl->val, &info->proof.preSharedUrl);
if (ret != HC_SUCCESS) {
LOGE("Failed to set preSharedUrl of proof!");
return ret;
}
ret = SetProtocolsToIdentityInfo(info);
if (ret != HC_SUCCESS) {
LOGE("Failed to set protocols!");
return ret;
}
info->proofType = PRE_SHARED;
info->IdInfoType = P2P_DIRECT_AUTH;
*returnInfo = info;
return HC_SUCCESS;
}
/**
* @brief compute shared key alias
*
* @param osAccountId
* @param selfAuthId self device udid
* @param peerAuthId peer device udid
* @param sharedKeyAlias
* @return int32_t
*/
static int32_t ComputeAndSaveDirectAuthPsk(int32_t osAccountId, const char *selfAuthId, const char *peerAuthId,
const char *peerServiceType, const Uint8Buff *sharedKeyAlias)
{
Uint8Buff selfAuthIdBuff = { (uint8_t *)selfAuthId, strlen(selfAuthId) };
Uint8Buff pkgNameBuff = { (uint8_t *)DEFAULT_PACKAGE_NAME, strlen(DEFAULT_PACKAGE_NAME) };
Uint8Buff serviceTypeBuff = { (uint8_t *)DEFAULT_SERVICE_TYPE, strlen(DEFAULT_SERVICE_TYPE) };
KeyAliasType keyType = KEY_ALIAS_P2P_AUTH;
uint8_t selfKeyAliasVal[PAKE_KEY_ALIAS_LEN] = { 0 };
Uint8Buff selfKeyAlias = { selfKeyAliasVal, PAKE_KEY_ALIAS_LEN };
int32_t ret = GenerateKeyAlias(&pkgNameBuff, &serviceTypeBuff, keyType, &selfAuthIdBuff, &selfKeyAlias);
if (ret != HC_SUCCESS) {
LOGE("Failed to generate self key alias!");
return ret;
}
LOGI("selfKeyAlias: %x %x %x %x****.", selfKeyAlias.val[DEV_AUTH_ZERO], selfKeyAlias.val[DEV_AUTH_ONE],
selfKeyAlias.val[DEV_AUTH_TWO], selfKeyAlias.val[DEV_AUTH_THREE]);
Uint8Buff peerServiceTypeBuff = { (uint8_t *)peerServiceType, strlen(peerServiceType) };
KeyAliasType keyTypePeer = KEY_ALIAS_P2P_AUTH;
Uint8Buff peerAuthIdBuff = { (uint8_t *)peerAuthId, strlen(peerAuthId) };
uint8_t peerKeyAliasVal[PAKE_KEY_ALIAS_LEN] = { 0 };
Uint8Buff peerKeyAlias = { peerKeyAliasVal, PAKE_KEY_ALIAS_LEN };
ret = GenerateKeyAlias(&pkgNameBuff, &peerServiceTypeBuff, keyTypePeer, &peerAuthIdBuff, &peerKeyAlias);
if (ret != HC_SUCCESS) {
LOGE("Failed to generate peer key alias!");
return ret;
}
LOGI("peerKeyAlias: %x %x %x %x****.", peerKeyAlias.val[DEV_AUTH_ZERO], peerKeyAlias.val[DEV_AUTH_ONE],
peerKeyAlias.val[DEV_AUTH_TWO], peerKeyAlias.val[DEV_AUTH_THREE]);
ret = GetLoaderInstance()->checkKeyExist(&selfKeyAlias);
if (ret != HC_SUCCESS) {
LOGE("self auth keyPair not exist!");
return ret;
}
ret = GetLoaderInstance()->checkKeyExist(&peerKeyAlias);
if (ret != HC_SUCCESS) {
LOGE("peer auth pubKey not exist!");
return ret;
}
KeyBuff selfKeyAliasBuff = { selfKeyAlias.val, selfKeyAlias.length, true };
KeyBuff peerKeyAliasBuff = { peerKeyAlias.val, peerKeyAlias.length, true };
return GetLoaderInstance()->agreeSharedSecretWithStorage(
&selfKeyAliasBuff, &peerKeyAliasBuff, ED25519, PAKE_PSK_LEN, sharedKeyAlias);
}
static int32_t GetDirectAuthPskAliasCreateIfNeeded(const CJson *in, Uint8Buff *pskKeyAlias)
{
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 *selfAuthId = GetStringFromJson(in, FIELD_AUTH_ID);
if (selfAuthId == NULL) {
LOGE("get authId from context fail.");
return HC_ERR_JSON_GET;
}
const char *peerAuthId = GetStringFromJson(in, FIELD_PEER_CONN_DEVICE_ID);
if (peerAuthId == NULL) {
LOGE("get peerConnDeviceId from json fail.");
return HC_ERR_JSON_GET;
}
const char *peerServieType = GetStringFromJson(in, FIELD_SERVICE_TYPE);
if (peerServieType == NULL) {
LOGI("get serviceType from json fail, replace by default");
peerServieType = DEFAULT_SERVICE_TYPE;
}
Uint8Buff pkgNameBuff = { (uint8_t *)DEFAULT_PACKAGE_NAME, strlen(DEFAULT_PACKAGE_NAME) };
Uint8Buff serviceTypeBuff = { (uint8_t *)peerServieType, strlen(peerServieType) };
Uint8Buff peerAuthIdBuff = { (uint8_t *)peerAuthId, strlen(peerAuthId) };
int32_t ret = GenerateKeyAlias(&pkgNameBuff, &serviceTypeBuff, KEY_ALIAS_PSK, &peerAuthIdBuff, pskKeyAlias);
if (ret != HC_SUCCESS) {
LOGE("Failed to generate psk key alias!");
return ret;
}
LOGI("psk alias: %x %x %x %x****.", pskKeyAlias->val[DEV_AUTH_ZERO], pskKeyAlias->val[DEV_AUTH_ONE],
pskKeyAlias->val[DEV_AUTH_TWO], pskKeyAlias->val[DEV_AUTH_THREE]);
ret = GetLoaderInstance()->checkKeyExist(pskKeyAlias);
if (ret != HC_SUCCESS) {
ret = ComputeAndSaveDirectAuthPsk(osAccountId, selfAuthId, peerAuthId, peerServieType, pskKeyAlias);
}
return ret;
}
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;
}
uint8_t pskKeyAliasVal[PAKE_KEY_ALIAS_LEN] = { 0 };
Uint8Buff pskKeyAlias = { pskKeyAliasVal, PAKE_KEY_ALIAS_LEN };
int32_t ret = GetDirectAuthPskAliasCreateIfNeeded(in, &pskKeyAlias);
if (ret != HC_SUCCESS) {
LOGE("Failed to generate key alias for psk!");
return ret;
}
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 };
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, strlen(TMP_AUTH_KEY_FACTOR) };
ret = GetLoaderInstance()->computeHkdf(&pskKeyAlias, &nonceBuff, &keyInfo, &pskBuff, true);
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 GetCredInfoByPeerCert(const CJson *in, const CertInfo *certInfo, IdentityInfo **returnInfo)
{
// NOT SUPPORT FOR P2P AUTH
return HC_ERR_ALG_FAIL;
}
static int32_t GetSharedSecretByPeerCert(
const CJson *in, const CertInfo *peerCertInfo, ProtocolAlgType protocolType, Uint8Buff *sharedSecret)
{
// NOT SUPPORT P2P AUTH
return HC_ERR_ALG_FAIL;
}
static const AuthIdentity g_authIdentity = {
.getCredInfosByPeerIdentity = GetCredInfosByPeerIdentity,
.getCredInfoByPeerUrl = GetCredInfoByPeerUrl,
.getSharedSecretByUrl = GetSharedSecretByUrl,
.getCredInfoByPeerCert = GetCredInfoByPeerCert,
.getSharedSecretByPeerCert = GetSharedSecretByPeerCert,
};
const AuthIdentity *GetP2pAuthIdentity(void)
{
return &g_authIdentity;
}
@@ -0,0 +1,363 @@
/*
* 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 "alg_defs.h"
#include "alg_loader.h"
#include "hc_log.h"
#include "identity_manager.h"
static int32_t SetDlSpekeProtocol(IdentityInfo *info)
{
#ifdef ENABLE_P2P_BIND_DL_SPEKE
ProtocolEntity *dlSpekeEntity = (ProtocolEntity *)HcMalloc(sizeof(ProtocolEntity), 0);
if (dlSpekeEntity == NULL) {
LOGE("Failed to alloc memory for dl speke entity!");
return HC_ERR_ALLOC_MEMORY;
}
dlSpekeEntity->protocolType = ALG_DL_SPEKE;
dlSpekeEntity->expandProcessCmds = CMD_IMPORT_AUTH_CODE | CMD_ADD_TRUST_DEVICE;
if (info->protocolVec.pushBack(&info->protocolVec, (const ProtocolEntity **)&dlSpekeEntity) == NULL) {
LOGE("Failed to push dl speke entity!");
HcFree(dlSpekeEntity);
return HC_ERR_ALLOC_MEMORY;
}
return HC_SUCCESS;
#else
(void)info;
return HC_SUCCESS;
#endif
}
static int32_t SetIsoProtocol(IdentityInfo *info)
{
#ifdef ENABLE_P2P_BIND_ISO
ProtocolEntity *isoEntity = (ProtocolEntity *)HcMalloc(sizeof(ProtocolEntity), 0);
if (isoEntity == NULL) {
LOGE("Failed to alloc memory for iso entity!");
return HC_ERR_ALLOC_MEMORY;
}
isoEntity->protocolType = ALG_ISO;
isoEntity->expandProcessCmds = 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);
return HC_ERR_ALLOC_MEMORY;
}
return HC_SUCCESS;
#else
(void)info;
return HC_SUCCESS;
#endif
}
static int32_t SetLiteProtocols(IdentityInfo *info)
{
int32_t res = SetDlSpekeProtocol(info);
if (res != HC_SUCCESS) {
return res;
}
return SetIsoProtocol(info);
}
static int32_t SetLiteProtocolsForPinType(const CJson *in, IdentityInfo *info)
{
#ifndef ENABLE_P2P_BIND_LITE_PROTOCOL_CHECK
(void)in;
return SetLiteProtocols(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);
}
return res;
#endif
}
static int32_t SetProtocolsForPinType(const CJson *in, IdentityInfo *info)
{
#ifdef ENABLE_P2P_BIND_EC_SPEKE
ProtocolEntity *ecSpekeEntity = (ProtocolEntity *)HcMalloc(sizeof(ProtocolEntity), 0);
if (ecSpekeEntity == NULL) {
LOGE("Failed to alloc memory for ec speke entity!");
return HC_ERR_ALLOC_MEMORY;
}
ecSpekeEntity->protocolType = ALG_EC_SPEKE;
ecSpekeEntity->expandProcessCmds = 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);
return HC_ERR_ALLOC_MEMORY;
}
#endif
return SetLiteProtocolsForPinType(in, info);
}
static bool IsDirectAuth(const CJson *context)
{
bool isDirectAuth = false;
(void)GetBoolFromJson(context, FIELD_IS_DIRECT_AUTH, &isDirectAuth);
return isDirectAuth;
}
static int32_t SetProtocolsForDirectAuth(IdentityInfo *info)
{
#ifdef ENABLE_P2P_AUTH_EC_SPEKE
ProtocolEntity *ecSpekeEntity = (ProtocolEntity *)HcMalloc(sizeof(ProtocolEntity), 0);
if (ecSpekeEntity == NULL) {
LOGE("Failed to alloc memory for ec speke entity!");
return HC_ERR_ALLOC_MEMORY;
}
ecSpekeEntity->protocolType = ALG_EC_SPEKE;
ecSpekeEntity->expandProcessCmds = 0;
info->protocolVec.pushBack(&info->protocolVec, (const ProtocolEntity **)&ecSpekeEntity);
#else
#endif
return HC_SUCCESS;
}
static int32_t GetCredInfosByPeerIdentity(const CJson *in, IdentityInfoVec *vec)
{
IdentityInfo *info = CreateIdentityInfo();
if (info == NULL) {
LOGE("Failed to create identity info!");
return HC_ERR_ALLOC_MEMORY;
}
CJson *urlJson = CreateCredUrlJson(PRE_SHARED, KEY_TYPE_SYM, TRUST_TYPE_PIN);
if (!urlJson) {
LOGE("Failed to create CredUrlJson info!");
return HC_ERR_ALLOC_MEMORY;
}
if (IsDirectAuth(in) && AddBoolToJson(urlJson, FIELD_IS_DIRECT_AUTH, true) != HC_SUCCESS) {
LOGE("Failed to isDirectAuth to preshared url!");
FreeJson(urlJson);
return HC_ERR_JSON_ADD;
}
char *urlStr = PackJsonToString(urlJson);
FreeJson(urlJson);
if (urlStr == NULL) {
LOGE("Failed to pack url json to string!");
return HC_ERR_PACKAGE_JSON_TO_STRING_FAIL;
}
int32_t ret = SetPreSharedUrlForProof(urlStr, &info->proof.preSharedUrl);
FreeJsonString(urlStr);
if (ret != HC_SUCCESS) {
LOGE("Failed to set preSharedUrl of proof!");
return ret;
}
if (IsDirectAuth(in)) {
ret = SetProtocolsForDirectAuth(info);
info->IdInfoType = P2P_DIRECT_AUTH;
} else {
ret = SetProtocolsForPinType(in, info);
}
if (ret != HC_SUCCESS) {
LOGE("Failed to set protocols!");
return ret;
}
info->proofType = PRE_SHARED;
vec->pushBack(vec, (const IdentityInfo **)&info);
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 = CreateIdentityInfo();
if (info == NULL) {
LOGE("Failed to create identity info!");
return HC_ERR_ALLOC_MEMORY;
}
CJson *urlJson = CreateJsonFromString((const char *)presharedUrl->val);
if (urlJson == NULL) {
LOGE("Failed to create url json!");
return HC_ERR_JSON_CREATE;
}
int32_t credentialType = PRE_SHARED;
if (GetIntFromJson(urlJson, PRESHARED_URL_CREDENTIAL_TYPE, &credentialType) != HC_SUCCESS) {
LOGE("Failed to get credential type!");
FreeJson(urlJson);
return HC_ERR_JSON_GET;
}
FreeJson(urlJson);
int32_t ret = SetPreSharedUrlForProof((const char *)presharedUrl->val, &info->proof.preSharedUrl);
if (ret != HC_SUCCESS) {
LOGE("Failed to set preSharedUrl of proof!");
return ret;
}
if (IsDirectAuth(in)) {
ret = SetProtocolsForDirectAuth(info);
info->IdInfoType = P2P_DIRECT_AUTH;
} else {
ret = SetProtocolsForPinType(in, info);
}
if (ret != HC_SUCCESS) {
LOGE("Failed to set protocols!");
return ret;
}
info->proofType = credentialType;
*returnInfo = info;
return HC_SUCCESS;
}
static int32_t AuthGeneratePskUsePin(const Uint8Buff *seed, const char *pinCode, Uint8Buff *sharedSecret)
{
Uint8Buff messageBuf = { (uint8_t *)pinCode, (uint32_t)strlen(pinCode) };
uint8_t hash[SHA256_LEN] = { 0 };
Uint8Buff hashBuf = { hash, sizeof(hash) };
int ret = GetLoaderInstance()->sha256(&messageBuf, &hashBuf);
if (ret != HC_SUCCESS) {
LOGE("sha256 failed, ret:%d", ret);
return ret;
}
return GetLoaderInstance()->computeHmac(&hashBuf, seed, sharedSecret, false);
}
#ifdef ENABLE_P2P_BIND_LITE_PROTOCOL_CHECK
static bool CheckPinLenForStandardIso(const CJson *in, const char *pinCode)
{
int32_t protocolExpandVal = INVALID_PROTOCOL_EXPAND_VALUE;
(void)GetIntFromJson(in, FIELD_PROTOCOL_EXPAND, &protocolExpandVal);
if (protocolExpandVal != LITE_PROTOCOL_STANDARD_MODE) {
LOGI("not standard iso, no need to check.");
return true;
}
return HcStrlen(pinCode) >= PIN_CODE_LEN_LONG;
}
#endif
static int32_t GetSharedSecretForPinInIso(const CJson *in, Uint8Buff *sharedSecret)
{
const char *pinCode = GetStringFromJson(in, FIELD_PIN_CODE);
if (pinCode == NULL) {
LOGE("Failed to get pinCode!");
return HC_ERR_JSON_GET;
}
if (HcStrlen(pinCode) < PIN_CODE_LEN_SHORT) {
LOGE("Pin code is too short!");
return HC_ERR_INVALID_LEN;
}
#ifdef ENABLE_P2P_BIND_LITE_PROTOCOL_CHECK
if (!CheckPinLenForStandardIso(in, pinCode)) {
LOGE("Invalid pin code len!");
return HC_ERR_INVALID_LEN;
}
#endif
uint8_t *seedVal = (uint8_t *)HcMalloc(SEED_LEN, 0);
if (seedVal == NULL) {
LOGE("Failed to alloc seed memory!");
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 psk memory!");
HcFree(seedVal);
return HC_ERR_ALLOC_MEMORY;
}
sharedSecret->val = pskVal;
sharedSecret->length = ISO_PSK_LEN;
ret = AuthGeneratePskUsePin(&seedBuff, pinCode, sharedSecret);
HcFree(seedVal);
if (ret != HC_SUCCESS) {
LOGE("Failed to generate psk use pin!");
FreeBuffData(sharedSecret);
}
return ret;
}
static int32_t GetSharedSecretForPinInPake(const CJson *in, Uint8Buff *sharedSecret)
{
const char *pinCode = GetStringFromJson(in, FIELD_PIN_CODE);
if (pinCode == NULL) {
LOGE("Failed to get pinCode!");
return HC_ERR_JSON_GET;
}
uint32_t pinLen = strlen(pinCode);
if (pinLen < PIN_CODE_LEN_SHORT) {
LOGE("Invalid pin code len!");
return HC_ERR_INVALID_LEN;
}
sharedSecret->val = (uint8_t *)HcMalloc(pinLen, 0);
if (sharedSecret->val == NULL) {
LOGE("Failed to alloc sharedSecret memory!");
return HC_ERR_ALLOC_MEMORY;
}
if (memcpy_s(sharedSecret->val, pinLen, pinCode, pinLen) != HC_SUCCESS) {
LOGE("Failed to memcpy pinCode!");
FreeBuffData(sharedSecret);
return HC_ERR_MEMORY_COPY;
}
sharedSecret->length = pinLen;
return HC_SUCCESS;
}
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;
}
int32_t ret;
if (protocolType == ALG_ISO) {
ret = GetSharedSecretForPinInIso(in, sharedSecret);
LOGI("get shared secret for pin in iso result: %d", ret);
} else {
ret = GetSharedSecretForPinInPake(in, sharedSecret);
LOGI("get shared secret for pin in pake result: %d", ret);
}
return ret;
}
static int32_t GetCredInfoByPeerCert(const CJson *in, const CertInfo *certInfo, IdentityInfo **returnInfo)
{
// NOT SUPPORT FOR PIN
return HC_ERR_ALG_FAIL;
}
static int32_t GetSharedSecretByPeerCert(
const CJson *in, const CertInfo *peerCertInfo, ProtocolAlgType protocolType, Uint8Buff *sharedSecret)
{
// NOT SUPPORT FOR PIN
return HC_ERR_ALG_FAIL;
}
static const AuthIdentity g_authIdentity = {
.getCredInfosByPeerIdentity = GetCredInfosByPeerIdentity,
.getCredInfoByPeerUrl = GetCredInfoByPeerUrl,
.getSharedSecretByUrl = GetSharedSecretByUrl,
.getCredInfoByPeerCert = GetCredInfoByPeerCert,
.getSharedSecretByPeerCert = GetSharedSecretByPeerCert,
};
const AuthIdentity *GetPinAuthIdentity(void)
{
return &g_authIdentity;
}
@@ -13,12 +13,11 @@
* limitations under the License.
*/
#include "account_related_creds_manager.h"
#include "cert_operation.h"
#include "device_auth_defines.h"
int32_t GetAccountRelatedCredInfo(int32_t osAccountId, const char *groupId, const char *deviceId,
bool isUdid, IdentityInfo *info)
int32_t GetAccountRelatedCredInfo(
int32_t osAccountId, const char *groupId, const char *deviceId, bool isUdid, IdentityInfo *info)
{
(void)osAccountId;
(void)groupId;
@@ -0,0 +1,51 @@
/*
* 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_common.h"
#include "securec.h"
IdentityInfo *CreateIdentityInfo(void)
{
return NULL;
}
void DestroyIdentityInfo(IdentityInfo *info)
{
(void)info;
}
IdentityInfoVec CreateIdentityInfoVec(void)
{
IdentityInfoVec v;
(void)memset_s(&v, sizeof(IdentityInfo), 0, sizeof(IdentityInfo));
return v;
}
void ClearIdentityInfoVec(IdentityInfoVec *vec)
{
(void)vec;
}
ProtocolEntityVec CreateProtocolEntityVec(void)
{
ProtocolEntityVec v;
(void)memset_s(&v, sizeof(ProtocolEntityVec), 0, sizeof(ProtocolEntityVec));
return v;
}
void ClearProtocolEntityVec(ProtocolEntityVec *vec)
{
(void)vec;
}
@@ -0,0 +1,65 @@
/*
* 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"
/* in order to expand to uint16_t */
static const uint8_t KEY_TYPE_PAIRS[KEY_ALIAS_TYPE_END][KEY_TYPE_PAIR_LEN] = {
{ 0x00, 0x00 }, /* ACCESSOR_PK */
{ 0x00, 0x01 }, /* CONTROLLER_PK */
{ 0x00, 0x02 }, /* ed25519 KEYPAIR */
{ 0x00, 0x03 }, /* KEK, key encryption key, used only by DeviceAuthService */
{ 0x00, 0x04 }, /* DEK, data encryption key, used only by upper apps */
{ 0x00, 0x05 }, /* key tmp */
{ 0x00, 0x06 }, /* PSK, preshared key index */
{ 0x00, 0x07 }, /* AUTHTOKEN */
{ 0x00, 0x08 } /* P2P_AUTH */
};
uint8_t *GetKeyTypePair(KeyAliasType keyAliasType)
{
return (uint8_t *)KEY_TYPE_PAIRS[keyAliasType];
}
const AuthIdentity *GetAuthIdentityByType(AuthIdentityType type)
{
(void)type;
return NULL;
}
const AuthIdentityManager *GetAuthIdentityManager(void)
{
return NULL;
}
const AuthIdentity *GetGroupAuthIdentity(void)
{
return NULL;
}
const AuthIdentity *GetPinAuthIdentity(void)
{
return NULL;
}
const AuthIdentity *GetP2pAuthIdentity(void)
{
return NULL;
}
const CredentialOperator *GetCredentialOperator(void)
{
return NULL;
}
@@ -1,46 +1,46 @@
/*
* Copyright (C) 2022 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 ACCOUNT_MULTI_TASK_MANAGER_H
#define ACCOUNT_MULTI_TASK_MANAGER_H
#include "account_task_main.h"
#define ACCOUNT_MULTI_TASK_MAX_SIZE 64
typedef struct {
int32_t count;
AccountTask *taskArray[ACCOUNT_MULTI_TASK_MAX_SIZE];
bool (*isTaskNumUpToMax)(void);
int32_t (*addTaskToManager)(AccountTask *taskBase);
AccountTask *(*getTaskFromManager)(int32_t taskId);
void (*deleteTaskFromManager)(int32_t taskId);
} AccountMultiTaskManager;
#ifdef __cplusplus
extern "C" {
#endif
AccountMultiTaskManager *GetAccountMultiTaskManager(void);
void InitAccountMultiTaskManager(void);
void DestroyAccountMultiTaskManager(void);
#ifdef __cplusplus
}
#endif
#endif
/*
* Copyright (C) 2022 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 ACCOUNT_MULTI_TASK_MANAGER_H
#define ACCOUNT_MULTI_TASK_MANAGER_H
#include "account_task_main.h"
#define ACCOUNT_MULTI_TASK_MAX_SIZE 64
typedef struct {
int32_t count;
AccountTask *taskArray[ACCOUNT_MULTI_TASK_MAX_SIZE];
bool (*isTaskNumUpToMax)(void);
int32_t (*addTaskToManager)(AccountTask *taskBase);
AccountTask *(*getTaskFromManager)(int32_t taskId);
void (*deleteTaskFromManager)(int32_t taskId);
} AccountMultiTaskManager;
#ifdef __cplusplus
extern "C" {
#endif
AccountMultiTaskManager *GetAccountMultiTaskManager(void);
void InitAccountMultiTaskManager(void);
void DestroyAccountMultiTaskManager(void);
#ifdef __cplusplus
}
#endif
#endif
@@ -1,47 +1,47 @@
/*
* Copyright (C) 2022 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 ACCOUNT_TASK_MAIN_H
#define ACCOUNT_TASK_MAIN_H
#include "json_utils.h"
#include "account_module_defines.h"
typedef struct TaskBaseT {
AccountTaskType (*getTaskType)(void);
void (*destroyTask)(struct TaskBaseT *);
int32_t (*process)(struct TaskBaseT *, const CJson *in, CJson *out, int32_t *status);
int32_t taskStatus;
} TaskBase;
typedef struct AccountTaskT {
int32_t taskId;
void (*destroyTask)(struct AccountTaskT *);
int32_t (*processTask)(struct AccountTaskT *, const CJson *in, CJson *out, int32_t *status);
int32_t versionStatus;
TaskBase *subTask;
} AccountTask;
#ifdef __cplusplus
extern "C" {
#endif
AccountTask *CreateAccountTaskT(int32_t *taskId, const CJson *in, CJson *out);
#ifdef __cplusplus
}
#endif
#endif
/*
* Copyright (C) 2022 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 ACCOUNT_TASK_MAIN_H
#define ACCOUNT_TASK_MAIN_H
#include "json_utils.h"
#include "account_module_defines.h"
typedef struct TaskBaseT {
AccountTaskType (*getTaskType)(void);
void (*destroyTask)(struct TaskBaseT *);
int32_t (*process)(struct TaskBaseT *, const CJson *in, CJson *out, int32_t *status);
int32_t taskStatus;
} TaskBase;
typedef struct AccountTaskT {
int32_t taskId;
void (*destroyTask)(struct AccountTaskT *);
int32_t (*processTask)(struct AccountTaskT *, const CJson *in, CJson *out, int32_t *status);
int32_t versionStatus;
TaskBase *subTask;
} AccountTask;
#ifdef __cplusplus
extern "C" {
#endif
AccountTask *CreateAccountTaskT(int32_t *taskId, const CJson *in, CJson *out);
#ifdef __cplusplus
}
#endif
#endif
@@ -1,69 +1,69 @@
/*
* Copyright (C) 2022 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 ACCOUNT_VERSION_UTIL_H
#define ACCOUNT_VERSION_UTIL_H
#include "alg_defs.h"
#include "json_utils.h"
#include "pake_defs.h"
#include "protocol_common.h"
#include "account_task_main.h"
typedef enum {
BIND_VERSION_NO_NONE = 0,
BIND_PAKE_V2_DL = 0x0001,
BIND_PAKE_V2_EC_P256 = 0x0002,
BIND_PAKE_V2_EC_P256_WITH_PROOF = 0x0004,
BIND_PAKE_V2_EC_X25519 = 0x0008,
BIND_PAKE_V1_DL = 0x0010,
} BindVersionNo;
typedef enum {
AUTH_VERSION_NO_NONE = 0,
AUTH_PAKE_V2_EC_P256 = 0x0001,
AUTH_ISO = 0x0002,
} AuthVersionNo;
typedef enum {
VERSION_INITIAL = 0,
VERSION_NEGOTIATION = 1,
VERSION_CONFIRMED = 2,
} AccountVersionStatus;
typedef struct AccountVersionInfoT {
uint64_t versionNo;
ProtocolType protocolType;
PakeAlgType pakeAlgType;
CurveType curveType;
bool withExtraOperation;
bool (*isTaskSupported)(void);
TaskBase *(*createTask)(const CJson *, CJson *, const struct AccountVersionInfoT *);
} AccountVersionInfo;
#ifdef __cplusplus
extern "C" {
#endif
void InitVersionInfos(void);
void DestroyVersionInfos(void);
uint64_t GetSupportedVersionNo(int32_t operationCode);
const AccountVersionInfo *GetNegotiatedVersionInfo(int32_t operationCode, int32_t credentialType);
#ifdef __cplusplus
}
#endif
#endif
/*
* Copyright (C) 2022 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 ACCOUNT_VERSION_UTIL_H
#define ACCOUNT_VERSION_UTIL_H
#include "alg_defs.h"
#include "json_utils.h"
#include "pake_defs.h"
#include "protocol_common.h"
#include "account_task_main.h"
typedef enum {
BIND_VERSION_NO_NONE = 0,
BIND_PAKE_V2_DL = 0x0001,
BIND_PAKE_V2_EC_P256 = 0x0002,
BIND_PAKE_V2_EC_P256_WITH_PROOF = 0x0004,
BIND_PAKE_V2_EC_X25519 = 0x0008,
BIND_PAKE_V1_DL = 0x0010,
} BindVersionNo;
typedef enum {
AUTH_VERSION_NO_NONE = 0,
AUTH_PAKE_V2_EC_P256 = 0x0001,
AUTH_ISO = 0x0002,
} AuthVersionNo;
typedef enum {
VERSION_INITIAL = 0,
VERSION_NEGOTIATION = 1,
VERSION_CONFIRMED = 2,
} AccountVersionStatus;
typedef struct AccountVersionInfoT {
uint64_t versionNo;
ProtocolType protocolType;
PakeAlgType pakeAlgType;
CurveType curveType;
bool withExtraOperation;
bool (*isTaskSupported)(void);
TaskBase *(*createTask)(const CJson *, CJson *, const struct AccountVersionInfoT *);
} AccountVersionInfo;
#ifdef __cplusplus
extern "C" {
#endif
void InitVersionInfos(void);
void DestroyVersionInfos(void);
uint64_t GetSupportedVersionNo(int32_t operationCode);
const AccountVersionInfo *GetNegotiatedVersionInfo(int32_t operationCode, int32_t credentialType);
#ifdef __cplusplus
}
#endif
#endif
@@ -1,39 +1,39 @@
/*
* Copyright (C) 2022 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 ISO_AUTH_CLIENT_TASK_H
#define ISO_AUTH_CLIENT_TASK_H
#include "account_task_main.h"
#include "account_version_util.h"
#include "json_utils.h"
#include "iso_auth_task_common.h"
typedef struct {
TaskBase taskBase;
IsoAuthParams params;
} IsoAuthClientTask;
#ifdef __cplusplus
extern "C" {
#endif
TaskBase *CreateIsoAuthClientTask(const CJson *in, CJson *out, const AccountVersionInfo *verInfo);
#ifdef __cplusplus
}
#endif
/*
* Copyright (C) 2022 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 ISO_AUTH_CLIENT_TASK_H
#define ISO_AUTH_CLIENT_TASK_H
#include "account_task_main.h"
#include "account_version_util.h"
#include "json_utils.h"
#include "iso_auth_task_common.h"
typedef struct {
TaskBase taskBase;
IsoAuthParams params;
} IsoAuthClientTask;
#ifdef __cplusplus
extern "C" {
#endif
TaskBase *CreateIsoAuthClientTask(const CJson *in, CJson *out, const AccountVersionInfo *verInfo);
#ifdef __cplusplus
}
#endif
#endif
@@ -1,39 +1,39 @@
/*
* Copyright (C) 2022 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 ISO_AUTH_SERVER_TASK_H
#define ISO_AUTH_SERVER_TASK_H
#include "account_task_main.h"
#include "account_version_util.h"
#include "json_utils.h"
#include "iso_auth_task_common.h"
typedef struct {
TaskBase taskBase;
IsoAuthParams params;
} IsoAuthServerTask;
#ifdef __cplusplus
extern "C" {
#endif
TaskBase *CreateIsoAuthServerTask(const CJson *in, CJson *out, const AccountVersionInfo *verInfo);
#ifdef __cplusplus
}
#endif
/*
* Copyright (C) 2022 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 ISO_AUTH_SERVER_TASK_H
#define ISO_AUTH_SERVER_TASK_H
#include "account_task_main.h"
#include "account_version_util.h"
#include "json_utils.h"
#include "iso_auth_task_common.h"
typedef struct {
TaskBase taskBase;
IsoAuthParams params;
} IsoAuthServerTask;
#ifdef __cplusplus
extern "C" {
#endif
TaskBase *CreateIsoAuthServerTask(const CJson *in, CJson *out, const AccountVersionInfo *verInfo);
#ifdef __cplusplus
}
#endif
#endif
@@ -1,62 +1,62 @@
/*
* Copyright (C) 2022 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 ISO_AUTH_TASK_COMMON_H
#define ISO_AUTH_TASK_COMMON_H
#include "account_module_defines.h"
#include "account_task_main.h"
#include "account_version_util.h"
#include "iso_protocol_common.h"
#include "json_utils.h"
typedef struct {
uint64_t versionNo;
int32_t authForm;
int32_t credentialType;
int32_t localDevType;
int32_t keyLength;
uint8_t seed[SEED_SIZE];
uint8_t hmacToken[HMAC_TOKEN_SIZE];
Uint8Buff challenge;
Uint8Buff devIdSelf;
Uint8Buff devIdPeer;
char *userIdSelf;
char *userIdPeer;
char *deviceIdSelf;
char *deviceIdPeer;
IsoBaseParams isoBaseParams;
} IsoAuthParams;
#ifdef __cplusplus
extern "C" {
#endif
bool IsIsoAuthTaskSupported(void);
TaskBase *CreateIsoAuthTask(const CJson *in, CJson *out, const AccountVersionInfo *verInfo);
int32_t InitIsoAuthParams(const CJson *in, IsoAuthParams *params, const AccountVersionInfo *verInfo);
void DestroyIsoAuthParams(IsoAuthParams *params);
int32_t AccountAuthGeneratePsk(IsoAuthParams *params);
int32_t ExtractAndVerifyPayload(IsoAuthParams *params, const CJson *in);
int32_t AuthIsoSendFinalToOut(IsoAuthParams *params, CJson *out);
#ifdef __cplusplus
}
#endif
#endif
/*
* Copyright (C) 2022 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 ISO_AUTH_TASK_COMMON_H
#define ISO_AUTH_TASK_COMMON_H
#include "account_module_defines.h"
#include "account_task_main.h"
#include "account_version_util.h"
#include "iso_protocol_common.h"
#include "json_utils.h"
typedef struct {
uint64_t versionNo;
int32_t authForm;
int32_t credentialType;
int32_t localDevType;
int32_t keyLength;
uint8_t seed[SEED_SIZE];
uint8_t hmacToken[HMAC_TOKEN_SIZE];
Uint8Buff challenge;
Uint8Buff devIdSelf;
Uint8Buff devIdPeer;
char *userIdSelf;
char *userIdPeer;
char *deviceIdSelf;
char *deviceIdPeer;
IsoBaseParams isoBaseParams;
} IsoAuthParams;
#ifdef __cplusplus
extern "C" {
#endif
bool IsIsoAuthTaskSupported(void);
TaskBase *CreateIsoAuthTask(const CJson *in, CJson *out, const AccountVersionInfo *verInfo);
int32_t InitIsoAuthParams(const CJson *in, IsoAuthParams *params, const AccountVersionInfo *verInfo);
void DestroyIsoAuthParams(IsoAuthParams *params);
int32_t AccountAuthGeneratePsk(IsoAuthParams *params);
int32_t ExtractAndVerifyPayload(IsoAuthParams *params, const CJson *in);
int32_t AuthIsoSendFinalToOut(IsoAuthParams *params, CJson *out);
#ifdef __cplusplus
}
#endif
#endif
@@ -1,39 +1,39 @@
/*
* Copyright (C) 2022 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 PAKE_V2_AUTH_CLIENT_TASK_H
#define PAKE_V2_AUTH_CLIENT_TASK_H
#include "json_utils.h"
#include "pake_v2_auth_task_common.h"
#include "account_task_main.h"
#include "account_version_util.h"
typedef struct {
TaskBase taskBase;
PakeAuthParams params;
} PakeV2AuthClientTask;
#ifdef __cplusplus
extern "C" {
#endif
TaskBase *CreatePakeV2AuthClientTask(const CJson *in, CJson *out, const AccountVersionInfo *verInfo);
#ifdef __cplusplus
}
#endif
/*
* Copyright (C) 2022 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 PAKE_V2_AUTH_CLIENT_TASK_H
#define PAKE_V2_AUTH_CLIENT_TASK_H
#include "json_utils.h"
#include "pake_v2_auth_task_common.h"
#include "account_task_main.h"
#include "account_version_util.h"
typedef struct {
TaskBase taskBase;
PakeAuthParams params;
} PakeV2AuthClientTask;
#ifdef __cplusplus
extern "C" {
#endif
TaskBase *CreatePakeV2AuthClientTask(const CJson *in, CJson *out, const AccountVersionInfo *verInfo);
#ifdef __cplusplus
}
#endif
#endif
@@ -1,39 +1,39 @@
/*
* Copyright (C) 2022 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 PAKE_V2_AUTH_SERVER_TASK_H
#define PAKE_V2_AUTH_SERVER_TASK_H
#include "json_utils.h"
#include "pake_v2_auth_task_common.h"
#include "account_task_main.h"
#include "account_version_util.h"
typedef struct {
TaskBase taskBase;
PakeAuthParams params;
} PakeV2AuthServerTask;
#ifdef __cplusplus
extern "C" {
#endif
TaskBase *CreatePakeV2AuthServerTask(const CJson *in, CJson *out, const AccountVersionInfo *verInfo);
#ifdef __cplusplus
}
#endif
/*
* Copyright (C) 2022 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 PAKE_V2_AUTH_SERVER_TASK_H
#define PAKE_V2_AUTH_SERVER_TASK_H
#include "json_utils.h"
#include "pake_v2_auth_task_common.h"
#include "account_task_main.h"
#include "account_version_util.h"
typedef struct {
TaskBase taskBase;
PakeAuthParams params;
} PakeV2AuthServerTask;
#ifdef __cplusplus
extern "C" {
#endif
TaskBase *CreatePakeV2AuthServerTask(const CJson *in, CJson *out, const AccountVersionInfo *verInfo);
#ifdef __cplusplus
}
#endif
#endif
@@ -1,76 +1,76 @@
/*
* Copyright (C) 2022 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 PAKE_V2_AUTH_TASK_COMMON_H
#define PAKE_V2_AUTH_TASK_COMMON_H
#include "json_utils.h"
#include "pake_defs.h"
#include "string_util.h"
#include "account_module_defines.h"
#include "account_task_main.h"
#include "account_version_util.h"
typedef struct {
PakeBaseParams pakeParams;
uint64_t versionNo;
int32_t authForm;
int32_t credentialType;
int32_t osAccountId;
int32_t authKeyAlgEncode;
Uint8Buff deviceIdSelf;
Uint8Buff deviceIdPeer;
Uint8Buff devIdSelf;
Uint8Buff devIdPeer;
uint8_t userIdSelf[DEV_AUTH_USER_ID_SIZE];
uint8_t userIdPeer[DEV_AUTH_USER_ID_SIZE];
uint8_t pkSelf[PK_SIZE];
Uint8Buff pkInfoSelf;
Uint8Buff pkInfoSignSelf;
uint8_t pkPeer[PK_SIZE];
Uint8Buff pkInfoPeer;
Uint8Buff pkInfoSignPeer;
} PakeAuthParams;
#ifdef __cplusplus
extern "C" {
#endif
bool IsPakeV2AuthTaskSupported(void);
TaskBase *CreatePakeV2AuthTask(const CJson *in, CJson *out, const AccountVersionInfo *verInfo);
int32_t VerifyPkSignPeer(const PakeAuthParams *params);
int32_t GenerateEcdhSharedKey(PakeAuthParams *params);
int32_t GetPkInfoPeer(PakeAuthParams *params, const CJson *in);
int32_t InitPakeAuthParams(const CJson *in, PakeAuthParams *params, const AccountVersionInfo *verInfo);
void DestroyPakeAuthParams(PakeAuthParams *params);
int32_t ExtractPakePeerId(PakeAuthParams *params, const CJson *in);
int32_t ExtractPakeSelfId(PakeAuthParams *params);
int32_t ExtractPeerDeviceId(PakeAuthParams *params, const CJson *in);
int32_t ExtractPeerDevId(PakeAuthParams *params, const CJson *in);
#ifdef __cplusplus
}
#endif
#endif
/*
* Copyright (C) 2022 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 PAKE_V2_AUTH_TASK_COMMON_H
#define PAKE_V2_AUTH_TASK_COMMON_H
#include "json_utils.h"
#include "pake_defs.h"
#include "string_util.h"
#include "account_module_defines.h"
#include "account_task_main.h"
#include "account_version_util.h"
typedef struct {
PakeBaseParams pakeParams;
uint64_t versionNo;
int32_t authForm;
int32_t credentialType;
int32_t osAccountId;
int32_t authKeyAlgEncode;
Uint8Buff deviceIdSelf;
Uint8Buff deviceIdPeer;
Uint8Buff devIdSelf;
Uint8Buff devIdPeer;
uint8_t userIdSelf[DEV_AUTH_USER_ID_SIZE];
uint8_t userIdPeer[DEV_AUTH_USER_ID_SIZE];
uint8_t pkSelf[PK_SIZE];
Uint8Buff pkInfoSelf;
Uint8Buff pkInfoSignSelf;
uint8_t pkPeer[PK_SIZE];
Uint8Buff pkInfoPeer;
Uint8Buff pkInfoSignPeer;
} PakeAuthParams;
#ifdef __cplusplus
extern "C" {
#endif
bool IsPakeV2AuthTaskSupported(void);
TaskBase *CreatePakeV2AuthTask(const CJson *in, CJson *out, const AccountVersionInfo *verInfo);
int32_t VerifyPkSignPeer(const PakeAuthParams *params);
int32_t GenerateEcdhSharedKey(PakeAuthParams *params);
int32_t GetPkInfoPeer(PakeAuthParams *params, const CJson *in);
int32_t InitPakeAuthParams(const CJson *in, PakeAuthParams *params, const AccountVersionInfo *verInfo);
void DestroyPakeAuthParams(PakeAuthParams *params);
int32_t ExtractPakePeerId(PakeAuthParams *params, const CJson *in);
int32_t ExtractPakeSelfId(PakeAuthParams *params);
int32_t ExtractPeerDeviceId(PakeAuthParams *params, const CJson *in);
int32_t ExtractPeerDevId(PakeAuthParams *params, const CJson *in);
#ifdef __cplusplus
}
#endif
#endif
@@ -75,17 +75,4 @@ typedef enum CurTaskTypeT {
TASK_TYPE_NONE,
} CurTaskType;
typedef enum {
KEY_ALIAS_ACCESSOR_PK = DEVICE_TYPE_ACCESSORY,
KEY_ALIAS_CONTROLLER_PK = DEVICE_TYPE_CONTROLLER,
KEY_ALIAS_LT_KEY_PAIR = 2,
KEY_ALIAS_KEK = 3,
KEY_ALIAS_DEK = 4,
KEY_ALIAS_TMP = 5,
KEY_ALIAS_PSK = 6,
KEY_ALIAS_AUTH_TOKEN = 7,
KEY_ALIAS_TYPE_END
} KeyAliasType; // 0 ~ 2^8-1, don't change the order
#endif
@@ -17,6 +17,7 @@
#define DAS_COMMON_H
#include "das_module_defines.h"
#include "identity_defines.h"
#include "hc_types.h"
#include "json_utils.h"
#include "string_util.h"
@@ -1,128 +1,128 @@
/*
* Copyright (C) 2022 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 "account_multi_task_manager.h"
#include "device_auth.h"
#include "device_auth_defines.h"
#include "hc_log.h"
#include "hc_types.h"
static AccountMultiTaskManager g_taskManager;
static bool IsManagerHasTaskId(int32_t taskId)
{
for (uint32_t i = 0; i < ACCOUNT_MULTI_TASK_MAX_SIZE; ++i) {
if (g_taskManager.taskArray[i] != NULL && taskId == g_taskManager.taskArray[i]->taskId) {
LOGD("Task already exists, taskId: %d.", taskId);
return true;
}
}
LOGD("Multi auth manager do not has task id(%d).", taskId);
return false;
}
static bool IsTaskNumUpToMax(void)
{
if (g_taskManager.count >= ACCOUNT_MULTI_TASK_MAX_SIZE) {
LOGD("The number of tasks reaches maximun.");
return true;
}
return false;
}
static bool CanAddTaskInManager(int32_t taskId)
{
if (IsTaskNumUpToMax()) {
LOGE("Task number is up to limit.");
return false;
}
if (IsManagerHasTaskId(taskId)) {
LOGE("Task id is already in exist.");
return false;
}
return true;
}
static int32_t AddTaskToManager(AccountTask *task)
{
if (task == NULL) {
LOGE("Task is null.");
return HC_ERR_NULL_PTR;
}
if (!CanAddTaskInManager(task->taskId)) {
LOGE("Can not add task into manager.");
return HC_ERR_ADD_ACCOUNT_TASK;
}
for (uint32_t i = 0; i < ACCOUNT_MULTI_TASK_MAX_SIZE; ++i) {
if (g_taskManager.taskArray[i] == NULL) {
g_taskManager.taskArray[i] = task;
g_taskManager.count++;
return HC_SUCCESS;
}
}
LOGE("There is no empty space in the task manager.");
return HC_ERR_OUT_OF_LIMIT;
}
static AccountTask *GetTaskFromManager(int32_t taskId)
{
for (uint32_t i = 0; i < ACCOUNT_MULTI_TASK_MAX_SIZE; ++i) {
if ((g_taskManager.taskArray[i] != NULL) && (g_taskManager.taskArray[i]->taskId == taskId)) {
return g_taskManager.taskArray[i];
}
}
LOGE("Task does not exist, taskId: %d.", taskId);
return NULL;
}
static void DeleteTaskFromManager(int32_t taskId)
{
for (uint32_t i = 0; i < ACCOUNT_MULTI_TASK_MAX_SIZE; ++i) {
if ((g_taskManager.taskArray[i] != NULL) && (g_taskManager.taskArray[i]->taskId == taskId)) {
g_taskManager.taskArray[i]->destroyTask(g_taskManager.taskArray[i]);
g_taskManager.taskArray[i] = NULL;
g_taskManager.count--;
}
}
}
void InitAccountMultiTaskManager(void)
{
DestroyAccountMultiTaskManager();
g_taskManager.count = 0;
g_taskManager.isTaskNumUpToMax = IsTaskNumUpToMax;
g_taskManager.addTaskToManager = AddTaskToManager;
g_taskManager.getTaskFromManager = GetTaskFromManager;
g_taskManager.deleteTaskFromManager = DeleteTaskFromManager;
}
AccountMultiTaskManager *GetAccountMultiTaskManager(void)
{
return &g_taskManager;
}
void DestroyAccountMultiTaskManager(void)
{
for (uint32_t i = 0; i < ACCOUNT_MULTI_TASK_MAX_SIZE; ++i) {
if (g_taskManager.taskArray[i] != NULL) {
if (g_taskManager.taskArray[i]->destroyTask != NULL) {
g_taskManager.taskArray[i]->destroyTask(g_taskManager.taskArray[i]);
}
g_taskManager.taskArray[i] = NULL;
}
}
(void)memset_s(&g_taskManager, sizeof(AccountMultiTaskManager), 0, sizeof(AccountMultiTaskManager));
/*
* Copyright (C) 2022 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 "account_multi_task_manager.h"
#include "device_auth.h"
#include "device_auth_defines.h"
#include "hc_log.h"
#include "hc_types.h"
static AccountMultiTaskManager g_taskManager;
static bool IsManagerHasTaskId(int32_t taskId)
{
for (uint32_t i = 0; i < ACCOUNT_MULTI_TASK_MAX_SIZE; ++i) {
if (g_taskManager.taskArray[i] != NULL && taskId == g_taskManager.taskArray[i]->taskId) {
LOGD("Task already exists, taskId: %d.", taskId);
return true;
}
}
LOGD("Multi auth manager do not has task id(%d).", taskId);
return false;
}
static bool IsTaskNumUpToMax(void)
{
if (g_taskManager.count >= ACCOUNT_MULTI_TASK_MAX_SIZE) {
LOGD("The number of tasks reaches maximun.");
return true;
}
return false;
}
static bool CanAddTaskInManager(int32_t taskId)
{
if (IsTaskNumUpToMax()) {
LOGE("Task number is up to limit.");
return false;
}
if (IsManagerHasTaskId(taskId)) {
LOGE("Task id is already in exist.");
return false;
}
return true;
}
static int32_t AddTaskToManager(AccountTask *task)
{
if (task == NULL) {
LOGE("Task is null.");
return HC_ERR_NULL_PTR;
}
if (!CanAddTaskInManager(task->taskId)) {
LOGE("Can not add task into manager.");
return HC_ERR_ADD_ACCOUNT_TASK;
}
for (uint32_t i = 0; i < ACCOUNT_MULTI_TASK_MAX_SIZE; ++i) {
if (g_taskManager.taskArray[i] == NULL) {
g_taskManager.taskArray[i] = task;
g_taskManager.count++;
return HC_SUCCESS;
}
}
LOGE("There is no empty space in the task manager.");
return HC_ERR_OUT_OF_LIMIT;
}
static AccountTask *GetTaskFromManager(int32_t taskId)
{
for (uint32_t i = 0; i < ACCOUNT_MULTI_TASK_MAX_SIZE; ++i) {
if ((g_taskManager.taskArray[i] != NULL) && (g_taskManager.taskArray[i]->taskId == taskId)) {
return g_taskManager.taskArray[i];
}
}
LOGE("Task does not exist, taskId: %d.", taskId);
return NULL;
}
static void DeleteTaskFromManager(int32_t taskId)
{
for (uint32_t i = 0; i < ACCOUNT_MULTI_TASK_MAX_SIZE; ++i) {
if ((g_taskManager.taskArray[i] != NULL) && (g_taskManager.taskArray[i]->taskId == taskId)) {
g_taskManager.taskArray[i]->destroyTask(g_taskManager.taskArray[i]);
g_taskManager.taskArray[i] = NULL;
g_taskManager.count--;
}
}
}
void InitAccountMultiTaskManager(void)
{
DestroyAccountMultiTaskManager();
g_taskManager.count = 0;
g_taskManager.isTaskNumUpToMax = IsTaskNumUpToMax;
g_taskManager.addTaskToManager = AddTaskToManager;
g_taskManager.getTaskFromManager = GetTaskFromManager;
g_taskManager.deleteTaskFromManager = DeleteTaskFromManager;
}
AccountMultiTaskManager *GetAccountMultiTaskManager(void)
{
return &g_taskManager;
}
void DestroyAccountMultiTaskManager(void)
{
for (uint32_t i = 0; i < ACCOUNT_MULTI_TASK_MAX_SIZE; ++i) {
if (g_taskManager.taskArray[i] != NULL) {
if (g_taskManager.taskArray[i]->destroyTask != NULL) {
g_taskManager.taskArray[i]->destroyTask(g_taskManager.taskArray[i]);
}
g_taskManager.taskArray[i] = NULL;
}
}
(void)memset_s(&g_taskManager, sizeof(AccountMultiTaskManager), 0, sizeof(AccountMultiTaskManager));
}
@@ -1,221 +1,221 @@
/*
* Copyright (C) 2022 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 "account_task_main.h"
#include "alg_defs.h"
#include "alg_loader.h"
#include "common_defs.h"
#include "device_auth.h"
#include "device_auth_defines.h"
#include "clib_error.h"
#include "hc_log.h"
#include "json_utils.h"
#include "account_version_util.h"
static void AccountSendErrMsgToSelf(CJson *out, int32_t errCode)
{
CJson *sendToSelf = CreateJson();
if (sendToSelf == NULL) {
LOGE("Create sendToSelf json failed.");
return;
}
if (AddIntToJson(sendToSelf, FIELD_ERROR_CODE, errCode) != CLIB_SUCCESS) {
LOGE("Add errCode to self json failed.");
FreeJson(sendToSelf);
return;
}
if (AddObjToJson(out, FIELD_SEND_TO_SELF, sendToSelf) != CLIB_SUCCESS) {
LOGE("Add sendToSelf obj to out json failed.");
FreeJson(sendToSelf);
return;
}
FreeJson(sendToSelf);
}
static void AccountSendErrMsgToOut(CJson *out, int32_t opCode, int32_t errCode)
{
CJson *sendToSelf = CreateJson();
if (sendToSelf == NULL) {
LOGE("Create sendToSelf json failed.");
return;
}
CJson *sendToPeer = CreateJson();
if (sendToPeer == NULL) {
LOGE("Create sendToPeer json failed.");
FreeJson(sendToSelf);
return;
}
if (opCode == OP_BIND) {
if (AddIntToJson(sendToPeer, FIELD_MESSAGE, ERR_MSG) != CLIB_SUCCESS) {
LOGE("Failed to add error message to json for bind.");
goto CLEAN_UP;
}
} else {
if (AddIntToJson(sendToPeer, FIELD_STEP, ERR_MSG) != CLIB_SUCCESS) {
LOGE("Failed to add error message to json for auth.");
goto CLEAN_UP;
}
}
if (AddIntToJson(sendToPeer, FIELD_ERROR_CODE, errCode) != CLIB_SUCCESS) {
LOGE("Add errCode to json failed.");
goto CLEAN_UP;
}
if (AddIntToJson(sendToSelf, FIELD_AUTH_FORM, ACCOUNT_MODULE) != CLIB_SUCCESS) {
LOGE("Add auth form to json failed.");
goto CLEAN_UP;
}
if (AddObjToJson(out, FIELD_SEND_TO_PEER, sendToPeer) != CLIB_SUCCESS) {
LOGE("Add sendToPeer to json failed.");
goto CLEAN_UP;
}
if (AddObjToJson(out, FIELD_SEND_TO_SELF, sendToSelf) != CLIB_SUCCESS) {
LOGE("Add sendToSelf to json failed.");
goto CLEAN_UP;
}
CLEAN_UP:
FreeJson(sendToPeer);
FreeJson(sendToSelf);
return;
}
static void DestroyTaskT(AccountTask *task)
{
if (task == NULL) {
return;
}
if (task->subTask != NULL) {
task->subTask->destroyTask(task->subTask);
}
HcFree(task);
}
static bool IsPeerErrMessage(const CJson *in)
{
int32_t res = 0;
int32_t message = 0;
if ((GetIntFromJson(in, FIELD_MESSAGE, &message) != CLIB_SUCCESS) &&
(GetIntFromJson(in, FIELD_STEP, &message) != CLIB_SUCCESS)) {
LOGD("There is no message code."); // The first message of the client has no message code
return false;
}
if (message != ERR_MSG) {
return false;
}
if (GetIntFromJson(in, FIELD_ERROR_CODE, &res) != CLIB_SUCCESS) {
LOGE("Get peer error code failed.");
}
LOGE("Receive error message from peer, errCode: %x.", res);
return true;
}
static int32_t MapSubTaskTypeToOpCode(AccountTaskType subTaskType)
{
if (subTaskType >= TASK_TYPE_PAKE_V2_AUTH_CLIENT && subTaskType <= TASK_TYPE_ISO_AUTH_SERVER) {
return AUTHENTICATE;
}
return CODE_NULL;
}
static int32_t ProcessTaskT(AccountTask *task, const CJson *in, CJson *out, int32_t *status)
{
if (IsPeerErrMessage(in)) {
AccountSendErrMsgToSelf(out, HC_ERR_PEER_ERROR);
return HC_ERR_PEER_ERROR;
}
int32_t res = task->subTask->process(task->subTask, in, out, status);
if (res != HC_SUCCESS) {
LOGE("Process subTask failed, res: %x.", res);
int32_t operationCode = MapSubTaskTypeToOpCode(task->subTask->getTaskType());
AccountSendErrMsgToOut(out, operationCode, res);
}
return res;
}
static int32_t NegotiateAndCreateSubTask(AccountTask *task, const CJson *in, CJson *out)
{
int32_t operationCode = 0;
int32_t credentialType = INVALID_CRED;
if (GetIntFromJson(in, FIELD_OPERATION_CODE, &operationCode) != CLIB_SUCCESS) {
LOGE("Get operationCode from json failed.");
return HC_ERR_JSON_GET;
}
if (GetIntFromJson(in, FIELD_CREDENTIAL_TYPE, &credentialType) != CLIB_SUCCESS) {
LOGE("Failed to get credential type from input data.");
return HC_ERR_JSON_GET;
}
const AccountVersionInfo *verInfo = GetNegotiatedVersionInfo(operationCode, credentialType);
if (verInfo == NULL) {
LOGE("Get Negotiated versionInfo failed.");
return HC_ERR_UNSUPPORTED_VERSION;
}
task->subTask = verInfo->createTask(in, out, verInfo);
if (task->subTask == NULL) {
LOGE("Create sub task failed.");
return HC_ERR_ALLOC_MEMORY;
}
task->versionStatus = VERSION_CONFIRMED;
return HC_SUCCESS;
}
static void AccountSendCreateError(const CJson *in, CJson *out, int32_t errCode)
{
bool isClient = false;
if (GetBoolFromJson(in, FIELD_IS_CLIENT, &isClient) != CLIB_SUCCESS) {
LOGE("Get isClient from json failed.");
}
if (isClient) {
AccountSendErrMsgToSelf(out, errCode);
return;
}
int32_t operationCode = CODE_NULL;
if (GetIntFromJson(in, FIELD_OPERATION_CODE, &operationCode) != CLIB_SUCCESS) {
LOGE("Get operationCode from json failed.");
} else {
AccountSendErrMsgToOut(out, operationCode, errCode);
}
}
AccountTask *CreateAccountTaskT(int32_t *taskId, const CJson *in, CJson *out)
{
int32_t res;
AccountTask *task = (AccountTask *)HcMalloc(sizeof(AccountTask), 0);
if (task == NULL) {
LOGE("Malloc for account related task failed.");
res = HC_ERR_ALLOC_MEMORY;
goto ERR;
}
task->destroyTask = DestroyTaskT;
task->processTask = ProcessTaskT;
task->versionStatus = VERSION_INITIAL;
Uint8Buff taskIdBuf = { (uint8_t *)taskId, sizeof(int32_t) };
res = GetLoaderInstance()->generateRandom(&taskIdBuf);
if (res != HC_SUCCESS) {
LOGE("Generate taskId failed, res: %d.", res);
goto ERR;
}
task->taskId = *taskId;
res = NegotiateAndCreateSubTask(task, in, out);
if (res != HC_SUCCESS) {
LOGE("NegotiateAndCreateSubTask failed, res: %d.", res);
goto ERR;
}
return task;
ERR:
AccountSendCreateError(in, out, res);
DestroyTaskT(task);
return NULL;
}
/*
* Copyright (C) 2022 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 "account_task_main.h"
#include "alg_defs.h"
#include "alg_loader.h"
#include "common_defs.h"
#include "device_auth.h"
#include "device_auth_defines.h"
#include "clib_error.h"
#include "hc_log.h"
#include "json_utils.h"
#include "account_version_util.h"
static void AccountSendErrMsgToSelf(CJson *out, int32_t errCode)
{
CJson *sendToSelf = CreateJson();
if (sendToSelf == NULL) {
LOGE("Create sendToSelf json failed.");
return;
}
if (AddIntToJson(sendToSelf, FIELD_ERROR_CODE, errCode) != CLIB_SUCCESS) {
LOGE("Add errCode to self json failed.");
FreeJson(sendToSelf);
return;
}
if (AddObjToJson(out, FIELD_SEND_TO_SELF, sendToSelf) != CLIB_SUCCESS) {
LOGE("Add sendToSelf obj to out json failed.");
FreeJson(sendToSelf);
return;
}
FreeJson(sendToSelf);
}
static void AccountSendErrMsgToOut(CJson *out, int32_t opCode, int32_t errCode)
{
CJson *sendToSelf = CreateJson();
if (sendToSelf == NULL) {
LOGE("Create sendToSelf json failed.");
return;
}
CJson *sendToPeer = CreateJson();
if (sendToPeer == NULL) {
LOGE("Create sendToPeer json failed.");
FreeJson(sendToSelf);
return;
}
if (opCode == OP_BIND) {
if (AddIntToJson(sendToPeer, FIELD_MESSAGE, ERR_MSG) != CLIB_SUCCESS) {
LOGE("Failed to add error message to json for bind.");
goto CLEAN_UP;
}
} else {
if (AddIntToJson(sendToPeer, FIELD_STEP, ERR_MSG) != CLIB_SUCCESS) {
LOGE("Failed to add error message to json for auth.");
goto CLEAN_UP;
}
}
if (AddIntToJson(sendToPeer, FIELD_ERROR_CODE, errCode) != CLIB_SUCCESS) {
LOGE("Add errCode to json failed.");
goto CLEAN_UP;
}
if (AddIntToJson(sendToSelf, FIELD_AUTH_FORM, ACCOUNT_MODULE) != CLIB_SUCCESS) {
LOGE("Add auth form to json failed.");
goto CLEAN_UP;
}
if (AddObjToJson(out, FIELD_SEND_TO_PEER, sendToPeer) != CLIB_SUCCESS) {
LOGE("Add sendToPeer to json failed.");
goto CLEAN_UP;
}
if (AddObjToJson(out, FIELD_SEND_TO_SELF, sendToSelf) != CLIB_SUCCESS) {
LOGE("Add sendToSelf to json failed.");
goto CLEAN_UP;
}
CLEAN_UP:
FreeJson(sendToPeer);
FreeJson(sendToSelf);
return;
}
static void DestroyTaskT(AccountTask *task)
{
if (task == NULL) {
return;
}
if (task->subTask != NULL) {
task->subTask->destroyTask(task->subTask);
}
HcFree(task);
}
static bool IsPeerErrMessage(const CJson *in)
{
int32_t res = 0;
int32_t message = 0;
if ((GetIntFromJson(in, FIELD_MESSAGE, &message) != CLIB_SUCCESS) &&
(GetIntFromJson(in, FIELD_STEP, &message) != CLIB_SUCCESS)) {
LOGD("There is no message code."); // The first message of the client has no message code
return false;
}
if (message != ERR_MSG) {
return false;
}
if (GetIntFromJson(in, FIELD_ERROR_CODE, &res) != CLIB_SUCCESS) {
LOGE("Get peer error code failed.");
}
LOGE("Receive error message from peer, errCode: %x.", res);
return true;
}
static int32_t MapSubTaskTypeToOpCode(AccountTaskType subTaskType)
{
if (subTaskType >= TASK_TYPE_PAKE_V2_AUTH_CLIENT && subTaskType <= TASK_TYPE_ISO_AUTH_SERVER) {
return AUTHENTICATE;
}
return CODE_NULL;
}
static int32_t ProcessTaskT(AccountTask *task, const CJson *in, CJson *out, int32_t *status)
{
if (IsPeerErrMessage(in)) {
AccountSendErrMsgToSelf(out, HC_ERR_PEER_ERROR);
return HC_ERR_PEER_ERROR;
}
int32_t res = task->subTask->process(task->subTask, in, out, status);
if (res != HC_SUCCESS) {
LOGE("Process subTask failed, res: %x.", res);
int32_t operationCode = MapSubTaskTypeToOpCode(task->subTask->getTaskType());
AccountSendErrMsgToOut(out, operationCode, res);
}
return res;
}
static int32_t NegotiateAndCreateSubTask(AccountTask *task, const CJson *in, CJson *out)
{
int32_t operationCode = 0;
int32_t credentialType = INVALID_CRED;
if (GetIntFromJson(in, FIELD_OPERATION_CODE, &operationCode) != CLIB_SUCCESS) {
LOGE("Get operationCode from json failed.");
return HC_ERR_JSON_GET;
}
if (GetIntFromJson(in, FIELD_CREDENTIAL_TYPE, &credentialType) != CLIB_SUCCESS) {
LOGE("Failed to get credential type from input data.");
return HC_ERR_JSON_GET;
}
const AccountVersionInfo *verInfo = GetNegotiatedVersionInfo(operationCode, credentialType);
if (verInfo == NULL) {
LOGE("Get Negotiated versionInfo failed.");
return HC_ERR_UNSUPPORTED_VERSION;
}
task->subTask = verInfo->createTask(in, out, verInfo);
if (task->subTask == NULL) {
LOGE("Create sub task failed.");
return HC_ERR_ALLOC_MEMORY;
}
task->versionStatus = VERSION_CONFIRMED;
return HC_SUCCESS;
}
static void AccountSendCreateError(const CJson *in, CJson *out, int32_t errCode)
{
bool isClient = false;
if (GetBoolFromJson(in, FIELD_IS_CLIENT, &isClient) != CLIB_SUCCESS) {
LOGE("Get isClient from json failed.");
}
if (isClient) {
AccountSendErrMsgToSelf(out, errCode);
return;
}
int32_t operationCode = CODE_NULL;
if (GetIntFromJson(in, FIELD_OPERATION_CODE, &operationCode) != CLIB_SUCCESS) {
LOGE("Get operationCode from json failed.");
} else {
AccountSendErrMsgToOut(out, operationCode, errCode);
}
}
AccountTask *CreateAccountTaskT(int32_t *taskId, const CJson *in, CJson *out)
{
int32_t res;
AccountTask *task = (AccountTask *)HcMalloc(sizeof(AccountTask), 0);
if (task == NULL) {
LOGE("Malloc for account related task failed.");
res = HC_ERR_ALLOC_MEMORY;
goto ERR;
}
task->destroyTask = DestroyTaskT;
task->processTask = ProcessTaskT;
task->versionStatus = VERSION_INITIAL;
Uint8Buff taskIdBuf = { (uint8_t *)taskId, sizeof(int32_t) };
res = GetLoaderInstance()->generateRandom(&taskIdBuf);
if (res != HC_SUCCESS) {
LOGE("Generate taskId failed, res: %d.", res);
goto ERR;
}
task->taskId = *taskId;
res = NegotiateAndCreateSubTask(task, in, out);
if (res != HC_SUCCESS) {
LOGE("NegotiateAndCreateSubTask failed, res: %d.", res);
goto ERR;
}
return task;
ERR:
AccountSendCreateError(in, out, res);
DestroyTaskT(task);
return NULL;
}
@@ -1,106 +1,106 @@
/*
* Copyright (C) 2022 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 "account_version_util.h"
#include "common_defs.h"
#include "hc_log.h"
#include "hc_types.h"
#include "iso_auth_task_common.h"
#include "pake_defs.h"
#include "pake_protocol_dl_common.h"
#include "pake_protocol_ec_common.h"
#include "pake_v2_auth_task_common.h"
#define IS_SUPPORT_CURVE_256 true
#define IS_SUPPORT_CURVE_25519 false
DECLARE_HC_VECTOR(AccountVersionInfoVec, void *)
IMPLEMENT_HC_VECTOR(AccountVersionInfoVec, void *, 1)
static AccountVersionInfoVec g_authVersionInfoVec;
static uint64_t g_authVersionNo = 0;
static bool IsAuthPakeV2EcP256Supported(void)
{
return IsPakeV2AuthTaskSupported() && (GetPakeEcAlg() == PAKE_ALG_EC) && IS_SUPPORT_CURVE_256;
}
static bool IsAuthIsoSupported(void)
{
return IsIsoAuthTaskSupported();
}
static AccountVersionInfo g_authVersionInfoAll[] = {
{ AUTH_PAKE_V2_EC_P256, PAKE_V2, PAKE_ALG_EC, CURVE_256, false, IsAuthPakeV2EcP256Supported, CreatePakeV2AuthTask},
{ AUTH_ISO, ISO, PAKE_ALG_NONE, CURVE_NONE, false, IsAuthIsoSupported, CreateIsoAuthTask }
};
void InitVersionInfos(void)
{
g_authVersionInfoVec = CREATE_HC_VECTOR(AccountVersionInfoVec);
uint32_t size = sizeof(g_authVersionInfoAll) / sizeof(AccountVersionInfo);
for (uint32_t i = 0; i < size; i++) {
if (!g_authVersionInfoAll[i].isTaskSupported()) {
continue;
}
(void)g_authVersionInfoVec.pushBackT(&g_authVersionInfoVec, (void *)(&g_authVersionInfoAll[i]));
g_authVersionNo |= g_authVersionInfoAll[i].versionNo;
}
}
void DestroyVersionInfos(void)
{
DESTROY_HC_VECTOR(AccountVersionInfoVec, &g_authVersionInfoVec);
}
static const AccountVersionInfo *NegotiateForAuth(int32_t credentialType)
{
uint64_t versionNo;
if (credentialType == SYMMETRIC_CRED) {
versionNo = AUTH_ISO;
} else if (credentialType == ASYMMETRIC_CRED) {
versionNo = AUTH_PAKE_V2_EC_P256;
} else {
LOGE("Invalid credential type for auth: %d.", credentialType);
return NULL;
}
uint32_t index;
void **ptr = NULL;
FOR_EACH_HC_VECTOR(g_authVersionInfoVec, index, ptr) {
AccountVersionInfo *temp = (AccountVersionInfo *)(*ptr);
if ((temp->versionNo & versionNo) == versionNo) {
return temp;
}
}
LOGE("Version is not matched, failed to negotiate for account auth.");
return NULL;
}
const AccountVersionInfo *GetNegotiatedVersionInfo(int32_t operationCode, int32_t credentialType)
{
// Now, only support auth negotiate.
if (operationCode != AUTHENTICATE) {
LOGE("operationCode is not auth, not supported.");
return NULL;
}
return NegotiateForAuth(credentialType);
}
uint64_t GetSupportedVersionNo(int32_t operationCode)
{
(void)operationCode; // Now, only support auth negotiate.
return g_authVersionNo;
}
/*
* Copyright (C) 2022 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 "account_version_util.h"
#include "common_defs.h"
#include "hc_log.h"
#include "hc_types.h"
#include "iso_auth_task_common.h"
#include "pake_defs.h"
#include "pake_protocol_dl_common.h"
#include "pake_protocol_ec_common.h"
#include "pake_v2_auth_task_common.h"
#define IS_SUPPORT_CURVE_256 true
#define IS_SUPPORT_CURVE_25519 false
DECLARE_HC_VECTOR(AccountVersionInfoVec, void *)
IMPLEMENT_HC_VECTOR(AccountVersionInfoVec, void *, 1)
static AccountVersionInfoVec g_authVersionInfoVec;
static uint64_t g_authVersionNo = 0;
static bool IsAuthPakeV2EcP256Supported(void)
{
return IsPakeV2AuthTaskSupported() && (GetPakeEcAlg() == PAKE_ALG_EC) && IS_SUPPORT_CURVE_256;
}
static bool IsAuthIsoSupported(void)
{
return IsIsoAuthTaskSupported();
}
static AccountVersionInfo g_authVersionInfoAll[] = {
{ AUTH_PAKE_V2_EC_P256, PAKE_V2, PAKE_ALG_EC, CURVE_256, false, IsAuthPakeV2EcP256Supported, CreatePakeV2AuthTask},
{ AUTH_ISO, ISO, PAKE_ALG_NONE, CURVE_NONE, false, IsAuthIsoSupported, CreateIsoAuthTask }
};
void InitVersionInfos(void)
{
g_authVersionInfoVec = CREATE_HC_VECTOR(AccountVersionInfoVec);
uint32_t size = sizeof(g_authVersionInfoAll) / sizeof(AccountVersionInfo);
for (uint32_t i = 0; i < size; i++) {
if (!g_authVersionInfoAll[i].isTaskSupported()) {
continue;
}
(void)g_authVersionInfoVec.pushBackT(&g_authVersionInfoVec, (void *)(&g_authVersionInfoAll[i]));
g_authVersionNo |= g_authVersionInfoAll[i].versionNo;
}
}
void DestroyVersionInfos(void)
{
DESTROY_HC_VECTOR(AccountVersionInfoVec, &g_authVersionInfoVec);
}
static const AccountVersionInfo *NegotiateForAuth(int32_t credentialType)
{
uint64_t versionNo;
if (credentialType == SYMMETRIC_CRED) {
versionNo = AUTH_ISO;
} else if (credentialType == ASYMMETRIC_CRED) {
versionNo = AUTH_PAKE_V2_EC_P256;
} else {
LOGE("Invalid credential type for auth: %d.", credentialType);
return NULL;
}
uint32_t index;
void **ptr = NULL;
FOR_EACH_HC_VECTOR(g_authVersionInfoVec, index, ptr) {
AccountVersionInfo *temp = (AccountVersionInfo *)(*ptr);
if ((temp->versionNo & versionNo) == versionNo) {
return temp;
}
}
LOGE("Version is not matched, failed to negotiate for account auth.");
return NULL;
}
const AccountVersionInfo *GetNegotiatedVersionInfo(int32_t operationCode, int32_t credentialType)
{
// Now, only support auth negotiate.
if (operationCode != AUTHENTICATE) {
LOGE("operationCode is not auth, not supported.");
return NULL;
}
return NegotiateForAuth(credentialType);
}
uint64_t GetSupportedVersionNo(int32_t operationCode)
{
(void)operationCode; // Now, only support auth negotiate.
return g_authVersionNo;
}
@@ -1,387 +1,387 @@
/*
* Copyright (C) 2022 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 "iso_auth_client_task.h"
#include "account_module_defines.h"
#include "clib_error.h"
#include "common_defs.h"
#include "device_auth.h"
#include "device_auth_defines.h"
#include "hc_log.h"
#include "hc_types.h"
#include "iso_auth_task_common.h"
#include "iso_protocol_common.h"
#include "protocol_common.h"
enum {
TASK_STATUS_ISO_MAIN_BEGIN = 0,
TASK_STATUS_ISO_MAIN_STEP_ONE = 1,
TASK_STATUS_ISO_MAIN_STEP_TWO = 2,
TASK_STATUS_ISO_MAIN_END = 3,
};
static AccountTaskType GetIsoAuthClientType(void)
{
return TASK_TYPE_ISO_AUTH_CLIENT;
}
static int32_t AddBeginDataToJson(const IsoAuthParams *params, CJson *sendToPeer)
{
CJson *data = CreateJson();
if (data == NULL) {
LOGE("Create data json failed.");
return HC_ERR_JSON_CREATE;
}
if (AddByteToJson(data, FIELD_SALT,
params->isoBaseParams.randSelf.val, params->isoBaseParams.randSelf.length) != CLIB_SUCCESS) {
LOGE("Add saltSelf to json failed.");
goto CLEAN_UP;
}
if (AddByteToJson(data, FIELD_PAYLOAD,
params->isoBaseParams.authIdSelf.val, params->isoBaseParams.authIdSelf.length) != CLIB_SUCCESS) {
LOGE("Add payloadSelf to json failed.");
goto CLEAN_UP;
}
if (AddByteToJson(data, FIELD_SEED, params->seed, sizeof(params->seed)) != CLIB_SUCCESS) {
LOGE("Add seed to json failed.");
goto CLEAN_UP;
}
if (AddObjToJson(sendToPeer, FIELD_DATA, data) != CLIB_SUCCESS) {
LOGE("Add data json obj to json failed.");
goto CLEAN_UP;
}
FreeJson(data);
return HC_SUCCESS;
CLEAN_UP:
FreeJson(data);
return HC_ERR_JSON_ADD;
}
static int32_t PackIsoAuthClientBeginMsg(const IsoAuthParams *params, CJson *out)
{
CJson *sendToPeer = CreateJson();
if (sendToPeer == NULL) {
LOGE("Create sendToPeer json failed.");
return HC_ERR_JSON_CREATE;
}
if (AddIntToJson(sendToPeer, FIELD_AUTH_FORM, params->authForm) != CLIB_SUCCESS) {
LOGE("Add authForm to json failed.");
goto CLEAN_UP;
}
if (AddIntToJson(sendToPeer, FIELD_STEP, CMD_ISO_AUTH_MAIN_ONE) != CLIB_SUCCESS) {
LOGE("Add step code to json failed.");
goto CLEAN_UP;
}
if (AddIntToJson(sendToPeer, FIELD_CREDENTIAL_TYPE, params->credentialType) != CLIB_SUCCESS) {
LOGE("Add credentialType to json failed.");
goto CLEAN_UP;
}
if (AddStringToJson(sendToPeer, FIELD_USER_ID, params->userIdSelf) != CLIB_SUCCESS) {
LOGE("Add userIdSelf to json failed.");
goto CLEAN_UP;
}
if (AddByteToJson(sendToPeer, FIELD_DEV_ID, params->devIdSelf.val, params->devIdSelf.length) != CLIB_SUCCESS) {
LOGE("Add devIdSelf to json failed.");
goto CLEAN_UP;
}
if (AddStringToJson(sendToPeer, FIELD_DEVICE_ID, params->deviceIdSelf) != CLIB_SUCCESS) {
LOGE("Add deviceIdSelf to json failed.");
goto CLEAN_UP;
}
if (AddBeginDataToJson(params, sendToPeer) != HC_SUCCESS) {
LOGE("AddBeginDataToJson failed.");
goto CLEAN_UP;
}
if (AddObjToJson(out, FIELD_SEND_TO_PEER, sendToPeer) != CLIB_SUCCESS) {
LOGE("Add sendToPeer to json failed.");
goto CLEAN_UP;
}
FreeJson(sendToPeer);
return HC_SUCCESS;
CLEAN_UP:
FreeJson(sendToPeer);
return HC_ERR_JSON_ADD;
}
static int32_t AccountAuthGenSeed(IsoAuthParams *params)
{
Uint8Buff seedBuff = { params->seed, sizeof(params->seed) };
int32_t res = params->isoBaseParams.loader->generateRandom(&seedBuff);
if (res != HC_SUCCESS) {
LOGE("GenerateRandom for seed failed, res: %d.", res);
}
return res;
}
static int32_t IsoAuthClientBegin(TaskBase *task, const CJson *in, CJson *out, int32_t *status)
{
(void)in;
if (task->taskStatus != TASK_STATUS_ISO_MAIN_BEGIN) {
LOGD("The message is repeated, ignore it, taskStatus: %d.", task->taskStatus);
*status = IGNORE_MSG;
return HC_SUCCESS;
}
IsoAuthClientTask *innerTask = (IsoAuthClientTask *)task;
int32_t ret = IsoClientGenRandom(&innerTask->params.isoBaseParams);
if (ret != HC_SUCCESS) {
LOGE("IsoClientGenRandom failed, res: %d.", ret);
return ret;
}
ret = AccountAuthGenSeed(&innerTask->params);
if (ret != HC_SUCCESS) {
LOGE("AccountAuthGenSeed failed, res: %d.", ret);
return ret;
}
// Send params to server.
ret = PackIsoAuthClientBeginMsg(&innerTask->params, out);
if (ret != HC_SUCCESS) {
LOGE("PackIsoAuthClientBeginMsg failed, ret: %d.", ret);
return ret;
}
innerTask->taskBase.taskStatus = TASK_STATUS_ISO_MAIN_STEP_ONE;
*status = CONTINUE;
return HC_SUCCESS;
}
static int32_t ParseIsoAuthServerGetTokenMsg(IsoAuthParams *params, const CJson *in, Uint8Buff *peerToken)
{
const char *userIdPeer = GetStringFromJson(in, FIELD_USER_ID);
if (userIdPeer == NULL) {
LOGE("Failed to get userIdPeer from input data for client in sym auth.");
return HC_ERR_JSON_GET;
}
if (strcpy_s(params->userIdPeer, DEV_AUTH_USER_ID_SIZE, userIdPeer) != EOK) {
LOGE("Copy for userIdPeer failed for client in sym auth.");
return HC_ERR_MEMORY_COPY;
}
if (GetByteFromJson(in, FIELD_SALT, params->isoBaseParams.randPeer.val,
params->isoBaseParams.randPeer.length) != CLIB_SUCCESS) {
LOGE("Get saltPeer from json failed for client.");
return HC_ERR_JSON_GET;
}
if (GetByteFromJson(in, FIELD_TOKEN, peerToken->val, peerToken->length) != CLIB_SUCCESS) {
LOGE("Get peerToken from json failed for client.");
return HC_ERR_JSON_GET;
}
int32_t res = ExtractAndVerifyPayload(params, in);
if (res != HC_SUCCESS) {
LOGE("ExtractAndVerifyPayload failed for client, res: %d.", res);
}
return res;
}
static int32_t PackIsoAuthClientGetTokenMsg(const IsoAuthParams *params, CJson *out)
{
CJson *sendToPeer = CreateJson();
if (sendToPeer == NULL) {
LOGE("Create sendToPeer json failed.");
return HC_ERR_JSON_CREATE;
}
CJson *data = CreateJson();
if (data == NULL) {
LOGE("Create data json failed.");
FreeJson(sendToPeer);
return HC_ERR_JSON_CREATE;
}
if (AddIntToJson(sendToPeer, FIELD_AUTH_FORM, params->authForm) != CLIB_SUCCESS) {
LOGE("Add authForm to json failed.");
goto CLEAN_UP;
}
if (AddIntToJson(sendToPeer, FIELD_STEP, CMD_ISO_AUTH_MAIN_TWO) != CLIB_SUCCESS) {
LOGE("Add step code to json failed.");
goto CLEAN_UP;
}
if (AddByteToJson(data, FIELD_TOKEN, params->hmacToken, sizeof(params->hmacToken)) != CLIB_SUCCESS) {
LOGE("Add hmacToken to json failed.");
goto CLEAN_UP;
}
if (AddObjToJson(sendToPeer, FIELD_DATA, data) != CLIB_SUCCESS) {
LOGE("Add data json obj to json failed.");
goto CLEAN_UP;
}
if (AddObjToJson(out, FIELD_SEND_TO_PEER, sendToPeer) != CLIB_SUCCESS) {
LOGE("Add sendToPeer to json failed.");
goto CLEAN_UP;
}
FreeJson(sendToPeer);
FreeJson(data);
return HC_SUCCESS;
CLEAN_UP:
FreeJson(sendToPeer);
FreeJson(data);
return HC_ERR_JSON_ADD;
}
static int32_t IsoAuthClientGetToken(TaskBase *task, const CJson *in, CJson *out, int32_t *status)
{
IsoAuthClientTask *innerTask = (IsoAuthClientTask *)task;
if (innerTask->taskBase.taskStatus < TASK_STATUS_ISO_MAIN_STEP_ONE) {
LOGE("Message code is not match with task status, taskStatus: %d", innerTask->taskBase.taskStatus);
return HC_ERR_BAD_MESSAGE;
}
if (innerTask->taskBase.taskStatus > TASK_STATUS_ISO_MAIN_STEP_ONE) {
LOGI("The message is repeated, ignore it, taskStatus: %d.", innerTask->taskBase.taskStatus);
*status = IGNORE_MSG;
return HC_SUCCESS;
}
// Receive params from server.
uint8_t peerToken[HMAC_TOKEN_SIZE] = { 0 };
Uint8Buff peerTokenBuf = { peerToken, HMAC_TOKEN_SIZE };
int32_t res = ParseIsoAuthServerGetTokenMsg(&innerTask->params, in, &peerTokenBuf);
if (res != HC_SUCCESS) {
LOGE("ParseIsoAuthServerGetTokenMsg failed, res: %d.", res);
return res;
}
// Get psk and process hmacToken.
res = AccountAuthGeneratePsk(&innerTask->params);
if (res != HC_SUCCESS) {
LOGE("AccountAuthGeneratePsk failed, res: %d.", res);
return res;
}
Uint8Buff selfTokenBuf = { innerTask->params.hmacToken, HMAC_TOKEN_SIZE };
res = IsoClientCheckAndGenToken(&(innerTask->params.isoBaseParams), &peerTokenBuf, &selfTokenBuf);
if (res != HC_SUCCESS) {
LOGE("IsoClientCheckAndGenToken failed, res: %d.", res);
return res;
}
// Send params to server.
res = PackIsoAuthClientGetTokenMsg(&innerTask->params, out);
if (res != HC_SUCCESS) {
LOGE("PackIsoAuthClientGetTokenMsg failed, res: %d.", res);
return res;
}
innerTask->taskBase.taskStatus = TASK_STATUS_ISO_MAIN_STEP_TWO;
*status = CONTINUE;
return HC_SUCCESS;
}
static int32_t IsoAuthClientGetSessionKey(TaskBase *task, const CJson *in, CJson *out, int32_t *status)
{
IsoAuthClientTask *innerTask = (IsoAuthClientTask *)task;
if (innerTask->taskBase.taskStatus < TASK_STATUS_ISO_MAIN_STEP_TWO) {
LOGE("Message code is not match with task status, taskStatus: %d", innerTask->taskBase.taskStatus);
return HC_ERR_BAD_MESSAGE;
}
if (innerTask->taskBase.taskStatus > TASK_STATUS_ISO_MAIN_STEP_TWO) {
LOGI("The message is repeated, ignore it, taskStatus: %d", innerTask->taskBase.taskStatus);
*status = IGNORE_MSG;
return HC_SUCCESS;
}
// Receive params from server.
uint8_t authResultHmac[AUTH_RESULT_MAC_SIZE] = { 0 };
if (GetByteFromJson(in, FIELD_AUTH_RESULT_MAC, authResultHmac, sizeof(authResultHmac)) != CLIB_SUCCESS) {
LOGE("Get authResultHmac from json failed.");
return HC_ERR_JSON_GET;
}
// Generate and verify the HMAC, then generate session key.
int32_t res = IsoClientGenSessionKey(&(innerTask->params.isoBaseParams), 0, authResultHmac, sizeof(authResultHmac));
if (res != HC_SUCCESS) {
LOGE("IsoClientGenSessionKey failed, res: %d.", res);
return res;
}
res = AuthIsoSendFinalToOut(&innerTask->params, out);
if (res != HC_SUCCESS) {
LOGE("AuthIsoSendFinalToOut failed, res: %d.", res);
return res;
}
innerTask->taskBase.taskStatus = TASK_STATUS_ISO_MAIN_END;
*status = FINISH;
return HC_SUCCESS;
}
static int32_t ProcessClientTask(TaskBase *task, const CJson *in, CJson *out, int32_t *status)
{
int32_t res;
if (task->taskStatus == TASK_STATUS_ISO_MAIN_BEGIN) {
res = IsoAuthClientBegin(task, in, out, status);
if (res != HC_SUCCESS) {
LOGE("IsoAuthClientBegin failed, res: %d.", res);
}
return res;
}
int32_t authStep;
if (GetIntFromJson(in, FIELD_STEP, &authStep) != CLIB_SUCCESS) {
LOGE("Get message code from json failed.");
return HC_ERR_JSON_GET;
}
switch (authStep) {
case RET_ISO_AUTH_FOLLOWER_ONE:
res = IsoAuthClientGetToken(task, in, out, status);
break;
case RET_ISO_AUTH_FOLLOWER_TWO:
res = IsoAuthClientGetSessionKey(task, in, out, status);
break;
default:
res = HC_ERR_BAD_MESSAGE;
}
if (res != HC_SUCCESS) {
LOGE("Process iso auth client failed, step: %d, res: %d.", authStep, res);
}
return res;
}
static void DestroyAuthClientAuthTask(TaskBase *task)
{
if (task == NULL) {
return;
}
IsoAuthClientTask *innerTask = (IsoAuthClientTask *)task;
DestroyIsoAuthParams(&(innerTask->params));
HcFree(innerTask);
}
TaskBase *CreateIsoAuthClientTask(const CJson *in, CJson *out, const AccountVersionInfo *verInfo)
{
if ((in == NULL) || (out == NULL) || (verInfo == NULL)) {
LOGE("Params is null for client sym auth.");
return NULL;
}
IsoAuthClientTask *task = (IsoAuthClientTask *)HcMalloc(sizeof(IsoAuthClientTask), 0);
if (task == NULL) {
LOGE("Malloc for IsoAuthClientTask failed.");
return NULL;
}
task->taskBase.getTaskType = GetIsoAuthClientType;
task->taskBase.process = ProcessClientTask;
task->taskBase.destroyTask = DestroyAuthClientAuthTask;
int32_t res = InitIsoAuthParams(in, &(task->params), verInfo);
if (res != HC_SUCCESS) {
LOGE("InitIsoAuthParams failed, res: %d.", res);
DestroyAuthClientAuthTask((TaskBase *)task);
return NULL;
}
task->taskBase.taskStatus = TASK_STATUS_ISO_MAIN_BEGIN;
return (TaskBase *)task;
}
/*
* Copyright (C) 2022 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 "iso_auth_client_task.h"
#include "account_module_defines.h"
#include "clib_error.h"
#include "common_defs.h"
#include "device_auth.h"
#include "device_auth_defines.h"
#include "hc_log.h"
#include "hc_types.h"
#include "iso_auth_task_common.h"
#include "iso_protocol_common.h"
#include "protocol_common.h"
enum {
TASK_STATUS_ISO_MAIN_BEGIN = 0,
TASK_STATUS_ISO_MAIN_STEP_ONE = 1,
TASK_STATUS_ISO_MAIN_STEP_TWO = 2,
TASK_STATUS_ISO_MAIN_END = 3,
};
static AccountTaskType GetIsoAuthClientType(void)
{
return TASK_TYPE_ISO_AUTH_CLIENT;
}
static int32_t AddBeginDataToJson(const IsoAuthParams *params, CJson *sendToPeer)
{
CJson *data = CreateJson();
if (data == NULL) {
LOGE("Create data json failed.");
return HC_ERR_JSON_CREATE;
}
if (AddByteToJson(data, FIELD_SALT,
params->isoBaseParams.randSelf.val, params->isoBaseParams.randSelf.length) != CLIB_SUCCESS) {
LOGE("Add saltSelf to json failed.");
goto CLEAN_UP;
}
if (AddByteToJson(data, FIELD_PAYLOAD,
params->isoBaseParams.authIdSelf.val, params->isoBaseParams.authIdSelf.length) != CLIB_SUCCESS) {
LOGE("Add payloadSelf to json failed.");
goto CLEAN_UP;
}
if (AddByteToJson(data, FIELD_SEED, params->seed, sizeof(params->seed)) != CLIB_SUCCESS) {
LOGE("Add seed to json failed.");
goto CLEAN_UP;
}
if (AddObjToJson(sendToPeer, FIELD_DATA, data) != CLIB_SUCCESS) {
LOGE("Add data json obj to json failed.");
goto CLEAN_UP;
}
FreeJson(data);
return HC_SUCCESS;
CLEAN_UP:
FreeJson(data);
return HC_ERR_JSON_ADD;
}
static int32_t PackIsoAuthClientBeginMsg(const IsoAuthParams *params, CJson *out)
{
CJson *sendToPeer = CreateJson();
if (sendToPeer == NULL) {
LOGE("Create sendToPeer json failed.");
return HC_ERR_JSON_CREATE;
}
if (AddIntToJson(sendToPeer, FIELD_AUTH_FORM, params->authForm) != CLIB_SUCCESS) {
LOGE("Add authForm to json failed.");
goto CLEAN_UP;
}
if (AddIntToJson(sendToPeer, FIELD_STEP, CMD_ISO_AUTH_MAIN_ONE) != CLIB_SUCCESS) {
LOGE("Add step code to json failed.");
goto CLEAN_UP;
}
if (AddIntToJson(sendToPeer, FIELD_CREDENTIAL_TYPE, params->credentialType) != CLIB_SUCCESS) {
LOGE("Add credentialType to json failed.");
goto CLEAN_UP;
}
if (AddStringToJson(sendToPeer, FIELD_USER_ID, params->userIdSelf) != CLIB_SUCCESS) {
LOGE("Add userIdSelf to json failed.");
goto CLEAN_UP;
}
if (AddByteToJson(sendToPeer, FIELD_DEV_ID, params->devIdSelf.val, params->devIdSelf.length) != CLIB_SUCCESS) {
LOGE("Add devIdSelf to json failed.");
goto CLEAN_UP;
}
if (AddStringToJson(sendToPeer, FIELD_DEVICE_ID, params->deviceIdSelf) != CLIB_SUCCESS) {
LOGE("Add deviceIdSelf to json failed.");
goto CLEAN_UP;
}
if (AddBeginDataToJson(params, sendToPeer) != HC_SUCCESS) {
LOGE("AddBeginDataToJson failed.");
goto CLEAN_UP;
}
if (AddObjToJson(out, FIELD_SEND_TO_PEER, sendToPeer) != CLIB_SUCCESS) {
LOGE("Add sendToPeer to json failed.");
goto CLEAN_UP;
}
FreeJson(sendToPeer);
return HC_SUCCESS;
CLEAN_UP:
FreeJson(sendToPeer);
return HC_ERR_JSON_ADD;
}
static int32_t AccountAuthGenSeed(IsoAuthParams *params)
{
Uint8Buff seedBuff = { params->seed, sizeof(params->seed) };
int32_t res = params->isoBaseParams.loader->generateRandom(&seedBuff);
if (res != HC_SUCCESS) {
LOGE("GenerateRandom for seed failed, res: %d.", res);
}
return res;
}
static int32_t IsoAuthClientBegin(TaskBase *task, const CJson *in, CJson *out, int32_t *status)
{
(void)in;
if (task->taskStatus != TASK_STATUS_ISO_MAIN_BEGIN) {
LOGD("The message is repeated, ignore it, taskStatus: %d.", task->taskStatus);
*status = IGNORE_MSG;
return HC_SUCCESS;
}
IsoAuthClientTask *innerTask = (IsoAuthClientTask *)task;
int32_t ret = IsoClientGenRandom(&innerTask->params.isoBaseParams);
if (ret != HC_SUCCESS) {
LOGE("IsoClientGenRandom failed, res: %d.", ret);
return ret;
}
ret = AccountAuthGenSeed(&innerTask->params);
if (ret != HC_SUCCESS) {
LOGE("AccountAuthGenSeed failed, res: %d.", ret);
return ret;
}
// Send params to server.
ret = PackIsoAuthClientBeginMsg(&innerTask->params, out);
if (ret != HC_SUCCESS) {
LOGE("PackIsoAuthClientBeginMsg failed, ret: %d.", ret);
return ret;
}
innerTask->taskBase.taskStatus = TASK_STATUS_ISO_MAIN_STEP_ONE;
*status = CONTINUE;
return HC_SUCCESS;
}
static int32_t ParseIsoAuthServerGetTokenMsg(IsoAuthParams *params, const CJson *in, Uint8Buff *peerToken)
{
const char *userIdPeer = GetStringFromJson(in, FIELD_USER_ID);
if (userIdPeer == NULL) {
LOGE("Failed to get userIdPeer from input data for client in sym auth.");
return HC_ERR_JSON_GET;
}
if (strcpy_s(params->userIdPeer, DEV_AUTH_USER_ID_SIZE, userIdPeer) != EOK) {
LOGE("Copy for userIdPeer failed for client in sym auth.");
return HC_ERR_MEMORY_COPY;
}
if (GetByteFromJson(in, FIELD_SALT, params->isoBaseParams.randPeer.val,
params->isoBaseParams.randPeer.length) != CLIB_SUCCESS) {
LOGE("Get saltPeer from json failed for client.");
return HC_ERR_JSON_GET;
}
if (GetByteFromJson(in, FIELD_TOKEN, peerToken->val, peerToken->length) != CLIB_SUCCESS) {
LOGE("Get peerToken from json failed for client.");
return HC_ERR_JSON_GET;
}
int32_t res = ExtractAndVerifyPayload(params, in);
if (res != HC_SUCCESS) {
LOGE("ExtractAndVerifyPayload failed for client, res: %d.", res);
}
return res;
}
static int32_t PackIsoAuthClientGetTokenMsg(const IsoAuthParams *params, CJson *out)
{
CJson *sendToPeer = CreateJson();
if (sendToPeer == NULL) {
LOGE("Create sendToPeer json failed.");
return HC_ERR_JSON_CREATE;
}
CJson *data = CreateJson();
if (data == NULL) {
LOGE("Create data json failed.");
FreeJson(sendToPeer);
return HC_ERR_JSON_CREATE;
}
if (AddIntToJson(sendToPeer, FIELD_AUTH_FORM, params->authForm) != CLIB_SUCCESS) {
LOGE("Add authForm to json failed.");
goto CLEAN_UP;
}
if (AddIntToJson(sendToPeer, FIELD_STEP, CMD_ISO_AUTH_MAIN_TWO) != CLIB_SUCCESS) {
LOGE("Add step code to json failed.");
goto CLEAN_UP;
}
if (AddByteToJson(data, FIELD_TOKEN, params->hmacToken, sizeof(params->hmacToken)) != CLIB_SUCCESS) {
LOGE("Add hmacToken to json failed.");
goto CLEAN_UP;
}
if (AddObjToJson(sendToPeer, FIELD_DATA, data) != CLIB_SUCCESS) {
LOGE("Add data json obj to json failed.");
goto CLEAN_UP;
}
if (AddObjToJson(out, FIELD_SEND_TO_PEER, sendToPeer) != CLIB_SUCCESS) {
LOGE("Add sendToPeer to json failed.");
goto CLEAN_UP;
}
FreeJson(sendToPeer);
FreeJson(data);
return HC_SUCCESS;
CLEAN_UP:
FreeJson(sendToPeer);
FreeJson(data);
return HC_ERR_JSON_ADD;
}
static int32_t IsoAuthClientGetToken(TaskBase *task, const CJson *in, CJson *out, int32_t *status)
{
IsoAuthClientTask *innerTask = (IsoAuthClientTask *)task;
if (innerTask->taskBase.taskStatus < TASK_STATUS_ISO_MAIN_STEP_ONE) {
LOGE("Message code is not match with task status, taskStatus: %d", innerTask->taskBase.taskStatus);
return HC_ERR_BAD_MESSAGE;
}
if (innerTask->taskBase.taskStatus > TASK_STATUS_ISO_MAIN_STEP_ONE) {
LOGI("The message is repeated, ignore it, taskStatus: %d.", innerTask->taskBase.taskStatus);
*status = IGNORE_MSG;
return HC_SUCCESS;
}
// Receive params from server.
uint8_t peerToken[HMAC_TOKEN_SIZE] = { 0 };
Uint8Buff peerTokenBuf = { peerToken, HMAC_TOKEN_SIZE };
int32_t res = ParseIsoAuthServerGetTokenMsg(&innerTask->params, in, &peerTokenBuf);
if (res != HC_SUCCESS) {
LOGE("ParseIsoAuthServerGetTokenMsg failed, res: %d.", res);
return res;
}
// Get psk and process hmacToken.
res = AccountAuthGeneratePsk(&innerTask->params);
if (res != HC_SUCCESS) {
LOGE("AccountAuthGeneratePsk failed, res: %d.", res);
return res;
}
Uint8Buff selfTokenBuf = { innerTask->params.hmacToken, HMAC_TOKEN_SIZE };
res = IsoClientCheckAndGenToken(&(innerTask->params.isoBaseParams), &peerTokenBuf, &selfTokenBuf);
if (res != HC_SUCCESS) {
LOGE("IsoClientCheckAndGenToken failed, res: %d.", res);
return res;
}
// Send params to server.
res = PackIsoAuthClientGetTokenMsg(&innerTask->params, out);
if (res != HC_SUCCESS) {
LOGE("PackIsoAuthClientGetTokenMsg failed, res: %d.", res);
return res;
}
innerTask->taskBase.taskStatus = TASK_STATUS_ISO_MAIN_STEP_TWO;
*status = CONTINUE;
return HC_SUCCESS;
}
static int32_t IsoAuthClientGetSessionKey(TaskBase *task, const CJson *in, CJson *out, int32_t *status)
{
IsoAuthClientTask *innerTask = (IsoAuthClientTask *)task;
if (innerTask->taskBase.taskStatus < TASK_STATUS_ISO_MAIN_STEP_TWO) {
LOGE("Message code is not match with task status, taskStatus: %d", innerTask->taskBase.taskStatus);
return HC_ERR_BAD_MESSAGE;
}
if (innerTask->taskBase.taskStatus > TASK_STATUS_ISO_MAIN_STEP_TWO) {
LOGI("The message is repeated, ignore it, taskStatus: %d", innerTask->taskBase.taskStatus);
*status = IGNORE_MSG;
return HC_SUCCESS;
}
// Receive params from server.
uint8_t authResultHmac[AUTH_RESULT_MAC_SIZE] = { 0 };
if (GetByteFromJson(in, FIELD_AUTH_RESULT_MAC, authResultHmac, sizeof(authResultHmac)) != CLIB_SUCCESS) {
LOGE("Get authResultHmac from json failed.");
return HC_ERR_JSON_GET;
}
// Generate and verify the HMAC, then generate session key.
int32_t res = IsoClientGenSessionKey(&(innerTask->params.isoBaseParams), 0, authResultHmac, sizeof(authResultHmac));
if (res != HC_SUCCESS) {
LOGE("IsoClientGenSessionKey failed, res: %d.", res);
return res;
}
res = AuthIsoSendFinalToOut(&innerTask->params, out);
if (res != HC_SUCCESS) {
LOGE("AuthIsoSendFinalToOut failed, res: %d.", res);
return res;
}
innerTask->taskBase.taskStatus = TASK_STATUS_ISO_MAIN_END;
*status = FINISH;
return HC_SUCCESS;
}
static int32_t ProcessClientTask(TaskBase *task, const CJson *in, CJson *out, int32_t *status)
{
int32_t res;
if (task->taskStatus == TASK_STATUS_ISO_MAIN_BEGIN) {
res = IsoAuthClientBegin(task, in, out, status);
if (res != HC_SUCCESS) {
LOGE("IsoAuthClientBegin failed, res: %d.", res);
}
return res;
}
int32_t authStep;
if (GetIntFromJson(in, FIELD_STEP, &authStep) != CLIB_SUCCESS) {
LOGE("Get message code from json failed.");
return HC_ERR_JSON_GET;
}
switch (authStep) {
case RET_ISO_AUTH_FOLLOWER_ONE:
res = IsoAuthClientGetToken(task, in, out, status);
break;
case RET_ISO_AUTH_FOLLOWER_TWO:
res = IsoAuthClientGetSessionKey(task, in, out, status);
break;
default:
res = HC_ERR_BAD_MESSAGE;
}
if (res != HC_SUCCESS) {
LOGE("Process iso auth client failed, step: %d, res: %d.", authStep, res);
}
return res;
}
static void DestroyAuthClientAuthTask(TaskBase *task)
{
if (task == NULL) {
return;
}
IsoAuthClientTask *innerTask = (IsoAuthClientTask *)task;
DestroyIsoAuthParams(&(innerTask->params));
HcFree(innerTask);
}
TaskBase *CreateIsoAuthClientTask(const CJson *in, CJson *out, const AccountVersionInfo *verInfo)
{
if ((in == NULL) || (out == NULL) || (verInfo == NULL)) {
LOGE("Params is null for client sym auth.");
return NULL;
}
IsoAuthClientTask *task = (IsoAuthClientTask *)HcMalloc(sizeof(IsoAuthClientTask), 0);
if (task == NULL) {
LOGE("Malloc for IsoAuthClientTask failed.");
return NULL;
}
task->taskBase.getTaskType = GetIsoAuthClientType;
task->taskBase.process = ProcessClientTask;
task->taskBase.destroyTask = DestroyAuthClientAuthTask;
int32_t res = InitIsoAuthParams(in, &(task->params), verInfo);
if (res != HC_SUCCESS) {
LOGE("InitIsoAuthParams failed, res: %d.", res);
DestroyAuthClientAuthTask((TaskBase *)task);
return NULL;
}
task->taskBase.taskStatus = TASK_STATUS_ISO_MAIN_BEGIN;
return (TaskBase *)task;
}
@@ -1,343 +1,343 @@
/*
* Copyright (C) 2022 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 "iso_auth_server_task.h"
#include "account_module_defines.h"
#include "clib_error.h"
#include "common_defs.h"
#include "device_auth.h"
#include "device_auth_defines.h"
#include "hc_log.h"
#include "hc_types.h"
#include "iso_auth_task_common.h"
#include "iso_protocol_common.h"
#include "protocol_common.h"
enum {
TASK_STATUS_SERVER_BEGIN_TOKEN = 0,
TASK_STATUS_SERVER_GEN_SESSION_KEY = 1,
TASK_STATUS_SERVER_END = 2,
};
static AccountTaskType GetIsoAuthServerType(void)
{
return TASK_TYPE_ISO_AUTH_SERVER;
}
static int32_t ParseIsoAuthClientBeginMsg(IsoAuthParams *params, const CJson *in)
{
const char *userIdPeer = GetStringFromJson(in, FIELD_USER_ID);
if (userIdPeer == NULL) {
LOGE("Failed to get userIdPeer from input data for server in sym auth.");
return HC_ERR_JSON_GET;
}
if (strcpy_s(params->userIdPeer, DEV_AUTH_USER_ID_SIZE, userIdPeer) != EOK) {
LOGE("Copy for userIdPeer failed for server in sym auth.");
return HC_ERR_MEMORY_COPY;
}
if (GetByteFromJson(in, FIELD_SEED, params->seed, sizeof(params->seed)) != CLIB_SUCCESS) {
LOGE("Get seed from json failed for server.");
return HC_ERR_JSON_GET;
}
if (GetByteFromJson(in, FIELD_SALT, params->isoBaseParams.randPeer.val,
params->isoBaseParams.randPeer.length) != CLIB_SUCCESS) {
LOGE("Get saltPeer from json failed for server.");
return HC_ERR_JSON_GET;
}
int32_t res = ExtractAndVerifyPayload(params, in);
if (res != HC_SUCCESS) {
LOGE("ExtractAndVerifyPayload failed for server, res: %d.", res);
}
return res;
}
static int32_t AddGetTokenDataToJson(const IsoAuthParams *params, CJson *sendToPeer)
{
CJson *data = CreateJson();
if (data == NULL) {
LOGE("Create data json failed.");
return HC_ERR_JSON_CREATE;
}
if (AddByteToJson(data, FIELD_PAYLOAD,
params->isoBaseParams.authIdSelf.val, params->isoBaseParams.authIdSelf.length) != CLIB_SUCCESS) {
LOGE("Add payloadSelf to json failed.");
goto CLEAN_UP;
}
if (AddByteToJson(data, FIELD_TOKEN, params->hmacToken, sizeof(params->hmacToken)) != CLIB_SUCCESS) {
LOGE("Add hmacToken to json failed.");
goto CLEAN_UP;
}
if (AddByteToJson(data, FIELD_SALT,
params->isoBaseParams.randSelf.val, params->isoBaseParams.randSelf.length) != CLIB_SUCCESS) {
LOGE("Add saltSelf to json failed.");
goto CLEAN_UP;
}
if (AddObjToJson(sendToPeer, FIELD_DATA, data) != CLIB_SUCCESS) {
LOGE("Add data json obj to json failed.");
goto CLEAN_UP;
}
FreeJson(data);
return HC_SUCCESS;
CLEAN_UP:
FreeJson(data);
return HC_ERR_JSON_ADD;
}
static int32_t PackIsoAuthServerGetTokenMsg(const IsoAuthParams *params, CJson *out)
{
CJson *sendToPeer = CreateJson();
if (sendToPeer == NULL) {
LOGE("Create sendToPeer json is null in server.");
return HC_ERR_JSON_CREATE;
}
if (AddIntToJson(sendToPeer, FIELD_STEP, RET_ISO_AUTH_FOLLOWER_ONE) != CLIB_SUCCESS) {
LOGE("Add step code to json failed in server.");
goto CLEAN_UP;
}
if (AddIntToJson(sendToPeer, FIELD_AUTH_FORM, params->authForm) != CLIB_SUCCESS) {
LOGE("Add authForm to json failed in server.");
goto CLEAN_UP;
}
if (AddStringToJson(sendToPeer, FIELD_USER_ID, params->userIdSelf) != CLIB_SUCCESS) {
LOGE("Add userIdSelf to json failed in server.");
goto CLEAN_UP;
}
if (AddByteToJson(sendToPeer, FIELD_DEV_ID, params->devIdSelf.val, params->devIdSelf.length) != CLIB_SUCCESS) {
LOGE("Add devIdSelf to json failed in server.");
goto CLEAN_UP;
}
if (AddStringToJson(sendToPeer, FIELD_DEVICE_ID, params->deviceIdSelf) != CLIB_SUCCESS) {
LOGE("Add deviceIdSelf to json failed in server.");
goto CLEAN_UP;
}
int32_t res = AddGetTokenDataToJson(params, sendToPeer);
if (res != HC_SUCCESS) {
LOGE("AddGetTokenDataToJson failed, res: %d.", res);
FreeJson(sendToPeer);
return res;
}
if (AddObjToJson(out, FIELD_SEND_TO_PEER, sendToPeer) != CLIB_SUCCESS) {
LOGE("Add sendToPeer to json failed.");
goto CLEAN_UP;
}
FreeJson(sendToPeer);
return HC_SUCCESS;
CLEAN_UP:
FreeJson(sendToPeer);
return HC_ERR_JSON_ADD;
}
static int32_t IsoAuthServerGetToken(TaskBase *task, const CJson *in, CJson *out, int32_t *status)
{
IsoAuthServerTask *innerTask = (IsoAuthServerTask *)task;
if (innerTask->taskBase.taskStatus < TASK_STATUS_SERVER_BEGIN_TOKEN) {
LOGE("Message code is not match with task status, taskStatus: %d", innerTask->taskBase.taskStatus);
return HC_ERR_BAD_MESSAGE;
}
if (innerTask->taskBase.taskStatus > TASK_STATUS_SERVER_BEGIN_TOKEN) {
LOGI("The message is repeated, ignore it, taskStatus: %d.", innerTask->taskBase.taskStatus);
*status = IGNORE_MSG;
return HC_SUCCESS;
}
// Receive params from client.
int32_t res = ParseIsoAuthClientBeginMsg(&innerTask->params, in);
if (res != HC_SUCCESS) {
LOGE("ParseIsoAuthClientBeginMsg failed, res: %d.", res);
return res;
}
// Get psk and process hmacToken.
res = AccountAuthGeneratePsk(&innerTask->params);
if (res != HC_SUCCESS) {
LOGE("AccountAuthGeneratePsk failed, res: %d.", res);
return res;
}
Uint8Buff selfTokenBuf = { innerTask->params.hmacToken, HMAC_TOKEN_SIZE };
res = IsoServerGenRandomAndToken(&innerTask->params.isoBaseParams, &selfTokenBuf);
if (res != HC_SUCCESS) {
LOGE("IsoServerGenRandomAndToken failed, res: %d.", res);
return res;
}
// Send params to client.
res = PackIsoAuthServerGetTokenMsg(&innerTask->params, out);
if (res != HC_SUCCESS) {
LOGE("PackIsoAuthServerGetTokenMsg failed, res: %d.", res);
return res;
}
innerTask->taskBase.taskStatus = TASK_STATUS_SERVER_GEN_SESSION_KEY;
*status = CONTINUE;
return HC_SUCCESS;
}
static int32_t PackCalTokenAndSessionKeyMsg(const IsoAuthParams *params, CJson *out, const Uint8Buff *authResultMac)
{
CJson *sendToPeer = CreateJson();
if (sendToPeer == NULL) {
LOGE("Create sendToPeer json failed.");
return HC_ERR_JSON_CREATE;
}
CJson *data = CreateJson();
if (data == NULL) {
LOGE("Create data json failed.");
FreeJson(sendToPeer);
return HC_ERR_JSON_CREATE;
}
if (AddIntToJson(sendToPeer, FIELD_STEP, RET_ISO_AUTH_FOLLOWER_TWO) != CLIB_SUCCESS) {
LOGE("Add step code to json failed.");
goto CLEAN_UP;
}
if (AddIntToJson(sendToPeer, FIELD_AUTH_FORM, params->authForm) != CLIB_SUCCESS) {
LOGE("Add authForm to json failed.");
goto CLEAN_UP;
}
if (AddByteToJson(data, FIELD_AUTH_RESULT_MAC, authResultMac->val, authResultMac->length) != CLIB_SUCCESS) {
LOGE("Add authResultMac to json failed.");
goto CLEAN_UP;
}
if (AddObjToJson(sendToPeer, FIELD_DATA, data) != CLIB_SUCCESS) {
LOGE("Add data json obj to json failed.");
goto CLEAN_UP;
}
if (AddObjToJson(out, FIELD_SEND_TO_PEER, sendToPeer) != CLIB_SUCCESS) {
LOGE("Add sendToPeer to json failed.");
goto CLEAN_UP;
}
FreeJson(sendToPeer);
FreeJson(data);
return HC_SUCCESS;
CLEAN_UP:
FreeJson(sendToPeer);
FreeJson(data);
return HC_ERR_JSON_ADD;
}
static int32_t IsoAuthServerCalTokenAndSessionKey(TaskBase *task, const CJson *in, CJson *out, int32_t *status)
{
IsoAuthServerTask *innerTask = (IsoAuthServerTask *)task;
if (innerTask->taskBase.taskStatus < TASK_STATUS_SERVER_GEN_SESSION_KEY) {
LOGE("Message code is not match with task status, taskStatus: %d", innerTask->taskBase.taskStatus);
return HC_ERR_BAD_MESSAGE;
}
if (innerTask->taskBase.taskStatus > TASK_STATUS_SERVER_GEN_SESSION_KEY) {
LOGI("The message is repeated, ignore it, taskStatus: %d.", innerTask->taskBase.taskStatus);
*status = IGNORE_MSG;
return HC_SUCCESS;
}
// Receive params from client.
uint8_t peerToken[HMAC_TOKEN_SIZE] = { 0 };
Uint8Buff peerTokenBuf = { peerToken, HMAC_TOKEN_SIZE };
if (GetByteFromJson(in, FIELD_TOKEN, peerToken, sizeof(peerToken)) != CLIB_SUCCESS) {
LOGE("Get peerToken from json failed.");
return HC_ERR_JSON_GET;
}
// Process hmacToken and generate session key.
uint8_t authResultMac[AUTH_RESULT_MAC_SIZE] = { 0 };
Uint8Buff authResultMacBuf = { authResultMac, AUTH_RESULT_MAC_SIZE };
int32_t res = IsoServerGenSessionKeyAndCalToken(&(innerTask->params.isoBaseParams),
&peerTokenBuf, &authResultMacBuf);
if (res != HC_SUCCESS) {
LOGE("IsoServerGenSessionKeyAndCalToken failed, res: %d.", res);
return res;
}
// Return params to client.
res = PackCalTokenAndSessionKeyMsg(&innerTask->params, out, &authResultMacBuf);
if (res != HC_SUCCESS) {
LOGE("PackCalTokenAndSessionKeyMsg failed, res: %d.", res);
return res;
}
// Return params to server self.
res = AuthIsoSendFinalToOut(&innerTask->params, out);
if (res != HC_SUCCESS) {
LOGE("AuthIsoSendFinalToOut failed, res: %d.", res);
return res;
}
innerTask->taskBase.taskStatus = TASK_STATUS_SERVER_END;
*status = FINISH;
return HC_SUCCESS;
}
static int32_t ProcessServerTask(TaskBase *task, const CJson *in, CJson *out, int32_t *status)
{
int32_t authStep;
if (GetIntFromJson(in, FIELD_STEP, &authStep) != CLIB_SUCCESS) {
LOGE("Get step code from json failed.");
return HC_ERR_JSON_GET;
}
int32_t res;
switch (authStep) {
case CMD_ISO_AUTH_MAIN_ONE:
res = IsoAuthServerGetToken(task, in, out, status);
break;
case CMD_ISO_AUTH_MAIN_TWO:
res = IsoAuthServerCalTokenAndSessionKey(task, in, out, status);
break;
default:
res = HC_ERR_BAD_MESSAGE;
}
if (res != HC_SUCCESS) {
LOGE("Process iso auth server failed, step: %d, res: %d.", authStep, res);
}
return res;
}
static void DestroyAuthServerAuthTask(TaskBase *task)
{
if (task == NULL) {
return;
}
IsoAuthServerTask *innerTask = (IsoAuthServerTask *)task;
DestroyIsoAuthParams(&(innerTask->params));
HcFree(innerTask);
}
TaskBase *CreateIsoAuthServerTask(const CJson *in, CJson *out, const AccountVersionInfo *verInfo)
{
if ((in == NULL) || (out == NULL) || (verInfo == NULL)) {
LOGE("Params is null for server sym auth.");
return NULL;
}
IsoAuthServerTask *task = (IsoAuthServerTask *)HcMalloc(sizeof(IsoAuthServerTask), 0);
if (task == NULL) {
LOGE("Malloc for IsoAuthServerTask failed.");
return NULL;
}
task->taskBase.getTaskType = GetIsoAuthServerType;
task->taskBase.process = ProcessServerTask;
task->taskBase.destroyTask = DestroyAuthServerAuthTask;
int32_t res = InitIsoAuthParams(in, &(task->params), verInfo);
if (res != HC_SUCCESS) {
LOGE("InitIsoAuthParams failed, res: %d.", res);
DestroyAuthServerAuthTask((TaskBase *)task);
return NULL;
}
task->taskBase.taskStatus = TASK_STATUS_SERVER_BEGIN_TOKEN;
return (TaskBase *)task;
}
/*
* Copyright (C) 2022 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 "iso_auth_server_task.h"
#include "account_module_defines.h"
#include "clib_error.h"
#include "common_defs.h"
#include "device_auth.h"
#include "device_auth_defines.h"
#include "hc_log.h"
#include "hc_types.h"
#include "iso_auth_task_common.h"
#include "iso_protocol_common.h"
#include "protocol_common.h"
enum {
TASK_STATUS_SERVER_BEGIN_TOKEN = 0,
TASK_STATUS_SERVER_GEN_SESSION_KEY = 1,
TASK_STATUS_SERVER_END = 2,
};
static AccountTaskType GetIsoAuthServerType(void)
{
return TASK_TYPE_ISO_AUTH_SERVER;
}
static int32_t ParseIsoAuthClientBeginMsg(IsoAuthParams *params, const CJson *in)
{
const char *userIdPeer = GetStringFromJson(in, FIELD_USER_ID);
if (userIdPeer == NULL) {
LOGE("Failed to get userIdPeer from input data for server in sym auth.");
return HC_ERR_JSON_GET;
}
if (strcpy_s(params->userIdPeer, DEV_AUTH_USER_ID_SIZE, userIdPeer) != EOK) {
LOGE("Copy for userIdPeer failed for server in sym auth.");
return HC_ERR_MEMORY_COPY;
}
if (GetByteFromJson(in, FIELD_SEED, params->seed, sizeof(params->seed)) != CLIB_SUCCESS) {
LOGE("Get seed from json failed for server.");
return HC_ERR_JSON_GET;
}
if (GetByteFromJson(in, FIELD_SALT, params->isoBaseParams.randPeer.val,
params->isoBaseParams.randPeer.length) != CLIB_SUCCESS) {
LOGE("Get saltPeer from json failed for server.");
return HC_ERR_JSON_GET;
}
int32_t res = ExtractAndVerifyPayload(params, in);
if (res != HC_SUCCESS) {
LOGE("ExtractAndVerifyPayload failed for server, res: %d.", res);
}
return res;
}
static int32_t AddGetTokenDataToJson(const IsoAuthParams *params, CJson *sendToPeer)
{
CJson *data = CreateJson();
if (data == NULL) {
LOGE("Create data json failed.");
return HC_ERR_JSON_CREATE;
}
if (AddByteToJson(data, FIELD_PAYLOAD,
params->isoBaseParams.authIdSelf.val, params->isoBaseParams.authIdSelf.length) != CLIB_SUCCESS) {
LOGE("Add payloadSelf to json failed.");
goto CLEAN_UP;
}
if (AddByteToJson(data, FIELD_TOKEN, params->hmacToken, sizeof(params->hmacToken)) != CLIB_SUCCESS) {
LOGE("Add hmacToken to json failed.");
goto CLEAN_UP;
}
if (AddByteToJson(data, FIELD_SALT,
params->isoBaseParams.randSelf.val, params->isoBaseParams.randSelf.length) != CLIB_SUCCESS) {
LOGE("Add saltSelf to json failed.");
goto CLEAN_UP;
}
if (AddObjToJson(sendToPeer, FIELD_DATA, data) != CLIB_SUCCESS) {
LOGE("Add data json obj to json failed.");
goto CLEAN_UP;
}
FreeJson(data);
return HC_SUCCESS;
CLEAN_UP:
FreeJson(data);
return HC_ERR_JSON_ADD;
}
static int32_t PackIsoAuthServerGetTokenMsg(const IsoAuthParams *params, CJson *out)
{
CJson *sendToPeer = CreateJson();
if (sendToPeer == NULL) {
LOGE("Create sendToPeer json is null in server.");
return HC_ERR_JSON_CREATE;
}
if (AddIntToJson(sendToPeer, FIELD_STEP, RET_ISO_AUTH_FOLLOWER_ONE) != CLIB_SUCCESS) {
LOGE("Add step code to json failed in server.");
goto CLEAN_UP;
}
if (AddIntToJson(sendToPeer, FIELD_AUTH_FORM, params->authForm) != CLIB_SUCCESS) {
LOGE("Add authForm to json failed in server.");
goto CLEAN_UP;
}
if (AddStringToJson(sendToPeer, FIELD_USER_ID, params->userIdSelf) != CLIB_SUCCESS) {
LOGE("Add userIdSelf to json failed in server.");
goto CLEAN_UP;
}
if (AddByteToJson(sendToPeer, FIELD_DEV_ID, params->devIdSelf.val, params->devIdSelf.length) != CLIB_SUCCESS) {
LOGE("Add devIdSelf to json failed in server.");
goto CLEAN_UP;
}
if (AddStringToJson(sendToPeer, FIELD_DEVICE_ID, params->deviceIdSelf) != CLIB_SUCCESS) {
LOGE("Add deviceIdSelf to json failed in server.");
goto CLEAN_UP;
}
int32_t res = AddGetTokenDataToJson(params, sendToPeer);
if (res != HC_SUCCESS) {
LOGE("AddGetTokenDataToJson failed, res: %d.", res);
FreeJson(sendToPeer);
return res;
}
if (AddObjToJson(out, FIELD_SEND_TO_PEER, sendToPeer) != CLIB_SUCCESS) {
LOGE("Add sendToPeer to json failed.");
goto CLEAN_UP;
}
FreeJson(sendToPeer);
return HC_SUCCESS;
CLEAN_UP:
FreeJson(sendToPeer);
return HC_ERR_JSON_ADD;
}
static int32_t IsoAuthServerGetToken(TaskBase *task, const CJson *in, CJson *out, int32_t *status)
{
IsoAuthServerTask *innerTask = (IsoAuthServerTask *)task;
if (innerTask->taskBase.taskStatus < TASK_STATUS_SERVER_BEGIN_TOKEN) {
LOGE("Message code is not match with task status, taskStatus: %d", innerTask->taskBase.taskStatus);
return HC_ERR_BAD_MESSAGE;
}
if (innerTask->taskBase.taskStatus > TASK_STATUS_SERVER_BEGIN_TOKEN) {
LOGI("The message is repeated, ignore it, taskStatus: %d.", innerTask->taskBase.taskStatus);
*status = IGNORE_MSG;
return HC_SUCCESS;
}
// Receive params from client.
int32_t res = ParseIsoAuthClientBeginMsg(&innerTask->params, in);
if (res != HC_SUCCESS) {
LOGE("ParseIsoAuthClientBeginMsg failed, res: %d.", res);
return res;
}
// Get psk and process hmacToken.
res = AccountAuthGeneratePsk(&innerTask->params);
if (res != HC_SUCCESS) {
LOGE("AccountAuthGeneratePsk failed, res: %d.", res);
return res;
}
Uint8Buff selfTokenBuf = { innerTask->params.hmacToken, HMAC_TOKEN_SIZE };
res = IsoServerGenRandomAndToken(&innerTask->params.isoBaseParams, &selfTokenBuf);
if (res != HC_SUCCESS) {
LOGE("IsoServerGenRandomAndToken failed, res: %d.", res);
return res;
}
// Send params to client.
res = PackIsoAuthServerGetTokenMsg(&innerTask->params, out);
if (res != HC_SUCCESS) {
LOGE("PackIsoAuthServerGetTokenMsg failed, res: %d.", res);
return res;
}
innerTask->taskBase.taskStatus = TASK_STATUS_SERVER_GEN_SESSION_KEY;
*status = CONTINUE;
return HC_SUCCESS;
}
static int32_t PackCalTokenAndSessionKeyMsg(const IsoAuthParams *params, CJson *out, const Uint8Buff *authResultMac)
{
CJson *sendToPeer = CreateJson();
if (sendToPeer == NULL) {
LOGE("Create sendToPeer json failed.");
return HC_ERR_JSON_CREATE;
}
CJson *data = CreateJson();
if (data == NULL) {
LOGE("Create data json failed.");
FreeJson(sendToPeer);
return HC_ERR_JSON_CREATE;
}
if (AddIntToJson(sendToPeer, FIELD_STEP, RET_ISO_AUTH_FOLLOWER_TWO) != CLIB_SUCCESS) {
LOGE("Add step code to json failed.");
goto CLEAN_UP;
}
if (AddIntToJson(sendToPeer, FIELD_AUTH_FORM, params->authForm) != CLIB_SUCCESS) {
LOGE("Add authForm to json failed.");
goto CLEAN_UP;
}
if (AddByteToJson(data, FIELD_AUTH_RESULT_MAC, authResultMac->val, authResultMac->length) != CLIB_SUCCESS) {
LOGE("Add authResultMac to json failed.");
goto CLEAN_UP;
}
if (AddObjToJson(sendToPeer, FIELD_DATA, data) != CLIB_SUCCESS) {
LOGE("Add data json obj to json failed.");
goto CLEAN_UP;
}
if (AddObjToJson(out, FIELD_SEND_TO_PEER, sendToPeer) != CLIB_SUCCESS) {
LOGE("Add sendToPeer to json failed.");
goto CLEAN_UP;
}
FreeJson(sendToPeer);
FreeJson(data);
return HC_SUCCESS;
CLEAN_UP:
FreeJson(sendToPeer);
FreeJson(data);
return HC_ERR_JSON_ADD;
}
static int32_t IsoAuthServerCalTokenAndSessionKey(TaskBase *task, const CJson *in, CJson *out, int32_t *status)
{
IsoAuthServerTask *innerTask = (IsoAuthServerTask *)task;
if (innerTask->taskBase.taskStatus < TASK_STATUS_SERVER_GEN_SESSION_KEY) {
LOGE("Message code is not match with task status, taskStatus: %d", innerTask->taskBase.taskStatus);
return HC_ERR_BAD_MESSAGE;
}
if (innerTask->taskBase.taskStatus > TASK_STATUS_SERVER_GEN_SESSION_KEY) {
LOGI("The message is repeated, ignore it, taskStatus: %d.", innerTask->taskBase.taskStatus);
*status = IGNORE_MSG;
return HC_SUCCESS;
}
// Receive params from client.
uint8_t peerToken[HMAC_TOKEN_SIZE] = { 0 };
Uint8Buff peerTokenBuf = { peerToken, HMAC_TOKEN_SIZE };
if (GetByteFromJson(in, FIELD_TOKEN, peerToken, sizeof(peerToken)) != CLIB_SUCCESS) {
LOGE("Get peerToken from json failed.");
return HC_ERR_JSON_GET;
}
// Process hmacToken and generate session key.
uint8_t authResultMac[AUTH_RESULT_MAC_SIZE] = { 0 };
Uint8Buff authResultMacBuf = { authResultMac, AUTH_RESULT_MAC_SIZE };
int32_t res = IsoServerGenSessionKeyAndCalToken(&(innerTask->params.isoBaseParams),
&peerTokenBuf, &authResultMacBuf);
if (res != HC_SUCCESS) {
LOGE("IsoServerGenSessionKeyAndCalToken failed, res: %d.", res);
return res;
}
// Return params to client.
res = PackCalTokenAndSessionKeyMsg(&innerTask->params, out, &authResultMacBuf);
if (res != HC_SUCCESS) {
LOGE("PackCalTokenAndSessionKeyMsg failed, res: %d.", res);
return res;
}
// Return params to server self.
res = AuthIsoSendFinalToOut(&innerTask->params, out);
if (res != HC_SUCCESS) {
LOGE("AuthIsoSendFinalToOut failed, res: %d.", res);
return res;
}
innerTask->taskBase.taskStatus = TASK_STATUS_SERVER_END;
*status = FINISH;
return HC_SUCCESS;
}
static int32_t ProcessServerTask(TaskBase *task, const CJson *in, CJson *out, int32_t *status)
{
int32_t authStep;
if (GetIntFromJson(in, FIELD_STEP, &authStep) != CLIB_SUCCESS) {
LOGE("Get step code from json failed.");
return HC_ERR_JSON_GET;
}
int32_t res;
switch (authStep) {
case CMD_ISO_AUTH_MAIN_ONE:
res = IsoAuthServerGetToken(task, in, out, status);
break;
case CMD_ISO_AUTH_MAIN_TWO:
res = IsoAuthServerCalTokenAndSessionKey(task, in, out, status);
break;
default:
res = HC_ERR_BAD_MESSAGE;
}
if (res != HC_SUCCESS) {
LOGE("Process iso auth server failed, step: %d, res: %d.", authStep, res);
}
return res;
}
static void DestroyAuthServerAuthTask(TaskBase *task)
{
if (task == NULL) {
return;
}
IsoAuthServerTask *innerTask = (IsoAuthServerTask *)task;
DestroyIsoAuthParams(&(innerTask->params));
HcFree(innerTask);
}
TaskBase *CreateIsoAuthServerTask(const CJson *in, CJson *out, const AccountVersionInfo *verInfo)
{
if ((in == NULL) || (out == NULL) || (verInfo == NULL)) {
LOGE("Params is null for server sym auth.");
return NULL;
}
IsoAuthServerTask *task = (IsoAuthServerTask *)HcMalloc(sizeof(IsoAuthServerTask), 0);
if (task == NULL) {
LOGE("Malloc for IsoAuthServerTask failed.");
return NULL;
}
task->taskBase.getTaskType = GetIsoAuthServerType;
task->taskBase.process = ProcessServerTask;
task->taskBase.destroyTask = DestroyAuthServerAuthTask;
int32_t res = InitIsoAuthParams(in, &(task->params), verInfo);
if (res != HC_SUCCESS) {
LOGE("InitIsoAuthParams failed, res: %d.", res);
DestroyAuthServerAuthTask((TaskBase *)task);
return NULL;
}
task->taskBase.taskStatus = TASK_STATUS_SERVER_BEGIN_TOKEN;
return (TaskBase *)task;
}
@@ -1,424 +1,424 @@
/*
* Copyright (C) 2022 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 "iso_auth_task_common.h"
#include "clib_error.h"
#include "common_defs.h"
#include "device_auth.h"
#include "device_auth_defines.h"
#include "hc_log.h"
#include "hc_types.h"
#include "iso_auth_client_task.h"
#include "iso_auth_server_task.h"
#include "protocol_common.h"
#include "sym_token_manager.h"
#define KEY_INFO_PERSISTENT_TOKEN "persistent_token"
#define AUTH_TOKEN_SIZE_BYTE 32
bool IsIsoAuthTaskSupported(void)
{
return true;
}
TaskBase *CreateIsoAuthTask(const CJson *in, CJson *out, const AccountVersionInfo *verInfo)
{
bool isClient = false;
if (GetBoolFromJson(in, FIELD_IS_CLIENT, &isClient) != CLIB_SUCCESS) {
LOGD("Get isClient from json failed."); /* default: server. */
}
return isClient ? CreateIsoAuthClientTask(in, out, verInfo) :
CreateIsoAuthServerTask(in, out, verInfo);
}
static int32_t FillUserId(const CJson *in, IsoAuthParams *params)
{
params->userIdSelf = (char *)HcMalloc(DEV_AUTH_USER_ID_SIZE, 0);
if (params->userIdSelf == NULL) {
LOGE("Failed to malloc for userIdSelf.");
return HC_ERR_ALLOC_MEMORY;
}
params->userIdPeer = (char *)HcMalloc(DEV_AUTH_USER_ID_SIZE, 0);
if (params->userIdPeer == NULL) {
LOGE("Failed to malloc for userIdPeer.");
return HC_ERR_ALLOC_MEMORY;
}
const char *userIdSelf = GetStringFromJson(in, FIELD_SELF_USER_ID);
if (userIdSelf == NULL) {
LOGE("Failed to get self userId from input data in sym auth.");
return HC_ERR_JSON_GET;
}
if (strcpy_s(params->userIdSelf, DEV_AUTH_USER_ID_SIZE, userIdSelf) != EOK) {
LOGE("Copy for userIdSelf failed in sym auth.");
return HC_ERR_MEMORY_COPY;
}
return HC_SUCCESS;
}
static int32_t FillPayload(const CJson *in, IsoAuthParams *params)
{
int32_t res = InitSingleParam(&params->devIdSelf, DEV_AUTH_DEVICE_ID_SIZE);
if (res != HC_SUCCESS) {
LOGE("InitSingleParam for devIdSelf failed, res: %d.", res);
return res;
}
const char *devIdSelf = GetStringFromJson(in, FIELD_SELF_DEV_ID);
if (devIdSelf == NULL) {
LOGE("Failed to get devIdSelf in sym auth.");
return HC_ERR_JSON_GET;
}
uint32_t devIdLen = HcStrlen(devIdSelf);
if (memcpy_s(params->devIdSelf.val, params->devIdSelf.length, devIdSelf, devIdLen + 1) != EOK) {
LOGE("Copy for self devId failed in sym auth.");
return HC_ERR_MEMORY_COPY;
}
params->devIdSelf.length = devIdLen;
const char *selfDeviceId = GetStringFromJson(in, FIELD_SELF_DEVICE_ID);
if (selfDeviceId == NULL) {
LOGE("Failed to get self deviceId from input data in sym auth.");
return HC_ERR_JSON_GET;
}
uint32_t selfDeviceIdLen = HcStrlen(selfDeviceId);
params->deviceIdSelf = (char *)HcMalloc(selfDeviceIdLen + 1, 0);
if (params->deviceIdSelf == NULL) {
LOGE("Failed to malloc for selfDeviceId.");
return HC_ERR_ALLOC_MEMORY;
}
if (memcpy_s(params->deviceIdSelf, selfDeviceIdLen + 1, selfDeviceId, selfDeviceIdLen) != EOK) {
LOGE("Copy for deviceIdSelf failed in sym auth.");
return HC_ERR_MEMORY_COPY;
}
params->isoBaseParams.authIdSelf.length = params->devIdSelf.length + HcStrlen(params->deviceIdSelf);
res = InitSingleParam(&params->isoBaseParams.authIdSelf, params->isoBaseParams.authIdSelf.length);
if (res != HC_SUCCESS) {
LOGE("InitSingleParam for authIdSelf failed, res: %d.", res);
return res;
}
if (memcpy_s(params->isoBaseParams.authIdSelf.val, params->isoBaseParams.authIdSelf.length,
params->devIdSelf.val, params->devIdSelf.length) != EOK) {
LOGE("Failed to memcpy devIdSelf for authId in sym auth.");
return HC_ERR_MEMORY_COPY;
}
if (memcpy_s(params->isoBaseParams.authIdSelf.val + params->devIdSelf.length,
params->isoBaseParams.authIdSelf.length - params->devIdSelf.length,
params->deviceIdSelf, selfDeviceIdLen) != EOK) {
LOGE("Failed to memcpy deviceIdSelf for authId in sym auth.");
return HC_ERR_MEMORY_COPY;
}
return HC_SUCCESS;
}
static int32_t SetChallenge(IsoAuthParams *params, const CJson *in)
{
if (((uint32_t)params->credentialType & SYMMETRIC_CRED) == SYMMETRIC_CRED) {
params->challenge.length = HcStrlen(KEY_INFO_PERSISTENT_TOKEN);
params->challenge.val = (uint8_t *)HcMalloc(params->challenge.length, 0);
if (params->challenge.val == NULL) {
LOGE("Failed to malloc for challenge.");
return HC_ERR_ALLOC_MEMORY;
}
if (memcpy_s(params->challenge.val, params->challenge.length, KEY_INFO_PERSISTENT_TOKEN,
HcStrlen(KEY_INFO_PERSISTENT_TOKEN)) != EOK) {
LOGE("Copy for challenge failed in sym auth.");
return HC_ERR_MEMORY_COPY;
}
return HC_SUCCESS;
}
LOGE("Invalid credentialType: %d", params->credentialType);
return HC_ERR_INVALID_PARAMS;
}
static int32_t GenerateAuthTokenForAccessory(const IsoAuthParams *params, Uint8Buff *outKey)
{
uint8_t keyAliasVal[SHA256_LEN] = { 0 };
Uint8Buff keyAlias = { keyAliasVal, SHA256_LEN };
int32_t res = GetSymTokenManager()->generateKeyAlias(params->userIdSelf, (const char *)(params->devIdSelf.val),
&keyAlias);
if (res != HC_SUCCESS) {
LOGE("Failed to generate key alias for authCode!");
return res;
}
res = InitSingleParam(outKey, AUTH_TOKEN_SIZE_BYTE);
if (res != HC_SUCCESS) {
LOGE("Malloc for authToken failed, res: %d.", res);
return res;
}
Uint8Buff userIdSelfBuff = {
.val = (uint8_t *)(params->userIdSelf),
.length = HcStrlen(params->userIdSelf)
};
res = params->isoBaseParams.loader->computeHkdf(&keyAlias, &userIdSelfBuff, &params->challenge, outKey, true);
if (res != HC_SUCCESS) {
LOGE("Failed to computeHkdf from authCode to authToken.");
FreeAndCleanKey(outKey);
}
return res;
}
static int32_t GenerateTokenAliasForController(const IsoAuthParams *params, Uint8Buff *authTokenAlias)
{
int32_t res = InitSingleParam(authTokenAlias, SHA256_LEN);
if (res != HC_SUCCESS) {
LOGE("Malloc for authToken alias failed, res: %d.", res);
return res;
}
res = GetSymTokenManager()->generateKeyAlias(params->userIdPeer, (const char *)(params->devIdPeer.val),
authTokenAlias);
if (res != HC_SUCCESS) {
LOGE("Failed to generate key alias for authToken.");
HcFree(authTokenAlias->val);
authTokenAlias->val = NULL;
}
return res;
}
int32_t AccountAuthGeneratePsk(IsoAuthParams *params)
{
bool isTokenStored = true;
Uint8Buff authToken = { NULL, 0 };
int32_t res;
if (params->localDevType == DEVICE_TYPE_ACCESSORY) {
LOGI("Account sym auth for accessory.");
isTokenStored = false;
res = GenerateAuthTokenForAccessory(params, &authToken);
} else {
LOGI("Account sym auth for controller.");
res = GenerateTokenAliasForController(params, &authToken);
}
if (res != HC_SUCCESS) {
LOGE("Failed to generate token-related info, res = %d.", res);
return res;
}
Uint8Buff pskBuf = { params->isoBaseParams.psk, PSK_SIZE };
Uint8Buff seedBuf = { params->seed, sizeof(params->seed) };
res = params->isoBaseParams.loader->computeHmac(&authToken, &seedBuf, &pskBuf, isTokenStored);
FreeAndCleanKey(&authToken);
if (res != HC_SUCCESS) {
LOGE("ComputeHmac for psk failed, res: %d.", res);
}
return res;
}
int32_t InitIsoAuthParams(const CJson *in, IsoAuthParams *params, const AccountVersionInfo *verInfo)
{
params->versionNo = verInfo->versionNo;
int32_t res = HC_ERR_JSON_GET;
if (GetIntFromJson(in, FIELD_AUTH_FORM, &params->authForm) != CLIB_SUCCESS) {
LOGE("Failed to get authForm from json in sym auth.");
goto CLEAN_UP;
}
if (GetIntFromJson(in, FIELD_CREDENTIAL_TYPE, &params->credentialType) != CLIB_SUCCESS) {
LOGE("Failed to get credentialType from json in sym auth.");
goto CLEAN_UP;
}
if (GetIntFromJson(in, FIELD_LOCAL_DEVICE_TYPE, &params->localDevType) != CLIB_SUCCESS) {
LOGE("Failed to get localDevType from json in sym auth.");
goto CLEAN_UP;
}
res = InitIsoBaseParams(&params->isoBaseParams);
if (res != HC_SUCCESS) {
LOGE("InitIsoBaseParams failed, res: %x.", res);
goto CLEAN_UP;
}
res = FillUserId(in, params);
if (res != HC_SUCCESS) {
LOGE("Failed to fill userId info, res = %d.", res);
goto CLEAN_UP;
}
res = FillPayload(in, params);
if (res != HC_SUCCESS) {
LOGE("Failed to fill payload info, res = %d.", res);
goto CLEAN_UP;
}
if (params->localDevType == DEVICE_TYPE_ACCESSORY) {
res = SetChallenge(params, in);
if (res != HC_SUCCESS) {
LOGE("SetChallenge failed, res = %d.", res);
goto CLEAN_UP;
}
}
return HC_SUCCESS;
CLEAN_UP:
DestroyIsoAuthParams(params);
return res;
}
void DestroyIsoAuthParams(IsoAuthParams *params)
{
LOGI("Destroy iso auth params begin.");
if (params == NULL) {
return;
}
DestroyIsoBaseParams(&params->isoBaseParams);
HcFree(params->challenge.val);
params->challenge.val = NULL;
HcFree(params->userIdSelf);
params->userIdSelf = NULL;
HcFree(params->userIdPeer);
params->userIdPeer = NULL;
HcFree(params->devIdSelf.val);
params->devIdSelf.val = NULL;
HcFree(params->devIdPeer.val);
params->devIdPeer.val = NULL;
HcFree(params->deviceIdSelf);
params->deviceIdSelf = NULL;
HcFree(params->deviceIdPeer);
params->deviceIdPeer = NULL;
}
static int32_t GetPayloadValue(IsoAuthParams *params, const CJson *in)
{
const char *devIdPeerHex = GetStringFromJson(in, FIELD_DEV_ID);
if (devIdPeerHex == NULL) {
LOGE("Get peer devId hex failed.");
return HC_ERR_JSON_GET;
}
uint32_t devIdPeerHexLen = HcStrlen(devIdPeerHex);
// DevId is string, the id from phone is byte. For both cases, apply one more bit for '\0'.
params->devIdPeer.val = (uint8_t *)HcMalloc(devIdPeerHexLen / BYTE_TO_HEX_OPER_LENGTH + 1, 0);
if (params->devIdPeer.val == NULL) {
LOGE("Failed to malloc for peer devId.");
return HC_ERR_ALLOC_MEMORY;
}
params->devIdPeer.length = devIdPeerHexLen / BYTE_TO_HEX_OPER_LENGTH;
if (HexStringToByte(devIdPeerHex, params->devIdPeer.val, params->devIdPeer.length) != CLIB_SUCCESS) {
LOGE("Failed to convert peer devId.");
return HC_ERR_CONVERT_FAILED;
}
const char *deviceIdPeer = GetStringFromJson(in, FIELD_DEVICE_ID);
if (deviceIdPeer == NULL) {
LOGE("Get peer deviceId failed.");
return HC_ERR_JSON_GET;
}
uint32_t deviceIdPeerLen = HcStrlen(deviceIdPeer);
params->deviceIdPeer = (char *)HcMalloc(deviceIdPeerLen + 1, 0);
if (params->deviceIdPeer == NULL) {
LOGE("Failed to malloc for peer deviceId.");
return HC_ERR_ALLOC_MEMORY;
}
if (memcpy_s(params->deviceIdPeer, deviceIdPeerLen + 1, deviceIdPeer, deviceIdPeerLen) != EOK) {
LOGE("Failed to copy peer deviceId.");
return HC_ERR_MEMORY_COPY;
}
return HC_SUCCESS;
}
static int32_t ExtractPeerAuthId(IsoAuthParams *params, const CJson *in)
{
const char *payloadHex = GetStringFromJson(in, FIELD_PAYLOAD);
if (payloadHex == NULL) {
LOGE("Get payloadHex peer from json failed.");
return HC_ERR_JSON_GET;
}
int32_t res = InitSingleParam(&(params->isoBaseParams.authIdPeer), HcStrlen(payloadHex) / BYTE_TO_HEX_OPER_LENGTH);
if (res != HC_SUCCESS) {
LOGE("InitSingleParam for payload peer failed, res: %d.", res);
return res;
}
if (HexStringToByte(payloadHex, params->isoBaseParams.authIdPeer.val,
params->isoBaseParams.authIdPeer.length) != CLIB_SUCCESS) {
LOGE("Convert payloadPeer from hex string to byte failed.");
return HC_ERR_CONVERT_FAILED;
}
return HC_SUCCESS;
}
int32_t ExtractAndVerifyPayload(IsoAuthParams *params, const CJson *in)
{
int32_t res = ExtractPeerAuthId(params, in);
if (res != HC_SUCCESS) {
LOGE("ExtractPeerAuthId failed, res: %d.", res);
return res;
}
res = GetPayloadValue(params, in);
if (res != HC_SUCCESS) {
LOGE("GetPayloadValue failed, res: %d.", res);
return res;
}
uint32_t deviceIdPeerLen = HcStrlen(params->deviceIdPeer);
uint32_t len = params->devIdPeer.length + deviceIdPeerLen;
char *combineString = (char *)HcMalloc(len, 0);
if (combineString == NULL) {
LOGE("Failed to malloc for combineString.");
return HC_ERR_ALLOC_MEMORY;
}
if (memcpy_s(combineString, len, params->devIdPeer.val, params->devIdPeer.length) != EOK) {
LOGE("Failed to copy peer devId.");
HcFree(combineString);
return HC_ERR_MEMORY_COPY;
}
if (memcpy_s(combineString + params->devIdPeer.length, len - params->devIdPeer.length, params->deviceIdPeer,
deviceIdPeerLen) != EOK) {
LOGE("Failed to copy peer deviceId.");
HcFree(combineString);
return HC_ERR_MEMORY_COPY;
}
if (memcmp(combineString, params->isoBaseParams.authIdPeer.val, len) != 0) {
LOGE("Payload is not equal.");
HcFree(combineString);
return HC_ERR_MEMORY_COMPARE;
}
HcFree(combineString);
return HC_SUCCESS;
}
int32_t AuthIsoSendFinalToOut(IsoAuthParams *params, CJson *out)
{
CJson *sendToSelf = CreateJson();
if (sendToSelf == NULL) {
LOGE("Create sendToSelf json failed.");
return HC_ERR_JSON_CREATE;
}
if (AddByteToJson(sendToSelf, FIELD_SESSION_KEY,
params->isoBaseParams.sessionKey.val, params->isoBaseParams.sessionKey.length) != CLIB_SUCCESS) {
LOGE("Add sessionKey to json failed.");
goto CLEAN_UP;
}
if (AddStringToJson(sendToSelf, FIELD_USER_ID, params->userIdPeer) != CLIB_SUCCESS) {
LOGE("Add userIdPeer to json failed.");
goto CLEAN_UP;
}
if (AddStringToJson(sendToSelf, FIELD_DEVICE_ID, params->deviceIdPeer) != CLIB_SUCCESS) {
LOGE("Add deviceIdPeer to json failed.");
goto CLEAN_UP;
}
if (AddIntToJson(sendToSelf, FIELD_CREDENTIAL_TYPE, params->credentialType) != CLIB_SUCCESS) {
LOGE("Add credentialType to json failed.");
goto CLEAN_UP;
}
if (AddStringToJson(sendToSelf, FIELD_DEV_ID, (char *)params->devIdPeer.val) != CLIB_SUCCESS) {
LOGE("Add devIdPeer to json failed.");
goto CLEAN_UP;
}
if (AddObjToJson(out, FIELD_SEND_TO_SELF, sendToSelf) != CLIB_SUCCESS) {
LOGE("Add sendToSelf to json failed.");
goto CLEAN_UP;
}
FreeJson(sendToSelf);
FreeAndCleanKey(&(params->isoBaseParams.sessionKey));
return HC_SUCCESS;
CLEAN_UP:
FreeJson(sendToSelf);
FreeAndCleanKey(&(params->isoBaseParams.sessionKey));
return HC_ERR_JSON_ADD;
}
/*
* Copyright (C) 2022 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 "iso_auth_task_common.h"
#include "clib_error.h"
#include "common_defs.h"
#include "device_auth.h"
#include "device_auth_defines.h"
#include "hc_log.h"
#include "hc_types.h"
#include "iso_auth_client_task.h"
#include "iso_auth_server_task.h"
#include "protocol_common.h"
#include "sym_token_manager.h"
#define KEY_INFO_PERSISTENT_TOKEN "persistent_token"
#define AUTH_TOKEN_SIZE_BYTE 32
bool IsIsoAuthTaskSupported(void)
{
return true;
}
TaskBase *CreateIsoAuthTask(const CJson *in, CJson *out, const AccountVersionInfo *verInfo)
{
bool isClient = false;
if (GetBoolFromJson(in, FIELD_IS_CLIENT, &isClient) != CLIB_SUCCESS) {
LOGD("Get isClient from json failed."); /* default: server. */
}
return isClient ? CreateIsoAuthClientTask(in, out, verInfo) :
CreateIsoAuthServerTask(in, out, verInfo);
}
static int32_t FillUserId(const CJson *in, IsoAuthParams *params)
{
params->userIdSelf = (char *)HcMalloc(DEV_AUTH_USER_ID_SIZE, 0);
if (params->userIdSelf == NULL) {
LOGE("Failed to malloc for userIdSelf.");
return HC_ERR_ALLOC_MEMORY;
}
params->userIdPeer = (char *)HcMalloc(DEV_AUTH_USER_ID_SIZE, 0);
if (params->userIdPeer == NULL) {
LOGE("Failed to malloc for userIdPeer.");
return HC_ERR_ALLOC_MEMORY;
}
const char *userIdSelf = GetStringFromJson(in, FIELD_SELF_USER_ID);
if (userIdSelf == NULL) {
LOGE("Failed to get self userId from input data in sym auth.");
return HC_ERR_JSON_GET;
}
if (strcpy_s(params->userIdSelf, DEV_AUTH_USER_ID_SIZE, userIdSelf) != EOK) {
LOGE("Copy for userIdSelf failed in sym auth.");
return HC_ERR_MEMORY_COPY;
}
return HC_SUCCESS;
}
static int32_t FillPayload(const CJson *in, IsoAuthParams *params)
{
int32_t res = InitSingleParam(&params->devIdSelf, DEV_AUTH_DEVICE_ID_SIZE);
if (res != HC_SUCCESS) {
LOGE("InitSingleParam for devIdSelf failed, res: %d.", res);
return res;
}
const char *devIdSelf = GetStringFromJson(in, FIELD_SELF_DEV_ID);
if (devIdSelf == NULL) {
LOGE("Failed to get devIdSelf in sym auth.");
return HC_ERR_JSON_GET;
}
uint32_t devIdLen = HcStrlen(devIdSelf);
if (memcpy_s(params->devIdSelf.val, params->devIdSelf.length, devIdSelf, devIdLen + 1) != EOK) {
LOGE("Copy for self devId failed in sym auth.");
return HC_ERR_MEMORY_COPY;
}
params->devIdSelf.length = devIdLen;
const char *selfDeviceId = GetStringFromJson(in, FIELD_SELF_DEVICE_ID);
if (selfDeviceId == NULL) {
LOGE("Failed to get self deviceId from input data in sym auth.");
return HC_ERR_JSON_GET;
}
uint32_t selfDeviceIdLen = HcStrlen(selfDeviceId);
params->deviceIdSelf = (char *)HcMalloc(selfDeviceIdLen + 1, 0);
if (params->deviceIdSelf == NULL) {
LOGE("Failed to malloc for selfDeviceId.");
return HC_ERR_ALLOC_MEMORY;
}
if (memcpy_s(params->deviceIdSelf, selfDeviceIdLen + 1, selfDeviceId, selfDeviceIdLen) != EOK) {
LOGE("Copy for deviceIdSelf failed in sym auth.");
return HC_ERR_MEMORY_COPY;
}
params->isoBaseParams.authIdSelf.length = params->devIdSelf.length + HcStrlen(params->deviceIdSelf);
res = InitSingleParam(&params->isoBaseParams.authIdSelf, params->isoBaseParams.authIdSelf.length);
if (res != HC_SUCCESS) {
LOGE("InitSingleParam for authIdSelf failed, res: %d.", res);
return res;
}
if (memcpy_s(params->isoBaseParams.authIdSelf.val, params->isoBaseParams.authIdSelf.length,
params->devIdSelf.val, params->devIdSelf.length) != EOK) {
LOGE("Failed to memcpy devIdSelf for authId in sym auth.");
return HC_ERR_MEMORY_COPY;
}
if (memcpy_s(params->isoBaseParams.authIdSelf.val + params->devIdSelf.length,
params->isoBaseParams.authIdSelf.length - params->devIdSelf.length,
params->deviceIdSelf, selfDeviceIdLen) != EOK) {
LOGE("Failed to memcpy deviceIdSelf for authId in sym auth.");
return HC_ERR_MEMORY_COPY;
}
return HC_SUCCESS;
}
static int32_t SetChallenge(IsoAuthParams *params, const CJson *in)
{
if (((uint32_t)params->credentialType & SYMMETRIC_CRED) == SYMMETRIC_CRED) {
params->challenge.length = HcStrlen(KEY_INFO_PERSISTENT_TOKEN);
params->challenge.val = (uint8_t *)HcMalloc(params->challenge.length, 0);
if (params->challenge.val == NULL) {
LOGE("Failed to malloc for challenge.");
return HC_ERR_ALLOC_MEMORY;
}
if (memcpy_s(params->challenge.val, params->challenge.length, KEY_INFO_PERSISTENT_TOKEN,
HcStrlen(KEY_INFO_PERSISTENT_TOKEN)) != EOK) {
LOGE("Copy for challenge failed in sym auth.");
return HC_ERR_MEMORY_COPY;
}
return HC_SUCCESS;
}
LOGE("Invalid credentialType: %d", params->credentialType);
return HC_ERR_INVALID_PARAMS;
}
static int32_t GenerateAuthTokenForAccessory(const IsoAuthParams *params, Uint8Buff *outKey)
{
uint8_t keyAliasVal[SHA256_LEN] = { 0 };
Uint8Buff keyAlias = { keyAliasVal, SHA256_LEN };
int32_t res = GetSymTokenManager()->generateKeyAlias(params->userIdSelf, (const char *)(params->devIdSelf.val),
&keyAlias);
if (res != HC_SUCCESS) {
LOGE("Failed to generate key alias for authCode!");
return res;
}
res = InitSingleParam(outKey, AUTH_TOKEN_SIZE_BYTE);
if (res != HC_SUCCESS) {
LOGE("Malloc for authToken failed, res: %d.", res);
return res;
}
Uint8Buff userIdSelfBuff = {
.val = (uint8_t *)(params->userIdSelf),
.length = HcStrlen(params->userIdSelf)
};
res = params->isoBaseParams.loader->computeHkdf(&keyAlias, &userIdSelfBuff, &params->challenge, outKey, true);
if (res != HC_SUCCESS) {
LOGE("Failed to computeHkdf from authCode to authToken.");
FreeAndCleanKey(outKey);
}
return res;
}
static int32_t GenerateTokenAliasForController(const IsoAuthParams *params, Uint8Buff *authTokenAlias)
{
int32_t res = InitSingleParam(authTokenAlias, SHA256_LEN);
if (res != HC_SUCCESS) {
LOGE("Malloc for authToken alias failed, res: %d.", res);
return res;
}
res = GetSymTokenManager()->generateKeyAlias(params->userIdPeer, (const char *)(params->devIdPeer.val),
authTokenAlias);
if (res != HC_SUCCESS) {
LOGE("Failed to generate key alias for authToken.");
HcFree(authTokenAlias->val);
authTokenAlias->val = NULL;
}
return res;
}
int32_t AccountAuthGeneratePsk(IsoAuthParams *params)
{
bool isTokenStored = true;
Uint8Buff authToken = { NULL, 0 };
int32_t res;
if (params->localDevType == DEVICE_TYPE_ACCESSORY) {
LOGI("Account sym auth for accessory.");
isTokenStored = false;
res = GenerateAuthTokenForAccessory(params, &authToken);
} else {
LOGI("Account sym auth for controller.");
res = GenerateTokenAliasForController(params, &authToken);
}
if (res != HC_SUCCESS) {
LOGE("Failed to generate token-related info, res = %d.", res);
return res;
}
Uint8Buff pskBuf = { params->isoBaseParams.psk, PSK_SIZE };
Uint8Buff seedBuf = { params->seed, sizeof(params->seed) };
res = params->isoBaseParams.loader->computeHmac(&authToken, &seedBuf, &pskBuf, isTokenStored);
FreeAndCleanKey(&authToken);
if (res != HC_SUCCESS) {
LOGE("ComputeHmac for psk failed, res: %d.", res);
}
return res;
}
int32_t InitIsoAuthParams(const CJson *in, IsoAuthParams *params, const AccountVersionInfo *verInfo)
{
params->versionNo = verInfo->versionNo;
int32_t res = HC_ERR_JSON_GET;
if (GetIntFromJson(in, FIELD_AUTH_FORM, &params->authForm) != CLIB_SUCCESS) {
LOGE("Failed to get authForm from json in sym auth.");
goto CLEAN_UP;
}
if (GetIntFromJson(in, FIELD_CREDENTIAL_TYPE, &params->credentialType) != CLIB_SUCCESS) {
LOGE("Failed to get credentialType from json in sym auth.");
goto CLEAN_UP;
}
if (GetIntFromJson(in, FIELD_LOCAL_DEVICE_TYPE, &params->localDevType) != CLIB_SUCCESS) {
LOGE("Failed to get localDevType from json in sym auth.");
goto CLEAN_UP;
}
res = InitIsoBaseParams(&params->isoBaseParams);
if (res != HC_SUCCESS) {
LOGE("InitIsoBaseParams failed, res: %x.", res);
goto CLEAN_UP;
}
res = FillUserId(in, params);
if (res != HC_SUCCESS) {
LOGE("Failed to fill userId info, res = %d.", res);
goto CLEAN_UP;
}
res = FillPayload(in, params);
if (res != HC_SUCCESS) {
LOGE("Failed to fill payload info, res = %d.", res);
goto CLEAN_UP;
}
if (params->localDevType == DEVICE_TYPE_ACCESSORY) {
res = SetChallenge(params, in);
if (res != HC_SUCCESS) {
LOGE("SetChallenge failed, res = %d.", res);
goto CLEAN_UP;
}
}
return HC_SUCCESS;
CLEAN_UP:
DestroyIsoAuthParams(params);
return res;
}
void DestroyIsoAuthParams(IsoAuthParams *params)
{
LOGI("Destroy iso auth params begin.");
if (params == NULL) {
return;
}
DestroyIsoBaseParams(&params->isoBaseParams);
HcFree(params->challenge.val);
params->challenge.val = NULL;
HcFree(params->userIdSelf);
params->userIdSelf = NULL;
HcFree(params->userIdPeer);
params->userIdPeer = NULL;
HcFree(params->devIdSelf.val);
params->devIdSelf.val = NULL;
HcFree(params->devIdPeer.val);
params->devIdPeer.val = NULL;
HcFree(params->deviceIdSelf);
params->deviceIdSelf = NULL;
HcFree(params->deviceIdPeer);
params->deviceIdPeer = NULL;
}
static int32_t GetPayloadValue(IsoAuthParams *params, const CJson *in)
{
const char *devIdPeerHex = GetStringFromJson(in, FIELD_DEV_ID);
if (devIdPeerHex == NULL) {
LOGE("Get peer devId hex failed.");
return HC_ERR_JSON_GET;
}
uint32_t devIdPeerHexLen = HcStrlen(devIdPeerHex);
// DevId is string, the id from phone is byte. For both cases, apply one more bit for '\0'.
params->devIdPeer.val = (uint8_t *)HcMalloc(devIdPeerHexLen / BYTE_TO_HEX_OPER_LENGTH + 1, 0);
if (params->devIdPeer.val == NULL) {
LOGE("Failed to malloc for peer devId.");
return HC_ERR_ALLOC_MEMORY;
}
params->devIdPeer.length = devIdPeerHexLen / BYTE_TO_HEX_OPER_LENGTH;
if (HexStringToByte(devIdPeerHex, params->devIdPeer.val, params->devIdPeer.length) != CLIB_SUCCESS) {
LOGE("Failed to convert peer devId.");
return HC_ERR_CONVERT_FAILED;
}
const char *deviceIdPeer = GetStringFromJson(in, FIELD_DEVICE_ID);
if (deviceIdPeer == NULL) {
LOGE("Get peer deviceId failed.");
return HC_ERR_JSON_GET;
}
uint32_t deviceIdPeerLen = HcStrlen(deviceIdPeer);
params->deviceIdPeer = (char *)HcMalloc(deviceIdPeerLen + 1, 0);
if (params->deviceIdPeer == NULL) {
LOGE("Failed to malloc for peer deviceId.");
return HC_ERR_ALLOC_MEMORY;
}
if (memcpy_s(params->deviceIdPeer, deviceIdPeerLen + 1, deviceIdPeer, deviceIdPeerLen) != EOK) {
LOGE("Failed to copy peer deviceId.");
return HC_ERR_MEMORY_COPY;
}
return HC_SUCCESS;
}
static int32_t ExtractPeerAuthId(IsoAuthParams *params, const CJson *in)
{
const char *payloadHex = GetStringFromJson(in, FIELD_PAYLOAD);
if (payloadHex == NULL) {
LOGE("Get payloadHex peer from json failed.");
return HC_ERR_JSON_GET;
}
int32_t res = InitSingleParam(&(params->isoBaseParams.authIdPeer), HcStrlen(payloadHex) / BYTE_TO_HEX_OPER_LENGTH);
if (res != HC_SUCCESS) {
LOGE("InitSingleParam for payload peer failed, res: %d.", res);
return res;
}
if (HexStringToByte(payloadHex, params->isoBaseParams.authIdPeer.val,
params->isoBaseParams.authIdPeer.length) != CLIB_SUCCESS) {
LOGE("Convert payloadPeer from hex string to byte failed.");
return HC_ERR_CONVERT_FAILED;
}
return HC_SUCCESS;
}
int32_t ExtractAndVerifyPayload(IsoAuthParams *params, const CJson *in)
{
int32_t res = ExtractPeerAuthId(params, in);
if (res != HC_SUCCESS) {
LOGE("ExtractPeerAuthId failed, res: %d.", res);
return res;
}
res = GetPayloadValue(params, in);
if (res != HC_SUCCESS) {
LOGE("GetPayloadValue failed, res: %d.", res);
return res;
}
uint32_t deviceIdPeerLen = HcStrlen(params->deviceIdPeer);
uint32_t len = params->devIdPeer.length + deviceIdPeerLen;
char *combineString = (char *)HcMalloc(len, 0);
if (combineString == NULL) {
LOGE("Failed to malloc for combineString.");
return HC_ERR_ALLOC_MEMORY;
}
if (memcpy_s(combineString, len, params->devIdPeer.val, params->devIdPeer.length) != EOK) {
LOGE("Failed to copy peer devId.");
HcFree(combineString);
return HC_ERR_MEMORY_COPY;
}
if (memcpy_s(combineString + params->devIdPeer.length, len - params->devIdPeer.length, params->deviceIdPeer,
deviceIdPeerLen) != EOK) {
LOGE("Failed to copy peer deviceId.");
HcFree(combineString);
return HC_ERR_MEMORY_COPY;
}
if (memcmp(combineString, params->isoBaseParams.authIdPeer.val, len) != 0) {
LOGE("Payload is not equal.");
HcFree(combineString);
return HC_ERR_MEMORY_COMPARE;
}
HcFree(combineString);
return HC_SUCCESS;
}
int32_t AuthIsoSendFinalToOut(IsoAuthParams *params, CJson *out)
{
CJson *sendToSelf = CreateJson();
if (sendToSelf == NULL) {
LOGE("Create sendToSelf json failed.");
return HC_ERR_JSON_CREATE;
}
if (AddByteToJson(sendToSelf, FIELD_SESSION_KEY,
params->isoBaseParams.sessionKey.val, params->isoBaseParams.sessionKey.length) != CLIB_SUCCESS) {
LOGE("Add sessionKey to json failed.");
goto CLEAN_UP;
}
if (AddStringToJson(sendToSelf, FIELD_USER_ID, params->userIdPeer) != CLIB_SUCCESS) {
LOGE("Add userIdPeer to json failed.");
goto CLEAN_UP;
}
if (AddStringToJson(sendToSelf, FIELD_DEVICE_ID, params->deviceIdPeer) != CLIB_SUCCESS) {
LOGE("Add deviceIdPeer to json failed.");
goto CLEAN_UP;
}
if (AddIntToJson(sendToSelf, FIELD_CREDENTIAL_TYPE, params->credentialType) != CLIB_SUCCESS) {
LOGE("Add credentialType to json failed.");
goto CLEAN_UP;
}
if (AddStringToJson(sendToSelf, FIELD_DEV_ID, (char *)params->devIdPeer.val) != CLIB_SUCCESS) {
LOGE("Add devIdPeer to json failed.");
goto CLEAN_UP;
}
if (AddObjToJson(out, FIELD_SEND_TO_SELF, sendToSelf) != CLIB_SUCCESS) {
LOGE("Add sendToSelf to json failed.");
goto CLEAN_UP;
}
FreeJson(sendToSelf);
FreeAndCleanKey(&(params->isoBaseParams.sessionKey));
return HC_SUCCESS;
CLEAN_UP:
FreeJson(sendToSelf);
FreeAndCleanKey(&(params->isoBaseParams.sessionKey));
return HC_ERR_JSON_ADD;
}
@@ -1,455 +1,455 @@
/*
* Copyright (C) 2022 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 "pake_v2_auth_task_common.h"
#include <ctype.h>
#include "account_module.h"
#include "asy_token_manager.h"
#include "common_defs.h"
#include "device_auth_defines.h"
#include "hc_dev_info.h"
#include "hc_log.h"
#include "hc_types.h"
#include "pake_v2_protocol_common.h"
#include "pake_v2_auth_client_task.h"
#include "pake_v2_auth_server_task.h"
#include "protocol_common.h"
#include "string_util.h"
#define P256_SHARED_SECRET_KEY_SIZE 32
#define P256_PUBLIC_SIZE 64
#define P256_KEY_SIZE 32
#define SHARED_KEY_ALIAS "sharedKeyAlias"
bool IsPakeV2AuthTaskSupported(void)
{
return true;
}
TaskBase *CreatePakeV2AuthTask(const CJson *in, CJson *out, const AccountVersionInfo *verInfo)
{
bool isClient = false;
if (GetBoolFromJson(in, FIELD_IS_CLIENT, &isClient) != HC_SUCCESS) {
LOGD("Get isClient from json failed.");
isClient = false;
}
if (isClient) {
return CreatePakeV2AuthClientTask(in, out, verInfo);
}
return CreatePakeV2AuthServerTask(in, out, verInfo);
}
int32_t VerifyPkSignPeer(const PakeAuthParams *params)
{
uint8_t *serverPkAlias = (uint8_t *)HcMalloc(SHA256_LEN, 0);
if (serverPkAlias == NULL) {
LOGE("Failed to malloc for serverPk key alias.");
return HC_ERR_ALLOC_MEMORY;
}
Uint8Buff serverPkAliasBuff = {
.val = serverPkAlias,
.length = SHA256_LEN
};
int32_t res = GetAccountAuthTokenManager()->generateKeyAlias((const char *)(params->userIdSelf),
(const char *)params->devIdSelf.val, &serverPkAliasBuff, true);
if (res != HC_SUCCESS) {
HcFree(serverPkAlias);
return res;
}
Uint8Buff messageBuff = {
.val = params->pkInfoPeer.val,
.length = params->pkInfoPeer.length
};
Uint8Buff peerSignBuff = {
.val = params->pkInfoSignPeer.val,
.length = params->pkInfoSignPeer.length
};
res = params->pakeParams.loader->verify(&serverPkAliasBuff, &messageBuff, P256, &peerSignBuff, true);
HcFree(serverPkAlias);
if (res != HC_SUCCESS) {
LOGE("Verify pk sign failed.");
return HC_ERR_VERIFY_FAILED;
}
return HC_SUCCESS;
}
int32_t GenerateEcdhSharedKey(PakeAuthParams *params)
{
uint8_t *priAliasVal = (uint8_t *)HcMalloc(SHA256_LEN, 0);
if (priAliasVal == NULL) {
LOGE("Failed to malloc for self key alias.");
return HC_ERR_ALLOC_MEMORY;
}
Uint8Buff aliasBuff = {
.val = priAliasVal,
.length = SHA256_LEN
};
int32_t res = GetAccountAuthTokenManager()->generateKeyAlias((const char *)(params->userIdSelf),
(const char *)params->devIdSelf.val, &aliasBuff, false);
if (res != HC_SUCCESS) {
HcFree(priAliasVal);
return res;
}
KeyBuff priAliasKeyBuff = {
.key = aliasBuff.val,
.keyLen = aliasBuff.length,
.isAlias = true
};
KeyBuff publicKeyBuff = {
.key = params->pkPeer,
.keyLen = sizeof(params->pkPeer),
.isAlias = false
};
uint32_t sharedKeyAliasLen = HcStrlen(SHARED_KEY_ALIAS) + 1;
params->pakeParams.psk.val = (uint8_t *)HcMalloc(sharedKeyAliasLen, 0);
if (params->pakeParams.psk.val == NULL) {
LOGE("Failed to malloc for psk alias.");
HcFree(priAliasVal);
return HC_ERR_ALLOC_MEMORY;
}
params->pakeParams.psk.length = sharedKeyAliasLen;
(void)memcpy_s(params->pakeParams.psk.val, sharedKeyAliasLen, SHARED_KEY_ALIAS, sharedKeyAliasLen);
res = params->pakeParams.loader->agreeSharedSecretWithStorage(&priAliasKeyBuff, &publicKeyBuff,
P256, P256_SHARED_SECRET_KEY_SIZE, &(params->pakeParams.psk));
HcFree(priAliasVal);
return res;
}
static int32_t InitCharStringBuff(Uint8Buff *param, uint32_t len)
{
if (param == NULL || len <= 0) {
LOGE("param is invalid for init.");
return HC_ERR_NULL_PTR;
}
if (InitSingleParam(param, len + 1) != HC_SUCCESS) {
return HC_ERR_ALLOC_MEMORY;
}
param->length = len;
return HC_SUCCESS;
}
int32_t ExtractPakePeerId(PakeAuthParams *params, const CJson *in)
{
if (params == NULL || in == NULL) {
LOGE("Input params is invalid.");
return HC_ERR_INVALID_PARAMS;
}
uint32_t deviceIdPeerLen = HcStrlen((const char *)params->deviceIdPeer.val);
if (InitCharStringBuff(&params->pakeParams.idPeer,
params->devIdPeer.length + deviceIdPeerLen) != HC_SUCCESS) {
LOGE("InitCharStringBuff: idPeer failed.");
return HC_ERR_AUTH_INTERNAL;
}
(void)memcpy_s(params->pakeParams.idPeer.val, params->pakeParams.idPeer.length, params->devIdPeer.val,
params->devIdPeer.length);
(void)memcpy_s(params->pakeParams.idPeer.val + params->devIdPeer.length,
params->pakeParams.idPeer.length - params->devIdPeer.length, params->deviceIdPeer.val, deviceIdPeerLen);
return HC_SUCCESS;
}
int32_t ExtractPakeSelfId(PakeAuthParams *params)
{
if (params == NULL) {
LOGE("Input params NULL.");
return HC_ERR_INVALID_PARAMS;
}
uint32_t deviceIdSelfLen = HcStrlen((const char *)params->deviceIdSelf.val);
if (InitCharStringBuff(&params->pakeParams.idSelf,
params->devIdSelf.length + deviceIdSelfLen) != HC_SUCCESS) {
LOGE("InitCharStringBuff: idSelf failed.");
return HC_ERR_AUTH_INTERNAL;
}
(void)memcpy_s(params->pakeParams.idSelf.val, params->pakeParams.idSelf.length, params->devIdSelf.val,
params->devIdSelf.length);
(void)memcpy_s(params->pakeParams.idSelf.val + params->devIdSelf.length,
params->pakeParams.idSelf.length - params->devIdSelf.length, params->deviceIdSelf.val, deviceIdSelfLen);
return HC_SUCCESS;
}
static int32_t ExtractSelfDeviceId(PakeAuthParams *params, const CJson *in, bool useSelfPrefix)
{
if (params == NULL || in == NULL) {
LOGE("Input params NULL.");
return HC_ERR_INVALID_PARAMS;
}
const char *deviceId = NULL;
if (useSelfPrefix) {
deviceId = GetStringFromJson(in, FIELD_SELF_DEVICE_ID);
} else {
deviceId = GetStringFromJson(in, FIELD_DEVICE_ID);
}
if (deviceId == NULL) {
LOGE("Get selfDeviceId from json failed.");
return HC_ERR_JSON_GET;
}
params->deviceIdSelf.length = HcStrlen(deviceId);
params->deviceIdSelf.val = (uint8_t *)HcMalloc(params->deviceIdSelf.length + 1, 0);
if (params->deviceIdSelf.val == NULL) {
LOGE("Failed to malloc for deviceIdSelf.");
return HC_ERR_ALLOC_MEMORY;
}
if (memcpy_s(params->deviceIdSelf.val, params->deviceIdSelf.length + 1,
deviceId, params->deviceIdSelf.length) != EOK) {
LOGE("Memcpy_s for deviceIdSelf failed.");
return HC_ERR_MEMORY_COPY;
}
return HC_SUCCESS;
}
int32_t ExtractPeerDeviceId(PakeAuthParams *params, const CJson *in)
{
if (params == NULL || in == NULL) {
LOGE("Input params NULL.");
return HC_ERR_INVALID_PARAMS;
}
const char *deviceId = GetStringFromJson(in, FIELD_DEVICE_ID);
if (deviceId == NULL) {
LOGE("Get peer deviceId failed.");
return HC_ERR_JSON_GET;
}
uint32_t len = HcStrlen(deviceId);
if (InitCharStringBuff(&params->deviceIdPeer, len) != HC_SUCCESS) {
LOGE("InitCharStringBuff: deviceIdPeer failed.");
return HC_ERR_AUTH_INTERNAL;
}
if (memcpy_s(params->deviceIdPeer.val, params->deviceIdPeer.length + 1, deviceId, len) != EOK) {
LOGE("memcpy_s deviceId failed.");
return HC_ERR_MEMORY_COPY;
}
for (uint32_t i = 0; i < params->deviceIdPeer.length; i++) {
// Change a - f charactor to upper charactor.
if (params->deviceIdPeer.val[i] >= 'a' && params->deviceIdPeer.val[i] <= 'f') {
params->deviceIdPeer.val[i] = (uint8_t)toupper(params->deviceIdPeer.val[i]);
}
}
return HC_SUCCESS;
}
static int32_t ExtractSelfDevId(PakeAuthParams *params, const CJson *in)
{
if (params == NULL || in == NULL) {
LOGE("Input params is invalid.");
return HC_ERR_INVALID_PARAMS;
}
const char *devIdSelf = GetStringFromJson(in, FIELD_SELF_DEV_ID);
if (devIdSelf == NULL) {
LOGE("Get devIdSelf failed.");
return HC_ERR_JSON_GET;
}
params->devIdSelf.length = HcStrlen(devIdSelf);
params->devIdSelf.val = (uint8_t *)HcMalloc(params->devIdSelf.length + 1, 0);
if (params->devIdSelf.val == NULL) {
LOGE("Malloc for devIdSelf failed.");
return HC_ERR_ALLOC_MEMORY;
}
if (memcpy_s(params->devIdSelf.val, params->devIdSelf.length, devIdSelf,
params->devIdSelf.length) != EOK) {
LOGE("Copy for self devId failed.");
return HC_ERR_MEMORY_COPY;
}
return HC_SUCCESS;
}
int32_t ExtractPeerDevId(PakeAuthParams *params, const CJson *in)
{
if (params == NULL || in == NULL) {
LOGE("Input params is invalid.");
return HC_ERR_INVALID_PARAMS;
}
const char *devId = GetStringFromJson(in, FIELD_DEV_ID);
if (devId == NULL) {
LOGE("Get PeerDevId failed.");
return HC_ERR_JSON_GET;
}
uint32_t len = HcStrlen(devId);
// Peer devId type is hex string, no need to transfer.
if (InitCharStringBuff(&params->devIdPeer, len) != HC_SUCCESS) {
LOGE("InitCharStringBuff: idPeer failed.");
return HC_ERR_AUTH_INTERNAL;
}
if (memcpy_s(params->devIdPeer.val, params->devIdPeer.length, devId, len) != EOK) {
LOGE("Failed to copy devId.");
return HC_ERR_MEMORY_COPY;
}
return HC_SUCCESS;
}
int32_t GetPkInfoPeer(PakeAuthParams *params, const CJson *in)
{
if (params == NULL || in == NULL) {
LOGE("Input params is invalid.");
return HC_ERR_INVALID_PARAMS;
}
const char *pkInfoPeerStr = GetStringFromJson(in, FIELD_AUTH_PK_INFO);
if (pkInfoPeerStr == NULL) {
LOGE("Failed to get peer pkInfo string.");
return HC_ERR_JSON_GET;
}
uint32_t len = HcStrlen(pkInfoPeerStr) + 1;
if (InitSingleParam(&params->pkInfoPeer, len) != HC_SUCCESS) {
LOGE("Failed to malloc for peer pkInfo.");
return HC_ERR_ALLOC_MEMORY;
}
if (memcpy_s(params->pkInfoPeer.val, len, pkInfoPeerStr, len) != EOK) {
LOGE("GetPkInfoPeer: copy pkInfoPeer failed.");
HcFree(params->pkInfoPeer.val);
params->pkInfoPeer.val = NULL;
return HC_ERR_ALLOC_MEMORY;
}
CJson *info = CreateJsonFromString(pkInfoPeerStr);
if (info == NULL) {
LOGE("Failed to create json for peer pkInfo.");
HcFree(params->pkInfoPeer.val);
params->pkInfoPeer.val = NULL;
return HC_ERR_JSON_CREATE;
}
if (GetByteFromJson(info, FIELD_DEVICE_PK, params->pkPeer, PK_SIZE) != HC_SUCCESS) {
LOGE("Failed to get devicePk.");
FreeJson(info);
HcFree(params->pkInfoPeer.val);
params->pkInfoPeer.val = NULL;
return HC_ERR_JSON_GET;
}
FreeJson(info);
return HC_SUCCESS;
}
static int32_t GetAsyPubKeyInfo(PakeAuthParams *params)
{
AccountToken *token = CreateAccountToken();
if (token == NULL) {
LOGE("Failed to create token.");
return HC_ERR_ALLOC_MEMORY;
}
int32_t res = HC_ERR_GET_PK_INFO;
do {
if (GetAccountAuthTokenManager()->getToken(params->osAccountId, token,
(const char *)params->userIdSelf, (const char *)params->devIdSelf.val) != HC_SUCCESS) {
LOGE("Get token from local error.");
break;
}
uint32_t pkInfoLen = token->pkInfoStr.length;
if (pkInfoLen >= PUBLIC_KEY_INFO_SIZE) {
LOGE("Length of pkInfo from local is error.");
break;
}
if (InitSingleParam(&params->pkInfoSelf, pkInfoLen) != HC_SUCCESS) {
LOGE("InitSingleParam: pkInfoSelf failed.");
break;
}
if (memcpy_s(params->pkInfoSelf.val, params->pkInfoSelf.length, token->pkInfoStr.val, pkInfoLen) != EOK) {
LOGE("Copy pkInfoSelf failed.");
break;
}
if (memcpy_s(params->pkSelf, PK_SIZE, token->pkInfo.devicePk.val, token->pkInfo.devicePk.length) != EOK) {
LOGE("Copy pkSelf failed.");
break;
}
if (memcpy_s(params->pkInfoSignSelf.val, params->pkInfoSignSelf.length, token->pkInfoSignature.val,
token->pkInfoSignature.length) != EOK) {
LOGE("Copy pkInfoSignSelf failed.");
break;
}
params->pkInfoSignSelf.length = token->pkInfoSignature.length;
res = HC_SUCCESS;
} while (0);
DestroyAccountToken(token);
return res;
}
static int32_t FillUserIdForAuth(const CJson *in, PakeAuthParams *params)
{
const char *userIdSelf = GetStringFromJson(in, FIELD_SELF_USER_ID);
if (userIdSelf == NULL) {
LOGE("Failed to get self userId from input data.");
return HC_ERR_JSON_GET;
}
if (memcpy_s(params->userIdSelf, sizeof(params->userIdSelf), userIdSelf,
sizeof(params->userIdSelf)) != EOK) {
LOGE("Copy for userIdSelf failed.");
return HC_ERR_MEMORY_COPY;
}
return HC_SUCCESS;
}
int32_t InitPakeAuthParams(const CJson *in, PakeAuthParams *params, const AccountVersionInfo *verInfo)
{
if (in == NULL || params == NULL || verInfo == NULL) {
LOGE("Input params is NULL.");
return HC_ERR_INVALID_PARAMS;
}
const char *deviceId = GetStringFromJson(in, FIELD_SELF_DEVICE_ID);
if (deviceId == NULL) {
LOGE("Self deviceId is NULL.");
return HC_ERR_INVALID_PARAMS;
}
uint32_t deviceIdLen = HcStrlen(deviceId);
GOTO_IF_ERR(GetIntFromJson(in, FIELD_OS_ACCOUNT_ID, &params->osAccountId));
GOTO_IF_ERR(InitPakeV2BaseParams(&params->pakeParams));
GOTO_IF_ERR(InitSingleParam(&params->pakeParams.epkPeer, P256_PUBLIC_SIZE));
GOTO_IF_ERR(InitSingleParam(&params->pkInfoSignSelf, SIGNATURE_SIZE));
GOTO_IF_ERR(InitSingleParam(&params->pkInfoSignPeer, SIGNATURE_SIZE));
GOTO_IF_ERR(InitSingleParam(&params->pakeParams.idSelf, deviceIdLen + 1));
GOTO_IF_ERR(ExtractSelfDeviceId(params, in, true));
GOTO_IF_ERR(ExtractSelfDevId(params, in));
(void)memcpy_s(params->pakeParams.idSelf.val, deviceIdLen, deviceId, deviceIdLen);
params->pakeParams.idSelf.length = deviceIdLen;
GOTO_IF_ERR(FillUserIdForAuth(in, params));
GOTO_IF_ERR(GetBoolFromJson(in, FIELD_IS_CLIENT, &params->pakeParams.isClient));
GOTO_IF_ERR(GetAsyPubKeyInfo(params));
params->pakeParams.supportedPakeAlg = verInfo->pakeAlgType;
params->pakeParams.curveType = verInfo->curveType;
params->versionNo = verInfo->versionNo;
#ifdef ACCOUNT_PAKE_DL_PRIME_LEN_384
params->pakeParams.supportedDlPrimeMod = (uint32_t)params->pakeParams.supportedDlPrimeMod | DL_PRIME_MOD_384;
#endif
#ifdef ACCOUNT_PAKE_DL_PRIME_LEN_256
params->pakeParams.supportedDlPrimeMod = (uint32_t)params->pakeParams.supportedDlPrimeMod | DL_PRIME_MOD_256;
#endif
return HC_SUCCESS;
ERR:
LOGE("InitPakeAuthParams failed.");
return HC_ERR_AUTH_INTERNAL;
}
void DestroyPakeAuthParams(PakeAuthParams *params)
{
if (params == NULL) {
LOGE("Pointer is NULL.");
return;
}
(void)memset_s(params->userIdSelf, sizeof(params->userIdSelf), 0, sizeof(params->userIdSelf));
(void)memset_s(params->userIdPeer, sizeof(params->userIdPeer), 0, sizeof(params->userIdPeer));
(void)memset_s(params->pkSelf, sizeof(params->pkSelf), 0, sizeof(params->pkSelf));
(void)memset_s(params->pkPeer, sizeof(params->pkPeer), 0, sizeof(params->pkPeer));
(void)memset_s(params->pkInfoPeer.val, params->pkInfoPeer.length, 0, params->pkInfoPeer.length);
FreeUint8Buff(&params->pkInfoPeer);
FreeUint8Buff(&params->deviceIdPeer);
FreeUint8Buff(&params->devIdSelf);
FreeUint8Buff(&params->devIdPeer);
FreeUint8Buff(&params->pkInfoSelf);
FreeUint8Buff(&params->pkInfoSignPeer);
FreeUint8Buff(&params->pkInfoSignSelf);
DestroyPakeV2BaseParams(&params->pakeParams);
HcFree(params->deviceIdSelf.val);
params->deviceIdSelf.val = NULL;
/*
* Copyright (C) 2022 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 "pake_v2_auth_task_common.h"
#include <ctype.h>
#include "account_module.h"
#include "asy_token_manager.h"
#include "common_defs.h"
#include "device_auth_defines.h"
#include "hc_dev_info.h"
#include "hc_log.h"
#include "hc_types.h"
#include "pake_v2_protocol_common.h"
#include "pake_v2_auth_client_task.h"
#include "pake_v2_auth_server_task.h"
#include "protocol_common.h"
#include "string_util.h"
#define P256_SHARED_SECRET_KEY_SIZE 32
#define P256_PUBLIC_SIZE 64
#define P256_KEY_SIZE 32
#define SHARED_KEY_ALIAS "sharedKeyAlias"
bool IsPakeV2AuthTaskSupported(void)
{
return true;
}
TaskBase *CreatePakeV2AuthTask(const CJson *in, CJson *out, const AccountVersionInfo *verInfo)
{
bool isClient = false;
if (GetBoolFromJson(in, FIELD_IS_CLIENT, &isClient) != HC_SUCCESS) {
LOGD("Get isClient from json failed.");
isClient = false;
}
if (isClient) {
return CreatePakeV2AuthClientTask(in, out, verInfo);
}
return CreatePakeV2AuthServerTask(in, out, verInfo);
}
int32_t VerifyPkSignPeer(const PakeAuthParams *params)
{
uint8_t *serverPkAlias = (uint8_t *)HcMalloc(SHA256_LEN, 0);
if (serverPkAlias == NULL) {
LOGE("Failed to malloc for serverPk key alias.");
return HC_ERR_ALLOC_MEMORY;
}
Uint8Buff serverPkAliasBuff = {
.val = serverPkAlias,
.length = SHA256_LEN
};
int32_t res = GetAccountAuthTokenManager()->generateKeyAlias((const char *)(params->userIdSelf),
(const char *)params->devIdSelf.val, &serverPkAliasBuff, true);
if (res != HC_SUCCESS) {
HcFree(serverPkAlias);
return res;
}
Uint8Buff messageBuff = {
.val = params->pkInfoPeer.val,
.length = params->pkInfoPeer.length
};
Uint8Buff peerSignBuff = {
.val = params->pkInfoSignPeer.val,
.length = params->pkInfoSignPeer.length
};
res = params->pakeParams.loader->verify(&serverPkAliasBuff, &messageBuff, P256, &peerSignBuff, true);
HcFree(serverPkAlias);
if (res != HC_SUCCESS) {
LOGE("Verify pk sign failed.");
return HC_ERR_VERIFY_FAILED;
}
return HC_SUCCESS;
}
int32_t GenerateEcdhSharedKey(PakeAuthParams *params)
{
uint8_t *priAliasVal = (uint8_t *)HcMalloc(SHA256_LEN, 0);
if (priAliasVal == NULL) {
LOGE("Failed to malloc for self key alias.");
return HC_ERR_ALLOC_MEMORY;
}
Uint8Buff aliasBuff = {
.val = priAliasVal,
.length = SHA256_LEN
};
int32_t res = GetAccountAuthTokenManager()->generateKeyAlias((const char *)(params->userIdSelf),
(const char *)params->devIdSelf.val, &aliasBuff, false);
if (res != HC_SUCCESS) {
HcFree(priAliasVal);
return res;
}
KeyBuff priAliasKeyBuff = {
.key = aliasBuff.val,
.keyLen = aliasBuff.length,
.isAlias = true
};
KeyBuff publicKeyBuff = {
.key = params->pkPeer,
.keyLen = sizeof(params->pkPeer),
.isAlias = false
};
uint32_t sharedKeyAliasLen = HcStrlen(SHARED_KEY_ALIAS) + 1;
params->pakeParams.psk.val = (uint8_t *)HcMalloc(sharedKeyAliasLen, 0);
if (params->pakeParams.psk.val == NULL) {
LOGE("Failed to malloc for psk alias.");
HcFree(priAliasVal);
return HC_ERR_ALLOC_MEMORY;
}
params->pakeParams.psk.length = sharedKeyAliasLen;
(void)memcpy_s(params->pakeParams.psk.val, sharedKeyAliasLen, SHARED_KEY_ALIAS, sharedKeyAliasLen);
res = params->pakeParams.loader->agreeSharedSecretWithStorage(&priAliasKeyBuff, &publicKeyBuff,
P256, P256_SHARED_SECRET_KEY_SIZE, &(params->pakeParams.psk));
HcFree(priAliasVal);
return res;
}
static int32_t InitCharStringBuff(Uint8Buff *param, uint32_t len)
{
if (param == NULL || len <= 0) {
LOGE("param is invalid for init.");
return HC_ERR_NULL_PTR;
}
if (InitSingleParam(param, len + 1) != HC_SUCCESS) {
return HC_ERR_ALLOC_MEMORY;
}
param->length = len;
return HC_SUCCESS;
}
int32_t ExtractPakePeerId(PakeAuthParams *params, const CJson *in)
{
if (params == NULL || in == NULL) {
LOGE("Input params is invalid.");
return HC_ERR_INVALID_PARAMS;
}
uint32_t deviceIdPeerLen = HcStrlen((const char *)params->deviceIdPeer.val);
if (InitCharStringBuff(&params->pakeParams.idPeer,
params->devIdPeer.length + deviceIdPeerLen) != HC_SUCCESS) {
LOGE("InitCharStringBuff: idPeer failed.");
return HC_ERR_AUTH_INTERNAL;
}
(void)memcpy_s(params->pakeParams.idPeer.val, params->pakeParams.idPeer.length, params->devIdPeer.val,
params->devIdPeer.length);
(void)memcpy_s(params->pakeParams.idPeer.val + params->devIdPeer.length,
params->pakeParams.idPeer.length - params->devIdPeer.length, params->deviceIdPeer.val, deviceIdPeerLen);
return HC_SUCCESS;
}
int32_t ExtractPakeSelfId(PakeAuthParams *params)
{
if (params == NULL) {
LOGE("Input params NULL.");
return HC_ERR_INVALID_PARAMS;
}
uint32_t deviceIdSelfLen = HcStrlen((const char *)params->deviceIdSelf.val);
if (InitCharStringBuff(&params->pakeParams.idSelf,
params->devIdSelf.length + deviceIdSelfLen) != HC_SUCCESS) {
LOGE("InitCharStringBuff: idSelf failed.");
return HC_ERR_AUTH_INTERNAL;
}
(void)memcpy_s(params->pakeParams.idSelf.val, params->pakeParams.idSelf.length, params->devIdSelf.val,
params->devIdSelf.length);
(void)memcpy_s(params->pakeParams.idSelf.val + params->devIdSelf.length,
params->pakeParams.idSelf.length - params->devIdSelf.length, params->deviceIdSelf.val, deviceIdSelfLen);
return HC_SUCCESS;
}
static int32_t ExtractSelfDeviceId(PakeAuthParams *params, const CJson *in, bool useSelfPrefix)
{
if (params == NULL || in == NULL) {
LOGE("Input params NULL.");
return HC_ERR_INVALID_PARAMS;
}
const char *deviceId = NULL;
if (useSelfPrefix) {
deviceId = GetStringFromJson(in, FIELD_SELF_DEVICE_ID);
} else {
deviceId = GetStringFromJson(in, FIELD_DEVICE_ID);
}
if (deviceId == NULL) {
LOGE("Get selfDeviceId from json failed.");
return HC_ERR_JSON_GET;
}
params->deviceIdSelf.length = HcStrlen(deviceId);
params->deviceIdSelf.val = (uint8_t *)HcMalloc(params->deviceIdSelf.length + 1, 0);
if (params->deviceIdSelf.val == NULL) {
LOGE("Failed to malloc for deviceIdSelf.");
return HC_ERR_ALLOC_MEMORY;
}
if (memcpy_s(params->deviceIdSelf.val, params->deviceIdSelf.length + 1,
deviceId, params->deviceIdSelf.length) != EOK) {
LOGE("Memcpy_s for deviceIdSelf failed.");
return HC_ERR_MEMORY_COPY;
}
return HC_SUCCESS;
}
int32_t ExtractPeerDeviceId(PakeAuthParams *params, const CJson *in)
{
if (params == NULL || in == NULL) {
LOGE("Input params NULL.");
return HC_ERR_INVALID_PARAMS;
}
const char *deviceId = GetStringFromJson(in, FIELD_DEVICE_ID);
if (deviceId == NULL) {
LOGE("Get peer deviceId failed.");
return HC_ERR_JSON_GET;
}
uint32_t len = HcStrlen(deviceId);
if (InitCharStringBuff(&params->deviceIdPeer, len) != HC_SUCCESS) {
LOGE("InitCharStringBuff: deviceIdPeer failed.");
return HC_ERR_AUTH_INTERNAL;
}
if (memcpy_s(params->deviceIdPeer.val, params->deviceIdPeer.length + 1, deviceId, len) != EOK) {
LOGE("memcpy_s deviceId failed.");
return HC_ERR_MEMORY_COPY;
}
for (uint32_t i = 0; i < params->deviceIdPeer.length; i++) {
// Change a - f charactor to upper charactor.
if (params->deviceIdPeer.val[i] >= 'a' && params->deviceIdPeer.val[i] <= 'f') {
params->deviceIdPeer.val[i] = (uint8_t)toupper(params->deviceIdPeer.val[i]);
}
}
return HC_SUCCESS;
}
static int32_t ExtractSelfDevId(PakeAuthParams *params, const CJson *in)
{
if (params == NULL || in == NULL) {
LOGE("Input params is invalid.");
return HC_ERR_INVALID_PARAMS;
}
const char *devIdSelf = GetStringFromJson(in, FIELD_SELF_DEV_ID);
if (devIdSelf == NULL) {
LOGE("Get devIdSelf failed.");
return HC_ERR_JSON_GET;
}
params->devIdSelf.length = HcStrlen(devIdSelf);
params->devIdSelf.val = (uint8_t *)HcMalloc(params->devIdSelf.length + 1, 0);
if (params->devIdSelf.val == NULL) {
LOGE("Malloc for devIdSelf failed.");
return HC_ERR_ALLOC_MEMORY;
}
if (memcpy_s(params->devIdSelf.val, params->devIdSelf.length, devIdSelf,
params->devIdSelf.length) != EOK) {
LOGE("Copy for self devId failed.");
return HC_ERR_MEMORY_COPY;
}
return HC_SUCCESS;
}
int32_t ExtractPeerDevId(PakeAuthParams *params, const CJson *in)
{
if (params == NULL || in == NULL) {
LOGE("Input params is invalid.");
return HC_ERR_INVALID_PARAMS;
}
const char *devId = GetStringFromJson(in, FIELD_DEV_ID);
if (devId == NULL) {
LOGE("Get PeerDevId failed.");
return HC_ERR_JSON_GET;
}
uint32_t len = HcStrlen(devId);
// Peer devId type is hex string, no need to transfer.
if (InitCharStringBuff(&params->devIdPeer, len) != HC_SUCCESS) {
LOGE("InitCharStringBuff: idPeer failed.");
return HC_ERR_AUTH_INTERNAL;
}
if (memcpy_s(params->devIdPeer.val, params->devIdPeer.length, devId, len) != EOK) {
LOGE("Failed to copy devId.");
return HC_ERR_MEMORY_COPY;
}
return HC_SUCCESS;
}
int32_t GetPkInfoPeer(PakeAuthParams *params, const CJson *in)
{
if (params == NULL || in == NULL) {
LOGE("Input params is invalid.");
return HC_ERR_INVALID_PARAMS;
}
const char *pkInfoPeerStr = GetStringFromJson(in, FIELD_AUTH_PK_INFO);
if (pkInfoPeerStr == NULL) {
LOGE("Failed to get peer pkInfo string.");
return HC_ERR_JSON_GET;
}
uint32_t len = HcStrlen(pkInfoPeerStr) + 1;
if (InitSingleParam(&params->pkInfoPeer, len) != HC_SUCCESS) {
LOGE("Failed to malloc for peer pkInfo.");
return HC_ERR_ALLOC_MEMORY;
}
if (memcpy_s(params->pkInfoPeer.val, len, pkInfoPeerStr, len) != EOK) {
LOGE("GetPkInfoPeer: copy pkInfoPeer failed.");
HcFree(params->pkInfoPeer.val);
params->pkInfoPeer.val = NULL;
return HC_ERR_ALLOC_MEMORY;
}
CJson *info = CreateJsonFromString(pkInfoPeerStr);
if (info == NULL) {
LOGE("Failed to create json for peer pkInfo.");
HcFree(params->pkInfoPeer.val);
params->pkInfoPeer.val = NULL;
return HC_ERR_JSON_CREATE;
}
if (GetByteFromJson(info, FIELD_DEVICE_PK, params->pkPeer, PK_SIZE) != HC_SUCCESS) {
LOGE("Failed to get devicePk.");
FreeJson(info);
HcFree(params->pkInfoPeer.val);
params->pkInfoPeer.val = NULL;
return HC_ERR_JSON_GET;
}
FreeJson(info);
return HC_SUCCESS;
}
static int32_t GetAsyPubKeyInfo(PakeAuthParams *params)
{
AccountToken *token = CreateAccountToken();
if (token == NULL) {
LOGE("Failed to create token.");
return HC_ERR_ALLOC_MEMORY;
}
int32_t res = HC_ERR_GET_PK_INFO;
do {
if (GetAccountAuthTokenManager()->getToken(params->osAccountId, token,
(const char *)params->userIdSelf, (const char *)params->devIdSelf.val) != HC_SUCCESS) {
LOGE("Get token from local error.");
break;
}
uint32_t pkInfoLen = token->pkInfoStr.length;
if (pkInfoLen >= PUBLIC_KEY_INFO_SIZE) {
LOGE("Length of pkInfo from local is error.");
break;
}
if (InitSingleParam(&params->pkInfoSelf, pkInfoLen) != HC_SUCCESS) {
LOGE("InitSingleParam: pkInfoSelf failed.");
break;
}
if (memcpy_s(params->pkInfoSelf.val, params->pkInfoSelf.length, token->pkInfoStr.val, pkInfoLen) != EOK) {
LOGE("Copy pkInfoSelf failed.");
break;
}
if (memcpy_s(params->pkSelf, PK_SIZE, token->pkInfo.devicePk.val, token->pkInfo.devicePk.length) != EOK) {
LOGE("Copy pkSelf failed.");
break;
}
if (memcpy_s(params->pkInfoSignSelf.val, params->pkInfoSignSelf.length, token->pkInfoSignature.val,
token->pkInfoSignature.length) != EOK) {
LOGE("Copy pkInfoSignSelf failed.");
break;
}
params->pkInfoSignSelf.length = token->pkInfoSignature.length;
res = HC_SUCCESS;
} while (0);
DestroyAccountToken(token);
return res;
}
static int32_t FillUserIdForAuth(const CJson *in, PakeAuthParams *params)
{
const char *userIdSelf = GetStringFromJson(in, FIELD_SELF_USER_ID);
if (userIdSelf == NULL) {
LOGE("Failed to get self userId from input data.");
return HC_ERR_JSON_GET;
}
if (memcpy_s(params->userIdSelf, sizeof(params->userIdSelf), userIdSelf,
sizeof(params->userIdSelf)) != EOK) {
LOGE("Copy for userIdSelf failed.");
return HC_ERR_MEMORY_COPY;
}
return HC_SUCCESS;
}
int32_t InitPakeAuthParams(const CJson *in, PakeAuthParams *params, const AccountVersionInfo *verInfo)
{
if (in == NULL || params == NULL || verInfo == NULL) {
LOGE("Input params is NULL.");
return HC_ERR_INVALID_PARAMS;
}
const char *deviceId = GetStringFromJson(in, FIELD_SELF_DEVICE_ID);
if (deviceId == NULL) {
LOGE("Self deviceId is NULL.");
return HC_ERR_INVALID_PARAMS;
}
uint32_t deviceIdLen = HcStrlen(deviceId);
GOTO_IF_ERR(GetIntFromJson(in, FIELD_OS_ACCOUNT_ID, &params->osAccountId));
GOTO_IF_ERR(InitPakeV2BaseParams(&params->pakeParams));
GOTO_IF_ERR(InitSingleParam(&params->pakeParams.epkPeer, P256_PUBLIC_SIZE));
GOTO_IF_ERR(InitSingleParam(&params->pkInfoSignSelf, SIGNATURE_SIZE));
GOTO_IF_ERR(InitSingleParam(&params->pkInfoSignPeer, SIGNATURE_SIZE));
GOTO_IF_ERR(InitSingleParam(&params->pakeParams.idSelf, deviceIdLen + 1));
GOTO_IF_ERR(ExtractSelfDeviceId(params, in, true));
GOTO_IF_ERR(ExtractSelfDevId(params, in));
(void)memcpy_s(params->pakeParams.idSelf.val, deviceIdLen, deviceId, deviceIdLen);
params->pakeParams.idSelf.length = deviceIdLen;
GOTO_IF_ERR(FillUserIdForAuth(in, params));
GOTO_IF_ERR(GetBoolFromJson(in, FIELD_IS_CLIENT, &params->pakeParams.isClient));
GOTO_IF_ERR(GetAsyPubKeyInfo(params));
params->pakeParams.supportedPakeAlg = verInfo->pakeAlgType;
params->pakeParams.curveType = verInfo->curveType;
params->versionNo = verInfo->versionNo;
#ifdef ACCOUNT_PAKE_DL_PRIME_LEN_384
params->pakeParams.supportedDlPrimeMod = (uint32_t)params->pakeParams.supportedDlPrimeMod | DL_PRIME_MOD_384;
#endif
#ifdef ACCOUNT_PAKE_DL_PRIME_LEN_256
params->pakeParams.supportedDlPrimeMod = (uint32_t)params->pakeParams.supportedDlPrimeMod | DL_PRIME_MOD_256;
#endif
return HC_SUCCESS;
ERR:
LOGE("InitPakeAuthParams failed.");
return HC_ERR_AUTH_INTERNAL;
}
void DestroyPakeAuthParams(PakeAuthParams *params)
{
if (params == NULL) {
LOGE("Pointer is NULL.");
return;
}
(void)memset_s(params->userIdSelf, sizeof(params->userIdSelf), 0, sizeof(params->userIdSelf));
(void)memset_s(params->userIdPeer, sizeof(params->userIdPeer), 0, sizeof(params->userIdPeer));
(void)memset_s(params->pkSelf, sizeof(params->pkSelf), 0, sizeof(params->pkSelf));
(void)memset_s(params->pkPeer, sizeof(params->pkPeer), 0, sizeof(params->pkPeer));
(void)memset_s(params->pkInfoPeer.val, params->pkInfoPeer.length, 0, params->pkInfoPeer.length);
FreeUint8Buff(&params->pkInfoPeer);
FreeUint8Buff(&params->deviceIdPeer);
FreeUint8Buff(&params->devIdSelf);
FreeUint8Buff(&params->devIdPeer);
FreeUint8Buff(&params->pkInfoSelf);
FreeUint8Buff(&params->pkInfoSignPeer);
FreeUint8Buff(&params->pkInfoSignSelf);
DestroyPakeV2BaseParams(&params->pakeParams);
HcFree(params->deviceIdSelf.val);
params->deviceIdSelf.val = NULL;
}
@@ -22,26 +22,9 @@
#include "protocol_common.h"
#include "string_util.h"
#define KEY_TYPE_PAIR_LEN 2
#define PACKAGE_NAME_MAX_LEN 256
#define SERVICE_TYPE_MAX_LEN 256
#define AUTH_ID_MAX_LEN 64
#define MESSAGE_RETURN 0x8000
#define MESSAGE_PREFIX 0x0010
/* in order to expand to uint16_t */
static const uint8_t KEY_TYPE_PAIRS[KEY_ALIAS_TYPE_END][KEY_TYPE_PAIR_LEN] = {
{ 0x00, 0x00 }, /* ACCESSOR_PK */
{ 0x00, 0x01 }, /* CONTROLLER_PK */
{ 0x00, 0x02 }, /* ed25519 KEYPAIR */
{ 0x00, 0x03 }, /* KEK, key encryption key, used only by DeviceAuthService */
{ 0x00, 0x04 }, /* DEK, data encryption key, used only by upper apps */
{ 0x00, 0x05 }, /* key tmp */
{ 0x00, 0x06 }, /* PSK, preshared key index */
{ 0x00, 0x07 } /* AUTHTOKEN */
};
void DasSendErrorToOut(CJson *out, int errCode)
{
CJson *sendToSelf = CreateJson();
@@ -331,7 +314,7 @@ int32_t GenerateKeyAlias(const Uint8Buff *pkgName, const Uint8Buff *serviceType,
LOGE("CombineServiceId failed, res: %x.", res);
goto ERR;
}
Uint8Buff keyTypeBuff = { (uint8_t *)KEY_TYPE_PAIRS[keyType], KEY_TYPE_PAIR_LEN };
Uint8Buff keyTypeBuff = { GetKeyTypePair(keyType), KEY_TYPE_PAIR_LEN };
if (keyType == KEY_ALIAS_AUTH_TOKEN) {
res = CombineKeyAliasForIso(&serviceId, &keyTypeBuff, authId, outKeyAlias);
} else {

Some files were not shown because too many files have changed in this diff Show More