From 06c50ccaca92cd9155a9ff66c8dc902b543809e8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=A2=81=E6=B5=A9?= Date: Wed, 15 Jun 2022 14:58:29 +0800 Subject: [PATCH] change tzdriver directory Signed-off-by: YuanHao --- BUILD.gn | 10 +- tzdriver/BUILD.gn | 56 - tzdriver/Kconfig | 6 - tzdriver/Makefile | 41 - tzdriver/include/agent.h | 139 -- tzdriver/include/cmdmonitor.h | 48 - tzdriver/include/gp_ops.h | 40 - tzdriver/include/mailbox_mempool.h | 65 - tzdriver/include/mem.h | 58 - tzdriver/include/security_auth_enhance.h | 47 - tzdriver/include/smc.h | 79 - tzdriver/include/tc_client_driver.h | 44 - tzdriver/include/tc_client_sub_driver.h | 92 -- tzdriver/include/tc_ns_client.h | 193 --- tzdriver/include/tc_ns_log.h | 83 - tzdriver/include/teek_client_api.h | 254 --- tzdriver/include/teek_client_constants.h | 175 --- tzdriver/include/teek_client_list.h | 180 --- tzdriver/include/teek_client_type.h | 206 --- tzdriver/include/teek_ns_client.h | 317 ---- tzdriver/include/tz_spi_notify.h | 39 - tzdriver/include/tzdebug.h | 57 - tzdriver/include/tzdriver.h | 38 - tzdriver/include/tzdriver_compat.h | 385 ----- tzdriver/src/agent.c | 1256 --------------- tzdriver/src/cmdmonitor.c | 337 ---- tzdriver/src/gp_ops.c | 1788 --------------------- tzdriver/src/mailbox_mempool.c | 568 ------- tzdriver/src/mem.c | 106 -- tzdriver/src/security_auth_enhance.c | 323 ---- tzdriver/src/smc_smp.c | 1622 ------------------- tzdriver/src/tc_client_driver.c | 1823 ---------------------- tzdriver/src/tc_client_sub_driver.c | 1131 -------------- tzdriver/src/teek_client_api.c | 765 --------- tzdriver/src/tz_spi_notify.c | 718 --------- tzdriver/src/tzdebug.c | 279 ---- tzdriver/src/tzdriver_compat.c | 262 ---- 37 files changed, 2 insertions(+), 13628 deletions(-) delete mode 100644 tzdriver/BUILD.gn delete mode 100644 tzdriver/Kconfig delete mode 100644 tzdriver/Makefile delete mode 100644 tzdriver/include/agent.h delete mode 100644 tzdriver/include/cmdmonitor.h delete mode 100644 tzdriver/include/gp_ops.h delete mode 100644 tzdriver/include/mailbox_mempool.h delete mode 100644 tzdriver/include/mem.h delete mode 100644 tzdriver/include/security_auth_enhance.h delete mode 100644 tzdriver/include/smc.h delete mode 100644 tzdriver/include/tc_client_driver.h delete mode 100644 tzdriver/include/tc_client_sub_driver.h delete mode 100644 tzdriver/include/tc_ns_client.h delete mode 100644 tzdriver/include/tc_ns_log.h delete mode 100644 tzdriver/include/teek_client_api.h delete mode 100644 tzdriver/include/teek_client_constants.h delete mode 100644 tzdriver/include/teek_client_list.h delete mode 100644 tzdriver/include/teek_client_type.h delete mode 100644 tzdriver/include/teek_ns_client.h delete mode 100644 tzdriver/include/tz_spi_notify.h delete mode 100644 tzdriver/include/tzdebug.h delete mode 100644 tzdriver/include/tzdriver.h delete mode 100644 tzdriver/include/tzdriver_compat.h delete mode 100644 tzdriver/src/agent.c delete mode 100644 tzdriver/src/cmdmonitor.c delete mode 100644 tzdriver/src/gp_ops.c delete mode 100644 tzdriver/src/mailbox_mempool.c delete mode 100644 tzdriver/src/mem.c delete mode 100644 tzdriver/src/security_auth_enhance.c delete mode 100644 tzdriver/src/smc_smp.c delete mode 100644 tzdriver/src/tc_client_driver.c delete mode 100644 tzdriver/src/tc_client_sub_driver.c delete mode 100644 tzdriver/src/teek_client_api.c delete mode 100644 tzdriver/src/tz_spi_notify.c delete mode 100644 tzdriver/src/tzdebug.c delete mode 100644 tzdriver/src/tzdriver_compat.c diff --git a/BUILD.gn b/BUILD.gn index c88a1b9..5bf9075 100644 --- a/BUILD.gn +++ b/BUILD.gn @@ -30,15 +30,9 @@ import("//kernel/liteos_a/liteos.gni") group("liteos") { - deps = [ - "hievent", - "tzdriver", - ] + deps = [ "hievent" ] } config("public") { - configs = [ - "hievent:public", - "tzdriver:public", - ] + configs = [ "hievent:public" ] } diff --git a/tzdriver/BUILD.gn b/tzdriver/BUILD.gn deleted file mode 100644 index dcb90ee..0000000 --- a/tzdriver/BUILD.gn +++ /dev/null @@ -1,56 +0,0 @@ -# Copyright (c) 2013-2019 Huawei Technologies Co., Ltd. All rights reserved. -# Copyright (c) 2020-2021 Huawei Device Co., Ltd. All rights reserved. -# -# Redistribution and use in source and binary forms, with or without modification, -# are permitted provided that the following conditions are met: -# -# 1. Redistributions of source code must retain the above copyright notice, this list of -# conditions and the following disclaimer. -# -# 2. Redistributions in binary form must reproduce the above copyright notice, this list -# of conditions and the following disclaimer in the documentation and/or other materials -# provided with the distribution. -# -# 3. Neither the name of the copyright holder nor the names of its contributors may be used -# to endorse or promote products derived from this software without specific prior written -# permission. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, -# THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR -# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, -# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, -# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; -# OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR -# OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF -# ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -import("//kernel/liteos_a/liteos.gni") - -module_switch = defined(LOSCFG_DRIVERS_TZDRIVER) -module_name = get_path_info(rebase_path("."), "name") -kernel_module(module_name) { - sources = [ - "src/agent.c", - "src/cmdmonitor.c", - "src/gp_ops.c", - "src/mailbox_mempool.c", - "src/mem.c", - "src/security_auth_enhance.c", - "src/smc_smp.c", - "src/tc_client_driver.c", - "src/tc_client_sub_driver.c", - "src/teek_client_api.c", - "src/tz_spi_notify.c", - "src/tzdebug.c", - "src/tzdriver_compat.c", - ] - - public_configs = [ ":public" ] -} - -config("public") { - include_dirs = [ "include" ] -} diff --git a/tzdriver/Kconfig b/tzdriver/Kconfig deleted file mode 100644 index 18688da..0000000 --- a/tzdriver/Kconfig +++ /dev/null @@ -1,6 +0,0 @@ -config DRIVERS_TZDRIVER - bool "Enable iTrustee tzdriver" - default n - depends on TEE_ENABLE - help - Enable iTrustee liteos tzdriver. diff --git a/tzdriver/Makefile b/tzdriver/Makefile deleted file mode 100644 index a79a2e7..0000000 --- a/tzdriver/Makefile +++ /dev/null @@ -1,41 +0,0 @@ -# Copyright (c) 2013-2019 Huawei Technologies Co., Ltd. All rights reserved. -# Copyright (c) 2020-2021 Huawei Device Co., Ltd. All rights reserved. -# -# Redistribution and use in source and binary forms, with or without modification, -# are permitted provided that the following conditions are met: -# -# 1. Redistributions of source code must retain the above copyright notice, this list of -# conditions and the following disclaimer. -# -# 2. Redistributions in binary form must reproduce the above copyright notice, this list -# of conditions and the following disclaimer in the documentation and/or other materials -# provided with the distribution. -# -# 3. Neither the name of the copyright holder nor the names of its contributors may be used -# to endorse or promote products derived from this software without specific prior written -# permission. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, -# THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR -# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, -# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, -# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; -# OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR -# OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF -# ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -include $(LITEOSTOPDIR)/config.mk -MODULE_NAME := $(notdir $(shell pwd)) - -LOCAL_SRCS := src/agent.c src/tzdebug.c src/security_auth_enhance.c src/mem.c \ - src/mailbox_mempool.c src/cmdmonitor.c src/teek_client_api.c src/tc_client_driver.c \ - src/tc_client_sub_driver.c src/gp_ops.c src/smc_smp.c src/tz_spi_notify.c src/tzdriver_compat.c \ - -LOCAL_INCLUDE := -I./include/ -I../../../third_party/mbedtls/include -I $(LITEOSTOPDIR)/../../$(LOSCFG_BOARD_CONFIG_PATH)/include - -LOCAL_FLAGS := $(LOCAL_INCLUDE) - -include $(MODULE) diff --git a/tzdriver/include/agent.h b/tzdriver/include/agent.h deleted file mode 100644 index 17025e7..0000000 --- a/tzdriver/include/agent.h +++ /dev/null @@ -1,139 +0,0 @@ -/* - * Copyright (c) 2013-2019 Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020-2021 Huawei Device Co., Ltd. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef AGENT_H -#define AGENT_H -#include "teek_ns_client.h" - -#define AGENT_FS_ID 0x46536673 /* FSfs */ -#define AGENT_MISC_ID 0x4d495343 /* MISC */ -#define TEE_RPMB_AGENT_ID 0x4abe6198 /* RPMB */ -#define AGENT_SOCKET_ID 0x69e85664 /* socket */ -#define SECFILE_LOAD_AGENT_ID 0x4c4f4144 /* SECFILE-LOAD-AGENT */ -#define TEE_SECE_AGENT_ID 0x53656345 /* test */ - -typedef enum { - AGENT_FALSE = -1, - AGENT_SUCCESS = 0, -} AgentErrCode; - -typedef enum { - AGENT_ALIVE = 1, - AGENT_DEAD = 0, -} AgentStatusCode; - -enum AgentStateType { - AGENT_CRASHED = 0, - AGENT_REGISTERED, - AGENT_READY, -}; - -struct SmcEventData *FindEventControl(unsigned int agentId); - -/* for secure agent */ -struct SmcEventData { - unsigned int agentId; - atomic_t agentReady; - wait_queue_head_t waitEventWq; - int retFlag; /* indicate whether agent is returned from TEE */ - wait_queue_head_t sendResponseWq; - struct list_head head; - TcNsSmcCmd cmd; - TcNsDevFile *owner; - void *agentBuffKernel; - void *agentBuffUser; /* used for unmap */ - unsigned int agentBuffSize; - atomic_t usage; -#ifdef CONFIG_TEE_SMP - wait_queue_head_t caPendingWq; - atomic_t caRun; /* indicate whether agent is allowed to return to TEE */ -#endif -}; - -struct TeeAgentKernelOps { - const char *agentName; /* MUST NOT be NULL */ - unsigned int agentId; /* MUST NOT be zero */ - int (*teeAgentInit)(struct TeeAgentKernelOps *agentInstance); - int (*teeAgentRun)(struct TeeAgentKernelOps *agentInstance); - /* MUST NOT be NULL */ - int (*teeAgentWork)(struct TeeAgentKernelOps *agentInstance); - int (*teeAgentStop)(struct TeeAgentKernelOps *agentInstance); - int (*teeAgentExit)(struct TeeAgentKernelOps *agentInstance); - int (*teeAgentCrashWork)( - struct TeeAgentKernelOps *agentInstance, - TcNsClientContext *context, - unsigned int devFileId); - LosTaskCB *agentThread; - void *agentData; - void *agentBuff; - unsigned int agentBuffSize; - struct list_head list; -}; - -static inline void GetAgentEvent(struct SmcEventData *eventData) -{ - if (eventData != NULL) { - atomic_inc(&eventData->usage); - } -} - -static inline void PutAgentEvent(struct SmcEventData *eventData) -{ - if (eventData != NULL) { - if (atomic_dec_and_test(&eventData->usage)) { - free(eventData); - } - } -} - -void AgentInit(void); -int AgentExit(void); -void SendEventResponse(unsigned int agentId); -int AgentProcessWork(const TcNsSmcCmd *smcCmd, unsigned int agentId); -int IsAgentAlive(unsigned int agentId); -int TcNsSetNativeHash(unsigned long arg, unsigned int cmdId); -int TcNsLateInit(unsigned long arg); -int TcNsRegisterAgent(TcNsDevFile *devFile, unsigned int agentId, - unsigned int bufferSize, void **buffer, bool userAgent); -int TcNsUnregisterAgent(unsigned int agentId); -void SendCrashedEventResponseAll(const TcNsDevFile *devFile); -int TcNsWaitEvent(unsigned int agentId); -int TcNsSendEventResponse(unsigned int agentId); -void SendEventResponseSingle(const TcNsDevFile *devFile); -int TcNsSyncSysTime(const TcNsClientTime *tcNsTime); -int TeeAgentClearWork(TcNsClientContext *context, - unsigned int devFileId); -int TeeAgentKernelRegister(struct TeeAgentKernelOps *newAgent); -bool IsSystemAgent(const TcNsDevFile *devFile); -void TeeAgentClearDevOwner(const TcNsDevFile *devFile); -extern int checkExtAgentAccess(LosTaskCB *caTask); - -#endif /* AGENT_H */ diff --git a/tzdriver/include/cmdmonitor.h b/tzdriver/include/cmdmonitor.h deleted file mode 100644 index 6ccaff9..0000000 --- a/tzdriver/include/cmdmonitor.h +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright (c) 2013-2019 Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020-2021 Huawei Device Co., Ltd. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "teek_ns_client.h" - -#ifndef _CMD_MONITOR_H_ -#define _CMD_MONITOR_H_ - -#define TEMPORALLY_CHAGE_TIMEOUT (25 * MSEC_PER_SEC) - -void CmdMonitorLog(const TcNsSmcCmd *cmd); -void CmdMonitorResetContext(void); -void CmdMonitorLogend(void); -void InitCmdMonitor(void); -void DoCmdNeedArchivelog(void); -bool IsThreadReported(unsigned int tid); -void TzDebugArchiveLog(void); -void CmdMonitorTaCrash(int32_t type); - -#endif diff --git a/tzdriver/include/gp_ops.h b/tzdriver/include/gp_ops.h deleted file mode 100644 index 729eee0..0000000 --- a/tzdriver/include/gp_ops.h +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Copyright (c) 2013-2019 Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020-2021 Huawei Device Co., Ltd. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef _GP_OPS_H_ -#define _GP_OPS_H_ -#include "tc_ns_client.h" -#include "teek_ns_client.h" - -int TcUserParamValid(TcNsClientContext *clientContext, unsigned int index); -int TcClientCall(TcNsClientContext *clientContext, - TcNsDevFile *devFile, TcNsSession *session, uint8_t flags); -#endif diff --git a/tzdriver/include/mailbox_mempool.h b/tzdriver/include/mailbox_mempool.h deleted file mode 100644 index 411e857..0000000 --- a/tzdriver/include/mailbox_mempool.h +++ /dev/null @@ -1,65 +0,0 @@ -/* - * Copyright (c) 2013-2019 Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020-2021 Huawei Device Co., Ltd. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef _MAILBOX_MEMPOOOL_H -#define _MAILBOX_MEMPOOOL_H - -#include -#include -#include "teek_ns_client.h" -#include "tzdriver_compat.h" - -#define MAILBOX_POOL_SIZE SZ_1M - -/* alloc options */ -#define MB_FLAG_ZERO 0x1 /* set 0 after alloc page */ -#define GLOBAL_UUID_LEN 17 /* first char represent global cmd */ - -struct MbCmdPack { - TcNsOperation operation; -#ifdef SECURITY_AUTH_ENHANCE - unsigned char loginData[MAX_SHA_256_SZ * NUM_OF_SO + HASH_PLAINTEXT_ALIGNED_SIZE + IV_BYTESIZE]; - unsigned char token[TOKEN_BUFFER_LEN]; - unsigned char secureParams[ALIGN_TZ(sizeof(struct SessionSecureParams), - CIPHER_BLOCK_BYTESIZE) + IV_BYTESIZE]; -#else - unsigned char loginData[MAX_SHA_256_SZ * NUM_OF_SO + MAX_SHA_256_SZ]; -#endif -}; - -void *MailboxAlloc(size_t size, unsigned int flag); -void MailboxFree(const void *ptr); -int MailboxMempoolInit(void); -void MailboxMempoolDestroy(void); -struct MbCmdPack *MailboxAllocCmdPack(void); -void *MailboxCopyAlloc(const void *src, size_t size); - -#endif diff --git a/tzdriver/include/mem.h b/tzdriver/include/mem.h deleted file mode 100644 index 96aec46..0000000 --- a/tzdriver/include/mem.h +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Copyright (c) 2013-2019 Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020-2021 Huawei Device Co., Ltd. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef _MEM_H_ -#define _MEM_H_ -#include -#include "teek_ns_client.h" - -int TcMemInit(void); -void TcMemDestroy(void); - -TcNsSharedMem *TcMemAllocate(size_t len); -void TcMemFree(TcNsSharedMem *sharedMem); - -static inline void GetSharememStruct(struct TagTcNsSharedMem *sharemem) -{ - if (sharemem != NULL) { - atomic_inc(&sharemem->usage); - } -} - -static inline void PutSharememStruct(struct TagTcNsSharedMem *sharemem) -{ - if (sharemem != NULL) { - if (atomic_dec_and_test(&sharemem->usage)) { - TcMemFree(sharemem); - } - } -} -#endif diff --git a/tzdriver/include/security_auth_enhance.h b/tzdriver/include/security_auth_enhance.h deleted file mode 100644 index c09734f..0000000 --- a/tzdriver/include/security_auth_enhance.h +++ /dev/null @@ -1,47 +0,0 @@ -/* - * Copyright (c) 2013-2019 Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020-2021 Huawei Device Co., Ltd. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef _SECURITY_AUTH_ENHANCE_H_ -#define _SECURITY_AUTH_ENHANCE_H_ -#include -#include "teek_ns_client.h" - -#define INC 0x01 -#define DEC 0x00 -#define UN_SYNCED 0x55 -#define IS_SYNCED 0xaa - -TeecResult UpdateTimestamp(const TcNsSmcCmd *cmd); -TeecResult UpdateChksum(TcNsSmcCmd *cmd); -TeecResult VerifyChksum(const TcNsSmcCmd *cmd); -TeecResult SyncTimestamp(const TcNsSmcCmd *cmd, uint8_t *token, - uint32_t tokenLen, bool global); -#endif diff --git a/tzdriver/include/smc.h b/tzdriver/include/smc.h deleted file mode 100644 index 76913fc..0000000 --- a/tzdriver/include/smc.h +++ /dev/null @@ -1,79 +0,0 @@ -/* - * Copyright (c) 2013-2019 Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020-2021 Huawei Device Co., Ltd. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef _SMC_H_ -#define _SMC_H_ - -#include "teek_client_constants.h" -#include "teek_ns_client.h" - -enum TcNsCmdType { - TC_NS_CMD_TYPE_INVALID = 0, - TC_NS_CMD_TYPE_NS_TO_SECURE, - TC_NS_CMD_TYPE_SECURE_TO_NS, - TC_NS_CMD_TYPE_SECURE_TO_SECURE, - TC_NS_CMD_TYPE_SECURE_CONFIG = 0xf, - TC_NS_CMD_TYPE_MAX -}; - -#ifdef CONFIG_TEE_SMP -struct PendingEntry { - atomic_t users; - pid_t pid; - wait_queue_head_t wq; - atomic_t run; - struct list_head list; -}; -#endif - -#define RESLEEP_TIMEOUT 15 - -struct SessionCryptoInfo *GetSessionRootKeyInstance(void); -int SigkillPending(LosTaskCB *tsk); -int SmcInitData(void); -void SmcFreeData(void); -int TcNsSmc(TcNsSmcCmd *cmd); -int TcNsSmcWithNoNr(TcNsSmcCmd *cmd); -void SetCmdSendState(void); -int InitSmcSvcThread(void); -int SmcWakeupCa(pid_t ca); -int SmcWakeupBroadcast(void); -int SmcShadowExit(pid_t ca); -int SmcQueueShadowWorker(uint64_t target); -void FiqShadowWorkFunc(uint64_t target); -struct PendingEntry *FindPendingEntry(pid_t pid); -void ForeachPendingEntry(void (*func)(struct PendingEntry *)); -void PutPendingEntry(struct PendingEntry *pe); -void ShowCmdBitmap(void); -void ShowCmdBitmapWithLock(void); -void WakeupTcSiq(void); - -#endif diff --git a/tzdriver/include/tc_client_driver.h b/tzdriver/include/tc_client_driver.h deleted file mode 100644 index cf2a03d..0000000 --- a/tzdriver/include/tc_client_driver.h +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Copyright (c) 2013-2019 Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020-2021 Huawei Device Co., Ltd. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef _TC_NS_CLIENT_DRIVER_H_ -#define _TC_NS_CLIENT_DRIVER_H_ - -#include -#include "teek_ns_client.h" - -mutex_t *GetServiceListLock(void); -struct TcNsDevList *GetTcNsDevList(void); -struct list_head *GetServiceList(void); -bool ScheduleWorkOn(int cpu, struct work_struct *work); -int TcNsLoadImage(TcNsDevFile *devFile, char *fileBuffer, unsigned int fileSize); -#endif - diff --git a/tzdriver/include/tc_client_sub_driver.h b/tzdriver/include/tc_client_sub_driver.h deleted file mode 100644 index a952466..0000000 --- a/tzdriver/include/tc_client_sub_driver.h +++ /dev/null @@ -1,92 +0,0 @@ -/* - * Copyright (c) 2013-2019 Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020-2021 Huawei Device Co., Ltd. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef _TC_NS_CLIENT_DRIVER_SUB_H_ -#define _TC_NS_CLIENT_DRIVER_SUB_H_ -#include -#include "tc_ns_client.h" -#include "teek_ns_client.h" - -#define CHECK_PATH_HASH_FAIL 0xff01 -#define CHECK_SECLABEL_FAIL 0xff02 -#define CHECK_CODE_HASH_FAIL 0xff03 -#define ENTER_BYPASS_CHANNEL 0xff04 -#define BUF_MAX_SIZE 1024 -#define MAX_PATH_SIZE 512 -#define SHA256_DIGEST_LENTH 32 - -char *GetProcessPath(LosTaskCB *task, char *tpath, int pathLen); -int CalcProcessPathHash(const unsigned char *data, - unsigned long dataLen, unsigned char *digest, unsigned int digLen); -int PackCaCert(char *caCert, const char *path, - LosTaskCB *caTask, int uid); -TcNsService *TcFindServiceInDev(TcNsDevFile *dev, - const unsigned char *uuid, int uuidSize); -TcNsService *TcRefServiceInDev(TcNsDevFile *dev, const unsigned char *uuid, - int uuidSize, bool *isFull); -TcNsService *TcFindServiceFromAll(const unsigned char *uuid, uint32_t uuidLen); -int AddServiceToDev(TcNsDevFile *dev, TcNsService *service); -void DelServiceFromDev(TcNsDevFile *dev, TcNsService *service); -TcNsSession *TcFindSessionWithOwner(struct list_head *sessionList, - unsigned int sessionId, TcNsDevFile *devFile); -void DumpServicesStatus(const char *param); -errno_t InitContext(TcNsClientContext *context, - const unsigned char *uuid, const unsigned int uuidLen); -#ifdef SECURITY_AUTH_ENHANCE -int GenerateRandomData(uint8_t *data, uint32_t size); -bool IsValidEncryptionHead(const struct EncryptionHead *head, const uint8_t *data, uint32_t len); -int GenerateChallengeWord(uint8_t *challengeWord, uint32_t size); -int SetEncryptionHead(struct EncryptionHead *head, uint32_t len); -TcNsSession *TcFindSession2(unsigned int devFileId, const TcNsSmcCmd *cmd); -void CleanSessionSecureInformation(TcNsSession *session); -int GetSessionSecureParams(TcNsDevFile *devFile, TcNsClientContext *context, TcNsSession *session); -#endif -int CloseSession(TcNsDevFile *dev, TcNsSession *session, const unsigned char *uuid, - unsigned int uuidLen, unsigned int sessionId); -void KillSession(TcNsDevFile *dev, const unsigned char *uuid, - unsigned int uuidLen, unsigned int sessionId); -int TcNsServiceInit(const unsigned char *uuid, uint32_t uuidLen, TcNsService **newService); -uint32_t TcNsGetUid(void); -int GetPackNameLen(TcNsDevFile *devFile, const uint8_t *certBuffer, - unsigned int certBufferSize); -int GetPublicKeyLen(TcNsDevFile *devFile, const uint8_t *certBuffer, - unsigned int certBufferSize); -bool IsValidTaSize(const char *fileBuffer, unsigned int fileSize); -int TcNsNeedLoadImage(unsigned int fileId, const unsigned char *uuid, - unsigned int uuidLen); -int LoadTaImage(TcNsDevFile *devFile, TcNsClientContext *context); -void ReleaseFreeSession(TcNsDevFile *devFile, TcNsClientContext *context, TcNsSession *session); -void CloseSessionInServiceList(TcNsDevFile *dev, TcNsService *service, uint32_t i); -void CloseUnclosedSession(TcNsDevFile *dev, uint32_t i); -void DelDevNode(TcNsDevFile *dev); -int NsClientCloseTeecdNotAgent(TcNsDevFile *dev); -int TcNsLoadSecfile(TcNsDevFile *devFile, const void __user *argp); -#endif diff --git a/tzdriver/include/tc_ns_client.h b/tzdriver/include/tc_ns_client.h deleted file mode 100644 index f8e27bd..0000000 --- a/tzdriver/include/tc_ns_client.h +++ /dev/null @@ -1,193 +0,0 @@ -/* - * Copyright (c) 2013-2019 Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020-2021 Huawei Device Co., Ltd. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef _TC_NS_CLIENT_H_ -#define _TC_NS_CLIENT_H_ - -#include -#include "teek_client_type.h" - -#ifdef SECURITY_AUTH_ENHANCE -#define SCRAMBLING_KEY_LEN 4 -#define TOKEN_BUFFER_LEN 42 /* token(32byte) + timestamp(8byte) + kernal_api(1byte) + sync(1byte) */ -#define TIMESTAMP_BUFFER_INDEX 32 -#define KERNAL_API_INDEX 40 -#define SYNC_INDEX 41 -#define UUID_LEN 16 -#define PARAM_NUM 4 -#define ADDR_TRANS_NUM 32 -#define TEE_PARAM_ONE 0 -#define TEE_PARAM_TWO 1 -#define TEE_PARAM_THREE 2 -#define TEE_PARAM_FOUR 3 - -#define TIMESTAMP_LEN_DEFAULT \ - ((KERNAL_API_INDEX) - (TIMESTAMP_BUFFER_INDEX)) -#define KERNAL_API_LEN \ - ((TOKEN_BUFFER_LEN) - (KERNAL_API_INDEX)) -#define TIMESTAMP_SAVE_INDEX 16 -#endif - -#ifndef ZERO_SIZE_PTR -#define ZERO_SIZE_PTR ((void *)16) -#define ZERO_OR_NULL_PTR(x) ((unsigned long)(x) <= (unsigned long)ZERO_SIZE_PTR) -#endif - -typedef struct { - unsigned int method; - unsigned int mdata; -} TcNsClientLogin; - -typedef union { - struct { - unsigned int buffer; - unsigned int bufferH; - unsigned int offset; - unsigned int offsetH; - unsigned int sizeAddr; - unsigned int sizeAddrH; - } memref; - struct { - unsigned int aAddr; - unsigned int aHaddr; - unsigned int bAddr; - unsigned int bHaddr; - } value; -} TcNsClientParam; - -typedef struct { - int code; - unsigned int origin; -} TcNsClientReturn; - -typedef struct { - unsigned char uuid[UUID_LEN]; - unsigned int sessionId; - unsigned int cmdId; - TcNsClientReturn returns; - TcNsClientLogin login; - TcNsClientParam params[PARAM_NUM]; - unsigned int paramTypes; - unsigned char started; -#ifdef SECURITY_AUTH_ENHANCE - void* teecToken; - unsigned int tokenLen; -#endif - unsigned int callingPid; - unsigned int fileSize; - union { - char *fileBuffer; - unsigned long long fileAddr; - }; -} TcNsClientContext; - -typedef struct { - unsigned int seconds; - unsigned int millis; -} TcNsClientTime; - -enum SecfileTypeT { - LOAD_TA = 0, - LOAD_SERVICE, - LOAD_LIB, -}; - -struct LoadSecfileIoctlStruct { - enum SecfileTypeT secfileType; - unsigned char uuid[UUID_LEN]; - unsigned int fileSize; - union { - char *fileBuffer; - unsigned long long file_addr; - }; -}; - -struct AgentIoctlArgs { - unsigned int id; - unsigned int bufferSize; - union { - void *buffer; - unsigned long long addr; - }; -}; - -#define TST_CMD_01 1 -#define TST_CMD_02 2 -#define TST_CMD_03 3 -#define TST_CMD_04 4 -#define TST_CMD_05 5 - -#define MAX_SHA_256_SZ 32 - -#define TC_NS_CLIENT_IOCTL_SES_OPEN_REQ \ - _IOW(TC_NS_CLIENT_IOC_MAGIC, 1, TcNsClientContext) -#define TC_NS_CLIENT_IOCTL_SES_CLOSE_REQ \ - _IOWR(TC_NS_CLIENT_IOC_MAGIC, 2, TcNsClientContext) -#define TC_NS_CLIENT_IOCTL_SEND_CMD_REQ \ - _IOWR(TC_NS_CLIENT_IOC_MAGIC, 3, TcNsClientContext) -#define TC_NS_CLIENT_IOCTL_SHRD_MEM_RELEASE \ - _IOWR(TC_NS_CLIENT_IOC_MAGIC, 4, unsigned int) -#define TC_NS_CLIENT_IOCTL_WAIT_EVENT \ - _IO(TC_NS_CLIENT_IOC_MAGIC, 5) -#define TC_NS_CLIENT_IOCTL_SEND_EVENT_RESPONSE \ - _IO(TC_NS_CLIENT_IOC_MAGIC, 6) -#define TC_NS_CLIENT_IOCTL_REGISTER_AGENT \ - _IOWR(TC_NS_CLIENT_IOC_MAGIC, 7, struct AgentIoctlArgs) -#define TC_NS_CLIENT_IOCTL_UNREGISTER_AGENT \ - _IO(TC_NS_CLIENT_IOC_MAGIC, 8) -#define TC_NS_CLIENT_IOCTL_LOAD_APP_REQ \ - _IOWR(TC_NS_CLIENT_IOC_MAGIC, 9, struct LoadSecfileIoctlStruct) -#define TC_NS_CLIENT_IOCTL_NEED_LOAD_APP \ - _IOWR(TC_NS_CLIENT_IOC_MAGIC, 10, TcNsClientContext) -#define TC_NS_CLIENT_IOCTL_ALLOC_EXCEPTING_MEM \ - _IOWR(TC_NS_CLIENT_IOC_MAGIC, 12, unsigned int) -#define TC_NS_CLIENT_IOCTL_CANCEL_CMD_REQ \ - _IOWR(TC_NS_CLIENT_IOC_MAGIC, 13, TcNsClientContext) -#define TC_NS_CLIENT_IOCTL_LOGIN \ - _IO(TC_NS_CLIENT_IOC_MAGIC, 14) -#define TC_NS_CLIENT_IOCTL_TST_CMD_REQ \ - _IOWR(TC_NS_CLIENT_IOC_MAGIC, 15, int) -#define TC_NS_CLIENT_IOCTL_TUI_EVENT \ - _IOWR(TC_NS_CLIENT_IOC_MAGIC, 16, int) -#define TC_NS_CLIENT_IOCTL_SYC_SYS_TIME \ - _IOWR(TC_NS_CLIENT_IOC_MAGIC, 17, TcNsClientTime) -#define TC_NS_CLIENT_IOCTL_SET_NATIVECA_IDENTITY \ - _IOWR(TC_NS_CLIENT_IOC_MAGIC, 18, int) -#define TC_NS_CLIENT_IOCTL_LOAD_TTF_FILE_AND_NOTCH_HEIGHT \ - _IOWR(TC_NS_CLIENT_IOC_MAGIC, 19, unsigned int) -#define TC_NS_CLIENT_IOCTL_LATEINIT \ - _IO(TC_NS_CLIENT_IOC_MAGIC, 20) -#define TC_NS_CLIENT_IOCTL_GET_TEE_VERSION \ - _IOWR(TC_NS_CLIENT_IOC_MAGIC, 21, unsigned int) -#define TC_NS_CLIENT_IOCTL_UNMAP_SHARED_MEM \ - _IOWR(TC_NS_CLIENT_IOC_MAGIC, 22, unsigned int) - -#endif diff --git a/tzdriver/include/tc_ns_log.h b/tzdriver/include/tc_ns_log.h deleted file mode 100644 index 4601182..0000000 --- a/tzdriver/include/tc_ns_log.h +++ /dev/null @@ -1,83 +0,0 @@ -/* - * Copyright (c) 2013-2019 Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020-2021 Huawei Device Co., Ltd. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef TC_NS_LOG_H_ -#define TC_NS_LOG_H_ - -#include -enum { - TZ_DEBUG_VERBOSE = 0, - TZ_DEBUG_DEBUG, - TZ_DEBUG_INFO, - TZ_DEBUG_WARN, - TZ_DEBUG_ERROR, -}; - -#ifdef DEF_ENG -#define TEE_ENG_LOG_MASK 2 -#define TEE_LOG_MASK TEE_ENG_LOG_MASK -#else -#define TEE_USR_LOG_MASK 3 -#define TEE_LOG_MASK TEE_USR_LOG_MASK -#endif - -#define tlogv(fmt, args...) \ -do { \ - if (TZ_DEBUG_VERBOSE >= TEE_LOG_MASK) \ - pr_info("(%i, %s)%s: " fmt, OsCurrTaskGet()->taskID, OsCurrTaskGet()->taskName, __func__, ## args); \ -} while (0) - - -#define tlogd(fmt, args...) \ -do { \ - if (TZ_DEBUG_DEBUG >= TEE_LOG_MASK) \ - pr_info("(%i, %s)%s: " fmt, OsCurrTaskGet()->taskID, OsCurrTaskGet()->taskName, __func__, ## args); \ -} while (0) - - -#define tlogi(fmt, args...) \ -do { \ - if (TZ_DEBUG_INFO >= TEE_LOG_MASK) \ - pr_info("(%i, %s)%s: " fmt, OsCurrTaskGet()->taskID, OsCurrTaskGet()->taskName, __func__, ## args); \ -} while (0) - - -#define tlogw(fmt, args...) \ -do { \ - if (TZ_DEBUG_WARN >= TEE_LOG_MASK) \ - pr_warn("(%i, %s)%s: " fmt, OsCurrTaskGet()->taskID, OsCurrTaskGet()->taskName, __func__, ## args); \ -} while (0) - - -#define tloge(fmt, args...) \ - pr_err("(%i, %s)%s: " fmt, OsCurrTaskGet()->taskID, OsCurrTaskGet()->taskName, __func__, ## args) - -#endif diff --git a/tzdriver/include/teek_client_api.h b/tzdriver/include/teek_client_api.h deleted file mode 100644 index de86d00..0000000 --- a/tzdriver/include/teek_client_api.h +++ /dev/null @@ -1,254 +0,0 @@ -/* - * Copyright (c) 2013-2019 Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020-2021 Huawei Device Co., Ltd. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -/* @defgroup TEEC_API client(REE) interface - * @defgroup TEEC_BASIC_FUNC common interface - * @ingroup TEEC_API - */ - -#ifndef _TEEK_CLIENT_API_H_ -#define _TEEK_CLIENT_API_H_ -#include "teek_client_type.h" -#include "teek_ns_client.h" - -/* - * @ingroup TEEC_BASIC_FUNC - * Calculate the values of the transfer parameters between REE and TEE - */ -#define TEEC_PARAM_TYPES(param0_type, param1_type, param2_type, param3_type) \ - (((param3_type) << 12) | ((param2_type) << 8) | \ - ((param1_type) << 4) | (param0_type)) - -/* - * @ingroup TEEC_BASIC_FUNC - * Get the index value in parmaTypes - */ -#define TEEC_PARAM_TYPE_GET(paramTypes, index) \ - (((paramTypes) >> ((index) << 2)) & 0x0F) - -/* - * @ingroup TEEC_BASIC_FUNC - * When the parameter type is #teec_value, if the member variable a or b is not assigned, - * you need to assign this value to it, indicates that this member variable is not used. - */ -#define TEEC_VALUE_UNDEF 0xFFFFFFFF - -/* - * Function: TeekIsAgentAlive - * Description: This function check if the special agent is launched. - * Used For HDCP key. - * e.g. If sfs agent is not alive, - * you can not do HDCP key write to SRAM. - * Parameters: agentId. - * Return: 1:agent is alive - * 0:agent not exsit. - */ -int TeekIsAgentAlive(unsigned int agentId); - -/* - * @ingroup TEEC_BASIC_FUNC - * @brief Initialize the TEE context - * - * @par Description - * Initialize the TEE context whose path is 'name'. The 'name' can be left empty, - * TEE initialization is the basis for opening a session and sending a command, - * after the initialization is successful, a connection is set up between the CA and the TEE. - * - * @param name [IN] Tee context path - * @param context [IN/OUT] context pointer,secure world environment handle - * - * @retval #TEEC_SUCCESS TEE context is successfully initialized - * @retval #TEEC_ERROR_BAD_PARAMETERS Parameter is incorrect, 'name' is incorrect or context is empty - * @retval #TEEC_ERROR_GENERIC System resources are insufficient - */ -TeecResult TeekInitializeContext(const char *name, TeecContext *context); - -/* - * @ingroup TEEC_BASIC_FUNC - * @brief Close the tee context - * - * @par Description - * Close the TEE context to which the 'context' points, and disconnect the client application from the TEE environment. - * - * @param context [IN/OUT] The TEE context that has been successfully initialized - * - */ -void TeekFinalizeContext(TeecContext *context); - -/* - * @ingroup TEEC_BASIC_FUNC - * @brief Open session - * - * @par Description - * Create a session which is from CA to the 'destination' UUID TA, - * the connection method is 'connectionMethod', and the link data is 'connectionData', - * The transferred data is contained in the 'opetation'. - * After a session is opened successfully, the output parameter 'session' is a description of the link. - * If the session fails to be opened, 'returnOrigin' is the error source. - * - * @param context [IN/OUT] The TEE context that has been successfully initialized - * @param session [OUT] Pointed to the session, the value cannot be empty - * @param destination [IN] UUID of a security service, a security service has a unique UUID. - * @param connectionMethod [IN] Connection mode. The value range is #TEEC_LoginMethod. - * @param connectionData [IN] Connection data corresponding to the connection mode - * If connection mode is #TEEC_LOGIN_PUBLIC, #TEEC_LOGIN_USE, - * #TEEC_LOGIN_USER_APPLICATION, #TEEC_LOGIN_GROUP_APPLICATION, connection data must be empty. - * If connection mode is #TEEC_LOGIN_GROUP、#TEEC_LOGIN_GROUP_APPLICATION, - * the connection data must point to data of type uint32_t, - * which represents the user group that the client application expects to connect to. - * @param operation [IN/OUT] Data transferred between CAs and TAs - * @param returnOrigin [IN/OUT] Error source. The value range is #TEEC_ReturnCodeOrigin. - * - * @retval #TEEC_SUCCESS Open successfully. - * @retval #TEEC_ERROR_BAD_PARAMETERS The parameter is incorrect. - * @retval #TEEC_ERROR_ACCESS_DENIED Failed to access the system call permission. - * @retval #TEEC_ERROR_OUT_OF_MEMORY Insufficient system resources. - * @retval #TEEC_ERROR_TRUSTED_APP_LOAD_ERROR Failed to load the security service. - * @retval Other return values, see. #TEEC_ReturnCode - */ -TeecResult TeekOpenSession(TeecContext *context, - TeecSession *session, - const TeecUuid *destination, - uint32_t connectionMethod, - const void *connectionData, - const TeecOperation *operation, - uint32_t *returnOrigin); - -/** - * @ingroup TEEC_BASIC_FUNC - * @brief Close session - * - * @par Description - * Close the session to which the 'session' points, and disconnect the client application from the security service. - * - * @param session [IN/OUT] Point to a session that has been opened successfully - */ -void TeekCloseSession(TeecSession *session); - -/** - * @ingroup TEEC_BASIC_FUNC - * @brief Send a command. - * - * @par Description - * In a specified 'session', the CA sends the 'commandID' command to the TA. - * The sent data is 'operation'. - * If the command fails to be sent, the 'returnOrigin' indicate the error source. - * - * @param session [IN/OUT] Pointing to a session that has been successfully opened - * @param commandID [IN] Command ID supported by the security service, which is defined by the security service. - * @param operation [IN/OUT] Contains the data sent from the CA to the TA. - * @param returnOrigin [IN/OUT] Error source. The value range is #TEEC_ReturnCodeOrigin. - * - * @retval #TEEC_SUCCESS Command sent successfully. - * @retval #TEEC_ERROR_BAD_PARAMETERS The parameter is incorrect, - * the session parameter is empty or the operation parameter is in an incorrect format. - * @retval #TEEC_ERROR_ACCESS_DENIED Failed to access the system call permission. - * @retval #TEEC_ERROR_OUT_OF_MEMORY Insufficient system resources. - * @retval other return values, see. #TEEC_ReturnCode - */ -TeecResult TeekInvokeCommand(TeecSession *session, - uint32_t commandID, - TeecOperation *operation, - uint32_t *returnOrigin); - -/** - * @ingroup TEEC_BASIC_FUNC - * @brief Register the Shared Memory - * - * @par Description - * Registers the shared memory 'sharedMem' in the specified TEE 'context', - * the operating system needs to support zero copy to obtain the shared memory through registration, - * in the current implementation, zero copy cannot be implemented in this mode. - * - * @attention If the size field of the input parameter 'sharedMem' is set to 0, - * the function returns a success message, but this field cannot be used.Shared memory, - * because this memory has no size - * @param context [IN/OUT] TEE environment that has been successfully initialized - * @param sharedMem [IN/OUT] Pointer to the shared memory, the memory cannot be null or 0. - * - * @retval #TEEC_SUCCESS Command sent successfully. - * @retval #TEEC_ERROR_BAD_PARAMETERS The parameter is incorrect. The context or sharedMem parameter is empty, - * or the memory to which the shared memory points is empty. - */ -TeecResult TeekRegisterSharedMemory(TeecContext *context, - TeecSharedMemory *sharedMem); - -/** - * @ingroup TEEC_BASIC_FUNC - * @brief Apply for Shared Memory - * - * @par Description - * Apply for the shared memory 'sharedMem' in the specified TEE 'context', - * The shared memory can implement zero copy when data is transferred - * between the non-secure world and the secure world. - * - * @attention If the size field of the input parameter 'sharedMem' is set to 0, - * the function returns a success message, but this Shared memory field cannot be used, - * because this memory has neither address nor size. - * @param context [IN/OUT] TEE environment that has been successfully initialized - * @param sharedMem [IN/OUT] Pointer to the shared memory. The size of the shared memory cannot be 0. - * - * @retval #TEEC_SUCCESS Command sent successfully. - * @retval #TEEC_ERROR_BAD_PARAMETERS The parameter is incorrect. The context or sharedMem parameter is empty. - * @retval #TEEC_ERROR_OUT_OF_MEMORY Allocation failed due to insufficient system resources. - */ -TeecResult TeekAllocateSharedMemory(TeecContext *context, - TeecSharedMemory *sharedMem); - -/** - * @ingroup TEEC_BASIC_FUNC - * @brief Release the shared memory. - * - * @par Description - * Releases the shared memory that has been registered or applied for. - * - * @attention If the shared memory is obtained in #TEEK_AllocateSharedMemory mode, When the memory is released, - * the memory is reclaimed. If the #TEEK_RegisterSharedMemory method is used, - * The local memory to which the shared memory points is not reclaimed when the shared memory is released. - * @param sharedMem [IN/OUT] Point to the shared memory that has been registered or applied for successfully - */ -void TeekReleaseSharedMemory(TeecSharedMemory *sharedMem); - -/** - * @ingroup TEEC_BASIC_FUNC - * @brief cancel API - * - * @par Description - * Cancel a running open session or an invoke command. - * Send a cancel signal and return immediately. - * - * @attention This operation only sends a cancel message, - * whether to perform the cancel operation is determined by the TEE or TA. - * @param operation [IN/OUT] Contains the data sent from the CA to the TA. - */ -void TeekRequestCancellation(TeecOperation *operation); - -#endif diff --git a/tzdriver/include/teek_client_constants.h b/tzdriver/include/teek_client_constants.h deleted file mode 100644 index 93a2a7d..0000000 --- a/tzdriver/include/teek_client_constants.h +++ /dev/null @@ -1,175 +0,0 @@ -/* - * Copyright (c) 2013-2019 Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020-2021 Huawei Device Co., Ltd. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include - -#ifndef _TEEK_CLIENT_CONSTANTS_H_ -#define _TEEK_CLIENT_CONSTANTS_H_ - -enum GlobalServiceCmdId { - GLOBAL_CMD_ID_INVALID = 0x0, - GLOBAL_CMD_ID_BOOT_ACK = 0x1, - GLOBAL_CMD_ID_OPEN_SESSION = 0x2, - GLOBAL_CMD_ID_CLOSE_SESSION = 0x3, - /* Global Task dynamically load secure applications */ - GLOBAL_CMD_ID_LOAD_SECURE_APP = 0x4, - /* Global Task determine whether to load a secure application */ - GLOBAL_CMD_ID_NEED_LOAD_APP = 0x5, - GLOBAL_CMD_ID_REGISTER_AGENT = 0x6, - GLOBAL_CMD_ID_UNREGISTER_AGENT = 0x7, - GLOBAL_CMD_ID_REGISTER_NOTIFY_MEMORY = 0x8, - GLOBAL_CMD_ID_UNREGISTER_NOTIFY_MEMORY = 0x9, - GLOBAL_CMD_ID_INIT_CONTENT_PATH = 0xa, /* Global Task init content path */ - /* Global Task free content path */ - GLOBAL_CMD_ID_TERMINATE_CONTENT_PATH = 0xb, - GLOBAL_CMD_ID_ALLOC_EXCEPTION_MEM = 0xc, - GLOBAL_CMD_ID_TEE_TIME = 0xd, - GLOBAL_CMD_ID_TEE_INFO = 0xe, - GLOBAL_CMD_ID_REGISTER_RDR_MEM = 0xf, - GLOBAL_CMD_ID_KILL_TASK = 0x10, /* Global Task Kill session */ - GLOBAL_CMD_ID_ADJUST_TIME = 0x12, /* TIME adjust */ - GLOBAL_CMD_ID_SET_CA_HASH = 0x13, /* set ca hash info */ - GLOBAL_CMD_ID_SET_BUILD_VERSION = 0x14, /* set the build version */ - /* get session key for encrypting dialog */ - GLOBAL_CMD_ID_GET_SESSION_SECURE_PARAMS = 0x16, - GLOBAL_CMD_ID_REGISTER_MAILBOX = 0x17, - GLOBAL_CMD_ID_DUMP_MEMINFO = 0x1a, - - /* this cmd will be used to service no ca handle cmd */ - GLOBAL_CMD_ID_SET_SERVE_CMD = 0x1b, - GLOBAL_CMD_ID_ADD_DYNAMIC_ION = 0x1c, - GLOBAL_CMD_ID_DEL_DYNAMIC_ION = 0x1d, - GLOBAL_CMD_ID_LOAD_SECURE_APP_ION = 0x1e, - GLOBAL_CMD_ID_LATE_INIT = 0x20, - GLOBAL_CMD_ID_GET_TEE_VERSION = 0x22, - GLOBAL_CMD_ID_UNKNOWN = 0x7FFFFFFE, - GLOBAL_CMD_ID_MAX = 0x7FFFFFFF -}; - -// Return Codes -enum TeecResult { - TEEC_SUCCESS = 0x0, - TEEC_ERROR_INVALID_CMD = 0x1, - TEEC_ERROR_SERVICE_NOT_EXIST = 0x2, - TEEC_ERROR_SESSION_NOT_EXIST = 0x3, - TEEC_ERROR_SESSION_MAXIMUM, /* security service session is full */ - TEEC_ERROR_REGISTER_EXIST_SERVICE, /* register exist service */ - TEEC_ERROR_TAGET_DEAD_FATAL, /* security service Global error,(Global is the basic of all services) */ - TEEC_ERROR_READ_DATA, /* read file fail */ - TEEC_ERROR_WRITE_DATA, /* write file fail */ - TEEC_ERROR_TRUNCATE_OBJECT, /* trancate file fail */ - TEEC_ERROR_SEEK_DATA, /* seek file fail */ - TEEC_ERROR_RENAME_OBJECT, /* renme file fail */ - TEEC_ERROR_TRUSTED_APP_LOAD_ERROR, /* load security app fail */ - TEEC_ERROR_GENERIC = 0xFFFF0000, - TEEC_ERROR_ACCESS_DENIED = 0xFFFF0001, - TEEC_ERROR_CANCEL = 0xFFFF0002, - TEEC_ERROR_ACCESS_CONFLICT = 0xFFFF0003, - TEEC_ERROR_EXCESS_DATA = 0xFFFF0004, - TEEC_ERROR_BAD_FORMAT = 0xFFFF0005, - TEEC_ERROR_BAD_PARAMETERS = 0xFFFF0006, - TEEC_ERROR_BAD_STATE = 0xFFFF0007, - TEEC_ERROR_ITEM_NOT_FOUND = 0xFFFF0008, - TEEC_ERROR_NOT_IMPLEMENTED = 0xFFFF0009, - TEEC_ERROR_NOT_SUPPORTED = 0xFFFF000A, - TEEC_ERROR_NO_DATA = 0xFFFF000B, - TEEC_ERROR_OUT_OF_MEMORY = 0xFFFF000C, - TEEC_ERROR_BUSY = 0xFFFF000D, - TEEC_ERROR_COMMUNICATION = 0xFFFF000E, - TEEC_ERROR_SECURITY = 0xFFFF000F, - TEEC_ERROR_SHORT_BUFFER = 0xFFFF0010, - TEEC_PENDING = 0xFFFF2000, - TEEC_PENDING2 = 0xFFFF2001, - TEE_ERROR_TAGET_DEAD = 0xFFFF3024, - TEE_ERROR_GT_DEAD = 0xFFFF3124, - TEEC_ERROR_MAC_INVALID = 0xFFFF3071, - TEEC_CLIENT_INTR = 0xFFFF4000, - TEEC_ERROR_CA_AUTH_FAIL = 0xFFFFCFE5, - TEE_ERROR_AUDIT_FAIL = 0xFFFF9112, -}; - -// Return Code Origins -enum TEEC_ReturnCodeOrigin { - TEEC_ORIGIN_API = 0x1, - TEEC_ORIGIN_COMMS = 0x2, - TEEC_ORIGIN_TEE = 0x3, - TEEC_ORIGIN_TRUSTED_APP = 0x4, - TEEC_ORIGIN_TRUSTED_APP_TUI = 0x5, -}; - -// Shared Memory Control -enum TEEC_SharedMemCtl { - TEEC_MEM_INPUT = 0x1, - TEEC_MEM_OUTPUT = 0x2, - TEEC_MEM_INOUT = 0x3, -}; - -// API Parameter Types -enum TEEC_ParamType { - TEEC_NONE = 0x0, - TEEC_VALUE_INPUT = 0x01, - TEEC_VALUE_OUTPUT = 0x02, - TEEC_VALUE_INOUT = 0x03, - TEEC_MEMREF_TEMP_INPUT = 0x05, - TEEC_MEMREF_TEMP_OUTPUT = 0x06, - TEEC_MEMREF_TEMP_INOUT = 0x07, - TEEC_ION_INPUT = 0x08, - TEEC_ION_SGLIST_INPUT = 0x09, - TEEC_MEMREF_WHOLE = 0xc, - TEEC_MEMREF_PARTIAL_INPUT = 0xd, - TEEC_MEMREF_PARTIAL_OUTPUT = 0xe, - TEEC_MEMREF_PARTIAL_INOUT = 0xf -}; - -enum TEE_ParamType { - TEE_PARAM_TYPE_NONE = 0x0, - TEE_PARAM_TYPE_VALUE_INPUT = 0x1, - TEE_PARAM_TYPE_VALUE_OUTPUT = 0x2, - TEE_PARAM_TYPE_VALUE_INOUT = 0x3, - TEE_PARAM_TYPE_MEMREF_INPUT = 0x5, - TEE_PARAM_TYPE_MEMREF_OUTPUT = 0x6, - TEE_PARAM_TYPE_MEMREF_INOUT = 0x7, - TEE_PARAM_TYPE_ION_INPUT = 0x8, - TEE_PARAM_TYPE_ION_SGLIST_INPUT = 0x9, -}; - -// Session Login Methods -enum TEEC_LoginMethod { - TEEC_LOGIN_PUBLIC = 0x0, - TEEC_LOGIN_USER, - TEEC_LOGIN_GROUP, - TEEC_LOGIN_APPLICATION = 0x4, - TEEC_LOGIN_USER_APPLICATION = 0x5, - TEEC_LOGIN_GROUP_APPLICATION = 0x6, - TEEC_LOGIN_IDENTIFY = 0x7, -}; - -#endif diff --git a/tzdriver/include/teek_client_list.h b/tzdriver/include/teek_client_list.h deleted file mode 100644 index 0ff927b..0000000 --- a/tzdriver/include/teek_client_list.h +++ /dev/null @@ -1,180 +0,0 @@ -/* - * Copyright (c) 2013-2019 Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020-2021 Huawei Device Co., Ltd. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include - -#ifndef _TEE_CLIENT_LIST_H_ -#define _TEE_CLIENT_LIST_H_ -/* - * @ingroup TEEC_List - * Linked list type - */ -struct ListNode { - struct ListNode *next; - struct ListNode *prev; -}; - -#define TEEK_INIT_LIST_HEAD(list) do { \ - (list)->next = (list); \ - (list)->prev = (list); \ -} while (0) - -#define LIST_FOR_EACH(node, list) for ((node) = (list)->next; (node) != (list); (node) = (node)->next) - -/* - * @ingroup TEEC_List - * @brief Define a linked list node. - * @par Description - * Defines a linked list node and initializes it. - * @param name [IN] linked list node name - */ -#define LIST_DECLARE(name) \ - struct ListNode (name) = { \ - .next = &(name), \ - .prev = &(name), \ - } - -#ifndef NULL -#define NULL 0 -#endif - -/* - * @ingroup TEEC_List - * Obtains the prev node of the linked list. - */ -#define LIST_TAIL(list) ((list)->prev) - -/* - * @ingroup TEEC_List - * Check whether the linked list is empty. - */ -#define LIST_EMPTY(list) ((list) == (list)->next) - -/* - * @ingroup TEEC_List - * @brief Inserts a new node from the head of a linked list. - * - * @par Description - * Inserts a new node from the head of a linked list - * - * @param list [IN/OUT]Pointer to the linked list header, the value cannot be empty. - * @param entry [IN/OUT]Pointer to the new linked list node, the value cannot be empty. - */ -static inline void ListInsertHead(struct ListNode *list, - struct ListNode *entry) -{ - list->next->prev = entry; - entry->next = list->next; - entry->prev = list; - list->next = entry; -} - -/* - * @ingroup TEEC_List - * @brief Inserts a new node at the end of the linked list. - * - * @par Description - * Inserts a new node at the end of the linked list. - * - * @param list [IN/OUT]Pointer to the linked list header, the value cannot be empty. - * @param entry [IN/OUT]Pointer to the new linked list node, the value cannot be empty. - */ -static inline void ListInsertTail(struct ListNode *list, - struct ListNode *entry) -{ - entry->next = list; - entry->prev = list->prev; - list->prev->next = entry; - list->prev = entry; -} - -/* - * @ingroup TEEC_List - * @brief Delete node - * - * @par Description - * Deletes a specified node. - * - * @attention Release the memory of the node to be deleted. - * @param entry [IN]Pointer to the linked list node to be deleted. The value cannot be null. - */ -static inline void ListRemove(struct ListNode *entry) -{ - entry->prev->next = entry->next; - entry->next->prev = entry->prev; -} - -/* - * @ingroup TEEC_List - * @brief Delete the head node of the linked list. - * - * @par Description - * Deletes the head node of a specified linked list. - * - * @attention After return, the memory of the deleted node should be release. - * @param list [IN]Pointer to the linked list header, the value cannot be empty. - * - * @retval #NULL The linked list is empty. - * @retval not #NULL Linked list header node - */ -static inline struct ListNode *ListRemoveHead(struct ListNode *list) -{ - struct ListNode *entry = NULL; - if (!LIST_EMPTY(list)) { - entry = list->next; - ListRemove(entry); - } - return entry; -} - -/* - * @ingroup TEEC_List - * @brief Delete the tail node of the linked list. - * - * @par Description - * Delete the tail node of the linked list. - * - * @attention After return, the memory of the deleted node should be release. - * @param list [IN]Pointer to the linked list header, the value cannot be empty. - * - * @retval NULL The linked list is empty. - * @retval not #NULL Linked list header node - */ -static inline struct ListNode *ListRemoveTail(struct ListNode *list) -{ - struct ListNode *entry = NULL; - if (!LIST_EMPTY(list)) { - entry = list->prev; - ListRemove(entry); - } - return entry; -} -#endif diff --git a/tzdriver/include/teek_client_type.h b/tzdriver/include/teek_client_type.h deleted file mode 100644 index d47ca9e..0000000 --- a/tzdriver/include/teek_client_type.h +++ /dev/null @@ -1,206 +0,0 @@ -/* - * Copyright (c) 2013-2019 Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020-2021 Huawei Device Co., Ltd. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef _TEE_CLIENT_TYPE_H_ -#define _TEE_CLIENT_TYPE_H_ -#define SECURITY_AUTH_ENHANCE -#include "teek_client_constants.h" -#include "teek_client_list.h" -#define TOKEN_SAVE_LEN 24 -#define CLOCK_NODE_LEN 8 -#define TEE_PARAM_NUM 4 - -/* - * @ingroup teec_common_data - * define NULL - */ -#ifndef NULL -#define NULL 0 -#endif - -/* - * @ingroup teec_common_data - * Function return value type - */ -typedef uint32_t TeecResult; - -/* - * @ingroup teec_common_data - * uuid type def - * - * uuid type follow rfc4122 [2],is used to identify the security service. - */ -typedef struct { - /* Lower 4 bytes of the timestamp */ - uint32_t timeLow; - /* Middle 2 bytes of the timestamp */ - uint16_t timeMid; - /* Combination of higher 2 bytes of the timestamp and version */ - uint16_t timeHiAndVersion; - /* Combination of clock sequence and node identifier */ - uint8_t clockseqAndNode[CLOCK_NODE_LEN]; -} TeecUuid; - -/* - * @ingroup teec_common_data - * teec_context struct definition - * - * Describes the connect context between client applications and the secure world. - */ -typedef struct { - void *dev; - uint8_t *ta_path; - /* session list */ - struct ListNode sessionList; - /* shared memory list */ - struct ListNode shrdMemList; -} TeecContext; - -/* - * @ingroup teec_common_data - * teec_session - * - * Describes the sessions established between CAs and the TEE. - */ -typedef struct { - /* Session ID, which is returned by the TEE. */ - uint32_t sessionId; - /* Indicates the UUID of a security service. Each TA has a unique UUID. */ - TeecUuid serviceId; - /* Number of operations in a session. */ - uint32_t opsCnt; - /* Session linked list header */ - struct ListNode head; - /* Point to the Tee context to which the session belongs */ - TeecContext *context; -#ifdef SECURITY_AUTH_ENHANCE - /* token_save_len 24byte = token 16byte + timestamp 8byte */ - uint8_t teecToken[TOKEN_SAVE_LEN]; -#endif -} TeecSession; - -/* - * @ingroup teec_common_data - * teec_sharedmemory - * - * Describes a piece of shared memory that can be registered or allocated. - */ -typedef struct { - /* Memory pointer */ - void *buffer; - /* Memory Size */ - size_t size; - /* Memory flags which is used to distinguish between input and output, range is as follows:#teec_sharedmemctl */ - uint32_t flags; - /* Number of memory operations */ - uint32_t opsCnt; - /* Memory allocation identifier, which is used to identify whether the memory is registered or allocated. */ - bool isAllocated; - /* Linked list header of the shared memory */ - struct ListNode head; - /* The Tee context to which the object belongs. */ - TeecContext *context; -} TeecSharedMemory; - -/* - * @ingroup teec_common_data - * teec_tempmemory_reference - * - * A temporary buffer is used for #teec_parameter, corresponding to which can be - * #teec_memref_temp_input, #teec_memref_temp_output,or #teec_memref_temp_inout - */ -typedef struct { - /* temporary buffer pointer */ - void *buffer; - /* temporary buffer size */ - size_t size; -} TeecTempmemoryReference; - -/* - * @ingroup teec_common_data - * teec_registeredmemory_reference - * - * Indicates the pointer of the shared memory, which points to the registered or allocated shared memory. - * The type that can be used for #teec_parameter, corresponding to which can be - * #teec_memref_whole, #teec_memref_partial_input, - * #teec_memref_partial_output,or #teec_memref_partial_inout - */ -typedef struct { - /* shared memory pointer */ - TeecSharedMemory *parent; - /* shared memory size */ - size_t size; - /* shared memory offset */ - size_t offset; -} TeecRegisteredmemoryReference; - -/* - * @ingroup teec_common_data - * teec_value - * - * Describe a small amount of data - * The type that can be used for #teec_parameter, corresponding to which can be - * #teec_value_input, #teec_value_output, or #teec_value_inout - */ -typedef struct { - uint32_t a; - uint32_t b; -} TeecValue; - -/* - * @ingroup teec_common_data - * teec_parameter - * - * Parameter type corresponding to #teec_operation. - */ -typedef union { - TeecTempmemoryReference tmpref; - TeecRegisteredmemoryReference memref; - TeecValue value; -} TeecParameter; - -/* - * @ingroup teec_common_data - * teec_operation - * - * Parameters used for opening a session or sending a command, - * can also be used to cancel an operation - */ -typedef struct { - /* Indicates whether the operation is canceled. 0 indicates canceled. */ - uint32_t started; - uint32_t paramTypes; - TeecParameter params[TEE_PARAM_NUM]; - TeecSession *session; - bool cancelFlag; -} TeecOperation; - -#endif diff --git a/tzdriver/include/teek_ns_client.h b/tzdriver/include/teek_ns_client.h deleted file mode 100644 index 6cc8621..0000000 --- a/tzdriver/include/teek_ns_client.h +++ /dev/null @@ -1,317 +0,0 @@ -/* - * Copyright (c) 2013-2019 Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020-2021 Huawei Device Co., Ltd. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef _TEEK_NS_CLIENT_H_ -#define _TEEK_NS_CLIENT_H_ - -#include -#include -#include -#include "tc_ns_client.h" -#include "tc_ns_log.h" -#include "tzdriver_compat.h" - -#define TC_NS_CLIENT_IOC_MAGIC 't' -#define TC_NS_CLIENT_DEV "tc_ns_client" -#define TC_NS_CLIENT_DEV_NAME "/dev/tc_ns_client" - -#ifdef CONFIG_SECURE_EXTENSION -#define TC_ASYNC_NOTIFY_SUPPORT -#endif - -#define EXCEPTION_MEM_SIZE (8*1024) /* mem for exception handling */ -#define TSP_REQUEST 0xB2000008 -#define TSP_RESPONSE 0xB2000009 -#define TSP_REE_SIQ 0xB200000A -#define TSP_CRASH 0xB200000B -#define TSP_PREEMPTED 0xB2000005 -#define TC_CALL_GLOBAL 0x01 -#define TC_CALL_SYNC 0x02 -#define TC_CALL_LOGIN 0x04 -#define TEE_REQ_FROM_USER_MODE 0x0 -#define TEE_REQ_FROM_KERNEL_MODE 0x1 - -/* Max sizes for login info buffer comming from teecd */ -#define MAX_PACKAGE_NAME_LEN 255 -/* The application certificate format is as follows: - * modulus_size(4 bytes) + modulus buffer(512 bytes) - * + exponent size(4 bytes) + exponent buffer(1 bytes) - */ -#define MAX_PUBKEY_LEN 1024 - -struct TagTcNsSharedMem; -struct TagTcNsService; - -struct TcNsDevList { - mutex_t devLock; /* for devFileList */ - struct list_head devFileList; -}; - -#define SERVICES_MAX_COUNT 32 /* service limit can opened on 1 fd */ -typedef struct TagTcNsDevFile { - unsigned int devFileId; - mutex_t serviceLock; /* for serviceRef[], services[] */ - uint8_t serviceRef[SERVICES_MAX_COUNT]; /* a judge if set services[i]=NULL */ - struct TagTcNsService *services[SERVICES_MAX_COUNT]; - mutex_t sharedMemLock; /* for sharedMemList */ - struct list_head sharedMemList; - struct list_head head; - /* Device is linked to call from kernel */ - uint8_t kernelApi; - /* client login info provided by teecd, can be either package name and public - * key or uid(for non services/daemons) - * login information can only be set once, dont' allow subsequent calls - */ - bool loginSetup; - mutex_t LoginSetupLock; /* for loginSetup */ - uint32_t pkgNameLen; - uint8_t PkgName[MAX_PACKAGE_NAME_LEN]; - uint32_t pubKeyLen; - uint8_t pubKey[MAX_PUBKEY_LEN]; - int loadAppFlag; -} TcNsDevFile; - -typedef union { - struct { - unsigned int buffer; - unsigned int size; - } memref; - struct { - unsigned int a; - unsigned int b; - } value; -} TcNsParameter; - -typedef struct TagTcNsLogin { - unsigned int method; - unsigned int mdata; -} tc_ns_login; - -typedef struct TagTcNsOperation { - unsigned int paramTypes; - TcNsParameter params[TEE_PARAM_NUM]; - unsigned int bufferHaddr[TEE_PARAM_NUM]; - struct TagTcNsSharedMem *sharemem[TEE_PARAM_NUM]; - void *mbBuffer[TEE_PARAM_NUM]; -} TcNsOperation; - -typedef struct TagTcNsTempBuf { - void *tempBuffer; - unsigned int size; -} TcNsTempBuf; - -typedef struct TagTcNsSmcCmd { - uint8_t uuid[sizeof(TeecUuid)]; - bool globalCmd; /* mark it's a gtask cmd */ - unsigned int cmdId; - unsigned int devFileId; - unsigned int contextId; - unsigned int agentId; - unsigned int operationPhys; - unsigned int operationHphys; - unsigned int loginMethod; - unsigned int loginDataPhy; - unsigned int loginDataHaddr; - unsigned int loginDataLen; - unsigned int errOrigin; - int retVal; - unsigned int eventNr; - unsigned int uid; -#ifdef CONFIG_TEE_SMP - unsigned int caPid; -#endif -#ifdef SECURITY_AUTH_ENHANCE - unsigned int tokenPhys; - unsigned int tokenHphys; - unsigned int pid; - unsigned int paramsPhys; - unsigned int paramsHphys; - unsigned int eventindex; // tee audit event index for upload -#endif - bool started; -}__attribute__((__packed__))TcNsSmcCmd; - -typedef struct TagTcNsSharedMem { - void *kernelAddr; - void *userAddr; - void *userAddrCa; /* for ca alloc share mem */ - unsigned int len; - struct list_head head; - atomic_t usage; - atomic_t offset; -} TcNsSharedMem; - -typedef struct TagTcNsService { - unsigned char uuid[UUID_LEN]; - mutex_t SessionLock; /* for sessionList */ - struct list_head sessionList; - struct list_head head; - mutex_t operationLock; /* for session's open/close */ - atomic_t usage; -} TcNsService; - -/* - * @brief - */ -struct TcWaitData { - wait_queue_head_t sendCmdWq; - int sendWaitFlag; -}; - -#ifdef SECURITY_AUTH_ENHANCE -/* Using AES-CBC algorithm to encrypt communication between secure world and - * normal world. - */ -#define CIPHER_KEY_BYTESIZE 32 /* AES-256 key size */ -#define IV_BYTESIZE 16 /* AES-CBC encryption initialization vector size */ -#define CIPHER_BLOCK_BYTESIZE 16 /* AES-CBC cipher block size */ -#define SCRAMBLING_NUMBER 3 -#define CHKSUM_LENGTH (sizeof(TcNsSmcCmd) - sizeof(uint32_t)) - -#define HASH_PLAINTEXT_SIZE (MAX_SHA_256_SZ + sizeof(struct EncryptionHead)) -#define HASH_PLAINTEXT_ALIGNED_SIZE \ - ALIGN_TZ(HASH_PLAINTEXT_SIZE, CIPHER_BLOCK_BYTESIZE) - -enum SCRAMBLING_ID { - SCRAMBLING_TOKEN = 0, - SCRAMBLING_OPERATION = 1, - SCRAMBLING_MAX = SCRAMBLING_NUMBER -}; - -struct SessionCryptoInfo { - uint8_t key[CIPHER_KEY_BYTESIZE]; /* AES-256 key */ - uint8_t iv[IV_BYTESIZE]; /* AES-CBC encryption initialization vector */ -}; - -struct SessionSecureInfo { - uint32_t challengeWord; - uint32_t scrambling[SCRAMBLING_NUMBER]; - struct SessionCryptoInfo cryptoInfo; -}; - -#define MAGIC_SIZE 16 -#define MAGIC_STRING "Trusted-magic" - -/* One encrypted block, which is aligned with CIPHER_BLOCK_BYTESIZE bytes - * Head + Payload + Padding - */ -struct EncryptionHead { - int8_t magic[MAGIC_SIZE]; - uint32_t payloadLen; -}; - -struct SessionSecureParams { - struct EncryptionHead head; - union { - struct { - uint32_t challengeWord; - } ree2tee; - struct { - uint32_t scrambling[SCRAMBLING_NUMBER]; - struct SessionCryptoInfo cryptoInfo; - } tee2ree; - } payload; -}; -#endif - -#ifdef SECURITY_AUTH_ENHANCE -typedef struct TagTcNsToken { - /* 42byte, token_32byte + timestamp_8byte + kernal_api_1byte + sync_1byte */ - uint8_t *tokenBuffer; - uint32_t tokenLen; -} TcNsToken; -#endif - -#define NUM_OF_SO 1 -#define KIND_OF_SO 2 -typedef struct TagTcNsSession { - unsigned int sessionId; - struct list_head head; - struct TcWaitData waitData; - mutex_t taSessionLock; /* for open/close/invoke on 1 session */ - TcNsDevFile *owner; -#ifdef SECURITY_AUTH_ENHANCE - /* Session secure enhanced information */ - struct SessionSecureInfo secureInfo; - TcNsToken TcNsToken; - /* when SECURITY_AUTH_ENHANCE enabled, hash of the same CA and - * SO library will be encrypted by different session key, - * so put authHashBuf in TcNsSession. - * the first MAX_SHA_256_SZ size stores SO hash, - * the next HASH_PLAINTEXT_ALIGNED_SIZE stores CA hash and cryptohead, - * the last IV_BYTESIZE size stores aes iv - */ - uint8_t authHashBuf[MAX_SHA_256_SZ * NUM_OF_SO + HASH_PLAINTEXT_ALIGNED_SIZE + IV_BYTESIZE]; -#else - uint8_t authHashBuf[MAX_SHA_256_SZ * NUM_OF_SO + MAX_SHA_256_SZ]; -#endif - atomic_t usage; -} TcNsSession; - -void GetServiceStruct(struct TagTcNsService *service); -void PutServiceStruct(struct TagTcNsService *service); - -static inline void GetSessionStruct(struct TagTcNsSession *session) -{ - if (session != NULL) { - atomic_inc(&session->usage); - } -} - -void PutSessionStruct(struct TagTcNsSession *session); - -TcNsSession *TcFindSessionWithOwner(struct list_head *sessionList, - unsigned int sessionId, TcNsDevFile *dev); - -#ifdef SECURITY_AUTH_ENHANCE -int GenerateEncryptedSessionSecureParams( - const struct SessionSecureInfo *secureInfo, - uint8_t *encSecureParams, size_t encParamsSize); -#define ENCRYPT 1 -#define DECRYPT 0 - -int CryptoSessionAescbcKey256(uint8_t *in, uint32_t inLen, - uint8_t *out, uint32_t out_len, - const uint8_t *key, uint8_t *iv, - uint32_t mode); -int CryptoAescbcCmsPadding(uint8_t *plaintext, uint32_t plaintextLen, - uint32_t payloadLen); -#endif - -int TcNsClientOpen(TcNsDevFile **devFile, uint8_t kernelApi); -int TcNsClientClose(TcNsDevFile *dev); -int IsAgentAlive(unsigned int agentId); -int TcNsOpenSession(TcNsDevFile *devFile, TcNsClientContext *context); -int TcNsCloseSession(TcNsDevFile *devFile, TcNsClientContext *context); -int TcNsSendCmd(TcNsDevFile *devFile, TcNsClientContext *context); -uint32_t TcNsGetUid(void); - -#endif diff --git a/tzdriver/include/tz_spi_notify.h b/tzdriver/include/tz_spi_notify.h deleted file mode 100644 index 7ebd45d..0000000 --- a/tzdriver/include/tz_spi_notify.h +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Copyright (c) 2013-2019 Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020-2021 Huawei Device Co., Ltd. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef _TZ_SPI_NOTIFY_H_ -#define _TZ_SPI_NOTIFY_H_ -#include "teek_ns_client.h" - -int TzSpiInit(void); -void TzSpiExit(void); -int TcNsTstCmd(TcNsDevFile *devId, void *argp); -#endif diff --git a/tzdriver/include/tzdebug.h b/tzdriver/include/tzdebug.h deleted file mode 100644 index cc47497..0000000 --- a/tzdriver/include/tzdebug.h +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Copyright (c) 2013-2019 Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020-2021 Huawei Device Co., Ltd. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef _TZDEBUG_H_ -#define _TZDEBUG_H_ - -#include -struct ta_mem { - char taName[16]; - uint32_t pmem; - uint32_t pmemMax; - uint32_t pmemLimit; -}; - -#define MEMINFO_TA_MAX 100 -struct TeeMem { - uint32_t totalMem; - uint32_t pmem; - uint32_t freeMem; - uint32_t freeMemMin; - uint32_t taNum; - struct ta_mem TaMemInfo[MEMINFO_TA_MAX]; -}; - -int GetTeeMeminfo(struct TeeMem *meminfo); -void TeeDumpMem(void); -int TzdebugInit(void); - -#endif diff --git a/tzdriver/include/tzdriver.h b/tzdriver/include/tzdriver.h deleted file mode 100644 index d9bb071..0000000 --- a/tzdriver/include/tzdriver.h +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Copyright (c) 2013-2019 Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020-2021 Huawei Device Co., Ltd. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef _TZDRIVER_H -#define _TZDRIVER_H - -int TcInit(void); -void SetVmmRegionCodeStart(UINTPTR codeStart, UINT32 codeSize); - -#endif diff --git a/tzdriver/include/tzdriver_compat.h b/tzdriver/include/tzdriver_compat.h deleted file mode 100644 index 41b811b..0000000 --- a/tzdriver/include/tzdriver_compat.h +++ /dev/null @@ -1,385 +0,0 @@ -/* - * Copyright (c) 2013-2019 Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020-2021 Huawei Device Co., Ltd. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef __TZDRIVER_COMPAT_H -#define __TZDRIVER_COMPAT_H - -#include -#include -#include -#include "arm.h" -#include "fs/driver.h" -#include "hisoc/random.h" -#include "los_process_pri.h" -#include "los_sched_pri.h" -#include "los_task_pri.h" -#include "los_vm_lock.h" -#include "los_vm_map.h" -#include "los_vm_phys.h" -#include "mbedtls/sha256.h" - -/* TEE config */ -#define DEF_ENG 1 -#define CONFIG_TEE_SMP 1 -#define CONFIG_TEELOG 1 -#define CONFIG_CPU_AFF_NR 0 -#define CONFIG_TEE_SMP 1 -/* TEE config end */ - -#define VERIFY_READ 0 -#define VERIFY_WRITE 1 -#define MAX_DEV_NAME_SIZE 32 -#define SHA256_DIGEST_LENGTH 32 -#define ALIGN_TZ(x, boundary) (((x) + ((boundary) - 1)) & ~((boundary) - 1)) - -#ifndef ARRAY_SIZE -#define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0])) -#endif - -typedef pthread_mutex_t mutex_t; - -#ifndef IS_ERR_OR_NULL -#ifndef IS_ERR_VALUE -#define IS_ERR_VALUE(x) unlikely((unsigned long)(void *)(x) >= (unsigned long) - 4095) -#endif -#define IS_ERR_OR_NULL(x) ((!x) || IS_ERR_VALUE((UINTPTR)x)) -#endif - -#define TEE_DEV_PRI 0660 - -#define TASK_COMM_LEN OS_TCB_NAME_LEN - -#define WQ_HIGHPRI (1 << 4) -#define IRQF_NO_SUSPEND 0x00004000 -#define __GFP_ZERO 0x8000u - -#define SZ_4K 0x1000UL -#define SZ_1M (1024 * 1024) -#define SZ_4M (4 * SZ_1M) -#define SZ_8M (8 * SZ_1M) - -#define MAX_POW_TWO(n) \ -( \ -((n) >> 31) ? 31 : ((n) >> 30) ? 30 : \ -((n) >> 29) ? 29 : ((n) >> 28) ? 28 : \ -((n) >> 27) ? 27 : ((n) >> 26) ? 26 : \ -((n) >> 25) ? 25 : ((n) >> 25) ? 25 : \ -((n) >> 23) ? 23 : ((n) >> 22) ? 22 : \ -((n) >> 21) ? 21 : ((n) >> 20) ? 20 : \ -((n) >> 19) ? 19 : ((n) >> 18) ? 18 : \ -((n) >> 17) ? 17 : ((n) >> 16) ? 16 : \ -((n) >> 15) ? 15 : ((n) >> 14) ? 14 : \ -((n) >> 13) ? 13 : ((n) >> 12) ? 12 : \ -((n) >> 11) ? 11 : ((n) >> 10) ? 10 : \ -((n) >> 9) ? 9: ((n) >> 8) ? 8 : \ -((n) >> 7) ? 7: ((n) >> 6) ? 6 : \ -((n) >> 5) ? 5: ((n) >> 4) ? 4 : \ -((n) >> 3) ? 3: ((n) >> 2) ? 2 : 1) - -#define GET_ORDER(n) \ -( \ - n <= PAGE_SIZE ? 0 : (MAX_POW_TWO(n - 1) - PAGE_SHIFT + 1) \ -) - -#ifndef MSEC_PER_SEC -#define MSEC_PER_SEC 1000 -#endif - -#ifndef NSEC_PER_MSEC -#define NSEC_PER_MSEC 1000000L -#endif - -#ifndef USEC_PER_SEC -#define USEC_PER_SEC 1000000L -#endif - -#ifndef NSEC_PER_USEC -#define NSEC_PER_USEC 1000 -#endif - -#define CRASH_RET_EXIT 0 -#define CRASH_RET_TA 1 -#define CRASH_RET_IP 2 - -#undef DIV_ROUND_UP -#define DIV_ROUND_UP(n, d) (((n) + (d)-1) / (d)) -#undef BITS_PER_BYTE -#define BITS_PER_BYTE 8 -#undef BITS_PER_LONG -#define BITS_PER_LONG 64 -#undef BITS_TO_LONGS -#define BITS_TO_LONGS(nr) DIV_ROUND_UP(nr, BITS_PER_BYTE * sizeof(uint64_t)) -#undef BIT_MASK -#define BIT_MASK(nr) (1UL << ((nr) % BITS_PER_LONG)) -#undef BIT_WORD -#define BIT_WORD(nr) ((nr) / BITS_PER_LONG) -#undef DECLARE_BITMAP -#define DECLARE_BITMAP(name, bits) uint64_t name[BITS_TO_LONGS(bits)] - -#define INIT_WORK_ONSTACK(_work, _func) \ -do { \ - INIT_WORK(_work, _func); \ -} while (0) - -bool ScheduleWorkOn(int cpu, struct work_struct *work); - -#define __WORK_INIT(n, f) { \ - .data = 0, \ - .entry = { &(n).entry, &(n).entry }, \ - .func = f \ -} -#define DECLARE_WORK(work, func) \ - struct work_struct work = __WORK_INIT(work, func); - -#define noinline __attribute__((noinline)) - -LosTaskCB *KthreadRun(int (*threadfn)(UINTPTR data, int dataLen), void *data, int len, char *name); -void KthreadStop(const LosTaskCB *k); -int KthreadShouldStop(void); -INT32 DoVmallocRemap(LosVmMapRegion *vma, void *kvaddr); -int RemapVmallocRange(LosVmMapRegion *vma, void *addr, unsigned long pgoff); -int CreateTcClientDevice(const char *devName, const struct file_operations_vfs *op); -ssize_t SimpleReadFromBuffer(void *to, size_t count, const void *from, size_t available); -LosVmPage *MailboxPoolAllocPages(unsigned int order); -void MailboxPoolFreePages(LosVmPage *pageArray, size_t order); - -struct AesParam { - unsigned char *iv; - const unsigned char *key; - int size; - unsigned int encryptoType; -}; - -int CryptoAescbcKey256(unsigned char *output, const unsigned char *input, struct AesParam *param); - -#define INT_SIZE 4 - -static inline struct workqueue_struct *AllocOrderedWorkqueue(const char *fmt, unsigned int flags) -{ - return create_workqueue((char *)fmt); -} - -static inline int AccessOk(int type, unsigned long ptr, unsigned int size) -{ - if (ptr + size < ptr) { - return false; - } - return LOS_IsUserAddress(ptr + size); -} - -static inline int GetTaskUid(LosTaskCB *task) -{ -#ifdef LOSCFG_SECURITY_CAPABILITY - return (int)OsProcessUserIDGet(task); -#else - return 0; -#endif -} - -static inline int DevmRequestIrq(unsigned int irq, irq_handler_t handler, - unsigned long irqflags, const char *devname, void *devId) -{ - return request_irq(irq, handler, irqflags, devname, NULL); -} - -static inline void *GetPhyPage(void) -{ - LosVmPage *page = LOS_PhysPageAlloc(); - if (page == NULL) { - return NULL; - } - return OsVmPageToVaddr(page); -} - -static inline void FreePhyPage(void *ptr) -{ - if (ptr == NULL) { - return; - } - LosVmPage *page = OsVmVaddrToPage(ptr); - if (page != NULL) { - LOS_PhysPageFree(page); - } -} - -static inline void KthreadBindMask(LosTaskCB *p, UINT16 mask) -{ - if (p == NULL) { - return; - } - LOS_TaskCpuAffiSet(p->taskID, mask); -} - -static inline void HmSetBit(int nr, volatile uint64_t *addr) -{ - if (addr == NULL) { - return; - } - uint64_t mask = BIT_MASK(nr); - uint64_t *p = ((uint64_t *)addr) + BIT_WORD(nr); - *p |= mask; -} - -static inline void HmClearBit(int nr, volatile uint64_t *addr) -{ - if (addr == NULL) { - return; - } - - uint64_t mask = BIT_MASK(nr); - uint64_t *p = ((uint64_t *)addr) + BIT_WORD(nr); - *p &= ~mask; -} - -static inline int HmTestBit(int nr, const volatile uint64_t *addr) -{ - if (addr == NULL) { - return 0; - } - - return 1UL & (addr[BIT_WORD(nr)] >> (nr & (BITS_PER_LONG - 1))); -} - -static inline void PreemptDisable(void) -{ - UINT32 intSave = LOS_IntLock(); - OsSchedLock(); - LOS_IntRestore(intSave); -} - -static inline void PreemptEnable(void) -{ - UINT32 intSave = LOS_IntLock(); - OsSchedUnlock(); - LOS_IntRestore(intSave); -} - -static inline int CmpXchg(unsigned int *lock, int old, int new) -{ - return LOS_AtomicCmpXchg32bits((Atomic *)lock, new, old); -} - -static inline int RawSmpProcessorId(void) -{ - return ArchCurrCpuid(); -} - -static inline int WakeUpProcess(LosTaskCB *p) -{ - LOS_TaskYield(); - return 0; -} - -static inline void GetRandomBytesArch(void *data, uint32_t size) -{ - HiRandomHwGetNumber((char *)data, size); -} - -static inline void GetUser(unsigned int *value, const unsigned int *userPtr) -{ - copy_from_user(value, userPtr, sizeof(unsigned int)); -} - -static inline int GetCurrentPid(void) -{ - return OsCurrTaskGet()->processID; -} - -/* unsupport restart syscall */ -static inline int RestartSyscall(void) -{ - return 0; -} - -static inline LosTaskCB *GetProcessGroupLeader(LosTaskCB *task) -{ - if (task == NULL) { - return NULL; - } - return OS_TCB_FROM_TID(OsProcessThreadGroupIDGet(task)); -} - -static inline unsigned long MsecsToJiffies(const unsigned int m) -{ - if ((int)m < 0) { - return 0; - } - - return (m + (MSEC_PER_SEC / HZ) - 1) / (MSEC_PER_SEC / HZ); -} - -static inline struct timespec CurrentKernelTime(void) -{ - struct timespec ts; - clock_gettime(CLOCK_MONOTONIC_RAW, &ts); - return ts; -} - -static inline void InitDeferrableWork(struct delayed_work *w, void(* wq)(struct work_struct *)) -{ - INIT_DELAYED_WORK(w, wq); -} - -static inline int IsKernelThread(LosTaskCB *task) -{ - if (task == NULL) { - return true; - } - return !(OsProcessIsUserMode(OS_PCB_FROM_PID(task->processID))); -} - -static inline int IsTeecdProcess(LosTaskCB *teecd, LosTaskCB *task) -{ - if (teecd == NULL || task == NULL) { - return 0; - } - return teecd->processID == task->processID; -} - -typedef mbedtls_sha256_context TeeSha256Context; - -static inline void TeeSha256Init(TeeSha256Context *ctx) -{ - mbedtls_sha256_init(ctx); - (void)mbedtls_sha256_starts_ret(ctx, 0); -} - -static inline void TeeSha256Update(TeeSha256Context *ctx, const unsigned char *input, size_t ilen) -{ - (void)mbedtls_sha256_update_ret(ctx, input, ilen); -} - -static inline void TeeSha256Final(TeeSha256Context *ctx, unsigned char output[32]) -{ - (void)mbedtls_sha256_finish_ret(ctx, output); -} - -#endif diff --git a/tzdriver/src/agent.c b/tzdriver/src/agent.c deleted file mode 100644 index eebcaee..0000000 --- a/tzdriver/src/agent.c +++ /dev/null @@ -1,1256 +0,0 @@ -/* - * Copyright (c) 2013-2019 Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020-2021 Huawei Device Co., Ltd. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "agent.h" -#include -#include "cmdmonitor.h" -#include "mailbox_mempool.h" -#include "smc.h" -#include "tc_client_sub_driver.h" -#include "tc_ns_log.h" -#include "teek_client_constants.h" -#include "tzdriver_compat.h" - -#define HASH_FILE_MAX_SIZE (16 * 1024) -#define AGENT_BUFF_SIZE (4 * 1024) -#define AGENT_MAX 32 -#define MAX_PATH_SIZE 512 -#define PAGE_ORDER_RATIO 2 - -/* kernel agent, TeeAgentKernelOps list */ -static struct list_head g_teeAgentList; - -struct AgentControl { - spinlock_t lock; - struct list_head agentList; /* SmcEventData list */ -}; -static struct AgentControl g_agentControl; - -typedef struct TagCaInfo { - char path[MAX_PATH_SIZE]; - uint32_t uid; - uint32_t agentId; -} CaInfo; - -static CaInfo g_allowedExtAgentCa[] = { - /* just for test in ENG version */ -#ifdef DEF_ENG - { - "/vendor/bin/tee_test_agent", - 0, - TEE_SECE_AGENT_ID, - }, - -#endif -}; - -static int IsAllowedAgentCa(const CaInfo *ca, bool checkAgentIdFlag) -{ - uint32_t i; - bool tmpCheckStatus = false; - CaInfo *tmpCa = g_allowedExtAgentCa; - - if (!checkAgentIdFlag) { - for (i = 0; i < ARRAY_SIZE(g_allowedExtAgentCa); i++) { - if ((memcmp(ca->path, tmpCa->path, MAX_PATH_SIZE) == EOK) && - (ca->uid == tmpCa->uid)) { - return AGENT_SUCCESS; - } - tmpCa++; - } - } else { - for (i = 0; i < ARRAY_SIZE(g_allowedExtAgentCa); i++) { - tmpCheckStatus = ((memcmp(ca->path, tmpCa->path, MAX_PATH_SIZE) == EOK) && - (ca->uid == tmpCa->uid) && (ca->agentId == tmpCa->agentId)); - if (tmpCheckStatus) { - return AGENT_SUCCESS; - } - tmpCa++; - } - } - tlogd("ca-uid is %u, ca_path is %s, agent id is %x\n", ca->uid, ca->path, ca->agentId); - return AGENT_FALSE; -} - -static int GetCaPathAndUid(LosTaskCB *caTask, CaInfo *ca) -{ - char *path = NULL; - int messageSize; - int ret = -1; - char *tPath = NULL; - - tPath = malloc(MAX_PATH_SIZE); - if (ZERO_OR_NULL_PTR((unsigned long)(uintptr_t)tPath)) { - tloge("tPath malloc fail\n"); - return -EPERM; - } - - path = GetProcessPath(caTask, tPath, MAX_PATH_SIZE); - if (IS_ERR_OR_NULL(path)) { - ret = -ENOMEM; - tloge("get process path failed\n"); - goto END; - } - - messageSize = snprintf_s(ca->path, MAX_PATH_SIZE - 1, MAX_PATH_SIZE - 1, "%s", path); - ca->uid = GetTaskUid(caTask); - if (ca->uid < 0) { - free(tPath); - tPath = NULL; - return -EPERM; - } - tlogd("caTask->comm is %s, path is %s, ca uid is %u\n", caTask->taskName, path, ca->uid); - - if (messageSize > 0) { - ret = 0; - } - -END: - free(tPath); - tPath = NULL; - return ret; -} - -int CheckExtAgentAccess(LosTaskCB *caTask) -{ - int ret; - CaInfo agentCa = { {0}, 0 }; - - if (caTask == NULL) { - tloge("caTask is NULL.\n"); - return -EPERM; - } - - ret = GetCaPathAndUid(caTask, &agentCa); - if (ret) { - tloge("get cp path or uid failed.\n"); - return ret; - } - - ret = IsAllowedAgentCa(&agentCa, 0); - return ret; -} - -int CheckExtAgentAccessWithAgentId(LosTaskCB *caTask, - uint32_t agentId) -{ - int ret; - CaInfo agentCa = {"", 0, 0}; - - if (caTask == NULL) { - tloge("caTask is NULL\n"); - return -EPERM; - } - - ret = GetCaPathAndUid(caTask, &agentCa); - if (ret) { - tloge("get cp path or uid failed\n"); - return ret; - } - agentCa.agentId = agentId; - ret = IsAllowedAgentCa(&agentCa, 1); - return ret; -} - -static int CheckNativeHashParam(uint8_t *inBuf, uint32_t *bufLen) -{ - if (inBuf == NULL) { - return AGENT_FALSE; - } - if (TcNsGetUid() != 0) { - tloge("It is a fake tee agent\n"); - return -EACCES; - } - if (copy_from_user(bufLen, inBuf, sizeof(*bufLen))) { - tloge("copy from user failed\n"); - return -EFAULT; - } - if (*bufLen > HASH_FILE_MAX_SIZE) { - tloge("ERROR: file size[0x%x] too big\n", *bufLen); - return AGENT_FALSE; - } - return 0; -} - -int TcNsSetNativeHash(unsigned long arg, unsigned int cmdId) -{ - int ret; - TcNsSmcCmd smcCmd = { {0}, 0 }; - uint8_t *inBuf = (uint8_t *)(uintptr_t)arg; - uint32_t bufLen = 0; - uint8_t *bufToTee = NULL; - struct MbCmdPack *mbPack = NULL; - - ret = CheckNativeHashParam(inBuf, &bufLen); - if (ret) { - return ret; - } - - bufToTee = MailboxAlloc(bufLen, 0); - if (bufToTee == NULL) { - tloge("failed to alloc memory!\n"); - return AGENT_FALSE; - } - if (copy_from_user(bufToTee, inBuf, bufLen)) { - tloge("copy from user failed\n"); - MailboxFree(bufToTee); - return -EFAULT; - } - mbPack = MailboxAllocCmdPack(); - if (mbPack == NULL) { - tloge("alloc cmd pack failed\n"); - MailboxFree(bufToTee); - return -ENOMEM; - } - mbPack->operation.paramTypes = TEE_PARAM_TYPE_VALUE_INPUT | - (TEE_PARAM_TYPE_VALUE_INPUT << TEE_PARAM_NUM); - mbPack->operation.params[TEE_PARAM_ONE].value.a = - (unsigned int)LOS_PaddrQuery(bufToTee); - mbPack->operation.params[TEE_PARAM_ONE].value.b = 0; - mbPack->operation.params[TEE_PARAM_TWO].value.a = bufLen; - smcCmd.globalCmd = true; - smcCmd.cmdId = cmdId; - smcCmd.operationPhys = LOS_PaddrQuery(&mbPack->operation); - smcCmd.operationHphys = 0; - ret = TcNsSmc(&smcCmd); - MailboxFree(bufToTee); - MailboxFree(mbPack); - bufToTee = NULL; - mbPack = NULL; - return ret; -} - -int TcNsLateInit(unsigned long arg) -{ - int ret; - TcNsSmcCmd smcCmd = { {0}, 0 }; - uint32_t index = (uint32_t)arg; // index is uint32, no truncate risk - struct MbCmdPack *mbPack = NULL; - - if (TcNsGetUid() != 0) { - tloge("It is a fake tee agent\n"); - return -EACCES; - } - - mbPack = MailboxAllocCmdPack(); - if (mbPack == NULL) { - tloge("alloc cmd pack failed\n"); - return -ENOMEM; - } - - mbPack->operation.paramTypes = TEE_PARAM_TYPE_VALUE_INPUT; - mbPack->operation.params[TEE_PARAM_ONE].value.a = index; - - smcCmd.globalCmd = true; - smcCmd.cmdId = GLOBAL_CMD_ID_LATE_INIT; - smcCmd.operationPhys = LOS_PaddrQuery(&mbPack->operation); - smcCmd.operationHphys = 0; - - ret = TcNsSmc(&smcCmd); - - MailboxFree(mbPack); - mbPack = NULL; - - return ret; -} - -void SendEventResponseSingle(const TcNsDevFile *devFile) -{ - struct SmcEventData *eventData = NULL; - struct SmcEventData *tmp = NULL; - unsigned long flags; - unsigned int agentId = 0; - - if (devFile == NULL) { - return; - } - - spin_lock_irqsave(&g_agentControl.lock, flags); - list_for_each_entry_safe(eventData, tmp, &g_agentControl.agentList, head) { - if (eventData->owner == devFile) { - agentId = eventData->agentId; - break; - } - } - spin_unlock_irqrestore(&g_agentControl.lock, flags); - SendEventResponse(agentId); - return; -} - -struct SmcEventData *FindEventControl(unsigned int agentId) -{ - struct SmcEventData *eventData = NULL; - struct SmcEventData *tmpData = NULL; - unsigned long flags; - - spin_lock_irqsave(&g_agentControl.lock, flags); - list_for_each_entry(eventData, &g_agentControl.agentList, head) { - if (eventData->agentId == agentId) { - tmpData = eventData; - GetAgentEvent(eventData); - break; - } - } - spin_unlock_irqrestore(&g_agentControl.lock, flags); - - return tmpData; -} - -static void UnmapAgentBuffer(struct SmcEventData *eventData) -{ - if (eventData == NULL) { - tloge("event data is NULL\n"); - return; - } - - if (IS_ERR_OR_NULL(eventData->agentBuffUser)) { - return; - } - - if (LOS_UnMMap((VADDR_T)eventData->agentBuffUser, eventData->agentBuffSize) != 0) { - tloge("unmap failed\n"); - } - - eventData->agentBuffUser = NULL; -} - -static void FreeEventControl(unsigned int agentId) -{ - struct SmcEventData *eventData = NULL; - struct SmcEventData *tmpEvent = NULL; - unsigned long flags; - bool find = false; - - spin_lock_irqsave(&g_agentControl.lock, flags); - list_for_each_entry_safe(eventData, tmpEvent, &g_agentControl.agentList, head) { - if (eventData->agentId == agentId) { - list_del(&eventData->head); - find = true; - break; - } - } - spin_unlock_irqrestore(&g_agentControl.lock, flags); - - if (find) { - UnmapAgentBuffer(eventData); - - MailboxFree(eventData->agentBuffKernel); - eventData->agentBuffKernel = NULL; - PutAgentEvent(eventData); - } -} - -static int InitAgentContext(unsigned int agentId, - const TcNsSmcCmd *smcCmd, - struct SmcEventData **eventData) -{ - if (eventData == NULL) { - return TEEC_ERROR_GENERIC; - } - *eventData = FindEventControl(agentId); - if (*eventData == NULL) { - tloge("agent %u not exist\n", agentId); - return TEEC_ERROR_GENERIC; - } - tlogd("AgentProcessWork(0x%x): returning client command", agentId); - -#ifndef CONFIG_TEE_SMP - /* Keep a copy of the SMC cmd to return to TEE when the work is done */ - if (memcpy_s(&((*eventData)->cmd), sizeof((*eventData)->cmd), smcCmd, sizeof(*smcCmd))) { - tloge("failed to memcpy_s smcCmd\n"); - PutAgentEvent(*eventData); - return TEEC_ERROR_GENERIC; - } - ISB; - DSB; -#endif - return TEEC_SUCCESS; -} - -static int WaitAgentResponse(struct SmcEventData *eventData) -{ - int ret = TEEC_SUCCESS; - bool answered = true; - - do { - answered = true; - int r = wait_event_interruptible_timeout(eventData->caPendingWq, - atomic_read(&eventData->caRun), (long)(RESLEEP_TIMEOUT * HZ)); - if (r != 0) { - continue; - } - /* if no kill signal, just resleep before agent wake */ - if (SigkillPending(OsCurrTaskGet()) == 0) { - answered = false; - } else { - tloge("CA is killed, no need to wait agent response\n"); - eventData->retFlag = 0; - ret = TEEC_ERROR_GENERIC; - } - } while (!answered); - - return ret; -} - -int AgentProcessWork(const TcNsSmcCmd *smcCmd, unsigned int agentId) -{ - struct SmcEventData *eventData = NULL; - int ret = 0; - - if (smcCmd == NULL) { - tloge("smcCmd is null\n"); - return TEEC_ERROR_GENERIC; - } - if (InitAgentContext(agentId, smcCmd, &eventData) != TEEC_SUCCESS) { - return TEEC_ERROR_GENERIC; - } - -#ifdef CONFIG_TEE_SMP - if (atomic_read(&eventData->agentReady) == AGENT_CRASHED) { - tloge("agent 0x%x is killed and restarting\n", agentId); - PutAgentEvent(eventData); - return TEEC_ERROR_GENERIC; - } - eventData->retFlag = 1; - /* Wake up the agent that will process the command */ - tlogd("AgentProcessWork: wakeup the agent"); - wake_up(&eventData->waitEventWq); - tlogd("agent 0x%x request, goto sleep, pe->run=%d\n", - agentId, atomic_read(&eventData->caRun)); - - ret = WaitAgentResponse(eventData); - atomic_set(&eventData->caRun, 0); -#endif - - PutAgentEvent(eventData); - /* - * when agent work is done, reset cmd monitor time - * add agent call count, cause it's a new smc cmd. - */ - CmdMonitorResetContext(); - return ret; -} - -int IsAgentAlive(unsigned int agentId) -{ - struct SmcEventData *eventData = NULL; - - eventData = FindEventControl(agentId); - if (eventData != NULL) { - PutAgentEvent(eventData); - return AGENT_ALIVE; - } else { - return AGENT_DEAD; - } -} - -int TcNsWaitEvent(unsigned int agentId) -{ - int ret = -EINVAL; - struct SmcEventData *eventData = NULL; - - if ((TcNsGetUid() != 0) && - CheckExtAgentAccessWithAgentId(OsCurrTaskGet(), agentId)) { - tloge("It is a fake tee agent\n"); - return -EACCES; - } - tlogd("agent %u waits for command\n", agentId); - eventData = FindEventControl(agentId); - if (eventData != NULL) { - /* only when agent wait event, it's in ready state to work */ - atomic_set(&(eventData->agentReady), AGENT_READY); - ret = wait_event_interruptible(eventData->waitEventWq, eventData->retFlag); - PutAgentEvent(eventData); - } - - return ret; -} - -int TcNsSyncSysTime(const TcNsClientTime *tcNsTime) -{ - TcNsSmcCmd smcCmd = { {0}, 0 }; - int ret; - TcNsClientTime tmpTcNsTime = {0}; - struct MbCmdPack *mbPack = NULL; - - if (tcNsTime == NULL) { - tloge("tcNsTime is NULL input buffer\n"); - return -EINVAL; - } - if (TcNsGetUid() != 0) { - tloge("It is a fake tee agent\n"); - return TEEC_ERROR_GENERIC; - } - if (copy_from_user(&tmpTcNsTime, tcNsTime, - sizeof(tmpTcNsTime))) { - tloge("copy from user failed\n"); - return -EFAULT; - } - - mbPack = MailboxAllocCmdPack(); - if (mbPack == NULL) { - tloge("alloc mb pack failed\n"); - return -ENOMEM; - } - - smcCmd.globalCmd = true; - smcCmd.cmdId = GLOBAL_CMD_ID_ADJUST_TIME; - smcCmd.errOrigin = tmpTcNsTime.seconds; - smcCmd.retVal = (int)tmpTcNsTime.millis; - - ret = TcNsSmc(&smcCmd); - if (ret) { - tloge("tee adjust time failed, return error %x\n", ret); - } - - MailboxFree(mbPack); - mbPack = NULL; - - return ret; -} - -static struct SmcEventData *CheckForSendEventResponse(unsigned int agentId) -{ - struct SmcEventData *eventData = FindEventControl(agentId); - bool tmpCheckStatus = false; - - if (eventData == NULL) { - tloge("Can't get eventData\n"); - return NULL; - } - tmpCheckStatus = ((TcNsGetUid() != 0) && - CheckExtAgentAccessWithAgentId(OsCurrTaskGet(), agentId)); - if (tmpCheckStatus) { - tloge("It is a fake tee agent\n"); - PutAgentEvent(eventData); - return NULL; - } - return eventData; -} - -static int ProcessSendEventResponse(struct SmcEventData *eventData) -{ - int ret = 0; - if (eventData->retFlag) { - eventData->retFlag = 0; - /* Send the command back to the TA session waiting for it */ -#ifdef CONFIG_TEE_SMP - tlogd("agent wakeup ca\n"); - atomic_set(&eventData->caRun, 1); - /* make sure reset working_ca before wakeup CA */ - wake_up(&eventData->caPendingWq); - ret = 0; -#else - ret = TcNsPostSmc(&eventData->cmd); -#endif - } - return ret; -} - -int TcNsSendEventResponse(unsigned int agentId) -{ - struct SmcEventData *eventData = NULL; - int ret; - - eventData = CheckForSendEventResponse(agentId); - if (eventData == NULL) { - tlogd("agent %u pre-check failed\n", agentId); - return -1; - } - tlogd("agent %u sends answer back\n", agentId); - ret = ProcessSendEventResponse(eventData); - PutAgentEvent(eventData); - return ret; -} - -void SendEventResponse(unsigned int agentId) -{ - struct SmcEventData *eventData = FindEventControl(agentId); - int ret; - - if (eventData == NULL) { - tloge("Can't get eventData\n"); - return; - } - - tloge("agent 0x%x sends answer back\n", agentId); - atomic_set(&eventData->agentReady, AGENT_CRASHED); - ret = ProcessSendEventResponse(eventData); - PutAgentEvent(eventData); - if (ret) { - tloge("agent 0x%x sends answer back failed\n", agentId); - } - return; -} - -static void InitEventDataForRestart(TcNsDevFile *devFile, - struct SmcEventData *eventData) -{ - eventData->retFlag = 0; - eventData->owner = devFile; - atomic_set(&eventData->agentReady, AGENT_REGISTERED); - init_waitqueue_head(&(eventData->waitEventWq)); - init_waitqueue_head(&(eventData->sendResponseWq)); -#ifdef CONFIG_TEE_SMP - init_waitqueue_head(&(eventData->caPendingWq)); - atomic_set(&(eventData->caRun), 0); -#endif - return; -} - -static int AllocAndInitEventData(TcNsDevFile *devFile, - struct SmcEventData **eventData, unsigned int agentId, - UINTPTR *agentBuff, uint32_t agentBuffSize) -{ - *agentBuff = (UINTPTR)MailboxAlloc(agentBuffSize, MB_FLAG_ZERO); - if (*agentBuff == 0) { - tloge("alloc agent buff failed\n"); - return -ENOMEM; - } - *eventData = calloc(1, sizeof(**eventData)); - if (ZERO_OR_NULL_PTR((unsigned long)(uintptr_t)(*eventData))) { - MailboxFree((void *)*agentBuff); - *agentBuff = 0; - *eventData = NULL; - tloge("alloc event data failed\n"); - return -ENOMEM; - } - (*eventData)->agentId = agentId; - (*eventData)->retFlag = 0; - (*eventData)->agentBuffKernel = (void *)*agentBuff; - (*eventData)->agentBuffSize = agentBuffSize; - (*eventData)->owner = devFile; - atomic_set(&(*eventData)->agentReady, AGENT_REGISTERED); - init_waitqueue_head(&(*eventData)->waitEventWq); - init_waitqueue_head(&(*eventData)->sendResponseWq); - INIT_LIST_HEAD(&(*eventData)->head); -#ifdef CONFIG_TEE_SMP - init_waitqueue_head(&(*eventData)->caPendingWq); - atomic_set(&(*eventData)->caRun, 0); -#endif - return TEEC_SUCCESS; -} - -static bool IsBuiltInAgent(unsigned int agentId) -{ - bool checkValue = false; - - checkValue = ((agentId == AGENT_FS_ID) || - (agentId == AGENT_MISC_ID) || - (agentId == AGENT_SOCKET_ID) || - (agentId == SECFILE_LOAD_AGENT_ID)); - return checkValue; -} - -static unsigned long AgentBufferMap(unsigned long buffer, uint32_t size) -{ - int ret; - - if (!IS_PAGE_ALIGNED(buffer) || !IS_PAGE_ALIGNED(size)) { - return -EFAULT; - } - - vaddr_t userAddr = LOS_MMap(0, size, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, 0, 0); - if (IS_ERR_OR_NULL(userAddr)) { - goto ERR_OUT; - } - - for (int i = 0; i < (size >> PAGE_SHIFT); i++) { - LosVmPage *page = LOS_VmPageGet(buffer + PAGE_SIZE * i); - if (page == NULL) { - goto ERR_OUT; - } - LOS_AtomicInc(&page->refCounts); - } - - // agent buffer page is physically contiguous, so can entirety mmap - ret = remap_pfn_range(userAddr, buffer >> PAGE_SHIFT, size, - VM_MAP_REGION_FLAG_PERM_USER | VM_MAP_REGION_FLAG_PERM_READ | VM_MAP_REGION_FLAG_PERM_WRITE); - if (ret) { - tloge("remap agent buffer failed, err=%d", ret); - goto ERR_OUT; - } - return userAddr; - -ERR_OUT: - if (LOS_UnMMap(userAddr, size) != 0) { - tloge("munmap failed\n"); - } - return -EFAULT; -} - -static bool IsValidAgent(unsigned int agentId, - unsigned int bufferSize, bool userAgent) -{ - if (TcNsGetUid() != 0 && - CheckExtAgentAccessWithAgentId(OsCurrTaskGet(), agentId)) { - tloge("It is a fake tee agent\n"); - return false; - } - - if (userAgent && (bufferSize > SZ_4K)) { - tloge("size: %u of user agent's shared mem is invalid\n", - bufferSize); - return false; - } - return true; -} - -static void IsAgentAlreadyExist(unsigned int agentId, - struct SmcEventData **eventData, bool *findFlag) -{ - unsigned long flags; - bool flag = false; - struct SmcEventData *agentNode = NULL; - - spin_lock_irqsave(&g_agentControl.lock, flags); - list_for_each_entry(agentNode, &g_agentControl.agentList, head) { - if (agentNode->agentId == agentId) { - flag = true; - GetAgentEvent(agentNode); - break; - } - } - spin_unlock_irqrestore(&g_agentControl.lock, flags); - *findFlag = flag; - if (flag == true) { - *eventData = agentNode; - } - return; -} - -static void AddEventNodeToList(struct SmcEventData *eventData) -{ - unsigned long flags; - spin_lock_irqsave(&g_agentControl.lock, flags); - list_add_tail(&eventData->head, &g_agentControl.agentList); - atomic_set(&eventData->usage, 1); - spin_unlock_irqrestore(&g_agentControl.lock, flags); - return; -} - -static int RegisterAgentToTee(unsigned int agentId, UINTPTR agentBuff, - uint32_t agentBuffSize) -{ - int ret; - TcNsSmcCmd smcCmd = { {0}, 0 }; - struct MbCmdPack *mbPack = NULL; - - mbPack = MailboxAllocCmdPack(); - if (mbPack == NULL) { - tloge("alloc mailbox failed\n"); - return AGENT_FALSE; - } - - mbPack->operation.paramTypes = TEE_PARAM_TYPE_VALUE_INPUT | - (TEE_PARAM_TYPE_VALUE_INPUT << TEE_PARAM_NUM); - mbPack->operation.params[TEE_PARAM_ONE].value.a = - LOS_PaddrQuery((void *)agentBuff); - mbPack->operation.params[TEE_PARAM_ONE].value.b = 0; - mbPack->operation.params[TEE_PARAM_TWO].value.a = agentBuffSize; - smcCmd.globalCmd = true; - smcCmd.cmdId = GLOBAL_CMD_ID_REGISTER_AGENT; - smcCmd.operationPhys = LOS_PaddrQuery(&mbPack->operation); - smcCmd.operationHphys = 0; - smcCmd.agentId = agentId; - - ret = TcNsSmc(&smcCmd); - /* mbPack should be released no matter what ret is */ - MailboxFree(mbPack); - mbPack = NULL; - - return ret; -} - -static void ReleaseAgentResource(bool findFlag, struct SmcEventData *eventData, UINTPTR agentBuff) -{ - if (findFlag) { - PutAgentEvent(eventData); // match get action - } else { - free(eventData); // here eventData can never be NULL; - } - - if (agentBuff != 0) { - MailboxFree((void *)agentBuff); - } -} - -int TcNsRegisterAgent(TcNsDevFile *devFile, unsigned int agentId, - unsigned int bufferSize, void **buffer, bool userAgent) -{ - struct SmcEventData *eventData = NULL; - bool findFlag = false; - UINTPTR agentBuff = 0; - uint32_t sizeAlign; - - if (buffer == NULL || devFile == NULL) { - return TEEC_ERROR_GENERIC; - } - - if (IsValidAgent(agentId, bufferSize, userAgent) != true) { - return TEEC_ERROR_GENERIC; - } - - sizeAlign = ALIGN(bufferSize, SZ_4K); - - IsAgentAlreadyExist(agentId, &eventData, &findFlag); - /* - * We find the agent's eventData aready in agentList, it indicate agent - * didn't unregister normally, so the eventData will be reused. - */ - if (findFlag) { - InitEventDataForRestart(devFile, eventData); - } else { - if (AllocAndInitEventData(devFile, &eventData, - agentId, &agentBuff, sizeAlign) != TEEC_SUCCESS) { - return TEEC_ERROR_GENERIC; - } - } - - /* if the agent is first time or restart register, both case need a remap */ - if (userAgent) { - eventData->agentBuffUser = (void *)(uintptr_t)AgentBufferMap( - LOS_PaddrQuery(eventData->agentBuffKernel), - eventData->agentBuffSize); - if (IS_ERR(eventData->agentBuffUser)) { - tloge("vm map agent buffer failed\n"); - goto RELEASE_RSRC; - } - *buffer = eventData->agentBuffUser; - } else { - *buffer = eventData->agentBuffKernel; - } - - /* findFlag is false means it's a new agent register */ - if (findFlag == false) { - /* Obtain share memory which is released in TcNsUnregisterAgent */ - if (RegisterAgentToTee(agentId, agentBuff, sizeAlign) != TEEC_SUCCESS) { - UnmapAgentBuffer(eventData); - goto RELEASE_RSRC; - } - AddEventNodeToList(eventData); - } - if (findFlag) { - PutAgentEvent(eventData); // match get action - } - return TEEC_SUCCESS; -RELEASE_RSRC: - ReleaseAgentResource(findFlag, eventData, agentBuff); - return TEEC_ERROR_GENERIC; -} - -static int CheckForUnregisterAgent(unsigned int agentId) -{ - bool checkValue = false; - - checkValue = (TcNsGetUid() != 0); - if (checkValue) { - tloge("It is a fake tee agent\n"); - return TEEC_ERROR_GENERIC; - } - - checkValue = (IsBuiltInAgent(agentId) || - agentId == TEE_RPMB_AGENT_ID); - if (checkValue) { - tloge("agent: 0x%x is not allowed to unregister\n", agentId); - return TEEC_ERROR_GENERIC; - } - return TEEC_SUCCESS; -} - -static bool IsThirdPartyAgent(unsigned int agentId) -{ - uint32_t i; - CaInfo *tmpCa = g_allowedExtAgentCa; - - for (i = 0; i < ARRAY_SIZE(g_allowedExtAgentCa); i++) { - if (tmpCa->agentId == agentId) { - return true; - } - tmpCa++; - } - - return false; -} - -int TcNsUnregisterAgent(unsigned int agentId) -{ - struct SmcEventData *eventData = NULL; - int ret; - TcNsSmcCmd smcCmd = { {0}, 0 }; - struct MbCmdPack *mbPack = NULL; - - if (CheckForUnregisterAgent(agentId) != TEEC_SUCCESS) { - return TEEC_ERROR_GENERIC; - } - /* if third party itself trigger unregister agent - * we allow them to unregister. - */ - if (IsThirdPartyAgent(agentId) != true) { - tloge("invalid agent id: 0x%x\n", agentId); - return TEEC_ERROR_GENERIC; - } - - eventData = FindEventControl(agentId); - if (eventData == NULL || eventData->agentBuffKernel == NULL) { - tloge("agent is not found or kernelAddr is not allocated\n"); - return TEEC_ERROR_GENERIC; - } - - mbPack = MailboxAllocCmdPack(); - if (mbPack == NULL) { - tloge("alloc mailbox failed\n"); - PutAgentEvent(eventData); - return TEEC_ERROR_GENERIC; - } - mbPack->operation.paramTypes = TEE_PARAM_TYPE_VALUE_INPUT | - (TEE_PARAM_TYPE_VALUE_INPUT << TEE_PARAM_NUM); - mbPack->operation.params[TEE_PARAM_ONE].value.a = - LOS_PaddrQuery(eventData->agentBuffKernel); - - mbPack->operation.params[TEE_PARAM_ONE].value.b = 0; - mbPack->operation.params[TEE_PARAM_TWO].value.a = SZ_4K; - smcCmd.globalCmd = true; - smcCmd.cmdId = GLOBAL_CMD_ID_UNREGISTER_AGENT; - smcCmd.operationPhys = LOS_PaddrQuery(&mbPack->operation); - smcCmd.operationHphys = 0; - - smcCmd.agentId = agentId; - tlogd("Unregistering agent 0x%x\n", agentId); - ret = TcNsSmc(&smcCmd); - if (ret == TEEC_SUCCESS) { - FreeEventControl(agentId); - } - PutAgentEvent(eventData); - MailboxFree(mbPack); - return ret; -} - -bool IsSystemAgent(const TcNsDevFile *devFile) -{ - struct SmcEventData *eventData = NULL; - struct SmcEventData *tmp = NULL; - bool systemAgent = false; - unsigned long flags; - - if (devFile == NULL) { - return systemAgent; - } - - spin_lock_irqsave(&g_agentControl.lock, flags); - list_for_each_entry_safe(eventData, tmp, &g_agentControl.agentList, head) { - if (eventData->owner == devFile) { - systemAgent = true; - break; - } - } - spin_unlock_irqrestore(&g_agentControl.lock, flags); - - return systemAgent; -} - -void SendCrashedEventResponseAll(const TcNsDevFile *devFile) -{ - struct SmcEventData *eventData = NULL; - struct SmcEventData *tmp = NULL; - unsigned int agentId[AGENT_MAX] = {0}; - unsigned int i = 0; - unsigned long flags; - - spin_lock_irqsave(&g_agentControl.lock, flags); - list_for_each_entry_safe(eventData, tmp, &g_agentControl.agentList, - head) { - if ((eventData->owner == devFile) && (i < AGENT_MAX)) { - agentId[i++] = eventData->agentId; - } - } - spin_unlock_irqrestore(&g_agentControl.lock, flags); - - for (i = 0; i < AGENT_MAX; i++) { - if (agentId[i]) { - SendEventResponse(agentId[i]); - } - } - - return; -} - -void TeeAgentClearDevOwner(const TcNsDevFile *devFile) -{ - struct SmcEventData *eventData = NULL; - struct SmcEventData *tmp = NULL; - unsigned long flags; - - spin_lock_irqsave(&g_agentControl.lock, flags); - list_for_each_entry_safe(eventData, tmp, &g_agentControl.agentList, head) { - if (eventData->owner == devFile) { - eventData->owner = NULL; - break; - } - } - spin_unlock_irqrestore(&g_agentControl.lock, flags); - return; -} - -static int DefTeeAgentWork(UINTPTR instance, int len) -{ - int ret = 0; - struct TeeAgentKernelOps *agentInstance = NULL; - - if (len != sizeof(struct TeeAgentKernelOps)) { - return ret; - } - - agentInstance = (struct TeeAgentKernelOps *)instance; - while (!KthreadShouldStop()) { - tlogd("%s agent loop++++\n", agentInstance->agentName); - ret = TcNsWaitEvent(agentInstance->agentId); - if (ret) { - tloge("%s wait event fail\n", - agentInstance->agentName); - break; - } - if (agentInstance->teeAgentWork != NULL) { - ret = agentInstance->teeAgentWork(agentInstance); - if (ret) { - tloge("%s agent work fail\n", agentInstance->agentName); - } - } - ret = TcNsSendEventResponse(agentInstance->agentId); - if (ret) { - tloge("%s send event response fail\n", - agentInstance->agentName); - break; - } - tlogd("%s agent loop----\n", agentInstance->agentName); - } - - return ret; -} - -static int DefTeeAgentRun(struct TeeAgentKernelOps *agentInstance) -{ - TcNsDevFile dev = {0}; - int ret; - char agentName[OS_TCB_NAME_LEN] = {0}; - - /* 1. Register agent buffer to TEE */ - ret = TcNsRegisterAgent(&dev, agentInstance->agentId, - agentInstance->agentBuffSize, &agentInstance->agentBuff, false); - if (ret) { - tloge("register agent buffer fail,ret =0x%x\n", ret); - ret = -1; - goto OUT; - } - - /* 2. Create thread to run agent */ - ret = sprintf_s(agentName, OS_TCB_NAME_LEN, "agent_%s", agentInstance->agentName); - if (ret == -1) { - goto OUT; - } - agentInstance->agentThread = - KthreadRun(DefTeeAgentWork, (void *)agentInstance, sizeof(struct TeeAgentKernelOps), agentName); - if (IS_ERR_OR_NULL(agentInstance->agentThread)) { - tloge("kthread create fail\n"); - ret = PTR_ERR(agentInstance->agentThread); - agentInstance->agentThread = NULL; - goto OUT; - } - return AGENT_SUCCESS; - -OUT: - return ret; -} - -static int DefTeeAgentStop(struct TeeAgentKernelOps *agentInstance) -{ - int ret; - - if (TcNsSendEventResponse(agentInstance->agentId)) { - tloge("failed to send response for agent %u\n", - agentInstance->agentId); - } - - ret = TcNsUnregisterAgent(agentInstance->agentId); - if (ret != 0) { - tloge("failed to unregister agent %u\n", - agentInstance->agentId); - } - if (!IS_ERR_OR_NULL(agentInstance->agentThread)) { - KthreadStop(agentInstance->agentThread); - } - - return AGENT_SUCCESS; -} - -/* default kernel agent ops */ -static struct TeeAgentKernelOps g_defTeeAgentOps = { - .agentName = "default", - .agentId = 0, - .teeAgentInit = NULL, - .teeAgentRun = DefTeeAgentRun, - .teeAgentWork = NULL, - .teeAgentExit = NULL, - .teeAgentStop = DefTeeAgentStop, - .teeAgentCrashWork = NULL, - .agentBuffSize = PAGE_SIZE, - .list = LINUX_LIST_HEAD_INIT(g_defTeeAgentOps.list) -}; - -static int TeeAgentKernelInit(void) -{ - struct TeeAgentKernelOps *agentOps = NULL; - int ret = 0; - bool tmpCheckStatus = false; - - list_for_each_entry(agentOps, &g_teeAgentList, list) { - /* Check the agent validity */ - tmpCheckStatus = ((agentOps->agentId == 0) || - (agentOps->agentName == NULL) || - (agentOps->teeAgentWork == NULL)); - if (tmpCheckStatus) { - tloge("agent is invalid\n"); - continue; - } - tlogd("ready to init %s agent, id=0x%x\n", - agentOps->agentName, agentOps->agentId); - - /* Set agent buff size */ - if (agentOps->agentBuffSize == 0) { - agentOps->agentBuffSize = g_defTeeAgentOps.agentBuffSize; - } - - /* Initialize the agent */ - if (agentOps->teeAgentInit != NULL) { - ret = agentOps->teeAgentInit(agentOps); - } else if (g_defTeeAgentOps.teeAgentInit != NULL) { - ret = g_defTeeAgentOps.teeAgentInit(agentOps); - } else { - tlogw("agent id %u has no init function\n", - agentOps->agentId); - } - if (ret) { - tloge("teeAgentInit %s failed\n", - agentOps->agentName); - continue; - } - - /* Run the agent */ - if (agentOps->teeAgentRun != NULL) { - ret = agentOps->teeAgentRun(agentOps); - } else if (g_defTeeAgentOps.teeAgentRun != NULL) { - ret = g_defTeeAgentOps.teeAgentRun(agentOps); - } else { - tlogw("agent id %u has no run function\n", - agentOps->agentId); - } - if (ret) { - tloge("teeAgentRun %s failed\n", - agentOps->agentName); - if (agentOps->teeAgentExit != NULL) { - agentOps->teeAgentExit(agentOps); - } - continue; - } - } - - return AGENT_SUCCESS; -} - -static void TeeAgentKernelExit(void) -{ - struct TeeAgentKernelOps *agentOps = NULL; - - list_for_each_entry(agentOps, &g_teeAgentList, list) { - /* Stop the agent */ - if (agentOps->teeAgentStop != NULL) { - agentOps->teeAgentStop(agentOps); - } else if (g_defTeeAgentOps.teeAgentStop != NULL) { - g_defTeeAgentOps.teeAgentStop(agentOps); - } else { - tlogw("agent id %u has no stop function\n", - agentOps->agentId); - } - /* Uninitialize the agent */ - if (agentOps->teeAgentExit != NULL) { - agentOps->teeAgentExit(agentOps); - } else if (g_defTeeAgentOps.teeAgentExit != NULL) { - g_defTeeAgentOps.teeAgentExit(agentOps); - } else { - tlogw("agent id %u has no exit function\n", - agentOps->agentId); - } - } -} - -int TeeAgentClearWork(TcNsClientContext *context, - unsigned int devFileId) -{ - struct TeeAgentKernelOps *agentOps = NULL; - - list_for_each_entry(agentOps, &g_teeAgentList, list) { - if (agentOps->teeAgentCrashWork != NULL) { - agentOps->teeAgentCrashWork(agentOps, - context, devFileId); - } - } - return AGENT_SUCCESS; -} - -/* register kernel agent, for TeeAgentKernelInit load */ -int TeeAgentKernelRegister(struct TeeAgentKernelOps *newAgent) -{ - if (newAgent == NULL) { - return AGENT_FALSE; - } - INIT_LIST_HEAD(&newAgent->list); - list_add_tail(&newAgent->list, &g_teeAgentList); - return AGENT_SUCCESS; -} - -void AgentInit(void) -{ - spin_lock_init(&g_agentControl.lock); - INIT_LIST_HEAD(&g_agentControl.agentList); - INIT_LIST_HEAD(&g_teeAgentList); - - if (TeeAgentKernelInit() != AGENT_SUCCESS) { - tloge("tee agent kernel init failed\n"); - } - - return; -} - -int AgentExit(void) -{ - TeeAgentKernelExit(); - return AGENT_SUCCESS; -} diff --git a/tzdriver/src/cmdmonitor.c b/tzdriver/src/cmdmonitor.c deleted file mode 100644 index 843c5be..0000000 --- a/tzdriver/src/cmdmonitor.c +++ /dev/null @@ -1,337 +0,0 @@ -/* - * Copyright (c) 2013-2019 Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020-2021 Huawei Device Co., Ltd. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "cmdmonitor.h" -#include -#include "smc.h" -#include "tc_ns_log.h" -#include "tzdriver_compat.h" - -const char g_cmdMonitorWhiteTable[][TASK_COMM_LEN] = { -#ifdef DEF_ENG - {"tee_test_ut"}, -#endif -}; -const uint32_t g_whiteTableThreadNum = sizeof(g_cmdMonitorWhiteTable) / - TASK_COMM_LEN; - -static int g_cmdNeedArchiveLog = 0; -static LINUX_LIST_HEAD(g_cmdMonitorList); -static int g_cmdMonitorListSize = 0; -/* report 2 hours */ -#define MAX_CMD_MONITOR_LIST 200 -#define MAX_AGENT_CALL_COUNT 250 -static DEFINE_MUTEX(g_cmdMonitorLock); -struct CmdMonitor { - struct list_head list; - struct timespec sendTime; - int count; - bool returned; - bool isReported; - int pid; - int tid; - char pName[TASK_COMM_LEN]; - char tName[TASK_COMM_LEN]; - unsigned int lastCmdId; - long long timeTotal; - int agentCallCount; -}; -static struct delayed_work g_cmdMonitorWork; -static struct delayed_work g_cmdMonitorWorkArchive; -static int g_teeDetectTaCrash = 0; -enum { - TYPE_CRASH_TA = 1, - TYPE_CRASH_TEE = 2, -}; - -void TzDebugArchiveLog(void) -{ - schedule_delayed_work(&g_cmdMonitorWorkArchive, MsecsToJiffies(0)); -} - -void CmdMonitorTaCrash(int32_t type) -{ - g_teeDetectTaCrash = ((type == TYPE_CRASH_TEE) ? TYPE_CRASH_TEE : - TYPE_CRASH_TA); - TzDebugArchiveLog(); -} - -static bool IsThreadInWhiteTable(const char *tName) -{ - uint32_t i; - - if (tName == NULL) { - return false; - } - - for (i = 0; i < g_whiteTableThreadNum; i++) { - if (!strcmp(tName, g_cmdMonitorWhiteTable[i])) { - return true; - } - } - return false; -} - -bool IsThreadReported(unsigned int tid) -{ - bool ret = false; - struct CmdMonitor *monitor = NULL; - - mutex_lock(&g_cmdMonitorLock); - list_for_each_entry(monitor, &g_cmdMonitorList, list) { - if (monitor->tid == tid) { - ret = (monitor->isReported || - monitor->agentCallCount > MAX_AGENT_CALL_COUNT); - break; - } - } - mutex_unlock(&g_cmdMonitorLock); - return ret; -} - -void CmdMonitorResetContext(void) -{ - struct CmdMonitor *monitor = NULL; - int pid = OsCurrTaskGet()->processID; - int tid = OsCurrTaskGet()->taskID; - - mutex_lock(&g_cmdMonitorLock); - list_for_each_entry(monitor, &g_cmdMonitorList, list) { - if (monitor->pid == pid && monitor->tid == tid) { - monitor->sendTime = CurrentKernelTime(); - if (monitor->agentCallCount + 1 < 0) { - tloge("agent call count add overflow\n"); - } else { - monitor->agentCallCount++; - } - break; - } - } - mutex_unlock(&g_cmdMonitorLock); -} - -static void CmdMonitorTick(void) -{ - long long timeDif; - struct CmdMonitor *monitor = NULL; - struct CmdMonitor *tmp = NULL; - struct timespec nowTime = CurrentKernelTime(); - - mutex_lock(&g_cmdMonitorLock); - list_for_each_entry_safe(monitor, tmp, &g_cmdMonitorList, list) { - if (monitor->returned == true) { - g_cmdMonitorListSize--; - tloge("[CmdMonitorTick] pid:%d, pName:%s, tid:%d, tName:%s, \ -lastCmdId:%u, count:%d, agent call count:%d, timeTotal:%lld us returned, remained command(s):%d\n", - monitor->pid, monitor->pName, monitor->tid, - monitor->tName, monitor->lastCmdId, - monitor->count, monitor->agentCallCount, - monitor->timeTotal, g_cmdMonitorListSize); - list_del(&monitor->list); - free(monitor); - monitor = NULL; - continue; - } - /* not return, we need to check */ - - /* - * get time value D (timeDif=nowTime-sendTime), we do not care about overflow - * 1 year means 1000 * (60*60*24*365) = 0x757B12C00 - * only 5bytes, will not overflow - */ - timeDif = MSEC_PER_SEC * (nowTime.tv_sec - monitor->sendTime.tv_sec) + - (nowTime.tv_nsec - monitor->sendTime.tv_nsec) / NSEC_PER_MSEC; - - /* Temporally change timeout to 25s, we log the teeos log,and report */ - if ((timeDif > TEMPORALLY_CHAGE_TIMEOUT) && (!monitor->isReported)) { - monitor->isReported = true; - /* print tee stask */ - tloge("[CmdMonitorTick] pid:%d, pName:%s, tid:%d, tName:%s, \ -lastCmdId:%u, agent call count:%d, timeDif:%lld ms and report\n", - monitor->pid, monitor->pName, monitor->tid, - monitor->tName, monitor->lastCmdId, - monitor->agentCallCount, timeDif); - /* threads out of white table need info dump */ - if (!(IsThreadInWhiteTable(monitor->tName))) { - ShowCmdBitmapWithLock(); - g_cmdNeedArchiveLog = 1; - WakeupTcSiq(); - } - } else if (timeDif > 1 * MSEC_PER_SEC) { - tloge("[CmdMonitorTick] pid=%d, pName=%s, tid=%d, \ -lastCmdId=%u, agent call count:%d, timeDif=%lld ms\n", - monitor->pid, monitor->pName, monitor->tid, - monitor->lastCmdId, monitor->agentCallCount, - timeDif); - } - } - if (g_cmdMonitorListSize > 0) { - /* if have cmd in monitor list, we need tick */ - schedule_delayed_work(&g_cmdMonitorWork, MsecsToJiffies(MSEC_PER_SEC)); - } - mutex_unlock(&g_cmdMonitorLock); -} -static void CmdMonitorTickfn(struct work_struct *work) -{ - (void)(work); - CmdMonitorTick(); -} - -static void CmdMonitorArchivefn(struct work_struct *work) -{ - (void)(work); -} - -static struct CmdMonitor *InitMonitorLocked(void) -{ - struct CmdMonitor *newItem = NULL; - - newItem = calloc(1, sizeof(*newItem)); - if (ZERO_OR_NULL_PTR((unsigned long)(uintptr_t)newItem)) { - tloge("[CmdMonitorTick]calloc failed\n"); - return NULL; - } - newItem->sendTime = CurrentKernelTime(); - newItem->count = 1; - newItem->agentCallCount = 0; - newItem->returned = false; - newItem->isReported = false; - newItem->pid = OsCurrTaskGet()->processID; - newItem->tid = OsCurrTaskGet()->taskID; - - LosProcessCB *runProcess = OS_PCB_FROM_PID(newItem->pid); - if (strncpy_s(newItem->pName, TASK_COMM_LEN, runProcess->processName, OS_PCB_NAME_LEN) != EOK) { - free(newItem); - newItem = NULL; - return NULL; - } - if (strncpy_s(newItem->tName, TASK_COMM_LEN, OsCurrTaskGet()->taskName, OS_TCB_NAME_LEN) != EOK) { - free(newItem); - newItem = NULL; - return NULL; - } - INIT_LIST_HEAD(&newItem->list); - list_add_tail(&newItem->list, &g_cmdMonitorList); - g_cmdMonitorListSize++; - return newItem; -} - -void CmdMonitorLog(const TcNsSmcCmd *cmd) -{ - int foundFlag = 0; - int pid; - int tid; - struct CmdMonitor *monitor = NULL; - struct CmdMonitor *newItem = NULL; - - if (cmd == NULL) { - return; - } - pid = OsCurrTaskGet()->processID; - tid = OsCurrTaskGet()->taskID; - mutex_lock(&g_cmdMonitorLock); - do { - list_for_each_entry(monitor, &g_cmdMonitorList, list) { - if (monitor->pid == pid && monitor->tid == tid) { - foundFlag = 1; - /* restart */ - monitor->sendTime = CurrentKernelTime(); - monitor->count++; - monitor->returned = false; - monitor->isReported = false; - monitor->lastCmdId = cmd->cmdId; - monitor->agentCallCount = 0; - break; - } - } - if (foundFlag == 0) { - if (g_cmdMonitorListSize > MAX_CMD_MONITOR_LIST - 1) { - tloge("[CmdMonitorTick]MAX_CMD_MONITOR_LIST\n"); - break; - } - newItem = InitMonitorLocked(); - if (newItem == NULL) { - tloge("[CmdMonitorTick]init_monitor failed\n"); - break; - } - newItem->lastCmdId = cmd->cmdId; - /* the first cmd will cause timer */ - if (g_cmdMonitorListSize == 1) { - schedule_delayed_work(&g_cmdMonitorWork, - MsecsToJiffies(MSEC_PER_SEC)); - } - } - } while (0); - mutex_unlock(&g_cmdMonitorLock); -} - -void CmdMonitorLogend(void) -{ - int pid; - int tid; - struct CmdMonitor *monitor = NULL; - - pid = OsCurrTaskGet()->processID; - tid = OsCurrTaskGet()->taskID; - mutex_lock(&g_cmdMonitorLock); - list_for_each_entry(monitor, &g_cmdMonitorList, list) { - if (monitor->pid == pid && monitor->tid == tid && - monitor->returned == false) { - struct timespec nowTime = CurrentKernelTime(); - /* - * get time value D (timeDif=nowTime-sendTime), we do not care about overflow - * 1 year means 1000000 * (60*60*24*365) = 0x1CAE8C13E000 - * only 6bytes, will not overflow - */ - long long timeDif = USEC_PER_SEC * - (nowTime.tv_sec - monitor->sendTime.tv_sec) + - (nowTime.tv_nsec - monitor->sendTime.tv_nsec) / NSEC_PER_USEC; - monitor->timeTotal += timeDif; - monitor->returned = true; - break; - } - } - mutex_unlock(&g_cmdMonitorLock); -} - -void DoCmdNeedArchivelog(void) -{ - if (g_cmdNeedArchiveLog == 1) { - g_cmdNeedArchiveLog = 0; - schedule_delayed_work(&g_cmdMonitorWorkArchive, - MsecsToJiffies(MSEC_PER_SEC)); - } -} -void InitCmdMonitor(void) -{ - InitDeferrableWork((struct delayed_work *)(uintptr_t)&g_cmdMonitorWork, CmdMonitorTickfn); - InitDeferrableWork((struct delayed_work *)(uintptr_t)&g_cmdMonitorWorkArchive, CmdMonitorArchivefn); -} diff --git a/tzdriver/src/gp_ops.c b/tzdriver/src/gp_ops.c deleted file mode 100644 index 06b67ee..0000000 --- a/tzdriver/src/gp_ops.c +++ /dev/null @@ -1,1788 +0,0 @@ -/* - * Copyright (c) 2013-2019 Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020-2021 Huawei Device Co., Ltd. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "gp_ops.h" -#include -#include "agent.h" -#include "mailbox_mempool.h" -#include "mem.h" -#include "smc.h" -#include "tc_client_sub_driver.h" -#include "tc_ns_log.h" -#include "teek_client_constants.h" -#include "tzdriver_compat.h" - -#ifdef SECURITY_AUTH_ENHANCE -#include "security_auth_enhance.h" -#define AES_LOGIN_MAXLEN (((MAX_PUBKEY_LEN) > (MAX_PACKAGE_NAME_LEN)) ? \ - (MAX_PUBKEY_LEN) : (MAX_PACKAGE_NAME_LEN)) -static int DoEncryption(uint8_t *buffer, uint32_t bufferSize, - uint32_t payloadSize, const uint8_t *key); -static int EncryptLoginInfo(uint32_t loginInfoSize, uint8_t *buffer, - const uint8_t *key); -#endif - -typedef struct { - TcNsDevFile *devFile; - TcNsClientContext *clientContext; - TcNsSession *session; - TcNsTempBuf *localTempBuffer; - unsigned int tmpBufSize; -} TcCallParams; - -typedef struct { - TcNsDevFile *devFile; - TcNsClientContext *clientContext; - TcNsSession *session; - TcNsOperation *operation; - TcNsTempBuf *localTempBuffer; - unsigned int tmpBufSize; - unsigned int *transParamTypeToTee; - unsigned int TransParamTypeSize; -} AllocParams; - -typedef struct { - TcNsDevFile *devFile; - TcNsClientContext *clientContext; - TcNsOperation *operation; - TcNsTempBuf *localTempBuffer; - unsigned int tmpBufSize; - bool isComplete; -} UpdateParams; - -#define MAX_SHARED_SIZE 0x100000 /* 1 MiB */ -#define TEEC_PARAM_TYPES(param0_type, param1_type, param2_type, param3_type) \ - (((param3_type) << 12) | ((param2_type) << 8) | \ - ((param1_type) << 4) | (param0_type)) - -#define TEEC_PARAM_TYPE_GET(paramTypes, index) \ - (((paramTypes) >> ((index) << 2)) & 0x0F) - -#define ROUND_UP(N, S) (((N)+(S)-1)&(~((S)-1))) - -static void FreeOperation(TcCallParams *params, TcNsOperation *operation); - -#define INPUT_DIR 0 -#define OUTPUT_DIR 1 -#define BOTH_DIR 2 -/* dir: 0-inclue input, 1-include output, 2-both */ -static inline bool TeecValueType(unsigned int type, int dir) -{ - return (((dir == INPUT_DIR || dir == BOTH_DIR) && type == TEEC_VALUE_INPUT) || - ((dir == OUTPUT_DIR || dir == BOTH_DIR) && type == TEEC_VALUE_OUTPUT) || - type == TEEC_VALUE_INOUT) ? true : false; -} - -static inline bool TeecTmpmemType(unsigned int type, int dir) -{ - return (((dir == INPUT_DIR || dir == BOTH_DIR) && type == TEEC_MEMREF_TEMP_INPUT) || - ((dir == OUTPUT_DIR || dir == BOTH_DIR) && type == TEEC_MEMREF_TEMP_OUTPUT) || - type == TEEC_MEMREF_TEMP_INOUT) ? true : false; -} - -static inline bool TeecMemrefType(unsigned int type, int dir) -{ - return (((dir == INPUT_DIR || dir == BOTH_DIR) && type == TEEC_MEMREF_PARTIAL_INPUT) || - ((dir == OUTPUT_DIR || dir == BOTH_DIR) && type == TEEC_MEMREF_PARTIAL_OUTPUT) || - type == TEEC_MEMREF_PARTIAL_INOUT) ? true : false; -} - -static int CheckUserParamValue(const TcNsClientContext *clientContext, - unsigned int index) -{ - if (clientContext == NULL) { - tloge("clientContext is null.\n"); - return -EINVAL; - } - if (index > TEE_PARAM_FOUR) { - tloge("index is invalid, index:%x.\n", index); - return -EINVAL; - } - return 0; -} - -static int IsMemParam(unsigned int paramType) -{ - return (paramType == TEEC_MEMREF_TEMP_INPUT) || - (paramType == TEEC_MEMREF_TEMP_OUTPUT) || - (paramType == TEEC_MEMREF_TEMP_INOUT) || - (paramType == TEEC_MEMREF_PARTIAL_INPUT) || - (paramType == TEEC_MEMREF_PARTIAL_OUTPUT) || - (paramType == TEEC_MEMREF_PARTIAL_INOUT); -} - -static int IsValueParam(unsigned int paramType) -{ - return (paramType == TEEC_VALUE_INPUT) || - (paramType == TEEC_VALUE_OUTPUT) || - (paramType == TEEC_VALUE_INOUT) || - (paramType == TEEC_ION_INPUT) || - (paramType == TEEC_ION_SGLIST_INPUT); -} - -static int CheckMemParam(TcNsClientParam *clientParam) -{ - uint32_t size; - /* Check the size and buffer addresses have valid userspace addresses */ - if (!AccessOk(VERIFY_READ, - (unsigned long)(uintptr_t)clientParam->memref.sizeAddr, - sizeof(uint32_t))) { - return -EFAULT; - } - GetUser(&size, - (uint32_t *)(uintptr_t)clientParam->memref.sizeAddr); - /* Check if the buffer address is valid user space address */ - if (!AccessOk(VERIFY_READ, - (unsigned long)(uintptr_t)clientParam->memref.buffer, - size)) { - return -EFAULT; - } - return 0; -} - -static int CheckValueParam(TcNsClientParam *clientParam) -{ - if (!AccessOk(VERIFY_READ, - (unsigned long)(uintptr_t)clientParam->value.aAddr, - sizeof(uint32_t))) { - return -EFAULT; - } - if (!AccessOk(VERIFY_READ, - (unsigned long)(uintptr_t)clientParam->value.bAddr, - sizeof(uint32_t))) { - return -EFAULT; - } - return 0; -} - -int TcUserParamValid(TcNsClientContext *clientContext, - unsigned int index) -{ - TcNsClientParam *clientParam = NULL; - unsigned int paramType; - int checkResult = CheckUserParamValue(clientContext, index); - if (checkResult != 0) { - return checkResult; - } - - clientParam = &(clientContext->params[index]); - paramType = TEEC_PARAM_TYPE_GET(clientContext->paramTypes, index); - tlogd("Param %u type is %x\n", index, paramType); - if (paramType == TEEC_NONE) { - tlogd("paramType is TEEC_NONE.\n"); - return 0; - } - if (IsMemParam(paramType)) { - return CheckMemParam(clientParam); - } else if (IsValueParam(paramType)) { - return CheckValueParam(clientParam); - } else { - tloge("paramTypes is not supported.\n"); - return -EFAULT; - } -} - -/* - * These function handle read from client. Because client here can be - * kernel client or user space client, we must use the proper function - */ -static int ReadFromClient(void *dest, size_t destSize, - const void *src, size_t size, uint8_t kernelApi) -{ - int ret; - bool checkValue = false; - - checkValue = (dest == NULL) || (src == NULL); - if (checkValue == true) { - tloge("src or dest is NULL input buffer\n"); - return -EINVAL; - } - /* to be sure that size is <= dest's buffer size. */ - if (size > destSize) { - tloge("size is larger than destSize or size is 0\n"); - return -EINVAL; - } - if (size == 0) { - return 0; - } - - if (kernelApi) { - checkValue = (!LOS_IsUserAddress((uintptr_t)src) && LOS_PaddrQuery((void *)src)); - if (!checkValue) { - tloge("invalid addr\n"); - return -EFAULT; - } - ret = memcpy_s(dest, destSize, src, size); - if (ret != EOK) { - tloge("memcpy fail. line=%d, s_ret=%d\n", - __LINE__, ret); - return ret; - } - return ret; - } - /* buffer is in user space(CA call TEE API) */ - if (copy_from_user(dest, src, size)) { - tloge("copy from user failed\n"); - return -EFAULT; - } - - return 0; -} - -static int WriteToClient(void *dest, size_t destSize, - const void *src, size_t size, uint8_t kernelApi) -{ - int ret; - bool checkValue = false; - - checkValue = (dest == NULL) || (src == NULL); - if (checkValue == true) { - tloge("src or dest is NULL input buffer\n"); - return -EINVAL; - } - /* to be sure that size is <= dest's buffer size. */ - if (size > destSize) { - tloge("size is larger than destSize\n"); - return -EINVAL; - } - if (size == 0) { - return 0; - } - - if (kernelApi) { - checkValue = (!LOS_IsUserAddress((uintptr_t)src) && LOS_PaddrQuery((void *)src)); - if (!checkValue) { - tloge("invalid addr\n"); - return -EFAULT; - } - ret = memcpy_s(dest, destSize, src, size); - if (ret != EOK) { - tloge("write to client fail. line=%d, ret=%d\n", - __LINE__, ret); - return ret; - } - return ret; - } - /* buffer is in user space(CA call TEE API) */ - if (copy_to_user(dest, src, size)) { - tloge("copy to user failed\n"); - return -EFAULT; - } - return 0; -} - -static int CheckParamsForAlloc(const TcCallParams *params, - const TcNsOperation *operation) -{ - if (params->devFile == NULL) { - tloge("devFile is null"); - return -EINVAL; - } - if (params->session == NULL) { - tloge("session is null\n"); - return -EINVAL; - } - if (operation == NULL) { - tloge("operation is null\n"); - return -EINVAL; - } - if (params->localTempBuffer == NULL) { - tloge("localTempBuffer is null"); - return -EINVAL; - } - if (params->tmpBufSize != (unsigned int)TEE_PARAM_NUM) { - tloge("tmpBufSize is wrong"); - return -EINVAL; - } - return 0; -} - -static int CheckContextForAlloc(const TcNsClientContext *clientContext) -{ - if (clientContext == NULL) { - tloge("clientContext is null"); - return -EINVAL; - } - if (clientContext->paramTypes == 0) { - tloge("invalid param type\n"); - return -EINVAL; - } - return 0; -} - -static void SetKernelParamsForOpenSession(uint8_t flags, - int index, uint8_t *kernelParams) -{ - /* - * Normally kernelParams = kernelApi - * But when TC_CALL_LOGIN, params 2/3 will - * be filled by kernel. so under this circumstance, - * params 2/3 has to be set to kernel mode; and - * param 0/1 will keep the same with kernelApi. - */ - bool checkValue = (flags & TC_CALL_LOGIN) && (index >= TEE_PARAM_THREE); - if (checkValue) { - *kernelParams = TEE_REQ_FROM_KERNEL_MODE; - } - return; -} - -#ifdef SECURITY_AUTH_ENHANCE -static bool IsOpenSessionByIndex(uint8_t flags, uint32_t cmdId, - int index); -#endif - -static int CheckSizeForAlloc(const AllocParams *paramsIn, unsigned int index) -{ - bool checkValue = false; - - checkValue = (paramsIn->TransParamTypeSize != TEE_PARAM_NUM || - paramsIn->tmpBufSize != TEE_PARAM_NUM || - index >= TEE_PARAM_NUM); - if (checkValue == true) { - tloge("buf size or params type or index is invalid.\n"); - return -EFAULT; - } - return 0; -} - -static int CheckAllocTmpMem(AllocParams *paramsIn, unsigned int index, TcNsClientParam **clientParam, - uint32_t *bufferSize, uint8_t kernelParams) -{ - TcNsClientContext *clientContext = paramsIn->clientContext; - if (CheckSizeForAlloc(paramsIn, index) != 0) { - return -EFAULT; - } - /* For interface compatibility sake we assume buffer size to be 32bits */ - *clientParam = &(clientContext->params[index]); - if (ReadFromClient(bufferSize, sizeof(*bufferSize), - (uint32_t __user *)(uintptr_t)(*clientParam)->memref.sizeAddr, - sizeof(uint32_t), kernelParams)) { - tloge("copy memref.sizeAddr failed\n"); - return -EFAULT; - } - /* Don't allow unbounded malloc requests */ - if (*bufferSize > MAX_SHARED_SIZE) { - tloge("bufferSize %u from user is too large\n", *bufferSize); - return -EFAULT; - } - return 0; -} - -static int AllocForTmpMem(AllocParams *paramsIn, - uint8_t kernelParams, unsigned int paramType, uint8_t flags, - unsigned int index) -{ - TcNsClientContext *clientContext = paramsIn->clientContext; - TcNsTempBuf *localTempBuffer = paramsIn->localTempBuffer; - TcNsOperation *operation = paramsIn->operation; - TcNsSession *session = paramsIn->session; - unsigned int *transParamTypeToTee = paramsIn->transParamTypeToTee; - TcNsClientParam *clientParam = NULL; - void *tempBuf = NULL; - uint32_t bufferSize = 0; - bool checkValue = false; - int ret; - - ret = CheckAllocTmpMem(paramsIn, index, &clientParam, &bufferSize, kernelParams); - if (ret) { - return ret; - } - tempBuf = MailboxAlloc(bufferSize, MB_FLAG_ZERO); - /* If buffer size is zero or malloc failed */ - if (tempBuf == NULL) { - tloge("tempBuf malloc failed, i = %u.\n", index); - return -ENOMEM; - } - tlogd("tempBuf malloc ok, i = %u.\n", index); - localTempBuffer[index].tempBuffer = tempBuf; - localTempBuffer[index].size = bufferSize; - checkValue = (paramType == TEEC_MEMREF_TEMP_INPUT) || - (paramType == TEEC_MEMREF_TEMP_INOUT); - if (checkValue == true) { - tlogv("clientParam->memref.buffer=0x%llx\n", - clientParam->memref.buffer); - /* Kernel side buffer */ - if (ReadFromClient(tempBuf, bufferSize, - (void *)(uintptr_t)clientParam->memref.buffer, - bufferSize, kernelParams)) { - tloge("copy memref.buffer failed\n"); - return -EFAULT; - } - } -#ifdef SECURITY_AUTH_ENHANCE - if (IsOpenSessionByIndex(flags, clientContext->cmdId, index) == true) { - ret = EncryptLoginInfo(bufferSize, - tempBuf, session->secureInfo.cryptoInfo.key); - if (ret != 0) { - tloge("SECURITY_AUTH_ENHANCE:encry failed\n"); - return ret; - } - } -#endif - operation->params[index].memref.buffer = LOS_PaddrQuery((void *)tempBuf); - operation->bufferHaddr[index] = 0; - operation->params[index].memref.size = bufferSize; - /* TEEC_MEMREF_TEMP_INPUT equal to TEE_PARAM_TYPE_MEMREF_INPUT */ - transParamTypeToTee[index] = paramType; - return ret; -} - -static int CheckBufferForRef(uint32_t *bufferSize, - const TcNsClientParam *clientParam, uint8_t kernelParams) -{ - if (ReadFromClient(bufferSize, sizeof(*bufferSize), - (uint32_t __user *)(uintptr_t)clientParam->memref.sizeAddr, - sizeof(uint32_t), kernelParams)) { - tloge("copy memref.sizeAddr failed\n"); - return -EFAULT; - } - if (*bufferSize == 0) { - tloge("bufferSize from user is 0\n"); - return -ENOMEM; - } - return 0; -} - -static int CheckRefSharedMem(TcNsSharedMem *sharedMem, TcNsClientParam *clientParam, - uint32_t bufferSize, int index, TcNsOperation *operation) -{ - /* arbitrary CA can control offset by ioctl, so in here - * offset must be checked, and avoid integer overflow. - */ - int checkValue = ((sharedMem->len - - clientParam->memref.offset) >= bufferSize) && - (sharedMem->len > clientParam->memref.offset); - if (checkValue == true) { - void *bufferAddr = - (void *)(uintptr_t)((uintptr_t)sharedMem->kernelAddr + clientParam->memref.offset); - bufferAddr = MailboxCopyAlloc(bufferAddr, bufferSize); - if (bufferAddr == NULL) { - tloge("alloc mailbox copy failed\n"); - return -ENOMEM; - } - operation->mbBuffer[index] = bufferAddr; - operation->params[index].memref.buffer = LOS_PaddrQuery(bufferAddr); - operation->bufferHaddr[index] = 0; - /* save sharedMem in operation - * so that we can use it while FreeOperation - */ - operation->sharemem[index] = sharedMem; - GetSharememStruct(sharedMem); - } else { - tloge("Unexpected size %u vs %u", - sharedMem->len, bufferSize); - } - return 0; -} - -static int AllocForRefMem(AllocParams *paramsIn, - uint8_t kernelParams, unsigned int paramType, int index) -{ - TcNsClientContext *clientContext = paramsIn->clientContext; - TcNsOperation *operation = paramsIn->operation; - unsigned int *transParamTypeToTee = paramsIn->transParamTypeToTee; - TcNsDevFile *devFile = paramsIn->devFile; - TcNsClientParam *clientParam = NULL; - TcNsSharedMem *sharedMem = NULL; - uint32_t bufferSize = 0; - bool checkValue = false; - int ret; - - if (CheckSizeForAlloc(paramsIn, index) != 0) { - return -EFAULT; - } - clientParam = &(clientContext->params[index]); - ret = CheckBufferForRef(&bufferSize, clientParam, kernelParams); - if (ret != 0) { - return ret; - } - operation->params[index].memref.buffer = 0; - /* find kernel addr referred to user addr */ - mutex_lock(&devFile->sharedMemLock); - list_for_each_entry(sharedMem, &devFile->sharedMemList, head) { - if (sharedMem->userAddr == - (void *)(uintptr_t)clientParam->memref.buffer) { - ret = CheckRefSharedMem(sharedMem, clientParam, bufferSize, index, operation); - break; - } - } - mutex_unlock(&devFile->sharedMemLock); - /* for 8G physical memory device, there is a chance that - * operation->params[i].memref.buffer could be all 0, - * bufferHaddr cannot be 0 in the same time. - */ - checkValue = (!operation->params[index].memref.buffer) && - (!operation->bufferHaddr[index]); - if (checkValue == true) { - tloge("can not find shared buffer, exit\n"); - return -EINVAL; - } - operation->params[index].memref.size = bufferSize; - /* Change TEEC_MEMREF_PARTIAL_XXXXX to TEE_PARAM_TYPE_MEMREF_XXXXX */ - transParamTypeToTee[index] = paramType - - (TEEC_MEMREF_PARTIAL_INPUT - TEE_PARAM_TYPE_MEMREF_INPUT); - return ret; -} - -static int CopyForValue(AllocParams *paramsIn, uint8_t kernelParams, - unsigned int paramType, int index) -{ - TcNsOperation *operation = paramsIn->operation; - unsigned int *transParamTypeToTee = paramsIn->transParamTypeToTee; - TcNsClientContext *clientContext = paramsIn->clientContext; - int ret = 0; - TcNsClientParam *clientParam = NULL; - - if (CheckSizeForAlloc(paramsIn, index) != 0) { - return -EFAULT; - } - - clientParam = &(clientContext->params[index]); - if (ReadFromClient(&operation->params[index].value.a, - sizeof(operation->params[index].value.a), - (void *)(uintptr_t)clientParam->value.aAddr, - sizeof(operation->params[index].value.a), - kernelParams)) { - tloge("copy value.aAddr failed\n"); - return -EFAULT; - } - if (ReadFromClient(&operation->params[index].value.b, - sizeof(operation->params[index].value.b), - (void *)(uintptr_t)clientParam->value.bAddr, - sizeof(operation->params[index].value.b), - kernelParams)) { - tloge("copy value.bAddr failed\n"); - return -EFAULT; - } - /* TEEC_VALUE_INPUT equal - * to TEE_PARAM_TYPE_VALUE_INPUT - */ - transParamTypeToTee[index] = paramType; - return ret; -} - -static int AllocOperationParam(TcCallParams *params, AllocParams *paramsIn, - uint8_t flags, uint8_t kernelParams, int index) -{ - SetKernelParamsForOpenSession(flags, index, &kernelParams); - unsigned int paramType = TEEC_PARAM_TYPE_GET( - params->clientContext->paramTypes, index); - tlogd("Param %u type is %x\n", index, paramType); - if (TeecTmpmemType(paramType, TEE_PARAM_THREE)) { - /* temp buffers we need to allocate/deallocate - * for every operation - */ - return AllocForTmpMem(paramsIn, kernelParams, - paramType, flags, index); - } else if (TeecMemrefType(paramType, TEE_PARAM_THREE)) { - /* MEMREF_PARTIAL buffers are already allocated so we just - * need to search for the sharedMem ref; - * For interface compatibility we assume buffer size to be 32bits - */ - return AllocForRefMem(paramsIn, kernelParams, - paramType, index); - } else if (TeecValueType(paramType, TEE_PARAM_THREE)) { - return CopyForValue(paramsIn, kernelParams, - paramType, index); - } else { - tlogd("paramType = TEEC_NONE\n"); - } - return 0; -} - -static int AllocOperation(TcCallParams *params, - TcNsOperation *operation, uint8_t flags) -{ - int ret; - unsigned int index; - unsigned int transParamTypeToTee[TEE_PARAM_NUM] = { TEE_PARAM_TYPE_NONE }; - uint8_t kernelParams; - AllocParams paramsIn = { - params->devFile, params->clientContext, params->session, - operation, params->localTempBuffer, TEE_PARAM_NUM, - transParamTypeToTee, TEE_PARAM_NUM, - }; - ret = CheckParamsForAlloc(params, operation); - if (ret != 0) { - return ret; - } - ret = CheckContextForAlloc(params->clientContext); - if (ret != 0) { - return ret; - } - kernelParams = params->devFile->kernelApi; - tlogd("Allocating param types %08X\n", - params->clientContext->paramTypes); - /* Get the 4 params from the client context */ - for (index = 0; index < TEE_PARAM_NUM; index++) { - /* - * Normally kernelParams = kernelApi - * But when TC_CALL_LOGIN(open session), params 2/3 will - * be filled by kernel for authentication. so under this circumstance, - * params 2/3 has to be set to kernel mode for authentication; and - * param 0/1 will keep the same with user_api. - */ - ret = AllocOperationParam(params, ¶msIn, flags, kernelParams, index); - if (ret != 0) { - break; - } - } - if (ret != 0) { - FreeOperation(params, operation); - return ret; - } - operation->paramTypes = - TEEC_PARAM_TYPES(transParamTypeToTee[TEE_PARAM_ONE], - transParamTypeToTee[TEE_PARAM_TWO], - transParamTypeToTee[TEE_PARAM_THREE], - transParamTypeToTee[TEE_PARAM_FOUR]); - return ret; -} - -static int CheckParamsForUpdate(const TcCallParams *inParams) -{ - if (inParams->devFile == NULL) { - tloge("devFile is null"); - return -EINVAL; - } - if (inParams->clientContext == NULL) { - tloge("clientContext is null"); - return -EINVAL; - } - if (inParams->localTempBuffer == NULL) { - tloge("localTempBuffer is null"); - return -EINVAL; - } - if (inParams->tmpBufSize != TEE_PARAM_NUM) { - tloge("tmpBufSize is invalid"); - return -EINVAL; - } - return 0; -} - -static int UpdateForTmpMem(UpdateParams *paramsIn, int index) -{ - TcNsClientParam *clientParam = NULL; - uint32_t bufferSize; - TcNsDevFile *devFile = paramsIn->devFile; - TcNsClientContext *clientContext = paramsIn->clientContext; - TcNsOperation *operation = paramsIn->operation; - TcNsTempBuf *localTempBuffer = paramsIn->localTempBuffer; - bool isComplete = paramsIn->isComplete; - bool checkValue = paramsIn->tmpBufSize != TEE_PARAM_NUM || - index >= TEE_PARAM_NUM; - - if (checkValue == true) { - tloge("tmpBufSize or index is invalid\n"); - return -EFAULT; - } - /* temp buffer */ - bufferSize = operation->params[index].memref.size; - clientParam = &(clientContext->params[index]); - /* Size is updated all the time */ - if (WriteToClient((void *)(uintptr_t)clientParam->memref.sizeAddr, - sizeof(bufferSize), - &bufferSize, sizeof(bufferSize), - devFile->kernelApi)) { - tloge("copy tempbuf size failed\n"); - return -EFAULT; - } - if (bufferSize > localTempBuffer[index].size) { - /* incomplete case, when the buffer size is invalid see next param */ - if (!isComplete) - return 0; - /* complete case, operation is allocated from mailbox - * and share with gtask, so it's possible to be changed - */ - tloge("clientParam->memref.size has been changed larger than the initial\n"); - return -EFAULT; - } - /* Only update the buffer when the buffer size is valid in complete case */ - if (WriteToClient((void *)(uintptr_t)clientParam->memref.buffer, - operation->params[index].memref.size, - localTempBuffer[index].tempBuffer, - operation->params[index].memref.size, devFile->kernelApi)) { - tloge("copy tempbuf failed\n"); - return -ENOMEM; - } - return 0; -} - -static int UpdateForRefMem(UpdateParams *paramsIn, unsigned int index) -{ - TcNsClientParam *clientParam = NULL; - uint32_t bufferSize; - bool checkValue = false; - unsigned int origSize = 0; - TcNsDevFile *devFile = paramsIn->devFile; - TcNsClientContext *clientContext = paramsIn->clientContext; - TcNsOperation *operation = paramsIn->operation; - - if (index >= TEE_PARAM_NUM) { - tloge("index is invalid\n"); - return -EFAULT; - } - /* update size */ - bufferSize = operation->params[index].memref.size; - clientParam = &(clientContext->params[index]); - - if (ReadFromClient(&origSize, - sizeof(origSize), - (uint32_t __user *)(uintptr_t)clientParam->memref.sizeAddr, - sizeof(origSize), devFile->kernelApi)) { - tloge("copy orig memref.sizeAddr failed\n"); - return -EFAULT; - } - if (WriteToClient((void *)(uintptr_t)clientParam->memref.sizeAddr, - sizeof(bufferSize), - &bufferSize, sizeof(bufferSize), devFile->kernelApi)) { - tloge("copy buf size failed\n"); - return -EFAULT; - } - /* copy from mbBuffer to sharemem */ - checkValue = operation->mbBuffer[index] && origSize >= bufferSize; - if (checkValue == true) { - void *bufferAddr = - (void *)(uintptr_t)((uintptr_t) - operation->sharemem[index]->kernelAddr + - clientParam->memref.offset); - if (memcpy_s(bufferAddr, - operation->sharemem[index]->len - - clientParam->memref.offset, - operation->mbBuffer[index], bufferSize)) { - tloge("copy to sharemem failed\n"); - return -EFAULT; - } - } - return 0; -} - -static int UpdateForValue(UpdateParams *paramsIn, unsigned int index) -{ - TcNsClientParam *clientParam = NULL; - TcNsDevFile *devFile = paramsIn->devFile; - TcNsClientContext *clientContext = paramsIn->clientContext; - TcNsOperation *operation = paramsIn->operation; - - if (index >= TEE_PARAM_NUM) { - tloge("index is invalid\n"); - return -EFAULT; - } - clientParam = &(clientContext->params[index]); - if (WriteToClient((void *)(uintptr_t)clientParam->value.aAddr, - sizeof(operation->params[index].value.a), - &operation->params[index].value.a, - sizeof(operation->params[index].value.a), - devFile->kernelApi)) { - tloge("inc copy value.aAddr failed\n"); - return -EFAULT; - } - if (WriteToClient((void *)(uintptr_t)clientParam->value.bAddr, - sizeof(operation->params[index].value.b), - &operation->params[index].value.b, - sizeof(operation->params[index].value.b), - devFile->kernelApi)) { - tloge("inc copy value.bAddr failed\n"); - return -EFAULT; - } - return 0; -} - -static int UpdateClientOperation(TcCallParams *params, - TcNsOperation *operation, bool isComplete) -{ - int ret; - unsigned int paramType; - unsigned int index; - UpdateParams paramsIn = { - params->devFile, params->clientContext, - operation, params->localTempBuffer, TEE_PARAM_NUM, - isComplete - }; - ret = CheckParamsForUpdate(params); - if (ret != 0) { - return -EINVAL; - } - /* if paramTypes is NULL, no need to update */ - if (params->clientContext->paramTypes == 0) { - return 0; - } - for (index = 0; index < TEE_PARAM_NUM; index++) { - paramType = TEEC_PARAM_TYPE_GET( - params->clientContext->paramTypes, index); - if (TeecTmpmemType(paramType, OUTPUT_DIR)) { - ret = UpdateForTmpMem(¶msIn, index); - } else if (TeecMemrefType(paramType, OUTPUT_DIR)) { - ret = UpdateForRefMem(¶msIn, index); - } else if (isComplete && - TeecValueType(paramType, OUTPUT_DIR)) { - ret = UpdateForValue(¶msIn, index); - } else { - tlogd("paramType:%u don't need to update.\n", - paramType); - } - if (ret != 0) { - break; - } - } - return ret; -} - -static void FreeOperation(TcCallParams *params, TcNsOperation *operation) -{ - unsigned int paramType; - unsigned int index; - void *tempBuf = NULL; - bool checkTempMem = false; - bool checkPartMem = false; - TcNsTempBuf *localTempBuffer = params->localTempBuffer; - TcNsClientContext *clientContext = params->clientContext; - - if (params->tmpBufSize != TEE_PARAM_NUM) { - tloge("tmpBufSize is invalid %x.\n", params->tmpBufSize); - } - for (index = 0; index < TEE_PARAM_NUM; index++) { - paramType = TEEC_PARAM_TYPE_GET( - clientContext->paramTypes, index); - checkTempMem = paramType == TEEC_MEMREF_TEMP_INPUT || - paramType == TEEC_MEMREF_TEMP_OUTPUT || - paramType == TEEC_MEMREF_TEMP_INOUT; - checkPartMem = paramType == TEEC_MEMREF_PARTIAL_INPUT || - paramType == TEEC_MEMREF_PARTIAL_OUTPUT || - paramType == TEEC_MEMREF_PARTIAL_INOUT; - if (checkTempMem == true) { - /* free temp buffer */ - tempBuf = localTempBuffer[index].tempBuffer; - tlogd("Free temp buf, i = %u\n", index); - if (LOS_PaddrQuery(tempBuf) && - !ZERO_OR_NULL_PTR((unsigned long)(uintptr_t)tempBuf)) { - MailboxFree(tempBuf); - tempBuf = NULL; - } - } else if (checkPartMem == true) { - PutSharememStruct(operation->sharemem[index]); - if (operation->mbBuffer[index]) { - MailboxFree(operation->mbBuffer[index]); - } - } - } -} - -#ifdef SECURITY_AUTH_ENHANCE -unsigned char g_authHashBuf[MAX_SHA_256_SZ * NUM_OF_SO + HASH_PLAINTEXT_ALIGNED_SIZE + IV_BYTESIZE]; -#else -unsigned char g_authHashBuf[MAX_SHA_256_SZ * NUM_OF_SO + MAX_SHA_256_SZ]; -#endif - -#ifdef SECURITY_AUTH_ENHANCE -static int32_t SaveTokenInfo(void *dstTeec, uint32_t dstSize, - uint8_t *srcBuf, uint32_t srcSize, uint8_t kernelApi) -{ - uint8_t tempTeecToken[TOKEN_SAVE_LEN] = {0}; - bool checkValue = (dstTeec == NULL || srcBuf == NULL || - dstSize != TOKEN_SAVE_LEN || srcSize == 0); - - if (checkValue == true) { - tloge("dst data or src data is invalid.\n"); - return -EINVAL; - } - /* copy libteec_token && timestamp to libteec */ - if (memmove_s(tempTeecToken, sizeof(tempTeecToken), - srcBuf, TIMESTAMP_SAVE_INDEX) != EOK) { - tloge("copy teec token failed.\n"); - return -EFAULT; - } - if (memmove_s(&tempTeecToken[TIMESTAMP_SAVE_INDEX], - TIMESTAMP_LEN_DEFAULT, &srcBuf[TIMESTAMP_BUFFER_INDEX], - TIMESTAMP_LEN_DEFAULT) != EOK) { - tloge("copy teec timestamp failed.\n"); - return -EFAULT; - } - /* copy libteec_token to libteec */ - if (WriteToClient(dstTeec, dstSize, - tempTeecToken, TOKEN_SAVE_LEN, - kernelApi) != EOK) { - tloge("copy teec token & timestamp failed.\n"); - return -EFAULT; - } - /* clear libteec(16byte) */ - if (memset_s(srcBuf, TIMESTAMP_SAVE_INDEX, 0, - TIMESTAMP_SAVE_INDEX) != EOK) { - tloge("clear libteec failed.\n"); - return -EFAULT; - } - return EOK; -} - -static int CheckParamsForFillToken(const TcNsSmcCmd *smcCmd, - const TcNsToken *tcToken, const uint8_t *mbPackToken, - uint32_t mbPackTokenSize, const TcNsClientContext *clientContext) -{ - if (smcCmd == NULL || tcToken == NULL || mbPackToken == NULL || - clientContext == NULL || mbPackTokenSize < TOKEN_BUFFER_LEN) { - tloge("in parameter is ivalid.\n"); - return -EFAULT; - } - - if (clientContext->teecToken == NULL || - tcToken->tokenBuffer == NULL) { - tloge("teecToken or tokenBuffer is NULL, error!\n"); - return -EFAULT; - } - return 0; -} - -int FillSessionToken(uint8_t *tempLibteecToken, int len, TcNsToken *tcToken, - const TcNsClientContext *clientContext, const TcNsDevFile *devFile) -{ - errno_t retErr; - if (len != TOKEN_SAVE_LEN) { - return -EFAULT; - } - if (ReadFromClient(tempLibteecToken, - TOKEN_SAVE_LEN, - clientContext->teecToken, TOKEN_SAVE_LEN, - devFile->kernelApi)) { - tloge("copy libteec token failed!\n"); - return -EFAULT; - } - if (memcmp(&tempLibteecToken[TIMESTAMP_SAVE_INDEX], - &tcToken->tokenBuffer[TIMESTAMP_BUFFER_INDEX], - TIMESTAMP_LEN_DEFAULT)) { - tloge("timestamp compare failed!\n"); - return -EFAULT; - } - /* combine tokenBuffer teecToken, 0-15byte */ - if (memmove_s(tcToken->tokenBuffer, - TIMESTAMP_SAVE_INDEX, tempLibteecToken, - TIMESTAMP_SAVE_INDEX) != EOK) { - tloge("copy buffer failed!\n"); - retErr = memset_s(tcToken->tokenBuffer, - tcToken->tokenLen, 0, TOKEN_BUFFER_LEN); - if (retErr != EOK) - tloge("memset buffer error=%d\n", retErr); - return -EFAULT; - } - /* kernal_api, 40byte */ - if (memmove_s((tcToken->tokenBuffer + KERNAL_API_INDEX), - KERNAL_API_LEN, &devFile->kernelApi, - KERNAL_API_LEN) != EOK) { - tloge("copy KERNAL_API_LEN failed!\n"); - retErr = memset_s(tcToken->tokenBuffer, - tcToken->tokenLen, 0, TOKEN_BUFFER_LEN); - if (retErr != EOK) - tloge("fill info memset error=%d\n", retErr); - return -EFAULT; - } - return 0; -} - -static int FillTokenInfo(TcNsSmcCmd *smcCmd, - const TcNsClientContext *clientContext, TcNsToken *tcToken, - const TcNsDevFile *devFile, bool global, uint8_t *mbPackToken, - uint32_t mbPackTokenSize) -{ - uint8_t tempLibteecToken[TOKEN_SAVE_LEN] = {0}; - int ret; - bool checkValue = true; - - ret = CheckParamsForFillToken(smcCmd, tcToken, mbPackToken, - mbPackTokenSize, clientContext); - if (ret != 0) { - return ret; - } - checkValue = (clientContext->cmdId == GLOBAL_CMD_ID_CLOSE_SESSION) || - (!global); - if (checkValue == true) { - ret = FillSessionToken(tempLibteecToken, TOKEN_SAVE_LEN, tcToken, clientContext, devFile); - if (ret) { - return ret; - } - } else { /* open_session, set tokenBuffer 0 */ - if (memset_s(tcToken->tokenBuffer, tcToken->tokenLen, - 0, TOKEN_BUFFER_LEN) != EOK) { - tloge("alloc TcNsToken->tokenBuffer error.\n"); - return -EFAULT; - } - } - if (memcpy_s(mbPackToken, mbPackTokenSize, tcToken->tokenBuffer, - tcToken->tokenLen)) { - tloge("copy token failed\n"); - return -EFAULT; - } - - smcCmd->pid = OsCurrTaskGet()->processID; - smcCmd->tokenPhys = LOS_PaddrQuery(mbPackToken); - smcCmd->tokenHphys = 0; - return EOK; -} - -static int LoadSecurityEnhanceInfo(TcCallParams *params, - TcNsSmcCmd *smcCmd, TcNsToken *tcToken, - struct MbCmdPack *mbPack, bool global, bool IsTokenWork) -{ - int ret; - bool IsOpenSessionCmd = false; - TcNsDevFile *devFile = params->devFile; - TcNsClientContext *clientContext = params->clientContext; - TcNsSession *session = params->session; - - if (smcCmd == NULL || mbPack == NULL) { - tloge("in parameter is invalid.\n"); - return -EFAULT; - } - if (IsTokenWork == true) { - ret = FillTokenInfo(smcCmd, clientContext, tcToken, - devFile, global, mbPack->token, sizeof(mbPack->token)); - if (ret != EOK) { - tloge("fill info failed. global=%u, cmdId=%u, sessionId=%u\n", - global, smcCmd->cmdId, smcCmd->contextId); - return -EFAULT; - } - } - IsOpenSessionCmd = global && - (smcCmd->cmdId == GLOBAL_CMD_ID_OPEN_SESSION); - if (IsOpenSessionCmd) { - if (session == NULL) { - tloge("invalid session when load secure info\n"); - return -EFAULT; - } - if (GenerateEncryptedSessionSecureParams( - &session->secureInfo, mbPack->secureParams, - sizeof(mbPack->secureParams))) { - tloge("Can't get encrypted session parameters buffer!"); - return -EFAULT; - } - smcCmd->paramsPhys = - LOS_PaddrQuery((void *)mbPack->secureParams); - smcCmd->paramsHphys = 0; - } - return EOK; -} - -#ifdef TC_ASYNC_NOTIFY_SUPPORT -static int CheckParamsForAppendToken( - const TcNsClientContext *clientContext, - const TcNsToken *tcToken, const TcNsDevFile *devFile, - uint32_t mbPackTokenSize) -{ - if (clientContext == NULL || devFile == NULL || tcToken == NULL) { - tloge("in parameter is invalid.\n"); - return -EFAULT; - } - if (clientContext->teecToken == NULL || - tcToken->tokenBuffer == NULL) { - tloge("teecToken or tokenBuffer is NULL, error!\n"); - return -EFAULT; - } - if (mbPackTokenSize < TOKEN_BUFFER_LEN) { - tloge("mbPackTokenSize is invalid.\n"); - return -EFAULT; - } - return 0; -} - -static int AppendTeecToken(const TcNsClientContext *clientContext, - TcNsToken *tcToken, const TcNsDevFile *devFile, bool global, - uint8_t *mbPackToken, uint32_t mbPackTokenSize) -{ - uint8_t tempLibteecToken[TOKEN_SAVE_LEN] = {0}; - int sret; - int ret; - - ret = CheckParamsForAppendToken(clientContext, tcToken, - devFile, mbPackTokenSize); - if (ret) { - return ret; - } - if (!global) { - if (ReadFromClient(tempLibteecToken, - TOKEN_SAVE_LEN, - clientContext->teecToken, TOKEN_SAVE_LEN, - devFile->kernelApi)) { - tloge("copy libteec token failed!\n"); - return -EFAULT; - } - /* combine tokenBuffer ,teecToken, 0-15byte */ - if (memmove_s(tcToken->tokenBuffer, tcToken->tokenLen, - tempLibteecToken, TIMESTAMP_SAVE_INDEX) != EOK) { - tloge("copy tempLibteecToken failed!\n"); - sret = memset_s(tcToken->tokenBuffer, - tcToken->tokenLen, 0, TOKEN_BUFFER_LEN); - if (sret != 0) { - tloge("memset failed!\n"); - return -EFAULT; - } - return -EFAULT; - } - if (memcpy_s(mbPackToken, mbPackTokenSize, - tcToken->tokenBuffer, tcToken->tokenLen)) { - tloge("copy token failed\n"); - return -EFAULT; - } - } - return EOK; -} -#endif - -static int PostProcessToken(const TcNsSmcCmd *smcCmd, - TcNsClientContext *clientContext, TcNsToken *tcToken, - uint8_t *mbPackToken, uint32_t mbPackTokenSize, - uint8_t kernelApi, bool global) -{ - int ret; - bool checkValue = false; - - checkValue = (mbPackToken == NULL || tcToken == NULL || - clientContext == NULL || clientContext->teecToken == NULL || - tcToken->tokenBuffer == NULL || - mbPackTokenSize < TOKEN_BUFFER_LEN); - if (checkValue == true) { - tloge("in parameter is invalid.\n"); - return -EINVAL; - } - if (memcpy_s(tcToken->tokenBuffer, tcToken->tokenLen, mbPackToken, - mbPackTokenSize)) { - tloge("copy token failed\n"); - return -EFAULT; - } - if (memset_s(mbPackToken, mbPackTokenSize, 0, mbPackTokenSize)) { - tloge("memset mbPack token error.\n"); - return -EFAULT; - } - if (SyncTimestamp(smcCmd, tcToken->tokenBuffer, tcToken->tokenLen, global) - != TEEC_SUCCESS) { - tloge("sync time stamp error.\n"); - return -EFAULT; - } - - ret = SaveTokenInfo(clientContext->teecToken, clientContext->tokenLen, - tcToken->tokenBuffer, tcToken->tokenLen, kernelApi); - if (ret != EOK) { - tloge("save token info failed.\n"); - return -EFAULT; - } - return EOK; -} - -#define TEE_TZMP \ -{ \ - 0xf8028dca, \ - 0xaba0, \ - 0x11e6, \ - { \ - 0x80, 0xf5, 0x76, 0x30, 0x4d, 0xec, 0x7e, 0xb7 \ - } \ -} -#define INVALID_TZMP_UID 0xffffffff -static DEFINE_MUTEX(g_tzmpLock); -static unsigned int g_tzmpUid = INVALID_TZMP_UID; - -int Tzmp2Uid(const TcNsClientContext *clientContext, - TcNsSmcCmd *smcCmd, bool global) -{ - TeecUuid uuidTzmp = TEE_TZMP; - bool checkValue = false; - - if (clientContext == NULL || smcCmd == NULL) { - tloge("clientContext or smcCmd is null! "); - return -EINVAL; - } - if (memcmp(clientContext->uuid, (unsigned char *)&uuidTzmp, - sizeof(clientContext->uuid)) == 0) { - checkValue = smcCmd->cmdId == GLOBAL_CMD_ID_OPEN_SESSION && - global; - if (checkValue == true) { - /* save tzmp_uid */ - mutex_lock(&g_tzmpLock); - g_tzmpUid = 0; /* for multisesion, we use same uid */ - smcCmd->uid = 0; - tlogv("openSession , tzmp_uid.uid is %u", g_tzmpUid); - mutex_unlock(&g_tzmpLock); - return EOK; - } - mutex_lock(&g_tzmpLock); - if (g_tzmpUid == INVALID_TZMP_UID) { - tloge("tzmp_uid.uid error!"); - mutex_unlock(&g_tzmpLock); - return -EFAULT; - } - smcCmd->uid = g_tzmpUid; - tlogv("invokeCommand or closeSession , tzmp_uid is %u, global is %d", - g_tzmpUid, global); - mutex_unlock(&g_tzmpLock); - return EOK; - } - return EOK; -} -#endif - -static int CheckParamsForClientCall(const TcNsDevFile *devFile, - const TcNsClientContext *clientContext) -{ - if (devFile == NULL) { - tloge("devFile is null"); - return -EINVAL; - } - if (clientContext == NULL) { - tloge("clientContext is null"); - return -EINVAL; - } - return 0; -} - -static int AllocForClientCall(TcNsSmcCmd **smcCmd, - struct MbCmdPack **mbPack) -{ - *smcCmd = calloc(1, sizeof(**smcCmd)); - if (ZERO_OR_NULL_PTR((unsigned long)(uintptr_t)(*smcCmd))) { - tloge("smcCmd malloc failed.\n"); - return -ENOMEM; - } - *mbPack = MailboxAllocCmdPack(); - if (*mbPack == NULL) { - free(*smcCmd); - *smcCmd = NULL; - return -ENOMEM; - } - return 0; -} - -static int InitSmcCmd(const TcNsDevFile *devFile, - const TcNsClientContext *clientContext, TcNsSmcCmd *smcCmd, - const struct MbCmdPack *mbPack, bool global) -{ - smcCmd->globalCmd = global; - if (memcpy_s(smcCmd->uuid, sizeof(smcCmd->uuid), - clientContext->uuid, UUID_LEN)) { - tloge("memcpy_s uuid error.\n"); - return -EFAULT; - } - smcCmd->cmdId = clientContext->cmdId; - smcCmd->devFileId = devFile->devFileId; - smcCmd->contextId = clientContext->sessionId; - smcCmd->errOrigin = clientContext->returns.origin; - smcCmd->started = clientContext->started; -#ifdef SECURITY_AUTH_ENHANCE - if (Tzmp2Uid(clientContext, smcCmd, global) != EOK) { - tloge("caution! tzmp uid failed !\n\n"); - } -#endif - tlogv("current uid is %u\n", smcCmd->uid); - if (clientContext->paramTypes != 0) { - smcCmd->operationPhys = LOS_PaddrQuery((void *)&mbPack->operation); - smcCmd->operationHphys = 0; - } else { - smcCmd->operationPhys = 0; - smcCmd->operationHphys = 0; - } - smcCmd->loginMethod = clientContext->login.method; - return 0; -} - -static int CheckLoginForEncrypt(TcNsClientContext *clientContext, - TcNsSession *session, TcNsSmcCmd *smcCmd, - struct MbCmdPack *mbPack, int needCheckLogin) -{ - int ret; - - if (needCheckLogin && session != NULL) { -#ifdef SECURITY_AUTH_ENHANCE - ret = DoEncryption(session->authHashBuf, - sizeof(session->authHashBuf), - MAX_SHA_256_SZ * (NUM_OF_SO + 1), - session->secureInfo.cryptoInfo.key); - if (ret) { - tloge("hash encryption failed ret=%d\n", ret); - return ret; - } -#endif - if (memcpy_s(mbPack->loginData, sizeof(mbPack->loginData), - session->authHashBuf, - sizeof(session->authHashBuf))) { - tloge("copy login data failed\n"); - return -EFAULT; - } - smcCmd->loginDataPhy = LOS_PaddrQuery(mbPack->loginData); - smcCmd->loginDataHaddr = 0; - smcCmd->loginDataLen = MAX_SHA_256_SZ * (NUM_OF_SO + 1); - } else { - smcCmd->loginDataPhy = 0; - smcCmd->loginDataHaddr = 0; - smcCmd->loginDataLen = 0; - } - return 0; -} - -static void GetUidForCmd(uint32_t *uid) -{ - *uid = GetTaskUid(OsCurrTaskGet()); -} - -static int ProcCheckLoginForOpenSession( - TcCallParams *params, struct MbCmdPack *mbPack, - bool global, TcNsSmcCmd *smcCmd) -{ - int ret; - int needCheckLogin; - TcNsDevFile *devFile = params->devFile; - TcNsClientContext *clientContext = params->clientContext; - TcNsSession *session = params->session; - - ret = InitSmcCmd(devFile, clientContext, - smcCmd, mbPack, global); - if (ret != 0) { - return ret; - } - needCheckLogin = devFile->pubKeyLen == sizeof(uint32_t) && - smcCmd->cmdId == GLOBAL_CMD_ID_OPEN_SESSION && - (!IsKernelThread(OsCurrTaskGet())) && global; - ret = CheckLoginForEncrypt(clientContext, session, - smcCmd, mbPack, needCheckLogin); - if (ret != 0) { - return ret; - } -#ifdef CONFIG_TEE_SMP - smcCmd->caPid = GetCurrentPid(); -#endif - return ret; -} - -static void ResetSessionId(TcNsClientContext *clientContext, - bool global, TcNsSmcCmd *smcCmd, int teeRet) -{ - int needReset; - - clientContext->sessionId = smcCmd->contextId; - // if teeRet error except TEEC_PENDING, but contextId is set, need to reset to 0. - needReset = global && - clientContext->cmdId == GLOBAL_CMD_ID_OPEN_SESSION && - teeRet != 0 && TEEC_PENDING != teeRet; - if (needReset) { - clientContext->sessionId = 0; - } - return; -} - -#ifdef TC_ASYNC_NOTIFY_SUPPORT -static void PendCaThread(TcNsSession *session, const TcNsSmcCmd *smcCmd) -{ - struct TcWaitData *wq = NULL; - - if (session != NULL) { - wq = &session->waitData; - } - if (wq != NULL) { - tlogv("before wait event\n"); - /* use wait_event instead of wait_event_interruptible so - * that ap suspend will not wake up the TEE wait call - */ - wait_event(wq->sendCmdWq, wq->sendWaitFlag); - wq->sendWaitFlag = 0; - } - tlogv("operation start is :%d\n", smcCmd->started); - return; -} -#endif - -static void ProcErrorSituation(TcCallParams *params, - struct MbCmdPack *mbPack, const TcNsSmcCmd *smcCmd, - int teeRet, bool operationInit) -{ - /* free(NULL) is safe and this check is probably not required */ - params->clientContext->returns.code = teeRet; - params->clientContext->returns.origin = smcCmd->errOrigin; - /* when CA invoke command and crash, - * Gtask happen to release service node ,tzdriver need to kill ion; - * ta crash ,tzdriver also need to kill ion - */ - if (teeRet == TEE_ERROR_TAGET_DEAD || teeRet == TEEC_ERROR_GENERIC) { - tloge("ta_crash or ca is killed or some error happen\n"); - } - if (operationInit && mbPack != NULL) { - FreeOperation(params, &mbPack->operation); - } - free((void *)smcCmd); - MailboxFree(mbPack); - return; -} - -static void ProcShortBufferSituation(TcCallParams *params, - TcNsOperation *operation, TcNsSmcCmd *smcCmd, - bool operationInit) -{ - int ret; - /* update size */ - if (operationInit) { - ret = UpdateClientOperation(params, operation, false); - if (ret) { - smcCmd->errOrigin = TEEC_ORIGIN_COMMS; - return; - } - } - return; -} - -struct TcClientCallPreprocStruct { - TcNsSmcCmd *smcCmd; - bool global; -#ifdef SECURITY_AUTH_ENHANCE - bool IsTokenWork; - TcNsToken *tcToken; -#endif - TcCallParams inParams; - struct MbCmdPack *mbPack; - bool operationInit; -}; - -static int TcClientCallPreprocess(TcNsClientContext *clientContext, - TcNsDevFile *devFile, TcNsSession *session, uint8_t flags, struct TcClientCallPreprocStruct *preproc) -{ - int ret; - TcNsTempBuf localTempBuffer[TEE_PARAM_NUM] = { - { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 } - }; - preproc->global = flags & TC_CALL_GLOBAL; - uint32_t uid = 0; -#ifdef SECURITY_AUTH_ENHANCE - preproc->tcToken = (session != NULL) ? &session->TcNsToken : NULL; -#endif - TcCallParams tmpCallParams = { - devFile, clientContext, session, localTempBuffer, TEE_PARAM_NUM - }; - if (memcpy_s(&preproc->inParams, sizeof(preproc->inParams), &tmpCallParams, sizeof(tmpCallParams)) != EOK) { - return -EINVAL; - } - - GetUidForCmd(&uid); - ret = CheckParamsForClientCall(devFile, clientContext); - if (ret != 0) { - return ret; - } - ret = AllocForClientCall(&preproc->smcCmd, &preproc->mbPack); - if (ret != 0) { - return ret; - } - preproc->smcCmd->uid = uid; - if (clientContext->paramTypes != 0) { - ret = AllocOperation(&preproc->inParams, &preproc->mbPack->operation, flags); - if (ret) { - tloge("AllocOperation malloc failed"); - goto ERROR; - } - preproc->operationInit = true; - } - ret = ProcCheckLoginForOpenSession(&preproc->inParams, preproc->mbPack, preproc->global, preproc->smcCmd); - if (ret != 0) { - goto ERROR; - } -#ifdef SECURITY_AUTH_ENHANCE - /* invoke cmd(global is false) or open session */ - preproc->IsTokenWork = (!preproc->global) || (preproc->smcCmd->cmdId == GLOBAL_CMD_ID_OPEN_SESSION); - ret = LoadSecurityEnhanceInfo(&preproc->inParams, preproc->smcCmd, preproc->tcToken, - preproc->mbPack, preproc->global, preproc->IsTokenWork); - if (ret != EOK) { - tloge("LoadSecurityEnhanceInfo failed.\n"); - goto ERROR; - } -#endif - return ret; -ERROR: - ProcErrorSituation(&preproc->inParams, preproc->mbPack, preproc->smcCmd, 0, preproc->operationInit); - return ret; -} - -static int TcClientCallFail(TcNsClientContext *clientContext, int teeRetFirst, - TcNsDevFile *devFile, TcNsSession *session, struct TcClientCallPreprocStruct *preproc) -{ - int teeRet = teeRetFirst; - int ret = 0; -#ifdef TC_ASYNC_NOTIFY_SUPPORT - while (teeRet == TEEC_PENDING) { - PendCaThread(session, preproc->smcCmd); -#ifdef SECURITY_AUTH_ENHANCE - if (preproc->IsTokenWork) { - ret = AppendTeecToken(clientContext, preproc->tcToken, devFile, preproc->global, - preproc->mbPack->token, sizeof(preproc->mbPack->token)); - if (ret != EOK) { - tloge("append teec's member failed. global=%d, cmdId=%u, sessionId=%u\n", - preproc->global, preproc->smcCmd->cmdId, preproc->smcCmd->contextId); - goto ERROR; - } - } -#endif - teeRet = TcNsSmcWithNoNr(preproc->smcCmd); -#ifdef SECURITY_AUTH_ENHANCE - if (preproc->IsTokenWork) { - ret = PostProcessToken(preproc->smcCmd, clientContext, preproc->tcToken, preproc->mbPack->token, - sizeof(preproc->mbPack->token), devFile->kernelApi, preproc->global); - if (ret != EOK) { - tloge("NO NR, PostProcessToken failed.\n"); - goto ERROR; - } - } -#endif - } -#endif - /* Client was interrupted, return and let it handle it's own signals first then retry */ - if (teeRet == TEEC_CLIENT_INTR) { - ret = -ERESTARTSYS; - goto ERROR; - } else if (teeRet) { - tloge("smc_call returns error ret 0x%x\n", teeRet); - tloge("smc_call smc cmd ret 0x%x\n", preproc->smcCmd->retVal); - goto SHORT_BUFFER; - } - clientContext->sessionId = preproc->smcCmd->contextId; - return ret; - -SHORT_BUFFER: - if (teeRet == TEEC_ERROR_SHORT_BUFFER) { - ProcShortBufferSituation(&preproc->inParams, &preproc->mbPack->operation, - preproc->smcCmd, preproc->operationInit); - } - ret = EFAULT; -ERROR: - ProcErrorSituation(&preproc->inParams, preproc->mbPack, preproc->smcCmd, teeRet, preproc->operationInit); - return ret; -} - -int TcClientCall(TcNsClientContext *clientContext, - TcNsDevFile *devFile, TcNsSession *session, uint8_t flags) -{ - struct TcClientCallPreprocStruct preproc; - if (memset_s(&preproc, sizeof(preproc), 0, sizeof(preproc)) != EOK) { - return -ENOMEM; - } - - int ret = TcClientCallPreprocess(clientContext, devFile, session, flags, &preproc); - if (ret) { - return ret; - } - - /* send smc to secure world */ - int teeRet = TcNsSmc(preproc.smcCmd); - - ResetSessionId(clientContext, preproc.global, preproc.smcCmd, teeRet); -#ifdef SECURITY_AUTH_ENHANCE - if (preproc.IsTokenWork) { - ret = PostProcessToken(preproc.smcCmd, clientContext, preproc.tcToken, - preproc.mbPack->token, sizeof(preproc.mbPack->token), devFile->kernelApi, preproc.global); - if (ret != EOK) { - tloge("PostProcessToken failed.\n"); - preproc.smcCmd->errOrigin = TEEC_ORIGIN_COMMS; - goto ERROR; - } - } -#endif - - if (teeRet != 0) { - ret = TcClientCallFail(clientContext, teeRet, devFile, session, &preproc); - if (ret != EOK) { - return ret; - } - } - /* wake_up tee log reader */ - if (preproc.operationInit) { - ret = UpdateClientOperation(&preproc.inParams, &preproc.mbPack->operation, true); - if (ret) { - preproc.smcCmd->errOrigin = TEEC_ORIGIN_COMMS; - goto ERROR; - } - } - ret = 0; -ERROR: - ProcErrorSituation(&preproc.inParams, preproc.mbPack, preproc.smcCmd, teeRet, preproc.operationInit); - return ret; -} - -#ifdef SECURITY_AUTH_ENHANCE -static bool IsOpenSessionByIndex(uint8_t flags, uint32_t cmdId, - int index) -{ - /* params[2] for application certificate or native ca uid; - * params[3] for pkg name; therefore we set i>= 2 - */ - bool global = flags & TC_CALL_GLOBAL; - bool login_en = (global && (index >= TEE_PARAM_THREE) && - (cmdId == GLOBAL_CMD_ID_OPEN_SESSION)); - return login_en; -} - -static bool IsValidSize(uint32_t bufferSize, uint32_t tempSize) -{ - bool overFlow = false; - - if (bufferSize > AES_LOGIN_MAXLEN) { - tloge("SECURITY_AUTH_ENHANCE: bufferSize is not right\n"); - return false; - } - overFlow = (tempSize > ROUND_UP(bufferSize, SZ_4K)) ? true : false; - if (overFlow) { - tloge("SECURITY_AUTH_ENHANCE: input data exceeds limit\n"); - return false; - } - return true; -} -static int CheckParamForEncryption(uint8_t *buffer, - uint32_t bufferSize, uint8_t **plaintext, - uint32_t *plainTextBufferSize) -{ - if (buffer == NULL || bufferSize == 0) { - tloge("bad params before encryption!\n"); - return -EINVAL; - } - *plainTextBufferSize = bufferSize; - *plaintext = calloc(1, *plainTextBufferSize); - if (ZERO_OR_NULL_PTR((unsigned long)(uintptr_t)(*plaintext))) { - tloge("malloc plaintext failed\n"); - return -ENOMEM; - } - if (memcpy_s(*plaintext, *plainTextBufferSize, - buffer, bufferSize)) { - tloge("memcpy failed\n"); - free(*plaintext); - *plaintext = NULL; - return -EINVAL; - } - return 0; -} - -static int HandleEnd(uint8_t *plaintext, uint8_t *cryptotext, int ret) -{ - free(plaintext); - if (cryptotext != NULL) { - free((void *)cryptotext); - } - return ret; -} - -static int GetTotalAndCheck(uint32_t *plaintextSize, - uint32_t payloadSize, uint32_t bufferSize, - uint32_t *plaintextAlignedSize, uint32_t *totalSize) -{ - int ret = 0; - /* Payload + Head + Padding */ - *plaintextSize = payloadSize + sizeof(struct EncryptionHead); - *plaintextAlignedSize = - ROUND_UP(*plaintextSize, CIPHER_BLOCK_BYTESIZE); - /* Need 16 bytes to store AES-CBC iv */ - *totalSize = *plaintextAlignedSize + IV_BYTESIZE; - if (*totalSize > bufferSize) { - tloge("Do encryption buffer is not enough!\n"); - ret = -ENOMEM; - } - return ret; -} - -static int DoEncryption(uint8_t *buffer, uint32_t bufferSize, - uint32_t payloadSize, const uint8_t *key) -{ - uint32_t plaintextSize; - uint32_t plaintextAlignedSize; - uint32_t totalSize; - uint8_t *cryptotext = NULL; - uint8_t *plaintext = NULL; - uint32_t plainTextBufferSize; - struct EncryptionHead head; - int ret = CheckParamForEncryption(buffer, bufferSize, &plaintext, &plainTextBufferSize); - if (ret != 0) { - return ret; - } - - ret = GetTotalAndCheck(&plaintextSize, payloadSize, bufferSize, &plaintextAlignedSize, &totalSize); - if (ret != 0) { - goto END; - } - cryptotext = calloc(1, totalSize); - if (ZERO_OR_NULL_PTR((unsigned long)(uintptr_t)cryptotext)) { - tloge("Malloc failed when doing encryption!\n"); - ret = -ENOMEM; - goto END; - } - /* Setting encryption head */ - ret = SetEncryptionHead(&head, payloadSize); - if (ret) { - tloge("Set encryption head failed, ret = %d.\n", ret); - goto END; - } - ret = memcpy_s((void *)(plaintext + payloadSize), plainTextBufferSize - payloadSize, (void *)&head, sizeof(head)); - if (ret) { - tloge("Copy encryption head failed, ret = %d.\n", ret); - goto END; - } - /* Setting padding data */ - ret = CryptoAescbcCmsPadding(plaintext, plaintextAlignedSize, plaintextSize); - if (ret) { - tloge("Set encryption padding data failed, ret = %d.\n", ret); - goto END; - } - ret = CryptoSessionAescbcKey256(plaintext, plaintextAlignedSize, cryptotext, totalSize, key, NULL, ENCRYPT); - if (ret) { - tloge("Encrypt failed, ret=%d.\n", ret); - goto END; - } - ret = memcpy_s((void *)buffer, bufferSize, (void *)cryptotext, totalSize); - if (ret) { - tloge("Copy cryptotext failed, ret=%d.\n", ret); - } -END: - return HandleEnd(plaintext, cryptotext, ret); -} - -static int EncryptLoginInfo(uint32_t loginInfoSize, - uint8_t *buffer, const uint8_t *key) -{ - uint32_t payloadSize; - uint32_t plaintextSize; - uint32_t plaintextAlignedSize; - uint32_t totalSize; - - if (buffer == NULL) { - tloge("Login information buffer is null!\n"); - return -EINVAL; - } - /* Need adding the termination null byte ('\0') to the end. */ - payloadSize = loginInfoSize + sizeof(char); - - /* Payload + Head + Padding */ - plaintextSize = payloadSize + sizeof(struct EncryptionHead); - plaintextAlignedSize = ROUND_UP(plaintextSize, CIPHER_BLOCK_BYTESIZE); - /* Need 16 bytes to store AES-CBC iv */ - totalSize = plaintextAlignedSize + IV_BYTESIZE; - if (!IsValidSize(loginInfoSize, totalSize)) { - tloge("Login information encryption size is invalid!\n"); - return -EFAULT; - } - return DoEncryption(buffer, totalSize, payloadSize, key); -} -#endif diff --git a/tzdriver/src/mailbox_mempool.c b/tzdriver/src/mailbox_mempool.c deleted file mode 100644 index f13048c..0000000 --- a/tzdriver/src/mailbox_mempool.c +++ /dev/null @@ -1,568 +0,0 @@ -/* - * Copyright (c) 2013-2019 Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020-2021 Huawei Device Co., Ltd. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "mailbox_mempool.h" -#include -#include "smc.h" -#include "tc_ns_log.h" -#include "teek_client_constants.h" -#include "tzdriver_compat.h" - -#define MAILBOX_PAGE_MAX (MAILBOX_POOL_SIZE >> PAGE_SHIFT) -#define MAILBOX_ORDER_MAX GET_ORDER(MAILBOX_POOL_SIZE) -static unsigned int g_mailboxMaxOrder = MAILBOX_ORDER_MAX; - -struct MbPageT { - struct list_head node; - LosVmPage *page; - int order; // block size - unsigned int count; // whether be used -}; - -struct MbFreeAreaT { - struct list_head pageList; - int order; -}; - -struct MbZoneT { - LosVmPage *allPages; - struct MbPageT pages[MAILBOX_PAGE_MAX]; - struct MbFreeAreaT freeAreas[MAILBOX_ORDER_MAX + 1]; -}; - -static struct MbZoneT g_mZone; -static mutex_t g_mbLock; - -#ifdef DEF_ENG -static void MailboxShowStatus(void) -{ - unsigned int i; - struct MbPageT *pos = NULL; - struct list_head *head = NULL; - unsigned int used = 0; - - pr_info("########################################\n"); - mutex_lock(&g_mbLock); - for (i = 0; i < MAILBOX_PAGE_MAX; i++) { - if (g_mZone.pages[i].count) { - pr_info("page[%02d], order=%02d, count=%d\n", i, g_mZone.pages[i].order, g_mZone.pages[i].count); - used += (1UL << (uint32_t)g_mZone.pages[i].order); - } - } - pr_info("total usage:%u/%u\n", used, MAILBOX_PAGE_MAX); - pr_info("----------------------------------------\n"); - - for (i = 0; i < g_mailboxMaxOrder; i++) { - head = &g_mZone.freeAreas[i].pageList; - if (list_empty(head)) { - pr_info("order[%02d] is empty\n", i); - } else { - list_for_each_entry(pos, head, node) - pr_info("order[%02d]\n", i); - } - } - mutex_unlock(&g_mbLock); - - pr_info("########################################\n"); -} - -#define MB_SHOW_LINE 64 -#define BITS_OF_BYTE 8 -static void MailboxShowDetails(void) -{ - unsigned int i; - unsigned int used = 0; - unsigned int left = 0; - unsigned int order = 0; - - pr_info("----- show mailbox details -----"); - mutex_lock(&g_mbLock); - for (i = 0; i < MAILBOX_PAGE_MAX; i++) { - if ((i % MB_SHOW_LINE) == 0) { - PRINTK("\n"); - PRINTK("%04d-%04d:", i, i + MB_SHOW_LINE); - } - - if (g_mZone.pages[i].count) { - left = 1 << (uint32_t)g_mZone.pages[i].order; - order = g_mZone.pages[i].order; - used += (1UL << (uint32_t)g_mZone.pages[i].order); - } - - if (left) { - left--; - PRINTK("%01d", order); - } else { - PRINTK("X"); - } - - if (i > 1 && (i + 1) % (MB_SHOW_LINE / BITS_OF_BYTE) == 0) { - PRINTK(" "); - } - } - pr_info("\ntotal usage:%u/%u\n", used, MAILBOX_PAGE_MAX); - mutex_unlock(&g_mbLock); -} -#endif - -void *MailboxAlloc(size_t size, unsigned int flag) -{ - unsigned int i; - struct MbPageT *pos = (struct MbPageT *)NULL; - struct list_head *head = NULL; - unsigned int order = GET_ORDER(ALIGN(size, SZ_4K)); - void *addr = NULL; - - if (size == 0) { - tlogw("alloc 0 size mailbox\n"); - return NULL; - } - - if (order > g_mailboxMaxOrder) { - tloge("invalid order %d\n", order); - return NULL; - } - - mutex_lock(&g_mbLock); - for (i = order; i <= g_mailboxMaxOrder; i++) { - unsigned int j; - - head = &g_mZone.freeAreas[i].pageList; - if (list_empty(head)) { - continue; - } - - pos = list_first_entry(head, struct MbPageT, node); - - pos->count = 1; - pos->order = order; - - /* split and add free list */ - for (j = order; j < i; j++) { - struct MbPageT *newPage = NULL; - - newPage = pos + (1UL << j); - newPage->count = 0; - newPage->order = j; - list_add_tail(&newPage->node, &g_mZone.freeAreas[j].pageList); - } - list_del(&pos->node); - addr = OsVmPageToVaddr(pos->page); - break; - } - mutex_unlock(&g_mbLock); - - if (addr != NULL && (flag & MB_FLAG_ZERO)) { - if (memset_s(addr, ALIGN(size, SZ_4K), 0, - ALIGN(size, SZ_4K)) != EOK) { - tloge("clean mailbox failed\n"); - MailboxFree(addr); - return NULL; - } - } - return addr; -} - -void MailboxFree(const void *ptr) -{ - unsigned int i; - LosVmPage *page = NULL; - struct MbPageT *self = NULL; - struct MbPageT *buddy = NULL; - unsigned int selfIdx; - unsigned int buddyIdx; - - if (ptr == NULL) { - tloge("invalid ptr\n"); - return; - } - - page = OsVmVaddrToPage((void *)ptr); - if (page < g_mZone.allPages || - page >= (g_mZone.allPages + MAILBOX_PAGE_MAX)) { - tloge("invalid ptr to free in mailbox\n"); - return; - } - - mutex_lock(&g_mbLock); - selfIdx = page - g_mZone.allPages; - self = &g_mZone.pages[selfIdx]; - if (!self->count) { - tloge("already freed in mailbox\n"); - mutex_unlock(&g_mbLock); - return; - } - - for (i = (unsigned int)self->order; i <= - g_mailboxMaxOrder; i++) { - selfIdx = page - g_mZone.allPages; - buddyIdx = selfIdx ^ (1UL << i); - self = &g_mZone.pages[selfIdx]; - buddy = &g_mZone.pages[buddyIdx]; - self->count = 0; - /* is buddy free */ - if ((unsigned int)buddy->order == i && buddy->count == 0) { - /* release buddy */ - list_del(&buddy->node); - /* combine self and buddy */ - if (selfIdx > buddyIdx) { - page = buddy->page; - buddy->order = (int)i + 1; - self->order = -1; - } else { - self->order = (int)i + 1; - buddy->order = -1; - } - } else { - /* release self */ - list_add_tail(&self->node, &g_mZone.freeAreas[i].pageList); - mutex_unlock(&g_mbLock); - return; - } - } - mutex_unlock(&g_mbLock); -} - -struct MbCmdPack *MailboxAllocCmdPack(void) -{ - void *pack = MailboxAlloc(SZ_4K, MB_FLAG_ZERO); - - if (pack == NULL) { - tloge("alloc mb cmd pack failed\n"); - } - return (struct MbCmdPack *)pack; -} - -void *MailboxCopyAlloc(const void *src, size_t size) -{ - void *mbPtr = NULL; - - if ((src == NULL) || (size == 0)) { - tloge("invali src to alloc mailbox copy\n"); - return NULL; - } - - mbPtr = MailboxAlloc(size, 0); - if (mbPtr == NULL) { - tloge("alloc size(%zu) mailbox failed\n", size); - return NULL; - } - - if (memcpy_s(mbPtr, size, src, size)) { - tloge("memcpy to mailbox failed\n"); - MailboxFree(mbPtr); - return NULL; - } - - return mbPtr; -} - -#ifdef DEF_ENG -struct MbDbgEntry { - struct list_head node; - unsigned int idx; - void *ptr; -}; - -static LINUX_LIST_HEAD(g_mbDbgList); -static DEFINE_MUTEX(g_mbDbgLock); -static unsigned int g_mbDbgEntryCount = 1; -static unsigned int g_mbDbgLastRes; /* only cache 1 opt result */ - -static unsigned int MbDbgAddEntry(void *ptr) -{ - struct MbDbgEntry *newEntry = NULL; - - newEntry = malloc(sizeof(*newEntry)); - if (ZERO_OR_NULL_PTR((unsigned long)(uintptr_t)newEntry)) { - tloge("alloc entry failed\n"); - return 0; - } - INIT_LIST_HEAD(&newEntry->node); - newEntry->ptr = ptr; - mutex_lock(&g_mbDbgLock); - newEntry->idx = g_mbDbgEntryCount; - /* to make sure g_mbDbgEntryCount==0 is invalid */ - if ((g_mbDbgEntryCount++) == 0) { - g_mbDbgEntryCount++; - } - list_add_tail(&newEntry->node, &g_mbDbgList); - mutex_unlock(&g_mbDbgLock); - - return newEntry->idx; -} - -static void MbDbgRemoveEntry(unsigned int idx) -{ - struct MbDbgEntry *pos = NULL; - - mutex_lock(&g_mbDbgLock); - list_for_each_entry(pos, &g_mbDbgList, node) { - if (pos->idx == idx) { - MailboxFree(pos->ptr); - list_del(&pos->node); - free(pos); - mutex_unlock(&g_mbDbgLock); - return; - } - } - mutex_unlock(&g_mbDbgLock); - - tloge("entry %u invalid\n", idx); -} - -static void MbDbgReset(void) -{ - struct MbDbgEntry *pos = NULL; - struct MbDbgEntry *tmp = NULL; - - mutex_lock(&g_mbDbgLock); - list_for_each_entry_safe(pos, tmp, &g_mbDbgList, node) { - MailboxFree(pos->ptr); - list_del(&pos->node); - free(pos); - } - g_mbDbgEntryCount = 0; - mutex_unlock(&g_mbDbgLock); -} - -#define MB_WRITE_SIZE 64 - -static int CheckDbgOptWrite(struct file *filp, const char __user *ubuf, char *obuf, size_t cnt) -{ - bool checkValue = (filp == NULL); - if (checkValue || ubuf == NULL) { - return -EINVAL; - } - if (cnt >= MB_WRITE_SIZE || cnt == 0) { - return -EINVAL; - } - if (copy_from_user(obuf, ubuf, cnt)) { - return -EFAULT; - } - return 0; -} - -static ssize_t MbDbgOptWrite(struct file *filp, const char __user *ubuf, size_t cnt) -{ - char buf[MB_WRITE_SIZE] = {0}; - char *cmd = NULL; - char *value = NULL; - char *endPtr = NULL; - int ret = CheckDbgOptWrite(filp, ubuf, buf, cnt); - if (ret) { - return ret; - } - - buf[cnt] = 0; - value = buf; - if (!strncmp(value, "reset", strlen("reset"))) { - tlogi("mb dbg reset\n"); - MbDbgReset(); - return cnt; - } - - cmd = strsep(&value, ":"); - if (cmd == NULL || value == NULL) { - tloge("no valid cmd or value for mb dbg\n"); - return -EFAULT; - } - - if (!strncmp(cmd, "alloc", strlen("alloc"))) { - unsigned int allocSize = strtoul(value, &endPtr, 0); - if ((endPtr == NULL) || (*endPtr != 0)) { - tloge("invalid value format for mb dbg\n"); - return cnt; - } - - unsigned int idx; - void *ptr = MailboxAlloc(allocSize, 0); - if (ptr != NULL) { - idx = MbDbgAddEntry(ptr); - if (idx == 0) { - MailboxFree(ptr); - } - g_mbDbgLastRes = idx; - } else { - tloge("alloc order=%u in mailbox failed\n", allocSize); - } - } else if (!strncmp(cmd, "free", strlen("free"))) { - unsigned int freeIdx = strtoul(value, &endPtr, 0); - if ((endPtr == NULL) || (*endPtr != 0)) { - tloge("invalid value format for mb dbg\n"); - return cnt; - } - - MbDbgRemoveEntry(freeIdx); - } else { - tloge("invalid format for mb dbg\n"); - } - - return cnt; -} - -#define DBG_READ_BUFSIZE 16 -static ssize_t MbDbgOptRead(struct file *filp, char __user *ubuf, - size_t cnt) -{ - char buf[DBG_READ_BUFSIZE] = {0}; - ssize_t ret; - - (void)(filp); - - ret = snprintf_s(buf, sizeof(buf), sizeof(buf) - 1, "%u\n", g_mbDbgLastRes); - if (ret < 0) { - tloge("snprintf idx failed\n"); - return -EINVAL; - } - - return SimpleReadFromBuffer(ubuf, cnt, buf, ret); -} - -static const struct file_operations_vfs g_mbDbgOptFops = { - .read = MbDbgOptRead, - .write = MbDbgOptWrite, -}; - -static ssize_t MbDbgStateRead(struct file *filp, char __user *ubuf, - size_t cnt) -{ - (void)(filp); - (void)(ubuf); - MailboxShowStatus(); - MailboxShowDetails(); - return 0; -} - -static const struct file_operations_vfs mb_dbg_state_fops = { - .read = MbDbgStateRead, -}; -#endif - -static int MailboxRegister(const void *mbPool, unsigned int size) -{ - TcNsOperation *operation = NULL; - TcNsSmcCmd *smcCmd = NULL; - int ret = 0; - - smcCmd = calloc(1, sizeof(*smcCmd)); - if (ZERO_OR_NULL_PTR((unsigned long)(uintptr_t)smcCmd)) { - tloge("alloc smcCmd failed\n"); - return -EIO; - } - operation = calloc(1, sizeof(*operation)); - if (ZERO_OR_NULL_PTR((unsigned long)(uintptr_t)operation)) { - tloge("alloc operation failed\n"); - ret = -EIO; - goto FREE_SMC_CMD; - } - - operation->paramTypes = TEE_PARAM_TYPE_VALUE_INPUT | - (TEE_PARAM_TYPE_VALUE_INPUT << TEE_PARAM_NUM); - operation->params[TEE_PARAM_ONE].value.a = LOS_PaddrQuery((void *)mbPool); - operation->params[TEE_PARAM_ONE].value.b = 0; - operation->params[TEE_PARAM_TWO].value.a = size; - - smcCmd->globalCmd = true; - smcCmd->cmdId = GLOBAL_CMD_ID_REGISTER_MAILBOX; - smcCmd->operationPhys = LOS_PaddrQuery(operation); - smcCmd->operationHphys = 0; - - ret = TcNsSmc(smcCmd); - if (ret != TEEC_SUCCESS) { - tloge("resigter mailbox failed\n"); - ret = -EIO; - } - - free(operation); - operation = NULL; -FREE_SMC_CMD: - free(smcCmd); - smcCmd = NULL; - return ret; -} - -#define TC_NS_CLIENT_MEILBOX_OPT_NAME "/dev/tz_mailbox_opt" -#define TC_NS_CLIENT_MEILBOX_STATE_NAME "/dev/tz_mailbox_state" - -int MailboxMempoolInit(void) -{ - int i; - struct MbPageT *mbPage = NULL; - struct MbFreeAreaT *area = NULL; - LosVmPage *allPages = NULL; - - allPages = MailboxPoolAllocPages(g_mailboxMaxOrder); - if (allPages == NULL) { - tloge("fail to alloc mailbox mempool\n"); - return -ENOMEM; - } - if (MailboxRegister(OsVmPageToVaddr(allPages), MAILBOX_POOL_SIZE)) { - tloge("register mailbox failed\n"); - MailboxPoolFreePages(allPages, g_mailboxMaxOrder); - return -EIO; - } - for (i = 0; i < MAILBOX_PAGE_MAX; i++) { - g_mZone.pages[i].order = -1; - g_mZone.pages[i].count = 0; - g_mZone.pages[i].page = &allPages[i]; - } - g_mZone.pages[0].order = g_mailboxMaxOrder; - for (i = 0; i <= g_mailboxMaxOrder; i++) { - area = &g_mZone.freeAreas[i]; - INIT_LIST_HEAD(&area->pageList); - area->order = i; - } - - mbPage = &g_mZone.pages[0]; - list_add_tail(&mbPage->node, &area->pageList); - g_mZone.allPages = allPages; - mutex_init(&g_mbLock); - -#ifdef DEF_ENG - int ret = CreateTcClientDevice(TC_NS_CLIENT_MEILBOX_OPT_NAME, &g_mbDbgOptFops); - if (ret != EOK) { - return ret; - } - - ret = CreateTcClientDevice(TC_NS_CLIENT_MEILBOX_STATE_NAME, &mb_dbg_state_fops); - if (ret != EOK) { - return ret; - } -#endif - return 0; -} - -void MailboxMempoolDestroy(void) -{ - MailboxPoolFreePages(g_mZone.allPages, g_mailboxMaxOrder); - g_mZone.allPages = NULL; -} diff --git a/tzdriver/src/mem.c b/tzdriver/src/mem.c deleted file mode 100644 index 810c013..0000000 --- a/tzdriver/src/mem.c +++ /dev/null @@ -1,106 +0,0 @@ -/* - * Copyright (c) 2013-2019 Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020-2021 Huawei Device Co., Ltd. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "mem.h" -#include -#include "agent.h" -#include "mailbox_mempool.h" -#include "tc_ns_client.h" -#include "tc_ns_log.h" -#include "teek_ns_client.h" -#include "tzdriver_compat.h" - -void TcMemFree(TcNsSharedMem *sharedMem) -{ - if (sharedMem == NULL) { - return; - } - - if (sharedMem->kernelAddr != NULL) { - LOS_VFree(sharedMem->kernelAddr); - sharedMem->kernelAddr = NULL; - } - free(sharedMem); -} - -TcNsSharedMem *TcMemAllocate(size_t len) -{ - TcNsSharedMem *sharedMem = NULL; - void *addr = NULL; - - sharedMem = calloc(1, sizeof(*sharedMem)); - if (ZERO_OR_NULL_PTR((unsigned long)(uintptr_t)sharedMem)) { - tloge("sharedMem malloc failed\n"); - return ERR_PTR(-ENOMEM); - } - - len = ALIGN(len, SZ_4K); - if (len > MAILBOX_POOL_SIZE) { - tloge("alloc sharemem size(%zu) is too large\n", len); - free(sharedMem); - return ERR_PTR(-EINVAL); - } - - addr = LOS_VMalloc(len); - if (addr == NULL) { - tloge("alloc mailbox failed\n"); - free(sharedMem); - return ERR_PTR(-ENOMEM); - } - sharedMem->kernelAddr = addr; - sharedMem->len = len; - sharedMem->userAddr = NULL; - sharedMem->userAddrCa = NULL; - atomic_set(&sharedMem->usage, 0); - return sharedMem; -} - -int TcMemInit(void) -{ - int ret; - - tlogi("TcMemInit\n"); - - ret = MailboxMempoolInit(); - if (ret) { - tloge("tz mailbox init failed\n"); - return -ENOMEM; - } - - return 0; -} - -void TcMemDestroy(void) -{ - tlogi("tc_client exit\n"); - - MailboxMempoolDestroy(); -} diff --git a/tzdriver/src/security_auth_enhance.c b/tzdriver/src/security_auth_enhance.c deleted file mode 100644 index 0532a72..0000000 --- a/tzdriver/src/security_auth_enhance.c +++ /dev/null @@ -1,323 +0,0 @@ -/* - * Copyright (c) 2013-2019 Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020-2021 Huawei Device Co., Ltd. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "security_auth_enhance.h" -#include -#include "securectype.h" -#include "tc_client_sub_driver.h" -#include "tc_ns_client.h" -#include "tc_ns_log.h" -#include "teek_client_constants.h" -#include "teek_client_type.h" -#include "tzdriver_compat.h" - -#if !defined(UINT64_MAX) - #define UINT64_MAX ((uint64_t)0xFFFFFFFFFFFFFFFFULL) -#endif - -#ifdef SECURITY_AUTH_ENHANCE -#define GLOBAL_CMD_ID_SSA 0x2DCB /* SSA cmdId 11723 */ -#define GLOBAL_CMD_ID_MT 0x2DCC /* MT cmdId 11724 */ -#define GLOBAL_CMD_ID_MT_UPDATE 0x2DCD /* MT_IPDATE cmdId 11725 */ -#define TEEC_PENDING2_AGENT 0xFFFF2001 - -static bool IsTokenEmpty(const uint8_t *token, uint32_t tokenLen) -{ - uint32_t i; - - if (token == NULL) { - tloge("bad parameters, token is null\n"); - return true; - } - for (i = 0; i < tokenLen; i++) { - if (*(token + i)) { - return false; - } - } - return true; -} - -static TeecResult ScramblingTimestamp(const void *in, void *out, - uint32_t dataLen, const void *key, uint32_t keyLen) -{ - uint32_t i; - bool checkValue = false; - - if (in == NULL || out == NULL || key == NULL) { - tloge("bad parameters, input_data is null\n"); - return TEEC_ERROR_BAD_PARAMETERS; - } - checkValue = (dataLen == 0 || dataLen > SECUREC_MEM_MAX_LEN || - keyLen > SECUREC_MEM_MAX_LEN || keyLen == 0); - if (checkValue) { - tloge("bad parameters, dataLen is %u, scrambling_len is %u\n", - dataLen, keyLen); - return TEEC_ERROR_BAD_PARAMETERS; - } - for (i = 0; i < dataLen; i++) { - *((uint8_t *)out + i) = - *((uint8_t *)in + i) ^ *((uint8_t *)key + i % keyLen); - } - - return TEEC_SUCCESS; -} - -static int32_t ChangeTimeStamp(uint8_t flag, uint64_t *timeStamp) -{ - if (flag == INC) { - if (*timeStamp < UINT64_MAX) { - (*timeStamp)++; - } else { - tloge("val overflow\n"); - return -EFAULT; - } - } else if (flag == DEC) { - if (*timeStamp > 0) { - (*timeStamp)--; - } else { - tloge("val down overflow\n"); - return -EFAULT; - } - } else { - tloge("flag error , 0x%x\n", flag); - return -EFAULT; - } - return EOK; -} - -static int32_t DescramblingTimestamp(uint8_t *inTokenBuf, - const struct SessionSecureInfo *secureInfo, uint8_t flag) -{ - uint64_t timeStamp = 0; - int32_t ret; - - if (inTokenBuf == NULL || secureInfo == NULL) { - tloge("invalid params!\n"); - return -EINVAL; - } - if (ScramblingTimestamp(&inTokenBuf[TIMESTAMP_BUFFER_INDEX], - &timeStamp, TIMESTAMP_LEN_DEFAULT, secureInfo->scrambling, SCRAMBLING_KEY_LEN)) { - tloge("DescramblingTimestamp failed\n"); - return -EFAULT; - } - ret = ChangeTimeStamp(flag, &timeStamp); - if (ret != EOK) { - return ret; - } - - tlogd("timestamp is %llu\n", timeStamp); - if (ScramblingTimestamp(&timeStamp, &inTokenBuf[TIMESTAMP_BUFFER_INDEX], - TIMESTAMP_LEN_DEFAULT, secureInfo->scrambling, SCRAMBLING_KEY_LEN)) { - tloge("DescramblingTimestamp failed\n"); - return -EFAULT; - } - return EOK; -} - -TeecResult UpdateTimestamp(const TcNsSmcCmd *cmd) -{ - TcNsSession *session = NULL; - struct SessionSecureInfo *secureInfo = NULL; - uint8_t *tokenBuffer = NULL; - bool filterFlag = false; - bool needCheckFlag = false; - - if (cmd == NULL) { - tloge("cmd is NULL, error!"); - return TEEC_ERROR_BAD_PARAMETERS; - } - /* if cmd is agent, not check uuid. and sometime uuid canot access it */ - filterFlag = (cmd->agentId != 0) || - (cmd->retVal == TEEC_PENDING2_AGENT); - if (filterFlag) { - return TEEC_SUCCESS; - } - - needCheckFlag = (cmd->globalCmd == false) && (cmd->agentId == 0) && - (cmd->retVal != TEEC_PENDING2_AGENT); - if (needCheckFlag) { - tokenBuffer = (void *)LOS_PaddrToKVaddr((paddr_t)(cmd->tokenPhys)); - if (tokenBuffer == NULL || - IsTokenEmpty(tokenBuffer, TOKEN_BUFFER_LEN)) { - tloge("token is NULL or token is empyt, error!\n"); - return TEEC_ERROR_GENERIC; - } - - session = TcFindSession2(cmd->devFileId, cmd); - if (session == NULL) { - tlogd("tc_find_session_key find session FAILURE\n"); - return TEEC_ERROR_GENERIC; - } - secureInfo = &session->secureInfo; - if (DescramblingTimestamp(tokenBuffer, secureInfo, INC) != EOK) { - PutSessionStruct(session); - tloge("update tokenBuffer error\n"); - return TEEC_ERROR_GENERIC; - } - PutSessionStruct(session); - tokenBuffer[SYNC_INDEX] = UN_SYNCED; - } else { - tlogd("global cmd or agent, do not update timestamp\n"); - } - return TEEC_SUCCESS; -} - -TeecResult SyncTimestamp(const TcNsSmcCmd *cmd, uint8_t *token, - uint32_t tokenLen, bool global) -{ - TcNsSession *session = NULL; - bool checkVal = false; - - checkVal = (cmd == NULL || token == NULL || tokenLen <= SYNC_INDEX); - if (checkVal) { - tloge("parameters is NULL, error!\n"); - return TEEC_ERROR_BAD_PARAMETERS; - } - if (cmd->cmdId == GLOBAL_CMD_ID_OPEN_SESSION && global) { - tlogd("OpenSession would not need sync timestamp\n"); - return TEEC_SUCCESS; - } - - if (token[SYNC_INDEX] == UN_SYNCED) { - tlogd("flag is UN_SYNC, to sync timestamp!\n"); - - session = TcFindSession2(cmd->devFileId, cmd); - if (session == NULL) { - tloge("SyncTimestamp find session FAILURE\n"); - return TEEC_ERROR_GENERIC; - } - if (DescramblingTimestamp(token, &session->secureInfo, DEC) != EOK) { - PutSessionStruct(session); - tloge("sync tokenBuffer error\n"); - return TEEC_ERROR_GENERIC; - } - PutSessionStruct(session); - return TEEC_SUCCESS; - } else if (token[SYNC_INDEX] == IS_SYNCED) { - return TEEC_SUCCESS; - } else { - tloge("sync flag error! 0x%x\n", token[SYNC_INDEX]); - } - return TEEC_ERROR_GENERIC; -} - -/* scrambling operation and pid */ -static void ScramblingOperation(TcNsSmcCmd *cmd, uint32_t scrambler) -{ - if (cmd == NULL) { - return; - } - if (cmd->operationPhys != 0 || cmd->operationHphys != 0) { - cmd->operationPhys = cmd->operationPhys ^ scrambler; - cmd->operationHphys = cmd->operationHphys ^ scrambler; - } - cmd->pid = cmd->pid ^ scrambler; -} - -static bool AgentMsg(uint32_t cmdId) -{ - bool agent = cmdId == GLOBAL_CMD_ID_SSA || - cmdId == GLOBAL_CMD_ID_MT || - cmdId == GLOBAL_CMD_ID_MT_UPDATE; - - return agent; -} - -/* calculate cmd checksum and scrambling operation */ -TeecResult UpdateChksum(TcNsSmcCmd *cmd) -{ - TcNsSession *session = NULL; - struct SessionSecureInfo *secureInfo = NULL; - uint32_t ScramblerOper; - bool checkValue = false; - - if (cmd == NULL) { - tloge("cmd is NULL, error\n"); - return TEEC_ERROR_BAD_PARAMETERS; - } - /* - * if cmd is agent, do not check uuid. - * and sometimes uuid cannot access it - */ - checkValue = (cmd->agentId != 0 || cmd->retVal == TEEC_PENDING2_AGENT); - if (checkValue == true) { - return TEEC_SUCCESS; - } - - if (AgentMsg(cmd->cmdId)) { - tlogd("SSA cmd, no need to UpdateChksum\n"); - return TEEC_SUCCESS; - } - /* cmd is invoke command */ - checkValue = (cmd->globalCmd == false) && (cmd->agentId == 0) && - (cmd->retVal != TEEC_PENDING2_AGENT); - - if (checkValue) { - session = TcFindSession2(cmd->devFileId, cmd); - if (session != NULL) { - secureInfo = &session->secureInfo; - ScramblerOper = - secureInfo->scrambling[SCRAMBLING_OPERATION]; - ScramblingOperation(cmd, ScramblerOper); - PutSessionStruct(session); - } - } - return TEEC_SUCCESS; -} - -TeecResult VerifyChksum(const TcNsSmcCmd *cmd) -{ - TcNsSession *session = NULL; - bool checkFlag = false; - - if (cmd == NULL) { - tloge("cmd is NULL, error\n"); - return TEEC_ERROR_BAD_PARAMETERS; - } - if (AgentMsg(cmd->cmdId)) { - tlogd("SSA cmd, no need to UpdateChksum\n"); - return TEEC_SUCCESS; - } - - /* cmd is invoke command */ - checkFlag = cmd->globalCmd == false && - cmd->cmdId != GLOBAL_CMD_ID_CLOSE_SESSION && - cmd->cmdId != GLOBAL_CMD_ID_KILL_TASK && - cmd->agentId == 0; - if (checkFlag) { - session = TcFindSession2(cmd->devFileId, cmd); - if (session) { - PutSessionStruct(session); - } - } - return TEEC_SUCCESS; -} -#endif diff --git a/tzdriver/src/smc_smp.c b/tzdriver/src/smc_smp.c deleted file mode 100644 index 2bc6111..0000000 --- a/tzdriver/src/smc_smp.c +++ /dev/null @@ -1,1622 +0,0 @@ -/* - * Copyright (c) 2013-2019 Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020-2021 Huawei Device Co., Ltd. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "smc.h" -#include -#include -#include "agent.h" -#include "cmdmonitor.h" -#include "tc_ns_client.h" -#include "tc_ns_log.h" -#include "teek_client_constants.h" -#include "teek_ns_client.h" -#include "tzdriver_compat.h" -#ifdef SECURITY_AUTH_ENHANCE -#include "security_auth_enhance.h" - -struct SessionCryptoInfo *g_sessionRootKey = NULL; -struct SessionCryptoInfo *GetSessionRootKeyInstance(void) -{ - return g_sessionRootKey; -} -#endif - -#define SECS_SUSPEND_STATUS 0xA5A5 -#define PREEMPT_COUNT 10000 -#define HZ_COUNT 10 -#define IDLED_COUNT 100 - -#define MAX_EMPTY_RUNS 100 -#define TZ_CPU_ZERO 0 -#define TZ_CPU_ONE 1 -#define TZ_CPU_FOUR 4 -#define TZ_CPU_FIVE 5 -#define TZ_CPU_SIX 6 -#define TZ_CPU_SEVEN 7 -#define LOW_BYTE 0xF - -/* Current state of the system */ -static uint8_t g_sysCrash; - -enum SPI_CLK_MODE { - SPI_CLK_OFF = 0, - SPI_CLK_ON, -}; - -typedef struct { - int *nIdled; - uint64_t *ret; - uint64_t *exitReason; - uint64_t *ta; - uint64_t *target; -} WoPmParams; - -struct ShadowWork { - struct work_struct work; - uint64_t target; -}; - -unsigned long g_shadowThreadId = 0; -static LosTaskCB *g_siqThread = NULL; -static LosTaskCB *g_smcSvcThread = NULL; -struct workqueue_struct *g_ipiHelperWq = NULL; - -#ifdef SECURITY_AUTH_ENHANCE -#define MAX_SMC_CMD 18 -#else -#define MAX_SMC_CMD 23 -#endif - -typedef uint32_t SmcBufLockT; - -typedef struct __attribute__((__packed__)) TcNsSmcQueue { - /* set when CA send cmdIn, clear after cmdOut return */ - DECLARE_BITMAP(inBitmap, MAX_SMC_CMD); - /* set when gtask get cmdIn, clear after cmdOut return */ - DECLARE_BITMAP(doingBitmap, MAX_SMC_CMD); - /* set when gtask get cmdOut, clear after cmdOut return */ - DECLARE_BITMAP(outBitmap, MAX_SMC_CMD); - SmcBufLockT smcLock; - uint32_t lastIn; - TcNsSmcCmd in[MAX_SMC_CMD]; - uint32_t lastOut; - TcNsSmcCmd out[MAX_SMC_CMD]; -} TcNsSmcQueue; - -TcNsSmcQueue *g_cmdData = NULL; -paddr_t g_cmdPhys; - -static struct list_head g_pendingHead; -static spinlock_t g_pendLock; - -static inline void AcquireSmcBufLock(SmcBufLockT *lock) -{ - int ret; - PreemptDisable(); - do { - ret = CmpXchg(lock, 0, 1); - } while (ret); -} - -static inline void ReleaseSmcBufLock(SmcBufLockT *lock) -{ - (void)CmpXchg(lock, 1, 0); - PreemptEnable(); -} - -static int OccupyFreeSmcInEntry(const TcNsSmcCmd *cmd) -{ - int idx = -1; - int i; - - if (cmd == NULL) { - tloge("Bad parameters! cmd is NULL.\n"); - return -1; - } - /* Note: - * AcquireSmcBufLock will disable preempt and kernel will forbid - * call mutex_lock in preempt disabled scenes. - * To avoid such case(UpdateTimestamp and UpdateChksum will call - * mutex_lock), only cmd copy is done when preempt is disable, - * then do UpdateTimestamp and UpdateChksum. - * As soon as this idx of inBitmap is set, gtask will see this - * cmdIn, but the cmdIn is not ready that lack of update_xxx, - * so we make a tricky here, set doingBitmap and inBitmap both - * at first, after update_xxx is done, clear doingBitmap. - */ - AcquireSmcBufLock(&g_cmdData->smcLock); - for (i = 0; i < MAX_SMC_CMD; i++) { - if (HmTestBit(i, g_cmdData->inBitmap)) { - continue; - } - if (memcpy_s(&g_cmdData->in[i], sizeof(g_cmdData->in[i]), cmd, sizeof(*cmd)) != EOK) { - tloge("memcpy_s failed,%s line:%d", __func__, __LINE__); - break; - } - g_cmdData->in[i].eventNr = i; - ISB; - DSB; - HmSetBit(i, g_cmdData->inBitmap); - HmSetBit(i, g_cmdData->doingBitmap); - idx = i; - break; - } - ReleaseSmcBufLock(&g_cmdData->smcLock); - if (idx == -1) { - tloge("can't get any free smc entry\n"); - return -1; - } -#ifdef SECURITY_AUTH_ENHANCE - if (UpdateTimestamp(&g_cmdData->in[idx])) { - tloge("UpdateTimestamp failed !\n"); - goto clean; - } - if (UpdateChksum(&g_cmdData->in[idx])) { - tloge("UpdateChksum failed.\n"); - goto clean; - } -#endif - - AcquireSmcBufLock(&g_cmdData->smcLock); - ISB; - DSB; - HmClearBit(idx, g_cmdData->doingBitmap); - ReleaseSmcBufLock(&g_cmdData->smcLock); - return idx; -clean: - AcquireSmcBufLock(&g_cmdData->smcLock); - HmClearBit(i, g_cmdData->inBitmap); - HmClearBit(i, g_cmdData->doingBitmap); - ReleaseSmcBufLock(&g_cmdData->smcLock); - return -1; -} - -static int ReuseSmcInEntry(uint32_t idx) -{ - int rc = 0; - - AcquireSmcBufLock(&g_cmdData->smcLock); - if (!(HmTestBit(idx, g_cmdData->inBitmap) && - HmTestBit(idx, g_cmdData->doingBitmap))) { - tloge("invalid cmd to reuse\n"); - rc = -1; - goto out; - } - if (memcpy_s(&g_cmdData->in[idx], sizeof(g_cmdData->in[idx]), - &g_cmdData->out[idx], sizeof(g_cmdData->out[idx])) != EOK) { - tloge("memcpy_s failed,%s line:%d", __func__, __LINE__); - rc = -1; - goto out; - } - ReleaseSmcBufLock(&g_cmdData->smcLock); -#ifdef SECURITY_AUTH_ENHANCE - if (UpdateTimestamp(&g_cmdData->in[idx])) { - tloge("UpdateTimestamp failed !\n"); - return -1; - } - if (UpdateChksum(&g_cmdData->in[idx])) { - tloge("UpdateChksum failed.\n"); - return -1; - } -#endif - - AcquireSmcBufLock(&g_cmdData->smcLock); - ISB; - DSB; - HmClearBit(idx, g_cmdData->doingBitmap); -out: - ReleaseSmcBufLock(&g_cmdData->smcLock); - return rc; -} - -enum CmdReuse { - CLEAR, /* clear this cmd index */ - RESEND, /* use this cmd index resend */ -}; - -static int CopySmcOutEntry(uint32_t idx, TcNsSmcCmd *copy, - enum CmdReuse *usage) -{ - bool paramCheck = false; - - paramCheck = (copy == NULL || usage == NULL); - if (paramCheck == true) { - tloge("Bad parameters!\n"); - return -1; - } - AcquireSmcBufLock(&g_cmdData->smcLock); - if (!HmTestBit(idx, g_cmdData->outBitmap)) { - tloge("cmd out %u is not ready\n", idx); - ShowCmdBitmap(); - ReleaseSmcBufLock(&g_cmdData->smcLock); - return -1; - } - - if (memcpy_s(copy, sizeof(*copy), &g_cmdData->out[idx], - sizeof(g_cmdData->out[idx]))) { - tloge("copy smc out failed\n"); - ReleaseSmcBufLock(&g_cmdData->smcLock); - return -1; - } - - ISB; - DSB; - if (g_cmdData->out[idx].retVal == TEEC_PENDING2 || - g_cmdData->out[idx].retVal == TEEC_PENDING) { - *usage = RESEND; - } else { - HmClearBit(idx, g_cmdData->inBitmap); - HmClearBit(idx, g_cmdData->doingBitmap); - *usage = CLEAR; - } - HmClearBit(idx, g_cmdData->outBitmap); - ReleaseSmcBufLock(&g_cmdData->smcLock); - return 0; -} - -static inline void ReleaseSmcEntry(uint32_t idx) -{ - AcquireSmcBufLock(&g_cmdData->smcLock); - HmClearBit(idx, g_cmdData->inBitmap); - HmClearBit(idx, g_cmdData->doingBitmap); - HmClearBit(idx, g_cmdData->outBitmap); - ReleaseSmcBufLock(&g_cmdData->smcLock); -} - -static inline int IsCmdWorkingDone(uint32_t idx) -{ - bool ret = false; - AcquireSmcBufLock(&g_cmdData->smcLock); - - if (HmTestBit(idx, g_cmdData->outBitmap)) { - ret = true; - } - ReleaseSmcBufLock(&g_cmdData->smcLock); - return ret; -} - -static void ShowInBitmap(int *cmdIn, uint32_t len) -{ - uint32_t idx; - uint32_t in = 0; - char bitmap[MAX_SMC_CMD + 1]; - bool checkValue = (len != MAX_SMC_CMD || - g_cmdData == NULL); - - if (checkValue == true) { - return; - } - for (idx = 0; idx < MAX_SMC_CMD; idx++) { - if (HmTestBit(idx, g_cmdData->inBitmap)) { - bitmap[idx] = '1'; - cmdIn[in++] = idx; - } else { - bitmap[idx] = '0'; - } - } - bitmap[MAX_SMC_CMD] = '\0'; - tloge("inBitmap: %s\n", bitmap); -} - -static void ShowOutBitmap(int *cmdOut, uint32_t len) -{ - uint32_t idx; - uint32_t out = 0; - char bitmap[MAX_SMC_CMD + 1]; - bool checkValue = (len != MAX_SMC_CMD || - g_cmdData == NULL); - - if (checkValue == true) { - return; - } - for (idx = 0; idx < MAX_SMC_CMD; idx++) { - if (HmTestBit(idx, g_cmdData->outBitmap)) { - bitmap[idx] = '1'; - cmdOut[out++] = idx; - } else { - bitmap[idx] = '0'; - } - } - bitmap[MAX_SMC_CMD] = '\0'; - tloge("outBitmap: %s\n", bitmap); -} - -static void ShowDoingBitmap(void) -{ - uint32_t idx; - char bitmap[MAX_SMC_CMD + 1]; - - if (g_cmdData == NULL) { - return; - } - for (idx = 0; idx < MAX_SMC_CMD; idx++) { - if (HmTestBit(idx, g_cmdData->doingBitmap)) { - bitmap[idx] = '1'; - } else { - bitmap[idx] = '0'; - } - } - bitmap[MAX_SMC_CMD] = '\0'; - tloge("doingBitmap: %s\n", bitmap); -} - -void ShowCmdBitmapWithLock(void) -{ - if (g_cmdData == NULL) { - return; - } - AcquireSmcBufLock(&g_cmdData->smcLock); - ShowCmdBitmap(); - ReleaseSmcBufLock(&g_cmdData->smcLock); -} - -void ShowCmdBitmap(void) -{ - uint32_t idx; - int cmdIn[MAX_SMC_CMD]; - int cmdOut[MAX_SMC_CMD]; - bool checkValue = false; - - if (g_cmdData == NULL) { - return; - } - - checkValue = memset_s(cmdIn, sizeof(cmdIn), -1, sizeof(cmdIn)) || - memset_s(cmdOut, sizeof(cmdOut), -1, sizeof(cmdOut)); - if (checkValue) { - tloge("memset failed\n"); - return; - } - ShowInBitmap(cmdIn, MAX_SMC_CMD); - ShowDoingBitmap(); - ShowOutBitmap(cmdOut, MAX_SMC_CMD); - - tloge("cmdIn value:\n"); - for (idx = 0; idx < MAX_SMC_CMD; idx++) { - if (cmdIn[idx] == -1) { - break; - } - tloge("cmd[%d]: cmdId=%u, caPid=%u, devId = 0x%x, eventNr=%u, retVal=0x%x\n", - cmdIn[idx], - g_cmdData->in[cmdIn[idx]].cmdId, - g_cmdData->in[cmdIn[idx]].caPid, - g_cmdData->in[cmdIn[idx]].devFileId, - g_cmdData->in[cmdIn[idx]].eventNr, - g_cmdData->in[cmdIn[idx]].retVal); - } - - tloge("cmdOut value:\n"); - for (idx = 0; idx < MAX_SMC_CMD; idx++) { - if (cmdOut[idx] == -1) { - break; - } - tloge("cmd[%d]: cmdId=%u, caPid=%u, devId = 0x%x, eventNr=%u, retVal=0x%x\n", - cmdOut[idx], - g_cmdData->out[cmdOut[idx]].cmdId, - g_cmdData->out[cmdOut[idx]].caPid, - g_cmdData->out[cmdOut[idx]].devFileId, - g_cmdData->out[cmdOut[idx]].eventNr, - g_cmdData->out[cmdOut[idx]].retVal); - } -} - -static struct PendingEntry *InitPendingEntry(pid_t pid) -{ - struct PendingEntry *pe = NULL; - - pe = malloc(sizeof(*pe)); - if (ZERO_OR_NULL_PTR((unsigned long)(uintptr_t)pe)) { - tloge("alloc pe failed\n"); - return NULL; - } - if (memset_s(pe, sizeof(*pe), 0, sizeof(*pe)) != EOK) { - tloge("memset pe failed!.\n"); - free(pe); - return NULL; - } - atomic_set(&pe->users, 1); // init pe->users to 1 - pe->pid = pid; - init_waitqueue_head(&pe->wq); - atomic_set(&pe->run, 0); - INIT_LIST_HEAD(&pe->list); - spin_lock(&g_pendLock); - list_add_tail(&pe->list, &g_pendingHead); - spin_unlock(&g_pendLock); - return pe; -} - -struct PendingEntry *FindPendingEntry(pid_t pid) -{ - struct PendingEntry *pe = NULL; - - spin_lock(&g_pendLock); - list_for_each_entry(pe, &g_pendingHead, list) { - if (pe->pid == pid) { - atomic_inc(&pe->users); - spin_unlock(&g_pendLock); - return pe; - } - } - spin_unlock(&g_pendLock); - return NULL; -} - -void ForeachPendingEntry(void (*func)(struct PendingEntry *)) -{ - struct PendingEntry *pe = NULL; - - if (func == NULL) { - return; - } - spin_lock(&g_pendLock); - list_for_each_entry(pe, &g_pendingHead, list) { - func(pe); - } - spin_unlock(&g_pendLock); -} - -void PutPendingEntry(struct PendingEntry *pe) -{ - if (pe != NULL) { - if (atomic_dec_and_test(&pe->users)) { - free(pe); - } - } -} - -static void ReleasePendingEntry(struct PendingEntry *pe) -{ - spin_lock(&g_pendLock); - list_del(&pe->list); - spin_unlock(&g_pendLock); - PutPendingEntry(pe); -} - -static DECLARE_WAIT_QUEUE_HEAD(siqThWait); -static DECLARE_WAIT_QUEUE_HEAD(ipi_th_wait); -static atomic_t g_siqThRun; - -enum { - TYPE_CRASH_TA = 1, - TYPE_CRASH_TEE = 2, -}; - -enum SmcOpsExit { - SMC_OPS_NORMAL = 0x0, - SMC_OPS_SCHEDTO = 0x1, - SMC_OPS_START_SHADOW = 0x2, - SMC_OPS_START_FIQSHD = 0x3, - SMC_OPS_PROBE_ALIVE = 0x4, - SMC_OPS_TERMINATE = 0x5, - SMC_EXIT_NORMAL = 0x0, - SMC_EXIT_PREEMPTED = 0x1, - SMC_EXIT_SHADOW = 0x2, - SMC_EXIT_MAX = 0x3, -}; - -#define SHADOW_EXIT_RUN 0x1234dead - -typedef struct SmcCmdRet { - uint64_t exit; - uint64_t ta; - uint64_t target; -} SmcCmdRetT; - -static inline void SecretFill(SmcCmdRetT *ret, uint64_t exit, uint64_t ta, uint64_t target) -{ - if (ret != NULL) { - ret->exit = exit; - ret->ta = ta; - ret->target = target; - } -} - -int SigkillPending(LosTaskCB *tsk) -{ - if (tsk == NULL) { - tloge("tsk is null!\n"); - return 0; - } - - return OsSigIsMember(&tsk->sig.sigwaitmask, SIGKILL) || - OsSigIsMember(&tsk->sig.sigwaitmask, SIGUSR1); -} - -enum CmdState { - START, - KILLING, - KILLED, -}; - -#define CPU0_ONLY_MASK 0x0001 - -#if CONFIG_CPU_AFF_NR -static void SetCpuStrategy(UINT16 *oldMask) -{ - LosTaskCB *taskCB = OsCurrTaskGet(); - UINT16 newMask = CPU0_ONLY_MASK; - - *oldMask = taskCB->cpuAffiMask; - KthreadBindMask(taskCB, newMask); -} -#endif - -#if CONFIG_CPU_AFF_NR -static void RestoreCpu(UINT16 *oldMask) -{ - LosTaskCB *taskCB = OsCurrTaskGet(); - KthreadBindMask(taskCB, *oldMask); -} -#endif - -struct SmcParam { - uint32_t r0; - uint32_t r1; - uint32_t r2; - uint32_t r3; - uint32_t r4; - SmcCmdRetT *secret; - uint32_t cmd; - uint64_t ca; - uint32_t ta; - uint32_t exitReason; - uint32_t target; - enum CmdState state; - uint64_t ops; -}; - -static int DoSmpSmcSend(struct SmcParam *param) -{ - int ret; - if (param->secret != NULL && param->secret->exit == SMC_EXIT_PREEMPTED) { - param->r0 = param->cmd; - if (param->state == KILLING) { - param->state = KILLED; - param->r1 = SMC_OPS_TERMINATE; - param->r2 = param->ca; - } else { - param->r1 = SMC_OPS_SCHEDTO; - param->r2 = param->ca; - param->r3 = param->secret->ta; - param->r4 = param->secret->target; - } - } - int checkValue = param->ops == SMC_OPS_SCHEDTO || param->ops == SMC_OPS_START_FIQSHD; - if (param->secret != NULL && checkValue) { - param->r4 = param->secret->target; - } - ISB; - DSB; - - do { - __asm__ volatile( - "mov r0, %[fid]\n" - "mov r1, %[a1]\n" - "mov r2, %[a2]\n" - "mov r3, %[a3]\n" - ".arch_extension sec\n" - "smc #0\n" - "str r0, [%[re0]]\n" - "str r1, [%[re1]]\n" - "str r2, [%[re2]]\n" - "str r3, [%[re3]]\n" - : [fid] "+r" (param->r0), [a1] "+r" (param->r1), [a2] "+r" (param->r2), - [a3] "+r" (param->r3) - : [re0] "r" (&ret), [re1] "r" (¶m->exitReason), - [re2] "r" (¶m->ta), [re3] "r" (¶m->target) - : "r0", "r1", "r2", "r3"); - } while (0); - ISB; - DSB; - return ret; -} -static noinline int SmpSmcSend(uint32_t cmd, uint64_t ops, uint64_t ca, - SmcCmdRetT *secret, bool needKill) -{ - uint32_t ret = 0; - bool checkValue = false; -#if CONFIG_CPU_AFF_NR - UINT16 oldMask; -#endif - struct SmcParam param; - param.r0 = cmd; - param.r1 = ops; - param.r2 = ca; - param.r3 = 0; - param.r4 = 0; - param.exitReason = 0; - param.ta = 0; - param.target = 0; - param.state = START; - param.cmd = cmd; - param.ca = ca; - param.secret = secret; - param.ops = ops; - -RETRY: -#if CONFIG_CPU_AFF_NR - SetCpuStrategy(&oldMask); -#endif - - ret = DoSmpSmcSend(¶m); - - if (secret == NULL) { - return ret; - } - SecretFill(secret, param.exitReason, param.ta, param.target); - if (param.exitReason == SMC_EXIT_PREEMPTED) { - /* There's 2 ways to send a terminate cmd to kill a running TA, - * in current context or another. If send terminate in another - * context, may encounter concurrency problem, as terminate cmd - * is send but not process, the original cmd has finished. - * So we send the terminate cmd in current context. - */ - checkValue = needKill && SigkillPending(OsCurrTaskGet()) && param.state == START && - IsThreadReported(OsCurrTaskGet()->taskID); - if (checkValue == true) { - param.state = KILLING; - tloge("receive kill signal\n"); - } -#ifndef CONFIG_PREEMPT - /* yield cpu to avoid soft lockup */ - cond_resched(); -#endif - goto RETRY; - } -#if CONFIG_CPU_AFF_NR - RestoreCpu(&oldMask); -#endif - return ret; -} - -static uint32_t SendSmcCmd(uint32_t cmd, paddr_t cmdAddr, - uint32_t cmdType, uint8_t wait) -{ - register uint32_t r0 asm("r0") = cmd; - register uint32_t r1 asm("r1") = cmdAddr; - register uint32_t r2 asm("r2") = cmdType; - register uint32_t r3 asm("r3") = 0; - do { - __asm__ volatile( - ".ifnc %0, r0;.err;.endif;\n" - ".ifnc %1, r0;.err;.endif;\n" - ".ifnc %2, r1;.err;.endif;\n" - ".ifnc %3, r2;.err;.endif;\n" - ".ifnc %4, r3;.err;.endif;\n" - ".arch_extension sec\n" - "smc #0\n" - : "+r"(r0) - : "r"(r0), "r"(r1), "r"(r2), "r"(r3)); - } while (r0 == TSP_REQUEST && wait); - return r0; -} - -int RawSmcSend(uint32_t cmd, paddr_t cmdAddr, - uint32_t cmdType, uint8_t wait) -{ - uint32_t r0; - -#if (CONFIG_CPU_AFF_NR != 0) - UINT16 oldMask; - - SetCpuStrategy(&oldMask); -#endif - r0 = SendSmcCmd(cmd, cmdAddr, cmdType, wait); -#if (CONFIG_CPU_AFF_NR != 0) - RestoreCpu(&oldMask); -#endif - return r0; -} - -void SiqDump(paddr_t mode) -{ - (void)RawSmcSend(TSP_REE_SIQ, mode, 0, false); - DoCmdNeedArchivelog(); -} - -static int SiqThreadFn(UINTPTR arg, int len) -{ - int ret; - - while (1) { - ret = wait_event_interruptible(siqThWait, - atomic_read(&g_siqThRun)); - if (ret) { - tloge("wait_event_interruptible failed!\n"); - return -EINTR; - } - atomic_set(&g_siqThRun, 0); - SiqDump((paddr_t)(1)); // set this addr to 1 - } -} - -static void CmdResultCheck(TcNsSmcCmd *cmd) -{ - bool checkValue = false; -#ifdef SECURITY_AUTH_ENHANCE - checkValue = (cmd->retVal == TEEC_SUCCESS) && - (VerifyChksum(cmd) != TEEC_SUCCESS); - if (checkValue == true) { - cmd->retVal = TEEC_ERROR_GENERIC; - tloge("VerifyChksum failed.\n"); - } -#endif - checkValue = cmd->retVal == TEEC_PENDING || - cmd->retVal == TEEC_PENDING2; - - if (checkValue == true) { - tlogd("wakeup command %u\n", cmd->eventNr); - } - if (cmd->retVal == TEE_ERROR_TAGET_DEAD) { - tloge("error smc call: ret = %x and cmd.errOrigin=%x\n", - cmd->retVal, cmd->errOrigin); -#ifdef CONFIG_TEELOG - CmdMonitorTaCrash(TYPE_CRASH_TA); -#endif - } else if (cmd->retVal == TEE_ERROR_AUDIT_FAIL) { - tloge("error smc call: ret = %x and cmd.errOrigin=%x\n", - cmd->retVal, cmd->errOrigin); -#ifdef SECURITY_AUTH_ENHANCE - tloge("error smc call: status = %x and cmd.errOrigin=%x\n", - cmd->eventindex, cmd->errOrigin); -#endif - } -} - -static int ShadowWoPm(const void *arg, const WoPmParams *params) -{ - uint32_t r0 = TSP_REQUEST; - uint32_t r1 = SMC_OPS_START_SHADOW; - uint32_t r2 = OsCurrTaskGet()->taskID; - uint32_t r3 = 0; - uint32_t r4 = *(uint32_t *)arg; - - if (*(params->exitReason) == SMC_EXIT_PREEMPTED) { - r0 = TSP_REQUEST; - r1 = SMC_OPS_SCHEDTO; - r2 = OsCurrTaskGet()->taskID; - r3 = *(params->ta); - r4 = *(params->target); - } else if (*(params->exitReason) == SMC_EXIT_NORMAL) { - r0 = TSP_REQUEST; - r1 = SMC_OPS_SCHEDTO; - r2 = OsCurrTaskGet()->taskID; - r3 = 0; - r4 = 0; - if (*(params->nIdled) > IDLED_COUNT) { - *(params->nIdled) = 0; - r1 = SMC_OPS_PROBE_ALIVE; - } - } - ISB; - DSB; - tlogd("%s: [cpu %d] r0=%x r1=%x r2=%x r3=%x r4=%x\n", __func__, - RawSmpProcessorId(), r0, r1, r2, r3, r4); - do { - __asm__ volatile( - "mov r0, %[fid]\n" - "mov r1, %[a1]\n" - "mov r2, %[a2]\n" - "mov r3, %[a3]\n" - "mov r4, %[a4]\n" - ".arch_extension sec\n" - "smc #0\n" - "str r0, [%[re0]]\n" - "str r1, [%[re1]]\n" - "str r2, [%[re2]]\n" - "str r3, [%[re3]]\n" - :[fid] "+r"(r0), [a1] "+r"(r1), [a2] "+r"(r2), - [a3] "+r"(r3), [a4] "+r"(r4) - :[re0] "r"(params->ret), [re1] "r"(params->exitReason), - [re2] "r"(params->ta), [re3] "r"(params->target) - : "r0", "r1", "r2", "r3"); - } while (0); - - ISB; - DSB; - - return 0; -} - -static int CheckShadowParam(UINTPTR arg, int len, struct PendingEntry **pe) -{ - if (arg == 0) { - return -ENOMEM; - } - if (len != sizeof(uint64_t)) { - free((void *)arg); - return -ENOMEM; - } - - *pe = InitPendingEntry(GetCurrentPid()); - if (*pe == NULL) { - tloge("init pending entry failed\n"); - free((void *)arg); - return -ENOMEM; - } - - ISB; - DSB; - return 0; -} - -static int ShadowThreadFn(UINTPTR arg, int len) -{ - uint64_t ret = 0; - uint64_t exitReason = SMC_EXIT_MAX; - uint64_t ta = 0; - uint64_t target = 0; - int nPreempted = 0; - int nIdled = 0; - int retVal; - struct PendingEntry *pe = NULL; - int rc; - WoPmParams params = {&nIdled, &ret, &exitReason, &ta, &target}; - - ret = CheckShadowParam(arg, len, &pe); - if (ret) { - return ret; - } - -RETRY_WO_PM: - retVal = ShadowWoPm((void *)arg, ¶ms); - if (retVal == -1) { - goto CLEAN_WO_PM; - } - tlogd("shadow thread return %lld\n", exitReason); - if (exitReason == SMC_EXIT_PREEMPTED) { - nIdled = 0; - if (++nPreempted > PREEMPT_COUNT) { - tlogi("%s: retry 10K times on CPU%d\n", __func__, RawSmpProcessorId()); - nPreempted = 0; - } - goto RETRY_WO_PM; - } else if (exitReason == SMC_EXIT_NORMAL) { - nPreempted = 0; - long long timeout = HZ * (long)(HZ_COUNT + ((uint8_t)GetCurrentPid() & LOW_BYTE)); - rc = wait_event_interruptible_timeout(pe->wq, atomic_read(&pe->run), (long)timeout); - if (!rc) { - nIdled++; - } - if (atomic_read(&pe->run) == SHADOW_EXIT_RUN) { - tlogd("shadow thread work quit, be killed\n"); - goto CLEAN_WO_PM; - } else { - atomic_set(&pe->run, 0); - goto RETRY_WO_PM; - } - } else if (exitReason == SMC_EXIT_SHADOW) { - tlogd("shadow thread exit, it self\n"); - } else { - tlogd("shadow thread exit with unknown code %ld\n", (long)exitReason); - } - -CLEAN_WO_PM: - free((void *)arg); - ReleasePendingEntry(pe); - return retVal; -} - -static void ShadowWorkFunc(struct work_struct *work) -{ - LosTaskCB *shadowThread = NULL; - if (work == NULL) { - return; - } - struct ShadowWork *sWork = - container_of(work, struct ShadowWork, work); - uint64_t *targetArg = malloc(sizeof(uint64_t)); - - if (ZERO_OR_NULL_PTR((unsigned long)(uintptr_t)targetArg)) { - tloge("%s: malloc(8 bytes) failed\n", __func__); - return; - } - if (memset_s(targetArg, sizeof(uint64_t), - 0, sizeof(uint64_t)) != EOK) { - tloge("memset targetArg failed!.\n"); - free(targetArg); - return; - } - *targetArg = sWork->target; - - char shadowName[OS_TCB_NAME_LEN] = {0}; - int ret = sprintf_s(shadowName, OS_TCB_NAME_LEN, "shadow_th/%lu", g_shadowThreadId++); - if (ret < 0) { - free(targetArg); - return; - } - shadowThread = KthreadRun(ShadowThreadFn, targetArg, sizeof(uint64_t), shadowName); - if (IS_ERR_OR_NULL(shadowThread)) { - free(targetArg); - tloge("couldn't create shadowThread %ld\n", - PTR_ERR(shadowThread)); - return; - } - tlogd("%s: create shadow thread %lu for target %llx\n", - __func__, g_shadowThreadId, *targetArg); - WakeUpProcess(shadowThread); -} - -static int ProcSmcWakeupCa(pid_t ca, int which) -{ - if (ca == 0) { - tlogw("wakeup for ca = 0\n"); - } else { - struct PendingEntry *pe = FindPendingEntry(ca); - - if (pe == NULL) { - tloge("invalid ca pid=%d for pending entry\n", (int)ca); - return -1; - } - atomic_set(&pe->run, which); - wake_up(&pe->wq); - tlogd("wakeup pending thread %ld\n", (long)ca); - PutPendingEntry(pe); - } - return 0; -} - -void WakeupPe(struct PendingEntry *pe) -{ - if (pe != NULL) { - atomic_set(&pe->run, 1); - wake_up(&pe->wq); - } -} - -int SmcWakeupBroadcast(void) -{ - ForeachPendingEntry(WakeupPe); - return 0; -} - -int SmcWakeupCa(pid_t ca) -{ - return ProcSmcWakeupCa(ca, 1); // set pe->run to 1 -} - -int SmcShadowExit(pid_t ca) -{ - return ProcSmcWakeupCa(ca, SHADOW_EXIT_RUN); -} - -void FiqShadowWorkFunc(uint64_t target) -{ - SmcCmdRetT secret = { SMC_EXIT_MAX, 0, target }; - - (void)SmpSmcSend(TSP_REQUEST, SMC_OPS_START_FIQSHD, GetCurrentPid(), - &secret, false); - return; -} - -int SmcQueueShadowWorker(uint64_t target) -{ - struct ShadowWork shadowWork; - INIT_WORK_ONSTACK(&shadowWork.work, ShadowWorkFunc); - shadowWork.target = target; - - /* Run work on CPU 0 */ - queue_work(g_ipiHelperWq, &shadowWork.work); - flush_work(&shadowWork.work); - return 0; -} - -static int SmcOpsNormal(enum CmdReuse *cmdUsage, int *cmdIndex, - int *lastIndex, struct PendingEntry *pe, const TcNsSmcCmd *cmd) -{ - if (*cmdUsage == RESEND) { - if (ReuseSmcInEntry(*cmdIndex)) { - tloge("reuse smc entry failed\n"); - ReleaseSmcEntry(*cmdIndex); - ReleasePendingEntry(pe); - return -1; - } - } else { - *cmdIndex = OccupyFreeSmcInEntry(cmd); - if (*cmdIndex == -1) { - tloge("there's no more smc entry\n"); - ReleasePendingEntry(pe); - return -1; - } - } - if (*cmdUsage != CLEAR) { - *cmdIndex = *lastIndex; - *cmdUsage = CLEAR; - } else { - *lastIndex = *cmdIndex; - } - tlogd("submit new cmd: cmd.ca=%u cmd-id=%x ev-nr=%u cmd-index=%u last-index=%d\n", - cmd->caPid, cmd->cmdId, - g_cmdData->in[*cmdIndex].eventNr, *cmdIndex, - *lastIndex); - return 0; -} - -static int SmpSmcSendCmdDone(int cmdIndex, TcNsSmcCmd *cmd, - TcNsSmcCmd *in) -{ - CmdResultCheck(cmd); - switch (cmd->retVal) { - case TEEC_PENDING2: { - unsigned int agentId = cmd->agentId; - /* If the agent does not exist post - * the answer right back to the TEE - */ - if (AgentProcessWork(cmd, agentId) != TEEC_SUCCESS) { - tloge("agent process work failed\n"); - } - return -1; - } - case TEE_ERROR_TAGET_DEAD: - case TEEC_PENDING: - /* just copy out, and let out to proceed */ - default: - if (memcpy_s(in, sizeof(*in), - cmd, sizeof(*cmd)) != EOK) { - tloge("memcpy_s failed,%s line:%d", __func__, __LINE__); - cmd->retVal = -1; - } - break; - } - - return 0; -} - -#define SYM_NAME_LEN_MAX 16 -#define SYM_NAME_LEN_1 7 -#define SYM_NAME_LEN_2 4 -#define CRASH_REG_NUM 3 -#define LOW_FOUR_BITE 4 - -typedef union { - uint64_t crashReg[CRASH_REG_NUM]; - struct { - uint8_t haltReason : LOW_FOUR_BITE; - uint8_t app : LOW_FOUR_BITE; - char symName[SYM_NAME_LEN_1]; - uint16_t off; - uint16_t size; - uint32_t far; - uint32_t fault; - union { - char symNameAppend[SYM_NAME_LEN_2]; - uint32_t elr; - }; - } CrashMsg; -} CrashInf; - -static void PrintCrashMsg(CrashInf *crashInfo) -{ - static const char *teeCriticalApp[] = { - "gtask", - "teesmcmgr", - "hmsysmgr", - "hmfilemgr", - "platdrv", - "kernel" - }; - int appNum = sizeof(teeCriticalApp) / sizeof(teeCriticalApp[0]); - const char *crashAppName = "NULL"; - uint16_t off = crashInfo->CrashMsg.off; - int appIndex = crashInfo->CrashMsg.app & LOW_BYTE; - int haltReason = crashInfo->CrashMsg.haltReason; - int sret; - - crashInfo->CrashMsg.off = 0; // for end of symName - - if (appIndex >= 0 && appIndex < appNum) { - crashAppName = teeCriticalApp[appIndex]; - } else { - tloge("index error: %x\n", crashInfo->CrashMsg.app); - } - - // kernel - if (appIndex == (appNum - 1)) { - tloge("====crash app:%s user_sym:%s kernel crash off/size: <0x%x/0x%x>\n", - crashAppName, crashInfo->CrashMsg.symName, - off, crashInfo->CrashMsg.size); - tloge("====crash haltReason: 0x%x far:0x%x fault:0x%x elr:0x%x (ret_ip: 0x%llx)\n", - haltReason, crashInfo->CrashMsg.far, - crashInfo->CrashMsg.fault, crashInfo->CrashMsg.elr, - crashInfo->crashReg[CRASH_RET_IP]); - } else { // user app - char syms[SYM_NAME_LEN_MAX] = {0}; - - sret = memcpy_s(syms, SYM_NAME_LEN_MAX, - crashInfo->CrashMsg.symName, SYM_NAME_LEN_1); - if (sret != EOK) { - tloge("memcpy symName failed!\n"); - } - sret = memcpy_s(syms + SYM_NAME_LEN_1, - SYM_NAME_LEN_MAX - SYM_NAME_LEN_1, - crashInfo->CrashMsg.symNameAppend, SYM_NAME_LEN_2); - if (sret != EOK) { - tloge("memcpy symNameAppend failed!\n"); - } - tloge("====crash app:%s user_sym:%s + <0x%x/0x%x>\n", - crashAppName, syms, off, crashInfo->CrashMsg.size); - tloge("====crash far:0x%x fault:%x\n", - crashInfo->CrashMsg.far, crashInfo->CrashMsg.fault); - } -} - -static int SmpSmcSendProcess(TcNsSmcCmd *cmd, uint64_t ops, - SmcCmdRetT *cmdRet, int cmdIndex) -{ - int ret; - - ret = SmpSmcSend(TSP_REQUEST, ops, GetCurrentPid(), cmdRet, true); - tlogd("SmpSmcSend ret = %x, cmdRet.exit=%ld, cmdIndex=%d\n", - ret, (long)cmdRet->exit, cmdIndex); - ISB; - DSB; - if (ret == (int)TSP_CRASH) { - CrashInf crashInfo; - crashInfo.crashReg[CRASH_RET_EXIT] = cmdRet->exit; - crashInfo.crashReg[CRASH_RET_TA] = cmdRet->ta; - crashInfo.crashReg[CRASH_RET_IP] = cmdRet->target; - - tloge("TEEOS has crashed!\n"); - PrintCrashMsg(&crashInfo); - - g_sysCrash = 1; -#ifdef CONFIG_TEELOG - CmdMonitorTaCrash(TYPE_CRASH_TEE); -#endif - cmd->retVal = -1; - return -1; - } - - return 0; -} - -static int InitForSmcSend(TcNsSmcCmd *in, struct PendingEntry **pe, - TcNsSmcCmd *cmd, bool reuse) -{ - if (in == NULL) { - tloge("Bad params\n"); - return -1; - } - - *pe = InitPendingEntry(GetCurrentPid()); - if (*pe == NULL) { - tloge("init pending entry failed\n"); - return -ENOMEM; - } - in->caPid = GetCurrentPid(); - if (!reuse) { - if (memcpy_s(cmd, sizeof(*cmd), in, sizeof(*in))) { - tloge("memcpy_s failed,%s line:%d", __func__, __LINE__); - ReleasePendingEntry(*pe); - return -1; - } - } - return 0; -} - -#define GOTO_RESLEEP 1 -#define GOTO_RETRY_WITH_CMD 2 -#define GOTO_RETRY 3 -#define GOTO_CLEAN 4 - -static int CheckIsCaKilled(int cmdIndex, uint64_t *ops) -{ - /* if CA has not been killed */ - if (SigkillPending(OsCurrTaskGet()) == 0) { - if (!IsCmdWorkingDone(cmdIndex)) { - return GOTO_RESLEEP; - } else { - tloge("cmd done, may miss a spi!\n"); - ShowCmdBitmapWithLock(); - } - } else { - /* if CA killed, send terminate cmd */ - *ops = SMC_OPS_TERMINATE; - tloge("CA is killed, send terminate!\n"); - return GOTO_RETRY_WITH_CMD; - } - return 0; -} - -struct CmdPram { - TcNsSmcCmd *cmd; - int cmdIndex; - enum CmdReuse *cmdUsage; -}; - -static int CmdDoneProcess(TcNsSmcCmd *in, struct CmdPram *cmdParam, uint64_t *ops) -{ - if ((in == NULL) || (cmdParam == NULL) || (ops == NULL)) { - return 0; - } - - if (CopySmcOutEntry(cmdParam->cmdIndex, cmdParam->cmd, cmdParam->cmdUsage)) { - cmdParam->cmd->retVal = -1; - return GOTO_CLEAN; - } - - if (SmpSmcSendCmdDone(cmdParam->cmdIndex, cmdParam->cmd, in) == -1) { - *ops = SMC_OPS_NORMAL; - /* cmd will be reused */ - return GOTO_RETRY; - } - - return 0; -} - -static int RetryWithFillCmdProcess(TcNsSmcCmd *in, struct CmdPram *cmdParam, struct PendingEntry *pe, uint64_t *ops) -{ - SmcCmdRetT cmdRet = {0}; - - if ((in == NULL) || (cmdParam == NULL) || (pe == NULL) || (ops == NULL)) { - return 0; - } - - while (1) { - tlogd("SmpSmcSend start cmdId = %u, ca = %u\n", cmdParam->cmd->cmdId, cmdParam->cmd->caPid); - if (SmpSmcSendProcess(cmdParam->cmd, *ops, &cmdRet, cmdParam->cmdIndex) == -1) { - return GOTO_CLEAN; - } - if (IsCmdWorkingDone(cmdParam->cmdIndex)) { - return CmdDoneProcess(in, cmdParam, ops); - } - - if (cmdRet.exit != SMC_EXIT_NORMAL) { - tloge("invalid cmd work state\n"); - cmdParam->cmd->retVal = -1; - return GOTO_CLEAN; - } - /* task pending exit */ - tlogd("goto sleep, exitReason=%lld\n", cmdRet.exit); -RESLEEP: - if (wait_event_interruptible_timeout(pe->wq, atomic_read(&pe->run), - (long)(RESLEEP_TIMEOUT * HZ)) == 0) { - tlogd("CA wait event for %d s\n", RESLEEP_TIMEOUT); - int ret = CheckIsCaKilled(cmdParam->cmdIndex, ops); - if (ret == GOTO_RESLEEP) { - goto RESLEEP; - } else if (ret == GOTO_RETRY_WITH_CMD) { - continue; - } - } - atomic_set(&pe->run, 0); - - if (IsCmdWorkingDone(cmdParam->cmdIndex)) { - tlogd("cmd is done\n"); - return CmdDoneProcess(in, cmdParam, ops); - } - *ops = SMC_OPS_SCHEDTO; - } - - return 0; -} - -static int SmpSmcSendFunc(TcNsSmcCmd *in, uint32_t cmdType, - bool reuse) -{ - int cmdIndex = 0; - int lastIndex = 0; - TcNsSmcCmd cmd = { {0}, 0 }; - struct PendingEntry *pe = NULL; - uint64_t ops; - enum CmdReuse cmdUsage = CLEAR; - int ret; - bool check = false; - - if (InitForSmcSend(in, &pe, &cmd, reuse) != 0) { - tloge(KERN_INFO "InitForSmcSend fail\n"); - return -1; - } - if (reuse) { - lastIndex = cmdIndex = in->eventNr; - cmdUsage = RESEND; - } - ops = SMC_OPS_NORMAL; - -RETRY: - if ((ops == SMC_OPS_NORMAL) && - SmcOpsNormal(&cmdUsage, &cmdIndex, &lastIndex, pe, &cmd) == -1) { - tloge(KERN_INFO "SmcOpsNormal fail\n"); - return -1; - } - - struct CmdPram cmdParam; - cmdParam.cmd = &cmd; - cmdParam.cmdIndex = cmdIndex; - cmdParam.cmdUsage = &cmdUsage; - - ret = RetryWithFillCmdProcess(in, &cmdParam, pe, &ops); - if (ret == GOTO_CLEAN) { - goto CLEAN; - } else if (ret == GOTO_RETRY) { - goto RETRY; - } - -CLEAN: - check = (cmdUsage != CLEAR && cmd.retVal != TEEC_PENDING); - if (check == true) { - ReleaseSmcEntry(cmdIndex); - } - ReleasePendingEntry(pe); - return cmd.retVal; -} - -static int SmcSvcThreadFn(UINTPTR arg, int len) -{ - while (!KthreadShouldStop()) { - TcNsSmcCmd smcCmd = { {0}, 0 }; - int ret; - - smcCmd.globalCmd = true; - smcCmd.cmdId = GLOBAL_CMD_ID_SET_SERVE_CMD; - ret = SmpSmcSendFunc(&smcCmd, - TC_NS_CMD_TYPE_NS_TO_SECURE, false); - tlogd("smc svc return 0x%x\n", ret); - } - tloge("smc_svc_thread stop ...\n"); - return 0; -} - -void WakeupTcSiq(void) -{ - atomic_set(&g_siqThRun, 1); // init g_siqThRun to 1 - wake_up_interruptible(&siqThWait); -} -/* - * This function first power on crypto cell, then send smc cmd to trustedcore. - * After finished, power off crypto cell. - */ -static int ProcTcNsSmc(TcNsSmcCmd *cmd, bool reuse) -{ - int ret; - - if (g_sysCrash) { - tloge("ERROR: sys crash happened!!!\n"); - return TEEC_ERROR_GENERIC; - } - if (cmd == NULL) { - tloge("invalid cmd\n"); - return TEEC_ERROR_GENERIC; - } - tlogd(KERN_INFO "***TC_NS_SMC call start on cpu %d ***\n", - RawSmpProcessorId()); - CmdMonitorLog(cmd); - ret = SmpSmcSendFunc(cmd, TC_NS_CMD_TYPE_NS_TO_SECURE, reuse); - CmdMonitorLogend(); - return ret; -} - -int TcNsSmc(TcNsSmcCmd *cmd) -{ - return ProcTcNsSmc(cmd, false); -} - -int TcNsSmcWithNoNr(TcNsSmcCmd *cmd) -{ - return ProcTcNsSmc(cmd, true); -} - -static void SmcWorkNoWait(uint32_t type) -{ - (void)RawSmcSend(TSP_REQUEST, g_cmdPhys, type, true); -} - -static void SmcWorkSetCmdBuffer(struct work_struct *work) -{ - (void)work; - SmcWorkNoWait(TC_NS_CMD_TYPE_SECURE_CONFIG); -} - -static void SmcWorkInitSecondaryCpus(struct work_struct *work) -{ - (void)work; - SmcWorkNoWait(TC_NS_CMD_TYPE_NS_TO_SECURE); -} - -static int SmcSetCmdBuffer(void) -{ - struct work_struct work; - - INIT_WORK_ONSTACK(&work, SmcWorkSetCmdBuffer); - /* Run work on CPU 0 */ - ScheduleWorkOn(0, &work); - flush_work(&work); - tlogd("smc set cmd buffer done\n"); - return 0; -} - -static int SmcInitSecondaryCpus(void) -{ - unsigned int i; - struct work_struct work; - - INIT_WORK_ONSTACK(&work, SmcWorkInitSecondaryCpus); - /* Run work on all secondary cpus */ - for (i = 1; i < LOSCFG_KERNEL_CORE_NUM; i++) { -#if CONFIG_CPU_AFF_NR - if (i >= CONFIG_CPU_AFF_NR) { - break; - } -#endif - ScheduleWorkOn((int)i, &work); - flush_work(&work); - tlogd("init secondary cpu %u done\n", i); - } - return 0; -} - -#ifdef SECURITY_AUTH_ENHANCE -#define ALIGN_BIT 0x3 - -static void FreeRootKey(void) -{ - if (memset_s((void *)g_sessionRootKey, sizeof(*g_sessionRootKey), - 0, sizeof(*g_sessionRootKey)) != EOK) { - tloge("memset mem failed\n"); - } - free(g_sessionRootKey); - g_sessionRootKey = NULL; -} - -static int GetSessionRootKey(void) -{ - int ret; - uint32_t *buffer = (uint32_t *)(g_cmdData->in); -#ifdef CONFIG_ARM64 - if (buffer == NULL || ((uint64_t)(uintptr_t)buffer & ALIGN_BIT)) { -#else - if (buffer == NULL || ((uint32_t)(uintptr_t)buffer & ALIGN_BIT)) { -#endif - tloge("Session root key must be 4bytes aligned\n"); - return -EFAULT; - } - g_sessionRootKey = calloc(1, sizeof(*g_sessionRootKey)); - if (ZERO_OR_NULL_PTR((unsigned long)(uintptr_t)g_sessionRootKey)) { - tloge("No memory to store session root key\n"); - return -ENOMEM; - } - if (memcpy_s(g_sessionRootKey, sizeof(*g_sessionRootKey), - (void *)(buffer + 1), sizeof(*g_sessionRootKey))) { - tloge("Copy session root key from TEE failed\n"); - ret = -EFAULT; - goto FREE_MEM; - } - if (memset_s((void *)(g_cmdData->in), sizeof(g_cmdData->in), - 0, sizeof(g_cmdData->in))) { - tloge("Clean the command buffer failed\n"); - ret = -EFAULT; - goto FREE_MEM; - } - return 0; -FREE_MEM: - FreeRootKey(); - return ret; -} -#endif - -static int SmcInitDataCmdData(void) -{ - g_cmdData = (TcNsSmcQueue *)GetPhyPage(); - if (g_cmdData == NULL) { - return -ENOMEM; - } - if (memset_s(g_cmdData, sizeof(TcNsSmcQueue), 0, sizeof(TcNsSmcQueue))) { - FreePhyPage(g_cmdData); - g_cmdData = NULL; - return -ENOMEM; - } - g_cmdPhys = LOS_PaddrQuery(g_cmdData); - return 0; -} - -int SmcInitData(void) -{ - int ret = SmcInitDataCmdData(); - if (ret) { - return ret; - } - /* Send the allocated buffer to TrustedCore for init */ - if (SmcSetCmdBuffer()) { - ret = -EINVAL; - goto FREE_MEM; - } - if (SmcInitSecondaryCpus()) { - ret = -EINVAL; - goto FREE_MEM; - } -#ifdef SECURITY_AUTH_ENHANCE - if (GetSessionRootKey()) { - ret = -EFAULT; - goto FREE_MEM; - } -#endif - - g_siqThread = KthreadRun(SiqThreadFn, NULL, 0, "siqthread/0"); - if (unlikely(IS_ERR_OR_NULL(g_siqThread))) { - pr_err("couldn't create siqthread %ld\n", - PTR_ERR(g_siqThread)); - ret = (int)PTR_ERR(g_siqThread); - goto FREE_MEM; - } - - g_ipiHelperWq = create_workqueue("ipihelper"); - if (g_ipiHelperWq == NULL) { - tloge("couldn't create workqueue.\n"); - ret = -ENOMEM; - goto FREE_SIQ_WORKER; - } - - WakeUpProcess(g_siqThread); - InitCmdMonitor(); - INIT_LIST_HEAD(&g_pendingHead); - spin_lock_init(&g_pendLock); - return 0; - -FREE_SIQ_WORKER: - KthreadStop(g_siqThread); - g_siqThread = NULL; -FREE_MEM: - FreePhyPage(g_cmdData); - g_cmdData = NULL; -#ifdef SECURITY_AUTH_ENHANCE - if (!IS_ERR_OR_NULL(g_sessionRootKey)) { - FreeRootKey(); - } -#endif - return ret; -} - -int InitSmcSvcThread(void) -{ - g_smcSvcThread = KthreadRun(SmcSvcThreadFn, NULL, 0, "smc_svc_thread"); - if (unlikely(IS_ERR_OR_NULL(g_smcSvcThread))) { - tloge("couldn't create smc_svc_thread %ld\n", PTR_ERR(g_smcSvcThread)); - return PTR_ERR(g_smcSvcThread); - } - WakeUpProcess(g_smcSvcThread); - return 0; -} - -void SmcFreeData(void) -{ - FreePhyPage(g_cmdData); - g_cmdData = NULL; - if (!IS_ERR_OR_NULL(g_smcSvcThread)) { - KthreadStop(g_smcSvcThread); - g_smcSvcThread = NULL; - } -#ifdef SECURITY_AUTH_ENHANCE - if (!IS_ERR_OR_NULL(g_sessionRootKey)) { - FreeRootKey(); - } -#endif -} - diff --git a/tzdriver/src/tc_client_driver.c b/tzdriver/src/tc_client_driver.c deleted file mode 100644 index e6b7adc..0000000 --- a/tzdriver/src/tc_client_driver.c +++ /dev/null @@ -1,1823 +0,0 @@ -/* - * Copyright (c) 2013-2019 Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020-2021 Huawei Device Co., Ltd. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "tc_client_driver.h" -#include "agent.h" -#include "gp_ops.h" -#include "mailbox_mempool.h" -#include "mem.h" -#include "smc.h" -#include "tc_client_sub_driver.h" -#include "tc_ns_log.h" -#include "teek_client_constants.h" -#include "teek_client_type.h" -#include "tz_spi_notify.h" -#include "tzdebug.h" -#include "tzdriver_compat.h" - -struct workqueue_struct *g_tzdriverWq = NULL; - -#define TEEC_PARAM_TYPES(param0_type, param1_type, param2_type, param3_type) \ - (((param3_type) << 12) | ((param2_type) << 8) | \ - ((param1_type) << 4) | (param0_type)) - -#define TEEC_PARAM_TYPE_GET(paramTypes, index) \ - (((paramTypes) >> ((index) << 2)) & 0x0F) - -// record device_file count -static unsigned int g_deviceFileCnt = 1; -static DEFINE_MUTEX(g_deviceFileCntLock); - -static LosTaskCB *g_teecdTask = NULL; -// dev node list and itself has mutex to avoid race -struct TcNsDevList g_tcNsDevList; - -// record all service node and need mutex to avoid race -struct list_head g_serviceList; -DEFINE_MUTEX(g_serviceListLock); - -#define TEECD_CERT_INDEX 0 -// teecd must set 0 in g_arrayCertNativeVendor -static const unsigned char g_arrayCertNativeVendor[][SHA256_DIGEST_LENGTH] = { - /* /vendor/bin/teecd0 */ - {0x99, 0xa2, 0xf1, 0xb3, 0xa3, 0x5f, 0x3f, 0x11, 0x8b, 0x33, 0xc1, 0x7e, 0xb9, 0xe8, 0x53, 0xbe, - 0x88, 0xf0, 0xc4, 0x6a, 0xf2, 0x7e, 0x72, 0x6e, 0x91, 0xb7, 0x59, 0xf0, 0x73, 0x9c, 0x93, 0xa5}, - - /* /vendor/bin/teec_hello0 */ - {0x9a, 0xab, 0xac, 0x19, 0xaa, 0xb2, 0xeb, 0xf4, 0x99, 0x11, 0x94, 0x15, 0xee, 0xb0, 0x03, 0x09, - 0xd6, 0xe8, 0xfe, 0xe9, 0x32, 0x37, 0x48, 0xfd, 0x2b, 0xf2, 0x2c, 0x78, 0x74, 0xd6, 0xc3, 0x9c}, - - /* /vendor/bin/tee_test_mem0 */ - {0x44, 0x7c, 0x8f, 0xc2, 0xa1, 0x1e, 0xfd, 0xab, 0x21, 0x63, 0x0e, 0xf8, 0x7d, 0x0b, 0xce, 0x06, - 0x05, 0x7f, 0x4a, 0xa8, 0x14, 0x17, 0x0f, 0xef, 0xa6, 0xa5, 0x77, 0x6c, 0xfe, 0xca, 0x4a, 0x8e}, - - /* /vendor/bin/tee_test_sess0 */ - {0xa0, 0xe4, 0x1b, 0x61, 0x8c, 0xd5, 0xf4, 0x4c, 0xec, 0x29, 0x03, 0xcd, 0x2f, 0xce, 0x28, 0xa7, - 0x67, 0xba, 0x3a, 0x10, 0x20, 0xd7, 0x95, 0x2b, 0x41, 0xaf, 0x47, 0x7c, 0x3d, 0xed, 0xce, 0xa4}, - - /* /vendor/bin/tee_test_invoke0 */ - {0xb5, 0x4e, 0x9d, 0x7b, 0x42, 0x10, 0x63, 0xcc, 0x4b, 0x7b, 0x16, 0x7d, 0xf6, 0xfe, 0xa8, 0x8e, - 0x6f, 0xca, 0x1b, 0xf1, 0x6a, 0xff, 0xed, 0xfd, 0xee, 0x09, 0xed, 0xbb, 0x18, 0x13, 0x75, 0x02}, - - /* /vendor/bin/tee_test_ut0 */ - {0x45, 0x71, 0xd9, 0x4b, 0x5b, 0xc7, 0xc1, 0x29, 0x2f, 0x9f, 0x46, 0xf2, 0x92, 0xef, 0xd5, 0x44, - 0xda, 0xb4, 0x51, 0xfb, 0x75, 0xa4, 0xc7, 0x4f, 0x8d, 0x34, 0xca, 0x5e, 0x27, 0xa6, 0x08, 0x8c}, - - /* /vendor/bin/tee_test_ca0 */ - {0xe9, 0x16, 0xde, 0x3f, 0x62, 0x27, 0x5b, 0x12, 0x04, 0x39, 0x9c, 0xc9, 0xf0, 0x34, 0x1f, 0xee, - 0xf0, 0x1a, 0x66, 0x31, 0xa9, 0xbf, 0x7d, 0x14, 0x30, 0x3d, 0xae, 0xe1, 0xb3, 0x07, 0xb9, 0x54}, - - /* /vendor/bin/tee_test_agent0 */ - {0x20, 0x6f, 0x1c, 0x54, 0xd5, 0x5f, 0xa8, 0xa8, 0x88, 0x56, 0xc4, 0x0c, 0xc3, 0xf9, 0x9c, 0x9a, - 0xc3, 0x40, 0x86, 0x13, 0x61, 0xb0, 0xcf, 0x69, 0xdd, 0xb8, 0x6c, 0x1e, 0x53, 0xb4, 0x77, 0x55}, - - /* /vendor/bin/tee_test_client_api0 */ - {0xae, 0xe9, 0x12, 0x90, 0x23, 0x9b, 0x99, 0x01, 0x99, 0x1d, 0xa5, 0x22, 0xe0, 0x26, 0x06, 0x12, - 0x2b, 0xad, 0x5e, 0xaf, 0x34, 0xbf, 0x1a, 0x16, 0x3e, 0x75, 0x97, 0x65, 0xe6, 0x39, 0x9d, 0xf3}, -}; - -typedef struct { - TcNsDevFile *devFile; - char *fileBuffer; - unsigned int fileSize; -} LoadImageParams; - -mutex_t *GetServiceListLock(void) -{ - return &g_serviceListLock; -} - -struct TcNsDevList *GetTcNsDevList(void) -{ - return &g_tcNsDevList; -} - -struct list_head *GetServiceList(void) -{ - return &g_serviceList; -} - -static int GetMemSpace(char **caCert, char **tpath) -{ - *tpath = malloc(MAX_PATH_SIZE); - if (ZERO_OR_NULL_PTR((unsigned long)(uintptr_t)(*tpath))) { - tloge("tpath malloc fail\n"); - return -EPERM; - } - *caCert = malloc(BUF_MAX_SIZE); - if (ZERO_OR_NULL_PTR((unsigned long)(uintptr_t)(*caCert))) { - tloge("caCert malloc fail\n"); - free(*tpath); - *tpath = NULL; - return -EPERM; - } - return 0; -} - -static int CheckPathAndAccess(LosTaskCB *caTask, - char *caCert, unsigned long messageSize, - unsigned char *digest, unsigned int digLen) -{ - int ret; - unsigned long index; - - if (digLen != SHA256_DIGEST_LENGTH) { - tlogd("check process path digest len error\n"); - return CHECK_PATH_HASH_FAIL; - } - - ret = CalcProcessPathHash((unsigned char *)caCert, messageSize, digest, digLen); - if (ret != 0) { - return ret; - } - - for (index = 0; index < (sizeof(g_arrayCertNativeVendor) / SHA256_DIGEST_LENGTH); index++) { - ret = memcmp(digest, g_arrayCertNativeVendor[index], digLen); - if (ret == 0) { - if (g_teecdTask == NULL && index == TEECD_CERT_INDEX) { - g_teecdTask = GetProcessGroupLeader(caTask); - } - return 0; - } - } - return CHECK_PATH_HASH_FAIL; -} - -static int CheckProcessAccess(LosTaskCB *caTask) -{ - char *caCert = NULL; - char *path = NULL; - char *tpath = NULL; - unsigned char digest[SHA256_DIGEST_LENTH] = {0}; - int messageSize; - int ret; - - if (caTask == NULL) { - tloge("task_struct is NULL\n"); - return -EPERM; - } - - if (IsKernelThread(caTask)) { - tlogd("kernel thread need not check\n"); - ret = ENTER_BYPASS_CHANNEL; - return ret; - } - - ret = GetMemSpace(&caCert, &tpath); - if (ret != 0) { - return ret; - } - - path = GetProcessPath(caTask, tpath, MAX_PATH_SIZE); - if (!IS_ERR_OR_NULL(path)) { - errno_t sret; - - sret = memset_s(caCert, BUF_MAX_SIZE, 0x00, BUF_MAX_SIZE); - if (sret != EOK) { - tloge("memset error sret is %d\n", sret); - free(tpath); - free(caCert); - return -EPERM; - } - - messageSize = PackCaCert(caCert, path, caTask, GetTaskUid(caTask)); - if (messageSize > 0) { - ret = CheckPathAndAccess(caTask, caCert, - (unsigned long)messageSize, digest, - (unsigned int)SHA256_DIGEST_LENTH); - } else { - ret = -EPERM; - } - } else { - ret = -EPERM; - } - free(tpath); - free(caCert); - return ret; -} - -/* Calculate the SHA256 file digest */ -static int TeeCalcTaskHash(unsigned char *digest, - uint32_t digLen, LosTaskCB *curStruct) -{ - TeeSha256Context ctx; - LosVmSpace *space = OS_PCB_FROM_PID(curStruct->processID)->vmSpace; - if (space == NULL) { - return -EFAULT; - } - - TeeSha256Init(&ctx); - /* search the region list */ - if (space->codeStart != 0 && space->codeEnd > space->codeStart) { - TeeSha256Update(&ctx, (void *)space->codeStart, space->codeEnd - space->codeStart); - } else { - return -EFAULT; - } - TeeSha256Final(&ctx, digest); - return 0; -} - -#define LIBTEEC_CODE_PAGE_SIZE 8 -#define DEFAULT_TEXT_OFF 0 -#define LIBTEEC_NAME_MAX_LEN 50 - -#define LIBTEEC_SO "/vendor/lib/libteec_vendor.so" - -/* Calculate the SHA256 library digest */ -static int TeeCalcTaskSoHash(unsigned char *digest, uint32_t digLen, - LosTaskCB *curStruct, int soIndex) -{ - TeeSha256Context ctx; - int findFlag = 0; - LosRbNode *pstRbNode = NULL; - LosRbNode *pstRbNodeNext = NULL; - LosVmSpace *space = OS_PCB_FROM_PID(curStruct->processID)->vmSpace; - if (space == NULL) { - return -EFAULT; - } - - TeeSha256Init(&ctx); - /* search the region list */ - (VOID)LOS_MuxAcquire(&space->regionMux); - RB_SCAN_SAFE(&space->regionRbTree, pstRbNode, pstRbNodeNext) - LosVmMapRegion *region = (LosVmMapRegion *)pstRbNode; - if (!LOS_IsRegionFileValid(region)) { - continue; - } - struct Vnode *vnode = region->unTypeData.rf.vnode; - if (vnode != NULL && !strncmp(vnode->filePath, LIBTEEC_SO, strlen(LIBTEEC_SO))) { - TeeSha256Update(&ctx, (void *)region->range.base, region->range.size); - findFlag = 1; - break; - } - RB_SCAN_SAFE_END(&space->regionRbTree, pstRbNode, pstRbNodeNext) - (VOID)LOS_MuxRelease(&space->regionMux); - - if (findFlag == 0) { - return -EFAULT; - } - TeeSha256Final(&ctx, digest); - return 0; -} - -/* Modify the client context so params id 2 and 3 contain temp pointers to the - * public key and package name for the open session. This is used for the - * TEEC_LOGIN_IDENTIFY open session method - */ -static int SetLoginInformation(TcNsDevFile *devFile, - TcNsClientContext *context) -{ - /* The daemon has failed to get login information or not supplied */ - if (devFile->pkgNameLen == 0) { - return -1; - } - /* The 3rd parameter buffer points to the pkg name buffer in the - * device file pointer - * get package name len and package name - */ - context->params[TEE_PARAM_FOUR].memref.sizeAddr = - (uintptr_t)&devFile->pkgNameLen; - context->params[TEE_PARAM_FOUR].memref.buffer = - (uintptr_t)devFile->PkgName; - /* Set public key len and public key */ - if (devFile->pubKeyLen != 0) { - context->params[TEE_PARAM_THREE].memref.sizeAddr = - (uintptr_t)&devFile->pubKeyLen; - context->params[TEE_PARAM_THREE].memref.buffer = - (uintptr_t)devFile->pubKey; - } else { - /* If get public key failed, then get uid in kernel */ - uint32_t caUid = TcNsGetUid(); - if (caUid == (uint32_t)(-1)) { - tloge("Failed to get uid of the task\n"); - goto error; - } - - devFile->pubKeyLen = sizeof(caUid); - context->params[TEE_PARAM_THREE].memref.sizeAddr = - (uintptr_t)&devFile->pubKeyLen; - if (memcpy_s(devFile->pubKey, MAX_PUBKEY_LEN, &caUid, - devFile->pubKeyLen)) { - tloge("Failed to copy pubkey, pubKeyLen=%u\n", - devFile->pubKeyLen); - goto error; - } - context->params[TEE_PARAM_THREE].memref.buffer = - (uint64_t)(uintptr_t)devFile->pubKey; - } - /* Now we mark the 2 parameters as input temp buffers */ - context->paramTypes = TEEC_PARAM_TYPES( - TEEC_PARAM_TYPE_GET(context->paramTypes, TEE_PARAM_ONE), - TEEC_PARAM_TYPE_GET(context->paramTypes, TEE_PARAM_TWO), - TEEC_MEMREF_TEMP_INPUT, TEEC_MEMREF_TEMP_INPUT); - return 0; -error: - return -1; -} - -static int CheckProcessAndAllocParams(TcNsDevFile *devFile, - uint8_t **certBuffer, unsigned int *certBufferSize) -{ - int ret; - -#ifdef SECURITY_AUTH_ENHANCE - ret = CheckProcessAccess(OsCurrTaskGet()); - if (ret) { - tloge(KERN_ERR "tc client login: teecd verification failed ret 0x%x!\n", ret); - return -EPERM; - } -#endif - mutex_lock(&devFile->LoginSetupLock); - if (devFile->loginSetup) { - tloge("Login information cannot be set twice!\n"); - mutex_unlock(&devFile->LoginSetupLock); - return -EINVAL; - } - devFile->loginSetup = true; - mutex_unlock(&devFile->LoginSetupLock); - - unsigned int bufSize = (unsigned int)(MAX_PACKAGE_NAME_LEN + MAX_PUBKEY_LEN + - sizeof(devFile->pkgNameLen) + sizeof(devFile->pubKeyLen)); - *certBuffer = malloc(bufSize); - if (ZERO_OR_NULL_PTR((unsigned long)(uintptr_t)(*certBuffer))) { - tloge("Failed to allocate login buffer!"); - return -EFAULT; - } - *certBufferSize = bufSize; - - return 0; -} - -static int TcNsGetTeeVersion(const TcNsDevFile *devFile, void *argp) -{ - unsigned int version; - TcNsSmcCmd smcCmd = { {0}, 0 }; - int smcRet; - struct MbCmdPack *mbPack = NULL; - - if (argp == NULL || devFile == NULL) { - tloge("error input parameter\n"); - return -1; - } - mbPack = MailboxAllocCmdPack(); - if (mbPack == NULL) { - tloge("alloc mb pack failed\n"); - return -ENOMEM; - } - - mbPack->operation.paramTypes = TEEC_VALUE_OUTPUT; - smcCmd.globalCmd = true; - smcCmd.cmdId = GLOBAL_CMD_ID_GET_TEE_VERSION; - smcCmd.devFileId = devFile->devFileId; - smcCmd.operationPhys = LOS_PaddrQuery(&mbPack->operation); - smcCmd.operationHphys = 0; - smcRet = TcNsSmc(&smcCmd); - if (smcRet != 0) { - tloge("smc_call returns error ret 0x%x\n", smcRet); - } - - version = mbPack->operation.params[0].value.a; - if (copy_to_user(argp, &version, sizeof(unsigned int))) { - if (smcRet != 0) { - smcRet = -EFAULT; - } - } - MailboxFree(mbPack); - return smcRet; -} - -#define MAX_BUF_LEN 4096 - -static int TcNsClientLogWithoutCert(TcNsDevFile *devFile) -{ - int ret; - uint8_t *certBuffer = NULL; - uint8_t *tempCertBuffer = NULL; - errno_t sret; - unsigned int certBufferSize = 0; - char *path = NULL; - - ret = CheckProcessAndAllocParams(devFile, &certBuffer, - &certBufferSize); - if (ret != 0) { - return ret; - } - tempCertBuffer = certBuffer; - - path = GetProcessPath(OsCurrTaskGet(), (char *)certBuffer, MAX_PACKAGE_NAME_LEN); - if (path == NULL) { - goto error; - } - devFile->pkgNameLen = strlen(path); - - sret = strncpy_s((char *)devFile->PkgName, MAX_PACKAGE_NAME_LEN, (char *)certBuffer, - devFile->pkgNameLen); - if (sret != EOK) { - ret = -ENOMEM; - goto error; - } - int uid = GetTaskUid(OsCurrTaskGet()); - devFile->pubKeyLen = sizeof(uid); - if (memcpy_s((char *)devFile->pubKey, MAX_PUBKEY_LEN, (char *)&uid, - devFile->pubKeyLen)) { - tloge("Failed to copy cert, pubKeyLen=%u\n", - devFile->pubKeyLen); - ret = -EINVAL; - goto error; - } -error: - free(tempCertBuffer); - return ret; -} - -static int TcNsClientLogWithCert(TcNsDevFile *devFile, const void *buffer) -{ - int ret; - uint8_t *certBuffer = NULL; - uint8_t *tempCertBuffer = NULL; - errno_t sret; - unsigned int certBufferSize = 0; - - // application ca login - ret = CheckProcessAndAllocParams(devFile, &certBuffer, - &certBufferSize); - if (ret != 0) { - return ret; - } - - tempCertBuffer = certBuffer; - if (certBufferSize > MAX_BUF_LEN) { - tloge("cert buffer size is invalid!\n"); - ret = -EINVAL; - goto error; - } - - if (copy_from_user(certBuffer, buffer, certBufferSize)) { - tloge("Failed to get user login info!\n"); - ret = -EINVAL; - goto error; - } - /* get package name len */ - ret = GetPackNameLen(devFile, certBuffer, certBufferSize); - if (ret != 0) { - goto error; - } - certBuffer += sizeof(devFile->pkgNameLen); - - /* get package name */ - sret = strncpy_s((char *)devFile->PkgName, MAX_PACKAGE_NAME_LEN, (char *)certBuffer, devFile->pkgNameLen); - if (sret != EOK) { - ret = -ENOMEM; - goto error; - } - certBuffer += devFile->pkgNameLen; - - /* get public key len */ - ret = GetPublicKeyLen(devFile, certBuffer, certBufferSize); - if (ret != 0) { - goto error; - } - - /* get public key */ - if (devFile->pubKeyLen != 0) { - certBuffer += sizeof(devFile->pubKeyLen); - if (memcpy_s((char *)devFile->pubKey, MAX_PUBKEY_LEN, (char *)certBuffer, devFile->pubKeyLen)) { - tloge("Failed to copy cert, pubKeyLen=%u\n", devFile->pubKeyLen); - ret = -EINVAL; - goto error; - } - certBuffer += devFile->pubKeyLen; - } - ret = 0; -error: - free(tempCertBuffer); - return ret; -} - -static int TcNsClientLoginFunc(TcNsDevFile *devFile, - const void *buffer) -{ - if (buffer == NULL) { - return TcNsClientLogWithoutCert(devFile); - } else { - return TcNsClientLogWithCert(devFile, buffer); - } -} - -static int AllocForLoadImage(unsigned int *mbLoadSize, - unsigned int fileSize, char **mbLoadMem, - struct MbCmdPack **mbPack, TeecUuid **uuidReturn) -{ - /* we will try any possible to alloc mailbox mem to load TA */ - for (; *mbLoadSize > 0; *mbLoadSize >>= 1) { - *mbLoadMem = MailboxAlloc(*mbLoadSize, 0); - if (*mbLoadMem != NULL) { - break; - } - tlogw("alloc mem(size=%u) for TA load mem fail, will retry\n", *mbLoadSize); - } - if (*mbLoadMem == NULL) { - tloge("alloc TA load mem failed\n"); - return -ENOMEM; - } - *mbPack = MailboxAllocCmdPack(); - if (*mbPack == NULL) { - MailboxFree(*mbLoadMem); - *mbLoadMem = NULL; - tloge("alloc mb pack failed\n"); - return -ENOMEM; - } - *uuidReturn = MailboxAlloc(sizeof(TeecUuid), 0); - if (*uuidReturn == NULL) { - MailboxFree(*mbLoadMem); - *mbLoadMem = NULL; - MailboxFree(*mbPack); - *mbPack = NULL; - tloge("alloc uuid failed\n"); - return -ENOMEM; - } - return 0; -} - -static void PackDataForSmcCmd(uint32_t loadSize, - const char *mbLoadMem, struct MbCmdPack *mbPack, - TeecUuid *uuidReturn, TcNsSmcCmd *smcCmd) -{ - mbPack->operation.params[TEE_PARAM_ONE].memref.buffer = - LOS_PaddrQuery((void *)mbLoadMem); - mbPack->operation.bufferHaddr[TEE_PARAM_ONE] = 0; - mbPack->operation.params[TEE_PARAM_ONE].memref.size = loadSize + sizeof(int); - mbPack->operation.params[TEE_PARAM_THREE].memref.buffer = - LOS_PaddrQuery((void *)uuidReturn); - mbPack->operation.bufferHaddr[TEE_PARAM_THREE] = 0; - mbPack->operation.params[TEE_PARAM_THREE].memref.size = sizeof(*uuidReturn); - mbPack->operation.paramTypes = TEEC_PARAM_TYPES(TEEC_MEMREF_TEMP_INOUT, - TEEC_VALUE_OUTPUT, TEEC_MEMREF_TEMP_OUTPUT, TEEC_VALUE_INPUT); - /* load image smc command */ - smcCmd->globalCmd = true; - smcCmd->cmdId = GLOBAL_CMD_ID_LOAD_SECURE_APP; - smcCmd->contextId = 0; - smcCmd->operationPhys = LOS_PaddrQuery(&mbPack->operation); - smcCmd->operationHphys = 0; -} - -struct MbLoad { - unsigned int mbLoadSize; - char *mbLoadMem; -}; - -static int LoadImageByFrame(const LoadImageParams *paramsIn, - struct MbLoad *mb, struct MbCmdPack *mbPack, TeecUuid *uuidReturn, - unsigned int loadTimes) -{ - char *p = mb->mbLoadMem; - uint32_t loadSize; - int loadFlag = 1; /* 0:it's last block, 1:not last block */ - uint32_t loadedSize = 0; - unsigned int index; - TcNsSmcCmd smcCmd = { {0}, 0 }; - int smcRet; - - for (index = 0; index < loadTimes; index++) { - if (index == (loadTimes - 1)) { - loadFlag = 0; - loadSize = paramsIn->fileSize - loadedSize; - } else { - loadSize = mb->mbLoadSize - sizeof(loadFlag); - } - *(int *)p = loadFlag; - if (loadSize > mb->mbLoadSize - sizeof(loadFlag)) { - tloge("invalid load size %u/%u\n", loadSize, - mb->mbLoadSize); - return -1; - } - if (copy_from_user(mb->mbLoadMem + sizeof(loadFlag), - (void __user *)(paramsIn->fileBuffer + - loadedSize), loadSize)) { - tloge("file buf get fail\n"); - return -1; - } - PackDataForSmcCmd(loadSize, mb->mbLoadMem, mbPack, - uuidReturn, &smcCmd); - mbPack->operation.params[TEE_PARAM_FOUR].value.a = index; - smcCmd.devFileId = paramsIn->devFile->devFileId; - smcRet = TcNsSmc(&smcCmd); - tlogd("smc cmd ret %d\n", smcRet); - tlogd("configid=%u, ret=%d, loadFlag=%d, index=%u\n", - mbPack->operation.params[1].value.a, smcRet, - loadFlag, index); - - if (smcRet != 0) { - tloge("smc_call returns error ret 0x%x\n", smcRet); - return -1; - } - - loadedSize += loadSize; - } - return 0; -} - -int TcNsLoadImage(TcNsDevFile *devFile, char *fileBuffer, - unsigned int fileSize) -{ - int ret; - struct MbCmdPack *mbPack = NULL; - unsigned int mbLoadSize; - char *mbLoadMem = NULL; - TeecUuid *uuidReturn = NULL; - unsigned int loadTimes; - LoadImageParams paramsIn = {devFile, fileBuffer, fileSize}; - bool checkValue = false; - - checkValue = (devFile == NULL || fileBuffer == NULL); - if (checkValue) { - tloge("devFile or fileBuffer is NULL!\n"); - return -EINVAL; - } - if (!IsValidTaSize(fileBuffer, fileSize)) { - return -EINVAL; - } - - mbLoadSize = (fileSize > (SZ_1M - sizeof(int))) ? SZ_1M : ALIGN(fileSize, SZ_4K); - - ret = AllocForLoadImage(&mbLoadSize, fileSize, &mbLoadMem, - &mbPack, &uuidReturn); - if (ret != 0) { - return ret; - } - - if (mbLoadSize <= sizeof(int)) { - tloge("mbLoadSize is too small!\n"); - ret = -ENOMEM; - goto FREE_MEM; - } - - loadTimes = fileSize / (mbLoadSize - sizeof(int)); - if (fileSize % (mbLoadSize - sizeof(int))) { - loadTimes += 1; - } - struct MbLoad mb; - mb.mbLoadMem = mbLoadMem; - mb.mbLoadSize = mbLoadSize; - ret = LoadImageByFrame(¶msIn, &mb, mbPack, uuidReturn, loadTimes); -FREE_MEM: - MailboxFree(mbLoadMem); - MailboxFree(mbPack); - MailboxFree(uuidReturn); - return ret; -} - -static int CheckTaskState(LosTaskCB **halStruct, - const TcNsClientContext *context) -{ - bool checkValue = false; - - checkValue = (context->callingPid && !IsKernelThread(OsCurrTaskGet())); - if (checkValue == true) { - tloge("non hal service pass non-zero callingpid , reject please!!!\n"); - return -EFAULT; - } - return 0; -} - -static int CalcTaskHash(uint8_t kernelApi, - TcNsSession *session, TcNsService *service, - LosTaskCB *curStruct) -{ - int rc, i; - int soFound = 0; - if (kernelApi == TEE_REQ_FROM_USER_MODE) { - for (i = 0; soFound < NUM_OF_SO && i < KIND_OF_SO; i++) { - rc = TeeCalcTaskSoHash(session->authHashBuf + MAX_SHA_256_SZ * soFound, - (uint32_t)SHA256_DIGEST_LENTH, curStruct, i); - if (rc == 0) { - soFound++; - } - } - if (soFound != NUM_OF_SO) { - tlogd("so library found: %d\n", soFound); - } - } else { - tlogd("request from kernel\n"); - } - -#ifdef CONFIG_ASAN_DEBUG - tloge("so auth disabled for ASAN debug\n"); - uint32_t soHashLen = MAX_SHA_256_SZ * NUM_OF_SO; - errno_t sret = memset_s(session->authHashBuf, soHashLen, 0, soHashLen); - if (sret != EOK) { - tloge("memset so hash failed\n"); - return -EFAULT; - } -#endif - rc = TeeCalcTaskHash(session->authHashBuf + MAX_SHA_256_SZ * NUM_OF_SO, - (uint32_t)SHA256_DIGEST_LENTH, curStruct); - if (rc != 0) { - tloge("tee calc ca hash failed\n"); - return -EFAULT; - } - return 0; -} - -static int CheckLoginMethod(TcNsDevFile *devFile, - TcNsClientContext *context, uint8_t *flags) -{ - bool checkValue = false; - int ret; - - if (devFile == NULL || context == NULL || flags == NULL) { - return -EFAULT; - } - if (context->login.method == TEEC_LOGIN_IDENTIFY) { - tlogd("login method is IDENTIFY\n"); - /* Check if params 0 and 1 are valid */ - checkValue = devFile->kernelApi == TEE_REQ_FROM_USER_MODE && - (TcUserParamValid(context, (unsigned int)TEE_PARAM_ONE) || - TcUserParamValid(context, (unsigned int)TEE_PARAM_TWO)); - if (checkValue == true) { - return -EFAULT; - } - ret = SetLoginInformation(devFile, context); - if (ret != 0) { - tloge("SetLoginInformation failed ret =%d\n", ret); - return ret; - } - *flags |= TC_CALL_LOGIN; - } else { - tlogd("login method is not supported\n"); - return -EINVAL; - } - return 0; -} - -static TcNsService *FindService(TcNsDevFile *devFile, - const TcNsClientContext *context) -{ - int ret; - TcNsService *service = NULL; - bool isNewService = false; - bool isFull = false; - - mutex_lock(&devFile->serviceLock); - service = TcRefServiceInDev(devFile, context->uuid, - UUID_LEN, &isFull); - /* if service has been opened in this dev or ref cnt is full */ - if (service != NULL || isFull == true) { - /* If service has been reference by this dev, TcFindServiceInDev - * will increase a ref count to declaim there's how many callers to - * this service from the devFile, instead of increase service->usage. - * While close session, dev->serviceRef[i] will decrease and till - * it get to 0 PutServiceStruct will be called. - */ - mutex_unlock(&devFile->serviceLock); - return service; - } - mutex_lock(&g_serviceListLock); - service = TcFindServiceFromAll(context->uuid, (uint32_t)UUID_LEN); - /* if service has been opened in other dev */ - if (service != NULL) { - GetServiceStruct(service); - mutex_unlock(&g_serviceListLock); - goto ADD_SERVICE; - } - /* Create a new service if we couldn't find it in list */ - ret = TcNsServiceInit(context->uuid, (uint32_t)UUID_LEN, &service); - /* Put unlock after TcNsServiceInit to make sure TcFindServiceFromAll * is correct */ - mutex_unlock(&g_serviceListLock); - if (ret) { - tloge("service init failed"); - mutex_unlock(&devFile->serviceLock); - return NULL; - } - isNewService = true; -ADD_SERVICE: - ret = AddServiceToDev(devFile, service); - mutex_unlock(&devFile->serviceLock); - if (ret) { - if (isNewService) { - PutServiceStruct(service); - } - service = NULL; - tloge("fail to add service to dev\n"); - return NULL; - } - return service; -} - -static int ProcCalcTaskHash(TcNsDevFile *devFile, - TcNsClientContext *context, TcNsSession *session, - TcNsService *service, uint8_t *flags) -{ - int ret; - LosTaskCB *curStruct = NULL; - LosTaskCB *halStruct = NULL; - - ret = CheckLoginMethod(devFile, context, flags); - if (ret != 0) { - return ret; - } - context->cmdId = GLOBAL_CMD_ID_OPEN_SESSION; - mutex_init(&session->taSessionLock); - - ret = CheckTaskState(&halStruct, context); - if (ret != 0) { - return ret; - } - if (halStruct != NULL) { - curStruct = halStruct; - } else { - curStruct = OsCurrTaskGet(); - } - /* lock reason: - * TeeCalcTaskHash will use the global value g_tee_shash_tfm - */ - ret = CalcTaskHash(devFile->kernelApi, session, service, curStruct); - return ret; -} - -static void ProcAfterSmcCmd(TcNsDevFile *devFile, - const TcNsClientContext *context, TcNsService *service, - TcNsSession *session) -{ - session->sessionId = context->sessionId; -#ifdef TC_ASYNC_NOTIFY_SUPPORT - session->waitData.sendWaitFlag = 0; - init_waitqueue_head(&session->waitData.sendCmdWq); -#endif - atomic_set(&session->usage, 1); - session->owner = devFile; - mutex_lock(&service->SessionLock); - list_add_tail(&session->head, &service->sessionList); - mutex_unlock(&service->SessionLock); -} - -static int ProcOpenSession(TcNsDevFile *devFile, - TcNsClientContext *context, TcNsService *service, - TcNsSession *session, uint8_t flags) -{ - int ret; - - mutex_lock(&service->operationLock); - ret = LoadTaImage(devFile, context); - if (ret != 0) { - tloge("load ta image failed\n"); - mutex_unlock(&service->operationLock); - return ret; - } - /* send smc */ -#ifdef SECURITY_AUTH_ENHANCE - ret = GetSessionSecureParams(devFile, context, session); - if (ret) { - tloge("Get session secure parameters failed, ret = %d.\n", ret); - /* Clean this session secure information */ - CleanSessionSecureInformation(session); - mutex_unlock(&service->operationLock); - return ret; - } - session->TcNsToken.tokenBuffer = - calloc(1, TOKEN_BUFFER_LEN); - session->TcNsToken.tokenLen = TOKEN_BUFFER_LEN; - if (ZERO_OR_NULL_PTR((unsigned long)(uintptr_t) - session->TcNsToken.tokenBuffer)) { - tloge("calloc %d bytes token failed.\n", TOKEN_BUFFER_LEN); - /* Clean this session secure information */ - CleanSessionSecureInformation(session); - mutex_unlock(&service->operationLock); - return -ENOMEM; - } - ret = TcClientCall(context, devFile, session, flags); - if (ret != 0) { - /* Clean this session secure information */ - CleanSessionSecureInformation(session); - } -#else - ret = TcClientCall(context, devFile, session, flags); -#endif - if (ret != 0) { - mutex_unlock(&service->operationLock); - tloge("smc_call returns error, ret=0x%x\n", ret); - return ret; - } - ProcAfterSmcCmd(devFile, context, service, session); - /* sessionId in tee is unique, but in concurrency scene - * same sessionId may appear in tzdriver, put sessionList - * add/del in service->operationLock can avoid it. - */ - mutex_unlock(&service->operationLock); - return ret; -} - -static void ProcErrorSituation(TcNsDevFile *devFile, - TcNsClientContext *context, TcNsService *service, - TcNsSession *session) -{ - ReleaseFreeSession(devFile, context, session); - mutex_lock(&devFile->serviceLock); - DelServiceFromDev(devFile, service); - mutex_unlock(&devFile->serviceLock); - free(session); - return; -} - -int TcNsOpenSession(TcNsDevFile *devFile, - TcNsClientContext *context) -{ - int ret; - TcNsService *service = NULL; - TcNsSession *session = NULL; - uint8_t flags = TC_CALL_GLOBAL; - bool checkValue = (devFile == NULL || context == NULL); - - if (checkValue == true) { - tloge("invalid devFile or context\n"); - return -EINVAL; - } - - ret = CheckProcessAccess(OsCurrTaskGet()); - if (ret) { - tloge("tee driver fd may be leak\n"); - return -EPERM; - } - - service = FindService(devFile, context); - if (service == NULL) { - tloge("find service failed\n"); - return -ENOMEM; - } - session = calloc(1, sizeof(*session)); - if (ZERO_OR_NULL_PTR((unsigned long)(uintptr_t)session)) { - tloge("calloc failed\n"); - mutex_lock(&devFile->serviceLock); - DelServiceFromDev(devFile, service); - mutex_unlock(&devFile->serviceLock); - return -ENOMEM; - } - - ret = ProcCalcTaskHash(devFile, context, session, service, - &flags); - if (ret != 0) { - goto error; - } - ret = ProcOpenSession(devFile, context, service, session, flags); - if (ret == 0) { - return ret; - } -error: - ProcErrorSituation(devFile, context, service, session); - return ret; -} - -static TcNsService *GetService(TcNsDevFile *devFile, - const TcNsClientContext *context) -{ - TcNsService *service = NULL; - - mutex_lock(&devFile->serviceLock); - service = TcFindServiceInDev(devFile, - context->uuid, UUID_LEN); - GetServiceStruct(service); - mutex_unlock(&devFile->serviceLock); - return service; -} - -void PutSessionStruct(struct TagTcNsSession *session) -{ - if (session == NULL || !atomic_dec_and_test(&session->usage)) { - return; - } - -#ifdef SECURITY_AUTH_ENHANCE - if (session->TcNsToken.tokenBuffer != NULL) { - if (memset_s( - (void *)session->TcNsToken.tokenBuffer, - session->TcNsToken.tokenLen, - 0, - session->TcNsToken.tokenLen) != EOK) { - tloge("Caution, memset failed!\n"); - } - free(session->TcNsToken.tokenBuffer); - session->TcNsToken.tokenBuffer = NULL; - (void)session->TcNsToken.tokenBuffer; /* avoid Codex warning */ - } -#endif - if (memset_s((void *)session, sizeof(*session), 0, sizeof(*session)) != EOK) { - tloge("Caution, memset failed!\n"); - } - free(session); -} - -static TcNsSession *GetSession(TcNsService *service, - TcNsDevFile *devFile, const TcNsClientContext *context) -{ - TcNsSession *session = NULL; - - mutex_lock(&service->SessionLock); - session = TcFindSessionWithOwner(&service->sessionList, - context->sessionId, devFile); - GetSessionStruct(session); - mutex_unlock(&service->SessionLock); - return session; -} - -void GetServiceStruct(struct TagTcNsService *service) -{ - if (service != NULL) { - atomic_inc(&service->usage); - tlogd("service->usage = %d\n", atomic_read(&service->usage)); - } -} - -void PutServiceStruct(struct TagTcNsService *service) -{ - if (service != NULL) { - tlogd("service->usage = %d\n", atomic_read(&service->usage)); - mutex_lock(&g_serviceListLock); - if (atomic_dec_and_test(&service->usage)) { - tlogd("del service [0x%x] from service list\n", - *(uint32_t *)service->uuid); - list_del(&service->head); - free(service); - } - mutex_unlock(&g_serviceListLock); - } -} - -int TcNsCloseSession(TcNsDevFile *devFile, - TcNsClientContext *context) -{ - int ret = -EINVAL; - errno_t ret_err; - TcNsService *service = NULL; - TcNsSession *session = NULL; - - if (devFile == NULL || context == NULL) { - tloge("invalid devFile or context\n"); - return ret; - } - service = GetService(devFile, context); - if (service == NULL) { - tloge("invalid service\n"); - return ret; - } - /* - * sessionId in tee is unique, but in concurrency scene - * same sessionId may appear in tzdriver, put sessionList - * add/del in service->operationLock can avoid it. - */ - mutex_lock(&service->operationLock); - session = GetSession(service, devFile, context); - if (session != NULL) { - int ret2; - mutex_lock(&session->taSessionLock); - ret2 = CloseSession(devFile, session, context->uuid, - (unsigned int)UUID_LEN, context->sessionId); - mutex_unlock(&session->taSessionLock); - if (ret2 != TEEC_SUCCESS) { - tloge("close session smc failed!\n"); - } -#ifdef SECURITY_AUTH_ENHANCE - /* Clean this session secure information */ - ret_err = memset_s((void *)&session->secureInfo, - sizeof(session->secureInfo), - 0, sizeof(session->secureInfo)); - if (ret_err != EOK) { - tloge("close session memset error=%d\n", ret_err); - } -#endif - mutex_lock(&service->SessionLock); - list_del(&session->head); - mutex_unlock(&service->SessionLock); - - PutSessionStruct(session); - PutSessionStruct(session); /* pair with open session */ - - ret = TEEC_SUCCESS; - mutex_lock(&devFile->serviceLock); - DelServiceFromDev(devFile, service); - mutex_unlock(&devFile->serviceLock); - } else { - tloge("invalid session\n"); - } - mutex_unlock(&service->operationLock); - PutServiceStruct(service); - return ret; -} - -int TcNsSendCmd(TcNsDevFile *devFile, - TcNsClientContext *context) -{ - int ret = -EINVAL; - TcNsService *service = NULL; - TcNsSession *session = NULL; - bool checkValue = (devFile == NULL || context == NULL); - - if (checkValue == true) { - tloge("invalid devFile or context\n"); - return ret; - } - tlogd("session id :%x\n", context->sessionId); - service = GetService(devFile, context); - /* check sessionid is validated or not */ - if (service != NULL) { - session = GetSession(service, devFile, context); - PutServiceStruct(service); - if (session != NULL) { - tlogd("send cmd find session id %x\n", - context->sessionId); - goto FIND_SESSION; - } - } else { - tloge("can't find service\n"); - } - tloge("send cmd can not find session id %u\n", context->sessionId); - return ret; -FIND_SESSION: - /* send smc */ - mutex_lock(&session->taSessionLock); - ret = TcClientCall(context, devFile, session, 0); - mutex_unlock(&session->taSessionLock); - PutSessionStruct(session); - if (ret != 0) { - tloge("smc_call returns error, ret=0x%x\n", ret); - } - return ret; -} - -int TcNsClientOpen(TcNsDevFile **devFile, uint8_t kernelApi) -{ - int ret = TEEC_ERROR_GENERIC; - TcNsDevFile *dev = NULL; - - tlogd("TcClientOpen\n"); - if (devFile == NULL) { - tloge("devFile is NULL\n"); - return -EFAULT; - } - dev = calloc(1, sizeof(*dev)); - if (ZERO_OR_NULL_PTR((unsigned long)(uintptr_t)dev)) { - tloge("dev malloc failed\n"); - return ret; - } - mutex_lock(&g_tcNsDevList.devLock); - list_add_tail(&dev->head, &g_tcNsDevList.devFileList); - mutex_unlock(&g_tcNsDevList.devLock); - mutex_lock(&g_deviceFileCntLock); - dev->devFileId = g_deviceFileCnt; - g_deviceFileCnt++; - mutex_unlock(&g_deviceFileCntLock); - INIT_LIST_HEAD(&dev->sharedMemList); - dev->loginSetup = 0; - dev->kernelApi = kernelApi; - dev->loadAppFlag = 0; - mutex_init(&dev->serviceLock); - mutex_init(&dev->sharedMemLock); - mutex_init(&dev->LoginSetupLock); - *devFile = dev; - ret = TEEC_SUCCESS; - return ret; -} - -void FreeDev(TcNsDevFile *dev) -{ - DelDevNode(dev); - TeeAgentClearDevOwner(dev); - if (memset_s((void *)dev, sizeof(*dev), 0, sizeof(*dev)) != EOK) { - tloge("Caution, memset dev fail!\n"); - } - free(dev); -} - -int TcNsClientClose(TcNsDevFile *dev) -{ - int ret = TEEC_ERROR_GENERIC; - uint32_t index; - - if (dev == NULL) { - tloge("invalid dev(null)\n"); - return ret; - } - - /* close unclosed session */ - for (index = 0; index < SERVICES_MAX_COUNT; index++) { - CloseUnclosedSession(dev, index); - } - - // for thirdparty agent, code runs here only when agent crashed - SendCrashedEventResponseAll(dev); - ret = TEEC_SUCCESS; - FreeDev(dev); - return ret; -} - -static void ReleaseVmaSharedMem(TcNsDevFile *devFile, - const LosVmMapRegion *vma) -{ - TcNsSharedMem *sharedMem = NULL; - TcNsSharedMem *sharedMemTemp = NULL; - bool find = false; - - mutex_lock(&devFile->sharedMemLock); - list_for_each_entry_safe(sharedMem, sharedMemTemp, - &devFile->sharedMemList, head) { - if (sharedMem != NULL) { - if (sharedMem->userAddr == - (void *)(uintptr_t)vma->range.base) { - sharedMem->userAddr = NULL; - find = true; - } else if (sharedMem->userAddrCa == - (void *)(uintptr_t)vma->range.base) { - sharedMem->userAddrCa = NULL; - find = true; - } - - if ((sharedMem->userAddr == NULL) && - (sharedMem->userAddrCa == NULL)) { - list_del(&sharedMem->head); - } - - /* pair with TcClientMmap */ - if (find == true) { - PutSharememStruct(sharedMem); - break; - } - } - } - mutex_unlock(&devFile->sharedMemLock); -} - -static int TcNsSharedMemUnmap(TcNsDevFile *devFile, const unsigned int argp) -{ - if (devFile == NULL) { - tloge("unmap input error\n"); - return -EINVAL; - } - - LosVmMapRegion *vma = LOS_RegionFind(OsCurrProcessGet()->vmSpace, (vaddr_t)argp); - if (vma == NULL) { - tloge("unmap error memory\n"); - return -EINVAL; - } - - bool checkValue = (IsTeecdProcess(g_teecdTask, OsCurrTaskGet())) && (!TcNsGetUid()) && - ((g_teecdTask->taskStatus & OS_TASK_STATUS_EXIT) || (OsCurrTaskGet()->taskStatus & OS_TASK_STATUS_EXIT)); - if (checkValue == true) { - tlogd("teecd is killed, just return in vma close\n"); - return 0; - } - ReleaseVmaSharedMem(devFile, vma); - return 0; -} - -static TcNsSharedMem *AllocAndFindSharedMem(const LosVmMapRegion *vma, - TcNsDevFile *devFile, bool *onlyRemap) -{ - TcNsSharedMem *shmTmp = NULL; - unsigned long len = vma->range.size; - - /* using vma->vm_pgoff as share_mem index */ - /* check if aready allocated */ - list_for_each_entry(shmTmp, &devFile->sharedMemList, head) { - if (atomic_read(&shmTmp->offset) == vma->pgOff) { - tlogd("share_mem already allocated, shmTmp->offset=%d\n", - atomic_read(&shmTmp->offset)); - /* args check: - * 1. this shared mem is already mapped ? - * 2. remap a different size sharedMem ? - */ - if (shmTmp->userAddrCa != NULL || - vma->range.size != shmTmp->len) { - tloge("already remap once!\n"); - return NULL; - } - /* return the same sharedmem specified by vma->vm_pgoff */ - *onlyRemap = true; - GetSharememStruct(shmTmp); - return shmTmp; - } - } - - /* if not find, alloc a new sharemem */ - return TcMemAllocate(len); -} - -static int RemapSharedMem(LosVmMapRegion *vma, TcNsSharedMem *sharedMem) -{ - int ret; - - ret = RemapVmallocRange(vma, sharedMem->kernelAddr, 0); - if (ret) { - tloge("can't remap to user, ret = %d\n", ret); - return -1; - } - return ret; -} - -/* in this func, we need to deal with follow cases: - * vendor CA alloc sharedmem (alloc and remap); - * HAL alloc sharedmem (alloc and remap); - * system CA alloc sharedmem (only just remap); - */ -static int TcClientMmap(struct file *filp, LosVmMapRegion *vma) -{ - int ret; - TcNsDevFile *devFile = NULL; - TcNsSharedMem *sharedMem = NULL; - bool onlyRemap = false; - bool checkValue = false; - - checkValue = (filp == NULL || vma == NULL || filp->f_priv == NULL); - if (checkValue == true) { - tloge("invalid args for tc mmap\n"); - return -EINVAL; - } - devFile = filp->f_priv; - - mutex_lock(&devFile->sharedMemLock); - sharedMem = AllocAndFindSharedMem(vma, devFile, &onlyRemap); - if (IS_ERR_OR_NULL(sharedMem)) { - tloge("alloc shared mem failed\n"); - mutex_unlock(&devFile->sharedMemLock); - return -ENOMEM; - } - - ret = RemapSharedMem(vma, sharedMem); - if (ret != 0) { - if (onlyRemap) { - PutSharememStruct(sharedMem); - } else { - TcMemFree(sharedMem); - } - mutex_unlock(&devFile->sharedMemLock); - return ret; - } - - if (onlyRemap) { - sharedMem->userAddrCa = (void *)vma->range.base; - mutex_unlock(&devFile->sharedMemLock); - return ret; - } - sharedMem->userAddr = (void *)vma->range.base; - atomic_set(&sharedMem->offset, vma->pgOff); - GetSharememStruct(sharedMem); - list_add_tail(&sharedMem->head, &devFile->sharedMemList); - mutex_unlock(&devFile->sharedMemLock); - return ret; -} - -static int IoctlSessionSendCmd(TcNsDevFile *devFile, - TcNsClientContext *context, void *argp) -{ - int ret; - - ret = TcNsSendCmd(devFile, context); - if (ret) { - tloge("TcNsSendCmd Failed ret is %d\n", ret); - } - if (copy_to_user(argp, context, sizeof(*context))) { - if (ret == 0) { - ret = -EFAULT; - } - } - return ret; -} - -static int TcClientSessionIoctl(struct file *file, unsigned int cmd, - unsigned long arg) -{ - int ret = TEEC_ERROR_GENERIC; - void *argp = (void __user *)(uintptr_t)arg; - TcNsDevFile *devFile = file->f_priv; - TcNsClientContext context; - - if (argp == NULL) { - tloge("argp is NULL input buffer\n"); - ret = -EINVAL; - return ret; - } - if (copy_from_user(&context, argp, sizeof(context))) { - tloge("copy from user failed\n"); - return -EFAULT; - } - context.returns.origin = TEEC_ORIGIN_COMMS; - switch (cmd) { - case TC_NS_CLIENT_IOCTL_SES_OPEN_REQ: { - ret = TcNsOpenSession(devFile, &context); - if (ret) { - tloge("TcNsOpenSession Failed ret is %d\n", ret); - } - if (copy_to_user(argp, &context, sizeof(context)) && ret == 0) { - ret = -EFAULT; - } - break; - } - case TC_NS_CLIENT_IOCTL_SES_CLOSE_REQ: { - ret = TcNsCloseSession(devFile, &context); - break; - } - case TC_NS_CLIENT_IOCTL_SEND_CMD_REQ: { - ret = IoctlSessionSendCmd(devFile, &context, argp); - break; - } - default: - tloge("invalid cmd:0x%x!\n", cmd); - return ret; - } - /* - * Don't leak ERESTARTSYS to user space. - * - * CloseSession is not reentrant, so convert to -EINTR. - * In other case, RestartSyscall(). - * - * It is better to call it right after the error code - * is generated (in TcClientCall), but kernel CAs are - * still exist when these words are written. Setting TIF - * flags for callers of those CAs is very hard to analysis. - * - * For kernel CA, when ERESTARTSYS is seen, loop in kernel - * instead of notifying user. - * - * P.S. ret code in this function is in mixed naming space. - * See the definition of ret. However, this function never - * return its default value, so using -EXXX is safe. - */ - if (ret == -ERESTARTSYS) { - if (cmd == TC_NS_CLIENT_IOCTL_SES_CLOSE_REQ) { - ret = -EINTR; - } else { - return RestartSyscall(); - } - } - return ret; -} - -static int IoctlRegisterAgent(TcNsDevFile *devFile, unsigned long arg) -{ - int ret; - struct AgentIoctlArgs args; - - if (copy_from_user(&args, (void *)arg, sizeof(args))) { - tloge("copy agent args failed\n"); - return -EFAULT; - } - - ret = TcNsRegisterAgent(devFile, args.id, args.bufferSize, - &args.buffer, true); - if (ret == 0) { - if (copy_to_user((void *)arg, &args, sizeof(args))) { - tloge("copy agent user addr failed\n"); - } - } - - return ret; -} - -static int IoctlUnregisterAgent(const TcNsDevFile *devFile, unsigned long arg) -{ - int ret; - struct SmcEventData *eventData = NULL; - eventData = FindEventControl((unsigned int)arg); - if (eventData == NULL) { - tloge("invalid agent id\n"); - return TEEC_ERROR_GENERIC; - } - if (eventData->owner != devFile) { - tloge("invalid unregister request\n"); - PutAgentEvent(eventData); - return TEEC_ERROR_GENERIC; - } - PutAgentEvent(eventData); - ret = TcNsUnregisterAgent((unsigned int)arg); - return ret; -} - -static long TcAgentIoctl(struct file *file, unsigned int cmd, unsigned long arg) -{ - int ret = TEEC_ERROR_GENERIC; - TcNsDevFile *devFile = file->f_priv; - - if (devFile == NULL) { - tloge("invalid params\n"); - return ret; - } - switch (cmd) { - case TC_NS_CLIENT_IOCTL_WAIT_EVENT: { - ret = TcNsWaitEvent((unsigned int)arg); - break; - } - case TC_NS_CLIENT_IOCTL_SEND_EVENT_RESPONSE: { - ret = TcNsSendEventResponse((unsigned int)arg); - break; - } - case TC_NS_CLIENT_IOCTL_REGISTER_AGENT: { - ret = IoctlRegisterAgent(devFile, arg); - break; - } - case TC_NS_CLIENT_IOCTL_UNREGISTER_AGENT: { - ret = IoctlUnregisterAgent(devFile, arg); - break; - } - case TC_NS_CLIENT_IOCTL_SYC_SYS_TIME: { - ret = TcNsSyncSysTime((TcNsClientTime *)(uintptr_t)arg); - break; - } - case TC_NS_CLIENT_IOCTL_SET_NATIVECA_IDENTITY: { - ret = TcNsSetNativeHash(arg, GLOBAL_CMD_ID_SET_CA_HASH); - break; - } - case TC_NS_CLIENT_IOCTL_LATEINIT: { - ret = TcNsLateInit(arg); - break; - } - default: - tloge("invalid cmd!\n"); - return ret; - } - tlogd("TC_NS_ClientIoctl ret = 0x%x\n", ret); - return ret; -} - -static int TcClientIoctlOthers(struct file *file, int cmd, unsigned long arg) -{ - void *argp = (void __user *)(uintptr_t)arg; - int ret = TEEC_ERROR_GENERIC; - - switch (cmd) { - /* IOCTLs for the secure storage daemon */ - case TC_NS_CLIENT_IOCTL_WAIT_EVENT: - case TC_NS_CLIENT_IOCTL_SEND_EVENT_RESPONSE: - case TC_NS_CLIENT_IOCTL_REGISTER_AGENT: - case TC_NS_CLIENT_IOCTL_UNREGISTER_AGENT: - case TC_NS_CLIENT_IOCTL_SYC_SYS_TIME: - case TC_NS_CLIENT_IOCTL_LOAD_TTF_FILE_AND_NOTCH_HEIGHT: - case TC_NS_CLIENT_IOCTL_SET_NATIVECA_IDENTITY: - case TC_NS_CLIENT_IOCTL_LATEINIT: - ret = TcAgentIoctl(file, cmd, arg); - break; -#ifdef DEF_ENG - case TC_NS_CLIENT_IOCTL_TST_CMD_REQ: { - tlogd("come into tst cmd\n"); - ret = TcNsTstCmd(file->f_priv, argp); - break; - } -#endif - case TC_NS_CLIENT_IOCTL_GET_TEE_VERSION: { - ret = TcNsGetTeeVersion(file->f_priv, argp); - break; - } - case TC_NS_CLIENT_IOCTL_UNMAP_SHARED_MEM: { - ret = TcNsSharedMemUnmap(file->f_priv, (unsigned int)(UINTPTR)argp); - break; - } - default: { - tloge("invalid cmd 0x%x!\n", cmd); - break; - } - } - return ret; -} - -static int TcClientIoctl(struct file *file, int cmd, unsigned long arg) -{ - int ret = TEEC_ERROR_GENERIC; - void *argp = (void __user *)(uintptr_t)arg; - TcNsDevFile *devFile = file->f_priv; - TcNsClientContext clientContext = {{0}}; - - switch (cmd) { - /* IOCTLs for the CAs */ - case TC_NS_CLIENT_IOCTL_SES_OPEN_REQ: - /* Upvote for peripheral zone votage, needed by Coresight. - * Downvote will be processed inside CFC_RETURN_PMCLK_ON_COND - */ - /* Fall through */ - case TC_NS_CLIENT_IOCTL_SES_CLOSE_REQ: - case TC_NS_CLIENT_IOCTL_SEND_CMD_REQ: - ret = TcClientSessionIoctl(file, cmd, arg); - break; - case TC_NS_CLIENT_IOCTL_LOAD_APP_REQ: - ret = TcNsLoadSecfile(devFile, argp); - break; - case TC_NS_CLIENT_IOCTL_CANCEL_CMD_REQ: - if (argp == NULL) { - tloge("argp is NULL input buffer\n"); - ret = -EINVAL; - break; - } - if (copy_from_user(&clientContext, argp, - sizeof(clientContext))) { - tloge("copy from user failed\n"); - ret = -ENOMEM; - break; - } - ret = TcNsSendCmd(devFile, &clientContext); - break; - /* This is the login information - * and is set teecd when client opens a new session - */ - case TC_NS_CLIENT_IOCTL_LOGIN: { - ret = TcNsClientLoginFunc(devFile, argp); - break; - } - default: - ret = TcClientIoctlOthers(file, cmd, arg); - break; - } - - tlogd("tc client ioctl ret = 0x%x\n", ret); - return ret; -} - -static int TcClientOpen(struct file *file) -{ - int ret; - TcNsDevFile *dev = NULL; - ret = CheckProcessAccess(OsCurrTaskGet()); - if (ret) { - tloge(KERN_ERR "teecd service may be exploited 0x%x\n", ret); - return -EPERM; - } - - file->f_priv = NULL; - ret = TcNsClientOpen(&dev, TEE_REQ_FROM_USER_MODE); - if (ret == TEEC_SUCCESS) { - file->f_priv = dev; - } - return ret; -} - -static int TcClientClose(struct file *file) -{ - int ret = TEEC_ERROR_GENERIC; - TcNsDevFile *dev = file->f_priv; - bool checkValue = false; - - checkValue = (IsTeecdProcess(g_teecdTask, OsCurrTaskGet())) && - (!TcNsGetUid()); - if (checkValue == true) { - /* for teecd close fd */ - checkValue = (g_teecdTask->taskStatus & OS_TASK_STATUS_EXIT) || - (OsCurrTaskGet()->taskStatus & OS_TASK_STATUS_EXIT); - if (checkValue == true) { - /* when teecd is be killed or crash */ - tloge("teecd is killed, something bad must be happened!!!\n"); - if (IsSystemAgent(dev)) { - /* for teecd agent close fd */ - SendEventResponseSingle(dev); - FreeDev(dev); - } else { - /* for ca damon close fd */ - ret = NsClientCloseTeecdNotAgent(dev); - } - } else { - /* for ca damon close fd when ca damon close fd - * later than HAL thread - */ - ret = TcNsClientClose(dev); - } - } else { - /* for CA(HAL thread) close fd */ - ret = TcNsClientClose(dev); - } - file->f_priv = NULL; - return ret; -} - -static const struct file_operations_vfs g_tcNsClientFops = { - .open = TcClientOpen, - .close = TcClientClose, - .ioctl = TcClientIoctl, - .mmap = TcClientMmap, -}; - -bool ScheduleWorkOn(int cpu, struct work_struct *work) -{ - return queue_work(g_tzdriverWq, work); -} - -static int TcNsClientInit(void) -{ - int ret; - - tlogd("TcNsClientInit\n"); - - ret = CreateTcClientDevice(TC_NS_CLIENT_DEV_NAME, &g_tcNsClientFops); - if (ret != EOK) { - tloge("create tee device error.\n"); - return ret; - } - ret = memset_s(&g_tcNsDevList, sizeof(g_tcNsDevList), 0, - sizeof(g_tcNsDevList)); - if (ret != EOK) { - return ret; - } - - INIT_LIST_HEAD(&g_tcNsDevList.devFileList); - mutex_init(&g_tcNsDevList.devLock); - INIT_LIST_HEAD(&g_serviceList); - - g_tzdriverWq = create_workqueue("g_tzdriverWq"); - if (g_tzdriverWq == NULL) { - tloge("couldn't create workqueue.\n"); - return -ENOMEM; - } - return 0; -} - -static int TcTeeosInit(void) -{ - int ret; - - ret = SmcInitData(); - if (ret < 0) { - tloge("smc init failed\n"); - return ret; - } - - ret = TcMemInit(); - if (ret < 0) { - tloge("tcmem init failed\n"); - goto SMC_DATA_FREE; - } - - // following failure don't block tzdriver init proc; - AgentInit(); - - ret = TzSpiInit(); - if (ret) { - tloge("tz spi init failed\n"); - } - return 0; - -SMC_DATA_FREE: - SmcFreeData(); - return ret; -} - -static void TcReInit(void) -{ - int ret = 0; - - if (InitSmcSvcThread()) { - tloge("init svc thread\n"); - ret = -EFAULT; - } - - if (ret) { - tloge("Caution! Running environment init failed!\n"); - } -} - -int TcInit(void) -{ - int ret = TcNsClientInit(); - if (ret != 0) { - goto TC_INIT_FAIL; - } - - ret = TcTeeosInit(); - if (ret != 0) { - goto TC_INIT_FAIL; - } - // run-time environment init failure don't block tzdriver init proc; - TcReInit(); - -#ifdef DEF_ENG - TzdebugInit(); -#endif - return 0; - -TC_INIT_FAIL: - ret = unregister_driver(TC_NS_CLIENT_DEV_NAME); - if (g_tzdriverWq != NULL) { - destroy_workqueue(g_tzdriverWq); - } - return ret; -} diff --git a/tzdriver/src/tc_client_sub_driver.c b/tzdriver/src/tc_client_sub_driver.c deleted file mode 100644 index e2fd6e1..0000000 --- a/tzdriver/src/tc_client_sub_driver.c +++ /dev/null @@ -1,1131 +0,0 @@ -/* - * Copyright (c) 2013-2019 Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020-2021 Huawei Device Co., Ltd. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "tc_client_sub_driver.h" -#include "agent.h" -#include "gp_ops.h" -#include "mailbox_mempool.h" -#ifdef SECURITY_AUTH_ENHANCE -#include "security_auth_enhance.h" -#endif -#include "smc.h" -#include "tc_client_driver.h" -#include "tc_ns_log.h" -#include "tzdriver_compat.h" - -static DEFINE_MUTEX(g_loadAppLock); - -#ifdef SECURITY_AUTH_ENHANCE - -typedef struct { - TcNsDevFile *devFile; - TcNsClientContext *context; - TcNsSession *session; -} GetSecureInfoParams; - -static int CheckRandomData(const uint8_t *data, uint32_t size) -{ - uint32_t i; - - for (i = 0; i < size; i++) { - if (data[i] != 0) { - break; - } - } - if (i >= size) { - return -1; - } - return 0; -} - -int GenerateRandomData(uint8_t *data, uint32_t size) -{ - if (data == NULL || size == 0) { - tloge("Bad parameters!\n"); - return -EFAULT; - } - if (memset_s((void *)data, size, 0, size)) { - tloge("Clean the data buffer failed!\n"); - return -EFAULT; - } - GetRandomBytesArch((void *)data, size); - if (CheckRandomData(data, size) != 0) { - return -EFAULT; - } - return 0; -} - -bool IsValidEncryptionHead(const struct EncryptionHead *head, - const uint8_t *data, uint32_t len) -{ - if (head == NULL || data == NULL || len == 0) { - tloge("In parameters check failed.\n"); - return false; - } - - if (strncmp((const char *)head->magic, MAGIC_STRING, sizeof(MAGIC_STRING))) { - tloge("Magic string is invalid.\n"); - return false; - } - - if (head->payloadLen != len) { - tloge("Payload length is invalid.\n"); - return false; - } - return true; -} - -int GenerateChallengeWord(uint8_t *challengeWord, uint32_t size) -{ - if (challengeWord == NULL) { - tloge("Parameter is null pointer!\n"); - return -EINVAL; - } - return GenerateRandomData(challengeWord, size); -} - -int SetEncryptionHead(struct EncryptionHead *head, - uint32_t len) -{ - if (head == NULL || len == 0) { - tloge("In parameters check failed.\n"); - return -EINVAL; - } - if (strncpy_s((char *)head->magic, sizeof(head->magic), - MAGIC_STRING, strlen(MAGIC_STRING) + 1)) { - tloge("Copy magic string failed.\n"); - return -EFAULT; - } - head->payloadLen = len; - return 0; -} - -static TcNsDevFile *TcFindDevFile(unsigned int devFileId) -{ - TcNsDevFile *devFile = NULL; - - list_for_each_entry(devFile, &GetTcNsDevList()->devFileList, head) { - if (devFile->devFileId == devFileId) { - return devFile; - } - } - return NULL; -} - -TcNsSession *TcFindSession2(unsigned int devFileId, - const TcNsSmcCmd *cmd) -{ - TcNsDevFile *devFile = NULL; - TcNsService *service = NULL; - TcNsSession *session = NULL; - - if (cmd == NULL) { - tloge("Parameter is null pointer!\n"); - return NULL; - } - mutex_lock(&GetTcNsDevList()->devLock); - devFile = TcFindDevFile(devFileId); - mutex_unlock(&GetTcNsDevList()->devLock); - if (devFile == NULL) { - tloge("Can't find dev file! devFileId %d\n", devFileId); - return NULL; - } - mutex_lock(&devFile->serviceLock); - service = TcFindServiceInDev(devFile, cmd->uuid, UUID_LEN); - GetServiceStruct(service); - mutex_unlock(&devFile->serviceLock); - if (service == NULL) { - tloge(" Can't find service!\n"); - return NULL; - } - mutex_lock(&service->SessionLock); - session = TcFindSessionWithOwner(&service->sessionList, - cmd->contextId, devFile); - GetSessionStruct(session); - mutex_unlock(&service->SessionLock); - PutServiceStruct(service); - if (session == NULL) { - tloge("can't find session[0x%x]!\n", cmd->contextId); - return NULL; - } - return session; -} - -static inline uint32_t AlginUp(uint32_t x, uint32_t align) -{ - return (x + align - 1) & ~(align - 1); -} - -void CleanSessionSecureInformation(TcNsSession *session) -{ - if (session != NULL) { - if (memset_s((void *)&session->secureInfo, - sizeof(session->secureInfo), 0, sizeof(session->secureInfo))) - tloge("Clean this session secure information failed!\n"); - } -} - -static int AllocSecureParams(uint32_t secureParamsAlignedSize, - uint32_t paramsSize, struct SessionSecureParams **reeSecureParams, - struct SessionSecureParams **teeSecureParams) -{ - if (secureParamsAlignedSize == 0) { - tloge("secureParamsAlignedSize is invalid.\n"); - return -ENOMEM; - } - *reeSecureParams = MailboxAlloc(paramsSize, 0); - if (*reeSecureParams == NULL) { - tloge("Malloc REE session secure parameters buffer failed.\n"); - return -ENOMEM; - } - *teeSecureParams = calloc(1, secureParamsAlignedSize); - if (ZERO_OR_NULL_PTR((unsigned long)(uintptr_t)(*teeSecureParams))) { - tloge("Malloc TEE session secure parameters buffer failed.\n"); - MailboxFree(*reeSecureParams); - *reeSecureParams = NULL; - return -ENOMEM; - } - return 0; -} - -static int InitForAllocSecureParams(GetSecureInfoParams *paramsIn, - uint32_t *secureParamsAlignedSize, uint32_t *paramsSize) -{ - int ret; - - ret = GenerateChallengeWord( - (uint8_t *)¶msIn->session->secureInfo.challengeWord, - sizeof(paramsIn->session->secureInfo.challengeWord)); - if (ret) { - tloge("Generate challenge word failed, ret = %d\n", ret); - return ret; - } - *secureParamsAlignedSize = - AlginUp(sizeof(struct SessionSecureParams), CIPHER_BLOCK_BYTESIZE); - *paramsSize = *secureParamsAlignedSize + IV_BYTESIZE; - return 0; -} - -static int SendSmcCmdForSecureParams(const GetSecureInfoParams *paramsIn, - struct SessionSecureParams *reeSecureParams) -{ - int ret; - TcNsSmcCmd smcCmd = { {0}, 0 }; - uint32_t uid; - - uid = GetTaskUid(OsCurrTaskGet()); - /* Transfer chanllenge word to secure world */ - reeSecureParams->payload.ree2tee.challengeWord = - paramsIn->session->secureInfo.challengeWord; - smcCmd.globalCmd = true; - if (memcpy_s(smcCmd.uuid, sizeof(smcCmd.uuid), - paramsIn->context->uuid, UUID_LEN)) { - tloge("memcpy_s uuid error.\n"); - return -EFAULT; - } - smcCmd.cmdId = GLOBAL_CMD_ID_GET_SESSION_SECURE_PARAMS; - smcCmd.devFileId = paramsIn->devFile->devFileId; - smcCmd.contextId = paramsIn->context->sessionId; - smcCmd.operationPhys = 0; - smcCmd.operationHphys = 0; - smcCmd.loginDataPhy = 0; - smcCmd.loginDataHaddr = 0; - smcCmd.loginDataLen = 0; - smcCmd.errOrigin = 0; - smcCmd.uid = uid; - smcCmd.started = paramsIn->context->started; - smcCmd.paramsPhys = LOS_PaddrQuery((void *)reeSecureParams); - smcCmd.paramsHphys = 0; - ret = TcNsSmc(&smcCmd); - if (ret) { - reeSecureParams->payload.ree2tee.challengeWord = 0; - tloge("TC_NS_SMC returns error, ret = %d\n", ret); - return ret; - } - return 0; -} - -static int UpdateSecureParamsFromTee(GetSecureInfoParams *paramsIn, - struct SessionSecureParams *reeSecureParams, - struct SessionSecureParams *teeSecureParams, - uint32_t secureParamsAlignedSize, - uint32_t paramsSize) -{ - int ret; - uint8_t *encSecureParams = NULL; - /* Get encrypted session secure parameters from secure world */ - encSecureParams = (uint8_t *)reeSecureParams; - struct SessionCryptoInfo *rootKey = GetSessionRootKeyInstance(); - if (rootKey == NULL) { - return -EINVAL; - } - ret = CryptoSessionAescbcKey256(encSecureParams, paramsSize, - (uint8_t *)teeSecureParams, secureParamsAlignedSize, - rootKey->key, NULL, DECRYPT); - if (ret) { - tloge("Decrypted session secure parameters failed, ret = %d.\n", ret); - return ret; - } - /* Analyze encryption head */ - - if (!IsValidEncryptionHead(&teeSecureParams->head, - (uint8_t *)&teeSecureParams->payload, - sizeof(teeSecureParams->payload))) - return -EFAULT; - - /* Store session secure parameters */ - ret = memcpy_s((void *)paramsIn->session->secureInfo.scrambling, - sizeof(paramsIn->session->secureInfo.scrambling), - (void *)&teeSecureParams->payload.tee2ree.scrambling, - sizeof(teeSecureParams->payload.tee2ree.scrambling)); - if (ret) { - tloge("Memcpy scrambling data failed, ret = %d.\n", ret); - return ret; - } - ret = memcpy_s((void *)¶msIn->session->secureInfo.cryptoInfo, - sizeof(paramsIn->session->secureInfo.cryptoInfo), - (void *)&teeSecureParams->payload.tee2ree.cryptoInfo, - sizeof(teeSecureParams->payload.tee2ree.cryptoInfo)); - if (ret) { - tloge("Memcpy session crypto information failed, ret = %d.\n", ret); - return ret; - } - return 0; -} - -int GetSessionSecureParams(TcNsDevFile *devFile, - TcNsClientContext *context, TcNsSession *session) -{ - int ret; - uint32_t paramsSize; - uint32_t secureParamsAlignedSize; - struct SessionSecureParams *reeSecureParams = NULL; - struct SessionSecureParams *teeSecureParams = NULL; - bool checkValue = false; - GetSecureInfoParams paramsIn = { devFile, context, session }; - - checkValue = (devFile == NULL || context == NULL || session == NULL); - if (checkValue == true) { - tloge("Parameter is null pointer!\n"); - return -EINVAL; - } - ret = InitForAllocSecureParams(¶msIn, - &secureParamsAlignedSize, ¶msSize); - if (ret != 0) { - return ret; - } - ret = AllocSecureParams(secureParamsAlignedSize, - paramsSize, &reeSecureParams, &teeSecureParams); - if (ret != 0) { - return ret; - } - ret = SendSmcCmdForSecureParams(¶msIn, reeSecureParams); - if (ret != 0) { - goto free; - } - - ret = UpdateSecureParamsFromTee(¶msIn, reeSecureParams, - teeSecureParams, secureParamsAlignedSize, paramsSize); - if (memset_s((void *)teeSecureParams, secureParamsAlignedSize, - 0, secureParamsAlignedSize)) { - tloge("Clean the secure parameters buffer failed!\n"); - } -free: - MailboxFree(reeSecureParams); - reeSecureParams = NULL; - free(teeSecureParams); - teeSecureParams = NULL; - if (ret) { - CleanSessionSecureInformation(session); - } - return ret; -} - -int GenerateEncryptedSessionSecureParams( - const struct SessionSecureInfo *secureInfo, - uint8_t *encSecureParams, size_t encParamsSize) -{ - int ret; - struct SessionSecureParams *reeSecureParams = NULL; - uint32_t secureParamsAlignedSize = - AlginUp(sizeof(*reeSecureParams), CIPHER_BLOCK_BYTESIZE); - uint32_t paramsSize = secureParamsAlignedSize + IV_BYTESIZE; - - if (secureInfo == NULL || encSecureParams == NULL || - encParamsSize < paramsSize) { - tloge("invalid enc params\n"); - return -EINVAL; - } - reeSecureParams = calloc(1, secureParamsAlignedSize); - if (ZERO_OR_NULL_PTR((unsigned long)(uintptr_t)reeSecureParams)) { - tloge("Malloc REE session secure parameters buffer failed.\n"); - return -ENOMEM; - } - /* Transfer chanllenge word to secure world */ - reeSecureParams->payload.ree2tee.challengeWord = secureInfo->challengeWord; - /* Setting encryption head */ - ret = SetEncryptionHead(&reeSecureParams->head, - sizeof(reeSecureParams->payload)); - if (ret) { - tloge("Set encryption head failed, ret = %d.\n", ret); - reeSecureParams->payload.ree2tee.challengeWord = 0; - free(reeSecureParams); - return -EINVAL; - } - /* Setting padding data */ - ret = CryptoAescbcCmsPadding((uint8_t *)reeSecureParams, - secureParamsAlignedSize, - sizeof(struct SessionSecureParams)); - if (ret) { - tloge("Set encryption padding data failed, ret = %d.\n", ret); - reeSecureParams->payload.ree2tee.challengeWord = 0; - free(reeSecureParams); - return -EINVAL; - } - /* Encrypt buffer with current session key */ - ret = CryptoSessionAescbcKey256((uint8_t *)reeSecureParams, - secureParamsAlignedSize, - encSecureParams, paramsSize, secureInfo->cryptoInfo.key, - NULL, ENCRYPT); - if (ret) { - tloge("Encrypted session secure parameters failed, ret = %d.\n", - ret); - reeSecureParams->payload.ree2tee.challengeWord = 0; - free(reeSecureParams); - return -EINVAL; - } - reeSecureParams->payload.ree2tee.challengeWord = 0; - free(reeSecureParams); - return 0; -} - -static int CheckParamsForCryptoSession(const uint8_t *in, const uint8_t *out, - const uint8_t *key, uint32_t inLen, uint32_t outLen) -{ - if (in == NULL || out == NULL || key == NULL) { - tloge("AES-CBC crypto parameters have null pointer.\n"); - return -EINVAL; - } - if (inLen < IV_BYTESIZE || outLen < IV_BYTESIZE) { - tloge("AES-CBC crypto data length is invalid.\n"); - return -EINVAL; - } - return 0; -} - -int CryptoSessionAescbcKey256(uint8_t *in, uint32_t inLen, uint8_t *out, - uint32_t outLen, const uint8_t *key, uint8_t *iv, uint32_t mode) -{ - int ret; - uint32_t srcLen; - uint32_t destLen; - uint8_t *aescbcIv = NULL; - bool checkValue = false; - - ret = CheckParamsForCryptoSession(in, out, key, inLen, outLen); - if (ret) { - return ret; - } - /* For iv variable is null, iv is the first 16 bytes - * in cryptotext buffer. - */ - switch (mode) { - case ENCRYPT: - srcLen = inLen; - destLen = outLen - IV_BYTESIZE; - aescbcIv = out + destLen; - break; - case DECRYPT: - srcLen = inLen - IV_BYTESIZE; - destLen = outLen; - aescbcIv = in + srcLen; - break; - default: - tloge("AES-CBC crypto use error mode = %u.\n", mode); - return -EINVAL; - } - - /* IV is configured by user */ - if (iv != NULL) { - srcLen = inLen; - destLen = outLen; - aescbcIv = iv; - } - checkValue = (srcLen != destLen) || (srcLen == 0) || - (srcLen % CIPHER_BLOCK_BYTESIZE); - if (checkValue == true) { - tloge("AES-CBC, plaintext-len must be equal to cryptotext's. srcLen=%u, destLen=%u.\n", - srcLen, destLen); - return -EINVAL; - } - /* IV is configured in here */ - checkValue = (iv == NULL) && (mode == ENCRYPT); - if (checkValue == true) { - ret = GenerateRandomData(aescbcIv, IV_BYTESIZE); - if (ret) { - tloge("Generate AES-CBC iv failed, ret = %d.\n", ret); - return ret; - } - } - struct AesParam param = { - aescbcIv, key, srcLen, mode - }; - return CryptoAescbcKey256(out, in, ¶m); -} - -int CryptoAescbcCmsPadding(uint8_t *plaintext, uint32_t plaintextLen, - uint32_t payloadLen) -{ - uint32_t paddingLen; - uint8_t padding; - bool checkValue = false; - - if (plaintext == NULL) { - tloge("Plaintext is NULL.\n"); - return -EINVAL; - } - checkValue = (!plaintextLen) || - (plaintextLen % CIPHER_BLOCK_BYTESIZE) || - (plaintextLen < payloadLen); - if (checkValue == true) { - tloge("Plaintext length is invalid.\n"); - return -EINVAL; - } - paddingLen = plaintextLen - payloadLen; - if (paddingLen >= CIPHER_BLOCK_BYTESIZE) { - tloge("Padding length is error.\n"); - return -EINVAL; - } - if (paddingLen == 0) { - /* No need padding */ - return 0; - } - padding = (uint8_t)paddingLen; - if (memset_s((void *)(plaintext + payloadLen), - paddingLen, padding, paddingLen)) { - tloge("CMS-Padding is failed.\n"); - return -EFAULT; - } - return 0; -} -#endif - -char *GetProcessPath(LosTaskCB *task, char *tpath, int pathLen) -{ - if (task == NULL || tpath == NULL || pathLen < 0 || pathLen > MAX_PATH_SIZE) { - return NULL; - } - - struct Vnode *node = OsProcessExecVnodeGet(OS_PCB_FROM_PID(task->processID)); - if (node == NULL) { - return NULL; - } - int ret = memset_s(tpath, pathLen, '\0', pathLen); - if (ret != EOK) { - tloge("memset error ret is %d\n", ret); - return NULL; - } - - ret = memcpy_s(tpath, pathLen - 1, node->filePath, strlen(node->filePath)); - if (ret != EOK) { - tloge("memcpy error ret is %d\n", ret); - return NULL; - } - return tpath; -} - -int CalcProcessPathHash(const unsigned char *data, - unsigned long dataLen, unsigned char *digest, unsigned int digLen) -{ - bool checkValue = false; - TeeSha256Context ctx; - - checkValue = (data == NULL || digest == NULL || - dataLen == 0 || digLen != SHA256_DIGEST_LENTH); - if (checkValue == true) { - tloge("Bad parameters!\n"); - return -EFAULT; - } - - TeeSha256Init(&ctx); - TeeSha256Update(&ctx, data, dataLen); - TeeSha256Final(&ctx, digest); - return 0; -} - -int PackCaCert(char *caCert, const char *path, - LosTaskCB *caTask, int uid) -{ - int messageSize; - - if (caCert == NULL || path == NULL || caTask == NULL) { - return 0; - } - - messageSize = snprintf_s(caCert, BUF_MAX_SIZE - 1, - BUF_MAX_SIZE - 1, "%s%u", path, - uid); - - return messageSize; -} - -#define MAX_REF_COUNT 255 -TcNsService *TcRefServiceInDev(TcNsDevFile *dev, const unsigned char *uuid, - int uuidSize, bool *isFull) -{ - uint32_t i; - - if (dev == NULL || uuid == NULL || uuidSize != UUID_LEN || - isFull == NULL) { - return NULL; - } - for (i = 0; i < SERVICES_MAX_COUNT; i++) { - if (dev->services[i] != NULL && - memcmp(dev->services[i]->uuid, uuid, UUID_LEN) == 0) { - if (dev->serviceRef[i] == MAX_REF_COUNT) { - *isFull = true; - return NULL; - } - dev->serviceRef[i]++; - return dev->services[i]; - } - } - return NULL; -} - -TcNsService *TcFindServiceInDev(TcNsDevFile *dev, - const unsigned char *uuid, int uuidSize) -{ - uint32_t i; - - if (dev == NULL || uuid == NULL || uuidSize != UUID_LEN) { - return NULL; - } - for (i = 0; i < SERVICES_MAX_COUNT; i++) { - if (dev->services[i] != NULL && - memcmp(dev->services[i]->uuid, uuid, UUID_LEN) == 0) { - return dev->services[i]; - } - } - return NULL; -} - -TcNsService *TcFindServiceFromAll(const unsigned char *uuid, uint32_t uuidLen) -{ - TcNsService *service = NULL; - - if (uuid == NULL || uuidLen != UUID_LEN) { - return NULL; - } - list_for_each_entry(service, GetServiceList(), head) { - if (memcmp(service->uuid, uuid, sizeof(service->uuid)) == 0) { - return service; - } - } - return NULL; -} - -int AddServiceToDev(TcNsDevFile *dev, TcNsService *service) -{ - uint32_t i; - - if (dev == NULL || service == NULL) { - return -1; - } - for (i = 0; i < SERVICES_MAX_COUNT; i++) { - if (dev->services[i] == NULL) { - tlogd("add service %u to %u\n", i, dev->devFileId); - dev->services[i] = service; - dev->serviceRef[i] = 1; - return 0; - } - } - return -1; -} - -void DelServiceFromDev(TcNsDevFile *dev, TcNsService *service) -{ - uint32_t i; - - if (dev == NULL || service == NULL) { - return; - } - for (i = 0; i < SERVICES_MAX_COUNT; i++) { - if (dev->services[i] != service) { - continue; - } - tlogd("dev->serviceRef[%u] = %u\n", i, dev->serviceRef[i]); - if (dev->serviceRef[i] == 0) { - tloge("Caution! No service to be deleted!\n"); - break; - } - dev->serviceRef[i]--; - if (!dev->serviceRef[i]) { - tlogd("del service %u from %u\n", i, dev->devFileId); - dev->services[i] = NULL; - PutServiceStruct(service); - } - break; - } -} - -TcNsSession *TcFindSessionWithOwner(struct list_head *sessionList, - unsigned int sessionId, TcNsDevFile *devFile) -{ - TcNsSession *session = NULL; - bool checkValue = false; - - checkValue = (sessionList == NULL || devFile == NULL); - if (checkValue == true) { - tloge("sessionList or devFile is Null.\n"); - return NULL; - } - list_for_each_entry(session, sessionList, head) { - checkValue = (session->sessionId == sessionId && - session->owner == devFile); - if (checkValue == true) { - return session; - } - } - return NULL; -} - -void DumpServicesStatus(const char *param) -{ - TcNsService *service = NULL; - - (void)param; - mutex_lock(GetServiceListLock()); - tlogi("show service list:\n"); - list_for_each_entry(service, GetServiceList(), head) { - tlogi("uuid-%x, usage=%d\n", *(uint32_t *)service->uuid, - atomic_read(&service->usage)); - } - mutex_unlock(GetServiceListLock()); -} - -errno_t InitContext(TcNsClientContext *context, const unsigned char *uuid, - const unsigned int uuidLen) -{ - errno_t sret; - - if (context == NULL || uuid == NULL || uuidLen != UUID_LEN) { - return -1; - } - sret = memset_s(context, sizeof(*context), 0, sizeof(*context)); - if (sret != EOK) { - return -1; - } - - sret = memcpy_s(context->uuid, sizeof(context->uuid), uuid, uuidLen); - if (sret != EOK) { - return -1; - } - return 0; -} - -int CloseSession(TcNsDevFile *dev, TcNsSession *session, - const unsigned char *uuid, unsigned int uuidLen, unsigned int sessionId) -{ - TcNsClientContext context; - int ret; - errno_t sret; - bool checkValue = false; - - checkValue = (dev == NULL || session == NULL || - uuid == NULL || uuidLen != UUID_LEN); - if (checkValue == true) { - return TEEC_ERROR_GENERIC; - } - sret = InitContext(&context, uuid, uuidLen); - if (sret != 0) { - return TEEC_ERROR_GENERIC; - } - context.sessionId = sessionId; - context.cmdId = GLOBAL_CMD_ID_CLOSE_SESSION; - ret = TcClientCall(&context, dev, session, - TC_CALL_GLOBAL | TC_CALL_SYNC); - if (ret) { - tloge("close session failed, ret=0x%x\n", ret); - } - return ret; -} - -void KillSession(TcNsDevFile *dev, const unsigned char *uuid, - unsigned int uuidLen, unsigned int sessionId) -{ - TcNsClientContext context; - int ret; - errno_t sret; - - if (dev == NULL || uuid == NULL || uuidLen != UUID_LEN) { - return; - } - sret = InitContext(&context, uuid, uuidLen); - if (sret != 0) { - return; - } - context.sessionId = sessionId; - context.cmdId = GLOBAL_CMD_ID_KILL_TASK; - tlogd("devFileId=%u\n", dev->devFileId); - /* do clear work in agent */ - TeeAgentClearWork(&context, dev->devFileId); - ret = TcClientCall(&context, dev, NULL, - TC_CALL_GLOBAL | TC_CALL_SYNC); - if (ret) { - tloge("close session failed, ret=0x%x\n", ret); - } - return; -} - -int TcNsServiceInit(const unsigned char *uuid, uint32_t uuidLen, - TcNsService **newService) -{ - int ret = 0; - TcNsService *service = NULL; - errno_t sret; - bool checkValue = false; - - checkValue = (uuid == NULL || newService == NULL || - uuidLen != UUID_LEN); - if (checkValue == true) { - return -ENOMEM; - } - service = calloc(1, sizeof(*service)); - if (ZERO_OR_NULL_PTR((unsigned long)(uintptr_t)service)) { - tloge("calloc failed\n"); - ret = -ENOMEM; - return ret; - } - sret = memcpy_s(service->uuid, sizeof(service->uuid), uuid, uuidLen); - if (sret != EOK) { - free(service); - return -ENOMEM; - } - INIT_LIST_HEAD(&service->sessionList); - mutex_init(&service->SessionLock); - list_add_tail(&service->head, GetServiceList()); - tlogd("add service [0x%x] to service list\n", *(uint32_t *)uuid); - atomic_set(&service->usage, 1); - mutex_init(&service->operationLock); - *newService = service; - return ret; -} - -uint32_t TcNsGetUid(void) -{ - return GetTaskUid(OsCurrTaskGet()); -} - -int GetPackNameLen(TcNsDevFile *devFile, const uint8_t *certBuffer, - unsigned int certBufferSize) -{ - errno_t sret; - - if (devFile == NULL || certBuffer == NULL || certBufferSize == 0) { - return -ENOMEM; - } - sret = memcpy_s(&devFile->pkgNameLen, sizeof(devFile->pkgNameLen), - certBuffer, sizeof(devFile->pkgNameLen)); - if (sret != EOK) { - return -ENOMEM; - } - tlogd("package_name_len is %u\n", devFile->pkgNameLen); - if (devFile->pkgNameLen == 0 || - devFile->pkgNameLen >= MAX_PACKAGE_NAME_LEN) { - tloge("Invalid size of package name len login info!\n"); - return -EINVAL; - } - return 0; -} - -int GetPublicKeyLen(TcNsDevFile *devFile, const uint8_t *certBuffer, - unsigned int certBufferSize) -{ - errno_t sret; - - if (devFile == NULL || certBuffer == NULL || certBufferSize == 0) { - return -ENOMEM; - } - sret = memcpy_s(&devFile->pubKeyLen, sizeof(devFile->pubKeyLen), - certBuffer, sizeof(devFile->pubKeyLen)); - if (sret != EOK) { - return -ENOMEM; - } - tlogd("publick_key_len is %u\n", devFile->pubKeyLen); - if (devFile->pubKeyLen > MAX_PUBKEY_LEN) { - tloge("Invalid public key length in login info!\n"); - return -EINVAL; - } - return 0; -} - -bool IsValidTaSize(const char *fileBuffer, unsigned int fileSize) -{ - if (fileBuffer == NULL || fileSize == 0) { - tloge("invalid load ta size\n"); - return false; - } - if (fileSize > SZ_8M) { - tloge("larger than 8M TA is not supportedi, size=%d\n", fileSize); - return false; - } - return true; -} - -int TcNsNeedLoadImage(unsigned int fileId, const unsigned char *uuid, - unsigned int uuidLen) -{ - int ret = 0; - int smcRet; - TcNsSmcCmd smcCmd = { {0}, 0 }; - struct MbCmdPack *mbPack = NULL; - char *mbParam = NULL; - - if (uuid == NULL || uuidLen != UUID_LEN) { - tloge("invalid uuid\n"); - return -ENOMEM; - } - mbPack = MailboxAllocCmdPack(); - if (mbPack == NULL) { - tloge("alloc mb pack failed\n"); - return -ENOMEM; - } - - mbParam = MailboxCopyAlloc((void *)uuid, uuidLen); - if (mbParam == NULL) { - tloge("alloc mb param failed\n"); - ret = -ENOMEM; - goto clean; - } - - mbPack->operation.paramTypes = TEEC_MEMREF_TEMP_INOUT; - mbPack->operation.params[0].memref.buffer = LOS_PaddrQuery((void *)mbParam); - mbPack->operation.bufferHaddr[0] = 0; - mbPack->operation.params[0].memref.size = SZ_4K; - smcCmd.cmdId = GLOBAL_CMD_ID_NEED_LOAD_APP; - smcCmd.globalCmd = true; - smcCmd.devFileId = fileId; - smcCmd.contextId = 0; - smcCmd.operationPhys = LOS_PaddrQuery(&mbPack->operation); - smcCmd.operationHphys = 0; - tlogd("secure app load smc command\n"); - smcRet = TcNsSmc(&smcCmd); - if (smcRet != 0) { - tloge("smc_call returns error ret 0x%x\n", smcRet); - ret = -1; - goto clean; - } else { - ret = *(int *)mbParam; - } - -clean: - if (mbParam != NULL) { - MailboxFree(mbParam); - } - MailboxFree(mbPack); - - return ret; -} - -int TcNsLoadSecfile(TcNsDevFile *devFile, - const void *argp) -{ - int ret; - struct LoadSecfileIoctlStruct ioctlArg = { 0, {0}, 0, { NULL } }; - - if (devFile == NULL || argp == NULL) { - tloge("Invalid params !\n"); - return -EINVAL; - } - if (copy_from_user(&ioctlArg, argp, sizeof(ioctlArg))) { - tloge("copy from user failed\n"); - ret = -ENOMEM; - return ret; - } - mutex_lock(&g_loadAppLock); - if (ioctlArg.secfileType == LOAD_TA) { - ret = TcNsNeedLoadImage(devFile->devFileId, - ioctlArg.uuid, (unsigned int)UUID_LEN); - if (ret == 1) { // 1 means we need to load image - ret = TcNsLoadImage(devFile, ioctlArg.fileBuffer, - ioctlArg.fileSize); - } - } else if (ioctlArg.secfileType == LOAD_LIB) { - ret = TcNsLoadImage(devFile, - ioctlArg.fileBuffer, ioctlArg.fileSize); - } else { - tloge("invalid secfile type: %d!", ioctlArg.secfileType); - ret = -EINVAL; - } - - if (ret) { - tloge("load TA secfile: %d failed, ret = %x", ioctlArg.secfileType, ret); - } - mutex_unlock(&g_loadAppLock); - return ret; -} - -int LoadTaImage(TcNsDevFile *devFile, TcNsClientContext *context) -{ - int ret; - - if (devFile == NULL || context == NULL) { - return -1; - } - mutex_lock(&g_loadAppLock); - ret = TcNsNeedLoadImage(devFile->devFileId, context->uuid, - (unsigned int)UUID_LEN); - if (ret == 1) { - if (context->fileBuffer == NULL) { - tloge("context's fileBuffer is NULL"); - mutex_unlock(&g_loadAppLock); - return -1; - } - ret = TcNsLoadImage(devFile, context->fileBuffer, - context->fileSize); - if (ret) { - tloge("load image failed, ret=%x", ret); - mutex_unlock(&g_loadAppLock); - return ret; - } - } - mutex_unlock(&g_loadAppLock); - return ret; -} - -void ReleaseFreeSession(TcNsDevFile *devFile, - TcNsClientContext *context, TcNsSession *session) -{ - bool needKillSession = false; -#ifdef SECURITY_AUTH_ENHANCE - bool needFree = false; -#endif - - if (devFile == NULL || context == NULL || session == NULL) { - return; - } - needKillSession = context->sessionId != 0; - if (needKillSession) { - KillSession(devFile, context->uuid, (unsigned int)UUID_LEN, context->sessionId); - } -#ifdef SECURITY_AUTH_ENHANCE - needFree = (session != NULL && - session->TcNsToken.tokenBuffer != NULL); - if (needFree) { - if (memset_s((void *)session->TcNsToken.tokenBuffer, - session->TcNsToken.tokenLen, - 0, session->TcNsToken.tokenLen) != EOK) { - tloge("Caution, memset failed!\n"); - } - free(session->TcNsToken.tokenBuffer); - session->TcNsToken.tokenBuffer = NULL; - } -#endif -} - -void CloseSessionInServiceList(TcNsDevFile *dev, TcNsService *service, - uint32_t index) -{ - TcNsSession *tmpSession = NULL; - TcNsSession *session = NULL; - errno_t retErr; - int ret; - - if (dev == NULL || service == NULL || index >= SERVICES_MAX_COUNT) { - return; - } - list_for_each_entry_safe(session, tmpSession, - &dev->services[index]->sessionList, head) { - if (session->owner != dev) { - continue; - } - ret = CloseSession(dev, session, service->uuid, - (unsigned int)UUID_LEN, session->sessionId); - if (ret != TEEC_SUCCESS) { - tloge("close session smc(when close fd) failed!\n"); - } -#ifdef SECURITY_AUTH_ENHANCE - /* Clean session secure information */ - retErr = memset_s((void *)&session->secureInfo, - sizeof(session->secureInfo), - 0, - sizeof(session->secureInfo)); - if (retErr != EOK) { - tloge("TcNsClientClose memset error=%d\n", retErr); - } -#endif - mutex_lock(&service->SessionLock); - list_del(&session->head); - mutex_unlock(&service->SessionLock); - PutSessionStruct(session); /* pair with open session */ - } -} - -void CloseUnclosedSession(TcNsDevFile *dev, uint32_t index) -{ - TcNsService *service = NULL; - - if (dev == NULL || index >= SERVICES_MAX_COUNT) { - return; - } - if (dev->services[index] != NULL && - !list_empty(&dev->services[index]->sessionList)) { - service = dev->services[index]; - - mutex_lock(&service->operationLock); - CloseSessionInServiceList(dev, service, index); - mutex_unlock(&service->operationLock); - PutServiceStruct(service); /* pair with open session */ - } -} - -void DelDevNode(TcNsDevFile *dev) -{ - if (dev == NULL) { - return; - } - mutex_lock(&GetTcNsDevList()->devLock); - /* del dev from the list */ - list_del(&dev->head); - mutex_unlock(&GetTcNsDevList()->devLock); -} - -int NsClientCloseTeecdNotAgent(TcNsDevFile *dev) -{ - if (dev == NULL) { - tloge("invalid dev(null)\n"); - return TEEC_ERROR_GENERIC; - } - DelDevNode(dev); - free(dev); - return TEEC_SUCCESS; -} diff --git a/tzdriver/src/teek_client_api.c b/tzdriver/src/teek_client_api.c deleted file mode 100644 index d890f52..0000000 --- a/tzdriver/src/teek_client_api.c +++ /dev/null @@ -1,765 +0,0 @@ -/* - * Copyright (c) 2013-2019 Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020-2021 Huawei Device Co., Ltd. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "teek_client_api.h" -#include -#include "tc_ns_log.h" -#include "tzdriver_compat.h" - -static void EncdeForPartMem(TcNsClientContext *cliContext, - const TeecOperation *operation, uint32_t paramCnt, uint32_t *paramType) -{ - uint32_t diff = (uint32_t)TEEC_MEMREF_PARTIAL_INPUT - - (uint32_t)TEEC_MEMREF_TEMP_INPUT; - - if (paramCnt < TEE_PARAM_NUM) { - /* buffer offset len */ - if (paramType[paramCnt] == TEEC_MEMREF_WHOLE) { - cliContext->params[paramCnt].memref.offset = 0; - cliContext->params[paramCnt].memref.sizeAddr = - (uint64_t)(uintptr_t)&operation->params[paramCnt].memref.parent->size; - } else { - cliContext->params[paramCnt].memref.offset = - operation->params[paramCnt].memref.offset; - cliContext->params[paramCnt].memref.sizeAddr = - (uint64_t)(uintptr_t)&operation->params[paramCnt].memref.size; - } - if (operation->params[paramCnt].memref.parent->isAllocated) { - cliContext->params[paramCnt].memref.buffer = - (uint64_t)(uintptr_t) - operation->params[paramCnt].memref.parent->buffer; - } else { - cliContext->params[paramCnt].memref.buffer = - (uint64_t)(uintptr_t) - operation->params[paramCnt].memref.parent->buffer + - operation->params[paramCnt].memref.offset; - cliContext->params[paramCnt].memref.offset = 0; - } - /* translate the paramType to know the driver */ - if (paramType[paramCnt] == TEEC_MEMREF_WHOLE) { - switch (operation->params[paramCnt].memref.parent->flags) { - case TEEC_MEM_INPUT: - paramType[paramCnt] = TEEC_MEMREF_PARTIAL_INPUT; - break; - case TEEC_MEM_OUTPUT: - paramType[paramCnt] = TEEC_MEMREF_PARTIAL_OUTPUT; - break; - case TEEC_MEM_INOUT: - paramType[paramCnt] = TEEC_MEMREF_PARTIAL_INOUT; - break; - default: - paramType[paramCnt] = TEEC_MEMREF_PARTIAL_INOUT; - break; - } - } - /* if is not allocated, translate TEEC_MEMREF_PARTIAL_XXX to TEEC_MEMREF_TEMP_XXX */ - if (!operation->params[paramCnt].memref.parent->isAllocated) { - paramType[paramCnt] = paramType[paramCnt] - diff; - } - } - return; -} - -static TeecResult ProcTeekEncode(TcNsClientContext *cliContext, - const TeecOperation *operation) -{ - bool checkValue = false; - bool checkTempMem = false; - bool checkPartMem = false; - uint32_t paramType[TEE_PARAM_NUM]; - uint32_t paramCnt; - - paramType[TEE_PARAM_ONE] = - TEEC_PARAM_TYPE_GET(operation->paramTypes, TEE_PARAM_ONE); - paramType[TEE_PARAM_TWO] = - TEEC_PARAM_TYPE_GET(operation->paramTypes, TEE_PARAM_TWO); - paramType[TEE_PARAM_THREE] = - TEEC_PARAM_TYPE_GET(operation->paramTypes, TEE_PARAM_THREE); - paramType[TEE_PARAM_FOUR] = - TEEC_PARAM_TYPE_GET(operation->paramTypes, TEE_PARAM_FOUR); - for (paramCnt = 0; paramCnt < TEE_PARAM_NUM; paramCnt++) { - checkTempMem = paramType[paramCnt] == TEEC_MEMREF_TEMP_INPUT || - paramType[paramCnt] == TEEC_MEMREF_TEMP_OUTPUT || - paramType[paramCnt] == TEEC_MEMREF_TEMP_INOUT; - checkPartMem = paramType[paramCnt] == TEEC_MEMREF_WHOLE || - paramType[paramCnt] == TEEC_MEMREF_PARTIAL_INPUT || - paramType[paramCnt] == TEEC_MEMREF_PARTIAL_OUTPUT || - paramType[paramCnt] == TEEC_MEMREF_PARTIAL_INOUT; - checkValue = paramType[paramCnt] == TEEC_VALUE_INPUT || - paramType[paramCnt] == TEEC_VALUE_OUTPUT || - paramType[paramCnt] == TEEC_VALUE_INOUT; - if (checkTempMem == true) { - cliContext->params[paramCnt].memref.buffer = - (uint64_t)(uintptr_t)(operation->params[paramCnt].tmpref.buffer); - cliContext->params[paramCnt].memref.sizeAddr = - (uint64_t)(uintptr_t)(&operation->params[paramCnt].tmpref.size); - } else if (checkPartMem == true) { - EncdeForPartMem(cliContext, operation, - paramCnt, paramType); - } else if (checkValue == true) { - cliContext->params[paramCnt].value.aAddr = - (uint64_t)(uintptr_t)(&operation->params[paramCnt].value.a); - cliContext->params[paramCnt].value.bAddr = - (uint64_t)(uintptr_t)(&operation->params[paramCnt].value.b); - } else if (paramType[paramCnt] == TEEC_NONE) { - /* do nothing */ - } else { - tloge("paramType[%u]=%u not correct\n", paramCnt, - paramType[paramCnt]); - return (TeecResult)TEEC_ERROR_BAD_PARAMETERS; - } - } - cliContext->paramTypes = TEEC_PARAM_TYPES(paramType[TEE_PARAM_ONE], - paramType[TEE_PARAM_TWO], paramType[TEE_PARAM_THREE], - paramType[TEE_PARAM_FOUR]); - return TEEC_SUCCESS; -} - -struct TeekEncodeMeg { - TeecUuid serviceId; - uint32_t sessionId; - uint32_t cmdId; -}; - -static TeecResult TeekEncode(TcNsClientContext *cliContext, - struct TeekEncodeMeg *msg, - const TcNsClientLogin *cliLogin, const TeecOperation *operation) -{ - TeecResult ret; - errno_t sret; - - if (cliContext == NULL || cliLogin == NULL) { - tloge("cliContext or cliLogin is null.\n"); - return (TeecResult)TEEC_ERROR_BAD_PARAMETERS; - } - sret = memset_s(cliContext, sizeof(*cliContext), - 0x00, sizeof(*cliContext)); - if (sret != EOK) { - tloge("memset error sret is %d.\n", sret); - return (TeecResult)TEEC_ERROR_BAD_PARAMETERS; - } - sret = memcpy_s(cliContext->uuid, sizeof(cliContext->uuid), - (uint8_t *)&msg->serviceId, sizeof(msg->serviceId)); - if (sret != EOK) { - tloge("memcpy error sret is %d.\n", sret); - return (TeecResult)TEEC_ERROR_BAD_PARAMETERS; - } - cliContext->sessionId = msg->sessionId; - cliContext->cmdId = msg->cmdId; - cliContext->returns.code = 0; - cliContext->returns.origin = 0; - cliContext->login.method = cliLogin->method; - cliContext->login.mdata = cliLogin->mdata; - /* support when operation is null */ - if (operation == NULL) { - return TEEC_SUCCESS; - } - cliContext->started = operation->cancelFlag; - ret = ProcTeekEncode(cliContext, operation); - tlogv("cli param type %u\n", cliContext->paramTypes); - return ret; -} - -static TeecResult TeekCheckTmpRef(TeecTempmemoryReference tmpref) -{ - TeecResult ret; - bool checkValue = (tmpref.buffer == NULL) || (tmpref.size == 0); - - if (checkValue == true) { - tloge("tmpref buffer is null, or size is zero\n"); - ret = (TeecResult) TEEC_ERROR_BAD_PARAMETERS; - } else { - ret = (TeecResult) TEEC_SUCCESS; - } - return ret; -} - -static TeecResult TeekCheckMemRef(TeecRegisteredmemoryReference memref, - uint32_t paramType) -{ - bool checkValue = (memref.parent == NULL) || (memref.parent->buffer == NULL); - bool checkOffset = false; - - if (checkValue == true) { - tloge("parent of memref is null, or the buffer is zero\n"); - return (TeecResult) TEEC_ERROR_BAD_PARAMETERS; - } - if (paramType == TEEC_MEMREF_PARTIAL_INPUT) { - if (!(memref.parent->flags & TEEC_MEM_INPUT)) { - return (TeecResult) TEEC_ERROR_BAD_PARAMETERS; - } - } else if (paramType == TEEC_MEMREF_PARTIAL_OUTPUT) { - if (!(memref.parent->flags & TEEC_MEM_OUTPUT)) { - return (TeecResult) TEEC_ERROR_BAD_PARAMETERS; - } - } else if (paramType == TEEC_MEMREF_PARTIAL_INOUT) { - if (!(memref.parent->flags & TEEC_MEM_INPUT)) { - return (TeecResult) TEEC_ERROR_BAD_PARAMETERS; - } - if (!(memref.parent->flags & TEEC_MEM_OUTPUT)) { - return (TeecResult) TEEC_ERROR_BAD_PARAMETERS; - } - } else if (paramType == TEEC_MEMREF_WHOLE) { - /* if type is TEEC_MEMREF_WHOLE, ignore it */ - } else { - return (TeecResult)TEEC_ERROR_BAD_PARAMETERS; - } - - checkValue = (paramType == TEEC_MEMREF_PARTIAL_INPUT) || - (paramType == TEEC_MEMREF_PARTIAL_OUTPUT) || - (paramType == TEEC_MEMREF_PARTIAL_INOUT); - if (checkValue == true) { - checkOffset = (memref.offset + memref.size) > memref.parent->size || - (memref.offset + memref.size) < memref.offset || - (memref.offset + memref.size) < memref.size; - if (checkOffset == true) { - tloge("offset + size exceed the parent size\n"); - return (TeecResult) TEEC_ERROR_BAD_PARAMETERS; - } - } - return (TeecResult) TEEC_SUCCESS; -} - -/* - * This function checks an operation is valid or not. - */ -TeecResult TeekCheckOperation(const TeecOperation *operation) -{ - uint32_t paramType[TEE_PARAM_NUM] = {0}; - uint32_t paramCnt; - TeecResult ret = TEEC_SUCCESS; - bool checkValue = false; - bool checkTempMem = false; - bool checkPartMem = false; - - /* GP Support operation is NULL - * operation: a pointer to a Client Application initialized TeecOperation structure, - * or NULL if there is no payload to send or if the Command does not need to support - * cancellation. - */ - if (operation == NULL) { - return (TeecResult)TEEC_SUCCESS; - } - if (!operation->started) { - tloge("sorry, cancellation not support\n"); - return (TeecResult) TEEC_ERROR_NOT_IMPLEMENTED; - } - paramType[TEE_PARAM_ONE] = TEEC_PARAM_TYPE_GET(operation->paramTypes, TEE_PARAM_ONE); - paramType[TEE_PARAM_TWO] = TEEC_PARAM_TYPE_GET(operation->paramTypes, TEE_PARAM_TWO); - paramType[TEE_PARAM_THREE] = TEEC_PARAM_TYPE_GET(operation->paramTypes, TEE_PARAM_THREE); - paramType[TEE_PARAM_FOUR] = TEEC_PARAM_TYPE_GET(operation->paramTypes, TEE_PARAM_FOUR); - for (paramCnt = 0; paramCnt < TEE_PARAM_NUM; paramCnt++) { - checkTempMem = paramType[paramCnt] == TEEC_MEMREF_TEMP_INPUT || - paramType[paramCnt] == TEEC_MEMREF_TEMP_OUTPUT || paramType[paramCnt] == TEEC_MEMREF_TEMP_INOUT; - checkPartMem = paramType[paramCnt] == TEEC_MEMREF_WHOLE || - paramType[paramCnt] == TEEC_MEMREF_PARTIAL_INPUT || - paramType[paramCnt] == TEEC_MEMREF_PARTIAL_OUTPUT || - paramType[paramCnt] == TEEC_MEMREF_PARTIAL_INOUT; - checkValue = paramType[paramCnt] == TEEC_VALUE_INPUT || - paramType[paramCnt] == TEEC_VALUE_OUTPUT || paramType[paramCnt] == TEEC_VALUE_INOUT; - if (checkTempMem == true) { - ret = TeekCheckTmpRef(operation->params[paramCnt].tmpref); - if (ret != TEEC_SUCCESS) { - break; - } - } else if (checkPartMem == true) { - ret = TeekCheckMemRef(operation->params[paramCnt].memref, paramType[paramCnt]); - if (ret != TEEC_SUCCESS) { - break; - } - } else if (checkValue == true) { - /* if type is value, ignore it */ - } else if (paramType[paramCnt] == TEEC_NONE) { - /* if type is none, ignore it */ - } else { - tloge("paramType[%u]=%x is not support\n", paramCnt, paramType[paramCnt]); - ret = (TeecResult) TEEC_ERROR_BAD_PARAMETERS; - break; - } - } - return ret; -} - -/* - * This function check if the special agent is launched.Used For HDCP key. - * e.g. If sfs agent is not alive, you can not do HDCP key write to SRAM. - */ -int TeekIsAgentAlive(unsigned int agentId) -{ - return IsAgentAlive(agentId); -} - -/* - * This function initializes a new TEE Context, forming a connection between this Client Application - * and the TEE identified by the string identifier name. - */ -TeecResult TeekInitializeContext(const char *name, TeecContext *context) -{ - int32_t ret; - - /* name current not used */ - (void)(name); - tlogd("TeekInitializeContext Started:\n"); - /* First, check parameters is valid or not */ - if (context == NULL) { - tloge("context is null, not correct\n"); - return (TeecResult) TEEC_ERROR_BAD_PARAMETERS; - } - context->dev = NULL; - /* Paramters right, start execution */ - ret = TcNsClientOpen((TcNsDevFile **)&context->dev, - TEE_REQ_FROM_KERNEL_MODE); - if (ret != TEEC_SUCCESS) { - tloge("open device failed\n"); - return (TeecResult) TEEC_ERROR_GENERIC; - } - tlogd("open device success\n"); - TEEK_INIT_LIST_HEAD(&context->sessionList); - TEEK_INIT_LIST_HEAD(&context->shrdMemList); - return TEEC_SUCCESS; -} - -/* - * This function finalizes an initialized TEE Context. - */ -void TeekFinalizeContext(TeecContext *context) -{ - struct ListNode *ptr = NULL; - TeecSession *session = NULL; - /* TeecSharedMemory* shrdmem */ - tlogd("TeekFinalizeContext started\n"); - /* First, check parameters is valid or not */ - if (context == NULL || context->dev == NULL) { - tloge("context or dev is null, not correct\n"); - return; - } - /* Paramters right, start execution */ - if (!LIST_EMPTY(&context->sessionList)) { - tlogi("context still has sessions opened, close it\n"); - LIST_FOR_EACH(ptr, &context->sessionList) { - session = list_entry(ptr, TeecSession, head); - TeekCloseSession(session); - } - } - tlogd("close device\n"); - TcNsClientClose(context->dev); - context->dev = NULL; -} - -static TeecResult CheckParamsForOpenSession(TeecContext *context, - const TeecOperation *operation, TcNsClientLogin *cliLogin) -{ - bool checkValue = false; - TcNsDevFile *devFile = NULL; - TeecResult teecRet; - errno_t sret; - uint32_t paramType[TEE_PARAM_NUM] = {0}; - - paramType[TEE_PARAM_FOUR] = TEEC_PARAM_TYPE_GET(operation->paramTypes, TEE_PARAM_FOUR); - paramType[TEE_PARAM_THREE] = TEEC_PARAM_TYPE_GET(operation->paramTypes, TEE_PARAM_THREE); - checkValue = paramType[TEE_PARAM_FOUR] != TEEC_MEMREF_TEMP_INPUT || - paramType[TEE_PARAM_THREE] != TEEC_MEMREF_TEMP_INPUT; - if (checkValue == true) { - tloge("invalid param type 0x%x\n", operation->paramTypes); - return (TeecResult)TEEC_ERROR_BAD_PARAMETERS; - } - checkValue = operation->params[TEE_PARAM_FOUR].tmpref.buffer == NULL || - operation->params[TEE_PARAM_THREE].tmpref.buffer == NULL || - operation->params[TEE_PARAM_FOUR].tmpref.size == 0 || operation->params[TEE_PARAM_THREE].tmpref.size == 0; - if (checkValue == true) { - tloge("invalid operation params(NULL)\n"); - return (TeecResult)TEEC_ERROR_BAD_PARAMETERS; - } - cliLogin->method = TEEC_LOGIN_IDENTIFY; - devFile = (TcNsDevFile *)(context->dev); - if (devFile == NULL) { - tloge("invalid context->dev (NULL)\n"); - return (TeecResult)TEEC_ERROR_BAD_PARAMETERS; - } - devFile->pkgNameLen = operation->params[TEE_PARAM_FOUR].tmpref.size; - if (operation->params[TEE_PARAM_FOUR].tmpref.size > (MAX_PACKAGE_NAME_LEN - 1)) { - return (TeecResult)TEEC_ERROR_BAD_PARAMETERS; - } else { - sret = memset_s(devFile->PkgName, sizeof(devFile->PkgName), 0, MAX_PACKAGE_NAME_LEN); - if (sret != EOK) { - tloge("memset error sret is %d.\n", sret); - return (TeecResult)TEEC_ERROR_BAD_PARAMETERS; - } - sret = memcpy_s(devFile->PkgName, sizeof(devFile->PkgName), operation->params[TEE_PARAM_FOUR].tmpref.buffer, - operation->params[TEE_PARAM_FOUR].tmpref.size); - if (sret != EOK) { - tloge("memcpy error sret is %d.\n", sret); - return (TeecResult)TEEC_ERROR_BAD_PARAMETERS; - } - } - devFile->pubKeyLen = 0; - devFile->loginSetup = 1; - teecRet = TeekCheckOperation(operation); - if (teecRet != TEEC_SUCCESS) { - tloge("operation is invalid\n"); - return (TeecResult)TEEC_ERROR_BAD_PARAMETERS; - } - return teecRet; -} - -static TeecResult OpenSessionAndSwitchRet(TeecSession *session, - TeecContext *context, const TeecUuid *destination, - TcNsClientContext *cliContext, uint32_t *origin) -{ - int32_t ret; - TeecResult teecRet; - - ret = TcNsOpenSession(context->dev, cliContext); - if (ret == 0) { - tlogd("open session success\n"); - session->sessionId = cliContext->sessionId; - session->serviceId = *destination; - session->opsCnt = 0; - TEEK_INIT_LIST_HEAD(&session->head); - ListInsertTail(&context->sessionList, &session->head); - session->context = context; - return TEEC_SUCCESS; - } else if (ret < 0) { - tloge("open session failed, ioctl errno = %u\n", ret); - if (ret == -EFAULT) { - teecRet = (TeecResult) TEEC_ERROR_ACCESS_DENIED; - } else if (ret == -ENOMEM) { - teecRet = (TeecResult) TEEC_ERROR_OUT_OF_MEMORY; - } else if (ret == -EINVAL) { - teecRet = (TeecResult) TEEC_ERROR_BAD_PARAMETERS; - } else if (ret == -ERESTARTSYS) { - teecRet = (TeecResult) TEEC_CLIENT_INTR; - } else { - teecRet = (TeecResult) TEEC_ERROR_GENERIC; - } - *origin = TEEC_ORIGIN_COMMS; - return teecRet; - } else { - tloge("open session failed, code=0x%x, origin=%u\n", cliContext->returns.code, - cliContext->returns.origin); - teecRet = (TeecResult)cliContext->returns.code; - *origin = cliContext->returns.origin; - } - return teecRet; -} - -/* - * Function: TEEC_OpenSession - * Description: This function opens a new Session - * Parameters: context: a pointer to an initialized TEE Context. - * session: a pointer to a Session structure to open. - * destination: a pointer to a UUID structure. - * connectionMethod: the method of connection to use. - * connectionData: any necessary data required to support the connection method chosen. - * operation: a pointer to an Operation containing a set of Parameters. - * returnOrigin: a pointer to a variable which will contain the return origin. - * Return: TEEC_SUCCESS: success other: failure - */ -static TeecResult ProcTeekOpenSession(TeecContext *context, - TeecSession *session, const TeecUuid *destination, - uint32_t connectionMethod, const void *connectionData, - const TeecOperation *operation, uint32_t *returnOrigin) -{ - TeecResult teecRet; - uint32_t origin = TEEC_ORIGIN_API; - TcNsClientContext cliContext; - TcNsClientLogin cliLogin = { 0, 0 }; - bool checkValue = false; - - tlogd("TeekOpenSession Started:\n"); - /* connectionData current not used */ - (void)(connectionData); - /* returnOrigin maybe null, so only when it is valid, we set - * origin(error come from which module) - */ - if (returnOrigin != NULL) { - *returnOrigin = origin; - } - /* First, check parameters is valid or not */ - checkValue = (context == NULL || operation == NULL || - connectionMethod != TEEC_LOGIN_IDENTIFY); - if (checkValue == true || destination == NULL || session == NULL) { - tloge("invalid input params\n"); - return TEEC_ERROR_BAD_PARAMETERS; - } - teecRet = CheckParamsForOpenSession(context, operation, &cliLogin); - if (teecRet != TEEC_SUCCESS) { - goto RET_FAIL; - } - /* Paramters right, start execution - * note:before open session success, - * we should send session=0 as initial state. - */ - struct TeekEncodeMeg msg = { - *destination, 0, GLOBAL_CMD_ID_OPEN_SESSION - }; - teecRet = TeekEncode(&cliContext, &msg, &cliLogin, operation); - if (teecRet != TEEC_SUCCESS) { - tloge("encode failed\n"); - goto RET_FAIL; - } -#ifdef SECURITY_AUTH_ENHANCE - cliContext.teecToken = session->teecToken; - cliContext.tokenLen = sizeof(session->teecToken); -#endif - teecRet = OpenSessionAndSwitchRet(session, context, - destination, &cliContext, &origin); - /* ONLY when ioctl returnCode!=0 and returnOrigin not NULL, set returnOrigin */ - if (teecRet != TEEC_SUCCESS && returnOrigin != NULL) { - *returnOrigin = origin; - } -RET_FAIL: - return teecRet; -} - -#define RETRY_TIMES 5 -TeecResult TeekOpenSession(TeecContext *context, - TeecSession *session, const TeecUuid *destination, - uint32_t connectionMethod, const void *connectionData, - const TeecOperation *operation, uint32_t *returnOrigin) -{ - int i; - TeecResult ret; - - for (i = 0; i < RETRY_TIMES; i++) { - ret = ProcTeekOpenSession(context, session, - destination, connectionMethod, connectionData, - operation, returnOrigin); - if (ret != (TeecResult)TEEC_CLIENT_INTR) { - return ret; - } - } - return ret; -} - -static int CheckCloseSessionParam(TeecSession *session) -{ - bool checkValue = false; - bool found = false; - TeecSession *tempSess = NULL; - struct ListNode *ptr = NULL; - - /* First, check parameters is valid or not */ - checkValue = session == NULL || session->context == NULL; - if (checkValue || session->context->dev == NULL) { - tloge("input invalid session or session->context is null\n"); - return -1; - } - LIST_FOR_EACH(ptr, &session->context->sessionList) { - tempSess = list_entry(ptr, TeecSession, head); - if (tempSess == session) { - found = true; - break; - } - } - if (!found) { - tloge("session is not in the context list\n"); - return -1; - } - return 0; -} - -/* - * This function closes an opened Session. - */ -void TeekCloseSession(TeecSession *session) -{ - int32_t ret; - TcNsClientContext cliContext; - TcNsClientLogin cliLogin = { 0, 0 }; - errno_t sret; - - tlogd("TeekCloseSession started\n"); - ret = CheckCloseSessionParam(session); - if (ret) { - return; - } - /* Paramters all right, start execution */ - if (session->opsCnt) { - tloge("session still has commands running\n"); - } - struct TeekEncodeMeg msg = { - session->serviceId, session->sessionId, GLOBAL_CMD_ID_CLOSE_SESSION - }; - if (TeekEncode(&cliContext, &msg, &cliLogin, NULL) != TEEC_SUCCESS) { - tloge("encode failed, just return\n"); - return; - } -#ifdef SECURITY_AUTH_ENHANCE - cliContext.teecToken = session->teecToken; - cliContext.tokenLen = sizeof(session->teecToken); -#endif - ret = TcNsCloseSession(session->context->dev, &cliContext); - if (ret == 0) { - tlogd("close session success\n"); - session->sessionId = 0; - sret = memset_s((uint8_t *)(&session->serviceId), sizeof(session->serviceId), 0x00, UUID_LEN); - /* TeekCloseSession is void so go on execute */ - if (sret != EOK) { - tloge("memset error sret is %d.\n", sret); - } -#ifdef SECURITY_AUTH_ENHANCE - sret = memset_s(session->teecToken, TOKEN_SAVE_LEN, 0x00, TOKEN_SAVE_LEN); - if (sret != EOK) { - tloge("memset session's member error ret value is %d.\n", sret); - } -#endif - session->opsCnt = 0; - ListRemove(&session->head); - session->context = NULL; - } else { - tloge("close session failed\n"); - } -} - -static TeecResult InvokeCmdAndSwitchRet(TeecSession *session, - TcNsClientContext *cliContext, uint32_t *origin) -{ - int32_t ret; - TeecResult teecRet; - - ret = TcNsSendCmd(session->context->dev, cliContext); - if (ret == 0) { - tlogd("invoke cmd success\n"); - teecRet = TEEC_SUCCESS; - } else if (ret < 0) { - tloge("invoke cmd failed, ioctl errno = %d\n", ret); - if (ret == -EFAULT) { - teecRet = (TeecResult)TEEC_ERROR_ACCESS_DENIED; - } else if (ret == -ENOMEM) { - teecRet = (TeecResult)TEEC_ERROR_OUT_OF_MEMORY; - } else if (ret == -EINVAL) { - teecRet = (TeecResult)TEEC_ERROR_BAD_PARAMETERS; - } else { - teecRet = (TeecResult)TEEC_ERROR_GENERIC; - } - *origin = TEEC_ORIGIN_COMMS; - } else { - tloge("invoke cmd failed, code=0x%x, origin=%d\n", - cliContext->returns.code, cliContext->returns.origin); - teecRet = (TeecResult)cliContext->returns.code; - *origin = cliContext->returns.origin; - } - return teecRet; -} - -/* This function invokes a Command within the specified Session. */ -TeecResult TeekInvokeCommand(TeecSession *session, uint32_t commandID, - TeecOperation *operation, uint32_t *returnOrigin) -{ - TeecResult teecRet = (TeecResult) TEEC_ERROR_BAD_PARAMETERS; - uint32_t origin = TEEC_ORIGIN_API; - TcNsClientContext cliContext; - TcNsClientLogin cliLogin = { 0, 0 }; - - tlogd("TeekInvokeCommand Started:\n"); - /* First, check parameters is valid or not */ - if (session == NULL || session->context == NULL) { - tloge("input invalid session or session->context is null\n"); - if (returnOrigin != NULL) { - *returnOrigin = origin; - } - return teecRet; - } - teecRet = TeekCheckOperation(operation); - if (teecRet != TEEC_SUCCESS) { - tloge("operation is invalid\n"); - if (returnOrigin != NULL) { - *returnOrigin = origin; - } - return teecRet; - } - /* Paramters all right, start execution */ - session->opsCnt++; - struct TeekEncodeMeg msg = { - session->serviceId, session->sessionId, commandID - }; - teecRet = TeekEncode(&cliContext, &msg, &cliLogin, operation); - if (teecRet != TEEC_SUCCESS) { - tloge("encode failed\n"); - session->opsCnt--; - if (returnOrigin != NULL) { - *returnOrigin = origin; - } - return teecRet; - } -#ifdef SECURITY_AUTH_ENHANCE - cliContext.teecToken = session->teecToken; - cliContext.tokenLen = sizeof(session->teecToken); -#endif - teecRet = InvokeCmdAndSwitchRet(session, &cliContext, &origin); - session->opsCnt--; - /* ONLY when ioctl returnCode!=0 and returnOrigin not NULL, set *returnOrigin */ - if ((teecRet != TEEC_SUCCESS) && (returnOrigin != NULL)) { - *returnOrigin = origin; - } - return teecRet; -} - -/* - * This function registers a block of existing Client Application memory - * as a block of Shared Memory within the scope of the specified TEE Context. - */ -TeecResult TeekRegisterSharedMemory(TeecContext *context, - TeecSharedMemory *sharedMem) -{ - tloge("TeekRegisterSharedMemory not supported\n"); - return (TeecResult)TEEC_ERROR_NOT_SUPPORTED; -} - -/* - * This function allocates a new block of memory as a block of - * Shared Memory within the scope of the specified TEE Context. - */ -TeecResult TeekAllocateSharedMemory(TeecContext *context, - TeecSharedMemory *sharedMem) -{ - tloge("TeekAllocateSharedMemory not supported\n"); - return (TeecResult)TEEC_ERROR_NOT_SUPPORTED; -} - -/* - * This function deregisters or deallocates - * a previously initialized block of Shared Memory.. - */ -void TeekReleaseSharedMemory(TeecSharedMemory *sharedMem) -{ - tloge("TeekReleaseSharedMemory not supported\n"); -} - -/* - * This function requests the cancellation of a pending open Session operation or - * a Command invocation operation. - */ -void TeekRequestCancellation(TeecOperation *operation) -{ - tloge("TeekRequestCancellation not supported\n"); -} diff --git a/tzdriver/src/tz_spi_notify.c b/tzdriver/src/tz_spi_notify.c deleted file mode 100644 index b0ce55a..0000000 --- a/tzdriver/src/tz_spi_notify.c +++ /dev/null @@ -1,718 +0,0 @@ -/* - * Copyright (c) 2013-2019 Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020-2021 Huawei Device Co., Ltd. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "tz_spi_notify.h" -#include -#include "gp_ops.h" -#include "mailbox_mempool.h" -#include "smc.h" -#include "tc_client_driver.h" -#include "tc_client_sub_driver.h" -#include "tc_ns_client.h" -#include "tc_ns_log.h" -#include "teek_client_constants.h" - -#define MAX_CALLBACK_COUNT 100 -#define UUID_SIZE 16 -struct TeecTimerProperty; - -#ifdef DEF_ENG -static int g_timerType; -#endif - -enum TimerClassType { - /* timer event using timer10 */ - TIMER_GENERIC, - /* timer event using RTC */ - TIMER_RTC -}; - -struct TeecTimerProperty { - unsigned int type; - unsigned int timerId; - unsigned int timerClass; - unsigned int reserved2; -}; - -struct NotifyContextTimer { - unsigned int devFileId; - unsigned char uuid[UUID_SIZE]; - unsigned int sessionId; - struct TeecTimerProperty property; - uint32_t expireTime; -}; - -#ifdef CONFIG_TEE_SMP -struct NotifyContextWakeup { - pid_t caThreadId; -}; - -struct NotifyContextShadow { - uint64_t targetTcb; -}; - -struct NotifyContextStats { - uint32_t sends; - uint32_t recvs; - uint32_t sendw; - uint32_t recvw; - uint32_t missed; -}; -#endif - -union NotifyContext { - struct NotifyContextTimer timer; -#ifdef CONFIG_TEE_SMP - struct NotifyContextWakeup wakeup; - struct NotifyContextShadow shadow; - struct NotifyContextStats meta; -#endif -}; - -struct NotifyDataEntry { - uint32_t entryType : 31; - uint32_t filled : 1; - union NotifyContext context; -}; - -#define NOTIFY_DATA_ENTRY_COUNT \ - ((PAGE_SIZE / sizeof(struct NotifyDataEntry)) - 1) -struct NotifyDataStruct { - struct NotifyDataEntry entry[NOTIFY_DATA_ENTRY_COUNT]; - struct NotifyDataEntry meta; -}; - -static struct NotifyDataStruct *g_notifyData = NULL; -static struct NotifyDataEntry *g_notifyDataEntryTimer = NULL; -static struct NotifyDataEntry *g_notifyDataEntryRtc = NULL; -#ifdef CONFIG_TEE_SMP -static struct NotifyDataEntry *g_notifyDataEntryShadow = NULL; -#endif - -enum NotifyDataType { - NOTIFY_DATA_ENTRY_UNUSED, - NOTIFY_DATA_ENTRY_TIMER, - NOTIFY_DATA_ENTRY_RTC, -#ifdef CONFIG_TEE_SMP - NOTIFY_DATA_ENTRY_WAKEUP, - NOTIFY_DATA_ENTRY_SHADOW, - NOTIFY_DATA_ENTRY_FIQSHD, - NOTIFY_DATA_ENTRY_SHADOW_EXIT, -#endif - NOTIFY_DATA_ENTRY_MAX, -}; - -struct TcNsCallback { - unsigned char uuid[UUID_SIZE]; - mutex_t callbackLock; - void (*callbackFunc)(void *); - struct list_head head; -}; - -struct TcNsCallbackList { - unsigned int callbackCount; - mutex_t callbackListLock; - struct list_head callbackList; -}; - -static void TcNotifyFn(struct work_struct *dummy); -static struct TcNsCallbackList g_taCallbackFuncList; -static DECLARE_WORK(tc_notify_work, TcNotifyFn); -#ifdef CONFIG_TEE_SMP -static struct workqueue_struct *g_tzSpiWq = NULL; -#endif - -static void WalkCallback(struct NotifyContextTimer *tcNotifyDataTimer, struct TcNsCallback *callbackFuncT) -{ - if (tcNotifyDataTimer->property.timerClass == TIMER_RTC) { - tlogd("start to call callback func\n"); - callbackFuncT->callbackFunc((void *)(&(tcNotifyDataTimer->property))); - tlogd("end to call callback func\n"); - } else if (tcNotifyDataTimer->property.timerClass == TIMER_GENERIC) { - tlogd("timer60 no callback func\n"); - } -} - -static void WalkCallbackList(struct NotifyContextTimer *tcNotifyDataTimer) -{ - struct TcNsCallback *callbackFuncT = NULL; - - mutex_lock(&g_taCallbackFuncList.callbackListLock); - list_for_each_entry(callbackFuncT, &g_taCallbackFuncList.callbackList, head) { - if (memcmp(callbackFuncT->uuid, tcNotifyDataTimer->uuid, UUID_SIZE) == 0) { - WalkCallback(tcNotifyDataTimer, callbackFuncT); - } - } - mutex_unlock(&g_taCallbackFuncList.callbackListLock); -} - -static void TcNotifyTimerFn(struct NotifyDataEntry *notifyDataEntry) -{ - TcNsDevFile *tempDevFile = NULL; - TcNsService *tempSvc = NULL; - TcNsSession *tempSes = NULL; - int encFound = 0; - struct NotifyContextTimer *tcNotifyDataTimer = NULL; - - tcNotifyDataTimer = &(notifyDataEntry->context.timer); - notifyDataEntry->filled = 0; - tlogd("notify_data timer type is 0x%x, timer ID is 0x%x\n", - tcNotifyDataTimer->property.type, - tcNotifyDataTimer->property.timerId); - WalkCallbackList(tcNotifyDataTimer); - mutex_lock(&GetTcNsDevList()->devLock); - list_for_each_entry(tempDevFile, &GetTcNsDevList()->devFileList, head) { - tlogd("dev file id1 = %u, id2 = %u\n", tempDevFile->devFileId, tcNotifyDataTimer->devFileId); - if (tempDevFile->devFileId == tcNotifyDataTimer->devFileId) { - mutex_lock(&tempDevFile->serviceLock); - tempSvc = TcFindServiceInDev(tempDevFile, tcNotifyDataTimer->uuid, UUID_LEN); - GetServiceStruct(tempSvc); - mutex_unlock(&tempDevFile->serviceLock); - if (tempSvc == NULL) { - break; - } - mutex_lock(&tempSvc->SessionLock); - tempSes = TcFindSessionWithOwner(&tempSvc->sessionList, tcNotifyDataTimer->sessionId, tempDevFile); - GetSessionStruct(tempSes); - mutex_unlock(&tempSvc->SessionLock); - PutServiceStruct(tempSvc); - tempSvc = NULL; - if (tempSes != NULL) { - tlogd("send cmd ses id %u\n", tempSes->sessionId); - encFound = 1; - break; - } - break; - } - } - mutex_unlock(&GetTcNsDevList()->devLock); - if (tcNotifyDataTimer->property.timerClass == TIMER_GENERIC) { - tlogd("timer60 wake up event\n"); - if (encFound && tempSes != NULL) { - tempSes->waitData.sendWaitFlag = 1; - wake_up(&tempSes->waitData.sendCmdWq); - PutSessionStruct(tempSes); - tempSes = NULL; - } - } else { - tlogd("RTC do not need to wakeup\n"); - } -} - -#ifdef CONFIG_TEE_SMP -static noinline int GetNotifyDataEntry(struct NotifyDataEntry *copy) -{ - uint32_t i; - int filled; - int ret = -1; - - if (copy == NULL) { - tloge("Bad parameters! "); - return ret; - } - /* TIMER and RTC use fix entry, skip them. */ - for (i = NOTIFY_DATA_ENTRY_WAKEUP - 1; i < NOTIFY_DATA_ENTRY_COUNT; i++) { - struct NotifyDataEntry *e = NULL; - e = &g_notifyData->entry[i]; - filled = e->filled; - DMB; - if (!filled) { - continue; - } - switch (e->entryType) { - case NOTIFY_DATA_ENTRY_SHADOW: // fall through - case NOTIFY_DATA_ENTRY_SHADOW_EXIT: // fall through - case NOTIFY_DATA_ENTRY_FIQSHD: // fall through - g_notifyData->meta.context.meta.recvs++; - break; - case NOTIFY_DATA_ENTRY_WAKEUP: - g_notifyData->meta.context.meta.recvw++; - break; - default: - tloge("invalid notify type=%u\n", e->entryType); - goto exit; - } - if (memcpy_s(copy, sizeof(*copy), e, sizeof(*e)) != EOK) { - tloge("memcpy entry failed\n"); - break; - } - DMB; - e->filled = 0; - ret = 0; - break; - } -exit: - return ret; -} - -static void TcNotifyWakeupFn(struct NotifyDataEntry *entry) -{ - struct NotifyContextWakeup *tcNotifyWakeup = NULL; - - tcNotifyWakeup = &(entry->context.wakeup); - SmcWakeupCa(tcNotifyWakeup->caThreadId); - tlogd("notify_data_entry_wakeup ca: %d\n", tcNotifyWakeup->caThreadId); -} - -static void TcNotifyShadowFn(struct NotifyDataEntry *entry) -{ - struct NotifyContextShadow *tcNotifyShadow = NULL; - - tcNotifyShadow = &(entry->context.shadow); - SmcQueueShadowWorker(tcNotifyShadow->targetTcb); -} - -static void TcNotifyFiqshdFn(struct NotifyDataEntry *entry) -{ - struct NotifyContextShadow *tcNotifyShadow = NULL; - - if (entry == NULL) { - /* for NOTIFY_DATA_ENTRY_FIQSHD missed */ - FiqShadowWorkFunc(0); - return; - } - tcNotifyShadow = &(entry->context.shadow); - FiqShadowWorkFunc(tcNotifyShadow->targetTcb); -} - -static void TcNotifyShadowExitFn(struct NotifyDataEntry *entry) -{ - struct NotifyContextWakeup *tcNotifyWakeup = NULL; - - tcNotifyWakeup = &(entry->context.wakeup); - if (SmcShadowExit(tcNotifyWakeup->caThreadId) != 0) { - tloge("shadow ca exit failed: %d\n", - (int)tcNotifyWakeup->caThreadId); - } -} - -static void SpiBroadcastNotifications(void) -{ - uint32_t missed; - - DMB; - missed = LOS_AtomicXchg32bits((Atomic *)&g_notifyData->meta.context.meta.missed, 0); - if (!missed) { - return; - } - if (missed & (1U << NOTIFY_DATA_ENTRY_WAKEUP)) { - SmcWakeupBroadcast(); - missed &= ~(1U << NOTIFY_DATA_ENTRY_WAKEUP); - } - if (missed & (1U << NOTIFY_DATA_ENTRY_FIQSHD)) { - TcNotifyFiqshdFn(NULL); - missed &= ~(1U << NOTIFY_DATA_ENTRY_FIQSHD); - } - if (missed) { - tloge("missed spi notification mask %x\n", missed); - } -} - -static void TcNotifyOtherFun(void) -{ - struct NotifyDataEntry copy = {0}; - - while (GetNotifyDataEntry(©) == 0) { - switch (copy.entryType) { - case NOTIFY_DATA_ENTRY_WAKEUP: - TcNotifyWakeupFn(©); - break; - case NOTIFY_DATA_ENTRY_SHADOW: - TcNotifyShadowFn(©); - break; - case NOTIFY_DATA_ENTRY_FIQSHD: - TcNotifyFiqshdFn(©); - break; - case NOTIFY_DATA_ENTRY_SHADOW_EXIT: - TcNotifyShadowExitFn(©); - break; - default: - tloge("invalid entry type = %u\n", copy.entryType); - break; - } - if (memset_s(©, sizeof(copy), 0, sizeof(copy))) { - tloge("memset copy failed\n"); - } - } - SpiBroadcastNotifications(); -} -#else -static void TcNotifyOtherFun(void) {} -#endif -int g_spiInited = 0; -static void TcNotifyFn(struct work_struct *dummy) -{ - if (!g_spiInited) { - return; - } - if (g_notifyDataEntryTimer->filled) { - TcNotifyTimerFn(g_notifyDataEntryTimer); - } - if (g_notifyDataEntryRtc->filled) { - TcNotifyTimerFn(g_notifyDataEntryRtc); - } - TcNotifyOtherFun(); -} - -static irqreturn_t TcSecureNotify(int irq, void *devId) -{ -#ifdef CONFIG_TEE_SMP -#define N_WORK 8 - int i; - static struct work_struct tcNotifyWorks[N_WORK]; - static int init = 0; - if (!init) { - for (i = 0; i < N_WORK; i++) { - INIT_WORK(&tcNotifyWorks[i], TcNotifyFn); - } - init = 1; - } - for (i = 0; i < N_WORK; i++) { - if (queue_work(g_tzSpiWq, &tcNotifyWorks[i])) { - break; - } - } -#undef N_WORK -#else - schedule_work(&tc_notify_work); - ISB; - DSB; - TcSmcWakeup(); -#endif - return IRQ_HANDLED; -} - -int TcNsRegisterServiceCallBackFunc(const char *uuid, void *func) -{ - struct TcNsCallback *callbackFunc = NULL; - struct TcNsCallback *newCallback = NULL; - int ret = 0; - errno_t sret; - bool checkStat = (uuid == NULL || func == NULL); - - if (checkStat) { - return -EINVAL; - } - - mutex_lock(&g_taCallbackFuncList.callbackListLock); - if (g_taCallbackFuncList.callbackCount > MAX_CALLBACK_COUNT) { - mutex_unlock(&g_taCallbackFuncList.callbackListLock); - tloge("callbackCount is out\n"); - return -ENOMEM; - } - list_for_each_entry(callbackFunc, - &g_taCallbackFuncList.callbackList, head) { - if (memcmp(callbackFunc->uuid, uuid, UUID_SIZE) == 0) { - callbackFunc->callbackFunc = (void (*)(void *))func; - tlogd("succeed to find uuid ta_callback_func_list\n"); - goto FIND_CALLBACK; - } - } - /* create a new callback struct if we couldn't find it in list */ - newCallback = calloc(1, sizeof(*newCallback)); - if (ZERO_OR_NULL_PTR((unsigned long)(uintptr_t)newCallback)) { - tloge("calloc failed\n"); - ret = -ENOMEM; - goto FIND_CALLBACK; - } - sret = memcpy_s(newCallback->uuid, UUID_SIZE, uuid, UUID_SIZE); - if (sret != EOK) { - free(newCallback); - newCallback = NULL; - ret = -ENOMEM; - goto FIND_CALLBACK; - } - g_taCallbackFuncList.callbackCount++; - tlogd("ta_callback_func_list.callbackCount is %u\n", - g_taCallbackFuncList.callbackCount); - INIT_LIST_HEAD(&newCallback->head); - newCallback->callbackFunc = (void (*)(void *))func; - mutex_init(&newCallback->callbackLock); - list_add_tail(&newCallback->head, &g_taCallbackFuncList.callbackList); -FIND_CALLBACK: - mutex_unlock(&g_taCallbackFuncList.callbackListLock); - return ret; -} - -#ifdef DEF_ENG -static void TimerCallbackFunc(void *param) -{ - struct TeecTimerProperty *timerProperty = - (struct TeecTimerProperty *)param; - tlogd("timerProperty->type = %x, timerProperty->timerId = %x\n", - timerProperty->type, timerProperty->timerId); - g_timerType = (int)timerProperty->type; -} - -static void TstGetTimerType(int *type) -{ - *type = g_timerType; -} - -static void CallbackDemoMain(const char *uuid) -{ - int ret; - - tlogd("step into CallbackDemoMain\n"); - ret = TcNsRegisterServiceCallBackFunc(uuid, - (void *)&TimerCallbackFunc); - if (ret != 0) { - tloge("failed to TcNsRegisterServiceCallBackFunc\n"); - } -} - -#define PARAM1 1 -#define DUMP_UUID_INDEX0 0 -#define DUMP_UUID_INDEX1 1 -#define DUMP_UUID_INDEX2 2 -#define DUMP_UUID_INDEX3 3 -static int HandleTstCmdId(int cmdId, TcNsClientContext *clientContext) -{ - int timerType; - int ret; - switch (cmdId) { - case TST_CMD_01: - CallbackDemoMain((char *)clientContext->uuid); - break; - case TST_CMD_02: - TstGetTimerType(&timerType); - if (TcUserParamValid(clientContext, (unsigned int)PARAM1)) { - tloge("param 1 is invalid\n"); - ret = -EFAULT; - return ret; - } - if (copy_to_user( - (void *)(uintptr_t)clientContext->params[PARAM1].value.aAddr, - &timerType, sizeof(timerType))) { - tloge("copy to user failed:timerType\n"); - ret = -ENOMEM; - return ret; - } - break; - default: - ret = -EINVAL; - return ret; - } - return 0; -} - -int TcNsTstCmd(TcNsDevFile *devId, void *argp) -{ - TcNsClientContext clientContext; - int ret; - int cmdId; - - TeecUuid secureTimerUuid = { - 0x19b39980, 0x2487, 0x7b84, - {0xf4, 0x1a, 0xbc, 0x89, 0x22, 0x62, 0xbb, 0x3d} - }; - if (argp == NULL) { - tloge("argp is NULL input buffer\n"); - ret = -EINVAL; - return ret; - } - if (copy_from_user(&clientContext, argp, sizeof(clientContext))) { - tloge("copy from user failed\n"); - ret = -ENOMEM; - return ret; - } - if (TcUserParamValid(&clientContext, (unsigned int)0)) { - tloge("param 0 is invalid\n"); - ret = -EFAULT; - return ret; - } - /* aAddr contain the command id */ - if (copy_from_user(&cmdId, (void *)(uintptr_t)clientContext.params[0].value.aAddr, sizeof(cmdId))) { - tloge("copy from user failed:cmdId\n"); - ret = -ENOMEM; - return ret; - } - if (memcmp((char *)clientContext.uuid, (char *)&secureTimerUuid, sizeof(TeecUuid))) { - tloge("request not from secure_timer\n"); - tloge("request uuid: %x %x %x %x\n", clientContext.uuid[DUMP_UUID_INDEX0], - clientContext.uuid[DUMP_UUID_INDEX1], clientContext.uuid[DUMP_UUID_INDEX2], - clientContext.uuid[DUMP_UUID_INDEX3]); // just wanna print the first four characters of uuid - ret = -EACCES; - return ret; - } - ret = HandleTstCmdId(cmdId, &clientContext); - if (ret) { - return ret; - } - - if (copy_to_user(argp, (void *)&clientContext, sizeof(clientContext))) { - tloge("copy to user failed:client context\n"); - ret = -ENOMEM; - return ret; - } - return ret; -} -#endif - -static int TcNsRegisterNotifyDataMemory(void) -{ - TcNsSmcCmd smcCmd = { {0}, 0 }; - int ret; - struct MbCmdPack *mbPack = NULL; - - mbPack = MailboxAllocCmdPack(); - if (mbPack == NULL) { - return TEEC_ERROR_GENERIC; - } - mbPack->operation.paramTypes = - TEE_PARAM_TYPE_VALUE_INPUT | TEE_PARAM_TYPE_VALUE_INPUT << TEE_PARAM_NUM; - mbPack->operation.params[TEE_PARAM_ONE].value.a = LOS_PaddrQuery(g_notifyData); - mbPack->operation.params[TEE_PARAM_ONE].value.b = 0; - mbPack->operation.params[TEE_PARAM_TWO].value.a = SZ_4K; - smcCmd.globalCmd = true; - smcCmd.cmdId = GLOBAL_CMD_ID_REGISTER_NOTIFY_MEMORY; - smcCmd.operationPhys = LOS_PaddrQuery(&mbPack->operation); - smcCmd.operationHphys = 0; - tlogd("cmd. context_phys:%x\n", smcCmd.contextId); - ret = TcNsSmc(&smcCmd); - MailboxFree(mbPack); - mbPack = NULL; - return ret; -} - -static int TcNsUnregisterNotifyDataMemory(void) -{ - TcNsSmcCmd smcCmd = { {0}, 0 }; - int ret; - struct MbCmdPack *mbPack = NULL; - - mbPack = MailboxAllocCmdPack(); - if (mbPack == NULL) { - return TEEC_ERROR_GENERIC; - } - mbPack->operation.paramTypes = - TEE_PARAM_TYPE_VALUE_INPUT | TEE_PARAM_TYPE_VALUE_INPUT << TEE_PARAM_NUM; - mbPack->operation.params[TEE_PARAM_ONE].value.a = LOS_PaddrQuery(g_notifyData); - mbPack->operation.params[TEE_PARAM_ONE].value.b = 0; - mbPack->operation.params[TEE_PARAM_TWO].value.a = SZ_4K; - smcCmd.globalCmd = true; - smcCmd.cmdId = GLOBAL_CMD_ID_UNREGISTER_NOTIFY_MEMORY; - smcCmd.operationPhys = LOS_PaddrQuery(&mbPack->operation); - smcCmd.operationHphys = 0; - tlogd("cmd. context_phys:%x\n", smcCmd.contextId); - ret = TcNsSmc(&smcCmd); - MailboxFree(mbPack); - mbPack = NULL; - return ret; -} - -static int InitNotifyData(void) -{ - if (g_notifyData != NULL) { - return 0; - } - - g_notifyData = (struct NotifyDataStruct *)GetPhyPage(); - if (g_notifyData == NULL) { - tloge("GetFreePage failed for notification data\n"); - return -ENOMEM; - } - int ret = memset_s(g_notifyData, PAGESIZE, 0, sizeof(struct NotifyDataStruct)); - if (ret != EOK) { - return -EFAULT; - } - ret = TcNsRegisterNotifyDataMemory(); - if (ret != TEEC_SUCCESS) { - tloge("Shared memory failed ret is 0x%x\n", ret); - FreePhyPage(g_notifyData); - g_notifyData = NULL; - return -EFAULT; - } - g_notifyDataEntryTimer = &g_notifyData->entry[NOTIFY_DATA_ENTRY_TIMER - 1]; - g_notifyDataEntryRtc = &g_notifyData->entry[NOTIFY_DATA_ENTRY_RTC - 1]; -#ifdef CONFIG_TEE_SMP - g_notifyDataEntryShadow = &g_notifyData->entry[NOTIFY_DATA_ENTRY_SHADOW - 1]; - tlogi("test target is: %llx\n", g_notifyDataEntryShadow->context.shadow.targetTcb); -#endif - return 0; -} - -int TzSpiInit() -{ - unsigned int irq; -#ifdef CONFIG_TEE_SMP - g_tzSpiWq = AllocOrderedWorkqueue("g_tzSpiWq", WQ_HIGHPRI); - if (g_tzSpiWq == NULL) { - tloge("it failed to create workqueue g_tzSpiWq\n"); - return -ENOMEM; - } -#endif - /* Map IRQ 0 from the OF interrupts list */ - irq = NUM_HAL_INTERRUPT_TEE_SPI_NOTIFY; - int ret = DevmRequestIrq(irq, TcSecureNotify, IRQF_NO_SUSPEND, TC_NS_CLIENT_DEV, NULL); - if (ret < 0) { - tloge("device irq %u request failed %u", irq, ret); - goto clean; - } - ret = memset_s(&g_taCallbackFuncList, sizeof(g_taCallbackFuncList), 0, sizeof(g_taCallbackFuncList)); - if (ret != EOK) { - ret = -EFAULT; - goto clean; - } - g_taCallbackFuncList.callbackCount = 0; - INIT_LIST_HEAD(&g_taCallbackFuncList.callbackList); - mutex_init(&g_taCallbackFuncList.callbackListLock); - - ret = InitNotifyData(); - if (ret < 0) { - goto clean; - } - - g_spiInited = 1; - return 0; -clean: - TzSpiExit(); - return ret; -} - -void TzSpiExit(void) -{ - g_spiInited = 0; - - if (g_notifyData != NULL) { - if (TcNsUnregisterNotifyDataMemory() != TEEC_SUCCESS) { - tloge("unregister notify data mem failed\n"); - } - FreePhyPage(g_notifyData); - g_notifyData = NULL; - } -#ifdef CONFIG_TEE_SMP - if (g_tzSpiWq != NULL) { - destroy_workqueue(g_tzSpiWq); - g_tzSpiWq = NULL; - } -#endif -} diff --git a/tzdriver/src/tzdebug.c b/tzdriver/src/tzdebug.c deleted file mode 100644 index 9ea2458..0000000 --- a/tzdriver/src/tzdebug.c +++ /dev/null @@ -1,279 +0,0 @@ -/* - * Copyright (c) 2013-2019 Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020-2021 Huawei Device Co., Ltd. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "tzdebug.h" -#include -#include -#include "cmdmonitor.h" -#include "mailbox_mempool.h" -#include "smc.h" -#include "tc_client_sub_driver.h" -#include "tc_ns_log.h" -#include "teek_client_api.h" -#include "teek_client_constants.h" -#include "teek_ns_client.h" -#include "tzdriver_compat.h" - -typedef void (*TzdebugOptFunc)(const char *param); - -struct OptOps { - char *name; - TzdebugOptFunc func; -}; - -static DEFINE_MUTEX(g_meminfoLock); -static struct TeeMem g_teeMeminfo = {0}; -static int SendDumpMem(int flag, const struct TeeMem *statmem); -static void TzMemDump(const char *param); - -void TeeDumpMem(void) -{ - TzMemDump(NULL); -} - -/* get meminfo (TeeMem + N * ta_mem < 4Kbyte) from tee */ -static int GetTeeMemInfoCmd(void) -{ - int ret; - int sret; - struct TeeMem *mem = (struct TeeMem *)MailboxAlloc(sizeof(*mem), MB_FLAG_ZERO); - - if (mem == NULL) { - return -1; - } - ret = SendDumpMem(0, mem); - mutex_lock(&g_meminfoLock); - sret = memcpy_s((void *)&g_teeMeminfo, sizeof(g_teeMeminfo), mem, sizeof(*mem)); - if (sret != EOK) { - tloge("sret=%d\n", sret); - } - mutex_unlock(&g_meminfoLock); - MailboxFree(mem); - return ret; -} - -static atomic_t g_cmdSend = ATOMIC_INIT(1); - -void SetCmdSendState(void) -{ - atomic_set(&g_cmdSend, 1); -} - -int GetTeeMeminfo(struct TeeMem *meminfo) -{ - errno_t ret; - - if (meminfo == NULL) { - return -1; - } - if (atomic_read(&g_cmdSend)) { - if (GetTeeMemInfoCmd() != 0) { - return -1; - } - } else { - atomic_set(&g_cmdSend, 0); - } - mutex_lock(&g_meminfoLock); - ret = memcpy_s((void *)meminfo, sizeof(*meminfo), - (void *)&g_teeMeminfo, sizeof(g_teeMeminfo)); - mutex_unlock(&g_meminfoLock); - if (ret != EOK) { - return -1; - } - - return 0; -} -EXPORT_SYMBOL(GetTeeMeminfo); - -static int SendDumpMem(int flag, const struct TeeMem *statmem) -{ - TcNsSmcCmd smcCmd = { {0}, 0 }; - struct MbCmdPack *mbPack = NULL; - int ret; - - if (statmem == NULL) { - tloge("statmem is NULL\n"); - return -1; - } - mbPack = MailboxAllocCmdPack(); - if (mbPack == NULL) { - return -ENOMEM; - } - smcCmd.cmdId = GLOBAL_CMD_ID_DUMP_MEMINFO; - smcCmd.globalCmd = true; - mbPack->operation.paramTypes = TEEC_PARAM_TYPES( - TEE_PARAM_TYPE_MEMREF_INOUT, TEE_PARAM_TYPE_VALUE_INPUT, - TEE_PARAM_TYPE_NONE, TEE_PARAM_TYPE_NONE); - mbPack->operation.params[TEE_PARAM_ONE].memref.buffer = LOS_PaddrQuery((void *)statmem); - mbPack->operation.params[TEE_PARAM_ONE].memref.size = sizeof(*statmem); - mbPack->operation.bufferHaddr[TEE_PARAM_ONE] = 0; - mbPack->operation.params[TEE_PARAM_TWO].value.a = flag; - smcCmd.operationPhys = - (unsigned int)LOS_PaddrQuery(&mbPack->operation); - smcCmd.operationHphys = 0; - ret = TcNsSmc(&smcCmd); - if (ret) { - tloge("SendDumpMem failed.\n"); - } - MailboxFree(mbPack); - return ret; -} - -static void ArchiveLog(const char *param) -{ - (void)param; - TzDebugArchiveLog(); -} - -static void TzDump(const char *param) -{ - (void)param; - ShowCmdBitmap(); - WakeupTcSiq(); -} - -static void TzMemDump(const char *param) -{ - struct TeeMem *mem = NULL; - - (void)param; - mem = (struct TeeMem *)MailboxAlloc(sizeof(*mem), MB_FLAG_ZERO); - if (mem == NULL) { - tloge("mailbox alloc failed\n"); - return; - } - if (SendDumpMem(1, mem) != 0) { - tloge("send dump mem failed\n"); - } - - MailboxFree(mem); -} - -static int MemstatThread(UINTPTR arg, int len) -{ - (void)len; - (void)arg; - return 0; -} - -static void TzMemStat(const char *param) -{ - LosTaskCB *stat_tsk = NULL; - (void)param; - stat_tsk = KthreadRun(MemstatThread, NULL, 0, "tzmemstat"); - if (IS_ERR(stat_tsk)) { - tloge("memstat failed\n"); - } -} - -static void TzLogWriteDbg(const char *param) -{ - (void)param; -} - -static void TzHelp(const char *param); - -static struct OptOps g_optArr[] = { - {"help", TzHelp}, - {"archivelog", ArchiveLog}, - {"dump", TzDump}, - {"memdump", TzMemDump}, - {"logwrite", TzLogWriteDbg}, - {"dump_service", DumpServicesStatus}, - {"memstat", TzMemStat}, -}; - -static void TzHelp(const char *param) -{ - uint32_t i; - (void)param; - - for (i = 0; i < sizeof(g_optArr) / sizeof(struct OptOps); i++) { - tloge("cmd:%s\n", g_optArr[i].name); - } -} - -static ssize_t TzDbgOptWrite(struct file *filp, - const char __user *ubuf, size_t cnt) -{ - char buf[128] = {0}; /* 128, size of copy from ubuf */ - char *value = NULL; - char *p = NULL; - uint32_t i = 0; - - if ((ubuf == NULL) || (filp == NULL)) { - return -EINVAL; - } - - if (cnt >= sizeof(buf)) { - return -EINVAL; - } - - if (cnt == 0) { - return -EINVAL; - } - - if (copy_from_user(buf, ubuf, cnt)) { - return -EFAULT; - } - buf[cnt] = 0; - if (cnt > 0 && buf[cnt - 1] == '\n') { - buf[cnt - 1] = 0; - } - value = buf; - p = strsep(&value, ":"); - if (p == NULL) { - return -EINVAL; - } - for (i = 0; i < sizeof(g_optArr) / sizeof(struct OptOps); i++) { - if (!strncmp(p, g_optArr[i].name, strlen(g_optArr[i].name)) && - strlen(p) == strlen(g_optArr[i].name)) { - g_optArr[i].func(value); - return cnt; - } - } - return -EFAULT; -} - -static const struct file_operations_vfs g_tzDbgOptFops = { - .write = TzDbgOptWrite, -}; - -#define TC_NS_CLIENT_TZDEBUG "/dev/tzdebug" - -int TzdebugInit(void) -{ - int ret = CreateTcClientDevice(TC_NS_CLIENT_TZDEBUG, &g_tzDbgOptFops); - if (ret != EOK) { - return ret; - } - return 0; -} diff --git a/tzdriver/src/tzdriver_compat.c b/tzdriver/src/tzdriver_compat.c deleted file mode 100644 index ac4b27a..0000000 --- a/tzdriver/src/tzdriver_compat.c +++ /dev/null @@ -1,262 +0,0 @@ -/* - * Copyright (c) 2013-2019 Huawei Technologies Co., Ltd. All rights reserved. - * Copyright (c) 2020-2021 Huawei Device Co., Ltd. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be used - * to endorse or promote products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "tzdriver_compat.h" -#include "mbedtls/aes.h" - -LosTaskCB *KthreadRun(int (*threadfn)(UINTPTR data, int dataLen), void *data, int dataLen, char *name) -{ - LosTaskCB *ktask = NULL; - UINT32 taskId = 0; - UINT32 ret; - TSK_INIT_PARAM_S taskInitParam; - - if (threadfn == NULL) { - return NULL; - } - - if (memset_s(&taskInitParam, sizeof(TSK_INIT_PARAM_S), 0, sizeof(TSK_INIT_PARAM_S)) != EOK) { - return NULL; - } - - taskInitParam.pfnTaskEntry = (TSK_ENTRY_FUNC)threadfn; - taskInitParam.uwStackSize = LOSCFG_BASE_CORE_TSK_DEFAULT_STACK_SIZE; - taskInitParam.pcName = name; - taskInitParam.usTaskPrio = 1; - taskInitParam.auwArgs[0] = (UINTPTR)data; - taskInitParam.auwArgs[1] = dataLen; - taskInitParam.uwResved = LOS_TASK_STATUS_DETACHED; - - ret = LOS_TaskCreate(&taskId, &taskInitParam); - if (ret != LOS_OK) { - return NULL; - } - - ktask = (LosTaskCB *)OS_TCB_FROM_TID(taskId); - (VOID)LOS_TaskYield(); - return ktask; -} - -void KthreadStop(const LosTaskCB *k) -{ - if (k != NULL) { - LOS_TaskDelete(k->taskID); - } -} - -int KthreadShouldStop(void) -{ - return (OsCurrTaskGet()->signal == SIGNAL_KILL); -} - -ssize_t SimpleReadFromBuffer(void __user *to, size_t count, - const void *from, size_t available) -{ - size_t ret; - - if (count == 0 || available == 0) { - return 0; - } - - if (count > available) { - count = available; - } - - ret = copy_to_user(to, from, count); - if (ret == count) { - return -EFAULT; - } - count -= ret; - return count; -} - -#define MAX_ORDER 31 - -LosVmPage *MailboxPoolAllocPages(unsigned int order) -{ - if (order > MAX_ORDER) { - return NULL; - } - void *ptr = LOS_PhysPagesAllocContiguous(1UL << order); - if (ptr == NULL) { - PRINTK("mailbox pool contiguous ptr null size %x\n", 1 << order); - return NULL; - } - for (int i = 0; i < (1UL << order); i++) { - // mempool is used to mmap, add ref to prevent pmm free page to free list. - LosVmPage *page = OsVmVaddrToPage((void *)((intptr_t)ptr + PAGE_SIZE * i)); - if (page != NULL) { - LOS_AtomicInc(&page->refCounts); - } - } - - return OsVmVaddrToPage(ptr); -} - -void MailboxPoolFreePages(LosVmPage *pageArray, size_t order) -{ - if (pageArray == NULL || order > MAX_ORDER) { - return; - } - - for (int i = 0; i < (1UL << order); i++) { - LOS_AtomicDec(&(pageArray[i].refCounts)); - } - LOS_PhysPagesFreeContiguous(pageArray, (1UL << order)); -} - -INT32 DoVmallocRemap(LosVmMapRegion *vma, void *kvaddr) -{ - int i; - int ret = 0; - paddr_t pa; - UINT32 uflags = VM_MAP_REGION_FLAG_PERM_READ | VM_MAP_REGION_FLAG_PERM_WRITE | VM_MAP_REGION_FLAG_PERM_USER; - LosVmPage *vmPage = NULL; - - if (vma == NULL || kvaddr == NULL) { - return -EINVAL; - } - - LosVmSpace *vSpace = LOS_SpaceGet(vma->range.base); - if (vSpace == NULL) { - return -EINVAL; - } - - vaddr_t kva = (vaddr_t)(uintptr_t)kvaddr; - vaddr_t uva = vma->range.base; - unsigned int page; - - (VOID)LOS_MuxAcquire(&vSpace->regionMux); - for (i = 0; i < (vma->range.size >> PAGE_SHIFT); i++) { - page = (unsigned int)i; - pa = LOS_PaddrQuery((void *)(uintptr_t)(kva + (page << PAGE_SHIFT))); - if (pa == 0) { - PRINT_ERR("%s, %d\n", __FUNCTION__, __LINE__); - ret = -EINVAL; - break; - } - vmPage = LOS_VmPageGet(pa); - if (vmPage == NULL) { - PRINT_ERR("%s, %d\n", __FUNCTION__, __LINE__); - ret = -EINVAL; - break; - } - status_t err = LOS_ArchMmuMap(&vSpace->archMmu, uva + (page << PAGE_SHIFT), pa, 1, uflags); - if (err < 0) { - ret = err; - PRINT_ERR("%s, %d\n", __FUNCTION__, __LINE__); - break; - } - LOS_AtomicInc(&vmPage->refCounts); - } - /* if any failure happened, rollback */ - if (i < (vma->range.size >> PAGE_SHIFT)) { - for (i = i - 1; i >= 0; i--) { - page = (unsigned int)i; - pa = LOS_PaddrQuery((void *)(uintptr_t)(kva + (page << PAGE_SHIFT))); - vmPage = LOS_VmPageGet(pa); - (VOID)LOS_ArchMmuUnmap(&vSpace->archMmu, uva + (page << PAGE_SHIFT), 1); - (VOID)LOS_PhysPageFree(vmPage); - } - } - - (VOID)LOS_MuxRelease(&vSpace->regionMux); - return ret; -} - -int RemapVmallocRange(LosVmMapRegion *vma, void *addr, - unsigned long pgoff) -{ - if (pgoff != 0) { - return -1; - } - return DoVmallocRemap(vma, addr); -} - -int CreateTcClientDevice(const char *devName, const struct file_operations_vfs *op) -{ - int ret = register_driver(devName, op, TEE_DEV_PRI, NULL); - if (unlikely(ret)) { - return -1; - } - - return EOK; -} - -#define IV_LEN 16 -#define KEY_BITS 256 -#define MAX_AES_CRYPT_SIZE SZ_4M -int CryptoAescbcKey256(unsigned char *output, const unsigned char *input, struct AesParam *param) -{ - mbedtls_aes_context ctx; - int ret; - if (!output || !input) { - return -1; - } - - if (!param || !param->iv || !param->key || - param->size < 0 || param->size > MAX_AES_CRYPT_SIZE) { - return -1; - } - int mode = param->encryptoType ? MBEDTLS_AES_ENCRYPT : MBEDTLS_AES_DECRYPT; - unsigned char ivTmp[IV_LEN] = {0}; - - ret = memcpy_s(ivTmp, IV_LEN, param->iv, IV_LEN); - if (ret != EOK) { - return -1; - } - mbedtls_aes_init(&ctx); - - if (mode == MBEDTLS_AES_ENCRYPT) { - ret = mbedtls_aes_setkey_enc(&ctx, param->key, KEY_BITS); - } else { - ret = mbedtls_aes_setkey_dec(&ctx, param->key, KEY_BITS); - } - if (ret) { - return -1; - } - return mbedtls_aes_crypt_cbc(&ctx, mode, param->size, ivTmp, input, output); -} - -void SetVmmRegionCodeStart(UINTPTR codeStart, UINT32 codeSize) -{ - LosVmSpace *space = NULL; - space = OsCurrProcessGet()->vmSpace; - if (space->codeStart != 0) { - return; - } - - if (codeSize == 0 || codeStart + codeSize < codeStart) { - return; - } - space->codeStart = codeStart; - space->codeEnd = codeStart + codeSize; -} -- GitLab