attest ok

fix memory leak, remove HKS_ERROR_NO_PERMISSION device id attest case for HksAnonAttestKey
Revert "add code for delete failed TDD", This reverts commit 663233db03.
ASSERT_TRUE == -> ASSERT_EQ, remove useless header

Signed-off-by: code4lala <fengziteng2@huawei.com>
Change-Id: Ie28724b5fa950eae46b708bf64e8bdfee1a1b17f
This commit is contained in:
code4lala 2023-12-19 17:03:21 +08:00
parent 9a98774a0f
commit 8afe13145d
55 changed files with 880 additions and 619 deletions

View File

@ -95,7 +95,7 @@ static int32_t GetString(napi_env env, napi_value object, char **element, size_t
CIPHER_LOG_E("input is not a string-type object");
return ERROR_SUCCESS;
}
status = napi_get_value_string_utf8(env, object, nullptr, 0, len);
if (status != napi_ok) {
return ERROR_CODE_GENERAL;
@ -491,7 +491,7 @@ void SetFail(napi_env env, CallbackContext *asyncContext)
napi_value errorCode = nullptr;
napi_create_int32(env, ERROR_CODE, &errorCode);
napi_value params[FAIL_ARG] = { result, errorCode };
napi_get_reference_value(env, asyncContext->callbackFail, &callback);
napi_call_function(env, nullptr, callback, FAIL_ARG, params, &ret);

View File

@ -125,6 +125,15 @@ int32_t HksCheckOptionalParam(uint32_t tag, uint32_t alg, uint32_t purpose, bool
int32_t HksCheckNeedCache(uint32_t alg, uint32_t digest);
int32_t HksCheckUserAuthKeyInfoValidity(const struct HksParamSet *paramSet);
inline bool HksAttestIsAnonymous(const struct HksParamSet *paramSet)
{
struct HksParam *attestParam = NULL;
if (HksGetParam(paramSet, HKS_TAG_ATTESTATION_MODE, &attestParam) == HKS_SUCCESS) {
return attestParam->uint32Param == HKS_ATTESTATION_MODE_ANONYMOUS;
}
return false;
}
#ifdef __cplusplus
}
#endif

View File

@ -75,7 +75,7 @@ static int32_t HksOpensslFillRandomInner(struct HksBlob *randomData, bool isPriv
return HKS_ERROR_CRYPTO_ENGINE_ERROR;
}
HKS_LOG_D("generate random success, isPriv =%" LOG_PUBLIC "d", isPriv);
return HKS_SUCCESS;
}

View File

@ -86,10 +86,19 @@ if (os_level == "standard") {
"./ipc/src/hks_ipc_check.c",
"./ipc/src/hks_ipc_slice.c",
"./ipc/src/hks_request.cpp",
"//base/security/huks/services/huks_standard/huks_service/main/os_dependency/sa/hks_sa_interface.cpp"
# both client side and server side will include hks_sa_interface.cpp
"../../../../services/huks_standard/huks_service/main/os_dependency/sa/hks_sa_interface.cpp",
]
include_dirs = [ "//base/security/huks/services/huks_standard/huks_service/main/os_dependency/sa" ]
if (huks_security_level == "software") {
defines = [ "HKS_UNTRUSTED_RUNNING_ENV" ]
}
include_dirs = [
# hks_sa_interface.cpp will include hks_sa_interface.h which is in the following directory.
"../../../../services/huks_standard/huks_service/main/os_dependency/sa",
]
if (huks_use_rkc_in_standard) {
sources += [

View File

@ -15,12 +15,17 @@
#include "hks_request.h"
#include <iservice_registry.h>
#include <message_option.h>
#include <securec.h>
#include "iservice_registry.h"
#include "hks_base_check.h" // for HksAttestIsAnonymous
#include "hks_log.h"
#include "hks_param.h"
#include "hks_sa_interface.h"
#include "hks_template.h"
#include "hks_type.h"
#include "huks_service_ipc_interface_code.h"
using namespace OHOS;
@ -69,6 +74,54 @@ static int32_t HksReadRequestReply(MessageParcel &reply, struct HksBlob *outBlob
return HKS_SUCCESS;
}
static int32_t HksSendAnonAttestRequestAndWaitAsyncReply(MessageParcel &data, const struct HksParamSet *paramSet,
sptr<IRemoteObject> hksProxy, sptr<Security::Hks::HksStub> hksCallback, struct HksBlob *outBlob)
{
#ifndef HKS_UNTRUSTED_RUNNING_ENV
HKS_IF_NOT_SUCC_LOGE_RETURN(CheckBlob(outBlob), HKS_ERROR_INVALID_ARGUMENT, "invalid outBlob");
MessageParcel reply{};
// We send the request in sync mode, and we send a stub instance in the request.
// We wait for the instance callback later.
MessageOption option = MessageOption::TF_SYNC;
int error = hksProxy->SendRequest(HKS_MSG_ATTEST_KEY, data, reply, option);
HKS_IF_NOT_SUCC_LOGE_RETURN(error, HKS_ERROR_IPC_MSG_FAIL, "hksProxy->SendRequest failed %" LOG_PUBLIC "d", error);
HksBlob tmpBlob = *outBlob;
int ret = HksReadRequestReply(reply, &tmpBlob);
if (ret != HKS_SUCCESS) {
HKS_LOG_E("HksSendAnonAttestRequestAndWaitAsyncReply HksReadRequestReply failed %" LOG_PUBLIC "d", ret);
return ret;
}
int timeout = 10; // seconds
auto [errCode, packedCerts, packedSize] = hksCallback->WaitForAsyncReply(timeout);
if (errCode != HKS_SUCCESS || packedCerts == nullptr || packedSize == 0) {
HKS_LOG_E("errCode %" LOG_PUBLIC "u fail or packedCerts empty or size %" LOG_PUBLIC "u 0", errCode, packedSize);
return HUKS_ERR_CODE_EXTERNAL_ERROR;
}
if (outBlob->size < packedSize) {
HKS_LOG_E("out blob empty or too small %" LOG_PUBLIC "u %" LOG_PUBLIC "u", outBlob->size, packedSize);
return HKS_ERROR_INVALID_ARGUMENT;
}
errno_t err = memcpy_s(outBlob->data, outBlob->size, packedCerts.get(), packedSize);
if (err != EOK) {
HKS_LOG_E("memcpy_s failed destMax %" LOG_PUBLIC "u count %" LOG_PUBLIC "u", outBlob->size, packedSize);
return HKS_ERROR_INVALID_ARGUMENT;
}
outBlob->size = packedSize;
return HKS_SUCCESS;
#else
(void)(data);
(void)(paramSet);
(void)(hksProxy);
(void)(hksCallback);
(void)(outBlob);
return HKS_SUCCESS;
#endif
}
int32_t HksSendRequest(enum HksIpcInterfaceCode type, const struct HksBlob *inBlob,
struct HksBlob *outBlob, const struct HksParamSet *paramSet)
{
@ -100,8 +153,25 @@ int32_t HksSendRequest(enum HksIpcInterfaceCode type, const struct HksBlob *inBl
sptr<IRemoteObject> hksProxy = GetHksProxy();
HKS_IF_NULL_LOGE_RETURN(hksProxy, HKS_ERROR_BAD_STATE, "GetHksProxy registry is null")
if (type == HKS_MSG_ATTEST_KEY) {
sptr<Security::Hks::HksStub> hksCallback = new (std::nothrow) Security::Hks::HksStub();
HKS_IF_NULL_LOGE_RETURN(hksCallback, HKS_ERROR_INSUFFICIENT_MEMORY, "new HksStub failed")
// We write a HksStub instance if type == HKS_MSG_ATTEST_KEY,
// then we can read it in the server side if type == HKS_MSG_ATTEST_KEY.
bool result = data.WriteRemoteObject(hksCallback);
if (!result) {
HKS_LOG_E("WriteRemoteObject hksCallback failed %" LOG_PUBLIC "d", result);
return HKS_ERROR_IPC_MSG_FAIL;
}
if (HksAttestIsAnonymous(paramSet)) {
return HksSendAnonAttestRequestAndWaitAsyncReply(data, paramSet, hksProxy, hksCallback, outBlob);
}
// If the mode is non-anonymous attest, we write a HksStub instance here, then go back and process as normal.
}
int error = hksProxy->SendRequest(type, data, reply, option);
if (error != 0) {
HKS_LOG_E("hksProxy->SendRequest failed %" LOG_PUBLIC "d", error);
return HKS_ERROR_IPC_MSG_FAIL;
}

View File

@ -73,6 +73,7 @@ extern "C" {
#define SECURE_SIGN_VERSION 0x01000001
#define HKS_CERT_COUNT 4
#define HKS_ANON_CERT_COUNT 3
#define HKS_CERT_ROOT_SIZE 2048
#define HKS_CERT_CA_SIZE 2048
#define HKS_CERT_DEVICE_SIZE 2048

View File

@ -219,7 +219,7 @@
HDI_ADAPTER_PARAM(paramSet, &paramSetCore), \
HDI_ADAPTER_PARAM(srcData, &srcDataCore), \
HDI_ADAPTER_PARAM(signature, &signatureCore));
#define HDI_CONVERTER_FUNC_ENCRYPT(key, paramSet, plainText, cipherText, ret, func) \
struct HuksBlob keyCore = {0}; \
struct HuksParamSet paramSetCore = {0}; \

View File

@ -551,7 +551,7 @@ HKS_API_EXPORT int32_t HksGetKeyInfoList(const struct HksParamSet *paramSet,
#ifdef HKS_SUPPORT_API_ATTEST_KEY
static int32_t ConstructNewAttestParamSet(const struct HksParamSet *paramSet, enum HksAttestationMode mode,
enum HksSendType sendType, struct HksParamSet **newParamSet)
struct HksParamSet **newParamSet)
{
int32_t ret = HksCheckParamSet(paramSet, paramSet->paramSetSize);
if (ret != HKS_SUCCESS) {
@ -578,15 +578,6 @@ static int32_t ConstructNewAttestParamSet(const struct HksParamSet *paramSet, en
HKS_LOG_E("add param attestMode fail");
break;
}
// struct HksParam sendMode = {
// .tag = HKS_TAG_IS_ASYNCHRONIZED,
// .uint32Param = sendType,
// };
// ret = HksAddParams(*newParamSet, &sendMode, 1);
// if (ret != HKS_SUCCESS) {
// HKS_LOG_E("add param sendMode fail");
// break;
// }
ret = HksBuildParamSet(newParamSet);
if (ret != HKS_SUCCESS) {
HKS_LOG_E("build paramSet fail");

View File

@ -47,7 +47,7 @@ struct HksLiteApiResult {
int32_t HksParseParamSetWithAdd(const JSIValue* args, uint32_t index, struct HksParamSet **outParamSet,
struct HksParam *paramsToAdd, uint32_t paramsToAddSize);
int32_t HksParseKeyAlias(const JSIValue* args, uint32_t index, struct HksBlob *outKeyAliasBlob);
int32_t HksParseHandle(const JSIValue* args, uint32_t index, struct HksBlob *outHandle);

View File

@ -287,7 +287,7 @@ int32_t HksParseParamSetWithAdd(const JSIValue* args, uint32_t index, struct Hks
struct HksParam *paramsToAdd, uint32_t paramsToAddSize)
{
std::vector<HksParam> paramsVector;
JSIValue paramSetValue = nullptr;
int32_t ret;
do {

View File

@ -102,7 +102,7 @@ napi_ref GetCallback(napi_env env, napi_value object);
napi_value GetHandleValue(napi_env env, napi_value object, struct HksBlob *&handleBlob);
void FreeHksCertChain(HksCertChain *&certChain);
void FreeHksCertChain(HksCertChain *&certChain, uint32_t certChainCapacity);
void DeleteCommonAsyncContext(napi_env env, napi_async_work &asyncWork, napi_ref &callback,
struct HksBlob *&blob, struct HksParamSet *&paramSet);

View File

@ -32,7 +32,6 @@ constexpr int HUKS_NAPI_ATTEST_KEY_MAX_ARGS = 3;
constexpr int INDEX_0 = 0;
constexpr int INDEX_1 = 1;
constexpr int INDEX_2 = 2;
constexpr int INDEX_3 = 3;
} // namespace
struct AttestKeyAsyncContextT {
@ -44,6 +43,7 @@ struct AttestKeyAsyncContextT {
struct HksBlob *keyAlias = nullptr;
struct HksParamSet *paramSet = nullptr;
struct HksCertChain *certChain = nullptr;
uint32_t certChainCapacity = 0;
};
using AttestKeyAsyncContext = AttestKeyAsyncContextT *;
@ -62,7 +62,7 @@ static void DeleteAttestKeyAsyncContext(napi_env env, AttestKeyAsyncContext &con
return;
}
DeleteCommonAsyncContext(env, context->asyncWork, context->callback, context->keyAlias, context->paramSet);
FreeHksCertChain(context->certChain);
FreeHksCertChain(context->certChain, context->certChainCapacity);
HksFree(context);
context = nullptr;
}
@ -107,35 +107,31 @@ static napi_value AttestKeyParseParams(napi_env env, napi_callback_info info, At
return GetInt32(env, 0);
}
static int32_t InitCertChain(struct HksCertChain *certChain)
static int32_t InitCertChain(struct HksCertChain *certChain, uint32_t *certChainCapacity)
{
certChain->certsCount = HKS_CERT_COUNT;
certChain->certsCount = HKS_ANON_CERT_COUNT;
certChain->certs = static_cast<struct HksBlob *>(HksMalloc(certChain->certsCount * sizeof(struct HksBlob)));
if (certChain->certs != nullptr) {
certChain->certs[INDEX_0].size = HKS_CERT_APP_SIZE;
certChain->certs[INDEX_0].data = static_cast<uint8_t *>(HksMalloc(certChain->certs[INDEX_0].size));
if (certChain->certs[INDEX_0].data == nullptr) {
FreeHksCertChain(certChain);
return HKS_ERROR_INSUFFICIENT_MEMORY;
}
certChain->certs[INDEX_1].size = HKS_CERT_DEVICE_SIZE;
certChain->certs[INDEX_1].data = static_cast<uint8_t *>(HksMalloc(certChain->certs[INDEX_1].size));
if (certChain->certs[INDEX_1].data == nullptr) {
FreeHksCertChain(certChain);
return HKS_ERROR_INSUFFICIENT_MEMORY;
}
certChain->certs[INDEX_2].size = HKS_CERT_CA_SIZE;
certChain->certs[INDEX_2].data = static_cast<uint8_t *>(HksMalloc(certChain->certs[INDEX_2].size));
if (certChain->certs[INDEX_2].data == nullptr) {
FreeHksCertChain(certChain);
return HKS_ERROR_INSUFFICIENT_MEMORY;
}
certChain->certs[INDEX_3].size = HKS_CERT_ROOT_SIZE;
certChain->certs[INDEX_3].data = static_cast<uint8_t *>(HksMalloc(certChain->certs[INDEX_3].size));
if (certChain->certs[INDEX_3].data == nullptr) {
FreeHksCertChain(certChain);
return HKS_ERROR_INSUFFICIENT_MEMORY;
}
if (certChain->certs == nullptr) {
return HKS_ERROR_INSUFFICIENT_MEMORY;
}
*certChainCapacity = certChain->certsCount;
certChain->certs[INDEX_0].size = HKS_CERT_APP_SIZE;
certChain->certs[INDEX_0].data = static_cast<uint8_t *>(HksMalloc(certChain->certs[INDEX_0].size));
if (certChain->certs[INDEX_0].data == nullptr) {
FreeHksCertChain(certChain, *certChainCapacity);
return HKS_ERROR_INSUFFICIENT_MEMORY;
}
certChain->certs[INDEX_1].size = HKS_CERT_DEVICE_SIZE;
certChain->certs[INDEX_1].data = static_cast<uint8_t *>(HksMalloc(certChain->certs[INDEX_1].size));
if (certChain->certs[INDEX_1].data == nullptr) {
FreeHksCertChain(certChain, *certChainCapacity);
return HKS_ERROR_INSUFFICIENT_MEMORY;
}
certChain->certs[INDEX_2].size = HKS_CERT_CA_SIZE;
certChain->certs[INDEX_2].data = static_cast<uint8_t *>(HksMalloc(certChain->certs[INDEX_2].size));
if (certChain->certs[INDEX_2].data == nullptr) {
FreeHksCertChain(certChain, *certChainCapacity);
return HKS_ERROR_INSUFFICIENT_MEMORY;
}
return HKS_SUCCESS;
}
@ -159,7 +155,7 @@ static napi_value AnonAttestKeyAsyncWork(napi_env env, AttestKeyAsyncContext con
napiContext->certChain = static_cast<struct HksCertChain *>(HksMalloc(sizeof(struct HksCertChain)));
if (napiContext->certChain != nullptr) {
int32_t ret = InitCertChain(napiContext->certChain);
int32_t ret = InitCertChain(napiContext->certChain, &napiContext->certChainCapacity);
if (ret != HKS_SUCCESS) {
HKS_LOG_E("Init Cert Chain failed in napi");
return;

View File

@ -44,6 +44,7 @@ struct AttestKeyAsyncContextT {
struct HksBlob *keyAlias = nullptr;
struct HksParamSet *paramSet = nullptr;
struct HksCertChain *certChain = nullptr;
uint32_t certChainCapacity = 0;
};
using AttestKeyAsyncContext = AttestKeyAsyncContextT *;
@ -62,7 +63,7 @@ static void DeleteAttestKeyAsyncContext(napi_env env, AttestKeyAsyncContext &con
return;
}
DeleteCommonAsyncContext(env, context->asyncWork, context->callback, context->keyAlias, context->paramSet);
FreeHksCertChain(context->certChain);
FreeHksCertChain(context->certChain, context->certChainCapacity);
HksFree(context);
context = nullptr;
}
@ -107,11 +108,12 @@ static napi_value AttestKeyParseParams(napi_env env, napi_callback_info info, At
return GetInt32(env, 0);
}
static void InitCertChain(struct HksCertChain *certChain)
static void InitCertChain(struct HksCertChain *certChain, uint32_t *certChainCapacity)
{
certChain->certsCount = HKS_CERT_COUNT;
certChain->certs = static_cast<struct HksBlob *>(HksMalloc(certChain->certsCount * sizeof(struct HksBlob)));
if (certChain->certs != nullptr) {
*certChainCapacity = certChain->certsCount;
certChain->certs[INDEX_0].size = HKS_CERT_APP_SIZE;
certChain->certs[INDEX_0].data = static_cast<uint8_t *>(HksMalloc(certChain->certs[INDEX_0].size));
certChain->certs[INDEX_1].size = HKS_CERT_DEVICE_SIZE;
@ -142,7 +144,7 @@ static napi_value AttestKeyAsyncWork(napi_env env, AttestKeyAsyncContext context
napiContext->certChain = static_cast<struct HksCertChain *>(HksMalloc(sizeof(struct HksCertChain)));
if (napiContext->certChain != nullptr) {
InitCertChain(napiContext->certChain);
InitCertChain(napiContext->certChain, &napiContext->certChainCapacity);
}
napiContext->result = HksAttestKey(napiContext->keyAlias, napiContext->paramSet, napiContext->certChain);

View File

@ -444,14 +444,14 @@ static napi_value GenerateStringArray(napi_env env, const struct HksBlob *blob,
return array;
}
void FreeHksCertChain(HksCertChain *&certChain)
void FreeHksCertChain(HksCertChain *&certChain, uint32_t certChainCapacity)
{
if (certChain == nullptr) {
return;
}
if (certChain->certsCount > 0 && certChain->certs != nullptr) {
for (uint32_t i = 0; i < certChain->certsCount; i++) {
if (certChainCapacity > 0 && certChain->certs != nullptr) {
for (uint32_t i = 0; i < certChainCapacity; i++) {
if (certChain->certs[i].data != nullptr) {
HksFree(certChain->certs[i].data);
certChain->certs[i].data = nullptr;

View File

@ -29,7 +29,7 @@
struct HuksKeyNode {
struct DoubleList listHead;
struct HksParamSet *keyBlobParamSet;
/**
* @brief used to cache params of caller and state or temp prop in memory during using key
* CURRENT state:

View File

@ -651,7 +651,7 @@ static int32_t UpdateAesGcmNonce(struct HksParamSet **runtimeParamSet, const str
HKS_LOG_E("get random failed");
return ret;
}
ret = AddNonceToParamSet(runtimeParamSet, params, HKS_ARRAY_SIZE(params));
HksFree(params[0].blob.data);
if (ret != HKS_SUCCESS) {

View File

@ -252,7 +252,7 @@ static void FreeParamsForBuildKeyNode(struct HksBlob *aad, struct HksParamSet **
if (keyblobParamSet != NULL && *keyblobParamSet != NULL) {
FreeKeyBlobParamSet(keyblobParamSet);
}
if (keyNode != NULL) {
HksFree(keyNode);
}

View File

@ -21,7 +21,8 @@
"ohos.permission.USE_USER_IDM",
"ohos.permission.MANAGE_LOCAL_ACCOUNTS",
"ohos.permission.GET_BUNDLE_INFO_PRIVILEGED",
"ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS"
"ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS",
"ohos.permission.REQUEST_ANONYMOUS_ATTEST"
],
"start-mode" : "condition",
"secon" : "u:r:huks_service:s0"

View File

@ -46,6 +46,7 @@ if (os_level == "standard") {
if (huks_security_level == "trusted_environment") {
sources += [ "src/hks_client_service_dcm.cpp" ]
include_dirs += [ "//base/security/huks/services/huks_standard/huks_service/main/os_dependency/sa" ] # hks_dcm_callback_handler.h
}
sources += [

View File

@ -79,10 +79,7 @@ int32_t HksServiceGetKeyInfoList(const struct HksProcessInfo *processInfo, struc
uint32_t *listCount);
int32_t HksServiceAttestKey(const struct HksProcessInfo *processInfo, const struct HksBlob *keyAlias,
const struct HksParamSet *paramSet, struct HksBlob *certChain);
int32_t HksServiceAnonAttestKey(const struct HksProcessInfo *processInfo, const struct HksBlob *keyAlias,
const struct HksParamSet *paramSet, struct HksBlob *certChain);
const struct HksParamSet *paramSet, struct HksBlob *certChain, const uint8_t *remoteObject);
int32_t HksServiceInit(const struct HksProcessInfo *processInfo, const struct HksBlob *key,
const struct HksParamSet *paramSet, struct HksBlob *handle, struct HksBlob *token);

View File

@ -16,13 +16,14 @@
#ifndef HKS_CLIENT_SERVICE_DCM_H
#define HKS_CLIENT_SERVICE_DCM_H
#include "hks_param.h"
#include "hks_type.h"
#ifdef __cplusplus
extern "C" {
#endif
int32_t DcmGenerateCertChain(struct HksBlob *cert, struct HksCertChain *certChain);
int32_t DcmGenerateCertChain(struct HksBlob *cert, const uint8_t *remoteObject);
#ifdef __cplusplus
}

View File

@ -20,12 +20,13 @@
#endif
#include "hks_client_service.h"
#include "hks_client_service_dcm.h"
#include <stdbool.h>
#include <stddef.h>
#include "hks_base_check.h" // for HksAttestIsAnonymous
#include "hks_client_check.h"
#include "hks_client_service_dcm.h"
#include "hks_client_service_util.h"
#include "hks_common_check.h"
#include "hks_hitrace.h"
@ -1353,176 +1354,8 @@ static int32_t AddHapInfoToParamSet(const struct HksProcessInfo *processInfo, st
}
#endif
#ifdef HKS_SUPPORT_API_ATTEST_KEY
static void FreeHksCertChain(struct HksCertChain *certChain)
{
if (certChain == NULL) {
return;
}
if (certChain->certsCount > 0 && certChain->certs != NULL) {
for (uint32_t i = 0; i < certChain->certsCount; i++) {
if (certChain->certs[i].data != NULL) {
HKS_FREE_BLOB(certChain->certs[i]);
certChain->certs[i].data = NULL;
}
}
}
HksFree(certChain->certs);
}
#ifndef HKS_UNTRUSTED_RUNNING_ENV
#define CERT_KEY_INDEX 0
#define CERT_DEVICE_INDEX 1
#define CERT_CA_INDEX 2
#define CERT_ROOT_INDEX 3
static int32_t InitCertChain(struct HksCertChain *certChain)
{
certChain->certsCount = HKS_CERT_COUNT;
certChain->certs = (struct HksBlob *)(HksMalloc(certChain->certsCount * sizeof(struct HksBlob)));
if (certChain->certs == NULL) {
HKS_LOG_E("malloc certChain failed.");
return HKS_ERROR_INSUFFICIENT_MEMORY;
}
do {
certChain->certs[CERT_KEY_INDEX].size = HKS_CERT_APP_SIZE;
certChain->certs[CERT_KEY_INDEX].data = (uint8_t *)(HksMalloc(certChain->certs[CERT_KEY_INDEX].size));
// if data is null, FreeHksCertChain can free wild pointers
if (certChain->certs[CERT_KEY_INDEX].data == NULL) {
break;
}
certChain->certs[CERT_DEVICE_INDEX].size = HKS_CERT_DEVICE_SIZE;
certChain->certs[CERT_DEVICE_INDEX].data = (uint8_t *)(HksMalloc(certChain->certs[CERT_DEVICE_INDEX].size));
if (certChain->certs[CERT_DEVICE_INDEX].data == NULL) {
break;
}
certChain->certs[CERT_CA_INDEX].size = HKS_CERT_CA_SIZE;
certChain->certs[CERT_CA_INDEX].data = (uint8_t *)(HksMalloc(certChain->certs[CERT_CA_INDEX].size));
if (certChain->certs[CERT_CA_INDEX].data == NULL) {
break;
}
certChain->certs[CERT_ROOT_INDEX].size = HKS_CERT_ROOT_SIZE;
certChain->certs[CERT_ROOT_INDEX].data = (uint8_t *)(HksMalloc(certChain->certs[CERT_ROOT_INDEX].size));
if (certChain->certs[CERT_ROOT_INDEX].data == NULL) {
break;
}
return HKS_SUCCESS;
} while (0);
FreeHksCertChain(certChain);
return HKS_ERROR_INSUFFICIENT_MEMORY;
}
#endif
static int32_t GetAttestModeFlag(const struct HksParamSet *paramSet, uint32_t *attestMode)
{
struct HksParam *attestModeParam = NULL;
int32_t ret = HksGetParam(paramSet, HKS_TAG_ATTESTATION_MODE, &attestModeParam);
HKS_IF_NOT_SUCC_LOGE_RETURN(ret, ret, "get attestMode from paramSet fail.")
*attestMode = attestModeParam->uint32Param;
return HKS_SUCCESS;
}
static int32_t CopyBlobToBuffer(const struct HksBlob *blob, struct HksBlob *buf)
{
if (buf->size < sizeof(blob->size) + ALIGN_SIZE(blob->size)) {
HKS_LOG_E("buf size smaller than blob size");
return HKS_ERROR_BUFFER_TOO_SMALL;
}
if (memcpy_s(buf->data, buf->size, &blob->size, sizeof(blob->size)) != EOK) {
HKS_LOG_E("copy buf fail");
return HKS_ERROR_BUFFER_TOO_SMALL;
}
buf->data += sizeof(blob->size);
buf->size -= sizeof(blob->size);
if (memcpy_s(buf->data, buf->size, blob->data, blob->size) != EOK) {
HKS_LOG_E("copy buf fail");
return HKS_ERROR_BUFFER_TOO_SMALL;
}
buf->data += ALIGN_SIZE(blob->size);
buf->size -= ALIGN_SIZE(blob->size);
return HKS_SUCCESS;
}
static int32_t PackAttestChain(struct HksCertChain *certChain, struct HksBlob *certChainPacked)
{
if (certChain == NULL || certChain->certs == NULL) {
HKS_LOG_E("certChain buffer from caller is null.");
return HKS_ERROR_NULL_POINTER;
}
if (certChain->certsCount != HKS_CERT_COUNT) {
HKS_LOG_E("certs count is not correct");
return HKS_ERROR_BUFFER_TOO_SMALL;
}
struct HksBlob tmp = *certChainPacked;
if (tmp.size <= HKS_CERT_COUNT) {
HKS_LOG_E("certChainPacked size too small");
return HKS_ERROR_BUFFER_TOO_SMALL;
}
*((uint32_t *)tmp.data) = HKS_CERT_COUNT;
tmp.data += sizeof(uint32_t);
tmp.size -= sizeof(uint32_t);
int32_t ret = 0;
for (uint32_t i = 0; i < certChain->certsCount; ++i) {
if (certChain->certs[i].data == NULL) {
HKS_LOG_E("single cert %" LOG_PUBLIC "u from huks is null.", i);
ret = HKS_ERROR_NULL_POINTER;
break;
}
ret = CopyBlobToBuffer(&certChain->certs[i], &tmp);
HKS_IF_NOT_SUCC_LOGE_RETURN(ret, ret, "copy cert fail")
}
if (ret != HKS_SUCCESS) {
return ret;
}
certChainPacked->size = tmp.data - certChainPacked->data;
HKS_LOG_I("certChain size after packing is %" LOG_PUBLIC "u", certChainPacked->size);
return HKS_SUCCESS;
}
static int32_t HksAttestKeyDcmAttest(const struct HksParamSet *paramSet, struct HksBlob *certChain,
const uint32_t certChainCapacity)
{
struct HksCertChain certChainNew = { 0 };
if (certChainCapacity == 0) {
HKS_LOG_E("certChainCapacity is 0");
return HKS_ERROR_BUFFER_TOO_SMALL;
}
struct HksBlob certChainPacked = {
.size = certChainCapacity,
.data = (uint8_t *)HksMalloc(certChainCapacity)
};
if (certChainPacked.data == NULL) {
HKS_LOG_E("certChainPacked data is null.");
return HKS_ERROR_INSUFFICIENT_MEMORY;
}
int32_t ret =0;
do {
ret = InitCertChain(&certChainNew);
HKS_IF_NOT_SUCC_LOGE_BREAK(ret, "InitCertChainNew failed.")
ret = DcmGenerateCertChain(certChain, &certChainNew);
HKS_IF_NOT_SUCC_LOGE_BREAK(ret, "DcmGenerateCertChain fail result: %" LOG_PUBLIC "d", ret);
ret = PackAttestChain(&certChainNew, &certChainPacked);
HKS_IF_NOT_SUCC_LOGE_BREAK(ret, "PackAttestChain fail result: %" LOG_PUBLIC "d", ret);
if (memcpy_s(certChain->data, certChainCapacity, certChainPacked.data, certChainPacked.size) != EOK) {
HKS_LOG_E("copy certChainPacked fail");
ret = HKS_ERROR_BUFFER_TOO_SMALL;
break;
}
certChain->size = certChainPacked.size;
} while (0);
HKS_FREE_BLOB(certChainPacked);
FreeHksCertChain(&certChainNew);
return ret;
}
#endif
int32_t HksServiceAttestKey(const struct HksProcessInfo *processInfo, const struct HksBlob *keyAlias,
const struct HksParamSet *paramSet, struct HksBlob *certChain)
const struct HksParamSet *paramSet, struct HksBlob *certChain, const uint8_t *remoteObject)
{
#ifdef HKS_SUPPORT_API_ATTEST_KEY
struct HksHitraceId traceId = HksHitraceBegin(__func__, HKS_HITRACE_FLAG_DEFAULT);
@ -1545,20 +1378,18 @@ int32_t HksServiceAttestKey(const struct HksProcessInfo *processInfo, const stru
HKS_IF_NOT_SUCC_LOGE_BREAK(ret, "GetKeyAndNewParamSet failed, ret = %" LOG_PUBLIC "d.", ret)
#endif
uint32_t certChainCapacity = certChain->size;
ret = HuksAccessAttestKey(&keyFromFile, newParamSet, certChain);
HKS_IF_NOT_SUCC_LOGE_BREAK(ret, "HuksAccessAttestKey fail, ret = %" LOG_PUBLIC "d.", ret)
#ifndef HKS_UNTRUSTED_RUNNING_ENV
uint32_t attestMode = 0;
int32_t ret = GetAttestModeFlag(newParamSet, &attestMode);
HKS_IF_NOT_SUCC_LOGE_BREAK(ret, "GetAttestMode failed, ret = %" LOG_PUBLIC "d.", ret)
if (attestMode != HKS_ATTESTATION_MODE_ANONYMOUS) {
if (!HksAttestIsAnonymous(paramSet)) {
HKS_LOG_I("non anonymous attest key.");
break;
}
ret = HksAttestKeyDcmAttest(newParamSet, certChain, certChainCapacity);
HKS_IF_NOT_SUCC_LOGE_BREAK(ret, "HksAttestKeyDcmAttest fail, ret = %" LOG_PUBLIC "d.", ret)
ret = DcmGenerateCertChain(certChain, remoteObject);
HKS_IF_NOT_SUCC_LOGE_BREAK(ret, "DcmGenerateCertChain fail, ret = %" LOG_PUBLIC "d.", ret)
#else
(void)(remoteObject);
#endif
} while (0);
@ -1575,6 +1406,7 @@ int32_t HksServiceAttestKey(const struct HksProcessInfo *processInfo, const stru
(void)keyAlias;
(void)paramSet;
(void)certChain;
(void)remoteObject;
return HKS_ERROR_NOT_SUPPORTED;
#endif
}

View File

@ -13,204 +13,62 @@
* limitations under the License.
*/
#ifdef HKS_CONFIG_FILE
#include HKS_CONFIG_FILE
#else
#include "hks_config.h"
#endif
#ifndef HKS_UNTRUSTED_RUNNING_ENV
#include "hks_client_service_dcm.h"
#include <algorithm>
#include <chrono>
#include <condition_variable>
#include <cstdio>
#include <dlfcn.h>
#include <memory>
#include <mutex>
#include <thread>
#include <cinttypes>
#include <securec.h>
#include "hks_cfi.h"
#include "hks_dcm_callback_handler.h"
#include "hks_log.h"
#include "hks_mem.h"
#include "hks_template.h"
#include "hks_type.h"
typedef enum {
DCM_SUCCESS = 0
} DcmErrorCode;
struct DcmBlobT {
uint32_t size;
uint8_t *data;
};
using DcmBlob = DcmBlobT;
struct DcmCertChainT {
DcmBlob *cert;
uint32_t certCount;
};
using DcmCertChain = DcmCertChainT;
using DcmCallback = void (*)(uint32_t errCode, uint8_t *errInfo, uint32_t infoSize, DcmCertChain *certChain);
class DcmAttest {
std::condition_variable attestFinished{};
bool callbackCalled = false;
bool timeout = false;
bool isCallingFailed = false;
std::condition_variable sleepAlarm{};
HksCertChain *certChain{};
using AttestFunction = int32_t (*)(const DcmBlob *localAttestCert, DcmCallback callback);
void *certMgrSdkHandle {};
AttestFunction dcmAnonymousAttestKey {};
void DcmCallback(uint32_t errCode, uint8_t *errInfo, uint32_t infoSize, DcmCertChain *dcmCertChain);
void WaitTimeout();
public:
explicit DcmAttest(HksCertChain *certChain);
~DcmAttest();
int32_t AttestWithAnon(HksBlob *cert);
};
void DcmAttest::DcmCallback(uint32_t errCode, uint8_t *errInfo, uint32_t infoSize, DcmCertChain *dcmCertChain)
ENABLE_CFI(int32_t DcmGenerateCertChain(struct HksBlob *cert, const uint8_t *remoteObject))
{
if (timeout) {
return;
}
HKS_IF_NOT_SUCC_LOGE_RETURN(CheckBlob(cert), HKS_ERROR_INVALID_ARGUMENT, "invalid in cert");
AttestFunction fun = HksOpenDcmFunction();
HKS_IF_NULL_LOGE_RETURN(fun, HKS_ERROR_UNKNOWN_ERROR, "HksOpenDcmFunction failed");
int ret = HKS_ERROR_UNKNOWN_ERROR;
do {
if (errCode != DCM_SUCCESS) {
HKS_LOG_I("DcmCallBack result is fail, erroCode = %" LOG_PUBLIC "d", errCode);
break;
}
if (certChain == nullptr || certChain->certs == nullptr) {
HKS_LOG_E("certChain buffer from caller is null.");
break;
}
if (dcmCertChain == nullptr) {
HKS_LOG_E("dcmCertChain is NULL");
break;
}
if (certChain->certsCount < dcmCertChain->certCount) {
HKS_LOG_E("cert count from huks is not enough to load dcm certChain.");
break;
}
HKS_LOG_I("Begin to extract anon certChain.");
for (uint32_t i = 0; i < dcmCertChain->certCount; ++i) {
if (certChain->certs[i].data == nullptr) {
HKS_LOG_E("single cert chain from huks is null.");
isCallingFailed = true;
DcmAnonymousRequest request = {
.blob = { .size = cert->size, .data = cert->data },
.requestId = 0,
};
{
// We got a requestId after invoking DcmAnonymousAttestKey function,
// and the implementation of DcmAnonymousAttestKey will invoke our HksDcmCallback in a new thread.
// To avoid that the new thread will call HksDcmCallback before
// HksDcmCallbackHandlerSetRequestIdWithoutLock, we bind the getting requestId operation and setting
// requestId openration with one lock guard.
std::lock_guard<std::mutex> lockGuard(HksDcmCallbackHandlerGetMapMutex());
ret = fun(&request, [](DcmAnonymousResponse *response) {
HksDcmCallback(response);
});
HKS_LOG_I("got requestId %" LOG_PUBLIC PRIu64, request.requestId);
if (ret != DCM_SUCCESS) {
HKS_LOG_E("DcmAnonymousAttestKey failed %" LOG_PUBLIC "d", ret);
ret = HUKS_ERR_CODE_EXTERNAL_ERROR;
// We will not add callback instance into map and ignore callback in case of error.
break;
}
if (dcmCertChain->cert[i].data == nullptr) {
HKS_LOG_E("single dcmCertChain buffer is null.");
isCallingFailed = true;
break;
}
if (memcpy_s(certChain->certs[i].data, certChain->certs[i].size, dcmCertChain->cert[i].data,
dcmCertChain->cert[i].size) != EOK) {
HKS_LOG_E("huks certChain cert size is smaller than dcmCertChain certChain size: %" LOG_PUBLIC
"u, dcmCertSize: %" LOG_PUBLIC "u", certChain->certs[i].size, dcmCertChain->cert[i].size);
isCallingFailed = true;
break;
}
certChain->certs[i].size = dcmCertChain->cert[i].size;
ret = HksDcmCallbackHandlerSetRequestIdWithoutLock(remoteObject, request.requestId);
HKS_IF_NOT_SUCC_LOGE_BREAK(ret, "HksDcmCallbackHandlerSetRequestIdWithoutLock failed %" LOG_PUBLIC "d", ret)
}
HKS_LOG_I("Extract anon certChain final Success!");
} while (0);
callbackCalled = true;
attestFinished.notify_all();
}
void DcmAttest::WaitTimeout()
{
HKS_LOG_I("begin wait_for");
{
std::mutex sleepLock{};
std::unique_lock<std::mutex> lock(sleepLock);
std::cv_status waitResult =
sleepAlarm.wait_for(lock, std::chrono::seconds(10));
if (waitResult == std::cv_status::timeout) {
HKS_LOG_E("watting for dcm is timeout!");
} else {
HKS_LOG_I("finished successfully! waked up!");
}
}
timeout = true;
attestFinished.notify_all();
}
DcmAttest::DcmAttest(HksCertChain *certChain) : certChain(certChain)
{
HKS_LOG_I("begin dlopen libdevice_cert_mgr_sdk.z.so");
certMgrSdkHandle = dlopen("libdevice_cert_mgr_sdk.z.so", RTLD_NOW);
if (certMgrSdkHandle == nullptr) {
HKS_LOG_E("dlopen libdevice_cert_mgr_sdk.z.so failed! %" LOG_PUBLIC "s", dlerror());
return;
}
HKS_LOG_I("dlopen ok!");
dcmAnonymousAttestKey = reinterpret_cast<AttestFunction>(dlsym(certMgrSdkHandle, "DcmAnonymousAttestKey"));
if (dcmAnonymousAttestKey == nullptr) {
HKS_LOG_E("dlsym failed %" LOG_PUBLIC "s", dlerror());
return;
}
HKS_LOG_I("dlsym ok!");
}
DcmAttest::~DcmAttest()
{
if (certMgrSdkHandle == nullptr) {
return;
}
int ret = dlclose(certMgrSdkHandle);
HKS_LOG_W("dlclose ret %" LOG_PUBLIC "d", ret);
}
ENABLE_CFI(int32_t DcmAttest::AttestWithAnon(HksBlob *cert))
{
HKS_LOG_I("enter attest for dcm.");
if (dcmAnonymousAttestKey == nullptr) {
HKS_LOG_E("dcmAnonymousAttestKey is NULL!");
return HKS_ERROR_IPC_DLOPEN_FAIL;
}
std::thread timerThread([this]() { WaitTimeout(); });
DcmBlob dcmCert = {.size = cert->size, .data = cert->data};
HKS_LOG_I("begin to pack callback for dcmAnonymousAttestKey");
static auto callback = [this](uint32_t errCode, uint8_t *errInfo, uint32_t infoSize, DcmCertChain *dcmCertChain) {
DcmCallback(errCode, errInfo, infoSize, dcmCertChain);
};
HKS_LOG_I("begin time: anon sa attest key!");
int32_t ret = dcmAnonymousAttestKey(&dcmCert, [](uint32_t errCode, uint8_t *errInfo, uint32_t infoSize,
DcmCertChain *dcmCertChain) {
HKS_LOG_I("end time: anon sa attest key, receive callback!");
callback(errCode, errInfo, infoSize, dcmCertChain);
});
if (ret != DCM_SUCCESS) {
HKS_LOG_E("calling dcm anon attestKey not success,ret = %" LOG_PUBLIC "d", ret);
sleepAlarm.notify_all();
timerThread.join();
return ret;
}
HKS_LOG_I("Calling DcmanonymousAttestKey ok, begin to wait callback!");
std::mutex mtx{};
std::unique_lock<std::mutex> lock(mtx);
// only wait callback if ret is success
attestFinished.wait(lock, [&] { return callbackCalled || timeout; });
if (callbackCalled) {
HKS_LOG_I("callbackCalled return certchain.");
} else {
HKS_LOG_E("no callbackCalled");
ret = HKS_ERROR_COMMUNICATION_TIMEOUT;
}
if (isCallingFailed) {
ret = HKS_ERROR_BUFFER_TOO_SMALL;
}
HKS_LOG_I("begin notify sleep thread");
sleepAlarm.notify_all();
HKS_LOG_I("begin timerThread.join()");
timerThread.join();
// We will not return data on the sync interface, we will send the cert chain in the callback.
cert->size = 0;
return HKS_SUCCESS;
} while (false);
return ret;
}
int32_t DcmGenerateCertChain(HksBlob *cert, HksCertChain *certChain)
{
DcmAttest attest(certChain);
return attest.AttestWithAnon(cert);
}
#endif // HKS_UNTRUSTED_RUNNING_ENV

View File

@ -52,10 +52,16 @@ if (os_level == "standard") {
}
sources += [
"posix/hks_rwlock.c",
"sa/hks_dcm_callback_handler.cpp",
"sa/hks_sa.cpp",
# both client side and server side will include hks_sa_interface.cpp
"sa/hks_sa_interface.cpp",
]
defines = []
if (huks_security_level == "software") {
defines += [ "HKS_UNTRUSTED_RUNNING_ENV" ]
}
if (support_jsapi) {
sources += [ "sa/hks_event_observer.cpp" ]
defines += [ "SUPPORT_COMMON_EVENT" ]

View File

@ -27,14 +27,16 @@
#include "hks_config.h"
#endif
#include "hks_base_check.h" // for HksAttestIsAnonymous
#include "hks_client_check.h"
#include "hks_client_service_dcm.h"
#include "hks_client_service.h"
#include "hks_cmd_id.h"
#include "hks_service_ipc_serialization.h"
#include "hks_log.h"
#include "hks_mem.h"
#include "hks_response.h"
#include "hks_service_ipc_serialization.h"
#include "hks_template.h"
#include "hks_client_check.h"
#define MAX_KEY_SIZE 2048
@ -663,11 +665,7 @@ int32_t HksAttestAccessControl(struct HksParamSet *paramSet)
}
}
// HKS_ATTESTATION_MODE_ANONYMOUS no need check permission
struct HksParam *attestModeParam = NULL;
int32_t ret = HksGetParam(paramSet, HKS_TAG_ATTESTATION_MODE, &attestModeParam);
HKS_IF_NOT_SUCC_LOGE_RETURN(ret, ret, "get attestation mode fail.")
if (attestModeParam->uint32Param == HKS_ATTESTATION_MODE_ANONYMOUS) {
if (HksAttestIsAnonymous(paramSet)) {
return HKS_SUCCESS;
}
@ -682,7 +680,7 @@ int32_t HksAttestAccessControl(struct HksParamSet *paramSet)
return HKS_SUCCESS;
}
void HksIpcServiceAttestKey(const struct HksBlob *srcData, const uint8_t *context)
void HksIpcServiceAttestKey(const struct HksBlob *srcData, const uint8_t *context, const uint8_t *remoteObject)
{
struct HksBlob keyAlias = { 0, NULL };
struct HksParamSet *inParamSet = NULL;
@ -704,10 +702,11 @@ void HksIpcServiceAttestKey(const struct HksBlob *srcData, const uint8_t *contex
ret = HksAttestAccessControl(inParamSet);
HKS_IF_NOT_SUCC_LOGE_BREAK(ret, "HksAttestAccessControl fail, ret = %" LOG_PUBLIC "d", ret)
ret = HksServiceAttestKey(&processInfo, &keyAlias, inParamSet, &certChainBlob);
ret = HksServiceAttestKey(&processInfo, &keyAlias, inParamSet, &certChainBlob, remoteObject);
HKS_IF_NOT_SUCC_LOGE_BREAK(ret, "HksServiceAttestKey fail, ret = %" LOG_PUBLIC "d", ret)
HKS_LOG_E("get certChainBlob size %" LOG_PUBLIC "u", certChainBlob.size);
// certChainBlob.size would be 0 if attestation mode is anonymous
HKS_LOG_I("got certChainBlob size %" LOG_PUBLIC "u", certChainBlob.size);
HksSendResponse(context, ret, &certChainBlob);
} while (0);

View File

@ -54,7 +54,7 @@ void HksIpcServiceMac(const struct HksBlob *srcData, const uint8_t *context);
void HksIpcServiceGetKeyInfoList(const struct HksBlob *srcData, const uint8_t *context);
void HksIpcServiceAttestKey(const struct HksBlob *srcData, const uint8_t *context);
void HksIpcServiceAttestKey(const struct HksBlob *srcData, const uint8_t *context, const uint8_t *remoteObject);
void HksIpcServiceInit(const struct HksBlob *paramSetBlob, struct HksBlob *outData, const uint8_t *context);

View File

@ -65,17 +65,14 @@ void HksSendResponse(const uint8_t *context, int32_t result, const struct HksBlo
HKS_LOG_E("SendResponse NULL Pointer");
return;
}
HKS_LOG_E("reply->WriteUint32 result %" LOG_PUBLIC "d", result);
MessageParcel *reply = const_cast<MessageParcel *>(reinterpret_cast<const MessageParcel *>(context));
HKS_IF_NOT_TRUE_LOGE_RETURN_VOID(reply->WriteInt32(result));
if (response == nullptr) {
HKS_LOG_E("reply->WriteUint32 0");
HKS_IF_NOT_TRUE_LOGE_RETURN_VOID(reply->WriteUint32(0));
} else {
HKS_IF_NOT_TRUE_LOGE_RETURN_VOID(reply->WriteUint32(response->size));
HKS_LOG_E("reply->WriteUint32 size = %" LOG_PUBLIC "u", response->size);
HKS_IF_NOT_TRUE_LOGE_RETURN_VOID(reply->WriteBuffer(response->data, static_cast<size_t>(response->size)));
}
}

View File

@ -0,0 +1,257 @@
/*
* Copyright (c) 2023-2023 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifdef HKS_CONFIG_FILE
#include HKS_CONFIG_FILE
#else
#include "hks_config.h"
#endif
#ifndef HKS_UNTRUSTED_RUNNING_ENV
#include "hks_dcm_callback_handler.h"
#include <cinttypes>
#include <cstdint>
#include <dlfcn.h>
#include <map>
#include <mutex>
#include <new>
#include <refbase.h>
#include <securec.h>
#include "hks_log.h"
#include "hks_sa_interface.h"
#include "hks_template.h"
#include "hks_type.h"
#include "iremote_broker.h"
#include "iremote_object.h"
#define DCM_SDK_SO "libdevice_cert_mgr_sdk.z.so"
namespace OHOS {
namespace Security {
namespace Hks {
class ThreadSafeMap {
public:
std::mutex &GetMutex()
{
return mContainerLock;
}
int32_t SetNewInstanceWithoutLock(sptr<IHksService> index, uint64_t value)
{
typename std::map<sptr<IHksService>, uint64_t>::iterator position = mValues.find(index);
if (position != mValues.end()) {
HKS_LOG_E("SetNewInstance: current value exist requestId = %" LOG_PUBLIC PRIu64, position->second);
return HKS_ERROR_ALREADY_EXISTS;
}
mValues[index] = value;
return HKS_SUCCESS;
}
sptr<IHksService> GetProxyWithoutLock(uint64_t value)
{
auto position = findInMapByValue(value);
if (position == mValues.end()) {
HKS_LOG_E("GetProxyWithoutLock: current value not exist, requestId %" LOG_PUBLIC PRIu64, value);
return nullptr;
}
return position->first;
}
void RemoveWithoutLock(uint64_t value)
{
auto position = findInMapByValue(value);
if (position == mValues.end()) {
HKS_LOG_E("RemoveWithoutLock: current value not exist, requestId %" LOG_PUBLIC PRIu64, value);
return;
}
mValues.erase(position);
}
private:
std::mutex mContainerLock{};
std::map<sptr<IHksService>, uint64_t> mValues{};
std::map<sptr<IHksService>, uint64_t>::iterator findInMapByValue(uint64_t value)
{
return std::find_if(
mValues.begin(), mValues.end(), [value](const std::pair<sptr<IHksService>, uint64_t> &element) {
return element.second == value;
});
}
};
int32_t CopyBlobToBuffer(const struct DcmBlob *blob, struct HksBlob *buf)
{
if (buf->size < sizeof(blob->size) + ALIGN_SIZE(blob->size)) {
HKS_LOG_E("buf size smaller than blob size");
return HKS_ERROR_BUFFER_TOO_SMALL;
}
if (memcpy_s(buf->data, buf->size, &blob->size, sizeof(blob->size)) != EOK) {
HKS_LOG_E("copy buf fail");
return HKS_ERROR_BUFFER_TOO_SMALL;
}
buf->data += sizeof(blob->size);
buf->size -= sizeof(blob->size);
if (memcpy_s(buf->data, buf->size, blob->data, blob->size) != EOK) {
HKS_LOG_E("copy buf fail");
return HKS_ERROR_BUFFER_TOO_SMALL;
}
buf->data += ALIGN_SIZE(blob->size);
buf->size -= ALIGN_SIZE(blob->size);
return HKS_SUCCESS;
}
int32_t PackAttestChain(struct DcmCertChain *certChain, struct HksBlob *certChainPacked)
{
if (certChain == nullptr || certChain->certs == nullptr) {
HKS_LOG_E("certChain buffer from caller is null.");
return HKS_ERROR_NULL_POINTER;
}
if (certChain->certsCount == 0 || certChain->certsCount > HKS_CERT_COUNT) {
HKS_LOG_E("certs count %" LOG_PUBLIC "u is not correct", certChain->certsCount);
return HKS_ERROR_BUFFER_TOO_SMALL;
}
for (uint32_t i = 0; i < certChain->certsCount; ++i) {
if (certChain->certs[i].data == nullptr || certChain->certs[i].size == 0 ||
certChain->certs[i].size > HKS_CERT_APP_SIZE) {
HKS_LOG_E("cert %" LOG_PUBLIC "u is null or cert size %" LOG_PUBLIC "u invalid ",
i, certChain->certs[i].size);
return HKS_ERROR_INVALID_ARGUMENT;
}
}
struct HksBlob tmp = *certChainPacked;
if (tmp.size <= sizeof(uint32_t)) {
HKS_LOG_E("certChainPacked size too small");
return HKS_ERROR_BUFFER_TOO_SMALL;
}
*((uint32_t *)tmp.data) = certChain->certsCount;
tmp.data += sizeof(uint32_t);
tmp.size -= sizeof(uint32_t);
int32_t ret = 0;
for (uint32_t i = 0; i < certChain->certsCount; ++i) {
if (certChain->certs[i].data == nullptr) {
HKS_LOG_E("single cert %" LOG_PUBLIC "u from huks is null.", i);
ret = HKS_ERROR_NULL_POINTER;
break;
}
ret = CopyBlobToBuffer(&certChain->certs[i], &tmp);
HKS_IF_NOT_SUCC_LOGE_RETURN(ret, ret, "copy cert fail")
}
if (ret != HKS_SUCCESS) {
return ret;
}
certChainPacked->size = tmp.data - certChainPacked->data;
return HKS_SUCCESS;
}
ThreadSafeMap g_instancesList{};
void *g_certMgrSdkHandle{};
AttestFunction g_attestFunction{};
}}} // OHOS::Security::Hks
using OHOS::Security::Hks::g_instancesList;
using OHOS::Security::Hks::g_certMgrSdkHandle;
using OHOS::Security::Hks::g_attestFunction;
using OHOS::Security::Hks::IHksService;
using OHOS::Security::Hks::PackAttestChain;
using OHOS::sptr;
void HksDcmCallback(DcmAnonymousResponse *response)
{
if (response == nullptr) {
HKS_LOG_E("dcm callback got null response");
return;
}
HKS_LOG_I("dcm callback requestId %" LOG_PUBLIC PRIu64, response->requestId);
std::lock_guard<std::mutex> lockGuard(g_instancesList.GetMutex());
sptr<IHksService> hksProxy = g_instancesList.GetProxyWithoutLock(response->requestId);
if (hksProxy == nullptr) {
HKS_LOG_E("GetProxyWithoutLock failed *requestId %" LOG_PUBLIC PRIu64, response->requestId);
return;
}
std::unique_ptr<uint8_t[]> replyData = nullptr;
uint32_t replySize = 0;
do {
HKS_IF_NOT_SUCC_LOGE_BREAK(response->errCode, "HksDcmCallback failed %" LOG_PUBLIC "d", response->errCode)
uint32_t packedSize = HKS_CERT_ROOT_SIZE + HKS_CERT_CA_SIZE + HKS_CERT_DEVICE_SIZE + HKS_CERT_APP_SIZE;
std::unique_ptr<uint8_t[]> packedCertChain(new (std::nothrow) uint8_t[packedSize]());
HKS_IF_NULL_LOGE_BREAK(packedCertChain, "new cert chain buffer failed")
HksBlob packedBlob { .size = packedSize, .data = packedCertChain.get() };
int ret = PackAttestChain(response->certChain, &packedBlob);
HKS_IF_NOT_SUCC_LOGE_BREAK(ret, "PackAttestChain failed %" LOG_PUBLIC "d", ret)
replyData = std::move(packedCertChain);
replySize = packedBlob.size;
} while (false);
hksProxy->SendAsyncReply(response->errCode, replyData, replySize);
g_instancesList.RemoveWithoutLock(response->requestId);
}
int32_t HksDcmCallbackHandlerSetRequestIdWithoutLock(const uint8_t *remoteObject, uint64_t requestId)
{
auto hksProxy = OHOS::iface_cast<IHksService>(
reinterpret_cast<OHOS::IRemoteObject *>(const_cast<uint8_t *>(remoteObject)));
if (hksProxy == nullptr) {
HKS_LOG_E("iface_cast IHksService failed");
return HKS_ERROR_NULL_POINTER;
}
int ret = g_instancesList.SetNewInstanceWithoutLock(hksProxy, requestId);
if (ret != HKS_SUCCESS) {
HKS_LOG_E("g_instancesList.SetNewInstance failed %" LOG_PUBLIC "d", ret);
}
return ret;
}
std::mutex &HksDcmCallbackHandlerGetMapMutex(void)
{
return g_instancesList.GetMutex();
}
AttestFunction HksOpenDcmFunction(void)
{
if (g_attestFunction != nullptr) {
return g_attestFunction;
}
g_certMgrSdkHandle = dlopen(DCM_SDK_SO, RTLD_NOW);
if (g_certMgrSdkHandle == nullptr) {
HKS_LOG_E("dlopen " DCM_SDK_SO " failed! %" LOG_PUBLIC "s", dlerror());
return nullptr;
}
g_attestFunction = reinterpret_cast<AttestFunction>(dlsym(g_certMgrSdkHandle, "DcmAnonymousAttestKey"));
if (g_attestFunction == nullptr) {
HKS_LOG_E("dlsym failed %" LOG_PUBLIC "s", dlerror());
HksCloseDcmFunction();
return nullptr;
}
return g_attestFunction;
}
void HksCloseDcmFunction(void)
{
if (g_certMgrSdkHandle == nullptr) {
g_attestFunction = nullptr;
return;
}
int ret = dlclose(g_certMgrSdkHandle);
if (ret != 0) {
HKS_LOG_E("dlclose g_certMgrSdkHandle failed %" LOG_PUBLIC "d %" LOG_PUBLIC "s", ret, dlerror());
}
g_certMgrSdkHandle = nullptr;
g_attestFunction = nullptr;
}
#endif // HKS_UNTRUSTED_RUNNING_ENV

View File

@ -0,0 +1,74 @@
/*
* Copyright (c) 2023-2023 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef HKS_DCM_CALLBACK_HANDLER_H
#define HKS_DCM_CALLBACK_HANDLER_H
#include <stdint.h>
#ifdef __cplusplus
#include <mutex>
#endif
typedef enum {
DCM_SUCCESS = 0
} DcmErrorCode;
struct DcmBlob {
uint32_t size;
uint8_t *data;
};
struct DcmCertChain {
DcmBlob *certs;
uint32_t certsCount;
};
typedef struct {
DcmBlob blob;
uint64_t requestId;
} DcmAnonymousRequest;
typedef struct {
uint64_t requestId;
uint32_t errCode;
DcmBlob errInfo;
DcmCertChain *certChain;
} DcmAnonymousResponse;
typedef void (*DcmCallback)(DcmAnonymousResponse *response);
typedef int32_t (*AttestFunction)(DcmAnonymousRequest *requset, DcmCallback callback);
#ifdef __cplusplus
extern "C" {
#endif
void HksDcmCallback(DcmAnonymousResponse *response);
int32_t HksDcmCallbackHandlerSetRequestIdWithoutLock(const uint8_t *remoteObject, uint64_t requestId);
AttestFunction HksOpenDcmFunction(void);
void HksCloseDcmFunction(void);
#ifdef __cplusplus
} // extern "C"
#endif
#ifdef __cplusplus
std::mutex &HksDcmCallbackHandlerGetMapMutex(void);
#endif
#endif // HKS_DCM_CALLBACK_HANDLER_H

View File

@ -45,7 +45,6 @@ const struct HksIpcEntryPoint HKS_IPC_MESSAGE_HANDLER[] = {
{ HKS_MSG_DERIVE_KEY, HksIpcServiceDeriveKey },
{ HKS_MSG_MAC, HksIpcServiceMac },
{ HKS_MSG_GET_KEY_INFO_LIST, HksIpcServiceGetKeyInfoList },
{ HKS_MSG_ATTEST_KEY, HksIpcServiceAttestKey },
};
typedef void (*HksIpcThreeStageHandlerFuncProc)(const struct HksBlob *msg, struct HksBlob *outData,

View File

@ -15,20 +15,22 @@
#include "hks_sa.h"
#include "huks_service_ipc_interface_code.h"
#include "ipc_skeleton.h"
#include "iservice_registry.h"
#include "string_ex.h"
#include "system_ability_definition.h"
#include <ipc_skeleton.h>
#include <iservice_registry.h>
#include <string_ex.h>
#include <system_ability_definition.h>
#include "hks_client_service.h"
#include "hks_dcm_callback_handler.h"
#include "hks_ipc_service.h"
#include "hks_log.h"
#include "hks_mem.h"
#include "hks_message_handler.h"
#include "hks_template.h"
#include "hks_util.h"
#include "hks_response.h"
#include "hks_template.h"
#include "hks_type.h"
#include "hks_util.h"
#include "huks_service_ipc_interface_code.h"
#ifdef CONFIG_USE_JEMALLOC_DFX_INTF
#include "malloc.h"
@ -186,6 +188,23 @@ static void HksInitMemPolicy(void)
#endif
}
static int32_t ProcessAttestOrNormalMessage(
uint32_t code, MessageParcel &data, uint32_t outSize, const struct HksBlob &srcData, MessageParcel &reply)
{
// Since we have wrote a HksStub instance in client side,
// we can now read it without distinguishing anonymous attestation from normal attestation.
if (code == HKS_MSG_ATTEST_KEY) {
auto ptr = data.ReadRemoteObject();
HKS_IF_NULL_LOGE_RETURN(ptr, HKS_ERROR_IPC_MSG_FAIL, "ReadRemoteObject ptr failed")
HksIpcServiceAttestKey(reinterpret_cast<const HksBlob *>(&srcData),
reinterpret_cast<const uint8_t *>(&reply), reinterpret_cast<const uint8_t *>(ptr.GetRefPtr()));
return HKS_SUCCESS;
} else {
return ProcessMessage(code, outSize, srcData, reply);
}
}
int HksService::OnRemoteRequest(uint32_t code, MessageParcel &data,
MessageParcel &reply, MessageOption &option)
{
@ -231,30 +250,7 @@ int HksService::OnRemoteRequest(uint32_t code, MessageParcel &data,
break;
}
(void)memcpy_s(srcData.data, srcData.size, pdata, srcData.size);
sptr<IHksService> hksProxy = nullptr;
// since we have wrote a HksStub instance in client side,
// we ncan now read it without distinguishing anonymous attestation or normal attestation
if (code == HKS_MSG_ATTEST_KEY) {
auto ptr = data.ReadRemoteObject();
HKS_IF_NULL_LOGE_BREAK(ptr, "ReadRemoteObject ptr failed")
std::wstring_convert<std::codecvt_utf8<char16_t>, char16_t> converter;
const char16_t *desc = ptr->descriptor_.c_str();
std::string descStr = converter.to_bytes(desc);
HKS_LOG_E("ptr desc %" LOG_PUBLIC "s", descStr.c_str());
hksProxy = iface_cast<IHksService>(ptr);
HKS_IF_NULL_LOGE_BREAK(hksProxy, "ReadRemoteObject IHksService failed")
}
ret = ProcessMessage(code, outSize, srcData, reply);
// TODO 这里要做回调
if (code == HKS_MSG_ATTEST_KEY) {
int replyData = 2333;
HKS_LOG_I("begin SendAsyncReply");
hksProxy->SendAsyncReply(replyData);
HKS_LOG_I("done SendAsyncReply");
}
ret = ProcessAttestOrNormalMessage(code, data, outSize, srcData, reply);
} while (0);
HKS_FREE_BLOB(srcData);
@ -409,6 +405,9 @@ void HksService::OnStop()
HKS_LOG_I("HksService Service OnStop");
runningState_ = STATE_NOT_START;
registerToService_ = false;
#ifndef HKS_UNTRUSTED_RUNNING_ENV
HksCloseDcmFunction();
#endif // HKS_UNTRUSTED_RUNNING_ENV
}
} // namespace Hks
} // namespace Security

View File

@ -48,6 +48,7 @@ public:
virtual ~HksService();
int OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) override;
static sptr<HksService> GetInstance();
protected:
@ -64,10 +65,6 @@ private:
ServiceRunningState runningState_;
static std::mutex instanceLock;
static sptr<HksService> instance;
int asyncReply_ = { 0 };
std::mutex mutex_;
std::condition_variable cv_;
};
} // namespace Hks
} // namespace Security

View File

@ -1,4 +1,33 @@
/*
* Copyright (c) 2023-2023 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifdef HKS_CONFIG_FILE
#include HKS_CONFIG_FILE
#else
#include "hks_config.h"
#endif
#include "hks_sa_interface.h"
#include <errors.h>
#include <ipc_types.h>
#include <memory>
#include <mutex>
#include <securec.h>
#include "hks_dcm_callback_handler.h"
#include "hks_log.h"
#include "huks_service_ipc_interface_code.h"
@ -6,28 +35,67 @@ namespace OHOS {
namespace Security {
namespace Hks {
void HksStub::SendAsyncReply(int &replyValue)
void HksStub::SendAsyncReply(uint32_t errCode, std::unique_ptr<uint8_t[]> &certChain, uint32_t sz)
{
HKS_LOG_I("%" LOG_PUBLIC "s:%" LOG_PUBLIC "d:called", __PRETTY_FUNCTION__, __LITE__);
std::unique_lock<std::mutex> lck(mutex_);
asyncReply_ = replyValue;
cv_.notify_all();
std::unique_lock<std::mutex> lck(mMutex);
mErrCode = errCode;
mAsyncReply = std::move(certChain);
mSize = sz;
mCv.notify_all();
}
int HksStub::ProcessAttestKeyAsyncReply(MessageParcel& data)
{
std::unique_ptr<uint8_t[]> certChain{};
uint32_t errCode = data.ReadUint32();
if (errCode != DCM_SUCCESS) {
HKS_LOG_E("ipc client read errCode %" LOG_PUBLIC "u", errCode);
SendAsyncReply(errCode, certChain, 0);
return ERR_INVALID_DATA;
}
uint32_t certChainLen = 0;
int err = ERR_INVALID_DATA;
do {
uint32_t sz = data.ReadUint32();
if (sz == 0) {
HKS_LOG_E("sz is 0");
break;
}
const uint8_t *ptr = data.ReadBuffer(sz);
if (ptr == nullptr) {
HKS_LOG_E("ReadBuffer %" LOG_PUBLIC "u size ptr is nullptr", sz);
break;
}
std::unique_ptr<uint8_t[]> receivedPtr(new (std::nothrow) uint8_t[sz]());
if (receivedPtr == nullptr) {
HKS_LOG_E("new receivedPtr failed");
err = ERR_NO_MEMORY;
break;
}
errno_t err = memcpy_s(receivedPtr.get(), sz, ptr, sz);
if (err != EOK) {
HKS_LOG_E("memcpy_s receivedPtr failed");
break;
}
err = ERR_OK;
certChain = std::move(receivedPtr);
certChainLen = sz;
} while (false);
SendAsyncReply(errCode, certChain, certChainLen);
return err;
}
int HksStub::OnRemoteRequest(uint32_t code,
MessageParcel& data, MessageParcel& reply, MessageOption& option)
{
HKS_LOG_I("%" LOG_PUBLIC "s:%" LOG_PUBLIC "d:called code = %" LOG_PUBLIC "d", __PRETTY_FUNCTION__, __LITE__, code);
int result = ERR_NONE;
switch (code) {
case HKS_MSG_ATTEST_KEY_ASYNC_REPLY: {
int32_t replyData = data.ReadInt32();
HKS_LOG_I("%" LOG_PUBLIC "s:%" LOG_PUBLIC "d:called replyData = %" LOG_PUBLIC "d", __PRETTY_FUNCTION__, __LITE__, replyData);
SendAsyncReply(replyData);
case HKS_MSG_ATTEST_KEY_ASYNC_REPLY:
result = ProcessAttestKeyAsyncReply(data);
break;
}
default:
HKS_LOG_E("unknown remote request code %" LOG_PUBLIC "u", code);
result = ERR_TRANSACTION_FAILED;
break;
}
@ -35,32 +103,66 @@ int HksStub::OnRemoteRequest(uint32_t code,
return result;
}
int HksStub::WaitForAsyncReply(int timeout)
std::tuple<uint32_t, std::unique_ptr<uint8_t[]>, uint32_t> HksStub::WaitForAsyncReply(int timeout)
{
HKS_LOG_I("%" LOG_PUBLIC "s:%" LOG_PUBLIC "d:called", __PRETTY_FUNCTION__, __LITE__);
asyncReply_ = 0;
std::unique_lock<std::mutex> lck(mutex_);
cv_.wait_for(lck, std::chrono::seconds(timeout), [this]() {
return asyncReply_ != 0;
});
return asyncReply_;
std::unique_lock<std::mutex> lck(mMutex);
mAsyncReply = nullptr;
mSize = 0;
mErrCode = DCM_SUCCESS;
HKS_LOG_I("begin wait for async reply");
mCv.wait_for(lck, std::chrono::seconds(timeout));
return {mErrCode, std::move(mAsyncReply), mSize};
}
BrokerDelegator<HksProxy> HksProxy::delegator_;
HksProxy::HksProxy(const sptr<IRemoteObject> &impl)
: IRemoteProxy<IHksService>(impl)
{
HKS_LOG_I("%" LOG_PUBLIC "s:%" LOG_PUBLIC "d:called", __PRETTY_FUNCTION__, __LITE__);
}
void HksProxy::SendAsyncReply(int &replyValue)
void HksProxy::SendAsyncReply(uint32_t errCode, std::unique_ptr<uint8_t[]> &certChain, uint32_t sz)
{
HKS_LOG_I("%" LOG_PUBLIC "s:%" LOG_PUBLIC "d:called", __PRETTY_FUNCTION__, __LITE__);
if (Remote() == nullptr) {
HKS_LOG_E("Remote() is nullptr! Would not SendRequest!");
return;
}
MessageParcel data, reply;
MessageOption option = { MessageOption::TF_ASYNC };
data.WriteInt32(replyValue);
MessageOption option = MessageOption::TF_ASYNC;
bool writeResult = data.WriteUint32(errCode);
if (!writeResult) {
HKS_LOG_E("WriteUint32 errCode %" LOG_PUBLIC "u failed %" LOG_PUBLIC "d", errCode, writeResult);
return;
}
if (errCode != DCM_SUCCESS) {
HKS_LOG_E("dcm callback fail errCode %" LOG_PUBLIC "u", errCode);
int res = Remote()->SendRequest(HKS_MSG_ATTEST_KEY_ASYNC_REPLY, data, reply, option);
if (res != ERR_OK) {
HKS_LOG_E("send fail reply errCode failed %" LOG_PUBLIC "d", res);
}
return;
}
writeResult = data.WriteUint32(sz);
if (!writeResult) {
HKS_LOG_E("WriteUint32 sz %" LOG_PUBLIC "u failed %" LOG_PUBLIC "d", sz, writeResult);
return;
}
if (sz == 0 || certChain == nullptr) {
HKS_LOG_E("dcm reply success but empty certChain %" LOG_PUBLIC "u", sz);
int res = Remote()->SendRequest(HKS_MSG_ATTEST_KEY_ASYNC_REPLY, data, reply, option);
if (res != ERR_OK) {
HKS_LOG_E("Remote()->SendRequest HKS_MSG_ATTEST_KEY_ASYNC_REPLY failed %" LOG_PUBLIC "d", res);
}
return;
}
writeResult = data.WriteBuffer(certChain.get(), sz);
if (!writeResult) {
HKS_LOG_E("WriteBuffer size %" LOG_PUBLIC "u failed %" LOG_PUBLIC "d", sz, writeResult);
return;
}
int res = Remote()->SendRequest(HKS_MSG_ATTEST_KEY_ASYNC_REPLY, data, reply, option);
HKS_LOG_I("%" LOG_PUBLIC "s:%" LOG_PUBLIC "d: res = %" LOG_PUBLIC "d:", __PRETTY_FUNCTION__, __LITE__, res);
if (res != ERR_OK) {
HKS_LOG_E("Remote()->SendRequest HKS_MSG_ATTEST_KEY_ASYNC_REPLY failed %" LOG_PUBLIC "d", res);
}
}
} // namespace Hks

View File

@ -1,6 +1,25 @@
#include "iremote_broker.h"
#include "iremote_proxy.h"
#include "iremote_stub.h"
/*
* Copyright (c) 2023-2023 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef HKS_SA_INTERFACE_H
#define HKS_SA_INTERFACE_H
#include <iremote_broker.h>
#include <iremote_proxy.h>
#include <iremote_stub.h>
#include <memory>
namespace OHOS {
namespace Security {
@ -8,28 +27,35 @@ namespace Hks {
class IHksService : public IRemoteBroker {
public:
DECLARE_INTERFACE_DESCRIPTOR(u"ohos.security.hks.service");
virtual void SendAsyncReply(int &reply) = 0;
virtual void SendAsyncReply(uint32_t errCode, std::unique_ptr<uint8_t[]> &certChain, uint32_t sz) = 0;
};
class HksStub : public IRemoteStub<IHksService> {
public:
void SendAsyncReply(int &reply) override;
int WaitForAsyncReply(int timeout);
void SendAsyncReply(uint32_t errCode, std::unique_ptr<uint8_t[]> &certChain, uint32_t sz) override;
std::tuple<uint32_t, std::unique_ptr<uint8_t[]>, uint32_t> WaitForAsyncReply(int timeout);
int OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) override;
private:
int asyncReply_ = { 0 };
std::mutex mutex_;
std::condition_variable cv_;
int ProcessAttestKeyAsyncReply(MessageParcel& data);
uint32_t mErrCode = 0;
uint32_t mSize = 0;
std::unique_ptr<uint8_t[]> mAsyncReply {};
std::mutex mMutex;
std::condition_variable mCv;
};
class HksProxy : public IRemoteProxy<IHksService> {
public:
explicit HksProxy(const sptr<IRemoteObject> &impl);
~HksProxy() = default;
void SendAsyncReply(int &reply) override;
void SendAsyncReply(uint32_t errCode, std::unique_ptr<uint8_t[]> &certChain, uint32_t sz) override;
private:
static BrokerDelegator<HksProxy> delegator_;
};
};
} // namespace Hks
} // namespace Security
} // namespace OHOS
#endif // HKS_SA_INTERFACE_H

View File

@ -28,6 +28,7 @@
#define STRING_TAG_UNWRAP_ALGORITHM_SUITE "unwrapAlgorithmSuit"
#define STRING_TAG_ITERATION "iteration"
#define STRING_TAG_PURPOSE "purpose"
#define STRING_TAG_ATTESTATION_MODE "attestationMode"
static const struct HksBlob g_tagKeySize = {sizeof(STRING_TAG_KEY_SIZE) - 1, (uint8_t *)STRING_TAG_KEY_SIZE};
static const struct HksBlob g_tagDigest = {sizeof(STRING_TAG_DIGEST) - 1, (uint8_t *)STRING_TAG_DIGEST};
@ -36,6 +37,8 @@ static const struct HksBlob g_tagUnwrapAlgorithmSuit = {sizeof(STRING_TAG_UNWRAP
(uint8_t *)STRING_TAG_UNWRAP_ALGORITHM_SUITE};
static const struct HksBlob g_tagIteration = {sizeof(STRING_TAG_ITERATION) - 1, (uint8_t *)STRING_TAG_ITERATION};
static const struct HksBlob g_tagPurpose = {sizeof(STRING_TAG_PURPOSE) - 1, (uint8_t *)STRING_TAG_PURPOSE};
static const struct HksBlob g_tagAttestationMode = {
sizeof(STRING_TAG_ATTESTATION_MODE) - 1, (uint8_t *)STRING_TAG_ATTESTATION_MODE};
static int32_t AppendParamToExtra(const struct HksParam *paramIn, char *extraOut, uint32_t *index)
{
@ -139,6 +142,7 @@ static void PackExtra(const struct HksParamSet *paramSetIn, char *extraOut)
AppendIfExist(HKS_TAG_BLOCK_MODE, paramSetIn, &g_tagBlockMode, extraOut, &index);
AppendIfExist(HKS_TAG_UNWRAP_ALGORITHM_SUITE, paramSetIn, &g_tagUnwrapAlgorithmSuit, extraOut, &index);
AppendIfExist(HKS_TAG_ITERATION, paramSetIn, &g_tagIteration, extraOut, &index);
AppendIfExist(HKS_TAG_ATTESTATION_MODE, paramSetIn, &g_tagAttestationMode, extraOut, &index);
}
int32_t ReportFaultEvent(const char *funcName, const struct HksProcessInfo *processInfo,

View File

@ -32,7 +32,7 @@ namespace OHOS {
if (data == nullptr || size <= (TRIPLE_BLOB_SIZE + sizeof(struct HksParamSet))) {
return false;
}
uint8_t *myData = static_cast<uint8_t *>(HksMalloc(sizeof(uint8_t) * size));
if (myData == nullptr) {
return false;

View File

@ -888,7 +888,7 @@ protected:
} else {
EXPECT_EQ(EcdsaVerify(&pubKey, digest, &message, &signature), testCaseParams.verifyResult);
}
(void)HksDeleteKey(&authId, nullptr);
if (storage == HKS_STORAGE_TEMP) {
HksFree(authId.data);

View File

@ -871,7 +871,7 @@ protected:
} else {
EXPECT_EQ(EcdsaSign(&authId, digest, &message, &signature), testCaseParams.signResult);
}
if (storage == HKS_STORAGE_TEMP) {
EXPECT_EQ(HksVerify(&pubKey, paramInSet, &message, &signature), testCaseParams.verifyResult);
} else if (storage == HKS_STORAGE_PERSISTENT) {

View File

@ -137,7 +137,7 @@ HWTEST_F(HksBaseCheckTest, HksBaseCheckTest005, TestSize.Level0)
HWTEST_F(HksBaseCheckTest, HksBaseCheckTest006, TestSize.Level0)
{
HKS_LOG_I("enter HksBaseCheckTest006");
int32_t ret = HksCheckSignature(0, HKS_ALG_RSA, HKS_ECC_KEY_SIZE_256, nullptr);
ASSERT_EQ(ret, HKS_ERROR_INVALID_ARGUMENT) << "HksCheckSignature failed, ret = " << ret;
}
@ -150,7 +150,7 @@ HWTEST_F(HksBaseCheckTest, HksBaseCheckTest006, TestSize.Level0)
HWTEST_F(HksBaseCheckTest, HksBaseCheckTest007, TestSize.Level0)
{
HKS_LOG_I("enter HksBaseCheckTest007");
int32_t ret = HksCheckSignature(0, HKS_ALG_ECC, HKS_RSA_KEY_SIZE_1024, nullptr);
ASSERT_EQ(ret, HKS_ERROR_INVALID_ARGUMENT) << "HksCheckSignature failed, ret = " << ret;
}

View File

@ -270,7 +270,7 @@ HWTEST_F(HksClientServiceTest, HksClientServiceTest003, TestSize.Level0)
struct HksBlob *certChain = nullptr;
ret = ConstructCertChainBlob(&certChain);
ASSERT_TRUE(ret == HKS_SUCCESS) << "ConstructCertChainBlob failed, ret = " << ret;
ret = HksServiceAttestKey(&processInfo, &keyAliasBlob, paramSet, certChain);
ret = HksServiceAttestKey(&processInfo, &keyAliasBlob, paramSet, certChain, nullptr);
ASSERT_TRUE(ret == HKS_SUCCESS) << "HksServiceAttestKey failed, ret = " << ret;
FreeCertChainBlob(certChain);
HksFreeParamSet(&paramSet);
@ -324,7 +324,7 @@ HWTEST_F(HksClientServiceTest, HksClientServiceTest004, TestSize.Level0)
struct HksBlob *certChain = nullptr;
ret = ConstructCertChainBlob(&certChain);
ASSERT_TRUE(ret == HKS_SUCCESS) << "ConstructCertChainBlob failed, ret = " << ret;
ret = HksServiceAttestKey(&processInfo, &keyAlias, paramSet, certChain);
ret = HksServiceAttestKey(&processInfo, &keyAlias, paramSet, certChain, nullptr);
ASSERT_TRUE(ret == HKS_SUCCESS) << "HksServiceAttestKey failed, ret = " << ret;
HKS_LOG_I("Attest key success!");
FreeCertChainBlob(certChain);
@ -384,7 +384,7 @@ HWTEST_F(HksClientServiceTest, HksClientServiceTest005, TestSize.Level0)
struct HksBlob *certChain = nullptr;
ret = ConstructCertChainBlob(&certChain);
ASSERT_TRUE(ret == HKS_SUCCESS) << "HksClientServiceTest005 ConstructCertChainBlob failed, ret = " << ret;
ret = HksServiceAttestKey(&processInfo, &keyAlias, paramSet, certChain);
ret = HksServiceAttestKey(&processInfo, &keyAlias, paramSet, certChain, nullptr);
ASSERT_TRUE(ret == HKS_SUCCESS) << "HksClientServiceTest005 HksServiceAttestKey failed, ret = " << ret;
HKS_LOG_I("Attest key success!");
FreeCertChainBlob(certChain);

View File

@ -93,7 +93,7 @@ HWTEST_F(HksEventObserverTest, HksEventObserverTest002, TestSize.Level0)
HKS_LOG_I("enter HksEventObserverTest002");
Want want;
want.SetAction(OHOS::EventFwk::CommonEventSupport::COMMON_EVENT_USER_REMOVED);
CommonEventData data;
data.SetWant(want);

View File

@ -1,30 +0,0 @@
/*
* Copyright (C) 2022-2023 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef HKS_ATTEST_KEY_NONIDS_TEST_H
#define HKS_ATTEST_KEY_NONIDS_TEST_H
namespace Unittest::AttestKey {
int HksAttestKeyNonIdsTest001(void);
int HksAttestKeyNonIdsTest002(void);
int HksAttestKeyNonIdsTest003(void);
int HksAttestKeyNonIdsTest004(void);
int HksAttestKeyNonIdsTest005(void);
int HksAttestKeyNonIdsTest006(void);
int HksAttestKeyNonIdsTest007(void);
int HksAttestKeyNonIdsTest008(void);
}
#endif

View File

@ -368,7 +368,7 @@ HWTEST_F(HksAccessControlAgreeTest, HksAccessAgreePartTest007, TestSize.Level0)
struct HksBlob keyAlias = { sizeof(alias), alias };
uint8_t alias2[] = "testCheckAuthAgree2";
struct HksBlob keyAlias2 = { sizeof(alias2), alias2 };
struct HksParamSet *genParamSet = nullptr;
int32_t ret = InitParamSet(&genParamSet, HKS_ACCESS_TEST_001_PARAMS.genParams.data(),
HKS_ACCESS_TEST_001_PARAMS.genParams.size());

View File

@ -535,7 +535,7 @@ HWTEST_F(HksAccessControlCipherTest, HksAccessCipherPartTest014, TestSize.Level0
HKS_LOG_I("Enter HksAccessCipherPartTest014");
uint8_t alias[] = "testCheckAuthCipher";
struct HksBlob keyAlias = { sizeof(alias), alias };
struct HksParamSet *genParamSet = nullptr;
int32_t ret = InitParamSet(&genParamSet, HKS_ACCESS_TEST_001_PARAMS.genParams.data(),
HKS_ACCESS_TEST_001_PARAMS.genParams.size());

View File

@ -285,7 +285,7 @@ HWTEST_F(HksAccessControlDeriveTest, HksAccessDerivePartTest005, TestSize.Level0
HKS_LOG_I("Enter HksAccessDerivePartTest005");
uint8_t alias[] = "testCheckAuthDerive";
struct HksBlob keyAlias = { sizeof(alias), alias };
struct HksParamSet *genParamSet = nullptr;
int32_t ret = InitParamSet(&genParamSet, HKS_ACCESS_TEST_001_PARAMS.genParams.data(),
HKS_ACCESS_TEST_001_PARAMS.genParams.size());
@ -305,7 +305,7 @@ HWTEST_F(HksAccessControlDeriveTest, HksAccessDerivePartTest005, TestSize.Level0
struct HksParamSet *deriveParamSet = nullptr;
ret = InitParamSet(&deriveParamSet, deriveParams, sizeof(deriveParams) / sizeof(HksParam));
ASSERT_EQ(ret, HKS_SUCCESS);
uint8_t out[256] = {0};
struct HksBlob outBlob = { sizeof(out), out };
ret = HksDeriveKey(deriveParamSet, &keyAlias, &outBlob);

View File

@ -220,7 +220,7 @@ HWTEST_F(HksAccessControlMacTest, HksAccessMacPartTest005, TestSize.Level0)
HKS_LOG_I("Enter HksAccessMacPartTest005");
uint8_t alias[] = "testCheckAuthMac";
struct HksBlob keyAlias = { sizeof(alias), alias };
struct HksParamSet *genParamSet = nullptr;
int32_t ret = InitParamSet(&genParamSet, HKS_ACCESS_TEST_001_PARAMS.genParams.data(),
HKS_ACCESS_TEST_001_PARAMS.genParams.size());
@ -240,7 +240,7 @@ HWTEST_F(HksAccessControlMacTest, HksAccessMacPartTest005, TestSize.Level0)
struct HksParamSet *macParamSet = nullptr;
ret = InitParamSet(&macParamSet, macParams, sizeof(macParams) / sizeof(HksParam));
ASSERT_EQ(ret, HKS_SUCCESS);
uint8_t out[256] = {0};
struct HksBlob outBlob = { sizeof(out), out };
ret = HksMac(&keyAlias, macParamSet, &outBlob, &outBlob);

View File

@ -680,7 +680,7 @@ HWTEST_F(HksAccessControlRsaSignVerifyTest, HksAcRsaSignVerifyTest012, TestSize.
HKS_LOG_I("Enter HksAcRsaSignVerifyTest0012");
uint8_t alias[] = "testCheckAuthSigner";
struct HksBlob keyAlias = { sizeof(alias), alias };
struct HksParamSet *genParamSet = nullptr;
int32_t ret = InitParamSet(&genParamSet, HKS_ACCESS_TEST_RSA_SIGN_001_PARAMS.genParams.data(),
HKS_ACCESS_TEST_RSA_SIGN_001_PARAMS.genParams.size());

View File

@ -61,7 +61,7 @@ void HksAccessControlSecureSignTest::TearDown()
static const std::string g_inData = "Hks_SM4_Cipher_Test_000000000000000000000000000000000000000000000000000000000000"
"00000000000000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000000_string";
static const std::string g_inDataLess64 = "Hks_SM4_Cipher_Test_000000000000000000000000000000000000";
static const uint32_t g_authHeadSize = 24;
@ -265,7 +265,7 @@ static struct HksParam g_importDsaKeyParams[] = {
}
};
static struct HksParam g_importDsaKeyParamsNoAuthInfo[] = {
{ .tag = HKS_TAG_ALGORITHM, .uint32Param = HKS_ALG_DSA },
{ .tag = HKS_TAG_PURPOSE, .uint32Param = HKS_KEY_PURPOSE_SIGN | HKS_KEY_PURPOSE_VERIFY },
@ -503,7 +503,7 @@ static int32_t BuildImportKeyParamsForRsa(struct HksTestSecureSignImportParams *
importParams->inputParamSize = isAuth ? sizeof(g_importRsaKeyParams)/sizeof(g_importRsaKeyParams[0]) :
sizeof(g_importRsaKeyParamsNoAuth)/sizeof(g_importRsaKeyParamsNoAuth[0]);
}
importParams->expectResult = HKS_SUCCESS;
uint8_t *keyBuffer = (uint8_t *)HksMalloc(MAX_KEY_SIZE);
if (keyBuffer == nullptr) {
@ -742,7 +742,7 @@ int32_t HksTestUpdateFinishSignAuthInfo(struct HksTestSecureSignVerifyUpdateFini
}
genAuthTokenParams->authChallenge = &challenge;
struct HksParamSet *newParamSet = nullptr;
ret = HksBuildAuthTokenSecure(paramSet, genAuthTokenParams, &newParamSet);
EXPECT_EQ(ret, HKS_SUCCESS) << "HksBuildAuthTokenSecure failed.";
@ -772,7 +772,7 @@ int32_t HksTestUpdateFinishSignAuthInfo(struct HksTestSecureSignVerifyUpdateFini
HksFreeParamSet(&newParamSet);
return HKS_FAILURE;
}
HksFreeParamSet(&paramSet);
HksFreeParamSet(&newParamSet);
return ret;
@ -847,7 +847,7 @@ int32_t HksTestUpdateFinishVerifySignAuthInfo(struct HksTestSecureSignVerifyUpda
HksFreeParamSet(&newParamSet);
return HKS_FAILURE;
}
return ret;
}

View File

@ -13,16 +13,14 @@
* limitations under the License.
*/
#include "hks_attest_key_nonids_test.h"
#include <gtest/gtest.h>
#ifdef L2_STANDARD
#include "file_ex.h"
#endif
#include "hks_attest_key_test_common.h"
#include "native_huks_type.h"
#include "native_huks_api.h"
#include "native_huks_type.h"
using namespace testing::ext;
namespace Unittest::AttestKey {
@ -59,6 +57,7 @@ void HksAttestKeyNonIdsTest::TearDown()
}
static const struct HksBlob g_keyAlias = { sizeof(ALIAS), (uint8_t *)ALIAS };
static struct OH_Huks_Blob oh_g_keyAlias = { sizeof(ALIAS), (uint8_t *)ALIAS };
static const struct HksParam g_commonParams[] = {
{ .tag = HKS_TAG_ATTESTATION_ID_SEC_LEVEL_INFO, .blob = g_secInfo },
@ -77,7 +76,7 @@ static void ValidateCertChain(struct HksParamSet *paramSet, struct HksParamSet *
.tag = HKS_TAG_ASYMMETRIC_PUBLIC_KEY_DATA,
.blob = { .size = g_keyParamsetSize, .data = (uint8_t *)HksMalloc(g_keyParamsetSize) }
};
ASSERT_TRUE(g_getParam.blob.data != nullptr);
ASSERT_NE(g_getParam.blob.data, nullptr);
struct HksParam *keySizeParam = nullptr;
uint32_t rootUid = 0;
HksInitParamSet(&paramOutSet);
@ -85,13 +84,13 @@ static void ValidateCertChain(struct HksParamSet *paramSet, struct HksParamSet *
HksBuildParamSet(&paramOutSet);
HksFree(g_getParam.blob.data);
int32_t ret = HksGetKeyParamSet(&g_keyAlias, nullptr, paramOutSet);
ASSERT_TRUE(ret == HKS_SUCCESS);
ASSERT_EQ(ret, HKS_SUCCESS);
ret = HksGetParam(paramOutSet, HKS_TAG_KEY_SIZE, &keySizeParam);
ASSERT_TRUE(ret == HKS_SUCCESS);
ASSERT_TRUE(keySizeParam->uint32Param == HKS_RSA_KEY_SIZE_2048);
ASSERT_EQ(ret, HKS_SUCCESS);
ASSERT_EQ(keySizeParam->uint32Param, HKS_RSA_KEY_SIZE_2048);
struct HksParam *processParam = nullptr;
ret = HksGetParam(paramOutSet, HKS_TAG_PROCESS_NAME, &processParam);
ASSERT_TRUE(ret == HKS_SUCCESS);
ASSERT_EQ(ret, HKS_SUCCESS);
ASSERT_EQ(sizeof(rootUid), processParam->blob.size);
ASSERT_EQ(HksMemCmp(processParam->blob.data, &rootUid, processParam->blob.size), HKS_SUCCESS);
@ -104,7 +103,7 @@ static void ValidateCertChain(struct HksParamSet *paramSet, struct HksParamSet *
HksFreeParamSet(&paramSet);
ret = HksDeleteKey(&g_keyAlias, nullptr);
ASSERT_TRUE(ret == HKS_SUCCESS);
ASSERT_EQ(ret, HKS_SUCCESS);
}
/**
@ -120,7 +119,7 @@ HWTEST_F(HksAttestKeyNonIdsTest, HksAttestKeyNonIdsTest001, TestSize.Level0)
HksCertChain *certChain = nullptr;
HKS_LOG_I("enter HksAttestKeyNonIdsTest001");
int32_t ret = TestGenerateKey(&g_keyAlias, HKS_PADDING_PSS);
ASSERT_TRUE(ret == HKS_SUCCESS);
ASSERT_EQ(ret, HKS_SUCCESS);
GenerateParamSet(&paramSet, g_commonParams, sizeof(g_commonParams) / sizeof(g_commonParams[0]));
const struct HksTestCertChain certParam = { true, true, true, g_size };
(void)ConstructDataToCertChain(&certChain, &certParam);
@ -128,7 +127,7 @@ HWTEST_F(HksAttestKeyNonIdsTest, HksAttestKeyNonIdsTest001, TestSize.Level0)
if (ret != HKS_SUCCESS) {
HKS_LOG_I("HksAttestKey fail, ret is %" LOG_PUBLIC "d!", ret);
}
ASSERT_TRUE(ret == HKS_ERROR_NO_PERMISSION);
ASSERT_EQ(ret, HKS_ERROR_NO_PERMISSION);
ValidateCertChain(paramSet, paramOutSet, certChain);
}
@ -142,27 +141,27 @@ HWTEST_F(HksAttestKeyNonIdsTest, HksAttestKeyNonIdsTest002, TestSize.Level0)
{
HKS_LOG_I("enter HksAttestKeyNonIdsTest002");
int32_t ret = TestGenerateKey(&g_keyAlias, HKS_PADDING_PSS);
ASSERT_TRUE(ret == HKS_SUCCESS);
ASSERT_EQ(ret, HKS_SUCCESS);
struct HksParamSet *paramSet = NULL;
HksCertChain *certChain = NULL;
GenerateParamSet(&paramSet, g_commonParams, sizeof(g_commonParams) / sizeof(g_commonParams[0]));
const struct HksTestCertChain certParam = { true, true, false, g_size };
(void)ConstructDataToCertChain(&certChain, &certParam);
ret = HksAttestKey(&g_keyAlias, paramSet, certChain);
ASSERT_TRUE(ret == HKS_ERROR_INVALID_ARGUMENT);
ASSERT_EQ(ret, HKS_ERROR_INVALID_ARGUMENT);
FreeCertChain(&certChain, certChain->certsCount);
certChain = NULL;
(void)ConstructDataToCertChain(&certChain, &certParam);
ret = HksAnonAttestKey(&g_keyAlias, paramSet, certChain);
ASSERT_TRUE(ret == HKS_ERROR_INVALID_ARGUMENT);
ASSERT_EQ(ret, HKS_ERROR_INVALID_ARGUMENT);
FreeCertChain(&certChain, certChain->certsCount);
certChain = NULL;
HksFreeParamSet(&paramSet);
ret = HksDeleteKey(&g_keyAlias, NULL);
ASSERT_TRUE(ret == HKS_SUCCESS);
ASSERT_EQ(ret, HKS_SUCCESS);
}
/**
@ -175,26 +174,26 @@ HWTEST_F(HksAttestKeyNonIdsTest, HksAttestKeyNonIdsTest003, TestSize.Level0)
{
HKS_LOG_I("enter HksAttestKeyNonIdsTest003");
int32_t ret = TestGenerateKey(&g_keyAlias, HKS_PADDING_PSS);
ASSERT_TRUE(ret == HKS_SUCCESS);
ASSERT_EQ(ret, HKS_SUCCESS);
struct HksParamSet *paramSet = NULL;
GenerateParamSet(&paramSet, g_commonParams, sizeof(g_commonParams) / sizeof(g_commonParams[0]));
HksCertChain *certChain = NULL;
const struct HksTestCertChain certParam = { true, false, true, g_size };
(void)ConstructDataToCertChain(&certChain, &certParam);
ret = HksAttestKey(&g_keyAlias, paramSet, certChain);
ASSERT_TRUE(ret == HKS_ERROR_INVALID_ARGUMENT);
ASSERT_EQ(ret, HKS_ERROR_INVALID_ARGUMENT);
FreeCertChain(&certChain, certChain->certsCount);
(void)ConstructDataToCertChain(&certChain, &certParam);
ret = HksAnonAttestKey(&g_keyAlias, paramSet, certChain);
ASSERT_TRUE(ret == HKS_ERROR_INVALID_ARGUMENT);
ASSERT_EQ(ret, HKS_ERROR_INVALID_ARGUMENT);
FreeCertChain(&certChain, certChain->certsCount);
HksFreeParamSet(&paramSet);
ret = HksDeleteKey(&g_keyAlias, NULL);
ASSERT_TRUE(ret == HKS_SUCCESS);
ASSERT_EQ(ret, HKS_SUCCESS);
}
/**
@ -207,21 +206,21 @@ HWTEST_F(HksAttestKeyNonIdsTest, HksAttestKeyNonIdsTest004, TestSize.Level0)
{
HKS_LOG_I("enter HksAttestKeyNonIdsTest004");
int32_t ret = TestGenerateKey(&g_keyAlias, HKS_PADDING_PSS);
ASSERT_TRUE(ret == HKS_SUCCESS);
ASSERT_EQ(ret, HKS_SUCCESS);
struct HksParamSet *paramSet = NULL;
GenerateParamSet(&paramSet, g_commonParams, sizeof(g_commonParams) / sizeof(g_commonParams[0]));
HksCertChain *certChain = NULL;
const struct HksTestCertChain certParam = { false, true, true, g_size };
(void)ConstructDataToCertChain(&certChain, &certParam);
ret = HksAttestKey(&g_keyAlias, paramSet, certChain);
ASSERT_TRUE(ret == HKS_ERROR_NULL_POINTER);
ASSERT_EQ(ret, HKS_ERROR_NULL_POINTER);
if (certChain != NULL) {
FreeCertChain(&certChain, certChain->certsCount);
}
(void)ConstructDataToCertChain(&certChain, &certParam);
ret = HksAnonAttestKey(&g_keyAlias, paramSet, certChain);
ASSERT_TRUE(ret == HKS_ERROR_NULL_POINTER);
ASSERT_EQ(ret, HKS_ERROR_NULL_POINTER);
if (certChain != NULL) {
FreeCertChain(&certChain, certChain->certsCount);
}
@ -229,7 +228,7 @@ HWTEST_F(HksAttestKeyNonIdsTest, HksAttestKeyNonIdsTest004, TestSize.Level0)
HksFreeParamSet(&paramSet);
ret = HksDeleteKey(&g_keyAlias, NULL);
ASSERT_TRUE(ret == HKS_SUCCESS);
ASSERT_EQ(ret, HKS_SUCCESS);
}
/**
@ -242,7 +241,7 @@ HWTEST_F(HksAttestKeyNonIdsTest, HksAttestKeyNonIdsTest005, TestSize.Level0)
{
HKS_LOG_I("enter HksAttestKeyNonIdsTest005");
int32_t ret = TestGenerateKey(&g_keyAlias, HKS_PADDING_PSS);
ASSERT_TRUE(ret == HKS_SUCCESS);
ASSERT_EQ(ret, HKS_SUCCESS);
struct HksParam g_commonParams[] = {
{ .tag = HKS_TAG_ATTESTATION_ID_SEC_LEVEL_INFO, .blob = g_secInfo },
{ .tag = HKS_TAG_ATTESTATION_CHALLENGE, .blob = g_challenge },
@ -258,7 +257,7 @@ HWTEST_F(HksAttestKeyNonIdsTest, HksAttestKeyNonIdsTest005, TestSize.Level0)
(void)ConstructDataToCertChain(&certChain, &certParam);
ret = HksAttestKey(&g_keyAlias, paramSet, certChain);
ASSERT_TRUE(ret == HKS_ERROR_NO_PERMISSION);
ASSERT_EQ(ret, HKS_ERROR_NO_PERMISSION);
ret = ValidateCertChainTest(certChain, g_commonParams, NON_IDS_BASE64_PARAM);
FreeCertChain(&certChain, certChain->certsCount);
@ -266,7 +265,7 @@ HWTEST_F(HksAttestKeyNonIdsTest, HksAttestKeyNonIdsTest005, TestSize.Level0)
HksFreeParamSet(&paramSet);
ret = HksDeleteKey(&g_keyAlias, NULL);
ASSERT_TRUE(ret == HKS_SUCCESS);
ASSERT_EQ(ret, HKS_SUCCESS);
}
/**
@ -279,7 +278,7 @@ HWTEST_F(HksAttestKeyNonIdsTest, HksAttestKeyNonIdsTest007, TestSize.Level0)
{
HKS_LOG_I("enter HksAttestKeyNonIdsTest007");
int32_t ret = TestGenerateKey(&g_keyAlias, HKS_PADDING_PSS);
ASSERT_TRUE(ret == HKS_SUCCESS);
ASSERT_EQ(ret, HKS_SUCCESS);
static struct HksBlob dId = { sizeof(DEVICE_ID), (uint8_t *)DEVICE_ID };
struct HksParam g_commonParams[] = {
{ .tag = HKS_TAG_ATTESTATION_ID_SEC_LEVEL_INFO, .blob = g_secInfo },
@ -296,23 +295,14 @@ HWTEST_F(HksAttestKeyNonIdsTest, HksAttestKeyNonIdsTest007, TestSize.Level0)
(void)ConstructDataToCertChain(&certChain, &certParam);
ret = HksAttestKey(&g_keyAlias, paramSet, certChain);
ASSERT_TRUE(ret == HKS_ERROR_NO_PERMISSION);
ASSERT_EQ(ret, HKS_ERROR_NO_PERMISSION);
FreeCertChain(&certChain, certChain->certsCount);
certChain = NULL;
(void)ConstructDataToCertChain(&certChain, &certParam);
ret = HksAnonAttestKey(&g_keyAlias, paramSet, certChain);
ASSERT_TRUE(ret == HKS_ERROR_NO_PERMISSION);
FreeCertChain(&certChain, certChain->certsCount);
certChain = NULL;
HksFreeParamSet(&paramSet);
ret = HksDeleteKey(&g_keyAlias, NULL);
ASSERT_TRUE(ret == HKS_SUCCESS);
ASSERT_EQ(ret, HKS_SUCCESS);
}
/**
@ -328,7 +318,7 @@ HWTEST_F(HksAttestKeyNonIdsTest, HksAttestKeyNonIdsTest008, TestSize.Level0)
HksCertChain *certChain = nullptr;
HKS_LOG_I("enter HksAttestKeyNonIdsTest008");
int32_t ret = TestGenerateKey(&g_keyAlias, HKS_PADDING_PKCS1_V1_5);
ASSERT_TRUE(ret == HKS_SUCCESS);
ASSERT_EQ(ret, HKS_SUCCESS);
GenerateParamSet(&paramSet, g_commonParams, sizeof(g_commonParams) / sizeof(g_commonParams[0]));
const struct HksTestCertChain certParam = { true, true, true, g_size };
(void)ConstructDataToCertChain(&certChain, &certParam);
@ -336,8 +326,81 @@ HWTEST_F(HksAttestKeyNonIdsTest, HksAttestKeyNonIdsTest008, TestSize.Level0)
if (ret != HKS_SUCCESS) {
HKS_LOG_I("HksAttestKey fail, ret is %" LOG_PUBLIC "d!", ret);
}
ASSERT_TRUE(ret == HKS_ERROR_NO_PERMISSION);
ASSERT_EQ(ret, HKS_ERROR_NO_PERMISSION);
ValidateCertChain(paramSet, paramOutSet, certChain);
}
/**
* @tc.name: HksAttestKeyNonIdsTest.HksAttestKeyNonIdsTest009
* @tc.desc: attest with right params and validate success.
* @tc.type: FUNC
* @tc.require: issueI5NY0L
*/
HWTEST_F(HksAttestKeyNonIdsTest, HksAttestKeyNonIdsTest009, TestSize.Level0)
{
struct HksParamSet *paramSet = nullptr;
HksCertChain *certChain = nullptr;
HKS_LOG_I("enter HksAttestKeyNonIdsTest009");
int32_t ret = TestGenerateKey(&g_keyAlias, HKS_PADDING_PSS);
ASSERT_EQ(ret, HKS_SUCCESS);
GenerateParamSet(&paramSet, g_commonParams, sizeof(g_commonParams) / sizeof(g_commonParams[0]));
const struct HksTestCertChain certParam = { true, true, true, g_size };
(void)ConstructDataToCertChain(&certChain, &certParam);
ret = HksAnonAttestKey(&g_keyAlias, paramSet, certChain);
if (ret != HKS_SUCCESS) {
HKS_LOG_I("HksAnonAttestKey fail, ret is %" LOG_PUBLIC "d!", ret);
}
ASSERT_EQ(ret, HKS_SUCCESS);
}
/**
* @tc.name: HksAttestKeyNonIdsTest.HksAttestKeyNonIdsTest010
* @tc.desc: attest with right params(use pksc1_v1_5 for padding) and validate success.
* @tc.type: FUNC
* @tc.require: issueI5NY0L
*/
HWTEST_F(HksAttestKeyNonIdsTest, HksAttestKeyNonIdsTest010, TestSize.Level0)
{
struct HksParamSet *paramSet = nullptr;
HksCertChain *certChain = nullptr;
HKS_LOG_I("enter HksAttestKeyNonIdsTest010");
int32_t ret = TestGenerateKey(&g_keyAlias, HKS_PADDING_PKCS1_V1_5);
ASSERT_EQ(ret, HKS_SUCCESS);
GenerateParamSet(&paramSet, g_commonParams, sizeof(g_commonParams) / sizeof(g_commonParams[0]));
const struct HksTestCertChain certParam = { true, true, true, g_size };
(void)ConstructDataToCertChain(&certChain, &certParam);
ret = HksAnonAttestKey(&g_keyAlias, paramSet, certChain);
if (ret != HKS_SUCCESS) {
HKS_LOG_I("HksAnonAttestKey fail, ret is %" LOG_PUBLIC "d!", ret);
}
ASSERT_EQ(ret, HKS_SUCCESS);
}
/**
* @tc.name: HksAttestKeyNonIdsTest.HksAttestKeyNonIdsTest011
* @tc.desc: attest with right params.
* @tc.type: FUNC
* @tc.require: issueI5NY0L
*/
HWTEST_F(HksAttestKeyNonIdsTest, HksAttestKeyNonIdsTest011, TestSize.Level0)
{
struct HksParamSet *paramSet = nullptr;
HksCertChain *certChain = nullptr;
HKS_LOG_I("enter HksAttestKeyNonIdsTest011");
int32_t ret = TestGenerateKey(&g_keyAlias, HKS_PADDING_PSS);
ASSERT_EQ(ret, HKS_SUCCESS);
GenerateParamSet(&paramSet, g_commonParams, sizeof(g_commonParams) / sizeof(g_commonParams[0]));
const struct HksTestCertChain certParam = { true, true, true, g_size };
(void)ConstructDataToCertChain(&certChain, &certParam);
ret = OH_Huks_AnonAttestKeyItem(&oh_g_keyAlias, (struct OH_Huks_ParamSet *) paramSet,
(struct OH_Huks_CertChain *) certChain).errorCode;
if (ret != HKS_SUCCESS) {
HKS_LOG_I("OH_Huks_AnonAttestKeyItem fail, ret is %" LOG_PUBLIC "d!", ret);
}
ASSERT_EQ(ret, HKS_SUCCESS);
FreeCertChain(&certChain, certChain->certsCount);
HksFreeParamSet(&paramSet);
ret = HksDeleteKey(&g_keyAlias, NULL);
ASSERT_EQ(ret, HKS_SUCCESS);
}
}

View File

@ -308,7 +308,7 @@ static int32_t getParamSetAuthTest(struct HksParamSet **paramOutSet, const struc
}
HksAddParams(*paramOutSet, &localSecureKey, 1);
HksBuildParamSet(paramOutSet);
return HKS_SUCCESS;
}
@ -361,7 +361,7 @@ static int32_t CheckImportAuthTest(const TestAuthCaseParams &testCaseParams)
HKS_LOG_I("InitParamSet(gen) failed, ret : %" LOG_PUBLIC "d", ret);
return ret;
}
uint8_t alias[] = "testCheckAuth";
struct HksBlob keyAlias = { sizeof(alias), alias };
ret = HksGenerateKey(&keyAlias, genParamSet, nullptr);

View File

@ -760,7 +760,7 @@ HWTEST_F(HksChipsetPlatformDecryptTest, HksChipsetPlatformDecryptTest011, TestSi
{
HKS_LOG_E("enter HksChipsetPlatformDecryptTest011");
struct HksChipsetPlatformTestCase t(DECRYPT_KEY_NORMAL_CASES[0]);
t.cipher.emplace_back(1);
auto decryptParams = CipherMaterialsToDecryptInputParams(t);
@ -784,7 +784,7 @@ HWTEST_F(HksChipsetPlatformDecryptTest, HksChipsetPlatformDecryptTest012, TestSi
{
HKS_LOG_E("enter HksChipsetPlatformDecryptTest012");
struct HksChipsetPlatformTestCase t(DECRYPT_KEY_NORMAL_CASES[0]);
t.cipher = std::vector<uint8_t>(PLATFORM_KEY_TEXT_MAX_LEN + 1);
auto decryptParams = CipherMaterialsToDecryptInputParams(t);
@ -808,7 +808,7 @@ HWTEST_F(HksChipsetPlatformDecryptTest, HksChipsetPlatformDecryptTest013, TestSi
{
HKS_LOG_E("enter HksChipsetPlatformDecryptTest013");
struct HksChipsetPlatformTestCase t(DECRYPT_KEY_NORMAL_CASES[0]);
t.aad.emplace_back(1);
auto decryptParams = CipherMaterialsToDecryptInputParams(t);
@ -832,7 +832,7 @@ HWTEST_F(HksChipsetPlatformDecryptTest, HksChipsetPlatformDecryptTest014, TestSi
{
HKS_LOG_E("enter HksChipsetPlatformDecryptTest014");
struct HksChipsetPlatformTestCase t(DECRYPT_KEY_NORMAL_CASES[0]);
t.iv.emplace_back(1);
auto decryptParams = CipherMaterialsToDecryptInputParams(t);
@ -856,7 +856,7 @@ HWTEST_F(HksChipsetPlatformDecryptTest, HksChipsetPlatformDecryptTest015, TestSi
{
HKS_LOG_E("enter HksChipsetPlatformDecryptTest015");
struct HksChipsetPlatformTestCase t(DECRYPT_KEY_NORMAL_CASES[0]);
t.mac.emplace_back(1);
auto decryptParams = CipherMaterialsToDecryptInputParams(t);

View File

@ -594,7 +594,7 @@ namespace Unittest::ImportWrappedKey {
ret = BuildWrappedKeyData(blobArray, HKS_IMPORT_WRAPPED_KEY_NO_VERIFY_TOTAL_BLOBS,
isSigned, &wrappedKeyData);
}
EXPECT_EQ(ret, HKS_SUCCESS) << "BuildWrappedKeyData failed.";
HKS_LOG_I("start HksImportWrappedKey");
ret = HksImportWrappedKey(params->importKeyAlias, params->wrappingKeyAlias,
@ -914,7 +914,7 @@ namespace Unittest::ImportWrappedKey {
// The caller guarantees that the access will not cross the border
int32_t ret = ConstructImportedSm2Key(HKS_SM2_KEY_SIZE_256, HKS_KEY_TYPE_PRIVATE_KEY, &key);
EXPECT_EQ(ret, HKS_SUCCESS) << "init sm2 key failed .";
g_importWrappedSm2Params[TAG_ALG_PURPOSE_TYPE_ID].uint32Param = HKS_KEY_PURPOSE_SIGN;
g_importWrappedSm2Params[TAG_ALG_SUIT_ID].uint32Param =
HKS_UNWRAP_SUITE_SM2_SM4_128_CBC_PKCS7_WITH_VERIFY_DIG_SM3;

View File

@ -210,7 +210,7 @@ namespace Unittest::ImportWrappedKey {
&commonAad, &commonNonce, &kekTag, &keyMaterialLen, plainCipher };
int32_t ret = BuildWrappedKeyData(blobArray, HKS_IMPORT_WRAPPED_KEY_TOTAL_BLOBS, wrappedKeyData);
EXPECT_EQ(ret, HKS_SUCCESS) << "BuildWrappedKeyData failed.";
struct HksParam *purpose = nullptr;
ret = HksGetParam(params->importWrappedKeyParamSet, HKS_TAG_PURPOSE, &purpose);
EXPECT_EQ(ret, HKS_SUCCESS) << "Get wrapped purpose param failed.";

View File

@ -131,7 +131,7 @@ int32_t TestBatchUpdateLoopFinish(const struct HksBlob *handle, const struct Hks
if (MallocAndCheckBlobData(&outDataSeg, outDataSeg.size) != HKS_SUCCESS) {
return HKS_FAILURE;
}
int32_t ret = HksUpdate(handle, paramSet, &inDataSeg, &outDataSeg);
if (ret != HKS_SUCCESS) {
HKS_LOG_E("HksUpdate Failed.");
@ -156,7 +156,7 @@ int32_t TestBatchUpdateLoopFinish(const struct HksBlob *handle, const struct Hks
HksFree(outDataFinish.data);
return HKS_FAILURE;
}
if (memcpy_s(cur, curSize, outDataFinish.data, outDataFinish.size) != EOK) {
HksFree(outDataFinish.data);
return HKS_ERROR_BUFFER_TOO_SMALL;
@ -216,7 +216,7 @@ int32_t TestUpdateLoopFinish(const struct HksBlob *handle, const struct HksParam
HksFree(outDataFinish.data);
return HKS_FAILURE;
}
if (memcpy_s(cur, curSize, outDataFinish.data, outDataFinish.size) != EOK) {
HksFree(outDataFinish.data);
return HKS_ERROR_BUFFER_TOO_SMALL;

View File

@ -265,7 +265,7 @@ int32_t HksAesCipherTestCaseGcm3(const struct HksBlob *keyAlias, struct HksParam
struct HksBlob cipherText = { AES_COMMON_SIZE, cipher };
ret = HksAesCipherTestEncryptWithoutNonce(keyAlias, encryptParamSet, &inData, &cipherText, needAccessControl);
EXPECT_EQ(ret, HKS_SUCCESS) << "HksAesCipherTestEncrypt failed.";
cipherText.size -= NONCE_SIZE;
cipherText.size -= AEAD_SIZE;
@ -354,7 +354,7 @@ int32_t HksAesCipherTestCaseGcm4(const struct HksBlob *keyAlias, struct HksParam
if (ret != HKS_SUCCESS) {
return ret;
}
cipherText.size -= NONCE_SIZE;
cipherText.size -= AEAD_SIZE;