!122 change function name

Merge pull request !122 from 符子坤/master

Signed-off-by: ailu1 <jinyanhong1@huawei.com>
This commit is contained in:
openharmony_ci
2021-12-20 08:11:28 +00:00
committed by ailu1
131 changed files with 3132 additions and 2947 deletions
+121 -2
View File
@@ -14,6 +14,8 @@
*/
#include "string_util.h"
#include <stdbool.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <securec.h>
@@ -23,6 +25,21 @@
#define OUT_OF_HEX 16
#define NUMBER_9_IN_DECIMAL 9
#define ASCII_CASE_DIFFERENCE_VALUE 32
#define DESENSITIZATION_LEN 4
static const char * const g_base64CharacterTable =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
static const uint8_t g_base64DecodeTable[] = {
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 62, 0, 0, 0, 63,
52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 0, 0, 0, 0, 0, 0,
0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 0, 0, 0, 0, 0,
0, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51
};
static char HexToChar(uint8_t hex)
{
@@ -97,7 +114,7 @@ void ConvertToAnonymousStr(const char *originalStr, char **anonymousStr)
if ((originalStr == NULL) || (anonymousStr == NULL)) {
return;
}
uint32_t desensitizationLen = 4;
uint32_t desensitizationLen = DESENSITIZATION_LEN;
uint32_t len = strlen(originalStr);
if (len <= desensitizationLen) {
return;
@@ -118,10 +135,112 @@ void ConvertToAnonymousStr(const char *originalStr, char **anonymousStr)
}
}
static bool IsInvalidBase64Character(char c)
{
if (('A' <= c && c <= 'Z') || ('a' <= c && c <= 'z')) {
return false;
}
if ('0' <= c && c <= '9') {
return false;
}
if (c == '+' || c == '/') {
return false;
}
return true;
}
int32_t Base64StringToByte(const char *base64Str, uint8_t *byte, uint32_t *byteLen)
{
if (base64Str == NULL || byte == NULL || byteLen == NULL) {
return CLIB_ERR_NULL_PTR;
}
uint32_t strLen = strlen(base64Str);
if (strLen < BYTE_TO_BASE64_MULTIPLIER) {
return CLIB_ERR_INVALID_LEN;
}
uint32_t len = strLen / BYTE_TO_BASE64_MULTIPLIER * BYTE_TO_BASE64_DIVISOR;
int j = 0;
for (int i = 0; i < 2; i++) { // at most two end fillings '='
if (base64Str[strLen - 1 - i] == '=') {
j++;
}
}
if (len - j > (*byteLen)) {
return CLIB_ERR_INVALID_LEN;
}
*byteLen = len - j;
// 6 bits each character(first 2 bits pad 0), 4 characters as a group to decode
if (IsInvalidBase64Character(base64Str[0]) || IsInvalidBase64Character(base64Str[1]) ||
IsInvalidBase64Character(base64Str[2])) {
return CLIB_ERR_INVALID_PARAM;
}
for (uint32_t i = 0, j = 0; i < strLen - 2; j += 3, i += 4) {
if (IsInvalidBase64Character(base64Str[i + 3]) && i + 3 < strLen - j) {
return CLIB_ERR_INVALID_PARAM;
}
/* splice the last 6 bits of the first character's value and the first 2 bits of the second character's value */
byte[j] = (g_base64DecodeTable[(int)base64Str[i]] << 2) | (g_base64DecodeTable[(int)base64Str[i + 1]] >> 4);
/* splice the last 4 bits of the second character's value and the first 4 bits of the third character's value */
byte[j + 1] = (g_base64DecodeTable[(int)base64Str[i + 1]] << 4) |
(g_base64DecodeTable[(int)base64Str[i + 2]] >> 2);
/* splice the last 2 bits of the third character's value and the first 6 bits of the forth character's value */
byte[j + 2] = (g_base64DecodeTable[(int)base64Str[i + 2]] << 6) | (g_base64DecodeTable[(int)base64Str[i + 3]]);
}
return CLIB_SUCCESS;
}
int32_t ByteToBase64String(const uint8_t *byte, uint32_t byteLen, char *base64Str, uint32_t strLen)
{
if (byte == NULL || base64Str == NULL) {
return CLIB_ERR_NULL_PTR;
}
if (byteLen > (UINT32_MAX / BYTE_TO_BASE64_MULTIPLIER - 1) * BYTE_TO_BASE64_DIVISOR) {
return CLIB_ERR_INVALID_LEN;
}
uint32_t len = (byteLen / BYTE_TO_BASE64_DIVISOR + (byteLen % BYTE_TO_BASE64_DIVISOR != 0)) *
BYTE_TO_BASE64_MULTIPLIER;
if (len + 1 > strLen) {
return CLIB_ERR_INVALID_LEN;
}
uint32_t i;
uint32_t j;
// 3 bytes as a group to encode
for (i = 0, j = 0; i < len - 2; j += 3, i += 4) {
/* take the first 6 bits of the first byte to map to base64 character */
base64Str[i] = g_base64CharacterTable[byte[j] >> 2];
/*
* splice the last 2 bits of the first byte and the first 4 bits of the second byte,
* and map to base64 character
*/
base64Str[i + 1] = g_base64CharacterTable[((byte[j] & 0x3) << 4) | (byte[j + 1] >> 4)];
/*
* splice the last 4 bits of the second byte and the first 2 bits of the third byte,
* and map to base64 character
*/
base64Str[i + 2] = g_base64CharacterTable[((byte[j + 1] & 0xf) << 2) | (byte[j + 2] >> 6)];
/* take the last 6 bits of the third byte to map to base64 character */
base64Str[i + 3] = g_base64CharacterTable[byte[j + 2] & 0x3f];
}
// the lack of position fills '='
if (byteLen % 3 == 1) {
base64Str[i - 2] = '=';
base64Str[i - 1] = '=';
}
if (byteLen % 3 == 2) {
base64Str[i - 1] = '=';
}
base64Str[len] = '\0';
return CLIB_SUCCESS;
}
int32_t ToUpperCase(const char *oriStr, char **desStr)
{
if (oriStr == NULL || desStr == NULL) {
return CLIB_ERR_INVALID_PARAM;
return CLIB_ERR_NULL_PTR;
}
*desStr = ClibMalloc(strlen(oriStr) + 1, 0);
if (*desStr == NULL) {
+24 -3
View File
@@ -19,6 +19,8 @@
#include <stdint.h>
#define BYTE_TO_HEX_OPER_LENGTH 2
#define BYTE_TO_BASE64_DIVISOR 3
#define BYTE_TO_BASE64_MULTIPLIER 4
#define DEC 10
typedef struct {
@@ -34,7 +36,7 @@ extern "C" {
* Convert hex string to byte.
* @param hexStr: hex string
* @param byte: the converted result, need malloc by caller
* @param byteLen: the length of byte
* @param byteLen: the length of byte, must be not shorter than strlen(hexStr) / 2
* @result success(0), otherwise, failure.
*/
int32_t HexStringToByte(const char *hexStr, uint8_t *byte, uint32_t byteLen);
@@ -44,12 +46,11 @@ int32_t HexStringToByte(const char *hexStr, uint8_t *byte, uint32_t byteLen);
* @param byte: byte to be converted
* @param byteLen: the length of byte
* @param hexStr: the converted result, need malloc by caller, and need malloc for '\0'
* @param hexLen: strlen(hexStr) + 1, for '\0'
* @param hexLen: length of hexStr, must be not shorter than byteLen * 2 + 1, for '\0'
* @result success(0), otherwise, failure.
*/
int32_t ByteToHexString(const uint8_t *byte, uint32_t byteLen, char *hexStr, uint32_t hexLen);
/*
* Convert string to int64_t.
* @param cp: string to be converted
@@ -64,6 +65,26 @@ int64_t StringToInt64(const char *cp);
*/
void ConvertToAnonymousStr(const char *originalStr, char **anonymousStr);
/*
* Convert base64 string to byte.
* @param base64Str: base64 string
* @param byte: the converted result, need malloc by caller
* @param byteLen: the length of byte, must be not shorter than strlen(base64Str) / 4 * 3,
* and update it to the real length of the result written
* @result success(0), otherwise, failure.
*/
int32_t Base64StringToByte(const char *base64Str, uint8_t *byte, uint32_t *byteLen);
/*
* Convert byte to base64 string.
* @param byte: byte to be converted
* @param byteLen: the length of byte
* @param base64Str: the converted result, need malloc by caller, and need malloc for '\0'
* @param strLen: length of base64Str, must be not shorter than (byteLen / 3 + (byteLen % 3 != 0)) * 4 + 1, with '\0'
* @result success(0), otherwise, failure.
*/
int32_t ByteToBase64String(const uint8_t *byte, uint32_t byteLen, char *base64Str, uint32_t strLen);
/*
* Convert string to upper case.
* @param oriStr: original string.
@@ -17,11 +17,20 @@
#include "hal_error.h"
#include "hc_file.h"
#include "hc_log.h"
#include "hc_types.h"
#include "hks_api.h"
#include "hks_param.h"
#include "hks_type.h"
#include "string_util.h"
#define BASE_IMPORT_PARAMS_LEN 7
#define EXT_IMPORT_PARAMS_LEN 2
static enum HksKeyPurpose g_purposeToHksKeyPurpose[] = {
HKS_KEY_PURPOSE_MAC,
HKS_KEY_PURPOSE_DERIVE
};
static int32_t BaseCheckParams(const Uint8Buff **inParams, const char **paramTags, uint32_t len)
{
for (uint32_t i = 0; i < len; i++) {
@@ -60,7 +69,7 @@ static int32_t ConstructParamSet(struct HksParamSet **out, const struct HksParam
return HAL_SUCCESS;
}
static int32_t InitHks()
static int32_t InitHks(void)
{
int32_t res = HksInitialize();
if (res == HKS_SUCCESS) {
@@ -429,90 +438,89 @@ static int32_t AesGcmDecrypt(const Uint8Buff *key, const Uint8Buff *cipher,
return HAL_SUCCESS;
}
static int32_t CheckImportAsymmetricKeyParam(const Uint8Buff *keyAlias, const Uint8Buff *authToken,
const Uint8Buff *authId, const int32_t userType, const int32_t pairType)
static int32_t CheckImportSymmetricKeyParam(const Uint8Buff *keyAlias, const Uint8Buff *authToken)
{
const Uint8Buff *inParams[] = { keyAlias, authToken, authId };
const char *paramTags[] = { "keyAlias", "authToken", "authId" };
int32_t ret = BaseCheckParams(inParams, paramTags, CAL_ARRAY_SIZE(inParams));
if (ret != HAL_SUCCESS) {
return ret;
}
CHECK_LEN_HIGHER_RETURN(pairType, PAIR_TYPE_END - 1, "pairType");
return HAL_SUCCESS;
const Uint8Buff *inParams[] = { keyAlias, authToken };
const char *paramTags[] = { "keyAlias", "authToken" };
return BaseCheckParams(inParams, paramTags, CAL_ARRAY_SIZE(inParams));
}
static int32_t ConstructImportAsymmetricKeyParam(struct HksParamSet **paramSet, uint32_t keyLen, uint32_t roleInfo,
const struct HksBlob *authIdBlob)
static int32_t ConstructImportSymmetricKeyParam(struct HksParamSet **paramSet, uint32_t keyLen, KeyPurpose purpose,
const ExtraInfo *exInfo)
{
struct HksParam importParam[] = {
{
.tag = HKS_TAG_ALGORITHM,
.uint32Param = HKS_ALG_AES
}, {
.tag = HKS_TAG_KEY_SIZE,
.uint32Param = keyLen * BITS_PER_BYTE
}, {
.tag = HKS_TAG_PADDING,
.uint32Param = HKS_PADDING_NONE
}, {
.tag = HKS_TAG_KEY_AUTH_ID,
.blob = *authIdBlob
}, {
.tag = HKS_TAG_IS_ALLOWED_WRAP,
.boolParam = false
}, {
.tag = HKS_TAG_PURPOSE,
.uint32Param = HKS_KEY_PURPOSE_MAC
}, {
.tag = HKS_TAG_KEY_ROLE,
.uint32Param = roleInfo
}, {
.tag = HKS_TAG_BLOCK_MODE,
.uint32Param = HKS_MODE_GCM
}, {
.tag = HKS_TAG_DIGEST,
.uint32Param = HKS_DIGEST_SHA256
struct HksParam *importParam = NULL;
struct HksBlob authIdBlob = { 0, NULL };
union KeyRoleInfoUnion roleInfoUnion;
(void)memset_s(&roleInfoUnion, sizeof(roleInfoUnion), 0, sizeof(roleInfoUnion));
uint32_t idx = 0;
if (exInfo != NULL) {
CHECK_PTR_RETURN_HAL_ERROR_CODE(exInfo->authId.val, "authId");
CHECK_LEN_ZERO_RETURN_ERROR_CODE(exInfo->authId.length, "authId");
CHECK_LEN_HIGHER_RETURN(exInfo->pairType, PAIR_TYPE_END - 1, "pairType");
importParam = (struct HksParam *)HcMalloc(sizeof(struct HksParam) *
(BASE_IMPORT_PARAMS_LEN + EXT_IMPORT_PARAMS_LEN), 0);
if (importParam == NULL) {
LOGE("Malloc for importParam failed.");
return HAL_ERR_BAD_ALLOC;
}
authIdBlob.size = exInfo->authId.length;
authIdBlob.data = exInfo->authId.val;
roleInfoUnion.roleInfoStruct.userType = (uint8_t)exInfo->userType;
roleInfoUnion.roleInfoStruct.pairType = (uint8_t)exInfo->pairType;
importParam[idx].tag = HKS_TAG_KEY_AUTH_ID;
importParam[idx++].blob = authIdBlob;
importParam[idx].tag = HKS_TAG_KEY_ROLE;
importParam[idx++].uint32Param = roleInfoUnion.roleInfo;
} else {
importParam = (struct HksParam *)HcMalloc(sizeof(struct HksParam) * BASE_IMPORT_PARAMS_LEN, 0);
if (importParam == NULL) {
LOGE("Malloc for importParam failed.");
return HAL_ERR_BAD_ALLOC;
}
};
int ret = ConstructParamSet(paramSet, importParam, CAL_ARRAY_SIZE(importParam));
if (ret != HAL_SUCCESS) {
LOGE("construct decrypt param set failed, ret = %d", ret);
return ret;
}
importParam[idx].tag = HKS_TAG_ALGORITHM;
importParam[idx++].uint32Param = HKS_ALG_AES;
importParam[idx].tag = HKS_TAG_KEY_SIZE;
importParam[idx++].uint32Param = keyLen * BITS_PER_BYTE;
importParam[idx].tag = HKS_TAG_PADDING;
importParam[idx++].uint32Param = HKS_PADDING_NONE;
importParam[idx].tag = HKS_TAG_IS_ALLOWED_WRAP;
importParam[idx++].boolParam = false;
importParam[idx].tag = HKS_TAG_PURPOSE;
importParam[idx++].uint32Param = g_purposeToHksKeyPurpose[purpose];
importParam[idx].tag = HKS_TAG_BLOCK_MODE;
importParam[idx++].uint32Param = HKS_MODE_GCM;
importParam[idx].tag = HKS_TAG_DIGEST;
importParam[idx++].uint32Param = HKS_DIGEST_SHA256;
int ret = ConstructParamSet(paramSet, importParam, idx);
if (ret != HAL_SUCCESS) {
LOGE("Construct decrypt param set failed, ret = %d.", ret);
}
HcFree(importParam);
return ret;
}
static int32_t ImportAsymmetricKey(const Uint8Buff *keyAlias, const Uint8Buff *authToken, const ExtraInfo *exInfo)
static int32_t ImportSymmetricKey(const Uint8Buff *keyAlias, const Uint8Buff *authToken, KeyPurpose purpose,
const ExtraInfo *exInfo)
{
int32_t ret = CheckImportAsymmetricKeyParam(keyAlias, authToken, &exInfo->authId, exInfo->userType,
exInfo->pairType);
int32_t ret = CheckImportSymmetricKeyParam(keyAlias, authToken);
if (ret != HAL_SUCCESS) {
return ret;
}
struct HksBlob keyAliasBlob = { keyAlias->length, keyAlias->val };
struct HksBlob pubKeyBlob = { authToken->length, authToken->val };
struct HksBlob authIdBlob = { exInfo->authId.length, exInfo->authId.val };
union KeyRoleInfoUnion roleInfoUnion;
roleInfoUnion.roleInfoStruct.userType = (uint8_t)exInfo->userType;
roleInfoUnion.roleInfoStruct.pairType = (uint8_t)exInfo->pairType;
roleInfoUnion.roleInfoStruct.reserved1 = (uint8_t)0;
roleInfoUnion.roleInfoStruct.reserved2 = (uint8_t)0;
struct HksBlob symKeyBlob = { authToken->length, authToken->val };
struct HksParamSet *paramSet = NULL;
ret = ConstructImportAsymmetricKeyParam(&paramSet, authToken->length, roleInfoUnion.roleInfo, &authIdBlob);
ret = ConstructImportSymmetricKeyParam(&paramSet, authToken->length, purpose, exInfo);
if (ret != HAL_SUCCESS) {
LOGE("construct param set failed, ret = %d", ret);
return ret;
}
ret = HksImportKey(&keyAliasBlob, paramSet, &pubKeyBlob);
ret = HksImportKey(&keyAliasBlob, paramSet, &symKeyBlob);
if (ret != HKS_SUCCESS) {
LOGE("HksImportKey failed, ret: %d", ret);
HksFreeParamSet(&paramSet);
@@ -523,29 +531,180 @@ static int32_t ImportAsymmetricKey(const Uint8Buff *keyAlias, const Uint8Buff *a
return HAL_SUCCESS;
}
static int32_t BigNumExpMod(const Uint8Buff *base, const Uint8Buff *exp, const char *bigNumHex, Uint8Buff *outNum)
{
const Uint8Buff *inParams[] = { base, exp, outNum };
const char *paramTags[] = { "base", "exp", "outNum" };
int32_t ret = BaseCheckParams(inParams, paramTags, CAL_ARRAY_SIZE(inParams));
if (ret != HAL_SUCCESS) {
return ret;
}
CHECK_PTR_RETURN_HAL_ERROR_CODE(bigNumHex, "bigNumHex");
uint32_t primeLen = strlen(bigNumHex) / BYTE_TO_HEX_OPER_LENGTH;
if ((primeLen != BIG_PRIME_LEN_384) && (primeLen != BIG_PRIME_LEN_256)) {
LOGE("Not support big number len %d", outNum->length);
return HAL_FAILED;
}
CHECK_LEN_EQUAL_RETURN(outNum->length, primeLen, "outNum->length");
struct HksBlob baseBlob = { base->length, base->val };
struct HksBlob expBlob = { exp->length, exp->val };
struct HksBlob outNumBlob = { outNum->length, outNum->val };
struct HksBlob bigNumBlob = { 0, NULL };
bigNumBlob.size = outNum->length;
bigNumBlob.data = (uint8_t *)HcMalloc(bigNumBlob.size, 0);
if (bigNumBlob.data == NULL) {
LOGE("malloc bigNumBlob.data failed.");
return HAL_ERR_BAD_ALLOC;
}
ret = HexStringToByte(bigNumHex, bigNumBlob.data, bigNumBlob.size);
if (ret != HAL_SUCCESS) {
LOGE("HexStringToByte for bigNumHex failed.");
HcFree(bigNumBlob.data);
return ret;
}
ret = HksBnExpMod(&outNumBlob, &baseBlob, &expBlob, &bigNumBlob);
if (ret != HKS_SUCCESS) {
LOGE("Huks calculate big number exp mod failed, ret = %d", ret);
HcFree(bigNumBlob.data);
return HAL_FAILED;
}
outNum->length = outNumBlob.size;
HcFree(bigNumBlob.data);
return HAL_SUCCESS;
}
static bool CheckBigNumCompareParams(const Uint8Buff *a, const Uint8Buff *b, int *res)
{
if ((a == NULL || a->val == NULL) && (b == NULL || b->val == NULL)) {
*res = 0; // a = b
return false;
}
if ((a == NULL || a->val == NULL) && (b != NULL && b->val != NULL)) {
*res = 1; // a < b
return false;
}
if ((a != NULL && a->val != NULL) && (b == NULL || b->val == NULL)) {
*res = -1; // a > b
return false;
}
return true;
}
static int32_t BigNumCompare(const Uint8Buff *a, const Uint8Buff *b)
{
int res = 0;
if (!CheckBigNumCompareParams(a, b, &res)) {
return res;
}
const uint8_t *tmpA = a->val;
const uint8_t *tmpB = b->val;
uint32_t len = a->length;
if (a->length < b->length) {
for (uint32_t i = 0; i < b->length - a->length; i++) {
if (b->val[i] > 0) {
return 1; // a < b
}
}
tmpA = a->val;
tmpB = b->val + b->length - a->length;
len = a->length;
}
if (a->length > b->length) {
for (uint32_t i = 0; i < a->length - b->length; i++) {
if (a->val[i] > 0) {
return -1; // a > b
}
}
tmpA = a->val + a->length - b->length;
tmpB = b->val;
len = b->length;
}
for (uint32_t i = 0; i < len; i++) {
if (*(tmpA + i) > *(tmpB + i)) {
return -1; // a > b
}
if (*(tmpA + i) < *(tmpB + i)) {
return 1; // a < b
}
}
return 0; // a == b
}
static bool CheckDlPublicKey(const Uint8Buff *key, const char *primeHex)
{
if (key == NULL || key->val == NULL || primeHex == NULL) {
LOGE("Params is null.");
return false;
}
uint8_t min = 1;
uint32_t innerKeyLen = HcStrlen(primeHex) / BYTE_TO_HEX_OPER_LENGTH;
if (key->length > innerKeyLen) {
LOGE("Key length > prime number length.");
return false;
}
uint8_t *primeByte = (uint8_t *)HcMalloc(innerKeyLen, 0);
if (primeByte == NULL) {
LOGE("Malloc for primeByte failed.");
return false;
}
if (HexStringToByte(primeHex, primeByte, innerKeyLen) != HAL_SUCCESS) {
LOGE("Convert prime number from hex string to byte failed.");
HcFree(primeByte);
return false;
}
/*
* P - 1, since the last byte of large prime number must be greater than 1,
* needn't to think about borrowing forward
*/
primeByte[innerKeyLen - 1] -= 1;
Uint8Buff minBuff = { &min, sizeof(uint8_t) };
if (BigNumCompare(key, &minBuff) >= 0) {
LOGE("Pubkey is invalid, key <= 1.");
HcFree(primeByte);
return false;
}
Uint8Buff primeBuff = { primeByte, innerKeyLen };
if (BigNumCompare(key, &primeBuff) <= 0) {
LOGE("Pubkey is invalid, key >= p - 1.");
HcFree(primeByte);
return false;
}
HcFree(primeByte);
return true;
}
static const AlgLoader g_huksLoader = {
InitHks,
Sha256,
GenerateRandom,
ComputeHmac,
ComputeHkdf,
ImportAsymmetricKey,
CheckKeyExist,
DeleteKey,
AesGcmEncrypt,
AesGcmDecrypt,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL
.initAlg = InitHks,
.sha256 = Sha256,
.generateRandom = GenerateRandom,
.computeHmac = ComputeHmac,
.computeHkdf = ComputeHkdf,
.importSymmetricKey = ImportSymmetricKey,
.checkKeyExist = CheckKeyExist,
.deleteKey = DeleteKey,
.aesGcmEncrypt = AesGcmEncrypt,
.aesGcmDecrypt = AesGcmDecrypt,
.hashToPoint = NULL,
.agreeSharedSecretWithStorage = NULL,
.agreeSharedSecret = NULL,
.bigNumExpMod = BigNumExpMod,
.generateKeyPairWithStorage = NULL,
.generateKeyPair = NULL,
.exportPublicKey = NULL,
.sign = NULL,
.verify = NULL,
.importPublicKey = NULL,
.checkDlPublicKey = CheckDlPublicKey,
.checkEcPublicKey = NULL,
.bigNumCompare = BigNumCompare
};
const AlgLoader *GetRealLoaderInstance()
@@ -65,7 +65,7 @@ static int32_t ConstructParamSet(struct HksParamSet **out, const struct HksParam
return HAL_SUCCESS;
}
static int32_t InitHks()
static int32_t InitHks(void)
{
return HksInitialize();
}
@@ -752,7 +752,7 @@ static int32_t GenerateKeyPair(Algorithm algo, Uint8Buff *outPriKey, Uint8Buff *
if (outParamSet == NULL) {
LOGE("allocate buffer for output param set failed");
ret = HAL_ERR_BAD_ALLOC;
goto err;
goto ERR;
}
outParamSet->paramSetSize = outParamSetSize;
@@ -760,15 +760,15 @@ static int32_t GenerateKeyPair(Algorithm algo, Uint8Buff *outPriKey, Uint8Buff *
if (ret != HKS_SUCCESS) {
LOGE("generate x25519 key failed, ret:%d", ret);
ret = HAL_FAILED;
goto err;
goto ERR;
}
ret = GetKeyPair(outParamSet, outPriKey, outPubKey);
if (ret != HAL_SUCCESS) {
LOGE("parse x25519 output param set failed, ret:%d", ret);
goto err;
goto ERR;
}
err:
ERR:
HksFreeParamSet(&paramSet);
HcFree(outParamSet);
return ret;
@@ -835,29 +835,29 @@ static int32_t Sign(const Uint8Buff *keyAlias, const Uint8Buff *message, Algorit
if (messageHash.val == NULL) {
LOGE("malloc messageHash.data failed.");
ret = HAL_ERR_BAD_ALLOC;
goto err;
goto ERR;
}
ret = Sha256(message, &messageHash);
if (ret != HAL_SUCCESS) {
LOGE("Sha256 failed.");
goto err;
goto ERR;
}
struct HksBlob messageBlob = { messageHash.length, messageHash.val };
struct HksBlob signatureBlob = { outSignature->length, outSignature->val };
ret = ConstructSignParams(&paramSet, algo);
if (ret != HAL_SUCCESS) {
goto err;
goto ERR;
}
ret = HksSign(&keyAliasBlob, paramSet, &messageBlob, &signatureBlob);
if ((ret != HKS_SUCCESS) || (signatureBlob.size != SIGNATURE_LEN)) {
LOGE("Hks sign failed.");
ret = HAL_FAILED;
goto err;
goto ERR;
}
ret = HAL_SUCCESS;
err:
ERR:
HksFreeParamSet(&paramSet);
HcFree(messageHash.val);
return ret;
@@ -905,29 +905,29 @@ static int32_t Verify(const Uint8Buff *key, const Uint8Buff *message, Algorithm
if (messageHash.val == NULL) {
LOGE("malloc messageHash.data failed.");
ret = HAL_ERR_BAD_ALLOC;
goto err;
goto ERR;
}
ret = Sha256(message, &messageHash);
if (ret != HAL_SUCCESS) {
LOGE("Sha256 failed.");
goto err;
goto ERR;
}
struct HksBlob messageBlob = { messageHash.length, messageHash.val };
struct HksBlob signatureBlob = { signature->length, signature->val };
ret = ConstructVerifyParams(&paramSet, algo, isAlias);
if (ret != HAL_SUCCESS) {
goto err;
goto ERR;
}
ret = HksVerify(&keyAliasBlob, paramSet, &messageBlob, &signatureBlob);
if ((ret != HKS_SUCCESS)) {
LOGE("HksVerify failed, ret: %d", ret);
ret = HAL_FAILED;
goto err;
goto ERR;
}
ret = HAL_SUCCESS;
err:
ERR:
HksFreeParamSet(&paramSet);
HcFree(messageHash.val);
return ret;
@@ -1014,30 +1014,51 @@ static int32_t ImportPublicKey(const Uint8Buff *keyAlias, const Uint8Buff *pubKe
return HAL_SUCCESS;
}
static int32_t Compare(const uint8_t *a, uint32_t lenA, const uint8_t *b, uint32_t lenB)
static bool CheckBigNumCompareParams(const Uint8Buff *a, const Uint8Buff *b, int *res)
{
const uint8_t *tmpA = a;
const uint8_t *tmpB = b;
uint32_t len = lenA;
if (lenA < lenB) {
for (uint32_t i = 0; i < lenB - lenA; i++) {
if (b[i] > 0) {
if ((a == NULL || a->val == NULL) && (b == NULL || b->val == NULL)) {
*res = 0; // a = b
return false;
}
if ((a == NULL || a->val == NULL) && (b != NULL && b->val != NULL)) {
*res = 1; // a < b
return false;
}
if ((a != NULL && a->val != NULL) && (b == NULL || b->val == NULL)) {
*res = -1; // a > b
return false;
}
return true;
}
static int32_t BigNumCompare(const Uint8Buff *a, const Uint8Buff *b)
{
int res = 0;
if (!CheckBigNumCompareParams(a, b, &res)) {
return res;
}
const uint8_t *tmpA = a->val;
const uint8_t *tmpB = b->val;
uint32_t len = a->length;
if (a->length < b->length) {
for (uint32_t i = 0; i < b->length - a->length; i++) {
if (b->val[i] > 0) {
return 1; // a < b
}
}
tmpA = a;
tmpB = b + lenB - lenA;
len = lenA;
tmpA = a->val;
tmpB = b->val + b->length - a->length;
len = a->length;
}
if (lenA > lenB) {
for (uint32_t i = 0; i < lenA - lenB; i++) {
if (a[i] > 0) {
if (a->length > b->length) {
for (uint32_t i = 0; i < a->length - b->length; i++) {
if (a->val[i] > 0) {
return -1; // a > b
}
}
tmpA = a + lenA - lenB;
tmpB = b;
len = lenB;
tmpA = a->val + a->length - b->length;
tmpB = b->val;
len = b->length;
}
for (uint32_t i = 0; i < len; i++) {
if (*(tmpA + i) > *(tmpB + i)) {
@@ -1050,7 +1071,7 @@ static int32_t Compare(const uint8_t *a, uint32_t lenA, const uint8_t *b, uint32
return 0; // a == b
}
bool CheckDlPublicKey(const Uint8Buff *key, const char *primeHex)
static bool CheckDlPublicKey(const Uint8Buff *key, const char *primeHex)
{
if (key == NULL || key->val == NULL || primeHex == NULL) {
LOGE("Params is null.");
@@ -1079,13 +1100,15 @@ bool CheckDlPublicKey(const Uint8Buff *key, const char *primeHex)
*/
primeByte[innerKeyLen - 1] -= 1;
if (Compare(key->val, key->length, &min, sizeof(uint8_t)) >= 0) {
Uint8Buff minBuff = { &min, sizeof(uint8_t) };
if (BigNumCompare(key, &minBuff) >= 0) {
LOGE("Pubkey is invalid, key <= 1.");
HcFree(primeByte);
return false;
}
if (Compare(key->val, key->length, primeByte, innerKeyLen) <= 0) {
Uint8Buff primeBuff = { primeByte, innerKeyLen };
if (BigNumCompare(key, &primeBuff) <= 0) {
LOGE("Pubkey is invalid, key >= p - 1.");
HcFree(primeByte);
return false;
@@ -1101,7 +1124,7 @@ static const AlgLoader g_huksLoader = {
.generateRandom = GenerateRandom,
.computeHmac = ComputeHmac,
.computeHkdf = ComputeHkdf,
.importAsymmetricKey = NULL,
.importSymmetricKey = NULL,
.checkKeyExist = CheckKeyExist,
.deleteKey = DeleteKey,
.aesGcmEncrypt = AesGcmEncrypt,
@@ -1118,7 +1141,7 @@ static const AlgLoader g_huksLoader = {
.importPublicKey = ImportPublicKey,
.checkDlPublicKey = CheckDlPublicKey,
.checkEcPublicKey = NULL,
.bigNumCompare = NULL
.bigNumCompare = BigNumCompare
};
const AlgLoader *GetRealLoaderInstance()
@@ -285,7 +285,7 @@ static int32_t CurveHashToPoint(const struct HksBlob *hash, struct HksBlob *poin
BN_CTX *ctx = BN_CTX_new();
if (ctx == NULL) {
ret = HAL_ERR_BAD_ALLOC;
goto err;
goto ERR;
}
do {
ret = CurveSetConstPara(&curvePara);
@@ -311,7 +311,7 @@ static int32_t CurveHashToPoint(const struct HksBlob *hash, struct HksBlob *poin
ret = HAL_FAILED;
}
} while (0);
err:
ERR:
CurveFreeConstPara(&curvePara);
BN_free(a);
BN_free(b);
@@ -65,7 +65,7 @@ static int32_t ConstructParamSet(struct HksParamSet **out, const struct HksParam
return HAL_SUCCESS;
}
static int32_t InitHks()
static int32_t InitHks(void)
{
return HksInitialize();
}
@@ -755,7 +755,7 @@ static int32_t GenerateKeyPair(Algorithm algo, Uint8Buff *outPriKey, Uint8Buff *
if (outParamSet == NULL) {
LOGE("allocate buffer for output param set failed");
ret = HAL_ERR_BAD_ALLOC;
goto err;
goto ERR;
}
outParamSet->paramSetSize = outParamSetSize;
@@ -763,15 +763,15 @@ static int32_t GenerateKeyPair(Algorithm algo, Uint8Buff *outPriKey, Uint8Buff *
if (ret != HKS_SUCCESS) {
LOGE("generate x25519 key failed, ret:%d", ret);
ret = HAL_FAILED;
goto err;
goto ERR;
}
ret = GetKeyPair(outParamSet, outPriKey, outPubKey);
if (ret != HAL_SUCCESS) {
LOGE("parse x25519 output param set failed, ret:%d", ret);
goto err;
goto ERR;
}
err:
ERR:
HksFreeParamSet(&paramSet);
HcFree(outParamSet);
return ret;
@@ -838,29 +838,29 @@ static int32_t Sign(const Uint8Buff *keyAlias, const Uint8Buff *message, Algorit
if (messageHash.val == NULL) {
LOGE("malloc messageHash.data failed.");
ret = HAL_ERR_BAD_ALLOC;
goto err;
goto ERR;
}
ret = Sha256(message, &messageHash);
if (ret != HAL_SUCCESS) {
LOGE("Sha256 failed.");
goto err;
goto ERR;
}
struct HksBlob messageBlob = { messageHash.length, messageHash.val };
struct HksBlob signatureBlob = { outSignature->length, outSignature->val };
ret = ConstructSignParams(&paramSet, algo);
if (ret != HAL_SUCCESS) {
goto err;
goto ERR;
}
ret = HksSign(&keyAliasBlob, paramSet, &messageBlob, &signatureBlob);
if ((ret != HKS_SUCCESS) || (signatureBlob.size != SIGNATURE_LEN)) {
LOGE("Hks sign failed.");
ret = HAL_FAILED;
goto err;
goto ERR;
}
ret = HAL_SUCCESS;
err:
ERR:
HksFreeParamSet(&paramSet);
HcFree(messageHash.val);
return ret;
@@ -908,29 +908,29 @@ static int32_t Verify(const Uint8Buff *key, const Uint8Buff *message, Algorithm
if (messageHash.val == NULL) {
LOGE("malloc messageHash.data failed.");
ret = HAL_ERR_BAD_ALLOC;
goto err;
goto ERR;
}
ret = Sha256(message, &messageHash);
if (ret != HAL_SUCCESS) {
LOGE("Sha256 failed.");
goto err;
goto ERR;
}
struct HksBlob messageBlob = { messageHash.length, messageHash.val };
struct HksBlob signatureBlob = { signature->length, signature->val };
ret = ConstructVerifyParams(&paramSet, algo, isAlias);
if (ret != HAL_SUCCESS) {
goto err;
goto ERR;
}
ret = HksVerify(&keyAliasBlob, paramSet, &messageBlob, &signatureBlob);
if ((ret != HKS_SUCCESS)) {
LOGE("HksVerify failed, ret: %d", ret);
ret = HAL_FAILED;
goto err;
goto ERR;
}
ret = HAL_SUCCESS;
err:
ERR:
HksFreeParamSet(&paramSet);
HcFree(messageHash.val);
return ret;
@@ -1017,30 +1017,51 @@ static int32_t ImportPublicKey(const Uint8Buff *keyAlias, const Uint8Buff *pubKe
return HAL_SUCCESS;
}
static int32_t Compare(const uint8_t *a, uint32_t lenA, const uint8_t *b, uint32_t lenB)
static bool CheckBigNumCompareParams(const Uint8Buff *a, const Uint8Buff *b, int *res)
{
const uint8_t *tmpA = a;
const uint8_t *tmpB = b;
uint32_t len = lenA;
if (lenA < lenB) {
for (uint32_t i = 0; i < lenB - lenA; i++) {
if (b[i] > 0) {
if ((a == NULL || a->val == NULL) && (b == NULL || b->val == NULL)) {
*res = 0; // a = b
return false;
}
if ((a == NULL || a->val == NULL) && (b != NULL && b->val != NULL)) {
*res = 1; // a < b
return false;
}
if ((a != NULL && a->val != NULL) && (b == NULL || b->val == NULL)) {
*res = -1; // a > b
return false;
}
return true;
}
static int32_t BigNumCompare(const Uint8Buff *a, const Uint8Buff *b)
{
int res = 0;
if (!CheckBigNumCompareParams(a, b, &res)) {
return res;
}
const uint8_t *tmpA = a->val;
const uint8_t *tmpB = b->val;
uint32_t len = a->length;
if (a->length < b->length) {
for (uint32_t i = 0; i < b->length - a->length; i++) {
if (b->val[i] > 0) {
return 1; // a < b
}
}
tmpA = a;
tmpB = b + lenB - lenA;
len = lenA;
tmpA = a->val;
tmpB = b->val + b->length - a->length;
len = a->length;
}
if (lenA > lenB) {
for (uint32_t i = 0; i < lenA - lenB; i++) {
if (a[i] > 0) {
if (a->length > b->length) {
for (uint32_t i = 0; i < a->length - b->length; i++) {
if (a->val[i] > 0) {
return -1; // a > b
}
}
tmpA = a + lenA - lenB;
tmpB = b;
len = lenB;
tmpA = a->val + a->length - b->length;
tmpB = b->val;
len = b->length;
}
for (uint32_t i = 0; i < len; i++) {
if (*(tmpA + i) > *(tmpB + i)) {
@@ -1053,7 +1074,7 @@ static int32_t Compare(const uint8_t *a, uint32_t lenA, const uint8_t *b, uint32
return 0; // a == b
}
bool CheckDlPublicKey(const Uint8Buff *key, const char *primeHex)
static bool CheckDlPublicKey(const Uint8Buff *key, const char *primeHex)
{
if (key == NULL || key->val == NULL || primeHex == NULL) {
LOGE("Params is null.");
@@ -1082,13 +1103,15 @@ bool CheckDlPublicKey(const Uint8Buff *key, const char *primeHex)
*/
primeByte[innerKeyLen - 1] -= 1;
if (Compare(key->val, key->length, &min, sizeof(uint8_t)) >= 0) {
Uint8Buff minBuff = { &min, sizeof(uint8_t) };
if (BigNumCompare(key, &minBuff) >= 0) {
LOGE("Pubkey is invalid, key <= 1.");
HcFree(primeByte);
return false;
}
if (Compare(key->val, key->length, primeByte, innerKeyLen) <= 0) {
Uint8Buff primeBuff = { primeByte, innerKeyLen };
if (BigNumCompare(key, &primeBuff) <= 0) {
LOGE("Pubkey is invalid, key >= p - 1.");
HcFree(primeByte);
return false;
@@ -1104,7 +1127,7 @@ static const AlgLoader g_huksLoader = {
.generateRandom = GenerateRandom,
.computeHmac = ComputeHmac,
.computeHkdf = ComputeHkdf,
.importAsymmetricKey = NULL,
.importSymmetricKey = NULL,
.checkKeyExist = CheckKeyExist,
.deleteKey = DeleteKey,
.aesGcmEncrypt = AesGcmEncrypt,
@@ -1121,7 +1144,7 @@ static const AlgLoader g_huksLoader = {
.importPublicKey = ImportPublicKey,
.checkDlPublicKey = CheckDlPublicKey,
.checkEcPublicKey = NULL,
.bigNumCompare = NULL
.bigNumCompare = BigNumCompare
};
const AlgLoader *GetRealLoaderInstance()
@@ -44,6 +44,11 @@ typedef enum {
P256 = 2,
} Algorithm;
typedef enum {
KEY_PURPOSE_MAC = 0,
KEY_PURPOSE_DERIVE = 1,
} KeyPurpose;
typedef enum {
CURVE_NONE,
CURVE_256,
@@ -74,7 +79,7 @@ typedef int32_t (*ComputeHmacFunc)(const Uint8Buff *key, const Uint8Buff *messag
typedef int32_t (*ComputeHkdfFunc)(const Uint8Buff *baseKey, const Uint8Buff *salt, const Uint8Buff *keyInfo,
Uint8Buff *outHkdf, bool isAlias);
typedef int32_t (*ImportAsymmetricKeyFunc)(const Uint8Buff *keyAlias, const Uint8Buff *authToken,
typedef int32_t (*ImportSymmetricKeyFunc)(const Uint8Buff *keyAlias, const Uint8Buff *authToken, KeyPurpose purpose,
const ExtraInfo *exInfo);
typedef int32_t (*CheckKeyExistFunc)(const Uint8Buff *keyAlias);
@@ -127,7 +132,7 @@ typedef struct {
GenerateRandomFunc generateRandom;
ComputeHmacFunc computeHmac;
ComputeHkdfFunc computeHkdf;
ImportAsymmetricKeyFunc importAsymmetricKey;
ImportSymmetricKeyFunc importSymmetricKey;
CheckKeyExistFunc checkKeyExist;
DeleteKeyFunc deleteKey;
AesGcmEncryptFunc aesGcmEncrypt;
@@ -47,6 +47,17 @@ const char *GetStoragePath(void)
return storageFile;
}
const char *GetStorageDirPath(void)
{
#ifndef LITE_DEVICE
const char *storageFile = "/data/data/deviceauth";
#else
const char *storageFile = "/storage/deviceauth";
#endif
LOGI("[OS]: storageDirFile: %s", storageFile);
return storageFile;
}
#ifdef __cplusplus
}
#endif
@@ -38,6 +38,7 @@ static char g_groupPath[MAX_FILE_PATH_SIZE] = { 0 };
static FileDefInfo g_fileDefInfo[FILE_ID_LAST] = {
{ FILE_ID_GROUP, "/data/data/deviceauth/hcgroup.dat" },
{ FILE_ID_CRED_DATA, "" }
};
void SetFilePath(FileIdEnum fileId, const char *path)
@@ -41,6 +41,11 @@ const char *GetStoragePath(void)
return "hcgroup.dat";
}
const char *GetStorageDirPath(void)
{
return "";
}
#ifdef __cplusplus
}
#endif
@@ -37,7 +37,8 @@ typedef struct {
} FileDefInfo;
static FileDefInfo g_fileDefInfo[FILE_ID_LAST] = {
{ FILE_ID_GROUP, "user/Hichain/hcgroup.dat" }
{ FILE_ID_GROUP, "user/Hichain/hcgroup.dat" },
{ FILE_ID_CRED_DATA, "" }
};
static char g_groupPath[MAX_FILE_PATH_SIZE] = { 0 };
@@ -35,7 +35,8 @@ typedef struct {
} FileDefInfo;
static FileDefInfo g_fileDefInfo[FILE_ID_LAST] = {
{ FILE_ID_GROUP, "/data/hcgroup.dat" }
{ FILE_ID_GROUP, "/data/hcgroup.dat" },
{ FILE_ID_CRED_DATA, "" }
};
void SetFilePath(FileIdEnum fileId, const char *path)
@@ -36,6 +36,7 @@ extern "C" {
int32_t HcGetUdid(uint8_t *udid, int32_t udidLen);
const char *GetStoragePath(void);
const char *GetStorageDirPath(void);
#ifdef __cplusplus
}
@@ -27,6 +27,7 @@ typedef union {
typedef enum FileIdEnumT {
FILE_ID_GROUP = 0,
FILE_ID_CRED_DATA,
FILE_ID_LAST,
} FileIdEnum;
@@ -26,6 +26,7 @@ typedef struct {
typedef enum FileIdEnumT {
FILE_ID_GROUP = 0,
FILE_ID_CRED_DATA,
FILE_ID_LAST,
} FileIdEnum;
+14 -4
View File
@@ -66,6 +66,7 @@
#define FIELD_GROUP_VISIBILITY "groupVisibility"
#define FIELD_EXPIRE_TIME "expireTime"
#define FIELD_IS_DELETE_ALL "isDeleteAll"
#define FIELD_BLE_CHALLENGE "bleChallenge"
typedef enum {
ALL_GROUP = 0,
@@ -92,10 +93,13 @@ typedef enum {
} GroupAuthForm;
typedef enum {
CREDENTIAL_SAVE = 0,
CREDENTIAL_CLEAR = 1,
CREDENTIAL_UPDATE = 2,
CREDENTIAL_QUERY = 3,
IMPORT_SELF_CREDENTIAL = 0,
DELETE_SELF_CREDENTIAL = 1,
QUERY_SELF_CREDENTIAL_INFO = 2,
IMPORT_TRUSTED_CREDENTIALS = 3,
DELETE_TRUSTED_CREDENTIALS = 4,
QUERY_TRUSTED_CREDENTIALS = 5,
REQUEST_SIGNATURE = 6,
} CredentialCode;
typedef enum {
@@ -104,6 +108,12 @@ typedef enum {
DEVICE_TYPE_PROXY = 2
} UserType;
typedef enum {
EXPIRE_TIME_INDEFINITE = -1,
EXPIRE_TIME_MIN = 1,
EXPIRE_TIME_MAX = 90,
} ExpireTime;
typedef enum {
REQUEST_REJECTED = 0x80000005,
REQUEST_ACCEPTED = 0x80000006,
+8 -2
View File
@@ -37,14 +37,18 @@ enum {
HC_ERR_CASE = 0x0000000A,
HC_ERR_BAD_TIMING = 0x0000000B,
HC_ERR_PEER_ERROR = 0x0000000C,
HC_ERR_FILE = 0x0000000D,
HC_ERR_MEMORY_COMPARE = 0x0000000E,
HC_ERR_OUT_OF_LIMIT = 0x0000000F,
HC_ERR_INIT_FAILED = 0x00000010,
/* error code for huks adapter , 0x00001000 ~ 0x00001FFF */
/* error code for algorithm adapter , 0x00001000 ~ 0x00001FFF */
HC_ERR_KEY_NOT_EXIST = 0x00001001,
HC_ERR_GENERATE_KEY_FAILED = 0x000010002,
HC_ERR_INVALID_PUBLIC_KEY = 0x00001003,
HC_ERR_VERIFY_FAILED = 0x00001004,
HC_ERR_HASH_FAIL = 0x00001005,
HC_ERR_INIT_FAILED = 0x00001006,
HC_ERR_ALG_FAIL = 0x00001006,
/* error code for json util , 0x00002000 ~ 0x00002FFF */
HC_ERR_JSON_FAIL = 0x00002001,
@@ -100,6 +104,8 @@ enum {
HC_ERR_SERVER_CONFIRM_FAIL = 0x0000500B,
HC_ERR_CREATE_SESSION_FAIL = 0x0000500C,
HC_ERR_SESSION_IS_FULL = 0x0000500D,
HC_ERR_INVALID_UDID = 0x0000500E,
HC_ERR_INVALID_TCIS_ID = 0x0000500F,
/* error code for database , 0x00006000 ~ 0x00006FFF */
HC_ERR_DB = 0x00006001,
+2 -13
View File
@@ -40,12 +40,7 @@ if (defined(ohos_lite)) {
]
defines = [ "HILOG_ENABLE" ]
if (enable_p2p_pake_dl_prime_len_384 == true) {
defines += [ "P2P_PAKE_DL_PRIME_LEN_384" ]
}
if (enable_p2p_pake_dl_prime_len_256 == true) {
defines += [ "P2P_PAKE_DL_PRIME_LEN_256" ]
}
defines += deviceauth_defines
cflags = build_flags
if (ohos_kernel_type == "linux" || ohos_kernel_type == "liteos_a") {
@@ -151,13 +146,7 @@ if (defined(ohos_lite)) {
sources = deviceauth_files
cflags = [ "-DHILOG_ENABLE" ]
defines = []
if (enable_p2p_pake_dl_prime_len_384 == true) {
defines += [ "P2P_PAKE_DL_PRIME_LEN_384" ]
}
if (enable_p2p_pake_dl_prime_len_256 == true) {
defines += [ "P2P_PAKE_DL_PRIME_LEN_256" ]
}
defines = deviceauth_defines
cflags += build_flags
if (target_cpu == "arm") {
cflags += [ "-DBINDER_IPC_32BIT" ]
@@ -0,0 +1,28 @@
/*
* Copyright (C) 2021 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_MODULE_H
#define ACCOUNT_MODULE_H
#include "dev_auth_module_manager.h"
#include "hc_types.h"
#include "json_utils.h"
int32_t CheckAccountMsgRepeatability(const CJson *in);
bool IsAccountSupported(void);
AuthModuleBase *CreateAccountModule(void);
int32_t ProcessAccountCredentials(int credentialOpCode, const CJson *in, CJson *out);
#endif
@@ -1,102 +0,0 @@
/*
* Copyright (C) 2021 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_COMMON_H
#define AUTH_COMMON_H
#define AUTH_STEP "authStep"
#define DEV_ID "devId"
#define SALT "salt"
#define USER_ID "userId"
#define SEED "seed"
#define AUTH_FORM "authForm"
#define AUTH_KEY_ALG_ENCODE "authKeyAlgEncode"
#define TOKEN "token"
#define SESSION_KEY "sessionKey"
#define AUTH_RESULT "authResult"
#define AUTH_RESULT_MAC "authResultMac"
#define IS_CLIENT "isClient"
#define HI_CHAIN_RETURN_KEY "hichain_return_key"
#define SEND_TO_SELF "sendToSelf"
#define SEND_TO_PEER "sendToPeer"
#define SEED_SIZE 32
#define AUTH_ID_SIZE 8
#define USER_ID_SIZE 20
#define TCIS_ID_SIZE 10
#define DEV_ID_SIZE 40
#define DEV_ID_MAX_SIZE 40
#define DEV_TYPE_SIZE 3
#define DEV_MODEL_MAX_SIZE 40
#define UDID_SIZE 10
#define RANDOM_SIZE 16
#define TOKEN_SIZE 32
#define PSK_SIZE 32
#define AUTH_RESULT_MAC_SIZE 32
#define AUTH_CODE_SIZE 32
#define PUBLIC_KEY_LENGTH 64
#define PUBLIC_KEY_HEX_LENGTH 128
#define AUTH_PK_SIG_SIZE 64
#define AUTH_RESULT_SIGN_SIZE 64
#define SIGNATURE_SIZE 128
#define SERVER_PK_SIZE 64
#define HI_CHAIN_STRING_SIZE 18
#define PUBLIC_KEY_INFO_SIZE 300
#ifdef ASY
#define PROOF_LEN 146
#define TOKEN_LEN 218
#endif
#ifdef SYM
#define TOKEN_LEN 48
#endif
typedef enum {
SYMMETRIC_AUTH = 0,
ASYMMETRIC_AUTH,
POINT_TO_POINT,
SAME_ACCOUNT,
ACROSS_ACCOUNT,
} AuthForm;
typedef enum {
AUTH_ERR_AUTH_STEP,
AUTH_ERR_INVALID_PARAM,
AUTH_ERR_TOKEN_NOT_MATCH,
AUTH_ERR_ALLOC_MEMORY,
AUTH_ERR_MAC_NOT_EQUAL,
AUTH_ERR_PROCESS_TASK,
AUTH_ERR_MESSAGE_PEER,
AUTH_ERR_STATUS,
AUTH_ERR_INTERNAL,
AUTH_ERR_GET_HMAC,
AUTH_ERR_JSON,
AUTH_ERR_GET_ITEM,
AUTH_ERR_COMPARE,
ERR_MULTI_AUTH_TASK_CREATE_FAIL,
AUTH_ERR_SUCCESS = 0,
} AuthResult;
typedef enum {
ALG_ECC = 0x0000,
ALG_RSA = 0x0001,
ALG_HKDF = 0x0002,
ALG_HMAC = 0x0003,
ALG_AES = 0x0004,
ALG_PBKDF2 = 0x0005,
ALG_ECDH = 0x0006,
ALG_X25519 = 0x0007,
ALG_ED25519 = 0x0008,
} KeyAlg;
#endif
@@ -1,37 +0,0 @@
/*
* Copyright (C) 2021 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 TCIS_DEVICE_AUTH_TASK_BASE_H
#define TCIS_DEVICE_AUTH_TASK_BASE_H
#include "alg_defs.h"
#include "tcis_module_defines.h"
typedef struct _TaskBase {
TcisTaskType (*getTaskType)(void);
void (*destroyTask)(struct _TaskBase *);
int (*process)(struct _TaskBase *, CJson *in, CJson *out, int *status);
int taskStatus;
int taskId;
} TaskBase;
typedef TaskBase *(*CreateTaskFunc)(int *, const CJson *, CJson *, AlgLoader *);
typedef struct {
int taskTypeId;
CreateTaskFunc createTask;
} TaskCreateInfo;
#endif
@@ -1,83 +0,0 @@
/*
* Copyright (C) 2021 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 TCIS_DEVICE_AUTH_TCIS_AUTH_TOKEN_MANAGER_H
#define TCIS_DEVICE_AUTH_TCIS_AUTH_TOKEN_MANAGER_H
#ifndef ASY
#define ASY
#include <stdint.h>
#include "common_defs.h"
#include "string_util.h"
#include "auth_common.h"
#define FILE_VERSION 0x01
#define SERVER_PUBLIC_KEY_ALIAS "tcisServerPk"
#define ECC_KEY_ALIAS "tcisEccKeyPair"
#define AUTH_CODE_ALIAS "tcisAuthCode"
typedef enum {
CMD_USER_ID = 0,
CMD_DEVICE_ID,
} FileCmd;
typedef struct {
uint64_t userId;
uint8_t deviceType[DEV_TYPE_SIZE];
uint8_t deviceId[DEV_ID_MAX_SIZE];
uint8_t deviceModel[DEV_MODEL_MAX_SIZE];
uint8_t publicKey[PUBLIC_KEY_HEX_LENGTH];
} PkInfo;
#ifdef ASY
typedef struct {
uint32_t version;
uint8_t userId[USER_ID_SIZE];
uint8_t deviceId[DEV_ID_MAX_SIZE];
uint8_t deviceModel[DEV_MODEL_MAX_SIZE];
uint8_t deviceType[DEV_TYPE_SIZE];
uint32_t algType;
uint8_t pairingTcisId[TCIS_ID_SIZE];
uint8_t publicKey[PUBLIC_KEY_HEX_LENGTH];
uint8_t signature[SIGNATURE_SIZE];
} RegisterProof;
typedef struct {
uint8_t pkInfoStr[PUBLIC_KEY_INFO_SIZE];
PkInfo pkInfo;
uint8_t pkInfoSignature[SIGNATURE_SIZE];
} TcisToken;
#endif
typedef struct {
int (*setToken)(CJson *in, CJson *out);
uint64_t (*getUserId)(void);
int (*getDeviceId)(Uint8Buff *deviceId);
int (*getToken)(TcisToken *token);
int (*getServerPublicKey)(Uint8Buff *publicKey);
int (*deleteToken)(void);
#ifdef ASY
int (*setRegisterProof)(CJson *in);
int (*getRegisterProof)(CJson *out);
#endif
} TcisAuthTokenManager;
TcisAuthTokenManager *GetTcisAuthTokenManager(void);
void InitTcisTokenManagerAlg(void);
#endif
#endif
@@ -1,57 +0,0 @@
/*
* Copyright (C) 2021 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 TCIS_DEVICE_AUTH_TCIS_MODULE_H
#define TCIS_DEVICE_AUTH_TCIS_MODULE_H
#include "task_base.h"
#include "auth_common.h"
#include "tcis_auth_token_manager.h"
#define TASK_MULTI_AUTH_NUM_MAX 8
#define TASK_INFOS_LENGTH 5
typedef enum {
CMD_ASY_AUTH_MAIN_ONE = 0x0030,
RET_ASY_AUTH_FOLLOWER_ONE = 0x0031,
CMD_ASY_AUTH_MAIN_TWO = 0x0032,
RET_ASY_AUTH_FOLLOWER_TWO = 0x0033,
CMD_ASY_AUTH_MAIN_FINAL = 0x0034,
ASY_BIND_PAKE_REQUEST = 0x0040,
ASY_BIND_PAKE_RESPONSE = 0x0041,
ASY_BIND_PAKE_CLIENT_CONFIRM = 0x0042,
ASY_BIND_PAKE_SERVER_CONFIRM = 0x0043,
ASY_BIND_EXCHANGE_REQUEST = 0x0043,
ASY_BIND_EXCHANGE_RESPONSE = 0x0044,
CMD_SYM_AUTH_MAIN_ONE = 0x0050,
RET_SYM_AUTH_FOLLOWER_ONE = 0x0051,
CMD_SYM_AUTH_MAIN_TWO = 0x0052,
RET_SYM_AUTH_FOLLOWER_TWO = 0x0053,
ERR_MSG = 0x8080,
} TcisMessageType;
typedef struct {
AuthModuleBase moduleBase;
TcisAuthTokenManager *tokenManager;
AlgLoader *algLoader;
} TcisAuthModule;
AuthModuleBase *CreateTcisModule(void);
bool IsTcisSupported(void);
#endif
@@ -1,57 +0,0 @@
/*
* Copyright (C) 2021 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 TCIS_DEVICE_AUTH_TCIS_MODULE_DEFINES_H
#define TCIS_DEVICE_AUTH_TCIS_MODULE_DEFINES_H
#include "alg_defs.h"
#include "auth_common.h"
#include "pake_protocol_common.h"
#include "string_util.h"
typedef enum {
TASK_TYPE_DEFAULT = 0,
TASK_TYPE_ASY_SERVER_BIND = 1,
TASK_TYPE_ASY_CLIENT_AUTH = 2,
TASK_TYPE_ASY_SERVER_AUTH = 3,
TASK_TYPE_SYM_SERVER_AUTH,
TASK_TYPE_SYM_CLIENT_AUTH,
} TcisTaskType;
typedef struct {
int authVersion;
bool isClient;
int authForm;
uint8_t seed[SEED_SIZE];
uint8_t userIdSelf[USER_ID_SIZE];
uint8_t userIdPeer[USER_ID_SIZE];
uint8_t devIdSelf[DEV_ID_MAX_SIZE];
uint8_t devIdPeer[DEV_ID_MAX_SIZE];
uint8_t saltSelf[RANDOM_SIZE];
uint8_t saltPeer[RANDOM_SIZE];
uint8_t token[TOKEN_SIZE];
uint8_t *sessionKey;
int keyLength;
KeyAlg authKeyAlgEncode;
uint8_t psk[PSK_SIZE];
AlgLoader *loader;
} SymAuthParams;
typedef struct BindParams {
PakeBaseParams baseParams;
uint8_t nonce[16];
uint8_t dataEncKey[32];
} BindParams;
#endif
@@ -18,8 +18,7 @@
#include "common_defs.h"
#include "string_util.h"
bool IsDasSupported(void);
#include "dev_auth_module_manager.h"
typedef struct DasAuthModuleT {
AuthModuleBase moduleBase;
@@ -29,6 +28,8 @@ typedef struct DasAuthModuleT {
int (*getPublicKey)(const char *, const char *, Uint8Buff *, int, Uint8Buff *);
} DasAuthModule;
bool IsDasSupported(void);
bool IsDasMsgNeedIgnore(const CJson *in);
AuthModuleBase *CreateDasModule(void);
#endif
@@ -66,12 +66,12 @@ typedef enum {
typedef enum CurTaskTypeT {
TASK_TYPE_ISO_PROTOCOL = 0,
TASK_TYPE_PAKE_PROTOCOL = 1,
TASK_TYPE_NEW_PAKE_PROTOCOL = 2,
TASK_TYPE_BIND_LITE_EXCHANGE,
TASK_TYPE_UNBIND_LITE_EXCHANGE,
TASK_TYPE_BIND_STANDARD_EXCHANGE,
TASK_TYPE_UNBIND_STANDARD_EXCHANGE,
TASK_TYPE_PAKE_V1_PROTOCOL = 1,
TASK_TYPE_PAKE_V2_PROTOCOL = 2,
TASK_TYPE_BIND_LITE_EXCHANGE = 3,
TASK_TYPE_UNBIND_LITE_EXCHANGE = 4,
TASK_TYPE_BIND_STANDARD_EXCHANGE = 5,
TASK_TYPE_UNBIND_STANDARD_EXCHANGE = 6,
TASK_TYPE_NONE,
} CurTaskType;
@@ -23,13 +23,13 @@
int32_t GenerateKeyAlias(const Uint8Buff *pkgName, const Uint8Buff *serviceType, const KeyAliasType keyType,
const Uint8Buff *authId, Uint8Buff *outKeyAlias);
int32_t GetIdPeerForParams(const CJson *in, const char *peerIdKey, const Uint8Buff *authIdSelf, Uint8Buff *authIdPeer);
int32_t GetIdPeer(const CJson *in, const char *peerIdKey, const Uint8Buff *authIdSelf, Uint8Buff *authIdPeer);
int32_t GetAndCheckAuthIdPeer(const CJson *in, const Uint8Buff *authIdSelf, const Uint8Buff *authIdPeer);
int32_t GetAuthIdPeerFromPayload(const CJson *in, const Uint8Buff *authIdSelf, Uint8Buff *authIdPeer);
int32_t GetAndCheckKeyLenOnServer(const CJson *in, uint32_t *returnKeyLen);
void SendErrMsgToSelf(const CJson *in, CJson *out, int errCode);
void SendErrorToOut(CJson *out, int opCode, int errCode);
void DasSendErrMsgToSelf(CJson *out, int errCode);
void DasSendErrorToOut(CJson *out, int errCode); // send error to self and peer
uint32_t ProtocolMessageIn(const CJson *in);
int ClientProtocolMessageOut(CJson *out, int opCode, uint32_t step);
@@ -33,8 +33,8 @@ typedef struct TaskT {
Task *CreateTaskT(int *taskId, const CJson *in, CJson *out);
int32_t InitDasProtocolType(void);
void DestroyDasProtocolType(void);
int32_t InitDasProtocolEntities(void);
void DestroyDasProtocolEntities(void);
int32_t RegisterLocalIdentityInTask(const char *pkgName, const char *serviceType, Uint8Buff *authId, int userType);
int32_t UnregisterLocalIdentityInTask(const char *pkgName, const char *serviceType, Uint8Buff *authId, int userType);
@@ -13,8 +13,8 @@
* limitations under the License.
*/
#ifndef DAS_ASY_TOKEN_MANAGER
#define DAS_ASY_TOKEN_MANAGER
#ifndef DAS_TOKEN_MANAGER_H
#define DAS_TOKEN_MANAGER_H
#include "common_defs.h"
#include "pake_base_cur_task.h"
@@ -27,6 +27,4 @@ typedef struct TokenManagerT {
int (*getPublicKey)(const char *, const char *, Uint8Buff *, int, Uint8Buff *);
} TokenManager;
const TokenManager *GetAsyTokenManagerInstance(void);
#endif
@@ -16,8 +16,23 @@
#ifndef DAS_VERSION_UTIL_H
#define DAS_VERSION_UTIL_H
#include "pake_defs.h"
#include "version_util.h"
#define ALG_OFFSET_FOR_PAKE_V1 0
#define ALG_OFFSET_FOR_PAKE_V2 5
typedef enum {
UNSUPPORTED_ALG = 0x0000,
DL_PAKE_V1 = 0x0001, // 0001
EC_PAKE_V1 = 0x0002, // 0010
STS_ALG = 0x0004, // 0100
PSK_SPEKE = 0x0008, // 1000
ISO_ALG = 0x0010, // 0001 0000
DL_PAKE_V2 = 0x0020, // 0010 0000
EC_PAKE_V2 = 0x0040, // 0100 0000
} DasAlgType;
typedef enum {
INITIAL,
VERSION_CONFIRM,
@@ -39,7 +54,7 @@ int32_t NegotiateVersion(VersionStruct *minVersionPeer, VersionStruct *curVersio
VersionStruct *curVersionSelf);
ProtocolType GetPrototolType(VersionStruct *curVersion, OperationCode opCode);
AlgType GetSupportedPakeAlg(VersionStruct *curVersion);
PakeAlgType GetSupportedPakeAlg(VersionStruct *curVersion, ProtocolType protocolType);
bool IsSupportedPsk(VersionStruct *curVersion);
#endif
@@ -25,6 +25,6 @@ typedef struct {
SymBaseCurTask *curTask;
} IsoServerTask;
SubTaskBase *CreateIsoServerTask(const CJson *in, CJson *out);
SubTaskBase *CreateIsoServerTask(const CJson *in);
#endif
@@ -28,8 +28,8 @@ int GenerateKeyAliasInIso(const IsoParams *params, uint8_t *keyAlias, uint32_t k
int GeneratePsk(const CJson *in, IsoParams *params);
int GenerateEncResult(const IsoParams *params, int message, CJson *sendToPeer, const char *aad);
int GenEncResult(const IsoParams *params, int message, CJson *out, const char *aad, bool isNeedReturnKey);
int SendResultToFinalSelf(const IsoParams *params, CJson *out, bool isNeedReturnKey);
int GenEncResult(IsoParams *params, int message, CJson *out, const char *aad, bool isNeedReturnKey);
int SendResultToFinalSelf(IsoParams *params, CJson *out, bool isNeedReturnKey);
int CheckEncResult(IsoParams *params, const CJson *in, const char *aad);
void DeleteAuthCode(const IsoParams *params);
@@ -18,10 +18,8 @@
#include "base_sub_task.h"
#include "json_utils.h"
#include "das_asy_token_manager.h"
bool IsIsoSupported(void);
const TokenManager *GetSymTokenManagerInstance(void);
SubTaskBase *CreateIsoSubTask(const CJson *in, CJson *out);
SubTaskBase *CreateIsoSubTask(const CJson *in);
#endif
@@ -13,11 +13,11 @@
* limitations under the License.
*/
#ifndef MODULE_COMMON_H
#define MODULE_COMMON_H
#ifndef DAS_LITE_TOKEN_MANAGER_H
#define DAS_LITE_TOKEN_MANAGER_H
#include "string_util.h"
#include "das_token_manager.h"
int32_t InitSingleParam(Uint8Buff *param, uint32_t len);
const TokenManager *GetLiteTokenManagerInstance(void);
#endif
@@ -13,8 +13,8 @@
* limitations under the License.
*/
#ifndef ISO_CLIENT_BIND_EXCHANGE_TASK
#define ISO_CLIENT_BIND_EXCHANGE_TASK
#ifndef ISO_CLIENT_BIND_EXCHANGE_TASK_H
#define ISO_CLIENT_BIND_EXCHANGE_TASK_H
#include "iso_base_cur_task.h"
@@ -13,16 +13,11 @@
* limitations under the License.
*/
#include "new_pake_task_main.h"
#ifndef DAS_STANDARD_TOKEN_MANAGER_H
#define DAS_STANDARD_TOKEN_MANAGER_H
bool IsSupportNewPake()
{
return false;
}
#include "das_token_manager.h"
SubTaskBase *CreateNewPakeSubTask(const CJson *in, CJson *out)
{
(void)in;
(void)out;
return NULL;
}
const TokenManager *GetStandardTokenManagerInstance(void);
#endif
@@ -16,17 +16,23 @@
#ifndef PAKE_BASE_CUR_TASK_H
#define PAKE_BASE_CUR_TASK_H
#include <stdint.h>
#include "json_utils.h"
#include "das_module_defines.h"
#include "hc_types.h"
#include "json_utils.h"
#include "pake_defs.h"
#define HICHAIN_RETURN_KEY "hichain_return_key"
#define TMP_AUTH_KEY_FACTOR "hichain_tmp_auth_enc_key"
#define PAKE_KEY_ALIAS_LEN 64
#define PAKE_ED25519_KEY_PAIR_LEN 32
#define PAKE_NONCE_LEN 32
#define PAKE_PSK_LEN 32
typedef struct PakeParamsT {
PakeBaseParams baseParams;
bool isPskSupported;
Uint8Buff returnKey;
Uint8Buff nonce;
int opCode;
@@ -19,7 +19,6 @@
#include "json_utils.h"
#include "pake_base_cur_task.h"
int32_t ParseStartJsonParams(PakeParams *params, const CJson *in);
int32_t PackagePakeRequestData(const PakeParams *params, CJson *payload);
int32_t ParsePakeRequestMessage(PakeParams *params, const CJson *in);
int32_t PackagePakeResponseData(const PakeParams *params, CJson *payload);
@@ -19,7 +19,6 @@
#include "pake_base_cur_task.h"
#include "json_utils.h"
int32_t FillPskWithDerivedKey(PakeParams *params);
int32_t FillDasPakeParams(PakeParams *params, const CJson *in);
int32_t ConstructOutJson(const PakeParams *params, CJson *out);
int32_t SendResultToSelf(PakeParams *params, CJson *out);
@@ -13,15 +13,15 @@
* limitations under the License.
*/
#ifndef PAKE_CLIENT_PROTOCOL_TASK_H
#define PAKE_CLIENT_PROTOCOL_TASK_H
#ifndef PAKE_V1_CLIENT_PROTOCOL_TASK_H
#define PAKE_V1_CLIENT_PROTOCOL_TASK_H
#include "pake_base_cur_task.h"
typedef struct {
AsyBaseCurTask taskBase;
} PakeProtocolClientTask;
} PakeV1ProtocolClientTask;
AsyBaseCurTask *CreatePakeProtocolClientTask(void);
AsyBaseCurTask *CreatePakeV1ProtocolClientTask(void);
#endif
@@ -13,8 +13,8 @@
* limitations under the License.
*/
#ifndef PAKE_CLIENT_TASK_H
#define PAKE_CLIENT_TASK_H
#ifndef PAKE_V1_CLIENT_TASK_H
#define PAKE_V1_CLIENT_TASK_H
#include "json_utils.h"
#include "pake_base_cur_task.h"
@@ -24,8 +24,8 @@ typedef struct {
SubTaskBase taskBase;
PakeParams params;
AsyBaseCurTask *curTask;
} PakeClientTask;
} PakeV1ClientTask;
SubTaskBase *CreatePakeClientTask(const CJson *in, CJson *out);
SubTaskBase *CreatePakeV1ClientTask(const CJson *in);
#endif
@@ -13,13 +13,14 @@
* limitations under the License.
*/
#ifndef PAKE_PROTOCOL_TASK_COMMOM_H
#define PAKE_PROTOCOL_TASK_COMMOM_H
#ifndef PAKE_V1_PROTOCOL_TASK_COMMOM_H
#define PAKE_V1_PROTOCOL_TASK_COMMOM_H
#include "pake_base_cur_task.h"
#include "json_utils.h"
int32_t InitDasPakeParams(PakeParams *params, const CJson *in);
void DestroyDasPakeParams(PakeParams *params);
int32_t InitDasPakeV1Params(PakeParams *params, const CJson *in);
void DestroyDasPakeV1Params(PakeParams *params);
int32_t FillPskWithDerivedKeyHex(PakeParams *params);
#endif
@@ -13,15 +13,15 @@
* limitations under the License.
*/
#ifndef PAKE_SERVER_PROTOCOL_TASK_H
#define PAKE_SERVER_PROTOCOL_TASK_H
#ifndef PAKE_V1_SERVER_PROTOCOL_TASK_H
#define PAKE_V1_SERVER_PROTOCOL_TASK_H
#include "pake_base_cur_task.h"
typedef struct {
AsyBaseCurTask taskBase;
} PakeProtocolServerTask;
} PakeV1ProtocolServerTask;
AsyBaseCurTask *CreatePakeProtocolServerTask(void);
AsyBaseCurTask *CreatePakeV1ProtocolServerTask(void);
#endif
@@ -13,8 +13,8 @@
* limitations under the License.
*/
#ifndef PAKE_SERVER_TASK_H
#define PAKE_SERVER_TASK_H
#ifndef PAKE_V1_SERVER_TASK_H
#define PAKE_V1_SERVER_TASK_H
#include "json_utils.h"
#include "pake_base_cur_task.h"
@@ -24,8 +24,8 @@ typedef struct {
SubTaskBase taskBase;
PakeParams params;
AsyBaseCurTask *curTask;
} PakeServerTask;
} PakeV1ServerTask;
SubTaskBase *CreatePakeServerTask(const CJson *in, CJson *out);
SubTaskBase *CreatePakeV1ServerTask(const CJson *in);
#endif
@@ -13,14 +13,14 @@
* limitations under the License.
*/
#ifndef PAKE_TASK_MAIN_H
#define PAKE_TASK_MAIN_H
#ifndef PAKE_V1_TASK_MAIN_H
#define PAKE_V1_TASK_MAIN_H
#include "base_sub_task.h"
#include "json_utils.h"
#include "das_module_defines.h"
bool IsSupportPake(void);
SubTaskBase *CreatePakeSubTask(const CJson *in, CJson *out);
bool IsSupportPakeV1(void);
SubTaskBase *CreatePakeV1SubTask(const CJson *in);
#endif
@@ -13,15 +13,15 @@
* limitations under the License.
*/
#ifndef NEW_PAKE_CLIENT_PROTOCOL_TASK_H
#define NEW_PAKE_CLIENT_PROTOCOL_TASK_H
#ifndef PAKE_V2_CLIENT_PROTOCOL_TASK_H
#define PAKE_V2_CLIENT_PROTOCOL_TASK_H
#include "pake_base_cur_task.h"
typedef struct {
AsyBaseCurTask taskBase;
} NewPakeProtocolClientTask;
} PakeV2ProtocolClientTask;
AsyBaseCurTask *CreateNewPakeProtocolClientTask(void);
AsyBaseCurTask *CreatePakeV2ProtocolClientTask(void);
#endif
@@ -13,8 +13,8 @@
* limitations under the License.
*/
#ifndef NEW_PAKE_SERVER_TASK_H
#define NEW_PAKE_SERVER_TASK_H
#ifndef PAKE_V2_CLIENT_TASK_H
#define PAKE_V2_CLIENT_TASK_H
#include "json_utils.h"
#include "pake_base_cur_task.h"
@@ -24,8 +24,8 @@ typedef struct {
SubTaskBase taskBase;
PakeParams params;
AsyBaseCurTask *curTask;
} NewPakeServerTask;
} PakeV2ClientTask;
SubTaskBase *CreateNewPakeServerTask(const CJson *in, CJson *out);
SubTaskBase *CreatePakeV2ClientTask(const CJson *in);
#endif
@@ -13,13 +13,14 @@
* limitations under the License.
*/
#ifndef NEW_PAKE_PROTOCOL_TASK_COMMOM_H
#define NEW_PAKE_PROTOCOL_TASK_COMMOM_H
#ifndef PAKE_V2_PROTOCOL_TASK_COMMOM_H
#define PAKE_V2_PROTOCOL_TASK_COMMOM_H
#include "pake_base_cur_task.h"
#include "json_utils.h"
int32_t InitDasNewPakeParams(PakeParams *params, const CJson *in);
void DestroyDasNewPakeParams(PakeParams *params);
int32_t InitDasPakeV2Params(PakeParams *params, const CJson *in);
void DestroyDasPakeV2Params(PakeParams *params);
int32_t FillPskWithDerivedKey(PakeParams *params);
#endif
@@ -13,15 +13,15 @@
* limitations under the License.
*/
#ifndef NEW_PAKE_SERVER_PROTOCOL_TASK_H
#define NEW_PAKE_SERVER_PROTOCOL_TASK_H
#ifndef PAKE_V2_SERVER_PROTOCOL_TASK_H
#define PAKE_V2_SERVER_PROTOCOL_TASK_H
#include "pake_base_cur_task.h"
typedef struct {
AsyBaseCurTask taskBase;
} NewPakeProtocolServerTask;
} PakeV2ProtocolServerTask;
AsyBaseCurTask *CreateNewPakeProtocolServerTask(void);
AsyBaseCurTask *CreatePakeV2ProtocolServerTask(void);
#endif
@@ -13,8 +13,8 @@
* limitations under the License.
*/
#ifndef NEW_PAKE_CLIENT_TASK_H
#define NEW_PAKE_CLIENT_TASK_H
#ifndef PAKE_V2_SERVER_TASK_H
#define PAKE_V2_SERVER_TASK_H
#include "json_utils.h"
#include "pake_base_cur_task.h"
@@ -24,8 +24,8 @@ typedef struct {
SubTaskBase taskBase;
PakeParams params;
AsyBaseCurTask *curTask;
} NewPakeClientTask;
} PakeV2ServerTask;
SubTaskBase *CreateNewPakeClientTask(const CJson *in, CJson *out);
SubTaskBase *CreatePakeV2ServerTask(const CJson *in);
#endif
@@ -13,14 +13,14 @@
* limitations under the License.
*/
#ifndef NEW_PAKE_TASK_MAIN_H
#define NEW_PAKE_TASK_MAIN_H
#ifndef PAKE_V2_TASK_MAIN_H
#define PAKE_V2_TASK_MAIN_H
#include "base_sub_task.h"
#include "json_utils.h"
#include "das_module_defines.h"
bool IsSupportNewPake(void);
SubTaskBase *CreateNewPakeSubTask(const CJson *in, CJson *out);
bool IsSupportPakeV2(void);
SubTaskBase *CreatePakeV2SubTask(const CJson *in);
#endif
@@ -13,29 +13,33 @@
* limitations under the License.
*/
#include "new_pake_protocol_dl.h"
#include "common_defs.h"
#include "account_module.h"
#include "device_auth_defines.h"
#include "hc_log.h"
#include "pake_defs.h"
#include "protocol_common.h"
uint32_t GetPakeNewDlAlg()
int32_t CheckAccountMsgRepeatability(const CJson *in)
{
return UNSUPPORTED_ALG;
(void)in;
LOGE("Account module is not supported.");
return HC_ERR_NOT_SUPPORT;
}
int32_t GenerateNewDlPakeParams(PakeBaseParams *params, const Uint8Buff *secret)
bool IsAccountSupported(void)
{
(void)params;
(void)secret;
LOGE("NEW-PAKE-DL unsupported.");
return HC_ERROR;
return false;
}
int32_t AgreeNewDlSharedSecret(PakeBaseParams *params, Uint8Buff *sharedSecret)
AuthModuleBase *CreateAccountModule(void)
{
(void)params;
(void)sharedSecret;
LOGE("NEW-PAKE-DL unsupported.");
return HC_ERROR;
LOGE("Account module is not supported.");
return NULL;
}
int32_t ProcessAccountCredentials(int credentialOpCode, const CJson *in, CJson *out)
{
(void)credentialOpCode;
(void)in;
(void)out;
LOGE("Account credentials manager is not supported.");
return HC_ERR_NOT_SUPPORT;
}
@@ -18,7 +18,10 @@
#include "hc_log.h"
#include "hc_types.h"
#include "hc_vector.h"
#include "task_main.h"
#include "das_task_main.h"
#define DAS_CLIENT_STEP_MASK 0xF00F
#define DAS_CLIENT_FIRST_MESSAGE 0x0001
DECLARE_HC_VECTOR(TaskInModuleVec, void *)
IMPLEMENT_HC_VECTOR(TaskInModuleVec, void *, 1)
@@ -26,35 +29,54 @@ IMPLEMENT_HC_VECTOR(TaskInModuleVec, void *, 1)
TaskInModuleVec g_taskInModuleVec;
DasAuthModule g_dasModule = {0};
static int32_t RegisterLocalIdentity(const char *pkgName, const char *serviceType, Uint8Buff *authId, int userType)
static int32_t RegisterDasLocalIdentity(const char *pkgName, const char *serviceType, Uint8Buff *authId, int userType)
{
return RegisterLocalIdentityInTask(pkgName, serviceType, authId, userType);
}
static int32_t UnregisterLocalIdentity(const char *pkgName, const char *serviceType, Uint8Buff *authId, int userType)
static int32_t UnregisterDasLocalIdentity(const char *pkgName, const char *serviceType, Uint8Buff *authId, int userType)
{
return UnregisterLocalIdentityInTask(pkgName, serviceType, authId, userType);
}
static int32_t DeletePeerAuthInfo(const char *pkgName, const char *serviceType, Uint8Buff *authId, int userType)
static int32_t DeleteDasPeerAuthInfo(const char *pkgName, const char *serviceType, Uint8Buff *authId, int userType)
{
return DeletePeerAuthInfoInTask(pkgName, serviceType, authId, userType);
}
static int32_t GetPublicKey(const char *pkgName, const char *serviceType, Uint8Buff *authId, int userType,
static int32_t GetDasPublicKey(const char *pkgName, const char *serviceType, Uint8Buff *authId, int userType,
Uint8Buff *returnPk)
{
return GetPublicKeyInTask(pkgName, serviceType, authId, userType, returnPk);
}
bool IsDasMsgNeedIgnore(const CJson *in)
{
uint32_t message = 0;
if (GetIntFromJson(in, FIELD_MESSAGE, (int *)&message) != HC_SUCCESS) {
LOGD("There is no message code."); // There is no message code in the client's createTask request params
return false;
}
if ((message & DAS_CLIENT_STEP_MASK) == DAS_CLIENT_FIRST_MESSAGE) {
return false;
}
LOGI("The message needs to ignore, message: %u.", message);
return true;
}
static int CreateDasTask(int *taskId, const CJson *in, CJson *out)
{
if (taskId == NULL || in == NULL || out == NULL) {
return HC_ERR_INVALID_PARAMS;
LOGE("Params is null.");
return HC_ERR_NULL_PTR;
}
if (IsDasMsgNeedIgnore(in)) {
return HC_ERR_IGNORE_MSG;
}
Task *task = CreateTaskT(taskId, in, out);
if (task == NULL) {
LOGE("CreateTaskT failed");
LOGE("Create das task failed.");
return HC_ERR_ALLOC_MEMORY;
}
@@ -72,14 +94,18 @@ static void DestroyDasModule(AuthModuleBase *module)
}
}
DESTROY_HC_VECTOR(TaskInModuleVec, &g_taskInModuleVec)
DestroyDasProtocolType();
DestroyDasProtocolEntities();
if (module != NULL) {
(void)memset_s(module, sizeof(AuthModuleBase), 0, sizeof(AuthModuleBase));
(void)memset_s(module, sizeof(DasAuthModule), 0, sizeof(DasAuthModule));
}
}
static int ProcessDasTask(int taskId, const CJson* in, CJson* out, int *status)
{
if (status == NULL || in == NULL || out == NULL) {
LOGE("Params is null.");
return HC_ERR_NULL_PTR;
}
uint32_t index;
void **ptr = NULL;
FOR_EACH_HC_VECTOR(g_taskInModuleVec, index, ptr) {
@@ -90,7 +116,9 @@ static int ProcessDasTask(int taskId, const CJson* in, CJson* out, int *status)
}
}
}
return HC_ERR_TASK_IS_NULL;
LOGE("Task doesn't exist, taskId: %d.", taskId);
return HC_ERR_TASK_ID_IS_NOT_MATCH;
}
static void DestroyDasTask(int taskId)
@@ -110,25 +138,25 @@ static void DestroyDasTask(int taskId)
}
}
bool IsDasSupported()
bool IsDasSupported(void)
{
return true;
}
AuthModuleBase *CreateDasModule()
AuthModuleBase *CreateDasModule(void)
{
g_dasModule.moduleBase.moduleType = DAS_MODULE;
g_dasModule.moduleBase.createTask = CreateDasTask;
g_dasModule.moduleBase.processTask = ProcessDasTask;
g_dasModule.moduleBase.destroyTask = DestroyDasTask;
g_dasModule.moduleBase.destroyModule = DestroyDasModule;
g_dasModule.registerLocalIdentity = RegisterLocalIdentity;
g_dasModule.unregisterLocalIdentity = UnregisterLocalIdentity;
g_dasModule.deletePeerAuthInfo = DeletePeerAuthInfo;
g_dasModule.getPublicKey = GetPublicKey;
g_dasModule.registerLocalIdentity = RegisterDasLocalIdentity;
g_dasModule.unregisterLocalIdentity = UnregisterDasLocalIdentity;
g_dasModule.deletePeerAuthInfo = DeleteDasPeerAuthInfo;
g_dasModule.getPublicKey = GetDasPublicKey;
g_taskInModuleVec = CREATE_HC_VECTOR(TaskInModuleVec)
if (InitDasProtocolType() != HC_SUCCESS) {
LOGE("InitDasProtocolType failed.");
if (InitDasProtocolEntities() != HC_SUCCESS) {
LOGE("Init das protocol entities failed.");
DestroyDasModule((AuthModuleBase *)&g_dasModule);
return NULL;
}
@@ -13,12 +13,13 @@
* limitations under the License.
*/
#include "das_common.h"
#include "das_task_common.h"
#include "alg_defs.h"
#include "alg_loader.h"
#include "device_auth_defines.h"
#include "hc_log.h"
#include "hc_types.h"
#include "module_common.h"
#include "protocol_common.h"
#include "string_util.h"
#define KEY_TYPE_PAIR_LEN 2
@@ -41,24 +42,26 @@ static const uint8_t KEY_TYPE_PAIRS[KEY_ALIAS_TYPE_END][KEY_TYPE_PAIR_LEN] = {
{ 0x00, 0x07 } /* AUTHTOKEN */
};
void SendErrorToOut(CJson *out, int opCode, int errCode)
void DasSendErrorToOut(CJson *out, int 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;
}
CJson *payload = CreateJson();
if (payload == NULL) {
goto err;
LOGE("Create payload json failed.");
goto ERR;
}
int res;
GOTO_ERR_AND_SET_RET(AddIntToJson(sendToSelf, FIELD_AUTH_FORM, AUTH_FORM_ACCOUNT_UNRELATED), res);
GOTO_ERR_AND_SET_RET(AddIntToJson(sendToSelf, FIELD_OPERATION_CODE, opCode), res);
GOTO_ERR_AND_SET_RET(AddIntToJson(sendToSelf, FIELD_ERROR_CODE, errCode), res);
GOTO_ERR_AND_SET_RET(AddIntToJson(payload, FIELD_ERROR_CODE, errCode), res);
@@ -67,35 +70,33 @@ void SendErrorToOut(CJson *out, int opCode, int errCode)
GOTO_ERR_AND_SET_RET(AddObjToJson(out, FIELD_SEND_TO_PEER, sendToPeer), res);
GOTO_ERR_AND_SET_RET(AddObjToJson(out, FIELD_SEND_TO_SELF, sendToSelf), res);
err:
ERR:
FreeJson(sendToPeer);
FreeJson(sendToSelf);
FreeJson(payload);
}
void SendErrMsgToSelf(const CJson *in, CJson *out, int errCode)
void DasSendErrMsgToSelf(CJson *out, int errCode)
{
(void)in;
CJson *sendToSelf = CreateJson();
if (sendToSelf == NULL) {
LOGE("Create sendToSelf json failed.");
return;
}
int res = AddIntToJson(sendToSelf, FIELD_AUTH_FORM, AUTH_FORM_ACCOUNT_UNRELATED);
if (res != 0) {
if (AddIntToJson(sendToSelf, FIELD_AUTH_FORM, AUTH_FORM_ACCOUNT_UNRELATED) != 0) {
FreeJson(sendToSelf);
LOGE("add authForm failed: %d", res);
LOGE("Add authForm failed.");
return;
}
res = AddIntToJson(sendToSelf, FIELD_ERROR_CODE, errCode);
if (res != 0) {
if (AddIntToJson(sendToSelf, FIELD_ERROR_CODE, errCode) != 0) {
FreeJson(sendToSelf);
LOGE("add errCode failed: %d", res);
LOGE("Add errCode failed.");
return;
}
res = AddObjToJson(out, FIELD_SEND_TO_SELF, sendToSelf);
if (res != 0) {
if (AddObjToJson(out, FIELD_SEND_TO_SELF, sendToSelf) != 0) {
FreeJson(sendToSelf);
LOGE("add obj failed :%d", res);
LOGE("Add sendToSelf failed.");
return;
}
FreeJson(sendToSelf);
@@ -104,8 +105,7 @@ void SendErrMsgToSelf(const CJson *in, CJson *out, int errCode)
uint32_t ProtocolMessageIn(const CJson *in)
{
uint32_t message = 0;
int res = GetIntFromJson(in, FIELD_MESSAGE, (int *)&message);
if (res != HC_SUCCESS) {
if (GetIntFromJson(in, FIELD_MESSAGE, (int *)&message) != 0) {
return INVALID_MESSAGE;
}
if (message == ERR_MESSAGE) {
@@ -124,14 +124,19 @@ int ClientProtocolMessageOut(CJson *out, int opCode, uint32_t step)
int res;
switch (opCode) {
case OP_BIND:
case AUTH_KEY_AGREEMENT:
res = AddIntToJson(sendToPeer, FIELD_MESSAGE, step);
break;
default:
case AUTHENTICATE:
case OP_UNBIND:
step = step | MESSAGE_PREFIX;
res = AddIntToJson(sendToPeer, FIELD_MESSAGE, step);
break;
default:
LOGE("Unsupported opCode: %d.", opCode);
return HC_ERR_NOT_SUPPORT;
}
return res;
return (res == 0) ? HC_SUCCESS : HC_ERR_JSON_ADD;
}
int ServerProtocolMessageOut(CJson *out, int opCode, uint32_t step)
@@ -144,16 +149,21 @@ int ServerProtocolMessageOut(CJson *out, int opCode, uint32_t step)
}
switch (opCode) {
case OP_BIND:
case AUTH_KEY_AGREEMENT:
step = step | MESSAGE_RETURN;
res = AddIntToJson(sendToPeer, FIELD_MESSAGE, step);
break;
default:
case AUTHENTICATE:
case OP_UNBIND:
step = step | MESSAGE_RETURN;
step = step | MESSAGE_PREFIX;
res = AddIntToJson(sendToPeer, FIELD_MESSAGE, step);
break;
default:
LOGE("Unsupported opCode: %d.", opCode);
return HC_ERR_NOT_SUPPORT;
}
return res;
return (res == 0) ? HC_SUCCESS : HC_ERR_JSON_ADD;
}
static int32_t CombineServiceId(const Uint8Buff *pkgName, const Uint8Buff *serviceType, Uint8Buff *serviceId)
@@ -165,27 +175,27 @@ static int32_t CombineServiceId(const Uint8Buff *pkgName, const Uint8Buff *servi
if (serviceIdPlain.val == NULL) {
LOGE("malloc serviceIdPlain.val failed.");
res = HC_ERR_ALLOC_MEMORY;
goto err;
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;
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;
goto ERR;
}
res = GetLoaderInstance()->sha256(&serviceIdPlain, serviceId);
if (res != HC_SUCCESS) {
LOGE("Service id Sha256 failed.");
goto err;
goto ERR;
}
err:
ERR:
HcFree(serviceIdPlain.val);
return res;
}
@@ -207,29 +217,29 @@ static int32_t CombineKeyAlias(const Uint8Buff *serviceId, const Uint8Buff *keyT
if (memcpy_s(keyAliasBuff.val, totalLen, serviceId->val, serviceId->length) != EOK) {
LOGE("Copy serviceId failed.");
res = HC_ERR_MEMORY_COPY;
goto err;
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;
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;
goto ERR;
}
res = GetLoaderInstance()->sha256(&keyAliasBuff, keyAliasHash);
if (res != HC_SUCCESS) {
LOGE("Sha256 failed.");
goto err;
goto ERR;
}
err:
ERR:
HcFree(keyAliasBuff.val);
return res;
}
@@ -256,32 +266,32 @@ static int32_t CombineKeyAliasForPake(const Uint8Buff *serviceId, const Uint8Buf
char *outKeyAliasHex = NULL;
if (outKeyAlias->length != SHA256_LEN * BYTE_TO_HEX_OPER_LENGTH) {
res = HC_ERR_INVALID_LEN;
goto err;
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;
goto ERR;
}
res = CombineKeyAlias(serviceId, keyType, authId, &keyAliasHash);
if (res != HC_SUCCESS) {
LOGE("CombineKeyAlias failed.");
goto err;
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;
goto ERR;
}
if (memcpy_s(outKeyAlias->val, outKeyAlias->length, outKeyAliasHex, strlen(outKeyAliasHex)) != EOK) {
LOGE("memcpy outkeyalias failed.");
res = HC_ERR_MEMORY_COPY;
goto err;
goto ERR;
}
err:
ERR:
HcFree(keyAliasHash.val);
HcFree(outKeyAliasHex);
return res;
@@ -299,10 +309,12 @@ int32_t GenerateKeyAlias(const Uint8Buff *pkgName, const Uint8Buff *serviceType,
CHECK_PTR_RETURN_ERROR_CODE(outKeyAlias, "outKeyAlias");
CHECK_PTR_RETURN_ERROR_CODE(outKeyAlias->val, "outKeyAlias->val");
if (pkgName->length == 0 || serviceType->length == 0 || authId->length == 0 || outKeyAlias->length == 0) {
LOGE("Invalid zero length params exist.");
return HC_ERR_INVALID_LEN;
}
if (pkgName->length > PACKAGE_NAME_MAX_LEN || serviceType->length > SERVICE_TYPE_MAX_LEN ||
authId->length > AUTH_ID_MAX_LEN || keyType >= KEY_ALIAS_TYPE_END) {
LOGE("Out of length params exist.");
return HC_ERR_INVALID_LEN;
}
@@ -310,14 +322,14 @@ int32_t GenerateKeyAlias(const Uint8Buff *pkgName, const Uint8Buff *serviceType,
Uint8Buff serviceId = { NULL, SHA256_LEN };
serviceId.val = (uint8_t *)HcMalloc(serviceId.length, 0);
if (serviceId.val == NULL) {
LOGE("malloc serviceId.val failed.");
LOGE("Malloc for serviceId failed.");
res = HC_ERR_ALLOC_MEMORY;
goto err;
goto ERR;
}
res = CombineServiceId(pkgName, serviceType, &serviceId);
if (res != HC_SUCCESS) {
LOGE("CombineServiceId failed.");
goto err;
LOGE("CombineServiceId failed, res: %x.", res);
goto ERR;
}
Uint8Buff keyTypeBuff = { (uint8_t *)KEY_TYPE_PAIRS[keyType], KEY_TYPE_PAIR_LEN };
if (keyType == KEY_ALIAS_AUTH_TOKEN) {
@@ -328,12 +340,12 @@ int32_t GenerateKeyAlias(const Uint8Buff *pkgName, const Uint8Buff *serviceType,
if (res != HC_SUCCESS) {
LOGE("CombineKeyAlias failed, keyType: %d, res: %d", keyType, res);
}
err:
ERR:
HcFree(serviceId.val);
return res;
}
int32_t GetIdPeerForParams(const CJson *in, const char *peerIdKey, const Uint8Buff *authIdSelf, Uint8Buff *authIdPeer)
int32_t GetIdPeer(const CJson *in, const char *peerIdKey, const Uint8Buff *authIdSelf, Uint8Buff *authIdPeer)
{
const char *authIdStr = GetStringFromJson(in, peerIdKey);
if (authIdStr == NULL) {
@@ -342,7 +354,7 @@ int32_t GetIdPeerForParams(const CJson *in, const char *peerIdKey, const Uint8Bu
}
uint32_t authIdLen = HcStrlen(authIdStr) / BYTE_TO_HEX_OPER_LENGTH;
if (authIdLen == 0 || authIdLen > MAX_AUTH_ID_LEN) {
LOGE("Invalid authIdPeerLen.");
LOGE("Invalid authIdPeerLen: %u.", authIdLen);
return HC_ERR_INVALID_LEN;
}
int32_t res = InitSingleParam(authIdPeer, authIdLen);
@@ -385,7 +397,7 @@ int32_t GetAndCheckAuthIdPeer(const CJson *in, const Uint8Buff *authIdSelf, cons
return HC_ERR_ALLOC_MEMORY;
}
if (HexStringToByte(authIdStr, authIdPeerTmp, authIdPeerLen) != HC_SUCCESS) {
LOGE("Convert peer authId from hex string to byte failed, res: %d.", HC_ERR_CONVERT_FAILED);
LOGE("Convert peer authId from hex string to byte failed.");
HcFree(authIdPeerTmp);
return HC_ERR_CONVERT_FAILED;
}
@@ -409,11 +421,11 @@ int32_t GetAuthIdPeerFromPayload(const CJson *in, const Uint8Buff *authIdSelf, U
const CJson *payload = GetObjFromJson(in, FIELD_PAYLOAD);
if (payload == NULL) {
LOGE("Not have payload.");
return HC_ERR_INVALID_PARAMS;
return HC_ERR_JSON_GET;
}
int res = GetIdPeerForParams(payload, FIELD_PEER_AUTH_ID, authIdSelf, authIdPeer);
int res = GetIdPeer(payload, FIELD_PEER_AUTH_ID, authIdSelf, authIdPeer);
if (res != HC_SUCCESS) {
LOGE("GetIdPeerForParams failed, res: %d.", res);
LOGE("GetIdPeer failed, res: %d.", res);
}
return res;
}
@@ -426,9 +438,8 @@ int32_t GetAndCheckKeyLenOnServer(const CJson *in, uint32_t *keyLen)
return HC_ERR_JSON_GET;
}
uint32_t tmpKeyLen = 0;
int32_t res = GetIntFromJson(payload, FIELD_KEY_LENGTH, (int *)&tmpKeyLen);
if (res != HC_SUCCESS) {
LOGE("Get tmpKeyLen from payload failed, res: %d.", res);
if (GetIntFromJson(payload, FIELD_KEY_LENGTH, (int *)&tmpKeyLen) != HC_SUCCESS) {
LOGE("Get tmpKeyLen from payload failed.");
return HC_ERR_JSON_GET;
}
@@ -436,5 +447,5 @@ int32_t GetAndCheckKeyLenOnServer(const CJson *in, uint32_t *keyLen)
LOGE("Key length is not equal.");
return HC_ERR_INVALID_PARAMS;
}
return res;
return HC_SUCCESS;
}
@@ -13,36 +13,36 @@
* limitations under the License.
*/
#include "task_main.h"
#include "das_task_main.h"
#include "alg_loader.h"
#include "base_sub_task.h"
#include "das_asy_token_manager.h"
#include "das_common.h"
#include "das_lite_token_manager.h"
#include "das_standard_token_manager.h"
#include "das_task_common.h"
#include "hc_log.h"
#include "iso_task_main.h"
#include "new_pake_protocol_dl.h"
#include "new_pake_protocol_ec.h"
#include "new_pake_task_main.h"
#include "pake_protocol_dl.h"
#include "pake_protocol_ec.h"
#include "pake_task_main.h"
#include "pake_v2_task_main.h"
#include "pake_protocol_dl_common.h"
#include "pake_protocol_ec_common.h"
#include "pake_v1_task_main.h"
#include "protocol_common.h"
typedef struct DasProtocolTypeT {
typedef struct DasProtocolEntityT {
ProtocolType type;
uint32_t algInProtocol;
const TokenManager *tokenManagerInstance;
SubTaskBase *(*createSubTask)(const CJson *, CJson *);
} DasProtocolType;
IMPLEMENT_HC_VECTOR(SubTaskVec, void *, 1)
DECLARE_HC_VECTOR(DasProtocolTypeVec, void *)
IMPLEMENT_HC_VECTOR(DasProtocolTypeVec, void *, 1)
SubTaskBase *(*createSubTask)(const CJson *);
} DasProtocolEntity;
DasProtocolTypeVec g_protocolTypeVec;
ProtocolType g_subTaskTypeToAlgType[] = {
IMPLEMENT_HC_VECTOR(SubTaskVec, void *, 1)
DECLARE_HC_VECTOR(DasProtocolEntityVec, void *)
IMPLEMENT_HC_VECTOR(DasProtocolEntityVec, void *, 1)
DasProtocolEntityVec g_protocolEntityVec;
ProtocolType g_taskTypeToProtocolType[] = {
ISO, // TASK_TYPE_ISO_PROTOCOL = 0,
PAKE, // TASK_TYPE_PAKE_PROTOCOL = 1,
NEW_PAKE // TASK_TYPE_NEW_PAKE_PROTOCOL = 2,
PAKE_V1, // TASK_TYPE_PAKE_V1_PROTOCOL = 1,
PAKE_V2 // TASK_TYPE_PAKE_V2_PROTOCOL = 2,
};
static void GetMinVersion(VersionStruct *version)
@@ -54,15 +54,15 @@ static void GetMinVersion(VersionStruct *version)
static void GetMaxVersion(VersionStruct *version)
{
version->first = VERSION_FIRST_BIT;
version->first = MAJOR_VERSION_NO;
version->second = 0;
version->third = 0;
uint32_t index;
void **ptr = NULL;
FOR_EACH_HC_VECTOR(g_protocolTypeVec, index, ptr) {
FOR_EACH_HC_VECTOR(g_protocolEntityVec, index, ptr) {
if (ptr != NULL && *ptr != NULL) {
DasProtocolType *temp = (DasProtocolType *)(*ptr);
DasProtocolEntity *temp = (DasProtocolEntity *)(*ptr);
version->third = (version->third) | temp->algInProtocol;
}
}
@@ -79,7 +79,7 @@ static int AddVersionToOut(const VersionInfo *versionInfo, CJson *out)
{
CJson *payload = GetObjFromJson(out, FIELD_PAYLOAD);
if (payload == NULL) {
LOGD("not find payload");
LOGD("Not find payload.");
return HC_SUCCESS;
}
return AddVersionToJson(payload, &(versionInfo->minVersion), &(versionInfo->curVersion));
@@ -98,40 +98,20 @@ static int CombineJson(CJson *desObj, const CJson *srcObj)
if (strcmp(key, FIELD_PAYLOAD) == 0 && payload != NULL) {
res = CombineJson(payload, item);
if (res != HC_SUCCESS) {
LOGE("combine payload failed");
LOGE("Combine payload failed, res: %x.", res);
return res;
}
} else {
res = AddObjToJson(desObj, key, item);
if (res != HC_SUCCESS) {
LOGE("AddObjToJson failed");
return res;
if (AddObjToJson(desObj, key, item) != HC_SUCCESS) {
LOGE("AddObjToJson failed.");
return HC_ERR_JSON_ADD;
}
}
}
return res;
}
static int AddErrToOut(CJson *out, const CJson *err)
{
CJson *sendToPeer = GetObjFromJson(err, FIELD_SEND_TO_PEER);
if (sendToPeer != NULL) {
if (AddObjToJson(out, FIELD_SEND_TO_PEER, sendToPeer) != HC_SUCCESS) {
LOGE("Add sendToPeer to json failed.");
return HC_ERR_JSON_ADD;
}
}
CJson *sendToSelf = GetObjFromJson(err, FIELD_SEND_TO_PEER);
if (sendToSelf != NULL) {
if (AddObjToJson(out, FIELD_SEND_TO_SELF, sendToSelf) != HC_SUCCESS) {
LOGE("Add sendToSelf to json failed.");
return HC_ERR_JSON_ADD;
}
}
return HC_SUCCESS;
}
static void DestroyTask(Task *task)
static void DestroyTaskT(Task *task)
{
if (task == NULL) {
return;
@@ -154,38 +134,42 @@ static int ProcessMultiTask(Task *task, const CJson *in, CJson *out, int *status
void **ptr = NULL;
CJson *tmpOut = NULL;
CJson *combinedSendToPeer = CreateJson();
if (combinedSendToPeer == NULL) {
LOGE("Create combinedSendToPeer failed.");
return HC_ERR_JSON_CREATE;
}
FOR_EACH_HC_VECTOR(task->vec, index, ptr) {
if ((ptr == NULL) || (*ptr == NULL)) {
LOGD("Null ptr in subTask vector.");
continue;
}
tmpOut = CreateJson();
if (tmpOut == NULL) {
LOGE("Create tmpOut failed.");
res = HC_ERR_JSON_CREATE;
goto ERR;
}
res = ((SubTaskBase *)(*ptr))->process((*ptr), in, tmpOut, status);
if (res != HC_SUCCESS) {
LOGE("process SubTaskBase failed, index: %u", index);
res = AddErrToOut(out, tmpOut);
if (res != HC_SUCCESS) {
LOGE("AddErrToOut failed");
goto err;
}
goto err;
LOGE("Process subTask failed, index: %u, res: %x.", index, res);
goto ERR;
}
CJson *tmpSendToPeer = GetObjFromJson(tmpOut, FIELD_SEND_TO_PEER);
res = CombineJson(combinedSendToPeer, tmpSendToPeer);
if (res != HC_SUCCESS) {
LOGE("CombineJson failed");
goto err;
LOGE("CombineJson failed, res: %x.", res);
goto ERR;
}
FreeJson(tmpOut);
tmpOut = NULL;
}
res = AddObjToJson(out, FIELD_SEND_TO_PEER, combinedSendToPeer);
if (res != HC_SUCCESS) {
LOGE("AddObjToJson failed");
goto err;
if (AddObjToJson(out, FIELD_SEND_TO_PEER, combinedSendToPeer) != HC_SUCCESS) {
LOGE("Add combinedSendToPeer to json object failed.");
res = HC_ERR_JSON_ADD;
goto ERR;
}
err:
ERR:
FreeJson(combinedSendToPeer);
FreeJson(tmpOut);
return res;
@@ -197,27 +181,27 @@ static int NegotiateAndProcessTask(Task *task, const CJson *in, CJson *out, int
VersionStruct minVersionPeer = { 0, 0, 0 };
int res = GetVersionFromJson(in, &minVersionPeer, &curVersionPeer);
if (res != HC_SUCCESS) {
LOGE("Get peer version info failed");
LOGE("Get peer version info failed, res: %x.", res);
return res;
}
res = NegotiateVersion(&minVersionPeer, &curVersionPeer, &(task->versionInfo.curVersion));
if (res != HC_SUCCESS) {
LOGE("NegotiateVersion failed");
LOGE("NegotiateVersion failed, res: %x.", res);
return res;
}
if (!IsVersionEqual(&(task->versionInfo.curVersion), &curVersionPeer)) {
LOGE("Negotiated version not equal");
LOGE("Negotiated version is not matched with peer.");
return HC_ERR_UNSUPPORTED_VERSION;
}
ProtocolType protocolType = GetPrototolType(&(task->versionInfo.curVersion), task->versionInfo.opCode);
LOGI("Client select protocolType:%d", protocolType);
LOGI("Client select protocolType: %d", protocolType);
SubTaskBase *subTask = NULL;
uint32_t index = 0;
void **ptr = task->vec.getp(&(task->vec), 0);
while (index < task->vec.size(&(task->vec)) && ptr != NULL) {
SubTaskBase *temp = (SubTaskBase *)(*ptr);
if (g_subTaskTypeToAlgType[temp->getTaskType(temp)] == protocolType) {
if (g_taskTypeToProtocolType[temp->getTaskType(temp)] == protocolType) {
subTask = temp;
index++;
} else {
@@ -227,93 +211,97 @@ static int NegotiateAndProcessTask(Task *task, const CJson *in, CJson *out, int
ptr = task->vec.getp(&(task->vec), index);
}
if (subTask == NULL) {
LOGE("Can't find subTask.");
LOGE("Can't find matched subTask.");
return HC_ERR_NOT_SUPPORT;
}
subTask->curVersion = task->versionInfo.curVersion;
res = subTask->process(subTask, in, out, status);
if (res != HC_SUCCESS) {
LOGE("Process subTask failed");
return res;
LOGE("Process subTask failed, res: %x.", res);
}
return res;
}
static bool IsPeerErrMessage(const CJson *in, CJson *out, int32_t *res)
static bool IsPeerErrMessage(const CJson *in, int32_t *res)
{
int message = 0;
if (GetIntFromJson(in, FIELD_MESSAGE, &message) != HC_SUCCESS) {
LOGD("Get message code failed.");
LOGD("There is no message code.");
return false;
}
if (message != ERR_MESSAGE) {
return false;
}
LOGE("Receive error message from peer.");
if (GetIntFromJson(in, FIELD_ERROR_CODE, res) != HC_SUCCESS) {
LOGE("Get error code failed.");
LOGE("Get peer error code failed.");
}
SendErrMsgToSelf(in, out, *res); /* when receive peer ERR_MESSAGE, only need to inform self */
return true;
}
static int ProcessTask(Task *task, const CJson *in, CJson *out, int *status)
static int ProcessTaskT(Task *task, const CJson *in, CJson *out, int *status)
{
if (task == NULL || in == NULL || out == NULL || status == NULL) {
return HC_ERR_INVALID_PARAMS;
int res;
if (IsPeerErrMessage(in, &res)) {
LOGE("Receive error message from peer, errCode: %x.", res);
DasSendErrMsgToSelf(out, HC_ERR_PEER_ERROR);
return HC_ERR_PEER_ERROR;
}
if (task->vec.size(&(task->vec)) == 0) {
LOGE("not has subTask");
return HC_ERROR;
}
int res = HC_ERROR;
if (IsPeerErrMessage(in, out, &res)) {
LOGE("Peer message is error message.");
return res;
LOGE("Task hasn't subTask.");
res = HC_ERR_TASK_IS_NULL;
goto ERR;
}
if (task->versionInfo.versionStatus == INITIAL) {
res = ProcessMultiTask(task, in, out, status);
if (res != HC_SUCCESS) {
LOGE("ProcessMultiTask failed");
return res;
LOGE("ProcessMultiTask failed, res: %x.", res);
goto ERR;
}
task->versionInfo.versionStatus = VERSION_CONFIRM;
} else if (task->versionInfo.versionStatus == VERSION_CONFIRM) {
res = NegotiateAndProcessTask(task, in, out, status);
if (res != HC_SUCCESS) {
LOGE("NegotiateAndProcessTask failed.");
return res;
LOGE("NegotiateAndProcessTask failed, res: %x.", res);
goto ERR;
}
task->versionInfo.versionStatus = VERSION_DECIDED;
} else {
SubTaskBase *subTask = HC_VECTOR_GET(&(task->vec), 0);
res = subTask->process(subTask, in, out, status);
if (res != HC_SUCCESS) {
LOGE("Process subTask failed");
return res;
LOGE("Process subTask failed, res: %x.", res);
goto ERR;
}
}
res = AddVersionToOut(&(task->versionInfo), out);
if (res != HC_SUCCESS) {
LOGE("AddVersionToOut failed");
LOGE("AddVersionToOut failed, res: %x.", res);
goto ERR;
}
return res;
ERR:
if (task->versionInfo.versionStatus == INITIAL) {
DasSendErrMsgToSelf(out, res);
} else {
DasSendErrorToOut(out, res);
}
return res;
}
static int CreateMultiSubTask(Task *task, const CJson *in, CJson *out)
static int CreateMultiSubTask(Task *task, const CJson *in)
{
InitVersionInfo(&(task->versionInfo));
uint32_t index;
void **ptr = NULL;
FOR_EACH_HC_VECTOR(g_protocolTypeVec, index, ptr) {
FOR_EACH_HC_VECTOR(g_protocolEntityVec, index, ptr) {
if (ptr != NULL && (*ptr) != NULL) {
DasProtocolType *temp = (DasProtocolType *)(*ptr);
SubTaskBase *subTask = temp->createSubTask(in, out);
DasProtocolEntity *temp = (DasProtocolEntity *)(*ptr);
SubTaskBase *subTask = temp->createSubTask(in);
if (subTask == NULL) {
LOGE("Create subTask failed");
LOGE("Create subTask failed, protocolType: %d.", temp->type);
return HC_ERR_ALLOC_MEMORY;
}
subTask->curVersion = task->versionInfo.curVersion;
@@ -323,37 +311,34 @@ static int CreateMultiSubTask(Task *task, const CJson *in, CJson *out)
return HC_SUCCESS;
}
static int CreateSingleSubTask(Task *task, const CJson *in, CJson *out)
static int CreateSingleSubTask(Task *task, const CJson *in)
{
VersionStruct curVersionPeer = { 0, 0, 0 };
VersionStruct minVersionPeer = { 0, 0, 0 };
int res = GetVersionFromJson(in, &minVersionPeer, &curVersionPeer);
if (res != HC_SUCCESS) {
LOGE("Get peer version info failed");
LOGE("Get peer version info failed, res: %x.", res);
return res;
}
InitVersionInfo(&(task->versionInfo));
res = NegotiateVersion(&minVersionPeer, &curVersionPeer, &(task->versionInfo.curVersion));
if (res != HC_SUCCESS) {
LOGE("NegotiateVersion failed");
LOGE("NegotiateVersion failed, res: %x.", res);
return res;
}
task->versionInfo.versionStatus = VERSION_DECIDED;
ProtocolType protocolType = GetPrototolType(&(task->versionInfo.curVersion), task->versionInfo.opCode);
LOGI("Server create protocolType:%d", protocolType);
LOGI("Server select protocolType: %d", protocolType);
uint32_t index;
void **ptr = NULL;
FOR_EACH_HC_VECTOR(g_protocolTypeVec, index, ptr) {
if ((ptr == NULL) || ((*ptr) == NULL)) {
continue;
}
DasProtocolType *temp = (DasProtocolType *)(*ptr);
if (temp->type == protocolType) {
SubTaskBase *subTask = temp->createSubTask(in, out);
FOR_EACH_HC_VECTOR(g_protocolEntityVec, index, ptr) {
if (ptr != NULL && (*ptr) != NULL && (((DasProtocolEntity *)(*ptr))->type == protocolType)) {
DasProtocolEntity *temp = (DasProtocolEntity *)(*ptr);
SubTaskBase *subTask = temp->createSubTask(in);
if (subTask == NULL) {
LOGE("Create subTask failed");
LOGE("Create subTask failed.");
return HC_ERR_ALLOC_MEMORY;
}
subTask->curVersion = task->versionInfo.curVersion;
@@ -368,49 +353,54 @@ static int CreateSingleSubTask(Task *task, const CJson *in, CJson *out)
Task *CreateTaskT(int *taskId, const CJson *in, CJson *out)
{
if (taskId == NULL || in == NULL || out == NULL) {
return NULL;
int res;
Task *task = NULL;
bool isClient = true;
if (GetBoolFromJson(in, FIELD_IS_CLIENT, &isClient) != HC_SUCCESS) {
LOGE("Get isClient failed.");
res = HC_ERR_JSON_GET;
goto ERR;
}
Task *task = (Task *)HcMalloc(sizeof(Task), 0);
task = (Task *)HcMalloc(sizeof(Task), 0);
if (task == NULL) {
return NULL;
LOGE("Malloc for das task failed.");
res = HC_ERR_ALLOC_MEMORY;
goto ERR;
}
task->vec = CREATE_HC_VECTOR(SubTaskVec)
task->destroyTask = DestroyTask;
task->processTask = ProcessTask;
const AlgLoader *loader = GetLoaderInstance();
if (loader == NULL) {
DestroyTask(task);
return NULL;
}
task->destroyTask = DestroyTaskT;
task->processTask = ProcessTaskT;
Uint8Buff taskIdBuf = { (uint8_t *)taskId, sizeof(int) };
int res = loader->generateRandom(&taskIdBuf);
res = GetLoaderInstance()->generateRandom(&taskIdBuf);
if (res != 0) {
DestroyTask(task);
return NULL;
LOGE("Generate taskId failed.");
goto ERR;
}
task->taskId = *taskId;
if (GetIntFromJson(in, FIELD_OPERATION_CODE, &(task->versionInfo.opCode)) != HC_SUCCESS) {
LOGE("Get opcode failed.");
DestroyTask(task);
return NULL;
}
bool isClient = true;
if (GetBoolFromJson(in, FIELD_IS_CLIENT, &isClient) != HC_SUCCESS) {
LOGE("Get isClient failed.");
DestroyTask(task);
return NULL;
res = HC_ERR_JSON_GET;
goto ERR;
}
if (isClient) {
res = CreateMultiSubTask(task, in, out);
res = CreateMultiSubTask(task, in);
} else {
res = CreateSingleSubTask(task, in, out);
res = CreateSingleSubTask(task, in);
}
if (res != 0) {
DestroyTask(task);
return NULL;
if (res != HC_SUCCESS) {
LOGE("Create sub task failed, res: %x.", res);
goto ERR;
}
return task;
ERR:
if (isClient) {
DasSendErrMsgToSelf(out, res);
} else {
DasSendErrorToOut(out, res);
}
DestroyTaskT(task);
return NULL;
}
int32_t RegisterLocalIdentityInTask(const char *pkgName, const char *serviceType, Uint8Buff *authId, int userType)
@@ -418,9 +408,9 @@ int32_t RegisterLocalIdentityInTask(const char *pkgName, const char *serviceType
int32_t res = HC_SUCCESS;
uint32_t index;
void **ptr = NULL;
FOR_EACH_HC_VECTOR(g_protocolTypeVec, index, ptr) {
FOR_EACH_HC_VECTOR(g_protocolEntityVec, index, ptr) {
if (ptr != NULL && (*ptr) != NULL) {
DasProtocolType *temp = (DasProtocolType *)(*ptr);
DasProtocolEntity *temp = (DasProtocolEntity *)(*ptr);
if ((temp->tokenManagerInstance == NULL) || (temp->tokenManagerInstance->registerLocalIdentity == NULL)) {
LOGD("Protocol type: %d, unsupported method!", temp->type);
continue;
@@ -440,9 +430,9 @@ int32_t UnregisterLocalIdentityInTask(const char *pkgName, const char *serviceTy
int32_t res = HC_SUCCESS;
uint32_t index;
void **ptr = NULL;
FOR_EACH_HC_VECTOR(g_protocolTypeVec, index, ptr) {
FOR_EACH_HC_VECTOR(g_protocolEntityVec, index, ptr) {
if (ptr != NULL && (*ptr) != NULL) {
DasProtocolType *temp = (DasProtocolType *)(*ptr);
DasProtocolEntity *temp = (DasProtocolEntity *)(*ptr);
if ((temp->tokenManagerInstance == NULL) || (temp->tokenManagerInstance->unregisterLocalIdentity == NULL)) {
LOGD("Protocol type: %d, unsupported method!", temp->type);
continue;
@@ -462,9 +452,9 @@ int32_t DeletePeerAuthInfoInTask(const char *pkgName, const char *serviceType, U
int32_t res = HC_SUCCESS;
uint32_t index;
void **ptr = NULL;
FOR_EACH_HC_VECTOR(g_protocolTypeVec, index, ptr) {
FOR_EACH_HC_VECTOR(g_protocolEntityVec, index, ptr) {
if (ptr != NULL && (*ptr) != NULL) {
DasProtocolType *temp = (DasProtocolType *)(*ptr);
DasProtocolEntity *temp = (DasProtocolEntity *)(*ptr);
if ((temp->tokenManagerInstance == NULL) || (temp->tokenManagerInstance->deletePeerAuthInfo == NULL)) {
LOGD("Protocol type: %d, unsupported method!", temp->type);
continue;
@@ -484,9 +474,9 @@ int32_t GetPublicKeyInTask(const char *pkgName, const char *serviceType, Uint8Bu
{
uint32_t index;
void **ptr = NULL;
FOR_EACH_HC_VECTOR(g_protocolTypeVec, index, ptr) {
FOR_EACH_HC_VECTOR(g_protocolEntityVec, index, ptr) {
if (ptr != NULL && (*ptr) != NULL) {
DasProtocolType *temp = (DasProtocolType *)(*ptr);
DasProtocolEntity *temp = (DasProtocolEntity *)(*ptr);
if ((temp->tokenManagerInstance == NULL) || (temp->tokenManagerInstance->getPublicKey == NULL)) {
LOGD("Protocol type: %d, unsupported method!", temp->type);
continue;
@@ -498,58 +488,74 @@ int32_t GetPublicKeyInTask(const char *pkgName, const char *serviceType, Uint8Bu
return HC_ERR_NOT_SUPPORT;
}
int32_t InitDasProtocolType(void)
static uint32_t GetPakeAlgInProtocol(int offset)
{
g_protocolTypeVec = CREATE_HC_VECTOR(DasProtocolTypeVec)
DasProtocolType *protocol = NULL;
uint32_t algInProtocol = PSK_SPEKE;
#ifdef P2P_PAKE_DL_TYPE
algInProtocol |= (GetPakeDlAlg() << offset);
#endif
#ifdef P2P_PAKE_EC_TYPE
algInProtocol |= (GetPakeEcAlg() << offset);
#endif
(void)offset;
return algInProtocol;
}
int32_t InitDasProtocolEntities(void)
{
g_protocolEntityVec = CREATE_HC_VECTOR(DasProtocolEntityVec)
DasProtocolEntity *protocol = NULL;
if (IsIsoSupported()) {
protocol = (DasProtocolType *)HcMalloc(sizeof(DasProtocolType), 0);
protocol = (DasProtocolEntity *)HcMalloc(sizeof(DasProtocolEntity), 0);
if (protocol == NULL) {
LOGE("Malloc for Iso dasProtocolEntity failed.");
return HC_ERR_ALLOC_MEMORY;
}
protocol->type = ISO;
protocol->algInProtocol = ISO_ALG;
protocol->createSubTask = CreateIsoSubTask;
protocol->tokenManagerInstance = GetSymTokenManagerInstance();
g_protocolTypeVec.pushBackT(&g_protocolTypeVec, (void *)protocol);
protocol->tokenManagerInstance = GetLiteTokenManagerInstance();
g_protocolEntityVec.pushBackT(&g_protocolEntityVec, (void *)protocol);
}
if (IsSupportPake()) {
protocol = (DasProtocolType *)HcMalloc(sizeof(DasProtocolType), 0);
if (IsSupportPakeV1()) {
protocol = (DasProtocolEntity *)HcMalloc(sizeof(DasProtocolEntity), 0);
if (protocol == NULL) {
LOGE("Malloc for pake v1 dasProtocolEntity failed.");
return HC_ERR_ALLOC_MEMORY;
}
protocol->type = PAKE;
protocol->algInProtocol = GetPakeEcAlg() | GetPakeDlAlg() | PSK_SPEKE;
protocol->createSubTask = CreatePakeSubTask;
protocol->tokenManagerInstance = GetAsyTokenManagerInstance();
g_protocolTypeVec.pushBackT(&g_protocolTypeVec, (void *)protocol);
protocol->type = PAKE_V1;
protocol->algInProtocol = GetPakeAlgInProtocol(ALG_OFFSET_FOR_PAKE_V1);
protocol->createSubTask = CreatePakeV1SubTask;
protocol->tokenManagerInstance = GetStandardTokenManagerInstance();
g_protocolEntityVec.pushBackT(&g_protocolEntityVec, (void *)protocol);
}
if (IsSupportNewPake()) {
protocol = (DasProtocolType *)HcMalloc(sizeof(DasProtocolType), 0);
if (IsSupportPakeV2()) {
protocol = (DasProtocolEntity *)HcMalloc(sizeof(DasProtocolEntity), 0);
if (protocol == NULL) {
LOGE("Malloc for pake v2 dasProtocolEntity failed.");
return HC_ERR_ALLOC_MEMORY;
}
protocol->type = NEW_PAKE;
protocol->algInProtocol = GetPakeNewEcAlg() | GetPakeNewDlAlg() | PSK_SPEKE;
protocol->createSubTask = CreateNewPakeSubTask;
protocol->tokenManagerInstance = GetAsyTokenManagerInstance();
g_protocolTypeVec.pushBackT(&g_protocolTypeVec, (void *)protocol);
protocol->type = PAKE_V2;
protocol->algInProtocol = GetPakeAlgInProtocol(ALG_OFFSET_FOR_PAKE_V2);
protocol->createSubTask = CreatePakeV2SubTask;
protocol->tokenManagerInstance = GetStandardTokenManagerInstance();
g_protocolEntityVec.pushBackT(&g_protocolEntityVec, (void *)protocol);
}
return HC_SUCCESS;
}
void DestroyDasProtocolType(void)
void DestroyDasProtocolEntities(void)
{
uint32_t index;
void **ptr = NULL;
FOR_EACH_HC_VECTOR(g_protocolTypeVec, index, ptr) {
FOR_EACH_HC_VECTOR(g_protocolEntityVec, index, ptr) {
if (ptr != NULL && *ptr != NULL) {
HcFree((DasProtocolType *)(*ptr));
HcFree((DasProtocolEntity *)(*ptr));
*ptr = NULL;
}
}
DESTROY_HC_VECTOR(DasProtocolTypeVec, &g_protocolTypeVec)
DESTROY_HC_VECTOR(DasProtocolEntityVec, &g_protocolEntityVec)
}
@@ -30,15 +30,15 @@ typedef struct PriorityMapT {
VersionStruct g_defaultVersion = { 1, 0, 0 };
PriorityMap g_bindPriorityList[BIND_PRIORITY_LEN] = {
{ NEW_EC_SPEKE, NEW_PAKE },
{ NEW_DL_SPEKE, NEW_PAKE },
{ EC_SPEKE, PAKE },
{ DL_SPEKE, PAKE },
{ EC_PAKE_V2, PAKE_V2 },
{ DL_PAKE_V2, PAKE_V2 },
{ EC_PAKE_V1, PAKE_V1 },
{ DL_PAKE_V1, PAKE_V1 },
{ ISO_ALG, ISO }
};
PriorityMap g_authPriorityList[AUTH_PRIORITY_LEN] = {
{ PSK_SPEKE | NEW_EC_SPEKE, NEW_PAKE },
{ PSK_SPEKE | EC_SPEKE, PAKE },
{ PSK_SPEKE | EC_PAKE_V2, PAKE_V2 },
{ PSK_SPEKE | EC_PAKE_V1, PAKE_V1 },
{ ISO_ALG, ISO }
};
@@ -53,9 +53,10 @@ int32_t GetVersionFromJson(const CJson* jsonObj, VersionStruct *minVer, VersionS
const char *maxStr = GetStringFromJson(jsonObj, FIELD_CURRENT_VERSION);
CHECK_PTR_RETURN_ERROR_CODE(maxStr, "maxStr");
int32_t minRet = StringToVersion(minStr, strlen(minStr), minVer);
int32_t maxRet = StringToVersion(maxStr, strlen(maxStr), maxVer);
int32_t minRet = StringToVersion(minStr, minVer);
int32_t maxRet = StringToVersion(maxStr, maxVer);
if (minRet != HC_SUCCESS || maxRet != HC_SUCCESS) {
LOGE("Convert version string to struct failed.");
return HC_ERROR;
}
return HC_SUCCESS;
@@ -127,50 +128,61 @@ int32_t NegotiateVersion(VersionStruct *minVersionPeer, VersionStruct *curVersio
static ProtocolType GetBindPrototolType(VersionStruct *curVersion)
{
if (IsVersionEqual(curVersion, &g_defaultVersion)) {
return PAKE;
} else {
for (int i = 0; i < BIND_PRIORITY_LEN; i++) {
if ((curVersion->third & g_bindPriorityList[i].alg) == g_bindPriorityList[i].alg) {
return g_bindPriorityList[i].type;
}
return PAKE_V1;
}
for (int i = 0; i < BIND_PRIORITY_LEN; i++) {
if ((curVersion->third & g_bindPriorityList[i].alg) == g_bindPriorityList[i].alg) {
return g_bindPriorityList[i].type;
}
}
return UNSUPPORTED;
return PROTOCOL_TYPE_NONE;
}
static ProtocolType GetAuthPrototolType(VersionStruct *curVersion)
{
if (IsVersionEqual(curVersion, &g_defaultVersion)) {
LOGE("Not support STS.");
return UNSUPPORTED;
} else {
for (int i = 0; i < AUTH_PRIORITY_LEN; i++) {
if ((curVersion->third & g_authPriorityList[i].alg) == g_authPriorityList[i].alg) {
return g_authPriorityList[i].type;
}
return PROTOCOL_TYPE_NONE;
}
for (int i = 0; i < AUTH_PRIORITY_LEN; i++) {
if ((curVersion->third & g_authPriorityList[i].alg) == g_authPriorityList[i].alg) {
return g_authPriorityList[i].type;
}
}
return UNSUPPORTED;
return PROTOCOL_TYPE_NONE;
}
ProtocolType GetPrototolType(VersionStruct *curVersion, OperationCode opCode)
{
if (opCode == OP_BIND) {
return GetBindPrototolType(curVersion);
} else {
return GetAuthPrototolType(curVersion);
switch (opCode) {
case OP_BIND:
case AUTH_KEY_AGREEMENT:
return GetBindPrototolType(curVersion);
case AUTHENTICATE:
case OP_UNBIND:
return GetAuthPrototolType(curVersion);
default:
LOGE("Unsupported opCode: %d.", opCode);
}
return PROTOCOL_TYPE_NONE;
}
AlgType GetSupportedPakeAlg(VersionStruct *curVersion)
PakeAlgType GetSupportedPakeAlg(VersionStruct *curVersion, ProtocolType protocolType)
{
return curVersion->third & (DL_SPEKE | EC_SPEKE | PSK_SPEKE | NEW_DL_SPEKE | NEW_EC_SPEKE);
PakeAlgType pakeAlgType = PAKE_ALG_NONE;
if (protocolType == PAKE_V2) {
pakeAlgType = ((curVersion->third & EC_PAKE_V2) >> ALG_OFFSET_FOR_PAKE_V2) |
((curVersion->third & DL_PAKE_V2) >> ALG_OFFSET_FOR_PAKE_V2);
} else if (protocolType == PAKE_V1) {
pakeAlgType = ((curVersion->third & EC_PAKE_V1) >> ALG_OFFSET_FOR_PAKE_V1) |
((curVersion->third & DL_PAKE_V1) >> ALG_OFFSET_FOR_PAKE_V1);
} else {
LOGE("Invalid protocolType: %d.", protocolType);
}
return pakeAlgType;
}
bool IsSupportedPsk(VersionStruct *curVersion)
{
if (curVersion->third & PSK_SPEKE) {
return true;
}
return false;
return ((curVersion->third & PSK_SPEKE) != 0);
}
@@ -14,7 +14,6 @@
*/
#include "iso_client_task.h"
#include "das_common.h"
#include "hc_log.h"
#include "hc_types.h"
#include "iso_client_bind_exchange_task.h"
@@ -26,7 +25,7 @@ static int GetIsoClientTaskType(const struct SubTaskBaseT *task)
{
IsoClientTask *realTask = (IsoClientTask *)task;
if (realTask->curTask == NULL) {
LOGE("cur Task is null");
LOGE("CurTask is null.");
return TASK_TYPE_NONE;
}
return realTask->curTask->getCurTaskType();
@@ -51,21 +50,20 @@ static int CreateNextTask(IsoClientTask *realTask, const CJson *in, CJson *out,
switch (realTask->params.opCode) {
case OP_BIND:
if (realTask->curTask->getCurTaskType() == TASK_TYPE_BIND_LITE_EXCHANGE) {
LOGD("bind exchange task end");
LOGI("Bind exchange task end successfully.");
*status = FINISH;
return HC_SUCCESS;
}
realTask->curTask->destroyTask(realTask->curTask);
realTask->curTask = CreateClientBindExchangeTask(&(realTask->params), in, out, status);
if (realTask->curTask == NULL) {
LOGE("CreateBindExchangeTask failed");
SendErrorToOut(out, realTask->params.opCode, HC_ERROR);
LOGE("CreateBindExchangeTask failed.");
return HC_ERROR;
}
break;
case OP_UNBIND:
if (realTask->curTask->getCurTaskType() == TASK_TYPE_UNBIND_LITE_EXCHANGE) {
LOGD("unbind exchange task end");
LOGI("Unbind exchange task end successfully.");
*status = FINISH;
return HC_SUCCESS;
}
@@ -73,44 +71,38 @@ static int CreateNextTask(IsoClientTask *realTask, const CJson *in, CJson *out,
realTask->curTask = CreateClientUnbindExchangeTask(&(realTask->params), in, out, status);
if (realTask->curTask == NULL) {
LOGE("CreateBindExchangeTask failed");
SendErrorToOut(out, realTask->params.opCode, HC_ERROR);
return HC_ERROR;
}
break;
default:
case AUTHENTICATE:
res = GenEncResult(&(realTask->params), ISO_RESULT_CONFIRM_CMD, out, RESULT_AAD, true);
if (res != HC_SUCCESS) {
LOGE("GenEncResult failed, res:%d", res);
SendErrorToOut(out, realTask->params.opCode, res);
return res;
}
LOGD("Authenticate task end.");
LOGI("Authenticate task end successfully.");
*status = FINISH;
break;
default:
LOGE("Unsupported opCode: %d.", realTask->params.opCode);
res = HC_ERR_NOT_SUPPORT;
}
return res;
}
static int Process(struct SubTaskBaseT *task, const CJson *in, CJson *out, int *status)
{
if (task == NULL || in == NULL || out == NULL || status == NULL) {
return HC_ERR_INVALID_PARAMS;
}
IsoClientTask *realTask = (IsoClientTask *)task;
if (realTask->curTask == NULL) {
LOGE("cur Task is null");
LOGE("CurTask is null.");
return HC_ERROR;
}
int res = realTask->curTask->process(realTask->curTask, &(realTask->params), in, out, status);
if (*status != FINISH) {
if (res != 0) {
SendErrorToOut(out, realTask->params.opCode, res);
}
if (res != HC_SUCCESS) {
LOGE("CurTask process failed, res: %x.", res);
return res;
}
if (res != 0) {
LOGE("process failed, res:%d", res);
SendErrorToOut(out, realTask->params.opCode, res);
if (*status != FINISH) {
return res;
}
return CreateNextTask(realTask, in, out, status);
@@ -120,6 +112,7 @@ SubTaskBase *CreateIsoClientTask(const CJson *in)
{
IsoClientTask *task = (IsoClientTask *)HcMalloc(sizeof(IsoClientTask), 0);
if (task == NULL) {
LOGE("Malloc for IsoClientTask failed.");
return NULL;
}
@@ -128,13 +121,15 @@ SubTaskBase *CreateIsoClientTask(const CJson *in)
task->taskBase.process = Process;
int res = InitIsoParams(&(task->params), in);
if (res != 0) {
if (res != HC_SUCCESS) {
LOGE("InitIsoParams failed, res: %x.", res);
DestroyIsoClientTask((struct SubTaskBaseT *)task);
return NULL;
}
task->curTask = CreateProtocolClientTask();
if (task->curTask == NULL) {
LOGE("CreateProtocolClientTask failed.");
DestroyIsoClientTask((struct SubTaskBaseT *)task);
return NULL;
}
@@ -15,7 +15,7 @@
#include "iso_client_protocol_task.h"
#include "common_defs.h"
#include "das_common.h"
#include "das_task_common.h"
#include "hc_log.h"
#include "hc_types.h"
#include "iso_protocol_common.h"
@@ -35,27 +35,25 @@ static CurTaskType GetTaskType(void)
static void DestroyProtocolClientTask(struct SymBaseCurTaskT *task)
{
IsoProtocolClientTask *realTask = (IsoProtocolClientTask *)task;
if (realTask == NULL) {
return;
}
HcFree(realTask);
HcFree(task);
}
static int IsoClientStartPackData(CJson *out, const IsoParams *params)
{
int res = HC_SUCCESS;
int res;
CJson *payload = NULL;
CJson *sendToPeer = NULL;
payload = CreateJson();
if (payload == NULL) {
res = HC_ERR_ALLOC_MEMORY;
goto err;
LOGE("Create payload json failed.");
res = HC_ERR_JSON_CREATE;
goto ERR;
}
sendToPeer = CreateJson();
if (sendToPeer == NULL) {
res = HC_ERR_ALLOC_MEMORY;
goto err;
LOGE("Create sendToPeer json failed.");
res = HC_ERR_JSON_CREATE;
goto ERR;
}
GOTO_ERR_AND_SET_RET(AddIntToJson(sendToPeer, FIELD_AUTH_FORM, AUTH_FORM_ACCOUNT_UNRELATED), res);
@@ -73,32 +71,32 @@ static int IsoClientStartPackData(CJson *out, const IsoParams *params)
}
GOTO_ERR_AND_SET_RET(AddObjToJson(sendToPeer, FIELD_PAYLOAD, payload), res);
GOTO_ERR_AND_SET_RET(AddObjToJson(out, FIELD_SEND_TO_PEER, sendToPeer), res);
err:
ERR:
FreeJson(payload);
FreeJson(sendToPeer);
return res;
}
static int IsoClientStart(SymBaseCurTask *task, IsoParams *params, const CJson *in, CJson *out, int *status)
static int IsoClientStart(SymBaseCurTask *task, IsoParams *params, CJson *out, int *status)
{
(void)in;
if (task->taskStatus != TASK_STATUS_BEGIN) {
LOGI("The message is repeated, ignore it, status :%d", task->taskStatus);
LOGI("The message is repeated, ignore it, status: %d", task->taskStatus);
*status = IGNORE_MSG;
return HC_SUCCESS;
}
int res;
res = IsoClientGenRandom(&params->baseParams);
int res = IsoClientGenRandom(&params->baseParams);
if (res != 0) {
LOGE("IsoClientGenRandom failed, res: %x.", res);
return res;
}
res = GenerateSeed(params);
if (res != 0) {
LOGE("GenerateSeed failed, res: %x.", res);
return res;
}
res = IsoClientStartPackData(out, params);
if (res != 0) {
LOGE("IsoClientStartPackData failed, res:%d", res);
LOGE("IsoClientStartPackData failed, res: %x.", res);
return res;
}
task->taskStatus = TASK_STATUS_SERVER_RES_TOKEN;
@@ -108,19 +106,21 @@ static int IsoClientStart(SymBaseCurTask *task, IsoParams *params, const CJson *
static int PackDataForCalToken(const IsoParams *params, const Uint8Buff *selfTokenBuf, CJson *out)
{
int res = HC_SUCCESS;
int res;
CJson *payload = NULL;
CJson *sendToPeer = NULL;
sendToPeer = CreateJson();
if (sendToPeer == NULL) {
res = HC_ERR_ALLOC_MEMORY;
goto err;
LOGE("Create sendToPeer json failed.");
res = HC_ERR_JSON_CREATE;
goto ERR;
}
payload = CreateJson();
if (payload == NULL) {
res = HC_ERR_ALLOC_MEMORY;
goto err;
LOGE("Create payload json failed.");
res = HC_ERR_JSON_CREATE;
goto ERR;
}
GOTO_ERR_AND_SET_RET(AddIntToJson(sendToPeer, FIELD_AUTH_FORM, AUTH_FORM_ACCOUNT_UNRELATED), res);
@@ -129,13 +129,13 @@ static int PackDataForCalToken(const IsoParams *params, const Uint8Buff *selfTok
GOTO_ERR_AND_SET_RET(AddByteToJson(payload, FIELD_TOKEN, selfTokenBuf->val, selfTokenBuf->length), res);
GOTO_ERR_AND_SET_RET(AddObjToJson(sendToPeer, FIELD_PAYLOAD, payload), res);
GOTO_ERR_AND_SET_RET(AddObjToJson(out, FIELD_SEND_TO_PEER, sendToPeer), res);
err:
ERR:
FreeJson(payload);
FreeJson(sendToPeer);
return res;
}
static int ParseServerStartMessage(IsoParams *params, const CJson *in, uint8_t *peerToken)
static int ParseServerStartMessage(IsoParams *params, const CJson *in, Uint8Buff *peerToken)
{
if (params->opCode == OP_BIND) {
RETURN_IF_ERR(GetAuthIdPeerFromPayload(in, &(params->baseParams.authIdSelf), &(params->baseParams.authIdPeer)));
@@ -144,7 +144,7 @@ static int ParseServerStartMessage(IsoParams *params, const CJson *in, uint8_t *
}
RETURN_IF_ERR(GetByteFromJson(in, FIELD_ISO_SALT, params->baseParams.randPeer.val,
params->baseParams.randPeer.length));
RETURN_IF_ERR(GetByteFromJson(in, FIELD_TOKEN, peerToken, ISO_TOKEN_LEN));
RETURN_IF_ERR(GetByteFromJson(in, FIELD_TOKEN, peerToken->val, peerToken->length));
RETURN_IF_ERR(GetIntFromJson(in, FIELD_PEER_USER_TYPE, &(params->peerUserType)));
return HC_SUCCESS;
}
@@ -152,112 +152,100 @@ static int ParseServerStartMessage(IsoParams *params, const CJson *in, uint8_t *
static int CalculateTokenClient(SymBaseCurTask *task, IsoParams *params, const CJson *in, CJson *out, int *status)
{
int res;
uint8_t *peerToken = NULL;
uint8_t *selfToken = NULL;
if (task->taskStatus < TASK_STATUS_SERVER_RES_TOKEN) {
LOGE("Invalid taskStatus:%d", task->taskStatus);
LOGE("Invalid taskStatus: %d", task->taskStatus);
return HC_ERR_BAD_MESSAGE;
}
if (task->taskStatus > TASK_STATUS_SERVER_RES_TOKEN) {
LOGI("The message is repeated, ignore it, status :%d", task->taskStatus);
LOGI("The message is repeated, ignore it, status: %d", task->taskStatus);
*status = IGNORE_MSG;
return HC_SUCCESS;
}
// parse message
peerToken = (uint8_t *)HcMalloc(ISO_TOKEN_LEN, 0);
if (peerToken == NULL) {
res = HC_ERR_ALLOC_MEMORY;
goto err;
}
uint8_t peerToken[ISO_TOKEN_LEN] = { 0 };
Uint8Buff peerTokenBuf = { peerToken, ISO_TOKEN_LEN };
selfToken = (uint8_t *)HcMalloc(ISO_TOKEN_LEN, 0);
if (selfToken == NULL) {
res = HC_ERR_ALLOC_MEMORY;
goto err;
}
uint8_t selfToken[ISO_TOKEN_LEN] = { 0 };
Uint8Buff selfTokenBuf = { selfToken, ISO_TOKEN_LEN };
res = ParseServerStartMessage(params, in, peerToken);
res = ParseServerStartMessage(params, in, &peerTokenBuf);
if (res != 0) {
LOGE("ParseServerStartMessage failed, res:%d", res);
goto err;
LOGE("ParseServerStartMessage failed, res: %x.", res);
return res;
}
res = GeneratePsk(in, params);
if (res != 0) {
LOGE("GeneratePsk failed, res:%d", res);
goto err;
LOGE("GeneratePsk failed, res: %x.", res);
return res;
}
// execute
res = IsoClientCheckAndGenToken(&params->baseParams, &peerTokenBuf, &selfTokenBuf);
if (res != HC_SUCCESS) {
LOGE("IsoClientCheckAndGenToken failed, res:%d", res);
goto err;
LOGE("IsoClientCheckAndGenToken failed, res: %x.", res);
return res;
}
// package message
res = PackDataForCalToken(params, &selfTokenBuf, out);
if (res != 0) {
LOGE("PackDataForCalToken failed, res: %d", res);
goto err;
return res;
}
task->taskStatus = TASK_STATUS_GEN_SESSION_KEY;
*status = CONTINUE;
err:
HcFree(peerToken);
HcFree(selfToken);
return res;
}
static int GenerateSessionKey(SymBaseCurTask *task, IsoParams *params, const CJson *in, int *status)
{
if (task->taskStatus < TASK_STATUS_GEN_SESSION_KEY) {
LOGE("Invalid taskStatus:%d", task->taskStatus);
LOGE("Invalid taskStatus: %d", task->taskStatus);
return HC_ERR_BAD_MESSAGE;
}
if (task->taskStatus > TASK_STATUS_GEN_SESSION_KEY) {
LOGI("The message is repeated, ignore it, status :%d", task->taskStatus);
LOGI("The message is repeated, ignore it, status: %d", task->taskStatus);
*status = IGNORE_MSG;
return HC_SUCCESS;
}
uint8_t *hmac = (uint8_t *)HcMalloc(HMAC_LEN, 0);
if (hmac == NULL) {
LOGE("Malloc for hmac failed.");
return HC_ERR_ALLOC_MEMORY;
}
int res = GetByteFromJson(in, FIELD_RETURN_CODE_MAC, hmac, HMAC_LEN);
if (res != 0) {
LOGE("get mac failed, res:%d", res);
goto err;
int res;
if (GetByteFromJson(in, FIELD_RETURN_CODE_MAC, hmac, HMAC_LEN) != 0) {
LOGE("Get hmac from json failed.");
res = HC_ERR_JSON_GET;
goto ERR;
}
// execute
res = IsoClientGenSessionKey(&params->baseParams, 0, hmac, HMAC_LEN);
if (res != 0) {
LOGE("IsoClientGenSessionKey failed, res:%d", res);
goto err;
LOGE("IsoClientGenSessionKey failed, res: %x.", res);
goto ERR;
}
task->taskStatus = TASK_STATUS_FINAL;
*status = FINISH;
err:
ERR:
HcFree(hmac);
return res;
}
static int Process(struct SymBaseCurTaskT *task, IsoParams *params, const CJson *in, CJson *out,
int *status)
static int Process(struct SymBaseCurTaskT *task, IsoParams *params, const CJson *in, CJson *out, int *status)
{
int res;
uint32_t step = ProtocolMessageIn(in);
if (step == INVALID_MESSAGE) {
res = IsoClientStart(task, params, in, out, status);
res = IsoClientStart(task, params, out, status);
step = STEP_ONE;
goto out_func;
goto OUT_FUNC;
}
step = step + 1; /* when receive peer message code, need to do next step */
@@ -272,17 +260,17 @@ static int Process(struct SymBaseCurTaskT *task, IsoParams *params, const CJson
res = HC_ERR_BAD_MESSAGE;
break;
}
out_func:
OUT_FUNC:
if (res != HC_SUCCESS) {
LOGE("Process step:%d failed, res: %x.", step, res);
return res;
}
if (step != STEP_THREE) {
res = ClientProtocolMessageOut(out, params->opCode, step);
if (res != HC_SUCCESS) {
LOGE("ClientProtocolMessageOut failed, res:%d", res);
LOGE("ClientProtocolMessageOut failed, res: %x.", res);
}
}
return res;
}
@@ -290,6 +278,7 @@ SymBaseCurTask *CreateProtocolClientTask(void)
{
IsoProtocolClientTask *task = (IsoProtocolClientTask *)HcMalloc(sizeof(IsoProtocolClientTask), 0);
if (task == NULL) {
LOGE("Malloc for IsoProtocolClientTask failed.");
return NULL;
}
task->taskBase.destroyTask = DestroyProtocolClientTask;
@@ -15,7 +15,7 @@
#include "iso_server_protocol_task.h"
#include "common_defs.h"
#include "das_common.h"
#include "das_task_common.h"
#include "hc_log.h"
#include "hc_types.h"
#include "iso_protocol_common.h"
@@ -36,11 +36,7 @@ static CurTaskType GetTaskType(void)
static void DestroyProtocolServerTask(struct SymBaseCurTaskT *task)
{
IsoProtocolServerTask *realTask = (IsoProtocolServerTask *)task;
if (realTask == NULL) {
return;
}
HcFree(realTask);
HcFree(task);
}
static int PackageServerStartMessage(const IsoParams *params, const Uint8Buff *selfTokenBuf, CJson *out)
@@ -50,13 +46,15 @@ static int PackageServerStartMessage(const IsoParams *params, const Uint8Buff *s
CJson *sendToPeer = NULL;
payload = CreateJson();
if (payload == NULL) {
res = HC_ERR_ALLOC_MEMORY;
goto err;
LOGE("Create payload json failed.");
res = HC_ERR_JSON_CREATE;
goto ERR;
}
sendToPeer = CreateJson();
if (sendToPeer == NULL) {
res = HC_ERR_ALLOC_MEMORY;
goto err;
LOGE("Create sendToPeer json failed.");
res = HC_ERR_JSON_CREATE;
goto ERR;
}
GOTO_ERR_AND_SET_RET(AddByteToJson(payload, FIELD_ISO_SALT, params->baseParams.randSelf.val,
params->baseParams.randSelf.length), res);
@@ -68,7 +66,7 @@ static int PackageServerStartMessage(const IsoParams *params, const Uint8Buff *s
GOTO_ERR_AND_SET_RET(AddIntToJson(sendToPeer, FIELD_AUTH_FORM, AUTH_FORM_ACCOUNT_UNRELATED), res);
GOTO_ERR_AND_SET_RET(AddObjToJson(sendToPeer, FIELD_PAYLOAD, payload), res);
GOTO_ERR_AND_SET_RET(AddObjToJson(out, FIELD_SEND_TO_PEER, sendToPeer), res);
err:
ERR:
FreeJson(payload);
FreeJson(sendToPeer);
return res;
@@ -77,13 +75,14 @@ err:
static int IsoServerStart(SymBaseCurTask *task, IsoParams *params, const CJson *in, CJson *out, int *status)
{
if (task->taskStatus != TASK_STATUS_BEGIN) {
LOGI("The message is repeated, ignore it, status :%d", task->taskStatus);
LOGI("The message is repeated, ignore it, status: %d", task->taskStatus);
*status = IGNORE_MSG;
return HC_SUCCESS;
}
int res;
uint8_t *selfToken = (uint8_t *)HcMalloc(ISO_TOKEN_LEN, 0);
if (selfToken == NULL) {
LOGE("Malloc for selfToken failed.");
return HC_ERR_ALLOC_MEMORY;
}
Uint8Buff selfTokenBuf = { selfToken, ISO_TOKEN_LEN };
@@ -100,23 +99,23 @@ static int IsoServerStart(SymBaseCurTask *task, IsoParams *params, const CJson *
res = GeneratePsk(in, params);
if (res != 0) {
LOGE("Generate psk failed, res:%d", res);
goto err;
goto ERR;
}
res = IsoServerGenRandomAndToken(&params->baseParams, &selfTokenBuf);
if (res != 0) {
LOGE("IsoServerGenRandomAndToken failed, res:%d", res);
goto err;
goto ERR;
}
res = PackageServerStartMessage(params, &selfTokenBuf, out);
if (res != HC_SUCCESS) {
LOGE("PackageServerStartMessage failed.");
goto err;
goto ERR;
}
task->taskStatus = TASK_STATUS_CMD_RES_TOKEN;
*status = CONTINUE;
err:
ERR:
HcFree(selfToken);
return res;
}
@@ -129,13 +128,15 @@ static int PackDataForCalTokenServer(const IsoParams *params, const Uint8Buff *t
sendToPeer = CreateJson();
if (sendToPeer == NULL) {
res = HC_ERR_ALLOC_MEMORY;
goto err;
LOGE("Create sendToPeer json failed.");
res = HC_ERR_JSON_CREATE;
goto ERR;
}
payload = CreateJson();
if (payload == NULL) {
res = HC_ERR_ALLOC_MEMORY;
goto err;
LOGE("Create payload json failed.");
res = HC_ERR_JSON_CREATE;
goto ERR;
}
GOTO_ERR_AND_SET_RET(AddByteToJson(payload, FIELD_PEER_AUTH_ID, params->baseParams.authIdSelf.val,
params->baseParams.authIdSelf.length), res);
@@ -144,7 +145,7 @@ static int PackDataForCalTokenServer(const IsoParams *params, const Uint8Buff *t
GOTO_ERR_AND_SET_RET(AddIntToJson(sendToPeer, FIELD_AUTH_FORM, AUTH_FORM_ACCOUNT_UNRELATED), res);
GOTO_ERR_AND_SET_RET(AddObjToJson(sendToPeer, FIELD_PAYLOAD, payload), res);
GOTO_ERR_AND_SET_RET(AddObjToJson(out, FIELD_SEND_TO_PEER, sendToPeer), res);
err:
ERR:
FreeJson(payload);
FreeJson(sendToPeer);
return res;
@@ -157,12 +158,12 @@ static int CalTokenAndGenSessionKey(SymBaseCurTask *task, IsoParams *params, con
uint8_t *tokenSelf = NULL;
if (task->taskStatus < TASK_STATUS_CMD_RES_TOKEN) {
LOGE("Invalid taskStatus:%d", task->taskStatus);
LOGE("Invalid taskStatus: %d", task->taskStatus);
return HC_ERR_BAD_MESSAGE;
}
if (task->taskStatus > TASK_STATUS_CMD_RES_TOKEN) {
LOGI("The message is repeated, ignore it, status :%d", task->taskStatus);
LOGI("The message is repeated, ignore it, status: %d", task->taskStatus);
*status = IGNORE_MSG;
return HC_SUCCESS;
}
@@ -170,16 +171,18 @@ static int CalTokenAndGenSessionKey(SymBaseCurTask *task, IsoParams *params, con
// parse message
peerToken = (uint8_t *)HcMalloc(ISO_TOKEN_LEN, 0);
if (peerToken == NULL) {
LOGE("Malloc for peerToken failed.");
res = HC_ERR_ALLOC_MEMORY;
goto err;
goto ERR;
}
GOTO_ERR_AND_SET_RET(GetByteFromJson(in, FIELD_TOKEN, peerToken, ISO_TOKEN_LEN), res);
Uint8Buff tokenFromPeer = { peerToken, ISO_TOKEN_LEN };
tokenSelf = (uint8_t *)HcMalloc(ISO_TOKEN_LEN, 0);
if (tokenSelf == NULL) {
LOGE("Malloc for tokenSelf failed.");
res = HC_ERR_ALLOC_MEMORY;
goto err;
goto ERR;
}
Uint8Buff tokenToPeer = { tokenSelf, ISO_TOKEN_LEN };
@@ -187,18 +190,18 @@ static int CalTokenAndGenSessionKey(SymBaseCurTask *task, IsoParams *params, con
res = IsoServerGenSessionKeyAndCalToken(&params->baseParams, &tokenFromPeer, &tokenToPeer);
if (res != 0) {
LOGE("IsoServerGenSessionKeyAndCalToken failed, res:%d", res);
goto err;
goto ERR;
}
// package message
res = PackDataForCalTokenServer(params, &tokenToPeer, out);
if (res != 0) {
LOGE("PackDataForCalTokenServer failed, res:%d", res);
goto err;
goto ERR;
}
task->taskStatus = TASK_STATUS_GEN_SESSION_KEY;
*status = FINISH;
err:
ERR:
HcFree(peerToken);
HcFree(tokenSelf);
return res;
@@ -207,14 +210,10 @@ err:
static int Process(struct SymBaseCurTaskT *task, IsoParams *params, const CJson *in, CJson *out, int *status)
{
int res;
if ((task == NULL) || (in == NULL) || (out == NULL) || (status == NULL) || (params == NULL)) {
res = HC_ERR_INVALID_PARAMS;
goto out;
}
uint32_t step = ProtocolMessageIn(in);
if (step == INVALID_MESSAGE) {
res = HC_ERR_BAD_MESSAGE;
goto out;
goto OUT_FUNC;
}
switch (step) {
case STEP_ONE:
@@ -227,11 +226,15 @@ static int Process(struct SymBaseCurTaskT *task, IsoParams *params, const CJson
res = HC_ERR_BAD_MESSAGE;
break;
}
out:
if (res == 0) {
res = ServerProtocolMessageOut(out, params->opCode, step);
OUT_FUNC:
if (res != HC_SUCCESS) {
LOGE("Process step:%d failed, res: %x.", step, res);
return res;
}
res = ServerProtocolMessageOut(out, params->opCode, step);
if (res != HC_SUCCESS) {
LOGE("ServerProtocolMessageOut failed, res: %x.", res);
}
return res;
}
@@ -239,6 +242,7 @@ SymBaseCurTask *CreateProtocolServerTask()
{
IsoProtocolServerTask *task = (IsoProtocolServerTask *)HcMalloc(sizeof(IsoProtocolServerTask), 0);
if (task == NULL) {
LOGE("Malloc for IsoProtocolServerTask failed.");
return NULL;
}
task->taskBase.destroyTask = DestroyProtocolServerTask;
@@ -14,7 +14,6 @@
*/
#include "iso_server_task.h"
#include "das_common.h"
#include "hc_log.h"
#include "hc_types.h"
#include "iso_server_bind_exchange_task.h"
@@ -26,7 +25,7 @@ static int GetIsoServerTaskType(const struct SubTaskBaseT *task)
{
IsoServerTask *realTask = (IsoServerTask *)task;
if (realTask->curTask == NULL) {
LOGE("cur Task is null");
LOGE("CurTask is null.");
return TASK_TYPE_NONE;
}
return realTask->curTask->getCurTaskType();
@@ -48,95 +47,80 @@ static void DestroyIsoServerTask(struct SubTaskBaseT *task)
static int CreateNextTask(IsoServerTask *realTask, const CJson *in, CJson *out, int *status)
{
int message = 0;
int res = GetIntFromJson(in, FIELD_MESSAGE, &message);
if (res != 0) {
LOGE("GetIntFromJson failed, res:%d", res);
return res;
if (GetIntFromJson(in, FIELD_MESSAGE, &message) != 0) {
LOGE("Get message code failed.");
return HC_ERR_JSON_GET;
}
int res = HC_SUCCESS;
switch (realTask->params.opCode) {
case OP_BIND:
if (message != ISO_CLIENT_BIND_EXCHANGE_CMD) {
LOGI("The message is repeated, ignore it message :%d.", message);
LOGI("The message is repeated, ignore it message: %d.", message);
*status = IGNORE_MSG;
break;
}
realTask->curTask = CreateServerBindExchangeTask(&(realTask->params), in, out, status);
if (realTask->curTask == NULL) {
LOGE("CreateBindExchangeTask failed");
res = HC_ERROR;
return HC_ERROR;
}
break;
case OP_UNBIND:
if (message != ISO_CLIENT_UNBIND_EXCHANGE_CMD) {
LOGI("The message is repeated, ignore it message :%d.", message);
LOGI("The message is repeated, ignore it message: %d.", message);
*status = IGNORE_MSG;
break;
}
realTask->curTask = CreateServerUnbindExchangeTask(&(realTask->params), in, out, status);
if (realTask->curTask == NULL) {
LOGE("CreateBindExchangeTask failed");
res = HC_ERROR;
return HC_ERROR;
}
break;
default:
res = CheckEncResult(&(realTask->params), in, RESULT_AAD);
if (res != 0) {
LOGE("CheckEncResult failed, res:%d", res);
case AUTHENTICATE:
if ((res = CheckEncResult(&(realTask->params), in, RESULT_AAD)) != 0) {
LOGE("CheckEncResult failed, res: %d.", res);
break;
}
res = SendResultToFinalSelf(&(realTask->params), out, true);
if (res != 0) {
LOGE("SendResultToFinalSelf failed, res:%d", res);
if ((res = SendResultToFinalSelf(&(realTask->params), out, true)) != 0) {
LOGE("SendResultToFinalSelf failed, res: %d.", res);
break;
}
LOGD("Authenticate task end.");
*status = FINISH;
break;
default:
LOGE("Unsupported opCode: %d.", realTask->params.opCode);
res = HC_ERR_NOT_SUPPORT;
}
if (res != 0) {
SendErrorToOut(out, realTask->params.opCode, res);
}
return res;
}
static int Process(struct SubTaskBaseT *task, const CJson *in, CJson *out, int *status)
{
if (task == NULL || in == NULL || out == NULL || status == NULL) {
return HC_ERR_INVALID_PARAMS;
}
IsoServerTask *realTask = (IsoServerTask *)task;
int res;
if (realTask->curTask != NULL) {
res = realTask->curTask->process(realTask->curTask, &(realTask->params), in, out, status);
if (*status != FINISH) {
if (res != 0) {
SendErrorToOut(out, realTask->params.opCode, res);
}
return res;
} else {
if (realTask->curTask->getCurTaskType() == TASK_TYPE_ISO_PROTOCOL) {
realTask->curTask->destroyTask(realTask->curTask);
realTask->curTask = NULL;
*status = CONTINUE;
}
int res = realTask->curTask->process(realTask->curTask, &(realTask->params), in, out, status);
if (res != HC_SUCCESS) {
LOGE("CurTask processes failed, res: %x.", res);
}
if (res != 0) {
LOGE("process failed, res:%d", res);
SendErrorToOut(out, realTask->params.opCode, res);
return res;
if (*status == FINISH && (realTask->curTask->getCurTaskType() == TASK_TYPE_ISO_PROTOCOL)) {
realTask->curTask->destroyTask(realTask->curTask);
realTask->curTask = NULL;
*status = CONTINUE;
}
return res;
} else {
res = CreateNextTask(realTask, in, out, status);
return CreateNextTask(realTask, in, out, status);
}
if (res != 0) {
SendErrorToOut(out, realTask->params.opCode, res);
}
return res;
}
SubTaskBase *CreateIsoServerTask(const CJson *in, CJson *out)
SubTaskBase *CreateIsoServerTask(const CJson *in)
{
IsoServerTask *task = (IsoServerTask *)HcMalloc(sizeof(IsoServerTask), 0);
if (task == NULL) {
LOGE("Malloc for IsoServerTask failed.");
return NULL;
}
@@ -146,14 +130,14 @@ SubTaskBase *CreateIsoServerTask(const CJson *in, CJson *out)
int res = InitIsoParams(&(task->params), in);
if (res != 0) {
SendErrorToOut(out, task->params.opCode, res);
LOGE("InitIsoParams failed, res: %x.", res);
DestroyIsoServerTask((struct SubTaskBaseT *)task);
return NULL;
}
task->curTask = CreateProtocolServerTask();
if (task->curTask == NULL) {
SendErrorToOut(out, task->params.opCode, res);
LOGE("CreateProtocolServerTask failed.");
DestroyIsoServerTask((struct SubTaskBaseT *)task);
return NULL;
}
@@ -15,13 +15,14 @@
#include "iso_task_common.h"
#include <time.h>
#include "das_common.h"
#include "das_task_common.h"
#include "das_module_defines.h"
#include "hc_log.h"
#include "hc_types.h"
#include "iso_protocol_common.h"
#include "protocol_common.h"
static int GenerateReturnKey(const IsoParams *params, uint8_t *returnKey, uint32_t returnKeyLen)
static int GenerateReturnKey(IsoParams *params, uint8_t *returnKey, uint32_t returnKeyLen)
{
int hkdfSaltLen = params->baseParams.randPeer.length + params->baseParams.randPeer.length;
int res;
@@ -34,26 +35,26 @@ static int GenerateReturnKey(const IsoParams *params, uint8_t *returnKey, uint32
params->baseParams.randSelf.length) != EOK) {
LOGE("Copy randSelf failed.");
res = HC_ERR_MEMORY_COPY;
goto err;
goto ERR;
}
if (memcpy_s(hkdfSalt + params->baseParams.randSelf.length, hkdfSaltLen - params->baseParams.randSelf.length,
params->baseParams.randPeer.val, params->baseParams.randPeer.length) != EOK) {
LOGE("Copy randPeer failed.");
res = HC_ERR_MEMORY_COPY;
goto err;
goto ERR;
}
} else {
if (memcpy_s(hkdfSalt, hkdfSaltLen, params->baseParams.randPeer.val,
params->baseParams.randPeer.length) != EOK) {
LOGE("Copy randPeer failed.");
res = HC_ERR_MEMORY_COPY;
goto err;
goto ERR;
}
if (memcpy_s(hkdfSalt + params->baseParams.randPeer.length, hkdfSaltLen - params->baseParams.randPeer.length,
params->baseParams.randSelf.val, params->baseParams.randSelf.length) != EOK) {
LOGE("Copy randSelf failed.");
res = HC_ERR_MEMORY_COPY;
goto err;
goto ERR;
}
}
Uint8Buff hkdfSaltBuf = { hkdfSalt, hkdfSaltLen };
@@ -63,9 +64,10 @@ static int GenerateReturnKey(const IsoParams *params, uint8_t *returnKey, uint32
&returnKeyBuf, false);
if (res != HC_SUCCESS) {
LOGE("computeHkdf for returnKey failed.");
goto err;
goto ERR;
}
err:
ERR:
FreeAndCleanKey(&(params->baseParams.sessionKey));
HcFree(hkdfSalt);
return res;
}
@@ -78,6 +80,7 @@ int GenerateEncResult(const IsoParams *params, int message, CJson *sendToPeer, c
Uint8Buff nonceBuf = { nonce, sizeof(nonce) };
int ret = params->baseParams.loader->generateRandom(&nonceBuf);
if (ret != 0) {
LOGE("Generate nonce failed, res: %x.", ret);
return ret;
}
@@ -91,18 +94,18 @@ int GenerateEncResult(const IsoParams *params, int message, CJson *sendToPeer, c
out = (uint8_t *)HcMalloc((sizeof(int) + TAG_LEN), 0);
if (out == NULL) {
ret = HC_ERR_ALLOC_MEMORY;
goto err;
goto ERR;
}
Uint8Buff outBuf = { out, sizeof(int) + TAG_LEN };
ret = params->baseParams.loader->aesGcmEncrypt(&params->baseParams.sessionKey, &plainBuf,
&encryptInfo, false, &outBuf);
if (ret != HC_SUCCESS) {
goto err;
goto ERR;
}
payload = CreateJson();
if (payload == NULL) {
ret = HC_ERR_ALLOC_MEMORY;
goto err;
goto ERR;
}
GOTO_ERR_AND_SET_RET(AddByteToJson(payload, FIELD_NONCE, nonce, sizeof(nonce)), ret);
GOTO_ERR_AND_SET_RET(AddByteToJson(payload, FIELD_ENC_RESULT, out, sizeof(int) + TAG_LEN), ret);
@@ -110,17 +113,18 @@ int GenerateEncResult(const IsoParams *params, int message, CJson *sendToPeer, c
GOTO_ERR_AND_SET_RET(AddObjToJson(sendToPeer, FIELD_PAYLOAD, payload), ret);
GOTO_ERR_AND_SET_RET(AddIntToJson(sendToPeer, FIELD_MESSAGE, message), ret);
GOTO_ERR_AND_SET_RET(AddIntToJson(sendToPeer, FIELD_AUTH_FORM, AUTH_FORM_ACCOUNT_UNRELATED), ret);
err:
ERR:
FreeJson(payload);
HcFree(out);
return ret;
}
int SendResultToFinalSelf(const IsoParams *params, CJson *out, bool isNeedReturnKey)
int SendResultToFinalSelf(IsoParams *params, CJson *out, bool isNeedReturnKey)
{
CJson *sendToSelf = CreateJson();
if (sendToSelf == NULL) {
return HC_ERR_ALLOC_MEMORY;
LOGE("Create sendToSelf json failed.");
return HC_ERR_JSON_CREATE;
}
uint8_t *returnSessionKey = NULL;
int res = 0;
@@ -129,18 +133,20 @@ int SendResultToFinalSelf(const IsoParams *params, CJson *out, bool isNeedReturn
if (isNeedReturnKey) {
returnSessionKey = (uint8_t *)HcMalloc(params->keyLen, 0);
if (returnSessionKey == NULL) {
LOGE("Malloc for returnSessionKey failed.");
res = HC_ERR_ALLOC_MEMORY;
goto err;
goto ERR;
}
res = GenerateReturnKey(params, returnSessionKey, params->keyLen);
if (res != 0) {
LOGE("gen return key failed, res:%d", res);
goto err;
goto ERR;
}
GOTO_ERR_AND_SET_RET(AddByteToJson(sendToSelf, FIELD_SESSION_KEY, returnSessionKey, params->keyLen), res);
}
GOTO_ERR_AND_SET_RET(AddObjToJson(out, FIELD_SEND_TO_SELF, sendToSelf), res);
err:
ERR:
ClearSensitiveStringInJson(sendToSelf, FIELD_SESSION_KEY);
FreeJson(sendToSelf);
if (returnSessionKey != NULL) {
(void)memset_s(returnSessionKey, params->keyLen, 0, params->keyLen);
@@ -149,34 +155,36 @@ err:
return res;
}
int GenEncResult(const IsoParams *params, int message, CJson *out, const char *aad, bool isNeedReturnKey)
int GenEncResult(IsoParams *params, int message, CJson *out, const char *aad, bool isNeedReturnKey)
{
CJson *sendToSelf = CreateJson();
if (sendToSelf == NULL) {
return HC_ERR_ALLOC_MEMORY;
LOGE("Create sendToSelf json failed.");
return HC_ERR_JSON_CREATE;
}
CJson *sendToPeer = CreateJson();
if (sendToPeer == NULL) {
LOGE("Create sendToPeer json failed.");
FreeJson(sendToSelf);
return HC_ERR_ALLOC_MEMORY;
return HC_ERR_JSON_CREATE;
}
uint8_t *returnKey = NULL;
int res = GenerateEncResult(params, message, sendToPeer, aad);
if (res != 0) {
goto err;
goto ERR;
}
GOTO_ERR_AND_SET_RET(AddIntToJson(sendToSelf, FIELD_AUTH_FORM, AUTH_FORM_ACCOUNT_UNRELATED), res);
if (isNeedReturnKey) {
returnKey = (uint8_t *)HcMalloc(params->keyLen, 0);
if (returnKey == NULL) {
res = HC_ERR_ALLOC_MEMORY;
goto err;
goto ERR;
}
res = GenerateReturnKey(params, returnKey, params->keyLen);
if (res != 0) {
LOGE("gen return key failed, res:%d", res);
goto err;
goto ERR;
}
GOTO_ERR_AND_SET_RET(AddByteToJson(sendToSelf, FIELD_SESSION_KEY, returnKey,
params->keyLen), res);
@@ -184,7 +192,8 @@ int GenEncResult(const IsoParams *params, int message, CJson *out, const char *a
GOTO_ERR_AND_SET_RET(AddIntToJson(sendToSelf, FIELD_OPERATION_CODE, params->opCode), res);
GOTO_ERR_AND_SET_RET(AddObjToJson(out, FIELD_SEND_TO_PEER, sendToPeer), res);
GOTO_ERR_AND_SET_RET(AddObjToJson(out, FIELD_SEND_TO_SELF, sendToSelf), res);
err:
ERR:
ClearSensitiveStringInJson(sendToSelf, FIELD_SESSION_KEY);
FreeJson(sendToPeer);
FreeJson(sendToSelf);
if (returnKey != NULL) {
@@ -204,13 +213,13 @@ int CheckEncResult(IsoParams *params, const CJson *in, const char *aad)
nonce = (uint8_t *)HcMalloc(NONCE_SIZE, 0);
if (nonce == NULL) {
res = HC_ERR_ALLOC_MEMORY;
goto err;
goto ERR;
}
GOTO_ERR_AND_SET_RET(GetByteFromJson(in, FIELD_NONCE, nonce, NONCE_SIZE), res);
encResult = (uint8_t *)HcMalloc(sizeof(int) + TAG_LEN, 0);
if (encResult == NULL) {
res = HC_ERR_ALLOC_MEMORY;
goto err;
goto ERR;
}
GOTO_ERR_AND_SET_RET(GetByteFromJson(in, FIELD_ENC_RESULT, encResult, sizeof(int) + TAG_LEN), res);
Uint8Buff outBuf = { (uint8_t *)&result, sizeof(int) };
@@ -225,9 +234,9 @@ int CheckEncResult(IsoParams *params, const CJson *in, const char *aad)
&outBuf);
if (res != 0) {
LOGE("decrypt result failed, res:%d", res);
goto err;
goto ERR;
}
err:
ERR:
HcFree(nonce);
HcFree(encResult);
return res;
@@ -242,11 +251,12 @@ void DeleteAuthCode(const IsoParams *params)
int res = GenerateKeyAliasInIso(params, keyAlias, ISO_KEY_ALIAS_LEN, true);
if (res != 0) {
LOGE("GenerateKeyAliasInIso failed, res:%d", res);
goto err;
goto ERR;
}
LOGI("AuthCode alias: %x%x%x%x****.", keyAlias[0], keyAlias[1], keyAlias[2], keyAlias[3]);
Uint8Buff outKeyAlias = { keyAlias, ISO_KEY_ALIAS_LEN };
params->baseParams.loader->deleteKey(&outKeyAlias);
err:
ERR:
HcFree(keyAlias);
return;
}
@@ -256,12 +266,9 @@ void DestroyIsoParams(IsoParams *params)
if (params == NULL) {
return;
}
if (params->baseParams.sessionKey.val != NULL) {
(void)memset_s(params->baseParams.sessionKey.val, params->baseParams.sessionKey.length, 0,
params->baseParams.sessionKey.length);
HcFree(params->baseParams.sessionKey.val);
params->baseParams.sessionKey.val = NULL;
}
DestroyIsoBaseParams(&params->baseParams);
if (params->packageName != NULL) {
HcFree(params->packageName);
params->packageName = NULL;
@@ -270,22 +277,6 @@ void DestroyIsoParams(IsoParams *params)
HcFree(params->serviceType);
params->serviceType = NULL;
}
if (params->baseParams.randSelf.val != NULL) {
HcFree(params->baseParams.randSelf.val);
params->baseParams.randSelf.val = NULL;
}
if (params->baseParams.randPeer.val != NULL) {
HcFree(params->baseParams.randPeer.val);
params->baseParams.randPeer.val = NULL;
}
if (params->baseParams.authIdPeer.val != NULL) {
HcFree(params->baseParams.authIdPeer.val);
params->baseParams.authIdPeer.val = NULL;
}
if (params->baseParams.authIdSelf.val != NULL) {
HcFree(params->baseParams.authIdSelf.val);
params->baseParams.authIdSelf.val = NULL;
}
if (params->seed.val != NULL) {
HcFree(params->seed.val);
params->seed.val = NULL;
@@ -307,7 +298,7 @@ static int FillAuthId(IsoParams *params, const CJson *in)
}
uint32_t authIdLen = strlen(authId);
if (authIdLen == 0 || authIdLen > MAX_AUTH_ID_LEN) {
LOGE("Invalid authIdSelfLen");
LOGE("Invalid authIdSelfLen: %d.", authIdLen);
return HC_ERR_INVALID_PARAMS;
}
params->baseParams.authIdSelf.length = authIdLen;
@@ -333,7 +324,7 @@ static int FillAuthId(IsoParams *params, const CJson *in)
}
authIdLen = strlen(authId);
if (authIdLen == 0 || authIdLen > MAX_AUTH_ID_LEN) {
LOGE("Invalid authIdPeerLen");
LOGE("Invalid authIdPeerLen %d.", authIdLen);
return HC_ERR_INVALID_PARAMS;
}
params->baseParams.authIdPeer.length = authIdLen;
@@ -352,24 +343,6 @@ static int FillAuthId(IsoParams *params, const CJson *in)
return HC_SUCCESS;
}
static int AllocRandom(IsoParams *params)
{
int res = HC_SUCCESS;
params->baseParams.randSelf.length = RAND_BYTE_LEN;
params->baseParams.randPeer.length = RAND_BYTE_LEN;
params->baseParams.randSelf.val = (uint8_t *)HcMalloc(params->baseParams.randSelf.length, 0);
if (params->baseParams.randSelf.val == NULL) {
LOGE("malloc randSelf failed");
return HC_ERR_ALLOC_MEMORY;
}
params->baseParams.randPeer.val = (uint8_t *)HcMalloc(params->baseParams.randPeer.length, 0);
if (params->baseParams.randPeer.val == NULL) {
LOGE("malloc randPeer failed");
res = HC_ERR_ALLOC_MEMORY;
}
return res;
}
static int FillPkgNameAndServiceType(IsoParams *params, const CJson *in)
{
const char *serviceType = GetStringFromJson(in, FIELD_SERVICE_TYPE);
@@ -433,6 +406,7 @@ static int AllocSeed(IsoParams *params)
{
params->seed.val = (uint8_t *)HcMalloc(SEED_LEN, 0);
if (params->seed.val == NULL) {
LOGE("Malloc for seed failed.");
return HC_ERR_ALLOC_MEMORY;
}
params->seed.length = SEED_LEN;
@@ -462,13 +436,13 @@ static int32_t GetKeyLength(IsoParams *params, const CJson *in)
params->keyLen = 0;
return HC_SUCCESS;
}
int res = GetIntFromJson(in, FIELD_KEY_LENGTH, (int *)&(params->keyLen));
if (res != HC_SUCCESS) {
LOGD("get key length failed, use default, res: %d", res);
if (GetIntFromJson(in, FIELD_KEY_LENGTH, (int *)&(params->keyLen)) != 0) {
LOGD("Get key length failed, use default.");
params->keyLen = DEFAULT_RETURN_KEY_LENGTH;
}
if (params->keyLen < MIN_OUTPUT_KEY_LEN || params->keyLen > MAX_OUTPUT_KEY_LEN) {
LOGE("Output key length is invalid.");
LOGE("Output key length is invalid, keyLen: %d.", params->keyLen);
return HC_ERR_INVALID_LEN;
}
return HC_SUCCESS;
@@ -476,51 +450,52 @@ static int32_t GetKeyLength(IsoParams *params, const CJson *in)
int InitIsoParams(IsoParams *params, const CJson *in)
{
int res = GetIntFromJson(in, FIELD_OPERATION_CODE, &(params->opCode));
if (res != 0) {
int res;
if (GetIntFromJson(in, FIELD_OPERATION_CODE, &(params->opCode)) != 0) {
LOGD("Get opCode failed, use default.");
params->opCode = AUTHENTICATE;
}
res = GetBoolFromJson(in, FIELD_IS_CLIENT, &(params->isClient));
if (res != HC_SUCCESS) {
if (params->opCode != OP_BIND && params->opCode != OP_UNBIND && params->opCode != AUTHENTICATE) {
LOGE("Unsupported opCode: %d.", params->opCode);
res = HC_ERR_NOT_SUPPORT;
goto ERR;
}
if (GetBoolFromJson(in, FIELD_IS_CLIENT, &(params->isClient)) != 0) {
LOGE("get isClient failed");
goto err;
res = HC_ERR_JSON_GET;
goto ERR;
}
res = InitIsoBaseParams(&params->baseParams);
if (res != HC_SUCCESS) {
LOGE("InitIsoBaseParams failed, res: %x.", res);
goto ERR;
}
res = GetKeyLength(params, in);
if (res != 0) {
goto err;
}
params->baseParams.sessionKey.length = ISO_SESSION_KEY_LEN;
params->baseParams.loader = GetLoaderInstance();
if (params->baseParams.loader == NULL) {
res = HC_ERROR;
goto err;
if (res != HC_SUCCESS) {
goto ERR;
}
res = GetUserType(params, in);
if (res != 0) {
goto err;
if (res != HC_SUCCESS) {
goto ERR;
}
res = FillAuthId(params, in);
if (res != 0) {
goto err;
}
res = AllocRandom(params);
if (res != 0) {
goto err;
if (res != HC_SUCCESS) {
goto ERR;
}
res = FillPkgNameAndServiceType(params, in);
if (res != 0) {
goto err;
if (res != HC_SUCCESS) {
goto ERR;
}
res = FillPin(params, in);
if (res != 0) {
goto err;
if (res != HC_SUCCESS) {
goto ERR;
}
res = AllocSeed(params);
if (res != 0) {
goto err;
if (res != HC_SUCCESS) {
goto ERR;
}
return HC_SUCCESS;
err:
ERR:
DestroyIsoParams(params);
return res;
}
@@ -533,6 +508,7 @@ static int AuthGeneratePsk(const Uint8Buff *seed, IsoParams *params)
return res;
}
LOGI("AuthCode alias: %x%x%x%x****.", keyAlias[0], keyAlias[1], keyAlias[2], keyAlias[3]);
Uint8Buff keyAliasBuf = { keyAlias, sizeof(keyAlias) };
Uint8Buff pskBuf = { params->baseParams.psk, sizeof(params->baseParams.psk) };
return params->baseParams.loader->computeHmac(&keyAliasBuf, seed, &pskBuf, true);
@@ -574,18 +550,29 @@ int GenerateKeyAliasInIso(const IsoParams *params, uint8_t *keyAlias, uint32_t k
int GeneratePsk(const CJson *in, IsoParams *params)
{
int res = 0;
if (!params->isClient) {
res = GetByteFromJson(in, FIELD_SEED, params->seed.val, params->seed.length);
}
if (res != 0) {
LOGE("get seed failed.");
return res;
if (GetByteFromJson(in, FIELD_SEED, params->seed.val, params->seed.length) != 0) {
LOGE("Get seed failed.");
return HC_ERR_JSON_GET;
}
}
int res;
if (params->opCode == AUTHENTICATE || params->opCode == OP_UNBIND) {
return AuthGeneratePsk(&params->seed, params);
res = AuthGeneratePsk(&params->seed, params);
} else {
res = AuthGeneratePskUsePin(&params->seed, params, params->pinCodeString);
if (params->pinCodeString != NULL) {
(void)memset_s(params->pinCodeString, HcStrlen(params->pinCodeString), 0, HcStrlen(params->pinCodeString));
}
}
return AuthGeneratePskUsePin(&params->seed, params, params->pinCodeString);
if (res != HC_SUCCESS) {
LOGE("Generate psk failed, res: %x.", res);
goto ERR;
}
return res;
ERR:
(void)memset_s(params->baseParams.psk, sizeof(params->baseParams.psk), 0, sizeof(params->baseParams.psk));
return res;
}
int GenerateSeed(IsoParams *params)
@@ -612,20 +599,20 @@ int GenerateSeed(IsoParams *params)
if (memcpy_s(input, SEED_LEN + sizeof(clock_t), random, SEED_LEN) != EOK) {
LOGE("memcpy seed failed.");
res = HC_ERR_MEMORY_COPY;
goto err;
goto ERR;
}
if (memcpy_s(input + SEED_LEN, sizeof(clock_t), &times, sizeof(clock_t)) != EOK) {
LOGE("memcpy times failed.");
res = HC_ERR_MEMORY_COPY;
goto err;
goto ERR;
}
Uint8Buff inputBuf = { input, SEED_LEN + sizeof(clock_t) };
res = params->baseParams.loader->sha256(&inputBuf, &params->seed);
if (res != HC_SUCCESS) {
LOGE("sha256 failed.");
goto err;
goto ERR;
}
err:
ERR:
HcFree(random);
HcFree(input);
return res;
@@ -14,80 +14,19 @@
*/
#include "iso_task_main.h"
#include "das_asy_token_manager.h"
#include "das_common.h"
#include "hc_log.h"
#include "hc_types.h"
#include "iso_base_cur_task.h"
#include "iso_client_task.h"
#include "iso_server_task.h"
static int32_t UnregisterLocalIdentity(const char *pkgName, const char *serviceType, Uint8Buff *authId, int userType)
{
(void)userType;
const AlgLoader *loader = GetLoaderInstance();
Uint8Buff pkgNameBuff = { (uint8_t *)pkgName, HcStrlen(pkgName) };
Uint8Buff serviceTypeBuff = { (uint8_t *)serviceType, HcStrlen(serviceType) };
uint8_t isoKeyAliasVal[ISO_KEY_ALIAS_LEN] = { 0 };
Uint8Buff isoKeyAliasBuff = { isoKeyAliasVal, ISO_KEY_ALIAS_LEN };
int32_t res = GenerateKeyAlias(&pkgNameBuff, &serviceTypeBuff, KEY_ALIAS_AUTH_TOKEN, authId, &isoKeyAliasBuff);
if (res != HC_SUCCESS) {
LOGE("Failed to generate authtoken alias!");
return res;
}
res = loader->deleteKey(&isoKeyAliasBuff);
if (res != HC_SUCCESS) {
LOGE("Failed to delete authtoken!");
return res;
}
LOGI("Authtoken deleted successfully!");
return HC_SUCCESS;
}
static int32_t DeletePeerAuthInfo(const char *pkgName, const char *serviceType, Uint8Buff *authIdPeer, int userTypePeer)
{
(void)userTypePeer;
const AlgLoader *loader = GetLoaderInstance();
Uint8Buff pkgNameBuff = { (uint8_t *)pkgName, HcStrlen(pkgName)};
Uint8Buff serviceTypeBuff = { (uint8_t *)serviceType, HcStrlen(serviceType) };
uint8_t isoKeyAliasVal[ISO_KEY_ALIAS_LEN] = { 0 };
Uint8Buff isoKeyAliasBuff = { isoKeyAliasVal, ISO_KEY_ALIAS_LEN };
int32_t res = GenerateKeyAlias(&pkgNameBuff, &serviceTypeBuff, KEY_ALIAS_AUTH_TOKEN, authIdPeer, &isoKeyAliasBuff);
if (res != HC_SUCCESS) {
LOGE("Failed to generate authtoken alias!");
return res;
}
res = loader->deleteKey(&isoKeyAliasBuff);
if (res != HC_SUCCESS) {
LOGE("Failed to delete authtoken!");
return res;
}
LOGI("Authtoken deleted successfully!");
return HC_SUCCESS;
}
TokenManager g_symTokenManagerInstance = {
.registerLocalIdentity = NULL,
.unregisterLocalIdentity = UnregisterLocalIdentity,
.deletePeerAuthInfo = DeletePeerAuthInfo,
.computeAndSavePsk = NULL,
.getPublicKey = NULL
};
bool IsIsoSupported(void)
{
return true;
}
SubTaskBase *CreateIsoSubTask(const CJson *in, CJson *out)
SubTaskBase *CreateIsoSubTask(const CJson *in)
{
if (in == NULL || out == NULL) {
return NULL;
}
bool isClient = true;
if (GetBoolFromJson(in, FIELD_IS_CLIENT, &isClient) != HC_SUCCESS) {
LOGE("Get isClient failed.");
@@ -96,11 +35,6 @@ SubTaskBase *CreateIsoSubTask(const CJson *in, CJson *out)
if (isClient) {
return CreateIsoClientTask(in);
} else {
return CreateIsoServerTask(in, out);
return CreateIsoServerTask(in);
}
}
const TokenManager *GetSymTokenManagerInstance(void)
{
return &g_symTokenManagerInstance;
}
@@ -0,0 +1,83 @@
/*
* Copyright (C) 2021 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 "das_lite_token_manager.h"
#include "alg_loader.h"
#include "das_task_common.h"
#include "hc_log.h"
#include "iso_base_cur_task.h"
static int32_t UnregisterLocalIdentity(const char *pkgName, const char *serviceType, Uint8Buff *authId, int userType)
{
(void)userType;
const AlgLoader *loader = GetLoaderInstance();
Uint8Buff pkgNameBuff = { (uint8_t *)pkgName, HcStrlen(pkgName) };
Uint8Buff serviceTypeBuff = { (uint8_t *)serviceType, HcStrlen(serviceType) };
uint8_t isoKeyAliasVal[ISO_KEY_ALIAS_LEN] = { 0 };
Uint8Buff isoKeyAliasBuff = { isoKeyAliasVal, ISO_KEY_ALIAS_LEN };
int32_t res = GenerateKeyAlias(&pkgNameBuff, &serviceTypeBuff, KEY_ALIAS_AUTH_TOKEN, authId, &isoKeyAliasBuff);
if (res != HC_SUCCESS) {
LOGE("Failed to generate authtoken alias!");
return res;
}
LOGI("AuthCode alias: %x%x%x%x****.", isoKeyAliasVal[0], isoKeyAliasVal[1], isoKeyAliasVal[2], isoKeyAliasVal[3]);
res = loader->deleteKey(&isoKeyAliasBuff);
if (res != HC_SUCCESS) {
LOGE("Failed to delete authtoken!");
return res;
}
LOGI("AuthCode deleted successfully!");
return HC_SUCCESS;
}
static int32_t DeletePeerAuthInfo(const char *pkgName, const char *serviceType, Uint8Buff *authIdPeer, int userTypePeer)
{
(void)userTypePeer;
const AlgLoader *loader = GetLoaderInstance();
Uint8Buff pkgNameBuff = { (uint8_t *)pkgName, HcStrlen(pkgName)};
Uint8Buff serviceTypeBuff = { (uint8_t *)serviceType, HcStrlen(serviceType) };
uint8_t isoKeyAliasVal[ISO_KEY_ALIAS_LEN] = { 0 };
Uint8Buff isoKeyAliasBuff = { isoKeyAliasVal, ISO_KEY_ALIAS_LEN };
int32_t res = GenerateKeyAlias(&pkgNameBuff, &serviceTypeBuff, KEY_ALIAS_AUTH_TOKEN, authIdPeer, &isoKeyAliasBuff);
if (res != HC_SUCCESS) {
LOGE("Failed to generate authtoken alias!");
return res;
}
LOGI("AuthCode alias: %x%x%x%x****.", isoKeyAliasVal[0], isoKeyAliasVal[1], isoKeyAliasVal[2], isoKeyAliasVal[3]);
res = loader->deleteKey(&isoKeyAliasBuff);
if (res != HC_SUCCESS) {
LOGE("Failed to delete authtoken!");
return res;
}
LOGI("AuthCode deleted successfully!");
return HC_SUCCESS;
}
TokenManager g_symTokenManagerInstance = {
.registerLocalIdentity = NULL,
.unregisterLocalIdentity = UnregisterLocalIdentity,
.deletePeerAuthInfo = DeletePeerAuthInfo,
.computeAndSavePsk = NULL,
.getPublicKey = NULL
};
const TokenManager *GetLiteTokenManagerInstance(void)
{
return &g_symTokenManagerInstance;
}
@@ -15,7 +15,7 @@
#include "iso_client_bind_exchange_task.h"
#include "alg_defs.h"
#include "das_common.h"
#include "das_task_common.h"
#include "das_module_defines.h"
#include "hc_log.h"
#include "hc_types.h"
@@ -35,8 +35,7 @@ static CurTaskType GetTaskType(void)
static void DestroyCreateClientBindExchangeTask(struct SymBaseCurTaskT *task)
{
IsoClientBindExchangeTask *realTask = (IsoClientBindExchangeTask *)task;
HcFree(realTask);
HcFree(task);
}
static int DecAndImportInner(IsoClientBindExchangeTask *realTask, const IsoParams *params,
@@ -46,7 +45,7 @@ static int DecAndImportInner(IsoClientBindExchangeTask *realTask, const IsoParam
uint8_t *keyAlias = (uint8_t *)HcMalloc(ISO_KEY_ALIAS_LEN, 0);
if (keyAlias == NULL) {
res = HC_ERR_ALLOC_MEMORY;
goto err;
goto ERR;
}
Uint8Buff keyAliasBuf = { keyAlias, ISO_KEY_ALIAS_LEN };
GcmParam gcmParam;
@@ -58,22 +57,23 @@ static int DecAndImportInner(IsoClientBindExchangeTask *realTask, const IsoParam
&gcmParam, false, authCodeBuf);
if (res != 0) {
LOGE("gcm decrypt failed, res:%d", res);
goto err;
goto ERR;
}
res = GenerateKeyAliasInIso(params, keyAlias, ISO_KEY_ALIAS_LEN, true);
if (res != 0) {
LOGE("GenerateKeyAliasInIso failed, res:%d", res);
goto err;
goto ERR;
}
LOGI("AuthCode alias: %x%x%x%x****.", keyAlias[0], keyAlias[1], keyAlias[2], keyAlias[3]);
ExtraInfo exInfo = { { params->baseParams.authIdPeer.val, params->baseParams.authIdPeer.length },
params->peerUserType, PAIR_TYPE_BIND };
res = params->baseParams.loader->importAsymmetricKey(&keyAliasBuf, authCodeBuf, &exInfo);
res = params->baseParams.loader->importSymmetricKey(&keyAliasBuf, authCodeBuf, KEY_PURPOSE_MAC, &exInfo);
if (res != 0) {
LOGE("import token failed, res:%d", res);
goto err;
LOGE("ImportSymmetricKey failed, res: %x.", res);
goto ERR;
}
err:
ERR:
HcFree(keyAlias);
return res;
}
@@ -88,12 +88,12 @@ static int DecAndImportAuthCode(IsoClientBindExchangeTask *realTask, const IsoPa
nonce = (uint8_t *)HcMalloc(NONCE_SIZE, 0);
if (nonce == NULL) {
res = HC_ERR_ALLOC_MEMORY;
goto err;
goto ERR;
}
encData = (uint8_t *)HcMalloc(encDataLen, 0);
if (encData == NULL) {
res = HC_ERR_ALLOC_MEMORY;
goto err;
goto ERR;
}
GOTO_ERR_AND_SET_RET(GetByteFromJson(in, FIELD_NONCE, nonce, NONCE_SIZE), res);
GOTO_ERR_AND_SET_RET(GetByteFromJson(in, FIELD_ENC_AUTH_TOKEN, encData, encDataLen), res);
@@ -102,7 +102,7 @@ static int DecAndImportAuthCode(IsoClientBindExchangeTask *realTask, const IsoPa
authCode = (uint8_t *)HcMalloc(AUTH_CODE_LEN, 0);
if (authCode == NULL) {
res = HC_ERR_ALLOC_MEMORY;
goto err;
goto ERR;
}
Uint8Buff authCodeBuf = { authCode, AUTH_CODE_LEN };
Uint8Buff nonceBuf = { nonce, NONCE_SIZE };
@@ -111,7 +111,7 @@ static int DecAndImportAuthCode(IsoClientBindExchangeTask *realTask, const IsoPa
if (res != 0) {
LOGE("DecAndImportInner failed, res:%d", res);
}
err:
ERR:
HcFree(nonce);
HcFree(encData);
if (authCode != NULL) {
@@ -125,12 +125,12 @@ static int Process(struct SymBaseCurTaskT *task, IsoParams *params, const CJson
{
IsoClientBindExchangeTask *realTask = (IsoClientBindExchangeTask *)task;
if (realTask->taskBase.taskStatus < TASK_TYPE_BEGIN) {
LOGE("taskStatus err %d", realTask->taskBase.taskStatus);
LOGE("Invalid taskStatus: %d", realTask->taskBase.taskStatus);
return HC_ERR_BAD_MESSAGE;
}
if (realTask->taskBase.taskStatus > TASK_TYPE_BEGIN) {
LOGI("The message is repeated, ignore it, status :%d", realTask->taskBase.taskStatus);
LOGI("The message is repeated, ignore it, status: %d", realTask->taskBase.taskStatus);
*status = IGNORE_MSG;
return HC_SUCCESS;
}
@@ -202,19 +202,19 @@ static int ClientBindExchangeStart(const IsoParams *params, IsoClientBindExchang
// execute
int res = ClientBindAesEncrypt(task, params, &encData, &nonce);
if (res != 0) {
goto err;
goto ERR;
}
// package message
sendToPeer = CreateJson();
if (sendToPeer == NULL) {
res = HC_ERR_ALLOC_MEMORY;
goto err;
goto ERR;
}
payload = CreateJson();
if (payload == NULL) {
res = HC_ERR_ALLOC_MEMORY;
goto err;
goto ERR;
}
GOTO_ERR_AND_SET_RET(AddIntToJson(sendToPeer, FIELD_MESSAGE, ISO_CLIENT_BIND_EXCHANGE_CMD), res);
GOTO_ERR_AND_SET_RET(AddByteToJson(payload, FIELD_NONCE, nonce, NONCE_SIZE), res);
@@ -224,7 +224,7 @@ static int ClientBindExchangeStart(const IsoParams *params, IsoClientBindExchang
task->taskBase.taskStatus = TASK_TYPE_BEGIN;
*status = CONTINUE;
err:
ERR:
FreeJson(payload);
FreeJson(sendToPeer);
HcFree(nonce);
@@ -237,7 +237,7 @@ SymBaseCurTask *CreateClientBindExchangeTask(IsoParams *params, const CJson *in,
(void)in;
IsoClientBindExchangeTask *task = (IsoClientBindExchangeTask *)HcMalloc(sizeof(IsoClientBindExchangeTask), 0);
if (task == NULL) {
LOGE("Failed to create client bind exchange task.");
LOGE("Failed to malloc client bind exchange task.");
return NULL;
}
task->taskBase.destroyTask = DestroyCreateClientBindExchangeTask;
@@ -17,7 +17,6 @@
#include "hc_log.h"
#include "hc_types.h"
#include "iso_task_common.h"
#include "securec.h"
enum {
TASK_TYPE_BEGIN = 1,
@@ -31,20 +30,19 @@ static CurTaskType GetTaskType(void)
static void DestroyClientUnbindExchangeTask(struct SymBaseCurTaskT *task)
{
IsoClientUnbindExchangeTask *realTask = (IsoClientUnbindExchangeTask *)task;
HcFree(realTask);
HcFree(task);
}
static int Process(struct SymBaseCurTaskT *task, IsoParams *params, const CJson *in, CJson *out, int *status)
{
IsoClientUnbindExchangeTask *realTask = (IsoClientUnbindExchangeTask *)task;
if (realTask->taskBase.taskStatus < TASK_TYPE_BEGIN) {
LOGE("taskStatus err %d", realTask->taskBase.taskStatus);
LOGE("Invalid taskStatus: %d", realTask->taskBase.taskStatus);
return HC_ERR_BAD_MESSAGE;
}
if (realTask->taskBase.taskStatus > TASK_TYPE_BEGIN) {
LOGI("The message is repeated, ignore it, status :%d", realTask->taskBase.taskStatus);
LOGI("The message is repeated, ignore it, status: %d", realTask->taskBase.taskStatus);
*status = IGNORE_MSG;
return HC_SUCCESS;
}
@@ -63,25 +61,26 @@ static int Process(struct SymBaseCurTaskT *task, IsoParams *params, const CJson
keyAlias = (uint8_t *)HcMalloc(ISO_KEY_ALIAS_LEN, 0);
if (keyAlias == NULL) {
res = HC_ERR_ALLOC_MEMORY;
goto err;
goto ERR;
}
res = GenerateKeyAliasInIso(params, keyAlias, ISO_KEY_ALIAS_LEN, true);
if (res != 0) {
LOGE("GenerateKeyAliasInIso failed, res:%d", res);
goto err;
goto ERR;
}
LOGI("AuthCode alias: %x%x%x%x****.", keyAlias[0], keyAlias[1], keyAlias[2], keyAlias[3]);
Uint8Buff outKeyAlias = { (uint8_t *)keyAlias, ISO_KEY_ALIAS_LEN };
res = params->baseParams.loader->deleteKey(&outKeyAlias);
if (res != 0) {
LOGE("delete auth code failed, res:%d", res);
goto err;
goto ERR;
}
res = SendResultToFinalSelf(params, out, false);
if (res == 0) {
realTask->taskBase.taskStatus = TASK_TYPE_FINAL;
*status = FINISH;
}
err:
ERR:
HcFree(keyAlias);
return res;
}
@@ -96,12 +95,12 @@ static int PackDataForStartUnbind(const IsoParams *params, const Uint8Buff *encD
payload = CreateJson();
if (payload == NULL) {
res = HC_ERR_ALLOC_MEMORY;
goto err;
goto ERR;
}
sendToPeer = CreateJson();
if (sendToPeer == NULL) {
res = HC_ERR_ALLOC_MEMORY;
goto err;
goto ERR;
}
GOTO_ERR_AND_SET_RET(AddIntToJson(sendToPeer, FIELD_MESSAGE, ISO_CLIENT_UNBIND_EXCHANGE_CMD), res);
GOTO_ERR_AND_SET_RET(AddIntToJson(payload, FIELD_OPERATION_CODE, params->opCode), res);
@@ -109,7 +108,7 @@ static int PackDataForStartUnbind(const IsoParams *params, const Uint8Buff *encD
GOTO_ERR_AND_SET_RET(AddByteToJson(payload, FIELD_NONCE, nonceBuf->val, nonceBuf->length), res);
GOTO_ERR_AND_SET_RET(AddObjToJson(sendToPeer, FIELD_PAYLOAD, payload), res);
GOTO_ERR_AND_SET_RET(AddObjToJson(out, FIELD_SEND_TO_PEER, sendToPeer), res);
err:
ERR:
FreeJson(payload);
FreeJson(sendToPeer);
return res;
@@ -132,7 +131,7 @@ static int GenerateEncRemoveInfo(const IsoParams *params, const Uint8Buff *nonce
if (rmvInfoStr == NULL) {
LOGE("rmvInfoStr PackJsonToString failed");
res = HC_ERR_PACKAGE_JSON_TO_STRING_FAIL;
goto err;
goto ERR;
}
Uint8Buff removeInfoBuf = { (uint8_t *)rmvInfoStr, strlen(rmvInfoStr) };
@@ -141,7 +140,7 @@ static int GenerateEncRemoveInfo(const IsoParams *params, const Uint8Buff *nonce
encData = (uint8_t *)HcMalloc(encDataLen, 0);
if (encData == NULL) {
res = HC_ERR_ALLOC_MEMORY;
goto err;
goto ERR;
}
Uint8Buff encDataBuf = { encData, encDataLen };
GcmParam gcmParam;
@@ -153,13 +152,13 @@ static int GenerateEncRemoveInfo(const IsoParams *params, const Uint8Buff *nonce
&encDataBuf);
if (res != 0) {
LOGE("encrypt removeInfo failed, res:%d", res);
goto err;
goto ERR;
}
res = PackDataForStartUnbind(params, &encDataBuf, nonceBuf, out);
if (res != HC_SUCCESS) {
LOGE("PackDataForStartUnbind failed, res:%d", res);
}
err:
ERR:
FreeJson(rmvInfoJson);
FreeJsonString(rmvInfoStr);
HcFree(encData);
@@ -176,23 +175,23 @@ static int ClientUnbindExchangeStart(const IsoParams *params, IsoClientUnbindExc
nonce = (uint8_t *)HcMalloc(NONCE_SIZE, 0);
if (nonce == NULL) {
res = HC_ERR_ALLOC_MEMORY;
goto err;
goto ERR;
}
Uint8Buff nonceBuf = { nonce, NONCE_SIZE };
res = params->baseParams.loader->generateRandom(&nonceBuf);
if (res != 0) {
LOGE("generate nonce failed, res:%d", res);
goto err;
goto ERR;
}
res = GenerateEncRemoveInfo(params, &nonceBuf, out);
if (res != 0) {
LOGE("GenerateEncRemoveInfo failed, res:%d", res);
goto err;
goto ERR;
}
task->taskBase.taskStatus = TASK_TYPE_BEGIN;
*status = CONTINUE;
err:
ERR:
HcFree(nonce);
return res;
}
@@ -14,7 +14,7 @@
*/
#include "iso_server_bind_exchange_task.h"
#include "das_common.h"
#include "das_task_common.h"
#include "das_module_defines.h"
#include "hc_log.h"
#include "hc_types.h"
@@ -34,8 +34,7 @@ static CurTaskType GetTaskType(void)
void DestroyServerBindExchangeTask(struct SymBaseCurTaskT *task)
{
IsoServerBindExchangeTask *realTask = (IsoServerBindExchangeTask *)task;
HcFree(realTask);
HcFree(task);
}
static int Process(struct SymBaseCurTaskT *task, IsoParams *params, const CJson *in, CJson *out, int *status)
@@ -47,7 +46,7 @@ static int Process(struct SymBaseCurTaskT *task, IsoParams *params, const CJson
}
if (realTask->taskBase.taskStatus > TASK_TYPE_BEGIN) {
LOGI("The message is repeated, ignore it, status :%d", realTask->taskBase.taskStatus);
LOGI("The message is repeated, ignore it, status: %d", realTask->taskBase.taskStatus);
*status = IGNORE_MSG;
return HC_SUCCESS;
}
@@ -84,13 +83,13 @@ static int DecryptChallenge(const IsoParams *params, const CJson *in, uint8_t *c
encData = (uint8_t *)HcMalloc(ENC_CHALLENGE_LEN, 0);
if (encData == NULL) {
res = HC_ERR_ALLOC_MEMORY;
goto err;
goto ERR;
}
GOTO_ERR_AND_SET_RET(GetByteFromJson(in, FIELD_ENC_DATA, encData, ENC_CHALLENGE_LEN), res);
nonce = (uint8_t *)HcMalloc(NONCE_SIZE, 0);
if (nonce == NULL) {
res = HC_ERR_ALLOC_MEMORY;
goto err;
goto ERR;
}
GOTO_ERR_AND_SET_RET(GetByteFromJson(in, FIELD_NONCE, nonce, NONCE_SIZE), res);
Uint8Buff encDataBuf = { encData, ENC_CHALLENGE_LEN };
@@ -104,9 +103,9 @@ static int DecryptChallenge(const IsoParams *params, const CJson *in, uint8_t *c
&challengeBuf);
if (res != 0) {
LOGE("decrypt challenge failed, res:%d", res);
goto err;
goto ERR;
}
err:
ERR:
HcFree(encData);
HcFree(nonce);
return res;
@@ -120,48 +119,49 @@ static int GenAndEncAuthCode(const IsoParams *params, Uint8Buff *nonceBuf, const
uint8_t *authCode = (uint8_t *)HcMalloc(AUTH_CODE_LEN, 0);
if (authCode == NULL) {
res = HC_ERR_ALLOC_MEMORY;
goto err;
goto ERR;
}
Uint8Buff authCodeBuf = { authCode, AUTH_CODE_LEN };
res = params->baseParams.loader->generateRandom(&authCodeBuf);
if (res != 0) {
LOGE("generate auth code failed, res:%d", res);
goto err;
goto ERR;
}
res = params->baseParams.loader->generateRandom(nonceBuf);
if (res != 0) {
LOGE("generate nonce failed, res:%d", res);
goto err;
goto ERR;
}
GcmParam gcmParam = { nonceBuf->val, nonceBuf->length, challengeBuf->val, challengeBuf->length };
res = params->baseParams.loader->aesGcmEncrypt(&params->baseParams.sessionKey, &authCodeBuf, &gcmParam, false,
encAuthCodeBuf);
if (res != 0) {
LOGE("encrypt auth code failed, res:%d", res);
goto err;
goto ERR;
}
keyAlias = (uint8_t *)HcMalloc(ISO_KEY_ALIAS_LEN, 0);
if (keyAlias == NULL) {
res = HC_ERR_ALLOC_MEMORY;
goto err;
goto ERR;
}
res = GenerateKeyAliasInIso(params, keyAlias, ISO_KEY_ALIAS_LEN, true);
if (res != 0) {
LOGE("GenerateKeyAliasInIso failed, res:%d", res);
goto err;
goto ERR;
}
LOGI("AuthCode alias: %x%x%x%x****.", keyAlias[0], keyAlias[1], keyAlias[2], keyAlias[3]);
Uint8Buff keyAliasBuf = { keyAlias, ISO_KEY_ALIAS_LEN };
ExtraInfo exInfo = { { params->baseParams.authIdPeer.val, params->baseParams.authIdPeer.length },
params->peerUserType, PAIR_TYPE_BIND };
res = params->baseParams.loader->importAsymmetricKey(&keyAliasBuf, &authCodeBuf, &exInfo);
res = params->baseParams.loader->importSymmetricKey(&keyAliasBuf, &authCodeBuf, KEY_PURPOSE_MAC, &exInfo);
if (res != 0) {
LOGE("importAsymmetricKey failed, res:%d", res);
goto err;
LOGE("ImportSymmetricKey failed, res: %x.", res);
goto ERR;
}
err:
ERR:
HcFree(keyAlias);
FreeAndCleanKey(&authCodeBuf);
return res;
@@ -178,12 +178,12 @@ static int GenerateAuthCodeAndImport(const IsoParams *params, CJson *out, uint8_
nonce = (uint8_t *)HcMalloc(NONCE_SIZE, 0);
if (nonce == NULL) {
res = HC_ERR_ALLOC_MEMORY;
goto err;
goto ERR;
}
encAuthCode = (uint8_t *)HcMalloc(AUTH_CODE_LEN + TAG_LEN, 0);
if (encAuthCode == NULL) {
res = HC_ERR_ALLOC_MEMORY;
goto err;
goto ERR;
}
Uint8Buff encAuthCodeBuf = { encAuthCode, AUTH_CODE_LEN + TAG_LEN };
Uint8Buff nonceBuf = { nonce, NONCE_SIZE };
@@ -192,17 +192,17 @@ static int GenerateAuthCodeAndImport(const IsoParams *params, CJson *out, uint8_
res = GenAndEncAuthCode(params, &nonceBuf, &challengeBuf, &encAuthCodeBuf);
if (res != 0) {
LOGE("GenAndEncAuthCode failed, res:%d", res);
goto err;
goto ERR;
}
payload = CreateJson();
if (payload == NULL) {
res = HC_ERR_ALLOC_MEMORY;
goto err;
goto ERR;
}
sendToPeer = CreateJson();
if (sendToPeer == NULL) {
res = HC_ERR_ALLOC_MEMORY;
goto err;
goto ERR;
}
GOTO_ERR_AND_SET_RET(AddIntToJson(sendToPeer, FIELD_MESSAGE, ISO_SERVER_BIND_EXCHANGE_RET), res);
GOTO_ERR_AND_SET_RET(AddByteToJson(payload, FIELD_ENC_AUTH_TOKEN, encAuthCodeBuf.val, encAuthCodeBuf.length), res);
@@ -210,7 +210,7 @@ static int GenerateAuthCodeAndImport(const IsoParams *params, CJson *out, uint8_
GOTO_ERR_AND_SET_RET(AddObjToJson(sendToPeer, FIELD_PAYLOAD, payload), res);
GOTO_ERR_AND_SET_RET(AddObjToJson(out, FIELD_SEND_TO_PEER, sendToPeer), res);
err:
ERR:
HcFree(nonce);
HcFree(encAuthCode);
FreeJson(payload);
@@ -225,21 +225,21 @@ static int ServerBindExchangeStart(const IsoParams *params, IsoServerBindExchang
uint8_t *challenge = (uint8_t *)HcMalloc(CHALLENGE_SIZE, 0);
if (challenge == NULL) {
res = HC_ERR_ALLOC_MEMORY;
goto err;
goto ERR;
}
res = DecryptChallenge(params, in, challenge, CHALLENGE_SIZE);
if (res != 0) {
LOGE("decrypt challenge failed, res:%d", res);
goto err;
goto ERR;
}
res = GenerateAuthCodeAndImport(params, out, challenge, CHALLENGE_SIZE);
if (res != 0) {
LOGE("GenerateAuthCodeAndImport failed, res:%d", res);
goto err;
goto ERR;
}
task->taskBase.taskStatus = TASK_TYPE_BEGIN;
*status = CONTINUE;
err:
ERR:
HcFree(challenge);
return res;
}
@@ -32,8 +32,7 @@ static CurTaskType GetTaskType(void)
static void DestroyServerUnbindExchangeTask(struct SymBaseCurTaskT *task)
{
IsoServerUnbindExchangeTask *realTask = (IsoServerUnbindExchangeTask *)task;
HcFree(realTask);
HcFree(task);
}
static int Process(struct SymBaseCurTaskT *task, IsoParams *params, const CJson *in, CJson *out, int *status)
@@ -58,29 +57,29 @@ static int CheckRemoveInfo(const Uint8Buff *removeInfoBuf, const IsoParams *para
int res = GetIntFromJson(removeInfoJson, FIELD_RMV_TYPE, &userType);
if (res != HC_SUCCESS) {
LOGE("Get user type failed");
goto err;
goto ERR;
}
if (userType != params->peerUserType) {
LOGE("User type not match :%d", userType);
res = HC_ERR_JSON_GET;
goto err;
goto ERR;
}
peerAuthId = (uint8_t *)HcMalloc(params->baseParams.authIdPeer.length, 0);
if (peerAuthId == NULL) {
LOGE("Malloc failed");
res = HC_ERR_ALLOC_MEMORY;
goto err;
goto ERR;
}
res = GetByteFromJson(removeInfoJson, FIELD_RMV_ID, peerAuthId, params->baseParams.authIdPeer.length);
if (res != HC_SUCCESS) {
LOGE("Get remove id failed, res:%d", res);
goto err;
goto ERR;
}
if (memcmp(peerAuthId, params->baseParams.authIdPeer.val, params->baseParams.authIdPeer.length) != 0) {
LOGE("Compare peerAuthId failed");
res = HC_ERROR;
}
err:
ERR:
FreeJson(removeInfoJson);
HcFree(peerAuthId);
return res;
@@ -96,7 +95,7 @@ static char *GetAndCheckEncDataStr(const CJson *in, uint32_t *removeInfoFromJson
*removeInfoFromJsonLen = strlen(removeInfoFromJson);
if (*removeInfoFromJsonLen <= TAG_LEN || *removeInfoFromJsonLen > MAX_BUFFER_LEN) {
LOGE("err removeInfoFromJsonLen");
LOGE("The length of removeInfoFromJson is invalid.");
return NULL;
}
return removeInfoFromJson;
@@ -112,21 +111,21 @@ static int DecryptRemoveInfo(const IsoParams *params, const CJson *in)
nonce = (uint8_t *)HcMalloc(NONCE_SIZE, 0);
if (nonce == NULL) {
res = HC_ERR_ALLOC_MEMORY;
goto err;
goto ERR;
}
GOTO_ERR_AND_SET_RET(GetByteFromJson(in, FIELD_NONCE, nonce, NONCE_SIZE), res);
uint32_t removeInfoFromJsonLen = 0;
char *removeInfoFromJson = GetAndCheckEncDataStr(in, &removeInfoFromJsonLen);
if (removeInfoFromJson == NULL) {
res = HC_ERR_JSON_GET;
goto err;
goto ERR;
}
uint32_t removeInfoLen = removeInfoFromJsonLen - TAG_LEN;
removeInfo = (uint8_t *)HcMalloc(removeInfoLen, 0);
if (removeInfo == NULL) {
res = HC_ERR_ALLOC_MEMORY;
goto err;
goto ERR;
}
encDataBuf.length = removeInfoFromJsonLen / BYTE_TO_HEX_OPER_LENGTH;
@@ -134,12 +133,12 @@ static int DecryptRemoveInfo(const IsoParams *params, const CJson *in)
if (encDataBuf.val == NULL) {
LOGE("Malloc encDataBuf.val failed.");
res = HC_ERR_ALLOC_MEMORY;
goto err;
goto ERR;
}
res = HexStringToByte(removeInfoFromJson, encDataBuf.val, encDataBuf.length);
if (res != HC_SUCCESS) {
LOGE("HexStringToByte for encData failed.");
goto err;
goto ERR;
}
Uint8Buff removeInfoBuf = { removeInfo, removeInfoLen };
GcmParam gcmParam = { nonce, NONCE_SIZE, (uint8_t *)UNBIND_ADD_REQUEST, HcStrlen(UNBIND_ADD_REQUEST) };
@@ -147,17 +146,17 @@ static int DecryptRemoveInfo(const IsoParams *params, const CJson *in)
&removeInfoBuf);
if (res != 0) {
LOGE("decrypt removeInfo failed, res:%d", res);
goto err;
goto ERR;
}
res = CheckRemoveInfo(&removeInfoBuf, params);
err:
ERR:
HcFree(nonce);
HcFree(removeInfo);
HcFree(encDataBuf.val);
return res;
}
static int ServerUnbindExchangeStart(const IsoParams *param, IsoServerUnbindExchangeTask *task,
static int ServerUnbindExchangeStart(IsoParams *param, IsoServerUnbindExchangeTask *task,
const CJson *in, CJson *out, int *status)
{
int res = DecryptRemoveInfo(param, in);
@@ -168,12 +167,12 @@ static int ServerUnbindExchangeStart(const IsoParams *param, IsoServerUnbindExch
res = GenEncResult(param, ISO_SERVER_UNBIND_EXCHANGE_RET, out, UNBIND_ADD_RESPONSE, false);
if (res != 0) {
LOGE("unbind exchange gen enc result failed, res:%d", res);
goto err;
goto ERR;
}
task->taskBase.taskStatus = TASK_TYPE_BEGIN;
*status = FINISH;
err:
ERR:
return res;
}
@@ -14,21 +14,20 @@
*/
#include "iso_task_main.h"
#include "das_asy_token_manager.h"
#include "das_lite_token_manager.h"
bool IsIsoSupported(void)
{
return false;
}
SubTaskBase *CreateIsoSubTask(const CJson *in, CJson *out)
SubTaskBase *CreateIsoSubTask(const CJson *in)
{
(void)in;
(void)out;
return NULL;
}
const TokenManager *GetSymTokenManagerInstance(void)
const TokenManager *GetLiteTokenManagerInstance(void)
{
return NULL;
}
@@ -13,71 +13,71 @@
* limitations under the License.
*/
#include "das_common.h"
#include "pake_message_util.h"
#include "das_task_common.h"
#include "hc_log.h"
#include "json_utils.h"
#include "module_common.h"
#include "pake_base_cur_task.h"
#include "protocol_common.h"
#include "string_util.h"
int32_t ParseStartJsonParams(PakeParams *params, const CJson *in)
int32_t PackagePakeRequestData(const PakeParams *params, CJson *payload)
{
if (GetBoolFromJson(in, FIELD_SUPPORT_256_MOD, &(params->baseParams.is256ModSupported)) != HC_SUCCESS) {
LOGD("Use default DL mod length: 384.");
// The value of is256ModSupported is true, when only 256 mode is supported
bool is256ModSupported =
(((uint32_t)params->baseParams.supportedDlPrimeMod | DL_PRIME_MOD_256) == DL_PRIME_MOD_256);
if (AddBoolToJson(payload, FIELD_SUPPORT_256_MOD, is256ModSupported) != HC_SUCCESS) {
LOGE("Add is256ModSupported failed.");
return HC_ERR_JSON_ADD;
}
if (AddIntToJson(payload, FIELD_OPERATION_CODE, params->opCode) != HC_SUCCESS) {
LOGE("Add opCode failed.");
return HC_ERR_JSON_ADD;
}
if (params->opCode == AUTHENTICATE || params->opCode == OP_UNBIND) {
if (AddStringToJson(payload, FIELD_PKG_NAME, params->packageName) != HC_SUCCESS) {
LOGE("Add packageName failed.");
return HC_ERR_JSON_ADD;
}
if (AddStringToJson(payload, FIELD_SERVICE_TYPE, params->serviceType) != HC_SUCCESS) {
LOGE("Add serviceType failed.");
return HC_ERR_JSON_ADD;
}
if (AddIntToJson(payload, FIELD_PEER_USER_TYPE, params->userType) != HC_SUCCESS) {
LOGE("Add userType failed.");
return HC_ERR_JSON_ADD;
}
}
return HC_SUCCESS;
}
int32_t PackagePakeRequestData(const PakeParams *params, CJson *payload)
{
int32_t res = AddBoolToJson(payload, FIELD_SUPPORT_256_MOD, params->baseParams.is256ModSupported);
if (res != HC_SUCCESS) {
LOGE("Add is256ModSupported failed, res: %d.", res);
return res;
}
res = AddIntToJson(payload, FIELD_OPERATION_CODE, params->opCode);
if (res != HC_SUCCESS) {
LOGE("Add opCode failed, res: %d.", res);
return res;
}
if (params->opCode == AUTHENTICATE || params->opCode == OP_UNBIND) {
res = AddStringToJson(payload, FIELD_PKG_NAME, params->packageName);
if (res != HC_SUCCESS) {
LOGE("Add packageName failed, res: %d.", res);
return res;
}
res = AddStringToJson(payload, FIELD_SERVICE_TYPE, params->serviceType);
if (res != HC_SUCCESS) {
LOGE("Add serviceType failed, res: %d.", res);
return res;
}
res = AddIntToJson(payload, FIELD_PEER_USER_TYPE, params->userType);
if (res != HC_SUCCESS) {
LOGE("Add userType failed, res: %d.", res);
return res;
}
}
return res;
}
int32_t ParsePakeRequestMessage(PakeParams *params, const CJson *in)
{
int32_t res = GetBoolFromJson(in, FIELD_SUPPORT_256_MOD, &(params->baseParams.is256ModSupported));
if (res != HC_SUCCESS) {
LOGE("Get is256ModSupported failed, res: %d.", res);
return res;
bool is256ModSupported = true;
if (GetBoolFromJson(in, FIELD_SUPPORT_256_MOD, &is256ModSupported) != HC_SUCCESS) {
LOGE("Get is256ModSupported failed.");
return HC_ERR_JSON_GET;
}
params->baseParams.supportedDlPrimeMod = is256ModSupported ?
(params->baseParams.supportedDlPrimeMod & DL_PRIME_MOD_256) :
(params->baseParams.supportedDlPrimeMod & DL_PRIME_MOD_384);
if (params->opCode == AUTHENTICATE) {
res = GetAndCheckKeyLenOnServer(in, &(params->returnKey.length));
/*
* opCode: OP_UNBIND, pake v1: don't need returnKey, use default 0 length
* opCode: OP_UNBIND, pake v2: don't need returnKey, use default 0 length
* opCode: OP_BIND, pake v1: use default 32 length
* opCode: OP_BIND, pake v2: don't need returnKey, use default 0 length
* Therefore, only params->opCode == AUTHENTICATE or AUTH_KEY_AGREEMENT, need to get keyLen from message
*/
if (params->opCode == AUTHENTICATE || params->opCode == AUTH_KEY_AGREEMENT) {
int32_t res = GetAndCheckKeyLenOnServer(in, &(params->returnKey.length));
if (res != HC_SUCCESS) {
LOGE("GetAndCheckKeyLenOnServer failed, res: %d.", res);
return res;
}
}
return res;
return HC_SUCCESS;
}
int32_t PackagePakeResponseData(const PakeParams *params, CJson *payload)
@@ -1,100 +0,0 @@
/*
* Copyright (C) 2021 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_protocol_task_common.h"
#include "hc_log.h"
#include "hc_types.h"
#include "module_common.h"
#include "pake_protocol_common.h"
#include "pake_task_common.h"
void DestroyDasPakeParams(PakeParams *params)
{
if (params == NULL) {
return;
}
DestroyPakeBaseParams(&(params->baseParams));
if (params->returnKey.val != NULL) {
(void)memset_s(params->returnKey.val, params->returnKey.length, 0, params->returnKey.length);
HcFree(params->returnKey.val);
params->returnKey.val = NULL;
}
HcFree(params->packageName);
params->packageName = NULL;
HcFree(params->serviceType);
params->serviceType = NULL;
HcFree(params->nonce.val);
params->nonce.val = NULL;
}
static int32_t FillReturnKey(PakeParams *params, const CJson *in)
{
if (params->opCode == OP_UNBIND) {
params->returnKey.val = NULL;
params->returnKey.length = 0;
return HC_SUCCESS;
}
int32_t res = GetIntFromJson(in, FIELD_KEY_LENGTH, (int *)&(params->returnKey.length));
if (res != HC_SUCCESS) {
LOGD("Get key length failed, use default, res: %d", res);
params->returnKey.length = DEFAULT_RETURN_KEY_LENGTH;
}
if (params->returnKey.length < MIN_OUTPUT_KEY_LEN || params->returnKey.length > MAX_OUTPUT_KEY_LEN) {
LOGE("Output key length is invalid.");
return HC_ERR_INVALID_LEN;
}
res = InitSingleParam(&params->returnKey, params->returnKey.length);
if (res != HC_SUCCESS) {
LOGE("InitSingleParam for returnKey failed, res: %d.", res);
}
return res;
}
int32_t InitDasPakeParams(PakeParams *params, const CJson *in)
{
if (params == NULL || in == NULL) {
LOGE("%s; %s;", (params == NULL) ? "params is null" : "params is not null",
(in == NULL) ? "in is null" : "in is not null");
return HC_ERR_INVALID_PARAMS;
}
int32_t res = InitPakeBaseParams(&(params->baseParams));
if (res != HC_SUCCESS) {
LOGE("InitPakeBaseParams failed, res: %d.", res);
goto err;
}
res = FillDasPakeParams(params, in);
if (res != HC_SUCCESS) {
LOGE("FillDasPakeParams failed, res: %d.", res);
goto err;
}
res = FillReturnKey(params, in);
if (res != HC_SUCCESS) {
LOGE("FillReturnKey failed, res: %d.", res);
goto err;
}
return HC_SUCCESS;
err:
DestroyDasPakeParams(params);
return res;
}
@@ -14,17 +14,10 @@
*/
#include "pake_task_common.h"
#include "das_asy_token_manager.h"
#include "das_common.h"
#include "das_module_defines.h"
#include "hc_log.h"
#include "hc_types.h"
#include "module_common.h"
#include "protocol_common.h"
#include "standard_client_bind_exchange_task.h"
#include "string_util.h"
#define ASCII_CASE_DIFFERENCE_VALUE 32
int32_t ConstructOutJson(const PakeParams *params, CJson *out)
{
@@ -36,34 +29,34 @@ int32_t ConstructOutJson(const PakeParams *params, CJson *out)
if (payload == NULL) {
LOGE("Create payload json failed.");
res = HC_ERR_ALLOC_MEMORY;
goto err;
goto ERR;
}
sendToPeer = CreateJson();
if (sendToPeer == NULL) {
LOGE("Create sendToPeer json failed.");
res = HC_ERR_ALLOC_MEMORY;
goto err;
goto ERR;
}
if (params->opCode == AUTHENTICATE) {
res = AddIntToJson(sendToPeer, FIELD_AUTH_FORM, AUTH_FORM_ACCOUNT_UNRELATED);
if (res != HC_SUCCESS) {
LOGE("Add authForm failed, res: %d.", res);
goto err;
goto ERR;
}
}
res = AddObjToJson(sendToPeer, FIELD_PAYLOAD, payload);
if (res != HC_SUCCESS) {
LOGE("Add payload to sendToPeer failed, res: %d.", res);
goto err;
goto ERR;
}
res = AddObjToJson(out, FIELD_SEND_TO_PEER, sendToPeer);
if (res != HC_SUCCESS) {
LOGE("Add sendToPeer to out failed, res: %d.", res);
goto err;
goto ERR;
}
err:
ERR:
FreeJson(payload);
FreeJson(sendToPeer);
return res;
@@ -75,38 +68,39 @@ static int32_t GenerateOutputKey(PakeParams *params)
int32_t res = params->baseParams.loader->computeHkdf(&(params->baseParams.sessionKey), &(params->baseParams.salt),
&keyInfo, &(params->returnKey), false);
if (res != HC_SUCCESS) {
LOGE("generate returnKey failed");
FreeAndCleanKey(&(params->baseParams.sessionKey));
LOGE("Generate returnKey failed.");
FreeAndCleanKey(&(params->returnKey));
return res;
}
FreeAndCleanKey(&(params->baseParams.sessionKey));
return res;
}
int32_t SendResultToSelf(PakeParams *params, CJson *out)
{
int res = HC_SUCCESS;
int res;
CJson *sendToSelf = CreateJson();
if (sendToSelf == NULL) {
return HC_ERR_ALLOC_MEMORY;
LOGE("Create sendToSelf json failed.");
res = HC_ERR_JSON_CREATE;
goto ERR;
}
GOTO_ERR_AND_SET_RET(AddIntToJson(sendToSelf, FIELD_OPERATION_CODE, OP_BIND), res);
GOTO_ERR_AND_SET_RET(AddIntToJson(sendToSelf, FIELD_OPERATION_CODE, params->opCode), res);
GOTO_ERR_AND_SET_RET(AddIntToJson(sendToSelf, FIELD_AUTH_FORM, AUTH_FORM_ACCOUNT_UNRELATED), res);
if (params->returnKey.length != 0) { /* keyLen == 0 means unbind, needn't to generate returnKey */
if (params->returnKey.length != 0) { /* keyLen == 0 means that returnKey needn't to be generated. */
res = GenerateOutputKey(params);
if (res != HC_SUCCESS) {
LOGE("GenerateOutputKey failed, res:%d", res);
goto err;
LOGE("GenerateOutputKey failed, res: %x.", res);
goto ERR;
}
GOTO_ERR_AND_SET_RET(AddByteToJson(sendToSelf, FIELD_SESSION_KEY, params->returnKey.val,
params->returnKey.length), res);
}
GOTO_ERR_AND_SET_RET(AddObjToJson(out, FIELD_SEND_TO_SELF, sendToSelf), res);
err:
FreeAndCleanKey(&(params->baseParams.sessionKey));
ERR:
FreeAndCleanKey(&(params->returnKey));
ClearSensitiveStringInJson(sendToSelf, FIELD_SESSION_KEY);
FreeJson(sendToSelf);
return res;
}
@@ -119,7 +113,7 @@ static int32_t FillPskWithPin(PakeParams *params, const CJson *in)
return HC_ERR_JSON_GET;
}
if (strlen(pinString) < MIN_PIN_LEN || strlen(pinString) > MAX_PIN_LEN) {
LOGE("Pin code is too short.");
LOGE("Pin code len is invalid.");
return HC_ERR_INVALID_LEN;
}
@@ -138,89 +132,6 @@ static int32_t FillPskWithPin(PakeParams *params, const CJson *in)
return HC_SUCCESS;
}
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;
}
}
}
static int32_t ConvertPsk(const Uint8Buff *srcPsk, PakeParams *params)
{
int res;
res = InitSingleParam(&(params->baseParams.psk), PAKE_PSK_LEN * BYTE_TO_HEX_OPER_LENGTH + 1);
if (res != HC_SUCCESS) {
LOGE("InitSingleParam for psk failed, res: %d.", res);
return res;
}
/* For compatibility, to be same with HiChain 2.0 */
res = ByteToHexString(srcPsk->val, srcPsk->length, (char *)params->baseParams.psk.val,
params->baseParams.psk.length);
if (res != HC_SUCCESS) {
LOGE("Convert psk from byte to hex string failed, res: %d.", res);
return res;
}
params->baseParams.psk.length = params->baseParams.psk.length - 1; // do not need include '\0' when using psk
(void)UpperToLowercase(&(params->baseParams.psk));
return res;
}
int32_t FillPskWithDerivedKey(PakeParams *params)
{
int32_t res;
if (!(params->baseParams.isClient)) {
res = params->baseParams.loader->generateRandom(&(params->nonce));
if (res != HC_SUCCESS) {
LOGE("Generate nonce failed, res: %d.", res);
return res;
}
}
uint8_t pskKeyAliasVal[PAKE_KEY_ALIAS_LEN] = { 0 };
Uint8Buff pskKeyAlias = { pskKeyAliasVal, PAKE_KEY_ALIAS_LEN };
Uint8Buff packageName = { (uint8_t *)params->packageName, strlen(params->packageName) };
Uint8Buff serviceType = { (uint8_t *)params->serviceType, strlen(params->serviceType) };
res = GenerateKeyAlias(&packageName, &serviceType, KEY_ALIAS_PSK, &(params->baseParams.idPeer), &pskKeyAlias);
if (res != HC_SUCCESS) {
LOGE("GenerateKeyAlias for psk failed, res: %d.", res);
return res;
}
if (params->baseParams.loader->checkKeyExist(&pskKeyAlias) != HC_SUCCESS) {
res = GetAsyTokenManagerInstance()->computeAndSavePsk(params);
if (res != HC_SUCCESS) {
LOGE("ComputeAndSavePsk failed, res: %d.", res);
return res;
}
}
Uint8Buff pskByte = { NULL, PAKE_PSK_LEN };
pskByte.val = (uint8_t *)HcMalloc(PAKE_PSK_LEN, 0);
if (pskByte.val == NULL) {
LOGE("Malloc for pskByte failed.");
return HC_ERR_ALLOC_MEMORY;
}
Uint8Buff keyInfo = { (uint8_t *)TMP_AUTH_KEY_FACTOR, strlen(TMP_AUTH_KEY_FACTOR) };
res = params->baseParams.loader->computeHkdf(&pskKeyAlias, &(params->nonce), &keyInfo, &pskByte, true);
if (res != HC_SUCCESS) {
LOGE("ComputeHkdf for psk failed, res: %d.", res);
goto err;
}
res = ConvertPsk(&pskByte, params);
if (res != HC_SUCCESS) {
LOGE("ConvertPsk failed, res: %d.", res);
goto err;
}
goto out;
err:
FreeAndCleanKey(&(params->baseParams.psk));
out:
FreeAndCleanKey(&pskByte);
return res;
}
static int32_t FillAuthId(PakeParams *params, const CJson *in)
{
const char *authId = GetStringFromJson(in, FIELD_SELF_AUTH_ID);
@@ -230,7 +141,7 @@ static int32_t FillAuthId(PakeParams *params, const CJson *in)
}
uint32_t authIdLen = strlen(authId);
if (authIdLen == 0 || authIdLen > MAX_AUTH_ID_LEN) {
LOGE("Invalid self authId length.");
LOGE("Invalid self authId length: %d.", authIdLen);
return HC_ERR_INVALID_LEN;
}
params->baseParams.idSelf.length = authIdLen;
@@ -252,7 +163,7 @@ static int32_t FillAuthId(PakeParams *params, const CJson *in)
}
authIdLen = strlen(authId);
if (authIdLen == 0 || authIdLen > MAX_AUTH_ID_LEN) {
LOGE("Invalid peer authId length.");
LOGE("Invalid peer authId length: %d.", authIdLen);
return HC_ERR_INVALID_LEN;
}
params->baseParams.idPeer.length = authIdLen;
@@ -272,15 +183,13 @@ static int32_t FillAuthId(PakeParams *params, const CJson *in)
static int32_t FillUserType(PakeParams *params, const CJson *in)
{
int32_t res = GetIntFromJson(in, FIELD_SELF_TYPE, &(params->userType));
if (res != HC_SUCCESS) {
LOGE("Get userType failed: %d", res);
return res;
if (GetIntFromJson(in, FIELD_SELF_TYPE, &(params->userType)) != HC_SUCCESS) {
LOGE("Get self userType failed");
return HC_ERR_JSON_GET;
}
res = GetIntFromJson(in, FIELD_PEER_USER_TYPE, &(params->userTypePeer));
if (res != HC_SUCCESS) {
LOGD("Get peer userType failed, use default, res: %d", res);
if (GetIntFromJson(in, FIELD_PEER_USER_TYPE, &(params->userTypePeer)) != HC_SUCCESS) {
LOGD("Get peer userType failed, use default.");
params->userTypePeer = DEVICE_TYPE_ACCESSORY;
}
return HC_SUCCESS;
@@ -321,9 +230,8 @@ static int32_t FillPkgNameAndServiceType(PakeParams *params, const CJson *in)
return HC_SUCCESS;
}
static int32_t FillNonce(PakeParams *params, const CJson *in)
static int32_t FillNonce(PakeParams *params)
{
(void)in;
if (params->opCode == AUTHENTICATE || params->opCode == OP_UNBIND) {
params->nonce.length = PAKE_NONCE_LEN;
params->nonce.val = (uint8_t *)HcMalloc(params->nonce.length, 0);
@@ -340,31 +248,36 @@ static int32_t FillNonce(PakeParams *params, const CJson *in)
int32_t FillDasPakeParams(PakeParams *params, const CJson *in)
{
int32_t res = GetIntFromJson(in, FIELD_OPERATION_CODE, &(params->opCode));
if (res != HC_SUCCESS) {
LOGD("Get opCode failed, use default, res: %d", res);
if (GetIntFromJson(in, FIELD_OPERATION_CODE, &(params->opCode)) != HC_SUCCESS) {
LOGD("Get opCode failed, use default.");
params->opCode = AUTHENTICATE;
}
res = GetBoolFromJson(in, FIELD_IS_CLIENT, &(params->baseParams.isClient));
if (res != HC_SUCCESS) {
LOGE("Get isClient failed, res: %d.", res);
return res;
if (params->opCode != OP_BIND && params->opCode != OP_UNBIND &&
params->opCode != AUTHENTICATE && params->opCode != AUTH_KEY_AGREEMENT) {
LOGE("Unsupported opCode: %d.", params->opCode);
return HC_ERR_NOT_SUPPORT;
}
res = FillNonce(params, in);
if (GetBoolFromJson(in, FIELD_IS_CLIENT, &(params->baseParams.isClient)) != HC_SUCCESS) {
LOGE("Get isClient failed.");
return HC_ERR_JSON_GET;
}
int res = FillNonce(params);
if (res != HC_SUCCESS) {
return res;
}
res = FillUserType(params, in);
if (res != HC_SUCCESS) {
return res;
}
if (params->opCode != AUTH_KEY_AGREEMENT) {
res = FillUserType(params, in);
if (res != HC_SUCCESS) {
return res;
}
res = FillPkgNameAndServiceType(params, in);
if (res != HC_SUCCESS) {
return res;
res = FillPkgNameAndServiceType(params, in);
if (res != HC_SUCCESS) {
return res;
}
}
res = FillAuthId(params, in);
@@ -372,7 +285,7 @@ int32_t FillDasPakeParams(PakeParams *params, const CJson *in)
return res;
}
if (params->opCode == OP_BIND) {
if (params->opCode == OP_BIND || params->opCode == AUTH_KEY_AGREEMENT) {
res = FillPskWithPin(params, in);
if (res != HC_SUCCESS) {
return res;
@@ -380,5 +293,11 @@ int32_t FillDasPakeParams(PakeParams *params, const CJson *in)
}
params->baseParams.curveType = CURVE_25519;
#ifdef P2P_PAKE_DL_PRIME_LEN_384
params->baseParams.supportedDlPrimeMod = (uint32_t)params->baseParams.supportedDlPrimeMod | DL_PRIME_MOD_384;
#endif
#ifdef P2P_PAKE_DL_PRIME_LEN_256
params->baseParams.supportedDlPrimeMod = (uint32_t)params->baseParams.supportedDlPrimeMod | DL_PRIME_MOD_256;
#endif
return HC_SUCCESS;
}
@@ -13,72 +13,71 @@
* limitations under the License.
*/
#include "pake_client_task.h"
#include "das_common.h"
#include "pake_v1_client_task.h"
#include "device_auth_defines.h"
#include "hc_log.h"
#include "hc_types.h"
#include "pake_client_protocol_task.h"
#include "pake_protocol_task_common.h"
#include "pake_v1_client_protocol_task.h"
#include "pake_v1_protocol_task_common.h"
#include "pake_task_common.h"
#include "standard_client_bind_exchange_task.h"
#include "standard_client_unbind_exchange_task.h"
static int GetPakeClientTaskType(const struct SubTaskBaseT *task)
static int GetPakeV1ClientTaskType(const struct SubTaskBaseT *task)
{
PakeClientTask *realTask = (PakeClientTask *)task;
PakeV1ClientTask *realTask = (PakeV1ClientTask *)task;
if (realTask->curTask == NULL) {
LOGE("cur Task is null");
LOGE("CurTask is null.");
return TASK_TYPE_NONE;
}
return realTask->curTask->getCurTaskType();
}
static void DestroyPakeClientTask(struct SubTaskBaseT *task)
static void DestroyPakeV1ClientTask(struct SubTaskBaseT *task)
{
PakeClientTask *innerTask = (PakeClientTask *)task;
PakeV1ClientTask *innerTask = (PakeV1ClientTask *)task;
if (innerTask == NULL) {
return;
}
DestroyDasPakeParams(&(innerTask->params));
DestroyDasPakeV1Params(&(innerTask->params));
if (innerTask->curTask != NULL) {
innerTask->curTask->destroyTask(innerTask->curTask);
}
HcFree(innerTask);
}
static int CreateAndProcessNextBindTask(PakeClientTask *realTask, const CJson *in, CJson *out, int *status)
static int CreateAndProcessNextBindTask(PakeV1ClientTask *realTask, const CJson *in, CJson *out, int *status)
{
realTask->curTask->destroyTask(realTask->curTask);
realTask->curTask = CreateStandardBindExchangeClientTask();
if (realTask->curTask == NULL) {
LOGE("CreateBindExchangeTask failed");
LOGE("CreateStandardBindExchangeClientTask failed.");
return HC_ERROR;
}
int res = realTask->curTask->process(realTask->curTask, &(realTask->params), in, out, status);
if (res != HC_SUCCESS) {
LOGE("process StandardBindExchangeClientTask failed.");
LOGE("Process StandardBindExchangeClientTask failed.");
}
return res;
}
static int CreateAndProcessNextUnbindTask(PakeClientTask *realTask, const CJson *in, CJson *out, int *status)
static int CreateAndProcessNextUnbindTask(PakeV1ClientTask *realTask, const CJson *in, CJson *out, int *status)
{
realTask->curTask->destroyTask(realTask->curTask);
realTask->curTask = CreateStandardUnbindExchangeClientTask();
if (realTask->curTask == NULL) {
LOGE("CreateBindExchangeTask failed");
LOGE("CreateStandardUnbindExchangeClientTask failed.");
return HC_ERROR;
}
int res = realTask->curTask->process(realTask->curTask, &(realTask->params), in, out, status);
if (res != HC_SUCCESS) {
LOGE("process StandardUnbindExchangeClientTask failed.");
LOGE("Process StandardUnbindExchangeClientTask failed.");
}
return res;
}
static int CreateNextTask(PakeClientTask *realTask, const CJson *in, CJson *out, int *status)
static int CreateNextTask(PakeV1ClientTask *realTask, const CJson *in, CJson *out, int *status)
{
int res = HC_SUCCESS;
switch (realTask->params.opCode) {
@@ -86,24 +85,25 @@ static int CreateNextTask(PakeClientTask *realTask, const CJson *in, CJson *out,
if (realTask->curTask->getCurTaskType() == TASK_TYPE_BIND_STANDARD_EXCHANGE) {
break;
}
*status = CONTINUE;
res = CreateAndProcessNextBindTask(realTask, in, out, status);
break;
case OP_UNBIND:
if (realTask->curTask->getCurTaskType() == TASK_TYPE_UNBIND_STANDARD_EXCHANGE) {
break;
}
*status = CONTINUE;
res = CreateAndProcessNextUnbindTask(realTask, in, out, status);
break;
case AUTH_KEY_AGREEMENT:
case AUTHENTICATE:
break;
default:
LOGE("error opcode: %d", realTask->params.opCode);
res = HC_ERR_INVALID_PARAMS;
LOGE("Unsupported opCode: %d.", realTask->params.opCode);
res = HC_ERR_NOT_SUPPORT;
}
if (res != HC_SUCCESS) {
LOGE("Create and process next task failed, opcode: %d, res: %d.", realTask->params.opCode, res);
SendErrorToOut(out, realTask->params.opCode, res);
return res;
}
if (*status != FINISH) {
@@ -112,59 +112,55 @@ static int CreateNextTask(PakeClientTask *realTask, const CJson *in, CJson *out,
res = SendResultToSelf(&realTask->params, out);
if (res != HC_SUCCESS) {
LOGE("SendResultToSelf failed, res: %d", res);
SendErrorToOut(out, realTask->params.opCode, res);
return res;
}
LOGD("End client task successfully.");
LOGI("End client task successfully, opcode: %d.", realTask->params.opCode);
return res;
}
static int Process(struct SubTaskBaseT *task, const CJson *in, CJson *out, int *status)
{
if (task == NULL || in == NULL || out == NULL || status == NULL) {
return HC_ERR_INVALID_PARAMS;
}
PakeClientTask *realTask = (PakeClientTask *)task;
PakeV1ClientTask *realTask = (PakeV1ClientTask *)task;
if (realTask->curTask == NULL) {
LOGE("cur Task is null");
return HC_ERROR;
LOGE("CurTask is null.");
return HC_ERR_NULL_PTR;
}
realTask->params.baseParams.supportedPakeAlg = GetSupportedPakeAlg(&(realTask->taskBase.curVersion));
realTask->params.baseParams.supportedPakeAlg = GetSupportedPakeAlg(&(realTask->taskBase.curVersion), PAKE_V1);
realTask->params.isPskSupported = IsSupportedPsk(&(realTask->taskBase.curVersion));
int res = realTask->curTask->process(realTask->curTask, &(realTask->params), in, out, status);
if (*status != FINISH) {
if (res != HC_SUCCESS) {
LOGE("CurTask processes failed, res: %x.", res);
return res;
}
if (res != HC_SUCCESS) {
LOGE("process failed, res:%d", res);
if (*status != FINISH) {
return res;
}
return CreateNextTask(realTask, in, out, status);
}
SubTaskBase *CreatePakeClientTask(const CJson *in, CJson *out)
SubTaskBase *CreatePakeV1ClientTask(const CJson *in)
{
(void)out;
PakeClientTask *task = (PakeClientTask *)HcMalloc(sizeof(PakeClientTask), 0);
PakeV1ClientTask *task = (PakeV1ClientTask *)HcMalloc(sizeof(PakeV1ClientTask), 0);
if (task == NULL) {
LOGE("Malloc for PakeClientTask failed.");
LOGE("Malloc for PakeV1ClientTask failed.");
return NULL;
}
task->taskBase.getTaskType = GetPakeClientTaskType;
task->taskBase.destroyTask = DestroyPakeClientTask;
task->taskBase.getTaskType = GetPakeV1ClientTaskType;
task->taskBase.destroyTask = DestroyPakeV1ClientTask;
task->taskBase.process = Process;
int res = InitDasPakeParams(&(task->params), in);
int res = InitDasPakeV1Params(&(task->params), in);
if (res != HC_SUCCESS) {
LOGE("Init das pake params failed, res: %d.", res);
DestroyPakeClientTask((struct SubTaskBaseT *)task);
DestroyPakeV1ClientTask((struct SubTaskBaseT *)task);
return NULL;
}
task->curTask = CreatePakeProtocolClientTask();
task->curTask = CreatePakeV1ProtocolClientTask();
if (task->curTask == NULL) {
LOGE("Create pake protocol client task failed, res: %d.", res);
DestroyPakeClientTask((struct SubTaskBaseT *)task);
LOGE("Create pake protocol client task failed.");
DestroyPakeV1ClientTask((struct SubTaskBaseT *)task);
return NULL;
}
return (SubTaskBase *)task;
@@ -13,12 +13,13 @@
* limitations under the License.
*/
#include "pake_client_protocol_task.h"
#include "das_common.h"
#include "pake_v1_client_protocol_task.h"
#include "das_task_common.h"
#include "hc_log.h"
#include "hc_types.h"
#include "pake_message_util.h"
#include "pake_protocol_common.h"
#include "pake_v1_protocol_common.h"
#include "pake_v1_protocol_task_common.h"
#include "pake_task_common.h"
enum {
@@ -30,32 +31,23 @@ enum {
static CurTaskType GetTaskType(void)
{
return TASK_TYPE_PAKE_PROTOCOL;
return TASK_TYPE_PAKE_V1_PROTOCOL;
}
static int PakeRequest(AsyBaseCurTask *task, PakeParams *params, const CJson *in, CJson *out, int *status)
static void DestroyPakeV1ProtocolClientTask(struct AsyBaseCurTaskT *task)
{
HcFree(task);
}
static int PakeRequest(AsyBaseCurTask *task, PakeParams *params, CJson *out, int *status)
{
int res;
if (task->taskStatus != TASK_STATUS_CLIENT_PAKE_BEGIN) {
LOGI("The message is repeated, ignore it, status :%d", task->taskStatus);
LOGI("The message is repeated, ignore it, status: %d", task->taskStatus);
*status = IGNORE_MSG;
return HC_SUCCESS;
}
res = ParseStartJsonParams(params, in);
if (res != HC_SUCCESS) {
LOGE("ParseStartJsonParams failed, res: %d.", res);
return res;
}
// execute
res = ClientRequestPakeProtocol(&params->baseParams);
if (res != HC_SUCCESS) {
LOGE("ClientRequestPakeProtocol failed, res: %d.", res);
return res;
}
res = ConstructOutJson(params, out);
int res = ConstructOutJson(params, out);
if (res != HC_SUCCESS) {
LOGE("ConstructOutJson failed, res: %d.", res);
return res;
@@ -78,6 +70,8 @@ static int PakeRequest(AsyBaseCurTask *task, PakeParams *params, const CJson *in
LOGE("Add idSelf failed, res: %d.", res);
return res;
}
}
if (params->opCode == AUTHENTICATE || params->opCode == OP_UNBIND || params->opCode == AUTH_KEY_AGREEMENT) {
res = AddIntToJson(payload, FIELD_KEY_LENGTH, params->returnKey.length);
if (res != HC_SUCCESS) {
LOGE("Add keyLength failed, res: %d.", res);
@@ -131,6 +125,7 @@ static int PackageMsgForClientConfirm(PakeParams *params, CJson *out)
LOGE("PackagePakeClientConfirmData failed, res: %d.", res);
return res;
}
// differentiated data
res = AddByteToJson(payload, FIELD_CHALLENGE, params->baseParams.challengeSelf.val,
params->baseParams.challengeSelf.length);
if (res != HC_SUCCESS) {
@@ -144,10 +139,11 @@ static int PakeClientConfirm(AsyBaseCurTask *task, PakeParams *params, const CJs
{
int res;
if (task->taskStatus < TASK_STATUS_CLIENT_PAKE_REQUEST) {
LOGE("Invalid taskStatus: %d", task->taskStatus);
return HC_ERR_BAD_MESSAGE;
}
if (task->taskStatus > TASK_STATUS_CLIENT_PAKE_REQUEST) {
LOGI("The message is repeated, ignore it, status :%d", task->taskStatus);
LOGI("The message is repeated, ignore it, status: %d", task->taskStatus);
*status = IGNORE_MSG;
return HC_SUCCESS;
}
@@ -157,19 +153,18 @@ static int PakeClientConfirm(AsyBaseCurTask *task, PakeParams *params, const CJs
LOGE("ParseMsgForClientConfirm failed, res: %d.", res);
return res;
}
if (((uint32_t)params->baseParams.supportedPakeAlg & PSK_SPEKE) &&
(params->opCode == AUTHENTICATE || params->opCode == OP_UNBIND)) {
res = FillPskWithDerivedKey(params);
if (params->isPskSupported && (params->opCode == AUTHENTICATE || params->opCode == OP_UNBIND)) {
res = FillPskWithDerivedKeyHex(params);
if (res != HC_SUCCESS) {
LOGE("FillPskWithDerivedKey failed.");
LOGE("FillPskWithDerivedKeyHex failed, res: %x.", res);
return res;
}
}
// execute
res = ClientConfirmPakeProtocol(&(params->baseParams));
res = ClientConfirmPakeV1Protocol(&(params->baseParams));
if (res != HC_SUCCESS) {
LOGE("ClientConfirmPakeProtocol failed, res:%d", res);
LOGE("ClientConfirmPakeV1Protocol failed, res:%d", res);
return res;
}
@@ -184,31 +179,29 @@ static int PakeClientConfirm(AsyBaseCurTask *task, PakeParams *params, const CJs
return res;
}
static int PakeClientVerifyConfirm(AsyBaseCurTask *task, PakeParams *params, const CJson *in, CJson *out, int *status)
static int PakeClientVerifyConfirm(AsyBaseCurTask *task, PakeParams *params, const CJson *in, int *status)
{
(void)out;
int res;
if (task->taskStatus < TASK_STATUS_CLIENT_PAKE_CONFIRM) {
LOGE("Invalid taskStatus: %d", task->taskStatus);
return HC_ERR_BAD_MESSAGE;
}
if (task->taskStatus > TASK_STATUS_CLIENT_PAKE_CONFIRM) {
LOGI("The message is repeated, ignore it, status :%d", task->taskStatus);
LOGI("The message is repeated, ignore it, status: %d", task->taskStatus);
*status = IGNORE_MSG;
return HC_SUCCESS;
}
// parse message
res = ParsePakeServerConfirmMessage(params, in);
int res = ParsePakeServerConfirmMessage(params, in);
if (res != HC_SUCCESS) {
LOGE("ParsePakeServerConfirmMessage failed, res: %d.", res);
return res;
}
// execute
res = ClientVerifyConfirmPakeProtocol(&params->baseParams);
res = ClientVerifyConfirmPakeV1Protocol(&params->baseParams);
if (res != HC_SUCCESS) {
LOGE("ClientVerifyConfirmPakeProtocol failed, res: %d.", res);
LOGE("ClientVerifyConfirmPakeV1Protocol failed, res: %d.", res);
return res;
}
@@ -222,9 +215,9 @@ static int Process(struct AsyBaseCurTaskT *task, PakeParams *params, const CJson
int res = HC_SUCCESS;
uint32_t step = ProtocolMessageIn(in);
if (step == INVALID_MESSAGE) {
res = PakeRequest(task, params, in, out, status);
res = PakeRequest(task, params, out, status);
step = 1;
goto out;
goto OUT;
}
step = step + 1; /* when receive peer message code, need to do next step */
@@ -233,40 +226,34 @@ static int Process(struct AsyBaseCurTaskT *task, PakeParams *params, const CJson
res = PakeClientConfirm(task, params, in, out, status);
break;
case STEP_THREE:
res = PakeClientVerifyConfirm(task, params, in, out, status);
res = PakeClientVerifyConfirm(task, params, in, status);
break;
default:
res = HC_ERR_BAD_MESSAGE;
break;
}
out:
OUT:
if (res != HC_SUCCESS) {
SendErrorToOut(out, params->opCode, res);
} else {
if (step != STEP_THREE) {
res = ClientProtocolMessageOut(out, params->opCode, step);
LOGE("Process step:%d failed, res: %x.", step, res);
return res;
}
if (step != STEP_THREE) {
res = ClientProtocolMessageOut(out, params->opCode, step);
if (res != HC_SUCCESS) {
LOGE("ClientProtocolMessageOut failed, res: %x.", res);
}
}
return res;
}
static void DestroyPakeProtocolClientTask(struct AsyBaseCurTaskT *task)
AsyBaseCurTask *CreatePakeV1ProtocolClientTask()
{
PakeProtocolClientTask *innerTask = (PakeProtocolClientTask *)task;
if (innerTask == NULL) {
return;
}
HcFree(innerTask);
}
AsyBaseCurTask *CreatePakeProtocolClientTask()
{
PakeProtocolClientTask *task = (PakeProtocolClientTask *)HcMalloc(sizeof(PakeProtocolClientTask), 0);
PakeV1ProtocolClientTask *task = (PakeV1ProtocolClientTask *)HcMalloc(sizeof(PakeV1ProtocolClientTask), 0);
if (task == NULL) {
LOGE("Malloc for PakeV1ProtocolClientTask failed.");
return NULL;
}
task->taskBase.destroyTask = DestroyPakeProtocolClientTask;
task->taskBase.destroyTask = DestroyPakeV1ProtocolClientTask;
task->taskBase.process = Process;
task->taskBase.taskStatus = TASK_STATUS_CLIENT_PAKE_BEGIN;
task->taskBase.getCurTaskType = GetTaskType;
@@ -0,0 +1,180 @@
/*
* Copyright (C) 2021 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_v1_protocol_task_common.h"
#include "das_standard_token_manager.h"
#include "das_task_common.h"
#include "hc_log.h"
#include "hc_types.h"
#include "protocol_common.h"
#include "pake_v1_protocol_common.h"
#include "pake_task_common.h"
#define ASCII_CASE_DIFFERENCE_VALUE 32
void DestroyDasPakeV1Params(PakeParams *params)
{
if (params == NULL) {
return;
}
DestroyPakeV1BaseParams(&(params->baseParams));
if (params->returnKey.val != NULL) {
(void)memset_s(params->returnKey.val, params->returnKey.length, 0, params->returnKey.length);
HcFree(params->returnKey.val);
params->returnKey.val = NULL;
}
HcFree(params->packageName);
params->packageName = NULL;
HcFree(params->serviceType);
params->serviceType = NULL;
HcFree(params->nonce.val);
params->nonce.val = NULL;
}
static int32_t AllocReturnKey(PakeParams *params, const CJson *in)
{
if (params->opCode == OP_UNBIND) {
params->returnKey.val = NULL;
params->returnKey.length = 0;
return HC_SUCCESS;
}
int32_t res = GetIntFromJson(in, FIELD_KEY_LENGTH, (int *)&(params->returnKey.length));
if (res != HC_SUCCESS) {
LOGD("Get key length failed, use default, res: %d", res);
params->returnKey.length = DEFAULT_RETURN_KEY_LENGTH;
}
if (params->returnKey.length < MIN_OUTPUT_KEY_LEN || params->returnKey.length > MAX_OUTPUT_KEY_LEN) {
LOGE("Output key length is invalid.");
return HC_ERR_INVALID_LEN;
}
res = InitSingleParam(&params->returnKey, params->returnKey.length);
if (res != HC_SUCCESS) {
LOGE("InitSingleParam for returnKey failed, res: %d.", res);
}
return res;
}
int32_t InitDasPakeV1Params(PakeParams *params, const CJson *in)
{
int32_t res = InitPakeV1BaseParams(&(params->baseParams));
if (res != HC_SUCCESS) {
LOGE("InitPakeV1BaseParams failed, res: %d.", res);
goto ERR;
}
res = FillDasPakeParams(params, in);
if (res != HC_SUCCESS) {
LOGE("FillDasPakeParams failed, res: %d.", res);
goto ERR;
}
res = AllocReturnKey(params, in);
if (res != HC_SUCCESS) {
LOGE("AllocReturnKey failed, res: %d.", res);
goto ERR;
}
return HC_SUCCESS;
ERR:
DestroyDasPakeV1Params(params);
return res;
}
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;
}
}
}
static int32_t ConvertPsk(const Uint8Buff *srcPsk, PakeParams *params)
{
int res = InitSingleParam(&(params->baseParams.psk), PAKE_PSK_LEN * BYTE_TO_HEX_OPER_LENGTH + 1);
if (res != HC_SUCCESS) {
LOGE("InitSingleParam for psk failed, res: %d.", res);
return res;
}
if (ByteToHexString(srcPsk->val, srcPsk->length, (char *)params->baseParams.psk.val,
params->baseParams.psk.length) != HC_SUCCESS) {
LOGE("Convert psk from byte to hex string failed.");
return HC_ERR_CONVERT_FAILED;
}
params->baseParams.psk.length = params->baseParams.psk.length - 1; // do not need include '\0' when using psk
(void)UpperToLowercase(&(params->baseParams.psk));
return res;
}
int32_t FillPskWithDerivedKeyHex(PakeParams *params)
{
int32_t res;
if (!(params->baseParams.isClient)) {
res = params->baseParams.loader->generateRandom(&(params->nonce));
if (res != HC_SUCCESS) {
LOGE("Generate nonce failed, res: %d.", res);
return res;
}
}
uint8_t pskKeyAliasVal[PAKE_KEY_ALIAS_LEN] = { 0 };
Uint8Buff pskKeyAlias = { pskKeyAliasVal, PAKE_KEY_ALIAS_LEN };
Uint8Buff packageName = { (uint8_t *)params->packageName, strlen(params->packageName) };
Uint8Buff serviceType = { (uint8_t *)params->serviceType, strlen(params->serviceType) };
res = GenerateKeyAlias(&packageName, &serviceType, KEY_ALIAS_PSK, &(params->baseParams.idPeer), &pskKeyAlias);
if (res != HC_SUCCESS) {
LOGE("GenerateKeyAlias for psk failed, res: %d.", res);
return res;
}
LOGI("Psk alias: %x%x%x%x****.", pskKeyAliasVal[0], pskKeyAliasVal[1], pskKeyAliasVal[2], pskKeyAliasVal[3]);
if (params->baseParams.loader->checkKeyExist(&pskKeyAlias) != HC_SUCCESS) {
res = GetStandardTokenManagerInstance()->computeAndSavePsk(params);
if (res != HC_SUCCESS) {
LOGE("ComputeAndSavePsk failed, res: %d.", res);
return res;
}
}
Uint8Buff pskByte = { NULL, PAKE_PSK_LEN };
pskByte.val = (uint8_t *)HcMalloc(PAKE_PSK_LEN, 0);
if (pskByte.val == NULL) {
LOGE("Malloc for pskByte failed.");
return HC_ERR_ALLOC_MEMORY;
}
Uint8Buff keyInfo = { (uint8_t *)TMP_AUTH_KEY_FACTOR, strlen(TMP_AUTH_KEY_FACTOR) };
res = params->baseParams.loader->computeHkdf(&pskKeyAlias, &(params->nonce), &keyInfo, &pskByte, true);
if (res != HC_SUCCESS) {
LOGE("ComputeHkdf for psk failed, res: %d.", res);
goto ERR;
}
res = ConvertPsk(&pskByte, params);
if (res != HC_SUCCESS) {
LOGE("ConvertPsk failed, res: %d.", res);
goto ERR;
}
goto OUT;
ERR:
FreeAndCleanKey(&(params->baseParams.psk));
OUT:
FreeAndCleanKey(&pskByte);
return res;
}
@@ -13,12 +13,13 @@
* limitations under the License.
*/
#include "pake_server_protocol_task.h"
#include "das_common.h"
#include "pake_v1_server_protocol_task.h"
#include "das_task_common.h"
#include "hc_log.h"
#include "hc_types.h"
#include "pake_message_util.h"
#include "pake_protocol_common.h"
#include "pake_v1_protocol_common.h"
#include "pake_v1_protocol_task_common.h"
#include "pake_task_common.h"
enum {
@@ -29,7 +30,12 @@ enum {
static CurTaskType GetTaskType(void)
{
return TASK_TYPE_PAKE_PROTOCOL;
return TASK_TYPE_PAKE_V1_PROTOCOL;
}
static void DestroyPakeV1ProtocolServerTask(struct AsyBaseCurTaskT *task)
{
HcFree(task);
}
static int PackageMsgForResponse(const PakeParams *params, CJson *out)
@@ -71,7 +77,7 @@ static int PakeResponse(AsyBaseCurTask *task, PakeParams *params, const CJson *i
{
int res;
if (task->taskStatus > TASK_STATUS_SERVER_PAKE_BEGIN) {
LOGI("The message is repeated, ignore it, status :%d", task->taskStatus);
LOGI("The message is repeated, ignore it, status: %d", task->taskStatus);
*status = IGNORE_MSG;
return HC_SUCCESS;
}
@@ -90,19 +96,18 @@ static int PakeResponse(AsyBaseCurTask *task, PakeParams *params, const CJson *i
}
}
if (((uint32_t)params->baseParams.supportedPakeAlg & PSK_SPEKE) &&
(params->opCode == AUTHENTICATE || params->opCode == OP_UNBIND)) {
res = FillPskWithDerivedKey(params);
if (params->isPskSupported && (params->opCode == AUTHENTICATE || params->opCode == OP_UNBIND)) {
res = FillPskWithDerivedKeyHex(params);
if (res != HC_SUCCESS) {
LOGE("FillPskWithDerivedKey failed, res: %d.", res);
LOGE("FillPskWithDerivedKeyHex failed, res: %d.", res);
return res;
}
}
// execute
res = ServerResponsePakeProtocol(&params->baseParams);
res = ServerResponsePakeV1Protocol(&params->baseParams);
if (res != HC_SUCCESS) {
LOGE("ServerResponsePakeProtocol failed, res:%d", res);
LOGE("ServerResponsePakeV1Protocol failed, res:%d", res);
return res;
}
@@ -122,10 +127,11 @@ static int PakeServerConfirm(AsyBaseCurTask *task, PakeParams *params, const CJs
{
int res;
if (task->taskStatus < TASK_STATUS_SERVER_PAKE_RESPONSE) {
LOGE("Invalid taskStatus: %d", task->taskStatus);
return HC_ERR_BAD_MESSAGE;
}
if (task->taskStatus > TASK_STATUS_SERVER_PAKE_RESPONSE) {
LOGI("The message is repeated, ignore it, status :%d", task->taskStatus);
LOGI("The message is repeated, ignore it, status: %d", task->taskStatus);
*status = IGNORE_MSG;
return HC_SUCCESS;
}
@@ -136,17 +142,17 @@ static int PakeServerConfirm(AsyBaseCurTask *task, PakeParams *params, const CJs
LOGE("ParsePakeClientConfirmMessage failed, res: %d", res);
return res;
}
res = GetByteFromJson(in, FIELD_CHALLENGE, params->baseParams.challengePeer.val,
params->baseParams.challengePeer.length);
if (res != HC_SUCCESS) {
LOGE("Get challengePeer failed, res: %d.", res);
return res;
// differentiated data
if (GetByteFromJson(in, FIELD_CHALLENGE, params->baseParams.challengePeer.val,
params->baseParams.challengePeer.length) != HC_SUCCESS) {
LOGE("Get challengePeer failed.");
return HC_ERR_JSON_GET;
}
// execute
res = ServerConfirmPakeProtocol(&params->baseParams);
res = ServerConfirmPakeV1Protocol(&params->baseParams);
if (res != HC_SUCCESS) {
LOGE("ServerConfirmPakeProtocol failed, res:%d", res);
LOGE("ServerConfirmPakeV1Protocol failed, res:%d", res);
return res;
}
@@ -174,15 +180,11 @@ static int PakeServerConfirm(AsyBaseCurTask *task, PakeParams *params, const CJs
static int Process(struct AsyBaseCurTaskT *task, PakeParams *params, const CJson *in, CJson *out, int *status)
{
int res = HC_SUCCESS;
if ((task == NULL) || (in == NULL) || (out == NULL) || (status == NULL) || (params == NULL)) {
res = HC_ERR_INVALID_PARAMS;
goto out;
}
int res;
uint32_t step = ProtocolMessageIn(in);
if (step == INVALID_MESSAGE) {
res = HC_ERR_BAD_MESSAGE;
goto out;
goto OUT;
}
switch (step) {
@@ -196,34 +198,26 @@ static int Process(struct AsyBaseCurTaskT *task, PakeParams *params, const CJson
res = HC_ERR_BAD_MESSAGE;
break;
}
out:
OUT:
if (res != HC_SUCCESS) {
if (out != NULL && params != NULL) {
SendErrorToOut(out, params->opCode, res);
}
} else {
res = ServerProtocolMessageOut(out, params->opCode, step);
LOGE("Process step:%d failed, res: %x.", step, res);
return res;
}
res = ServerProtocolMessageOut(out, params->opCode, step);
if (res != HC_SUCCESS) {
LOGE("ServerProtocolMessageOut failed, res: %x.", res);
}
return res;
}
static void DestroyPakeProtocolServerTask(struct AsyBaseCurTaskT *task)
AsyBaseCurTask *CreatePakeV1ProtocolServerTask()
{
PakeProtocolServerTask *innerTask = (PakeProtocolServerTask *)task;
if (innerTask == NULL) {
return;
}
HcFree(innerTask);
}
AsyBaseCurTask *CreatePakeProtocolServerTask()
{
PakeProtocolServerTask *task = (PakeProtocolServerTask *)HcMalloc(sizeof(PakeProtocolServerTask), 0);
PakeV1ProtocolServerTask *task = (PakeV1ProtocolServerTask *)HcMalloc(sizeof(PakeV1ProtocolServerTask), 0);
if (task == NULL) {
LOGE("Malloc for PakeV1ProtocolServerTask failed.");
return NULL;
}
task->taskBase.destroyTask = DestroyPakeProtocolServerTask;
task->taskBase.destroyTask = DestroyPakeV1ProtocolServerTask;
task->taskBase.process = Process;
task->taskBase.taskStatus = TASK_STATUS_SERVER_PAKE_BEGIN;
task->taskBase.getCurTaskType = GetTaskType;
@@ -13,46 +13,46 @@
* limitations under the License.
*/
#include "pake_server_task.h"
#include "das_common.h"
#include "pake_v1_server_task.h"
#include "device_auth_defines.h"
#include "hc_log.h"
#include "hc_types.h"
#include "pake_protocol_task_common.h"
#include "pake_server_protocol_task.h"
#include "pake_v1_protocol_task_common.h"
#include "pake_v1_server_protocol_task.h"
#include "pake_task_common.h"
#include "standard_server_bind_exchange_task.h"
#include "standard_server_unbind_exchange_task.h"
static int GetPakeServerTaskType(const struct SubTaskBaseT *task)
static int GetPakeV1ServerTaskType(const struct SubTaskBaseT *task)
{
PakeServerTask *realTask = (PakeServerTask *)task;
PakeV1ServerTask *realTask = (PakeV1ServerTask *)task;
if (realTask->curTask == NULL) {
LOGE("cur Task is null");
LOGE("CurTask is null.");
return TASK_TYPE_NONE;
}
return realTask->curTask->getCurTaskType();
}
static void DestroyPakeServerTask(struct SubTaskBaseT *task)
static void DestroyPakeV1ServerTask(struct SubTaskBaseT *task)
{
PakeServerTask *innerTask = (PakeServerTask *)task;
PakeV1ServerTask *innerTask = (PakeV1ServerTask *)task;
if (innerTask == NULL) {
return;
}
DestroyDasPakeParams(&(innerTask->params));
DestroyDasPakeV1Params(&(innerTask->params));
if (innerTask->curTask != NULL) {
innerTask->curTask->destroyTask(innerTask->curTask);
}
HcFree(innerTask);
}
static int CreateAndProcessNextBindTask(PakeServerTask *realTask, const CJson *in, CJson *out, int *status)
static int CreateAndProcessNextBindTask(PakeV1ServerTask *realTask, const CJson *in, CJson *out, int *status)
{
realTask->curTask->destroyTask(realTask->curTask);
realTask->curTask = CreateStandardBindExchangeServerTask();
if (realTask->curTask == NULL) {
LOGE("CreateStandardBindExchangeServerTask failed");
LOGE("CreateStandardBindExchangeServerTask failed.");
return HC_ERROR;
}
int res = realTask->curTask->process(realTask->curTask, &(realTask->params), in, out, status);
@@ -62,22 +62,22 @@ static int CreateAndProcessNextBindTask(PakeServerTask *realTask, const CJson *i
return res;
}
static int CreateAndProcessNextUnbindTask(PakeServerTask *realTask, const CJson *in, CJson *out, int *status)
static int CreateAndProcessNextUnbindTask(PakeV1ServerTask *realTask, const CJson *in, CJson *out, int *status)
{
realTask->curTask->destroyTask(realTask->curTask);
realTask->curTask = CreateStandardUnbindExchangeServerTask();
if (realTask->curTask == NULL) {
LOGE("CreateBindExchangeTask failed");
LOGE("CreateStandardUnbindExchangeServerTask failed.");
return HC_ERROR;
}
int res = realTask->curTask->process(realTask->curTask, &(realTask->params), in, out, status);
if (res != HC_SUCCESS) {
LOGE("process StandardUnbindExchangeServerTask failed.");
LOGE("Process StandardUnbindExchangeServerTask failed.");
}
return res;
}
static int CreateNextTask(PakeServerTask *realTask, const CJson *in, CJson *out, int *status)
static int CreateNextTask(PakeV1ServerTask *realTask, const CJson *in, CJson *out, int *status)
{
int res = HC_SUCCESS;
switch (realTask->params.opCode) {
@@ -85,23 +85,25 @@ static int CreateNextTask(PakeServerTask *realTask, const CJson *in, CJson *out,
if (realTask->curTask->getCurTaskType() == TASK_TYPE_BIND_STANDARD_EXCHANGE) {
break;
}
*status = CONTINUE;
res = CreateAndProcessNextBindTask(realTask, in, out, status);
break;
case OP_UNBIND:
if (realTask->curTask->getCurTaskType() == TASK_TYPE_UNBIND_STANDARD_EXCHANGE) {
break;
}
*status = CONTINUE;
res = CreateAndProcessNextUnbindTask(realTask, in, out, status);
break;
case AUTH_KEY_AGREEMENT:
case AUTHENTICATE:
break;
default:
LOGE("error opcode: %d", realTask->params.opCode);
res = HC_ERR_INVALID_PARAMS;
LOGE("Unsupported opCode: %d.", realTask->params.opCode);
res = HC_ERR_NOT_SUPPORT;
}
if (res != HC_SUCCESS) {
SendErrorToOut(out, realTask->params.opCode, res);
LOGE("Create and process next task failed, opcode: %d, res: %d.", realTask->params.opCode, res);
return res;
}
if (*status != FINISH) {
@@ -110,59 +112,55 @@ static int CreateNextTask(PakeServerTask *realTask, const CJson *in, CJson *out,
res = SendResultToSelf(&realTask->params, out);
if (res != HC_SUCCESS) {
LOGE("SendResultToSelf failed, res: %d", res);
SendErrorToOut(out, realTask->params.opCode, res);
return res;
}
LOGD("End server task successfully.");
LOGI("End server task successfully, opcode: %d.", realTask->params.opCode);
return res;
}
static int Process(struct SubTaskBaseT *task, const CJson *in, CJson *out, int *status)
{
if (task == NULL || in == NULL || out == NULL || status == NULL) {
return HC_ERR_INVALID_PARAMS;
}
PakeServerTask *realTask = (PakeServerTask *)task;
PakeV1ServerTask *realTask = (PakeV1ServerTask *)task;
if (realTask->curTask == NULL) {
LOGE("cur Task is null");
return HC_ERROR;
LOGE("CurTask is null.");
return HC_ERR_NULL_PTR;
}
realTask->params.baseParams.supportedPakeAlg = GetSupportedPakeAlg(&(realTask->taskBase.curVersion));
realTask->params.baseParams.supportedPakeAlg = GetSupportedPakeAlg(&(realTask->taskBase.curVersion), PAKE_V1);
realTask->params.isPskSupported = IsSupportedPsk(&(realTask->taskBase.curVersion));
int res = realTask->curTask->process(realTask->curTask, &(realTask->params), in, out, status);
if (*status != FINISH) {
if (res != HC_SUCCESS) {
LOGE("CurTask processes failed, res: %x.", res);
return res;
}
if (res != HC_SUCCESS) {
LOGE("process failed, res:%d", res);
if (*status != FINISH) {
return res;
}
return CreateNextTask(realTask, in, out, status);
}
SubTaskBase *CreatePakeServerTask(const CJson *in, CJson *out)
SubTaskBase *CreatePakeV1ServerTask(const CJson *in)
{
PakeServerTask *task = (PakeServerTask *)HcMalloc(sizeof(PakeServerTask), 0);
PakeV1ServerTask *task = (PakeV1ServerTask *)HcMalloc(sizeof(PakeV1ServerTask), 0);
if (task == NULL) {
LOGE("Malloc for PakeV1ServerTask failed.");
return NULL;
}
task->taskBase.getTaskType = GetPakeServerTaskType;
task->taskBase.destroyTask = DestroyPakeServerTask;
task->taskBase.getTaskType = GetPakeV1ServerTaskType;
task->taskBase.destroyTask = DestroyPakeV1ServerTask;
task->taskBase.process = Process;
int res = InitDasPakeParams(&(task->params), in);
int res = InitDasPakeV1Params(&(task->params), in);
if (res != HC_SUCCESS) {
LOGE("Init das pake params failed, res: %d.", res);
SendErrorToOut(out, task->params.opCode, HC_ERR_ALLOC_MEMORY);
DestroyPakeServerTask((struct SubTaskBaseT *)task);
DestroyPakeV1ServerTask((struct SubTaskBaseT *)task);
return NULL;
}
task->curTask = CreatePakeProtocolServerTask();
task->curTask = CreatePakeV1ProtocolServerTask();
if (task->curTask == NULL) {
LOGE("Create pake protocol server task failed, res: %d.", res);
SendErrorToOut(out, task->params.opCode, HC_ERR_ALLOC_MEMORY);
DestroyPakeServerTask((struct SubTaskBaseT *)task);
LOGE("Create pake protocol server task failed.");
DestroyPakeV1ServerTask((struct SubTaskBaseT *)task);
return NULL;
}
return (SubTaskBase *)task;
@@ -13,31 +13,28 @@
* limitations under the License.
*/
#include "pake_task_main.h"
#include "pake_v1_task_main.h"
#include "hc_log.h"
#include "hc_types.h"
#include "pake_base_cur_task.h"
#include "pake_client_task.h"
#include "pake_server_task.h"
#include "pake_v1_client_task.h"
#include "pake_v1_server_task.h"
bool IsSupportPake()
bool IsSupportPakeV1()
{
return true;
}
SubTaskBase *CreatePakeSubTask(const CJson *in, CJson *out)
SubTaskBase *CreatePakeV1SubTask(const CJson *in)
{
if (in == NULL || out == NULL) {
return NULL;
}
bool isClient = true;
if (GetBoolFromJson(in, FIELD_IS_CLIENT, &isClient) != HC_SUCCESS) {
LOGE("Get isClient failed.");
return NULL;
}
if (isClient) {
return CreatePakeClientTask(in, out);
return CreatePakeV1ClientTask(in);
} else {
return CreatePakeServerTask(in, out);
return CreatePakeV1ServerTask(in);
}
}
@@ -13,16 +13,15 @@
* limitations under the License.
*/
#include "pake_task_main.h"
#include "pake_v1_task_main.h"
bool IsSupportPake()
bool IsSupportPakeV1()
{
return false;
}
SubTaskBase *CreatePakeSubTask(const CJson *in, CJson *out)
SubTaskBase *CreatePakeV1SubTask(const CJson *in)
{
(void)in;
(void)out;
return NULL;
}
@@ -13,14 +13,15 @@
* limitations under the License.
*/
#include "tcis_module.h"
#include "pake_v2_task_main.h"
bool IsTcisSupported()
bool IsSupportPakeV2()
{
return false;
}
AuthModuleBase *CreateTcisModule()
SubTaskBase *CreatePakeV2SubTask(const CJson *in)
{
(void)in;
return NULL;
}
@@ -14,13 +14,12 @@
*/
#include "common_standard_bind_exchange.h"
#include "securec.h"
#include "alg_defs.h"
#include "das_asy_token_manager.h"
#include "das_common.h"
#include "das_standard_token_manager.h"
#include "das_task_common.h"
#include "hc_log.h"
#include "hc_types.h"
#include "module_common.h"
#include "protocol_common.h"
#include "string_util.h"
int32_t InitStandardBindExchangeParams(StandardBindExchangeParams *params)
@@ -34,21 +33,21 @@ int32_t InitStandardBindExchangeParams(StandardBindExchangeParams *params)
params->pubKeyPeer.val = (uint8_t *)HcMalloc(params->pubKeyPeer.length, 0);
if (params->pubKeyPeer.val == NULL) {
res = HC_ERR_ALLOC_MEMORY;
goto err;
goto ERR;
}
params->pubKeySelf.length = PAKE_ED25519_KEY_PAIR_LEN;
params->pubKeySelf.val = (uint8_t *)HcMalloc(params->pubKeySelf.length, 0);
if (params->pubKeySelf.val == NULL) {
res = HC_ERR_ALLOC_MEMORY;
goto err;
goto ERR;
}
params->nonce.length = STANDARD_BIND_EXCHANGE_NONCE_LEN;
params->nonce.val = (uint8_t *)HcMalloc(params->nonce.length, 0);
if (params->nonce.val == NULL) {
res = HC_ERR_ALLOC_MEMORY;
goto err;
goto ERR;
}
params->authInfo.length = 0;
@@ -57,7 +56,7 @@ int32_t InitStandardBindExchangeParams(StandardBindExchangeParams *params)
params->exInfoCipher.val = NULL;
return HC_SUCCESS;
err:
ERR:
DestroyStandardBindExchangeParams(params);
return res;
}
@@ -94,6 +93,7 @@ static int32_t PackageAuthInfo(const PakeParams *pakeParams, StandardBindExchang
{
int32_t res = pakeParams->baseParams.loader->checkKeyExist(keyAlias);
if (res != HC_SUCCESS) {
LOGI("The local identity key pair does not exist, generate it.");
Algorithm alg = (pakeParams->baseParams.curveType == CURVE_256) ? P256 : ED25519;
/* UserType and pairType are not required when generating key. */
ExtraInfo exInfo = { pakeParams->baseParams.idSelf, -1, -1 };
@@ -121,22 +121,22 @@ static int32_t PackageAuthInfo(const PakeParams *pakeParams, StandardBindExchang
if (authInfoStr == NULL) {
LOGE("authInfoStr PackJsonToString failed");
res = HC_ERR_PACKAGE_JSON_TO_STRING_FAIL;
goto err;
goto ERR;
}
res = InitSingleParam(&(exchangeParams->authInfo), strlen(authInfoStr));
if (res != HC_SUCCESS) {
LOGE("InitSingleParam for authInfo failed.");
goto err;
goto ERR;
}
if (memcpy_s(exchangeParams->authInfo.val, exchangeParams->authInfo.length,
authInfoStr, strlen(authInfoStr)) != EOK) {
LOGE("Memcpy authInfo failed.");
res = HC_ERR_MEMORY_COPY;
goto err;
goto ERR;
}
err:
ERR:
FreeJson(authInfoJson);
FreeJsonString(authInfoStr);
return res;
@@ -159,7 +159,7 @@ static int32_t GenerateSignInfo(const PakeParams *pakeParams, const StandardBind
pakeParams->baseParams.challengeSelf.length) != EOK) {
LOGE("Memcpy for challengeSelf failed.");
res = HC_ERR_MEMORY_COPY;
goto err;
goto ERR;
}
uint32_t usedLen = pakeParams->baseParams.challengeSelf.length;
@@ -167,7 +167,7 @@ static int32_t GenerateSignInfo(const PakeParams *pakeParams, const StandardBind
pakeParams->baseParams.challengePeer.length) != EOK) {
LOGE("Memcpy for challengePeer failed.");
res = HC_ERR_MEMORY_COPY;
goto err;
goto ERR;
}
usedLen += pakeParams->baseParams.challengePeer.length;
@@ -175,16 +175,16 @@ static int32_t GenerateSignInfo(const PakeParams *pakeParams, const StandardBind
exchangeParams->authInfo.length) != EOK) {
LOGE("Memcpy for authInfo failed.");
res = HC_ERR_MEMORY_COPY;
goto err;
goto ERR;
}
Algorithm alg = (pakeParams->baseParams.curveType == CURVE_256) ? P256 : ED25519;
res = pakeParams->baseParams.loader->sign(keyAlias, &msgInfo, alg, signInfo, true);
if (res != HC_SUCCESS) {
LOGE("sign failed");
goto err;
goto ERR;
}
err:
ERR:
HcFree(msgInfo.val);
return res;
}
@@ -204,25 +204,25 @@ static int32_t EncryptAuthAndSignInfo(const PakeParams *pakeParams, StandardBind
if (memcpy_s(exchangeInfo.val, exchangeInfo.length, exchangeParams->authInfo.val,
exchangeParams->authInfo.length) != EOK) {
res = HC_ERR_MEMORY_COPY;
goto err;
goto ERR;
}
if (memcpy_s(exchangeInfo.val + exchangeParams->authInfo.length,
exchangeInfo.length - exchangeParams->authInfo.length, signInfo->val, signInfo->length) != EOK) {
res = HC_ERR_MEMORY_COPY;
goto err;
goto ERR;
}
res = InitSingleParam(&(exchangeParams->exInfoCipher), exchangeInfo.length + AE_TAG_LEN);
if (res != HC_SUCCESS) {
LOGE("InitSingleParam for failed.");
goto err;
goto ERR;
}
// encrypt
res = pakeParams->baseParams.loader->generateRandom(&(exchangeParams->nonce));
if (res != HC_SUCCESS) {
LOGE("generateRandom failed");
goto err;
goto ERR;
}
GcmParam encryptInfo = {
@@ -235,10 +235,10 @@ static int32_t EncryptAuthAndSignInfo(const PakeParams *pakeParams, StandardBind
&encryptInfo, false, &(exchangeParams->exInfoCipher));
if (res != HC_SUCCESS) {
LOGE("aesGcmEncrypt failed");
goto err;
goto ERR;
}
err:
ERR:
HcFree(exchangeInfo.val);
return res;
}
@@ -265,52 +265,51 @@ static int32_t DecryptAuthAndSignInfo(const PakeParams *pakeParams, StandardBind
&(exchangeParams->exInfoCipher), &decryptInfo, false, &exchangeInfo);
if (res != HC_SUCCESS) {
LOGE("aesGcmDecrypt failed");
goto err;
goto ERR;
}
// get authInfo
res = InitSingleParam(&(exchangeParams->authInfo), exchangeInfo.length - SIGNATURE_LEN);
if (res != HC_SUCCESS) {
LOGE("InitSingleParam for authInfo failed.");
goto err;
goto ERR;
}
if (memcpy_s(exchangeParams->authInfo.val, exchangeParams->authInfo.length, exchangeInfo.val,
exchangeParams->authInfo.length) != EOK) {
LOGE("memcpy authInfo failed.");
res = HC_ERR_MEMORY_COPY;
goto err;
goto ERR;
}
if (memcpy_s(signInfo->val, signInfo->length, exchangeInfo.val + exchangeParams->authInfo.length,
SIGNATURE_LEN) != EOK) {
LOGE("memcpy signInfo failed.");
res = HC_ERR_MEMORY_COPY;
goto err;
goto ERR;
}
err:
ERR:
HcFree(exchangeInfo.val);
return res;
}
static int32_t ParseAuthInfo(PakeParams *pakeParams, const StandardBindExchangeParams *exchangeParams)
{
int32_t res = HC_SUCCESS;
int32_t res;
CJson *authInfoJson = CreateJsonFromString((char *)exchangeParams->authInfo.val);
if (authInfoJson == NULL) {
LOGE("create authInfoJson failed");
res = HC_ERROR;
goto err;
LOGE("Create authInfoJson failed.");
return HC_ERR_JSON_CREATE;
}
GOTO_ERR_AND_SET_RET(GetByteFromJson(authInfoJson, FIELD_AUTH_PK, exchangeParams->pubKeyPeer.val,
exchangeParams->pubKeyPeer.length), res);
res = GetIdPeerForParams(authInfoJson, FIELD_AUTH_ID,
res = GetIdPeer(authInfoJson, FIELD_AUTH_ID,
&pakeParams->baseParams.idSelf, &pakeParams->baseParams.idPeer);
if (res != HC_SUCCESS) {
LOGE("GetIdPeerForParams failed, res: %d.", res);
goto err;
LOGE("GetIdPeer failed, res: %d.", res);
goto ERR;
}
err:
ERR:
FreeJson(authInfoJson);
return res;
}
@@ -330,28 +329,28 @@ static int32_t VerifySignInfo(const PakeParams *pakeParams, StandardBindExchange
if (memcpy_s(verifyMsg.val, verifyMsg.length, pakeParams->baseParams.challengePeer.val,
pakeParams->baseParams.challengePeer.length) != EOK) {
res = HC_ERR_MEMORY_COPY;
goto err;
goto ERR;
}
uint32_t usedLen = pakeParams->baseParams.challengePeer.length;
if (memcpy_s(verifyMsg.val + usedLen, verifyMsg.length - usedLen, pakeParams->baseParams.challengeSelf.val,
pakeParams->baseParams.challengeSelf.length) != EOK) {
res = HC_ERR_MEMORY_COPY;
goto err;
goto ERR;
}
usedLen += pakeParams->baseParams.challengeSelf.length;
if (memcpy_s(verifyMsg.val + usedLen, verifyMsg.length - usedLen, exchangeParams->authInfo.val,
exchangeParams->authInfo.length) != EOK) {
res = HC_ERR_MEMORY_COPY;
goto err;
goto ERR;
}
Algorithm alg = (pakeParams->baseParams.curveType == CURVE_256) ? P256 : ED25519;
res = pakeParams->baseParams.loader->verify(&(exchangeParams->pubKeyPeer), &verifyMsg, alg, signInfo, false);
if (res != HC_SUCCESS) {
LOGE("verify failed");
goto err;
goto ERR;
}
err:
ERR:
HcFree(verifyMsg.val);
return res;
}
@@ -369,6 +368,7 @@ static int32_t SaveAuthInfo(const PakeParams *pakeParams, const StandardBindExch
LOGE("generateKeyAlias failed");
return res;
}
LOGI("PubKey alias: %x%x%x%x****.", keyAliasPeerVal[0], keyAliasPeerVal[1], keyAliasPeerVal[2], keyAliasPeerVal[3]);
Algorithm alg = (pakeParams->baseParams.curveType == CURVE_256) ? P256 : ED25519;
ExtraInfo exInfo = { pakeParams->baseParams.idPeer, pakeParams->userType, PAIR_TYPE_BIND };
res = pakeParams->baseParams.loader->importPublicKey(&keyAliasPeer, &(exchangeParams->pubKeyPeer), alg, &exInfo);
@@ -376,9 +376,9 @@ static int32_t SaveAuthInfo(const PakeParams *pakeParams, const StandardBindExch
LOGE("importPublicKey failed");
return res;
}
res = GetAsyTokenManagerInstance()->computeAndSavePsk(pakeParams);
res = GetStandardTokenManagerInstance()->computeAndSavePsk(pakeParams);
if (res != HC_SUCCESS) {
LOGE("ComputeAndSavePsk failed");
LOGE("ComputeAndSavePsk failed, res: %x.", res);
return res;
}
LOGI("Save pubKey and psk success.");
@@ -14,10 +14,10 @@
*/
#include "common_standard_unbind_exchange.h"
#include "das_common.h"
#include "das_task_common.h"
#include "hc_log.h"
#include "hc_types.h"
#include "module_common.h"
#include "protocol_common.h"
#include "securec.h"
int32_t InitStandardUnbindExchangeParams(StandardUnbindExchangeParams *params)
@@ -32,7 +32,7 @@ int32_t InitStandardUnbindExchangeParams(StandardUnbindExchangeParams *params)
params->nonce.val = (uint8_t *)HcMalloc(params->nonce.length, 0);
if (params->nonce.val == NULL) {
res = HC_ERR_ALLOC_MEMORY;
goto err;
goto ERR;
}
params->rmvInfo.length = 0;
@@ -43,7 +43,7 @@ int32_t InitStandardUnbindExchangeParams(StandardUnbindExchangeParams *params)
params->resultCipher.val = NULL;
return HC_SUCCESS;
err:
ERR:
DestroyStandardUnbindExchangeParams(params);
return res;
}
@@ -83,21 +83,21 @@ static int32_t PackageRmvInfo(const PakeParams *pakeParams, StandardUnbindExchan
if (rmvInfoStr == NULL) {
LOGE("rmvInfoStr PackJsonToString failed");
res = HC_ERR_PACKAGE_JSON_TO_STRING_FAIL;
goto err;
goto ERR;
}
res = InitSingleParam(&exchangeParams->rmvInfo, strlen(rmvInfoStr));
if (res != HC_SUCCESS) {
LOGE("InitSingleParam rmvInfo failed.");
goto err;
goto ERR;
}
if (memcpy_s(exchangeParams->rmvInfo.val, exchangeParams->rmvInfo.length, rmvInfoStr, strlen(rmvInfoStr)) != EOK) {
LOGE("Memcpy rmvInfo failed.");
res = HC_ERR_MEMORY_COPY;
goto err;
goto ERR;
}
err:
ERR:
FreeJson(rmvInfoJson);
FreeJsonString(rmvInfoStr);
return res;
@@ -168,12 +168,12 @@ static int32_t ParseRmvInfo(PakeParams *pakeParams, StandardUnbindExchangeParams
return HC_ERR_JSON_CREATE;
}
GOTO_ERR_AND_SET_RET(GetIntFromJson(rmvInfoJson, FIELD_RMV_TYPE, &(pakeParams->userTypePeer)), res);
res = GetIdPeerForParams(rmvInfoJson, FIELD_RMV_ID, &pakeParams->baseParams.idSelf, &pakeParams->baseParams.idPeer);
res = GetIdPeer(rmvInfoJson, FIELD_RMV_ID, &pakeParams->baseParams.idSelf, &pakeParams->baseParams.idPeer);
if (res != HC_SUCCESS) {
LOGE("GetIdPeerForParams failed, res: %d.", res);
goto err;
LOGE("GetIdPeer failed, res: %d.", res);
goto ERR;
}
err:
ERR:
FreeJson(rmvInfoJson);
return res;
}
@@ -190,19 +190,20 @@ static int32_t DeleteAuthInfo(PakeParams *pakeParams)
LOGE("generate pubKey alias failed");
return res;
}
LOGI("PubKey alias: %x%x%x%x****.", keyAliasVal[0], keyAliasVal[1], keyAliasVal[2], keyAliasVal[3]);
res = pakeParams->baseParams.loader->deleteKey(&keyAlias);
if (res != HC_SUCCESS) {
LOGE("deleteKey failed");
return res;
}
LOGI("delete peer pubKey success.");
(void)memset_s(keyAlias.val, keyAlias.length, 0, keyAlias.length);
res = GenerateKeyAlias(&packageName, &serviceType, KEY_ALIAS_PSK, &(pakeParams->baseParams.idPeer),
&keyAlias);
if (res != HC_SUCCESS) {
LOGE("generate pskKey alias failed");
return res;
}
LOGI("Psk alias: %x%x%x%x****.", keyAliasVal[0], keyAliasVal[1], keyAliasVal[2], keyAliasVal[3]);
res = pakeParams->baseParams.loader->deleteKey(&keyAlias);
if (res != HC_SUCCESS) {
LOGE("delete pskKey failed");
@@ -13,9 +13,9 @@
* limitations under the License.
*/
#include "das_asy_token_manager.h"
#include "das_standard_token_manager.h"
#include "alg_loader.h"
#include "das_common.h"
#include "das_task_common.h"
#include "hc_log.h"
static int32_t RegisterLocalIdentity(const char *pkgName, const char *serviceType, Uint8Buff *authId, int userType)
@@ -61,6 +61,8 @@ static int32_t UnregisterLocalIdentity(const char *pkgName, const char *serviceT
LOGE("Failed to generate identity keyPair alias!");
return res;
}
LOGI("KeyPair alias: %x%x%x%x****.", pakeKeyAliasVal[0], pakeKeyAliasVal[1],
pakeKeyAliasVal[2], pakeKeyAliasVal[3]);
res = loader->deleteKey(&pakeKeyAliasBuff);
if (res != HC_SUCCESS) {
LOGE("Failed to delete key pair!");
@@ -84,19 +86,20 @@ static int32_t DeletePeerAuthInfo(const char *pkgName, const char *serviceType,
LOGE("Failed to generate identity keyPair alias!");
return res;
}
LOGI("PubKey alias: %x%x%x%x****.", pakeKeyAliasVal[0], pakeKeyAliasVal[1], pakeKeyAliasVal[2], pakeKeyAliasVal[3]);
res = loader->deleteKey(&pakeKeyAliasBuff);
if (res != HC_SUCCESS) {
LOGE("Failed to delete key pair!");
return res;
}
LOGI("Key pair deleted successfully!");
LOGI("PubKey deleted successfully!");
(void)memset_s(pakeKeyAliasBuff.val, pakeKeyAliasBuff.length, 0, pakeKeyAliasBuff.length);
res = GenerateKeyAlias(&pkgNameBuff, &serviceTypeBuff, KEY_ALIAS_PSK, authIdPeer, &pakeKeyAliasBuff);
if (res != HC_SUCCESS) {
LOGE("Failed to generate psk alias!");
return res;
}
LOGI("Psk alias: %x%x%x%x****.", pakeKeyAliasVal[0], pakeKeyAliasVal[1], pakeKeyAliasVal[2], pakeKeyAliasVal[3]);
res = loader->deleteKey(&pakeKeyAliasBuff);
if (res != HC_SUCCESS) {
LOGE("Failed to delete psk!");
@@ -147,14 +150,17 @@ static int32_t ComputeAndSavePsk(const PakeParams *params)
return res;
}
LOGI("PubKey alias: %x%x%x%x****, priKey alias: %x%x%x%x****, psk alias: %x%x%x%x****.",
peerKeyAliasVal[0], peerKeyAliasVal[1], peerKeyAliasVal[2], peerKeyAliasVal[3],
selfKeyAliasVal[0], selfKeyAliasVal[1], selfKeyAliasVal[2], selfKeyAliasVal[3],
sharedKeyAliasVal[0], sharedKeyAliasVal[1], sharedKeyAliasVal[2], sharedKeyAliasVal[3]);
KeyBuff selfKeyAliasBuff = { selfKeyAlias.val, selfKeyAlias.length, true };
KeyBuff peerKeyAliasBuff = { peerKeyAlias.val, peerKeyAlias.length, true };
Algorithm alg = (params->baseParams.curveType == CURVE_256) ? P256 : ED25519;
res = params->baseParams.loader->agreeSharedSecretWithStorage(&selfKeyAliasBuff, &peerKeyAliasBuff, alg,
PAKE_PSK_LEN, &sharedKeyAlias);
if (res != HC_SUCCESS) {
LOGE("agree psk failed");
return res;
LOGE("Agree psk failed.");
}
return res;
@@ -198,7 +204,7 @@ TokenManager g_asyTokenManagerInstance = {
.getPublicKey = GetPublicKey
};
const TokenManager *GetAsyTokenManagerInstance()
const TokenManager *GetStandardTokenManagerInstance()
{
return &g_asyTokenManagerInstance;
}
@@ -14,7 +14,6 @@
*/
#include "standard_client_bind_exchange_task.h"
#include "das_common.h"
#include "hc_log.h"
#include "hc_types.h"
#include "protocol_common.h"
@@ -35,7 +34,7 @@ static int ExchangeRequest(AsyBaseCurTask *task, PakeParams *params, const CJson
{
int res;
if (task->taskStatus != TASK_STATUS_CLIENT_BIND_EXCHANGE_BEGIN) {
LOGI("The message is repeated, ignore it, status :%d", task->taskStatus);
LOGI("The message is repeated, ignore it, status: %d", task->taskStatus);
*status = IGNORE_MSG;
return HC_SUCCESS;
}
@@ -47,7 +46,7 @@ static int ExchangeRequest(AsyBaseCurTask *task, PakeParams *params, const CJson
CJson *sendToPeer = CreateJson();
if (sendToPeer == NULL) {
res = HC_ERR_ALLOC_MEMORY;
goto err;
goto ERR;
}
// parse message
@@ -75,21 +74,21 @@ static int ExchangeRequest(AsyBaseCurTask *task, PakeParams *params, const CJson
task->taskStatus = TASK_STATUS_CLIENT_BIND_EXCHANGE_REQUEST;
*status = CONTINUE;
err:
ERR:
FreeJson(data);
FreeJson(sendToPeer);
return res;
}
static int ExchangeConfirm(AsyBaseCurTask *task, PakeParams *params, const CJson *in, CJson *out, int *status)
static int ExchangeConfirm(AsyBaseCurTask *task, PakeParams *params, const CJson *in, int *status)
{
int res;
if (task->taskStatus < TASK_STATUS_CLIENT_BIND_EXCHANGE_REQUEST) {
LOGE("Invalid taskStatus:%d", task->taskStatus);
LOGE("Invalid taskStatus: %d", task->taskStatus);
return HC_ERR_BAD_MESSAGE;
}
if (task->taskStatus > TASK_STATUS_CLIENT_BIND_EXCHANGE_REQUEST) {
LOGI("The message is repeated, ignore it, status :%d", task->taskStatus);
LOGI("The message is repeated, ignore it, status: %d", task->taskStatus);
*status = IGNORE_MSG;
return HC_SUCCESS;
}
@@ -97,7 +96,7 @@ static int ExchangeConfirm(AsyBaseCurTask *task, PakeParams *params, const CJson
StandardBindExchangeClientTask *realTask = (StandardBindExchangeClientTask *)task;
// parse message
RETURN_IF_ERR(GetIntFromJson(in, FIELD_PEER_USER_TYPE, &(params->userTypePeer)));
(void)GetIntFromJson(in, FIELD_PEER_USER_TYPE, &(params->userTypePeer));
RETURN_IF_ERR(ParseNonceAndCipherFromJson(&(realTask->params.nonce),
&(realTask->params.exInfoCipher), in, FIELD_EX_AUTH_INFO));
@@ -119,7 +118,7 @@ static int Process(struct AsyBaseCurTaskT *task, PakeParams *params, const CJson
if (task->taskStatus == TASK_STATUS_CLIENT_BIND_EXCHANGE_BEGIN) {
res = ExchangeRequest(task, params, in, out, status);
if (res != HC_SUCCESS) {
goto err;
goto ERR;
}
return res;
}
@@ -127,24 +126,23 @@ static int Process(struct AsyBaseCurTaskT *task, PakeParams *params, const CJson
int message = 0;
res = GetIntFromJson(in, "message", &message);
if (res != HC_SUCCESS) {
goto err;
goto ERR;
}
switch (message) {
case PAKE_BIND_EXCHANGE_RESPONSE:
res = ExchangeConfirm(task, params, in, out, status);
res = ExchangeConfirm(task, params, in, status);
break;
default:
res = HC_ERR_INVALID_PARAMS;
break;
}
if (res != HC_SUCCESS) {
goto err;
goto ERR;
}
return res;
err:
ERR:
FreeAndCleanKey(&(params->baseParams.sessionKey));
SendErrorToOut(out, params->opCode, res);
return res;
}
@@ -159,7 +157,7 @@ static void DestroyStandardBindExchangeClientTask(struct AsyBaseCurTaskT *task)
HcFree(innerTask);
}
AsyBaseCurTask *CreateStandardBindExchangeClientTask()
AsyBaseCurTask *CreateStandardBindExchangeClientTask(void)
{
StandardBindExchangeClientTask *task =
(StandardBindExchangeClientTask *)HcMalloc(sizeof(StandardBindExchangeClientTask), 0);
@@ -14,8 +14,9 @@
*/
#include "standard_client_unbind_exchange_task.h"
#include "das_common.h"
#include "hc_log.h"
#include "hc_types.h"
#include "protocol_common.h"
#include "standard_exchange_message_util.h"
enum {
@@ -33,7 +34,7 @@ static int ExchangeRequest(AsyBaseCurTask *task, PakeParams *params, const CJson
{
int res;
if (task->taskStatus != TASK_STATUS_CLIENT_UNBIND_EXCHANGE_BEGIN) {
LOGI("The message is repeated, ignore it, status :%d", task->taskStatus);
LOGI("The message is repeated, ignore it, status: %d", task->taskStatus);
*status = IGNORE_MSG;
return HC_SUCCESS;
}
@@ -45,7 +46,7 @@ static int ExchangeRequest(AsyBaseCurTask *task, PakeParams *params, const CJson
CJson *sendToPeer = CreateJson();
if (sendToPeer == NULL) {
res = HC_ERR_ALLOC_MEMORY;
goto err;
goto ERR;
}
// parse message
@@ -72,13 +73,13 @@ static int ExchangeRequest(AsyBaseCurTask *task, PakeParams *params, const CJson
task->taskStatus = TASK_STATUS_CLIENT_UNBIND_EXCHANGE_REQUEST;
*status = CONTINUE;
err:
ERR:
FreeJson(data);
FreeJson(sendToPeer);
return res;
}
static int ExchangeConfirm(AsyBaseCurTask *task, PakeParams *params, const CJson *in, CJson *out, int *status)
static int ExchangeConfirm(AsyBaseCurTask *task, PakeParams *params, const CJson *in, int *status)
{
int res;
if (task->taskStatus < TASK_STATUS_CLIENT_UNBIND_EXCHANGE_REQUEST) {
@@ -87,7 +88,7 @@ static int ExchangeConfirm(AsyBaseCurTask *task, PakeParams *params, const CJson
}
if (task->taskStatus > TASK_STATUS_CLIENT_UNBIND_EXCHANGE_REQUEST) {
LOGI("The message is repeated, ignore it, status :%d", task->taskStatus);
LOGI("The message is repeated, ignore it, status: %d", task->taskStatus);
*status = IGNORE_MSG;
return HC_SUCCESS;
}
@@ -116,7 +117,7 @@ static int Process(struct AsyBaseCurTaskT *task, PakeParams *params, const CJson
if (task->taskStatus == TASK_STATUS_CLIENT_UNBIND_EXCHANGE_BEGIN) {
res = ExchangeRequest(task, params, in, out, status);
if (res != HC_SUCCESS) {
goto err;
goto ERR;
}
return res;
}
@@ -124,24 +125,23 @@ static int Process(struct AsyBaseCurTaskT *task, PakeParams *params, const CJson
int message = 0;
res = GetIntFromJson(in, "message", &message);
if (res != HC_SUCCESS) {
goto err;
goto ERR;
}
switch (message) {
case PAKE_UNBIND_EXCHANGE_RESPONSE:
res = ExchangeConfirm(task, params, in, out, status);
res = ExchangeConfirm(task, params, in, status);
break;
default:
res = HC_ERR_INVALID_PARAMS;
break;
}
if (res != HC_SUCCESS) {
goto err;
goto ERR;
}
return res;
err:
ERR:
FreeAndCleanKey(&(params->baseParams.sessionKey));
SendErrorToOut(out, params->opCode, res);
return res;
}
@@ -18,7 +18,7 @@
#include "hc_log.h"
#include "hc_types.h"
#include "json_utils.h"
#include "module_common.h"
#include "protocol_common.h"
#include "pake_base_cur_task.h"
#include "string_util.h"
@@ -30,21 +30,21 @@ int32_t PackageNonceAndCipherToJson(const Uint8Buff *nonce, const Uint8Buff *cip
if (exAuthInfoVal == NULL) {
LOGE("malloc exAuthInfoVal failed.");
res = HC_ERR_ALLOC_MEMORY;
goto err;
goto ERR;
}
if (memcpy_s(exAuthInfoVal, exAuthInfoLen, nonce->val, nonce->length) != EOK) {
LOGE("memcpy nonce failed");
res = HC_ERR_MEMORY_COPY;
goto err;
goto ERR;
}
if (memcpy_s(exAuthInfoVal + nonce->length, exAuthInfoLen - nonce->length,
cipher->val, cipher->length) != EOK) {
LOGE("memcpy exInfoCipher failed");
res = HC_ERR_MEMORY_COPY;
goto err;
goto ERR;
}
GOTO_ERR_AND_SET_RET(AddByteToJson(data, key, exAuthInfoVal, exAuthInfoLen), res);
err:
ERR:
HcFree(exAuthInfoVal);
return res;
}
@@ -57,38 +57,38 @@ int32_t ParseNonceAndCipherFromJson(Uint8Buff *nonce, Uint8Buff *cipher, const C
if (exAuthInfoStr == NULL) {
LOGE("get exAuthInfoStr failed.");
res = HC_ERR_JSON_GET;
goto err;
goto ERR;
}
int32_t exAuthInfoLen = strlen(exAuthInfoStr) / BYTE_TO_HEX_OPER_LENGTH;
exAuthInfoVal = (uint8_t *)HcMalloc(exAuthInfoLen, 0);
if (exAuthInfoVal == NULL) {
LOGE("Malloc exAuthInfoVal failed.");
res = HC_ERR_ALLOC_MEMORY;
goto err;
goto ERR;
}
res = HexStringToByte(exAuthInfoStr, exAuthInfoVal, exAuthInfoLen);
if (res != HC_SUCCESS) {
LOGE("Convert exAuthInfo from hex string to byte failed.");
goto err;
goto ERR;
}
if (memcpy_s(nonce->val, nonce->length, exAuthInfoVal, nonce->length) != EOK) {
LOGE("copy nonce failed!");
res = HC_ERR_MEMORY_COPY;
goto err;
goto ERR;
}
res = InitSingleParam(cipher, exAuthInfoLen - nonce->length);
if (res != HC_SUCCESS) {
LOGE("init exInfoCipher failed");
goto err;
goto ERR;
}
if (memcpy_s(cipher->val, cipher->length, exAuthInfoVal + nonce->length,
exAuthInfoLen - nonce->length) != EOK) {
LOGE("copy exInfoCipher failed!");
res = HC_ERR_MEMORY_COPY;
goto err;
goto ERR;
}
err:
ERR:
HcFree(exAuthInfoVal);
return res;
}
@@ -14,8 +14,9 @@
*/
#include "standard_server_bind_exchange_task.h"
#include "das_common.h"
#include "hc_log.h"
#include "hc_types.h"
#include "protocol_common.h"
#include "standard_exchange_message_util.h"
enum {
@@ -29,11 +30,11 @@ static CurTaskType GetTaskType(void)
return TASK_TYPE_BIND_STANDARD_EXCHANGE;
}
static int ExchangeStart(AsyBaseCurTask *task, PakeParams *params, const CJson *in, CJson *out, int *status)
static int ExchangeStart(AsyBaseCurTask *task, PakeParams *params, CJson *out, int *status)
{
int res = HC_SUCCESS;
if (task->taskStatus != TASK_STATUS_SERVER_BIND_EXCHANGE_BEGIN) {
LOGI("The message is repeated, ignore it, status :%d", task->taskStatus);
LOGI("The message is repeated, ignore it, status: %d", task->taskStatus);
*status = IGNORE_MSG;
return HC_SUCCESS;
}
@@ -68,7 +69,7 @@ static int ExchangeResponse(AsyBaseCurTask *task, PakeParams *params, const CJso
return HC_ERR_BAD_MESSAGE;
}
if (task->taskStatus > TASK_STATUS_SERVER_BIND_EXCHANGE_START) {
LOGI("The message is repeated, ignore it, status :%d", task->taskStatus);
LOGI("The message is repeated, ignore it, status: %d", task->taskStatus);
*status = IGNORE_MSG;
return HC_SUCCESS;
}
@@ -76,7 +77,11 @@ static int ExchangeResponse(AsyBaseCurTask *task, PakeParams *params, const CJso
StandardBindExchangeServerTask *realTask = (StandardBindExchangeServerTask *)task;
// parse message
GOTO_ERR_AND_SET_RET(GetIntFromJson(in, FIELD_PEER_USER_TYPE, &(params->userTypePeer)), res);
/*
* If failing to get userTypePeer, use the default value(DEVICE_TYPE_ACCESSORY),
* which was assigned at initialization.
*/
(void)GetIntFromJson(in, FIELD_PEER_USER_TYPE, &(params->userTypePeer));
if (params->baseParams.challengePeer.val == NULL) {
GOTO_ERR_AND_SET_RET(GetPeerChallenge(params, in), res);
}
@@ -93,13 +98,13 @@ static int ExchangeResponse(AsyBaseCurTask *task, PakeParams *params, const CJso
sendToPeer = CreateJson();
if (sendToPeer == NULL) {
res = HC_ERR_ALLOC_MEMORY;
goto err;
goto ERR;
}
GOTO_ERR_AND_SET_RET(AddIntToJson(sendToPeer, FIELD_MESSAGE, PAKE_BIND_EXCHANGE_RESPONSE), res);
data = CreateJson();
if (data == NULL) {
res = HC_ERR_ALLOC_MEMORY;
goto err;
goto ERR;
}
GOTO_ERR_AND_SET_RET(PackageNonceAndCipherToJson(&(realTask->params.nonce), &(realTask->params.exInfoCipher),
data, FIELD_EX_AUTH_INFO), res);
@@ -109,7 +114,7 @@ static int ExchangeResponse(AsyBaseCurTask *task, PakeParams *params, const CJso
task->taskStatus = TASK_STATUS_SERVER_BIND_EXCHANGE_RESPONSE;
*status = FINISH;
err:
ERR:
FreeJson(data);
FreeJson(sendToPeer);
return res;
@@ -118,14 +123,10 @@ err:
static int Process(struct AsyBaseCurTaskT *task, PakeParams *params, const CJson *in, CJson *out, int *status)
{
int res;
if ((task == NULL) || (in == NULL) || (out == NULL) || (status == NULL)) {
return HC_ERR_INVALID_PARAMS;
}
if (task->taskStatus == TASK_STATUS_SERVER_BIND_EXCHANGE_BEGIN) {
res = ExchangeStart(task, params, in, out, status);
res = ExchangeStart(task, params, out, status);
if (res != HC_SUCCESS) {
goto err;
goto ERR;
}
return res;
}
@@ -133,7 +134,7 @@ static int Process(struct AsyBaseCurTaskT *task, PakeParams *params, const CJson
int message = 0;
res = GetIntFromJson(in, "message", &message);
if (res != HC_SUCCESS) {
goto err;
goto ERR;
}
switch (message) {
@@ -145,12 +146,11 @@ static int Process(struct AsyBaseCurTaskT *task, PakeParams *params, const CJson
break;
}
if (res != HC_SUCCESS) {
goto err;
goto ERR;
}
return res;
err:
ERR:
FreeAndCleanKey(&(params->baseParams.sessionKey));
SendErrorToOut(out, params->opCode, res);
return res;
}
@@ -14,8 +14,9 @@
*/
#include "standard_server_unbind_exchange_task.h"
#include "das_common.h"
#include "hc_log.h"
#include "hc_types.h"
#include "protocol_common.h"
#include "standard_exchange_message_util.h"
enum {
@@ -29,11 +30,11 @@ static CurTaskType GetTaskType(void)
return TASK_TYPE_UNBIND_STANDARD_EXCHANGE;
}
static int ExchangeStart(AsyBaseCurTask *task, PakeParams *params, const CJson *in, CJson *out, int *status)
static int ExchangeStart(AsyBaseCurTask *task, PakeParams *params, CJson *out, int *status)
{
int res = HC_SUCCESS;
if (task->taskStatus != TASK_STATUS_SERVER_UNBIND_EXCHANGE_BEGIN) {
LOGI("The message is repeated, ignore it, status :%d", task->taskStatus);
LOGI("The message is repeated, ignore it, status: %d", task->taskStatus);
*status = IGNORE_MSG;
return HC_SUCCESS;
}
@@ -68,7 +69,7 @@ static int ExchangeResponse(AsyBaseCurTask *task, PakeParams *params, const CJso
return HC_ERR_BAD_MESSAGE;
}
if (task->taskStatus > TASK_STATUS_SERVER_UNBIND_EXCHANGE_START) {
LOGI("The message is repeated, ignore it, status :%d", task->taskStatus);
LOGI("The message is repeated, ignore it, status: %d", task->taskStatus);
*status = IGNORE_MSG;
return HC_SUCCESS;
}
@@ -91,13 +92,13 @@ static int ExchangeResponse(AsyBaseCurTask *task, PakeParams *params, const CJso
sendToPeer = CreateJson();
if (sendToPeer == NULL) {
res = HC_ERR_ALLOC_MEMORY;
goto err;
goto ERR;
}
GOTO_ERR_AND_SET_RET(AddIntToJson(sendToPeer, FIELD_MESSAGE, PAKE_UNBIND_EXCHANGE_RESPONSE), res);
data = CreateJson();
if (data == NULL) {
res = HC_ERR_ALLOC_MEMORY;
goto err;
goto ERR;
}
GOTO_ERR_AND_SET_RET(PackageNonceAndCipherToJson(&(realTask->params.nonce), &(realTask->params.resultCipher),
data, FIELD_RMV_RETURN), res);
@@ -106,7 +107,7 @@ static int ExchangeResponse(AsyBaseCurTask *task, PakeParams *params, const CJso
task->taskStatus = TASK_STATUS_SERVER_UNBIND_EXCHANGE_RESPONSE;
*status = FINISH;
err:
ERR:
FreeJson(data);
FreeJson(sendToPeer);
return res;
@@ -120,9 +121,9 @@ static int Process(struct AsyBaseCurTaskT *task, PakeParams *params, const CJson
}
if (task->taskStatus == TASK_STATUS_SERVER_UNBIND_EXCHANGE_BEGIN) {
res = ExchangeStart(task, params, in, out, status);
res = ExchangeStart(task, params, out, status);
if (res != HC_SUCCESS) {
goto err;
goto ERR;
}
return res;
}
@@ -130,7 +131,7 @@ static int Process(struct AsyBaseCurTaskT *task, PakeParams *params, const CJson
int message = 0;
res = GetIntFromJson(in, "message", &message);
if (res != HC_SUCCESS) {
goto err;
goto ERR;
}
switch (message) {
@@ -143,12 +144,11 @@ static int Process(struct AsyBaseCurTaskT *task, PakeParams *params, const CJson
}
if (res != HC_SUCCESS) {
goto err;
goto ERR;
}
return res;
err:
ERR:
FreeAndCleanKey(&(params->baseParams.sessionKey));
SendErrorToOut(out, params->opCode, res);
return res;
}
@@ -13,7 +13,7 @@
* limitations under the License.
*/
#include "das_asy_token_manager.h"
#include "das_standard_token_manager.h"
#include "standard_client_bind_exchange_task.h"
#include "standard_client_unbind_exchange_task.h"
#include "standard_server_bind_exchange_task.h"
@@ -39,7 +39,7 @@ AsyBaseCurTask *CreateStandardUnbindExchangeServerTask()
return NULL;
}
const TokenManager *GetAsyTokenManagerInstance()
const TokenManager *GetStandardTokenManagerInstance()
{
return NULL;
}
@@ -15,6 +15,13 @@
#include "das_module.h"
bool IsDasMsgNeedIgnore(const CJson *in)
{
(void)in;
LOGE("Das module is not supported.");
return false;
}
bool IsDasSupported()
{
return false;
@@ -22,5 +29,6 @@ bool IsDasSupported()
AuthModuleBase *CreateDasModule()
{
LOGE("Das module is not supported.");
return NULL;
}
+4 -3
View File
@@ -1194,7 +1194,8 @@ bool IsSameNameGroupExist(const char *ownerName, const char *groupName)
TrustedGroupEntry **entry = NULL;
g_databaseMutex->lock(g_databaseMutex);
FOR_EACH_HC_VECTOR(g_trustedGroupTable, index, entry) {
if (strcmp(StringGet(&(*entry)->name), groupName) != 0) {
if ((entry == NULL) || (*entry == NULL) ||
(strcmp(StringGet(&(*entry)->name), groupName) != 0)) {
continue;
}
if (HC_VECTOR_SIZE(&(*entry)->managers) > 0) {
@@ -1216,7 +1217,7 @@ bool IsIdenticalGroupExist(void)
TrustedGroupEntry **entry = NULL;
g_databaseMutex->lock(g_databaseMutex);
FOR_EACH_HC_VECTOR(g_trustedGroupTable, index, entry) {
if ((*entry)->type == IDENTICAL_ACCOUNT_GROUP) {
if ((entry != NULL) && (*entry != NULL) && ((*entry)->type == IDENTICAL_ACCOUNT_GROUP)) {
g_databaseMutex->unlock(g_databaseMutex);
return true;
}
@@ -1231,7 +1232,7 @@ bool IsAcrossAccountGroupExist(void)
TrustedGroupEntry **entry = NULL;
g_databaseMutex->lock(g_databaseMutex);
FOR_EACH_HC_VECTOR(g_trustedGroupTable, index, entry) {
if ((*entry)->type == ACROSS_ACCOUNT_AUTHORIZE_GROUP) {
if ((entry != NULL) && (*entry != NULL) && ((*entry)->type == ACROSS_ACCOUNT_AUTHORIZE_GROUP)) {
g_databaseMutex->unlock(g_databaseMutex);
return true;
}
+4
View File
@@ -67,6 +67,10 @@ static bool InitProcessDataTask(AuthDeviceTask *task, int64_t authReqId, CJson *
LOGE("Failed to add requestId to json!");
return false;
}
if (AddIntToJson(receivedData, FIELD_OPERATION_CODE, AUTHENTICATE) != HC_SUCCESS) {
LOGE("Failed to add operation code to json!");
return false;
}
task->authParams = receivedData;
task->callback = gaCallback;
if (task->callback == NULL) {
+40 -43
View File
@@ -22,6 +22,8 @@ group_manager_path = "${services_path}/group_manager"
enable_broadcast = true
deviceauth_defines = []
inc_path = [
"${innerkits_path}",
"${frameworks_path}/inc",
@@ -46,19 +48,20 @@ inc_path = [
"${dev_frameworks_path}/inc/module",
"${dev_frameworks_path}/inc/session",
"${dev_frameworks_path}/inc/task_manager",
"${authenticators_path}/inc/account_related/",
"${authenticators_path}/inc/account_related/tcis_auth_token_manager",
"${authenticators_path}/inc/account_related",
"${authenticators_path}/inc/account_unrelated",
"${authenticators_path}/inc/account_unrelated/iso_task",
"${authenticators_path}/inc/account_unrelated/iso_task/iso_protocol_task",
"${authenticators_path}/inc/account_unrelated/iso_task/lite_exchange_task",
"${authenticators_path}/inc/account_unrelated/pake_task",
"${authenticators_path}/inc/account_unrelated/pake_task/new_pake_task",
"${authenticators_path}/inc/account_unrelated/pake_task/pake_task",
"${authenticators_path}/inc/account_unrelated/pake_task/pake_v1_task",
"${authenticators_path}/inc/account_unrelated/pake_task/pake_v2_task",
"${protocol_path}/inc",
"${protocol_path}/inc/pake_protocol",
"${protocol_path}/inc/pake_protocol/pake_protocol",
"${protocol_path}/inc/pake_protocol/new_pake_protocol",
"${protocol_path}/inc/pake_protocol/pake_v1_protocol",
"${protocol_path}/inc/pake_protocol/pake_v2_protocol",
"${protocol_path}/inc/pake_protocol/pake_protocol_dl_common",
"${protocol_path}/inc/pake_protocol/pake_protocol_ec_common",
"${protocol_path}/inc/iso_protocol",
]
@@ -71,14 +74,17 @@ deviceauth_common_files = [
"${group_manager_path}/src/channel_manager/channel_manager.c",
"${group_manager_path}/src/callback_manager/callback_manager.c",
"${protocol_path}/src/protocol_common.c",
"${protocol_path}/src/pake_protocol/pake_protocol_common.c",
"${protocol_path}/src/iso_protocol/iso_protocol_common.c",
"${protocol_path}/src/pake_protocol/pake_common.c",
"${protocol_path}/src/pake_protocol/pake_v1_protocol/pake_v1_protocol_common.c",
"${protocol_path}/src/pake_protocol/pake_protocol_dl_common/pake_protocol_dl_common.c",
"${protocol_path}/src/pake_protocol/pake_protocol_ec_common/pake_protocol_ec_common.c",
]
dev_frameworks_files = [
"${dev_frameworks_path}/src/session/session_common.c",
"${dev_frameworks_path}/src/session/session_manager.c",
"${dev_frameworks_path}/src/module/dev_auth_module_manager.c",
"${dev_frameworks_path}/src/module/module_common.c",
"${dev_frameworks_path}/src/module/version_util.c",
"${dev_frameworks_path}/src/task_manager/task_manager.c",
]
@@ -147,17 +153,17 @@ bind_peer_mock_files = [
]
authenticators_p2p_files = [
"${authenticators_path}/src/account_unrelated/das_common.c",
"${authenticators_path}/src/account_unrelated/das_task_common.c",
"${authenticators_path}/src/account_unrelated/das_module.c",
"${authenticators_path}/src/account_unrelated/das_version_util.c",
"${authenticators_path}/src/account_unrelated/task_main.c",
"${authenticators_path}/src/account_unrelated/das_task_main.c",
"${authenticators_path}/src/account_unrelated/pake_task/pake_task_common.c",
"${authenticators_path}/src/account_unrelated/pake_task/pake_message_util.c",
]
authenticators_p2p_mock_files =
[ "${authenticators_path}/src/account_unrelated_mock/das_module_mock.c" ]
authenticators_account_related_mock_files =
[ "${authenticators_path}/src/account_related_mock/tcis_module_mock.c" ]
[ "${authenticators_path}/src/account_related_mock/account_module_mock.c" ]
authenticators_p2p_iso_files = [
"${authenticators_path}/src/account_unrelated/iso_task/iso_client_task.c",
"${authenticators_path}/src/account_unrelated/iso_task/iso_server_task.c",
@@ -165,6 +171,7 @@ authenticators_p2p_iso_files = [
"${authenticators_path}/src/account_unrelated/iso_task/iso_task_main.c",
"${authenticators_path}/src/account_unrelated/iso_task/iso_protocol_task/iso_client_protocol_task.c",
"${authenticators_path}/src/account_unrelated/iso_task/iso_protocol_task/iso_server_protocol_task.c",
"${authenticators_path}/src/account_unrelated/iso_task/lite_exchange_task/das_lite_token_manager.c",
"${authenticators_path}/src/account_unrelated/iso_task/lite_exchange_task/iso_client_bind_exchange_task.c",
"${authenticators_path}/src/account_unrelated/iso_task/lite_exchange_task/iso_client_unbind_exchange_task.c",
"${authenticators_path}/src/account_unrelated/iso_task/lite_exchange_task/iso_server_bind_exchange_task.c",
@@ -172,18 +179,18 @@ authenticators_p2p_iso_files = [
]
authenticators_p2p_iso_mock_files = [ "${authenticators_path}/src/account_unrelated/iso_task_mock/iso_task_main_mock.c" ]
authenticators_p2p_pake_files = [
"${authenticators_path}/src/account_unrelated/pake_task/pake_task/pake_task_main.c",
"${authenticators_path}/src/account_unrelated/pake_task/pake_task/pake_client_task.c",
"${authenticators_path}/src/account_unrelated/pake_task/pake_task/pake_server_task.c",
"${authenticators_path}/src/account_unrelated/pake_task/pake_task/pake_protocol_task/pake_client_protocol_task.c",
"${authenticators_path}/src/account_unrelated/pake_task/pake_task/pake_protocol_task/pake_server_protocol_task.c",
"${authenticators_path}/src/account_unrelated/pake_task/pake_task/pake_protocol_task/pake_protocol_task_common.c",
"${authenticators_path}/src/account_unrelated/pake_task/pake_v1_task/pake_v1_task_main.c",
"${authenticators_path}/src/account_unrelated/pake_task/pake_v1_task/pake_v1_client_task.c",
"${authenticators_path}/src/account_unrelated/pake_task/pake_v1_task/pake_v1_server_task.c",
"${authenticators_path}/src/account_unrelated/pake_task/pake_v1_task/pake_v1_protocol_task/pake_v1_client_protocol_task.c",
"${authenticators_path}/src/account_unrelated/pake_task/pake_v1_task/pake_v1_protocol_task/pake_v1_server_protocol_task.c",
"${authenticators_path}/src/account_unrelated/pake_task/pake_v1_task/pake_v1_protocol_task/pake_v1_protocol_task_common.c",
"${authenticators_path}/src/account_unrelated/pake_task/new_pake_task_mock/new_pake_task_main_mock.c",
"${authenticators_path}/src/account_unrelated/pake_task/pake_v2_task_mock/pake_v2_task_main_mock.c",
]
authenticators_p2p_pake_mock_files = [
"${authenticators_path}/src/account_unrelated/pake_task/pake_task_mock/pake_task_main_mock.c",
"${authenticators_path}/src/account_unrelated/pake_task/new_pake_task_mock/new_pake_task_main_mock.c",
"${authenticators_path}/src/account_unrelated/pake_task/pake_v1_task_mock/pake_v1_task_main_mock.c",
"${authenticators_path}/src/account_unrelated/pake_task/pake_v2_task_mock/pake_v2_task_main_mock.c",
]
authenticators_standard_exchange_task_files = [
@@ -193,7 +200,7 @@ authenticators_standard_exchange_task_files = [
"${authenticators_path}/src/account_unrelated/pake_task/standard_exchange_task/standard_client_unbind_exchange_task.c",
"${authenticators_path}/src/account_unrelated/pake_task/standard_exchange_task/standard_server_bind_exchange_task.c",
"${authenticators_path}/src/account_unrelated/pake_task/standard_exchange_task/standard_server_unbind_exchange_task.c",
"${authenticators_path}/src/account_unrelated/pake_task/standard_exchange_task/das_asy_token_manager.c",
"${authenticators_path}/src/account_unrelated/pake_task/standard_exchange_task/das_standard_token_manager.c",
"${authenticators_path}/src/account_unrelated/pake_task/standard_exchange_task/standard_exchange_message_util.c",
]
authenticators_standard_exchange_task_mock_files = [ "${authenticators_path}/src/account_unrelated/pake_task/standard_exchange_task_mock/standard_exchange_task_mock.c" ]
@@ -212,6 +219,13 @@ lcm_adapter_mock_files =
deviceauth_files =
dev_frameworks_files + deviceauth_common_files + key_agree_mock_files
if (enable_p2p_pake_dl_prime_len_384 == true) {
deviceauth_defines += [ "P2P_PAKE_DL_PRIME_LEN_384" ]
}
if (enable_p2p_pake_dl_prime_len_256 == true) {
deviceauth_defines += [ "P2P_PAKE_DL_PRIME_LEN_256" ]
}
if (enable_group == true) {
deviceauth_files +=
group_auth_files + group_manager_files + database_manager_files
@@ -246,6 +260,7 @@ if (enable_p2p_auth_lite_protocol == true) {
if (enable_p2p_bind_standard_protocol == true ||
enable_p2p_auth_standard_protocol == true) {
deviceauth_defines += [ "P2P_PAKE_EC_TYPE" ]
deviceauth_files += authenticators_p2p_pake_files
} else {
deviceauth_files += authenticators_p2p_pake_mock_files
@@ -259,9 +274,13 @@ if (enable_p2p_auth_standard_protocol == true) {
if (enable_group == true && enable_account == true) {
import("//base/security/deviceauth_account/deviceauth_account.gni")
deviceauth_defines += account_related_defines
inc_path += account_related_inc_path
deviceauth_files += account_related_files + bind_peer_files
} else if (enable_group == false && enable_account == true) {
import("//base/security/deviceauth_account/deviceauth_account.gni")
deviceauth_defines += account_related_defines
inc_path += account_related_inc_path
deviceauth_files +=
account_related_files + group_manager_identical_account_mock_files +
group_manager_across_account_mock_files + bind_peer_mock_files
@@ -273,28 +292,6 @@ if (enable_group == true && enable_account == true) {
lcm_adapter_mock_files + authenticators_account_related_mock_files
}
if (enable_p2p_bind_lite_protocol == true ||
enable_p2p_auth_lite_protocol == true) {
deviceauth_files +=
[ "${protocol_path}/src/iso_protocol/iso_protocol_common.c" ]
}
if (enable_p2p_bind_standard_protocol == true ||
enable_p2p_auth_standard_protocol == true) {
deviceauth_files += [
"${protocol_path}/src/pake_protocol/pake_protocol_dl/pake_protocol_dl.c",
"${protocol_path}/src/pake_protocol/pake_protocol_ec/pake_protocol_ec.c",
"${protocol_path}/src/new_pake_protocol/new_pake_protocol_dl_mock/new_pake_protocol_dl_mock.c",
"${protocol_path}/src/new_pake_protocol/new_pake_protocol_ec_mock/new_pake_protocol_ec_mock.c",
]
} else {
deviceauth_files += [
"${protocol_path}/src/pake_protocol/pake_protocol_dl_mock/pake_protocol_dl_mock.c",
"${protocol_path}/src/pake_protocol/pake_protocol_ec_mock/pake_protocol_ec_mock.c",
"${protocol_path}/src/new_pake_protocol/new_pake_protocol_dl_mock/new_pake_protocol_dl_mock.c",
"${protocol_path}/src/new_pake_protocol/new_pake_protocol_ec_mock/new_pake_protocol_ec_mock.c",
]
}
if (enable_soft_bus_channel == true) {
deviceauth_files += soft_bus_channel_files
} else {
+10 -14
View File
@@ -37,8 +37,13 @@
#define FIELD_CHANNEL_ID "channelId"
#define FIELD_CONN_DEVICE_ID "connDeviceId"
#define FIELD_CONNECT_PARAMS "connectParams"
#define FIELD_CROSS_USER_ID_LIST "crossUserIdList"
#define FIELD_CURRENT_VERSION "currentVersion"
#define FIELD_DELETE_ID "deleteId"
#define FIELD_DELETED_RESULT "deletedResult"
#define FIELD_DEVICE_CLOUD_CREDENTIAL "devCloudCred"
#define FIELD_DEV_ID "devId"
#define FIELD_DEVICES_CREDENTIAL "devicesCredential"
#define FIELD_ENC_AUTH_TOKEN "encAuthToken"
#define FIELD_ENC_RESULT "encResult"
#define FIELD_ENC_DATA "encData"
@@ -73,7 +78,6 @@
#define FIELD_PEER_DEVICE_ID "peerDeviceId"
#define FIELD_PIN_CODE "pinCode"
#define FIELD_PUBLIC_KEY "publicKey"
#define FIELD_PK_INFO "pkInfo"
#define FIELD_PKG_NAME "pkgName"
#define FIELD_SELF_AUTH_ID "selfAuthId"
#define FIELD_SELF_DEVICE_ID "selfDeviceId"
@@ -140,10 +144,10 @@ typedef enum {
typedef enum {
CREDENTIAL_TYPE_INVALID = 0,
CREDENTIAL_TYPE_AUTH_CODE = 0X0001,
CREDENTIAL_TYPE_TCIS = 0X0002,
CREDENTIAL_TYPE_ACCOUNT = 0X0002,
CREDENTIAL_TYPE_DEFAULT_CONTROLLER = 0X0003,
CREDENTIAL_TYPE_DEVICE_CLOUD = 0X0004,
CREDENTIAL_TYPE_BLE = 0X0008,
CREDENTIAL_TYPE_TEMP = 0X0008,
} CredentialType;
#define MAX_IN_PARAM_LEN 4096
@@ -175,14 +179,14 @@ typedef enum {
#define GOTO_IF_ERR(x) do { \
int32_t res = x; \
if ((res) != HC_SUCCESS) { \
goto err; \
goto ERR; \
} \
} while (0)
#define GOTO_ERR_AND_SET_RET(x, res) do { \
res = x; \
if ((res) != HC_SUCCESS) { \
goto err; \
goto ERR; \
} \
} while (0)
@@ -193,17 +197,9 @@ typedef enum {
} \
} while (0)
typedef struct AuthModuleBaseT {
int moduleType;
int (*createTask)(int *, const CJson *in, CJson *out);
int (*processTask)(int, const CJson *in, CJson *out, int *status);
void (*destroyTask)(int);
void (*destroyModule)(struct AuthModuleBaseT *module);
} AuthModuleBase;
typedef enum {
DAS_MODULE = 0x0001,
TCIS_MODULE = 0x0010,
ACCOUNT_MODULE = 0x0010,
} EnumModuleType;
typedef enum {
@@ -23,6 +23,14 @@
extern "C" {
#endif
typedef struct AuthModuleBaseT {
int moduleType;
int (*createTask)(int *, const CJson *in, CJson *out);
int (*processTask)(int, const CJson *in, CJson *out, int *status);
void (*destroyTask)(int);
void (*destroyModule)(struct AuthModuleBaseT *module);
} AuthModuleBase;
int32_t InitModules(void);
void DestroyModules(void);
@@ -41,10 +49,8 @@ int32_t DeletePeerAuthInfo(const char *pkgName, const char *serviceType, Uint8Bu
int32_t GetPublicKey(const char *pkgName, const char *serviceType, Uint8Buff *authId, int userType,
int moduleType, Uint8Buff *returnPk);
// for TCIS
int32_t SetToken(CJson *in, CJson *out, int moduleType);
int32_t DeleteToken(int moduleType);
int32_t GetRegisterProof(CJson *out, int moduleType);
// for ACCOUNT
int32_t ProcessCredentials(int credentialOpCode, const CJson *in, CJson *out, int moduleType);
#ifdef __cplusplus
}
@@ -20,7 +20,7 @@
#include "common_defs.h"
#include "protocol_common.h"
#define VERSION_FIRST_BIT 2
#define MAJOR_VERSION_NO 2
#define TMP_VERSION_STR_LEN 15
typedef struct {
@@ -30,7 +30,7 @@ typedef struct {
} VersionStruct;
int32_t VersionToString(const VersionStruct *version, char *verStr, uint32_t len);
int32_t StringToVersion(const char* verStr, uint32_t len, VersionStruct* version);
int32_t StringToVersion(const char* verStr, VersionStruct* version);
int32_t AddSingleVersionToJson(CJson *jsonObj, const VersionStruct *version);
int32_t GetSingleVersionFromJson(const CJson* jsonObj, VersionStruct *version);
@@ -14,20 +14,37 @@
*/
#include "dev_auth_module_manager.h"
#include "common_defs.h"
#include "das_module.h"
#include "hc_log.h"
#include "hc_vector.h"
#include "tcis_module.h"
#include "account_module.h"
#include "version_util.h"
#define CLIENT_FIRST_MESSAGE 0x0001
DECLARE_HC_VECTOR(AuthModuleVec, void *)
IMPLEMENT_HC_VECTOR(AuthModuleVec, void *, 1)
static AuthModuleVec g_authModuleVec;
static VersionStruct g_version;
int32_t CheckMsgRepeatability(const CJson *in, int moduleType)
{
if (in == NULL) {
LOGE("Params is null.");
return HC_ERR_NULL_PTR;
}
switch (moduleType) {
case DAS_MODULE:
return IsDasMsgNeedIgnore(in) ? HC_ERR_IGNORE_MSG : HC_SUCCESS;
case ACCOUNT_MODULE:
return CheckAccountMsgRepeatability(in);
default:
LOGE("Unsupported module type: %d.", moduleType);
return HC_ERR_MODULE_NOT_FOUNT;
}
return HC_ERROR;
}
static AuthModuleBase *GetModule(int moduleType)
{
uint32_t index;
@@ -39,61 +56,28 @@ static AuthModuleBase *GetModule(int moduleType)
}
}
}
LOGE("There is no matched module, moduleType: %d.", moduleType);
return NULL;
}
static bool IsDasMsgRepeated(const CJson *in)
{
uint32_t message = 0;
int res = GetIntFromJson(in, FIELD_MESSAGE, (int *)&message);
if (res != HC_SUCCESS) {
return false;
}
if ((message & 0xF00F) == CLIENT_FIRST_MESSAGE) {
return false;
}
LOGI("The message is repeated, ignore it message :%u.", message);
return true;
}
int32_t CheckMsgRepeatability(const CJson *in, int moduleType)
{
if (in == NULL) {
LOGE("Params is null.");
return HC_ERR_NULL_PTR;
}
switch (moduleType) {
case DAS_MODULE:
if (IsDasMsgRepeated(in)) {
return HC_ERR_IGNORE_MSG;
}
return HC_SUCCESS;
case TCIS_MODULE:
return HC_ERR_UNSUPPORTED_METHOD;
default:
LOGE("Invalid module type.");
return HC_ERR_MODULE_NOT_FOUNT;
}
}
static bool IsParamsForDasTokenManagerValid(const char *pkgName, const char *serviceType, Uint8Buff *authId,
int userType, int moduleType)
{
if (pkgName == NULL || serviceType == NULL || authId == NULL || authId->val == NULL) {
LOGE("Params is null.");
return false;
}
if (moduleType != DAS_MODULE) {
LOGE("Unsupported method in the module, moduleType: %d.", moduleType);
return false;
}
if (pkgName == NULL || serviceType == NULL || authId == NULL || authId->val == NULL) {
LOGE("Params is null.");
return false;
}
if (HcStrlen(pkgName) == 0 || HcStrlen(serviceType) == 0 || authId->length == 0) {
LOGE("The length of params is invalid!");
return false;
}
if (userType < DEVICE_TYPE_ACCESSORY || userType > DEVICE_TYPE_PROXY) {
LOGE("Invalid userType!");
LOGE("Invalid userType, userType: %d.", userType);
return false;
}
return true;
@@ -102,23 +86,19 @@ static bool IsParamsForDasTokenManagerValid(const char *pkgName, const char *ser
int32_t RegisterLocalIdentity(const char *pkgName, const char *serviceType, Uint8Buff *authId, int userType,
int moduleType)
{
if (pkgName == NULL || serviceType == NULL || authId == NULL || authId->val == NULL) {
LOGE("Params is null.");
return HC_ERR_NULL_PTR;
}
if (moduleType != DAS_MODULE) {
LOGE("Unsupported method.");
return HC_ERR_UNSUPPORTED_METHOD;
if (!IsParamsForDasTokenManagerValid(pkgName, serviceType, authId, userType, moduleType)) {
LOGE("Params for RegisterLocalIdentity is invalid.");
return HC_ERR_INVALID_PARAMS;
}
AuthModuleBase *module = GetModule(moduleType);
if (module == NULL) {
LOGE("Failed to get module!");
LOGE("Failed to get module for das.");
return HC_ERR_MODULE_NOT_FOUNT;
}
DasAuthModule *dasModule = (DasAuthModule *)module;
int32_t res = dasModule->registerLocalIdentity(pkgName, serviceType, authId, userType);
if (res != HC_SUCCESS) {
LOGE("An error occurs when the module processes task!");
LOGE("Register local identity failed, res: %x.", res);
return res;
}
return HC_SUCCESS;
@@ -127,23 +107,19 @@ int32_t RegisterLocalIdentity(const char *pkgName, const char *serviceType, Uint
int32_t UnregisterLocalIdentity(const char *pkgName, const char *serviceType, Uint8Buff *authId, int userType,
int moduleType)
{
if (pkgName == NULL || serviceType == NULL || authId == NULL || authId->val == NULL) {
LOGE("Params is null.");
return HC_ERR_NULL_PTR;
}
if (moduleType != DAS_MODULE) {
LOGE("Unsupported method.");
return HC_ERR_UNSUPPORTED_METHOD;
if (!IsParamsForDasTokenManagerValid(pkgName, serviceType, authId, userType, moduleType)) {
LOGE("Params for UnregisterLocalIdentity is invalid.");
return HC_ERR_INVALID_PARAMS;
}
AuthModuleBase *module = GetModule(moduleType);
if (module == NULL) {
LOGE("Failed to get module!");
LOGE("Failed to get module for das.");
return HC_ERR_MODULE_NOT_FOUNT;
}
DasAuthModule *dasModule = (DasAuthModule *)module;
int32_t res = dasModule->unregisterLocalIdentity(pkgName, serviceType, authId, userType);
if (res != HC_SUCCESS) {
LOGE("An error occurs when the module processes task!");
LOGE("Unregister local identity failed, res: %x.", res);
return res;
}
return HC_SUCCESS;
@@ -152,23 +128,19 @@ int32_t UnregisterLocalIdentity(const char *pkgName, const char *serviceType, Ui
int32_t DeletePeerAuthInfo(const char *pkgName, const char *serviceType, Uint8Buff *authId, int userType,
int moduleType)
{
if (pkgName == NULL || serviceType == NULL || authId == NULL || authId->val == NULL) {
LOGE("Params is null.");
return HC_ERR_NULL_PTR;
}
if (moduleType != DAS_MODULE) {
LOGE("Unsupported method.");
return HC_ERR_UNSUPPORTED_METHOD;
if (!IsParamsForDasTokenManagerValid(pkgName, serviceType, authId, userType, moduleType)) {
LOGE("Params for DeletePeerAuthInfo is invalid.");
return HC_ERR_INVALID_PARAMS;
}
AuthModuleBase *module = GetModule(moduleType);
if (module == NULL) {
LOGE("Failed to get module!");
LOGE("Failed to get module for das.");
return HC_ERR_MODULE_NOT_FOUNT;
}
DasAuthModule *dasModule = (DasAuthModule *)module;
int32_t res = dasModule->deletePeerAuthInfo(pkgName, serviceType, authId, userType);
if (res != HC_SUCCESS) {
LOGE("An error occurs when the module processes task!");
LOGE("Delete peer authInfo failed, res: %x.", res);
return res;
}
return HC_SUCCESS;
@@ -183,7 +155,7 @@ int32_t GetPublicKey(const char *pkgName, const char *serviceType, Uint8Buff *au
}
AuthModuleBase *module = GetModule(moduleType);
if (module == NULL) {
LOGE("Failed to get module!");
LOGE("Failed to get module for das.");
return HC_ERR_MODULE_NOT_FOUNT;
}
DasAuthModule *dasModule = (DasAuthModule *)module;
@@ -195,122 +167,56 @@ int32_t GetPublicKey(const char *pkgName, const char *serviceType, Uint8Buff *au
return HC_SUCCESS;
}
int32_t SetToken(CJson *in, CJson *out, int moduleType)
{
if (in == NULL || out == NULL) {
LOGE("Params is null.");
return HC_ERR_NULL_PTR;
}
if (moduleType != TCIS_MODULE) {
LOGE("Unsupported method.");
return HC_ERR_UNSUPPORTED_METHOD;
}
AuthModuleBase *module = GetModule(moduleType);
if (module == NULL) {
LOGE("Failed to get module!");
return HC_ERR_MODULE_NOT_FOUNT;
}
TcisAuthModule *realModule = (TcisAuthModule *)module;
if (realModule->tokenManager == NULL) {
LOGE("Tcis tokenManager is null");
return HC_ERR_MODULE_NOT_FOUNT;
}
realModule->tokenManager->setToken(in, out);
return HC_SUCCESS;
}
int32_t DeleteToken(int moduleType)
{
if (moduleType != TCIS_MODULE) {
LOGE("Unsupported method.");
return HC_ERR_UNSUPPORTED_METHOD;
}
AuthModuleBase *module = GetModule(moduleType);
if (module == NULL) {
LOGE("Failed to get module!");
return HC_ERR_MODULE_NOT_FOUNT;
}
TcisAuthModule *realModule = (TcisAuthModule *)module;
if (realModule->tokenManager == NULL) {
LOGE("Tcis tokenManager is null");
return HC_ERR_MODULE_NOT_FOUNT;
}
realModule->tokenManager->deleteToken();
return HC_SUCCESS;
}
int32_t GetRegisterProof(CJson *out, int moduleType)
{
if (out == NULL) {
LOGE("Params is null.");
return HC_ERR_NULL_PTR;
}
if (moduleType != TCIS_MODULE) {
LOGE("Unsupported method.");
return HC_ERR_UNSUPPORTED_METHOD;
}
AuthModuleBase *module = GetModule(moduleType);
if (module == NULL) {
LOGE("Failed to get module!");
return HC_ERR_MODULE_NOT_FOUNT;
}
TcisAuthModule *realModule = (TcisAuthModule *)module;
if (realModule->tokenManager == NULL) {
LOGE("Tcis tokenManager is null");
return HC_ERR_MODULE_NOT_FOUNT;
}
realModule->tokenManager->getRegisterProof(out);
return HC_SUCCESS;
}
int32_t ProcessTask(int taskId, const CJson *in, CJson *out, int *status, int moduleType)
{
if (in == NULL || out == NULL || status == NULL) {
LOGE("Params is null.");
return HC_ERR_NULL_PTR;
}
AuthModuleBase *module = GetModule(moduleType);
if (module == NULL) {
LOGE("Failed to get module!");
return HC_ERR_MODULE_NOT_FOUNT;
}
if (module->processTask == NULL) {
LOGE("Unsupported method.");
LOGE("Unsupported method in the module, moduleType: %d.", moduleType);
return HC_ERR_UNSUPPORTED_METHOD;
}
int32_t res = module->processTask(taskId, in, out, status);
if (res != HC_SUCCESS) {
LOGE("An error occurs when the module processes task!");
LOGE("Process task failed, taskId: %d, moduleType: %d, res: %d.", taskId, moduleType, res);
return res;
}
res = AddSingleVersionToJson(out, &g_version);
if (res != HC_SUCCESS) {
LOGE("AddSingleVersionToJson failed, res:%d", res);
} else {
LOGI("Process task success.");
LOGE("AddSingleVersionToJson failed, res: %x.", res);
return res;
}
LOGI("Process task success, taskId: %d, moduleType: %d.", taskId, moduleType);
return res;
}
int32_t CreateTask(int *taskId, const CJson *in, CJson *out, int moduleType)
{
if (in == NULL || out == NULL || taskId == NULL) {
LOGE("Params is null.");
return HC_ERR_NULL_PTR;
}
AuthModuleBase *module = GetModule(moduleType);
if (module == NULL) {
LOGE("Failed to get module!");
return HC_ERR_MODULE_NOT_FOUNT;
}
if (module->createTask == NULL) {
LOGE("Unsupported method.");
LOGE("Unsupported method in the module, moduleType: %d.", moduleType);
return HC_ERR_UNSUPPORTED_METHOD;
}
int32_t res = module->createTask(taskId, in, out);
if (res != HC_SUCCESS) {
LOGE("An error occurs when the module create task!");
LOGE("Create task failed, taskId: %d, moduleType: %d, res: %d.", *taskId, moduleType, res);
return res;
}
LOGI("Create task success.");
LOGI("Create task success, taskId: %d, moduleType: %d.", *taskId, moduleType);
return HC_SUCCESS;
}
@@ -321,36 +227,31 @@ void DestroyTask(int taskId, int moduleType)
return;
}
if (module->destroyTask == NULL) {
LOGE("Unsupported method.");
LOGE("Unsupported method in the module, moduleType: %d.", moduleType);
return;
}
module->destroyTask(taskId);
}
static AuthModuleBase *CreateDasModuleStatic(void)
{
return CreateDasModule();
}
static uint32_t InitDasModule(void)
{
AuthModuleBase *das = CreateDasModuleStatic();
AuthModuleBase *das = CreateDasModule();
if (das == NULL) {
LOGE("CreateDasModuleStatic failed.");
LOGE("Create das module failed.");
return HC_ERR_ALLOC_MEMORY;
}
g_authModuleVec.pushBackT(&g_authModuleVec, (void *)das);
return HC_SUCCESS;
}
static uint32_t InitTcisModule(void)
static uint32_t InitAccountModule(void)
{
AuthModuleBase *tcis = CreateTcisModule();
if (tcis == NULL) {
LOGE("Create tcis module failed.");
AuthModuleBase *accountModule = CreateAccountModule();
if (accountModule == NULL) {
LOGE("Create account module failed.");
return HC_ERR_ALLOC_MEMORY;
}
g_authModuleVec.pushBackT(&g_authModuleVec, (void *)tcis);
g_authModuleVec.pushBackT(&g_authModuleVec, (void *)accountModule);
return HC_SUCCESS;
}
@@ -358,24 +259,27 @@ int32_t InitModules(void)
{
g_authModuleVec = CREATE_HC_VECTOR(AuthModuleVec)
InitGroupAndModuleVersion(&g_version);
int res = HC_SUCCESS;
int res;
if (IsDasSupported()) {
res = InitDasModule();
if (res != HC_SUCCESS) {
LOGE("InitDasModule failed.");
DESTROY_HC_VECTOR(AuthModuleVec, &g_authModuleVec)
LOGE("Init das module failed, res: %x.", res);
DestroyModules();
return res;
}
g_version.third |= DAS_MODULE;
}
if (IsTcisSupported()) {
res = InitTcisModule();
if (IsAccountSupported()) {
res = InitAccountModule();
if (res != HC_SUCCESS) {
LOGE("InitTcisModule failed.");
DESTROY_HC_VECTOR(AuthModuleVec, &g_authModuleVec)
LOGE("Init account module failed, res: %x.", res);
DestroyModules();
return res;
}
g_version.third |= TCIS_MODULE;
g_version.third |= ACCOUNT_MODULE;
}
return res;
LOGI("Init modules success!");
return HC_SUCCESS;
}
void DestroyModules(void)
@@ -390,3 +294,13 @@ void DestroyModules(void)
DESTROY_HC_VECTOR(AuthModuleVec, &g_authModuleVec)
(void)memset_s(&g_version, sizeof(VersionStruct), 0, sizeof(VersionStruct));
}
int32_t ProcessCredentials(int credentialOpCode, const CJson *in, CJson *out, int moduleType)
{
if (moduleType != ACCOUNT_MODULE) {
LOGE("Unsupported method in the module, moduleType: %d.", moduleType);
return HC_ERR_NOT_SUPPORT;
}
return ProcessAccountCredentials(credentialOpCode, in, out);
}
@@ -1,37 +0,0 @@
/*
* Copyright (C) 2021 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 "module_common.h"
#include "common_defs.h"
#include "hc_log.h"
#include "hc_types.h"
int32_t InitSingleParam(Uint8Buff *param, uint32_t len)
{
if (param->val != NULL) {
(void)memset_s(param->val, param->length, 0, param->length);
HcFree(param->val);
param->val = NULL;
param->length = 0;
}
param->length = len;
param->val = (uint8_t *)HcMalloc(param->length, 0);
if (param->val == NULL) {
LOGE("Malloc for param failed.");
return HC_ERR_ALLOC_MEMORY;
}
return HC_SUCCESS;
}
+39 -30
View File
@@ -14,18 +14,17 @@
*/
#include "version_util.h"
#include "securec.h"
#include "hc_log.h"
#include "hc_types.h"
#include "protocol_common.h"
#include "string_util.h"
static const char *Split(char *str, char delim, int *next)
static const char *GetSlice(char *str, char delim, int *nextIdx)
{
int len = strlen(str);
for (int i = 0; i < len; i++) {
uint32_t len = HcStrlen(str);
for (uint32_t i = 0; i < len; i++) {
if (str[i] == delim) {
*next = *next + i + 1;
*nextIdx = *nextIdx + i + 1;
str[i] = '\0';
return str;
}
@@ -33,52 +32,50 @@ static const char *Split(char *str, char delim, int *next)
return str;
}
int32_t StringToVersion(const char* verStr, uint32_t len, VersionStruct* version)
int32_t StringToVersion(const char* verStr, VersionStruct* version)
{
CHECK_PTR_RETURN_ERROR_CODE(version, "version");
CHECK_PTR_RETURN_ERROR_CODE(verStr, "verStr");
if (*(verStr + len) != '\0') {
return HC_ERR_INVALID_PARAMS;
}
const char *subVer = NULL;
int next = 0;
int nextIdx = 0;
uint32_t len = HcStrlen(verStr);
char *verStrTmp = (char *)HcMalloc(len + 1, 0);
if (verStrTmp == NULL) {
LOGE("Malloc verStrTmp failed.");
LOGE("Malloc for verStrTmp failed.");
return HC_ERR_ALLOC_MEMORY;
}
if (memcpy_s(verStrTmp, len + 1, verStr, len) != EOK) {
LOGE("Memcpy verStrTmp failed.");
LOGE("Memcpy for verStrTmp failed.");
HcFree(verStrTmp);
return HC_ERR_MEMORY_COPY;
}
subVer = Split(verStrTmp, '.', &next);
subVer = GetSlice(verStrTmp, '.', &nextIdx);
if (subVer == NULL) {
goto err;
goto CLEAN_UP;
}
version->first = (uint32_t)strtoul(subVer, NULL, DEC);
subVer = Split(verStrTmp + next, '.', &next);
subVer = GetSlice(verStrTmp + nextIdx, '.', &nextIdx);
if (subVer == NULL) {
goto err;
goto CLEAN_UP;
}
version->second = (uint32_t)strtoul(subVer, NULL, DEC);
subVer = Split(verStrTmp + next, '.', &next);
subVer = GetSlice(verStrTmp + nextIdx, '.', &nextIdx);
if (subVer == NULL) {
goto err;
goto CLEAN_UP;
}
version->third = (uint32_t)strtoul(subVer, NULL, DEC);
HcFree(verStrTmp);
return HC_SUCCESS;
err:
LOGE("Split failed");
CLEAN_UP:
LOGE("GetSlice failed.");
HcFree(verStrTmp);
return HC_ERR_NULL_PTR;
return HC_ERROR;
}
int32_t VersionToString(const VersionStruct *version, char *verStr, uint32_t len)
@@ -87,11 +84,18 @@ int32_t VersionToString(const VersionStruct *version, char *verStr, uint32_t len
CHECK_PTR_RETURN_ERROR_CODE(verStr, "verStr");
char tmpStr[TMP_VERSION_STR_LEN] = { 0 };
if (sprintf_s(tmpStr, TMP_VERSION_STR_LEN, "%d.%d.%d", version->first, version->second, version->third) == -1) {
return HC_ERROR;
if (sprintf_s(tmpStr, TMP_VERSION_STR_LEN, "%d.%d.%d", version->first, version->second, version->third) <= 0) {
LOGE("Convert version struct to string failed.");
return HC_ERR_CONVERT_FAILED;
}
uint32_t tmpStrLen = HcStrlen(tmpStr);
if (len < tmpStrLen + 1) {
LOGE("The length of verStr is too short, len: %u.", len);
return HC_ERR_INVALID_LEN;
}
if (memcpy_s(verStr, len, tmpStr, strlen(tmpStr) + 1) != 0) {
if (memcpy_s(verStr, len, tmpStr, tmpStrLen + 1) != 0) {
LOGE("Memcpy for verStr failed.");
return HC_ERR_MEMORY_COPY;
}
@@ -106,7 +110,8 @@ int32_t AddSingleVersionToJson(CJson *jsonObj, const VersionStruct *version)
char versionStr[TMP_VERSION_STR_LEN] = { 0 };
int32_t ret = VersionToString(version, versionStr, TMP_VERSION_STR_LEN);
if (ret != HC_SUCCESS) {
return HC_ERROR;
LOGE("VersionToString failed, res: %x.", ret);
return ret;
}
CJson *sendToPeer = GetObjFromJson(jsonObj, FIELD_SEND_TO_PEER);
@@ -127,11 +132,15 @@ int32_t GetSingleVersionFromJson(const CJson* jsonObj, VersionStruct *version)
CHECK_PTR_RETURN_ERROR_CODE(version, "version");
const char *versionStr = GetStringFromJson(jsonObj, FIELD_GROUP_AND_MODULE_VERSION);
CHECK_PTR_RETURN_ERROR_CODE(versionStr, "versionStr");
if (versionStr == NULL) {
LOGE("Get group and module version from json failed.");
return HC_ERR_JSON_GET;
}
int32_t ret = StringToVersion(versionStr, strlen(versionStr), version);
int32_t ret = StringToVersion(versionStr, version);
if (ret != HC_SUCCESS) {
return HC_ERROR;
LOGE("StringToVersion failed, res: %x.", ret);
return ret;
}
return HC_SUCCESS;
}
@@ -139,10 +148,10 @@ int32_t GetSingleVersionFromJson(const CJson* jsonObj, VersionStruct *version)
void InitGroupAndModuleVersion(VersionStruct *version)
{
if (version == NULL) {
LOGE("version is invalid.");
LOGE("Version is null.");
return;
}
version->first = VERSION_FIRST_BIT;
version->first = MAJOR_VERSION_NO;
version->second = 0;
version->third = 0;
}
@@ -287,20 +287,19 @@ void OnChannelOpened(int64_t requestId, int64_t channelId)
uint32_t index;
void **session = NULL;
FOR_EACH_HC_VECTOR(g_sessionManagerVec, index, session) {
if (session != NULL && (*session != NULL)) {
if (((Session *)(*session))->sessionId == sessionId) {
int sessionType = ((Session *)(*session))->type;
if ((sessionType == TYPE_CLIENT_BIND_SESSION) ||
(sessionType == TYPE_CLIENT_BIND_SESSION_LITE) ||
(sessionType == TYPE_CLIENT_KEY_AGREE_SESSION)) {
BindSession *realSession = (BindSession *)(*session);
realSession->onChannelOpened(*session, channelId, requestId);
return;
}
LOGE("The type of the found session is not as expected!");
return;
}
if (session == NULL || (*session == NULL) || (((Session *)(*session))->sessionId != sessionId)) {
continue;
}
int sessionType = ((Session *)(*session))->type;
if ((sessionType == TYPE_CLIENT_BIND_SESSION) ||
(sessionType == TYPE_CLIENT_BIND_SESSION_LITE) ||
(sessionType == TYPE_CLIENT_KEY_AGREE_SESSION)) {
BindSession *realSession = (BindSession *)(*session);
realSession->onChannelOpened(*session, channelId, requestId);
return;
}
LOGE("The type of the found session is not as expected!");
return;
}
}
@@ -20,11 +20,12 @@
#include "base_group_auth.h"
#include "database_manager.h"
typedef void (*GetTcisCandidateGroupFunc)(const CJson *param, const GroupQueryParams *queryParams, GroupInfoVec *vec);
typedef void (*GetAccountCandidateGroupFunc)(const CJson *param, const GroupQueryParams *queryParams,
GroupInfoVec *vec);
typedef struct {
BaseGroupAuth base;
GetTcisCandidateGroupFunc getTcisCandidateGroup;
GetAccountCandidateGroupFunc getAccountCandidateGroup;
} AccountRelatedGroupAuth;
#ifdef __cplusplus

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