From c4c22f0044c901b43816ff4558e0e18181155c7b Mon Sep 17 00:00:00 2001 From: Jens Wiklander Date: Wed, 16 Oct 2024 20:31:53 +0200 Subject: [PATCH 01/27] tee_api_types.h: default alignment for TEE_BigIntFMMContext Remove the custom alignment from TEE_BigIntFMMContext. Signed-off-by: Jens Wiklander --- lib/libutee/include/tee_api_types.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/libutee/include/tee_api_types.h b/lib/libutee/include/tee_api_types.h index b78acd4ef32..b8dd324680f 100644 --- a/lib/libutee/include/tee_api_types.h +++ b/lib/libutee/include/tee_api_types.h @@ -190,7 +190,7 @@ typedef uint32_t TEE_BigInt; typedef uint32_t TEE_BigIntFMM; -typedef uint32_t TEE_BigIntFMMContext __aligned(__alignof__(void *)); +typedef uint32_t TEE_BigIntFMMContext; /* Tee Secure Element APIs */ From 9e9a4724b1e70e3d43a8643bb66072139fd7963f Mon Sep 17 00:00:00 2001 From: Jens Wiklander Date: Thu, 26 Sep 2024 09:02:29 +0200 Subject: [PATCH 02/27] libmbedtls: mbedtls_config_uta.h: enable SHA-384 and SHA-512 support Enable SHA-384 and SHA-512 support for user TAs. Signed-off-by: Jens Wiklander --- lib/libmbedtls/include/mbedtls_config_uta.h | 2 ++ 1 file changed, 2 insertions(+) diff --git a/lib/libmbedtls/include/mbedtls_config_uta.h b/lib/libmbedtls/include/mbedtls_config_uta.h index 492055676e2..a2130121022 100644 --- a/lib/libmbedtls/include/mbedtls_config_uta.h +++ b/lib/libmbedtls/include/mbedtls_config_uta.h @@ -22,6 +22,8 @@ #define MBEDTLS_SHA1_C #define MBEDTLS_SHA256_C +#define MBEDTLS_SHA384_C +#define MBEDTLS_SHA512_C #define MBEDTLS_MD_C #define MBEDTLS_MD5_C From 472fcb2cf97006927c31db5b3e78853d86d7095e Mon Sep 17 00:00:00 2001 From: Jens Wiklander Date: Thu, 19 Sep 2024 13:08:36 +0200 Subject: [PATCH 03/27] mk/subdir.mk: refactor process-subdir-{srcs-y,gensrcs-helper} Moves the common parts of the two make macros process-subdir-srcs-y and process-subdir-gensrcs-helper into a new macro, process-file-vars. Signed-off-by: Jens Wiklander Reviewed-by: Etienne Carriere Reviewed-by: Jerome Forissier --- mk/subdir.mk | 89 ++++++++++++++++++---------------------------------- 1 file changed, 30 insertions(+), 59 deletions(-) diff --git a/mk/subdir.mk b/mk/subdir.mk index d280c309ecf..a548e16b954 100644 --- a/mk/subdir.mk +++ b/mk/subdir.mk @@ -23,33 +23,18 @@ asm-defines-files := uniq = $(if $1,$(firstword $1) $(call uniq,$(filter-out $(firstword $1),$1))) -define process-subdir-srcs-y -ifeq ($$(sub-dir),.) -srcs += $1 -oname := $(out-dir)/$(base-prefix)$(basename $1).o -else -ifneq ($(filter /%,$(1)),) -# $1 is an absolute path - start with "/" -srcs += $1 -oname := $(out-dir)/$(base-prefix)$(basename $1).o -else -srcs += $(sub-dir)/$1 -oname := $(out-dir)/$(base-prefix)$(basename $$(sub-dir)/$1).o -endif -endif -cflags-$$(oname) := $$(cflags-y) $$(cflags-$(1)-y) -cflags-remove-$$(oname) := $$(cflags-remove-y) \ - $$(cflags-remove-$(1)-y) -cxxflags-$$(oname) := $$(cxxflags-y) $$(cxxflags-$(1)-y) -cxxflags-remove-$$(oname) := $$(cxxflags-remove-y) \ - $$(cxxflags-remove-$(1)-y) -cppflags-$$(oname) := $$(cppflags-y) $$(cppflags-$(1)-y) -cppflags-remove-$$(oname) := $$(cppflags-remove-y) \ - $$(cppflags-remove-$(1)-y) -aflags-$$(oname) := $$(aflags-y) $$(aflags-$(1)-y) -aflags-remove-$$(oname) := $$(aflags-remove-y) \ - $$(aflags-remove-$(1)-y) -incdirs-$$(oname) := $$(thissubdir-incdirs) $$(addprefix $(sub-dir)/,$$(incdirs-$(1)-y)) +define process-file-vars +# $1 is source file name +# $2 is output file name +cflags-$(2) := $$(cflags-y) $$(cflags-$(1)-y) +cflags-remove-$(2) := $$(cflags-remove-y) $$(cflags-remove-$(1)-y) +cxxflags-$(2) := $$(cxxflags-y) $$(cxxflags-$(1)-y) +cxxflags-remove-$(2) := $$(cxxflags-remove-y) $$(cxxflags-remove-$(1)-y) +cppflags-$(2) := $$(cppflags-y) $$(cppflags-$(1)-y) +cppflags-remove-$(2) := $$(cppflags-remove-y) $$(cppflags-remove-$(1)-y) +aflags-$(2) := $$(aflags-y) $$(aflags-$(1)-y) +aflags-remove-$(2) := $$(aflags-remove-y) $$(aflags-remove-$(1)-y) +incdirs-$(2) := $$(thissubdir-incdirs) $$(addprefix $(sub-dir)/,$$(incdirs-$(1)-y)) # Clear local filename specific variables to avoid accidental reuse # in another subdirectory cflags-$(1)-y := @@ -64,8 +49,23 @@ cppflags-lib-y := aflags-$(1)-y := aflags-remove-$(1)-y := incdirs-$(1)-y := -fname := -oname := +endef #process-file-vars + +define process-subdir-srcs-y +ifeq ($$(sub-dir),.) +srcs += $1 +oname := $(out-dir)/$(base-prefix)$(basename $1).o +else +ifneq ($(filter /%,$(1)),) +# $1 is an absolute path - start with "/" +srcs += $1 +oname := $(out-dir)/$(base-prefix)$(basename $1).o +else +srcs += $(sub-dir)/$1 +oname := $(out-dir)/$(base-prefix)$(basename $$(sub-dir)/$1).o +endif +endif +$$(eval $$(call process-file-vars,$1,$$(oname))) endef #process-subdir-srcs-y define process-subdir-gensrcs-helper @@ -90,36 +90,7 @@ $2: $$(depends-$1) $(q)mkdir -p $4 $(q)$$(recipe-$2) -cflags-$$(oname) := $$(cflags-y) $$(cflags-$(1)-y) -cflags-remove-$$(oname) := $$(cflags-remove-y) \ - $$(cflags-remove-$(1)-y) -cxxflags-$$(oname) := $$(cxxflags-y) $$(cxxflags-$(1)-y) -cxxflags-remove-$$(oname) := $$(cxxflags-remove-y) \ - $$(cxxflags-remove-$(1)-y) -cppflags-$$(oname) := $$(cppflags-y) $$(cppflags-$(1)-y) -cppflags-remove-$$(oname) := $$(cppflags-remove-y) \ - $$(cppflags-remove-$(1)-y) -aflags-$$(oname) := $$(aflags-y) $$(aflags-$(1)-y) -aflags-remove-$$(oname) := $$(aflags-remove-y) \ - $$(aflags-remove-$(1)-y) -incdirs-$$(oname) := $$(thissubdir-incdirs) $$(addprefix $(sub-dir)/,$$(incdirs-$(1)-y)) -# Clear local filename specific variables to avoid accidental reuse -# in another subdirectory -cflags-$(1)-y := -cflags-remove-$(1)-y := -cflags-lib-y := -cxxflags-$(1)-y := -cxxflags-remove-$(1)-y := -cxxflags-lib-y := -cppflags-$(1)-y := -cppflags-remove-$(1)-y := -cppflags-lib-y := -aflags-$(1)-y := -aflags-remove-$(1)-y := -incdirs-$(1)-y := -fname := -oname := - +$$(eval $$(call process-file-vars,$1,$$(oname))) endef #process-subdir-gensrcs-helper define process-subdir-gensrcs-y From f9f61da8de2c6fb11c6bc4e4f6efd7d5383db26c Mon Sep 17 00:00:00 2001 From: Jens Wiklander Date: Thu, 19 Sep 2024 14:14:31 +0200 Subject: [PATCH 04/27] ta_dev_kit.mk: use spec-srcs and spec-out-dir The commit cfa34d9afb5c ("Add support for compiling in-tree TAs") added spec-srcs and spec-out-dir for special handling of user_ta_header.c when compiling in-tree TAs. However, these variables are just as relevant for out-of-tree TAs compiled via ta/mk/ta_dev_kit.mk. So as a simplification switch to use spec-srcs and spec-out-dir in that file too. Signed-off-by: Jens Wiklander Reviewed-by: Etienne Carriere Acked-by: Jerome Forissier --- ta/mk/ta_dev_kit.mk | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/ta/mk/ta_dev_kit.mk b/ta/mk/ta_dev_kit.mk index 6d544a7a4ef..da788d592ed 100644 --- a/ta/mk/ta_dev_kit.mk +++ b/ta/mk/ta_dev_kit.mk @@ -126,11 +126,10 @@ include $(ta-dev-kit-dir$(sm))/mk/subdir.mk ifneq ($(user-ta-uuid),) # Build target is TA -vpath %.c $(ta-dev-kit-dir$(sm))/src -srcs += user_ta_header.c -ifeq ($(sm),ta_arm32) -vpath %.S $(ta-dev-kit-dir$(sm))/src -srcs += ta_entry_a32.S +spec-out-dir := $(link-out-dir$(sm)) +spec-srcs += $(ta-dev-kit-dir$(sm))/src/user_ta_header.c +ifeq ($(ta-target),ta_arm32) +spec-srcs += $(ta-dev-kit-dir$(sm))/src/ta_entry_a32.S endif endif From d9517f85b98ed3cea843256aee7047c0b1478e9a Mon Sep 17 00:00:00 2001 From: Jens Wiklander Date: Thu, 19 Sep 2024 11:42:50 +0200 Subject: [PATCH 05/27] mk: introduce global-incdirs_ext-y Introduce the global-incdirs_ext-y variable to deal with including header files from outside of this git (optee_os.git). Signed-off-by: Jens Wiklander Reviewed-by: Etienne Carriere Reviewed-by: Jerome Forissier --- mk/subdir.mk | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/mk/subdir.mk b/mk/subdir.mk index a548e16b954..58b31e5fba4 100644 --- a/mk/subdir.mk +++ b/mk/subdir.mk @@ -111,7 +111,7 @@ endif include $1/sub.mk sub-subdirs := $$(addprefix $1/,$$(subdirs-y)) $$(subdirs_ext-y) -incdirs$(sm) := $(incdirs$(sm)) $$(addprefix $1/,$$(global-incdirs-y)) +incdirs$(sm) := $(incdirs$(sm)) $$(addprefix $1/,$$(global-incdirs-y)) $$(global-incdirs_ext-y) thissubdir-incdirs := $(out-dir)/$(base-prefix)$1 $$(addprefix $1/,$$(incdirs-y)) $$(incdirs_ext-y) ifneq ($$(libname),) incdirs-lib$$(libname)-$$(sm) := $$(incdirs-lib$$(libname)-$$(sm)) $$(addprefix $1/,$$(incdirs-lib-y)) @@ -139,6 +139,7 @@ aflags-remove-y := subdirs-y := subdirs_ext-y := global-incdirs-y := +global-incdirs_ext-y := incdirs-lib-y := incdirs-y := incdirs_ext-y := From 2d6d8352a638b1906df02ed9058775ec657759bd Mon Sep 17 00:00:00 2001 From: Jens Wiklander Date: Thu, 19 Sep 2024 15:07:26 +0200 Subject: [PATCH 06/27] mk/subdir.mk: introduce srcs_ext-y and srcs_ext_base-y Introduce two new variables srcs_ext-y and srcs_ext_base-y to deal with compiling source code outside of this git (optee_os.git). srcs_ext_base-y assigns the root directory of the external source files to compile. srcs_ext-y works as srcs-y except that it's relative to the $(srcs_ext_base-y) directory. Introduce the per source file variable oname--y to override the default output object file name. This helps to shorten and make a more sane name for the output object file name when the source file is outside optee_os source tree, for instance, a third-party library. Signed-off-by: Jens Wiklander Acked-by: Jerome Forissier --- mk/compile.mk | 3 +-- mk/subdir.mk | 45 +++++++++++++++++++++++++++++++++++---------- 2 files changed, 36 insertions(+), 12 deletions(-) diff --git a/mk/compile.mk b/mk/compile.mk index e8d9026b2db..aa3f78aed37 100644 --- a/mk/compile.mk +++ b/mk/compile.mk @@ -163,8 +163,7 @@ $2: $1 FORCE-GENSRC$(sm) endef -$(foreach f, $(srcs), $(eval $(call \ - process_srcs,$(f),$(out-dir)/$(base-prefix)$$(basename $f).o))) +$(foreach f, $(srcs), $(eval $(call process_srcs,$(f),$$(oname-$(sm)-$(f))))) # Handle generated source files, that is, files that are compiled from out-dir $(foreach f, $(gen-srcs), $(eval $(call process_srcs,$(f),$$(basename $f).o))) diff --git a/mk/subdir.mk b/mk/subdir.mk index 58b31e5fba4..db10c1ce854 100644 --- a/mk/subdir.mk +++ b/mk/subdir.mk @@ -23,8 +23,8 @@ asm-defines-files := uniq = $(if $1,$(firstword $1) $(call uniq,$(filter-out $(firstword $1),$1))) -define process-file-vars -# $1 is source file name +define process-file-vars-helper +# $1 is local source file name # $2 is output file name cflags-$(2) := $$(cflags-y) $$(cflags-$(1)-y) cflags-remove-$(2) := $$(cflags-remove-y) $$(cflags-remove-$(1)-y) @@ -49,23 +49,44 @@ cppflags-lib-y := aflags-$(1)-y := aflags-remove-$(1)-y := incdirs-$(1)-y := -endef #process-file-vars +endef #process-file-vars-helper + +define process-file-vars +# $1 is local source file name +# $2 is output file name +# $3 is tree source file name +oname-$(sm)-$3 := $$(if $$(oname-$1-y),$(out-dir)/$(base-prefix)/$$(oname-$1-y),$2) +$$(eval $$(call process-file-vars-helper,$1,$$(oname-$(sm)-$3))) +endef define process-subdir-srcs-y ifeq ($$(sub-dir),.) -srcs += $1 -oname := $(out-dir)/$(base-prefix)$(basename $1).o +srcs += $1 +fname := $1 +oname := $(out-dir)/$(base-prefix)$(basename $1).o else ifneq ($(filter /%,$(1)),) # $1 is an absolute path - start with "/" -srcs += $1 -oname := $(out-dir)/$(base-prefix)$(basename $1).o +srcs += $1 +fname := $1 +oname := $(out-dir)/$(base-prefix)$(basename $1).o else -srcs += $(sub-dir)/$1 -oname := $(out-dir)/$(base-prefix)$(basename $$(sub-dir)/$1).o +srcs += $(sub-dir)/$1 +fname := $(sub-dir)/$1 +oname := $(out-dir)/$(base-prefix)$(basename $$(sub-dir)/$1).o endif endif -$$(eval $$(call process-file-vars,$1,$$(oname))) +$$(eval $$(call process-file-vars,$1,$$(oname),$$(fname))) +endef #process-subdir-srcs-y + +define process-subdir-srcs_ext-y +ifneq ($(filter /%,$(1)),) +$$(error Absolute path not supported for srcs_ext-y: $(1)) +endif +srcs += $2/$1 +fname := $2/$1 +oname := $(out-dir)/$(base-prefix)$(basename $$(sub-dir)/$1).o +$$(eval $$(call process-file-vars,$1,$$(oname),$$(fname))) endef #process-subdir-srcs-y define process-subdir-gensrcs-helper @@ -123,9 +144,13 @@ endif # Process files in current directory $$(foreach g, $$(gensrcs-y), $$(eval $$(call process-subdir-gensrcs-y,$$(g)))) $$(foreach s, $$(srcs-y), $$(eval $$(call process-subdir-srcs-y,$$(s)))) +$$(foreach s, $$(srcs_ext-y), $$(eval $$(call \ + process-subdir-srcs_ext-y,$$(s),$$(firstword $$(srcs_ext_base-y))))) $$(foreach a, $$(asm-defines-y), $$(eval $$(call process-subdir-asm-defines-y,$$(a)))) # Clear flags used when processing current directory srcs-y := +srcs_ext-y := +srcs_ext_base-y := cflags-y := cflags-lib-y := cxxflags-y := From bace05263cabcfb1300685e4e8d5194b281ae4eb Mon Sep 17 00:00:00 2001 From: Jens Wiklander Date: Wed, 18 Sep 2024 16:59:07 +0200 Subject: [PATCH 07/27] ta: ftpm: import initial source Import initial source from https://github.com/microsoft/ms-tpm-20-ref copy initial source code from Samples/ARM32-FirmwareTPM/optee_ta/fTPM commit e9fc7b89d865 ("Fix conflicting types for `ReadVarBytes`. (#102)") Signed-off-by: Jens Wiklander --- ta/ftpm/Makefile | 13 + ta/ftpm/fTPM.c | 479 ++++++++++++ ta/ftpm/include/Wolf/TpmToWolfHash.h | 199 +++++ ta/ftpm/include/Wolf/TpmToWolfMath.h | 91 +++ ta/ftpm/include/Wolf/TpmToWolfSym.h | 120 +++ ta/ftpm/include/Wolf/user_settings.h | 108 +++ ta/ftpm/include/fTPM.h | 106 +++ ta/ftpm/include/fTPM_event_log.h | 13 + ta/ftpm/include/fTPM_event_log_private.h | 269 +++++++ ta/ftpm/include/fTPM_helpers.h | 15 + ta/ftpm/lib/sub.mk | 8 + ta/ftpm/lib/tpm/sub.mk | 274 +++++++ ta/ftpm/lib/wolf/sub.mk | 58 ++ ta/ftpm/platform/AdminPPI.c | 426 +++++++++++ ta/ftpm/platform/Cancel.c | 80 ++ ta/ftpm/platform/Clock.c | 302 ++++++++ ta/ftpm/platform/EPS.c | 90 +++ ta/ftpm/platform/Entropy.c | 128 ++++ ta/ftpm/platform/EventLogPrint.c | 283 +++++++ ta/ftpm/platform/LocalityPlat.c | 65 ++ ta/ftpm/platform/NVMem.c | 646 ++++++++++++++++ ta/ftpm/platform/NvAdmin.c | 151 ++++ ta/ftpm/platform/PPPlat.c | 80 ++ ta/ftpm/platform/PlatformACT.c | 345 +++++++++ ta/ftpm/platform/PlatformData.c | 82 +++ ta/ftpm/platform/PowerPlat.c | 113 +++ ta/ftpm/platform/RunCommand.c | 90 +++ ta/ftpm/platform/Unique.c | 102 +++ ta/ftpm/platform/fTPM_event_log.c | 391 ++++++++++ ta/ftpm/platform/fTPM_helpers.c | 26 + ta/ftpm/platform/include/Admin.h | 230 ++++++ ta/ftpm/platform/include/Platform.h | 52 ++ ta/ftpm/platform/include/PlatformData.h | 137 ++++ ta/ftpm/platform/include/Platform_fp.h | 492 +++++++++++++ ta/ftpm/reference/RuntimeSupport.c | 84 +++ ta/ftpm/reference/include/RuntimeSupport.h | 93 +++ ta/ftpm/reference/include/TpmProfile.h | 810 +++++++++++++++++++++ ta/ftpm/reference/include/TpmSal.h | 115 +++ ta/ftpm/reference/include/VendorString.h | 93 +++ ta/ftpm/reference/include/bool.h | 51 ++ ta/ftpm/sub.mk | 77 ++ ta/ftpm/user_ta_header_defines.h | 56 ++ 42 files changed, 7443 insertions(+) create mode 100644 ta/ftpm/Makefile create mode 100644 ta/ftpm/fTPM.c create mode 100644 ta/ftpm/include/Wolf/TpmToWolfHash.h create mode 100644 ta/ftpm/include/Wolf/TpmToWolfMath.h create mode 100644 ta/ftpm/include/Wolf/TpmToWolfSym.h create mode 100644 ta/ftpm/include/Wolf/user_settings.h create mode 100644 ta/ftpm/include/fTPM.h create mode 100644 ta/ftpm/include/fTPM_event_log.h create mode 100644 ta/ftpm/include/fTPM_event_log_private.h create mode 100644 ta/ftpm/include/fTPM_helpers.h create mode 100644 ta/ftpm/lib/sub.mk create mode 100644 ta/ftpm/lib/tpm/sub.mk create mode 100644 ta/ftpm/lib/wolf/sub.mk create mode 100644 ta/ftpm/platform/AdminPPI.c create mode 100644 ta/ftpm/platform/Cancel.c create mode 100644 ta/ftpm/platform/Clock.c create mode 100644 ta/ftpm/platform/EPS.c create mode 100644 ta/ftpm/platform/Entropy.c create mode 100644 ta/ftpm/platform/EventLogPrint.c create mode 100644 ta/ftpm/platform/LocalityPlat.c create mode 100644 ta/ftpm/platform/NVMem.c create mode 100644 ta/ftpm/platform/NvAdmin.c create mode 100644 ta/ftpm/platform/PPPlat.c create mode 100644 ta/ftpm/platform/PlatformACT.c create mode 100644 ta/ftpm/platform/PlatformData.c create mode 100644 ta/ftpm/platform/PowerPlat.c create mode 100644 ta/ftpm/platform/RunCommand.c create mode 100644 ta/ftpm/platform/Unique.c create mode 100644 ta/ftpm/platform/fTPM_event_log.c create mode 100644 ta/ftpm/platform/fTPM_helpers.c create mode 100644 ta/ftpm/platform/include/Admin.h create mode 100644 ta/ftpm/platform/include/Platform.h create mode 100644 ta/ftpm/platform/include/PlatformData.h create mode 100644 ta/ftpm/platform/include/Platform_fp.h create mode 100644 ta/ftpm/reference/RuntimeSupport.c create mode 100644 ta/ftpm/reference/include/RuntimeSupport.h create mode 100644 ta/ftpm/reference/include/TpmProfile.h create mode 100644 ta/ftpm/reference/include/TpmSal.h create mode 100644 ta/ftpm/reference/include/VendorString.h create mode 100644 ta/ftpm/reference/include/bool.h create mode 100644 ta/ftpm/sub.mk create mode 100644 ta/ftpm/user_ta_header_defines.h diff --git a/ta/ftpm/Makefile b/ta/ftpm/Makefile new file mode 100644 index 00000000000..c71eecd6d17 --- /dev/null +++ b/ta/ftpm/Makefile @@ -0,0 +1,13 @@ +BINARY=bc50d971-d4c9-42c4-82cb-343fb7f37896 + +O ?= ../out/fTPM +WOLF_ROOT := ../../../../external/wolfssl/ +TPM_ROOT := ../../../../ + +include $(TA_DEV_KIT_DIR)/mk/ta_dev_kit.mk + +clean: clean_stripped_file +.PHONY: clean_stripped_file +clean_stripped_file: + rm -f $(BINARY).stripped.elf + diff --git a/ta/ftpm/fTPM.c b/ta/ftpm/fTPM.c new file mode 100644 index 00000000000..65d44976c84 --- /dev/null +++ b/ta/ftpm/fTPM.c @@ -0,0 +1,479 @@ +/* Microsoft Reference Implementation for TPM 2.0 + * + * The copyright in this software is being made available under the BSD License, + * included below. This software may be subject to other third party and + * contributor rights, including patent rights, and no such rights are granted + * under this license. + * + * Copyright (c) Microsoft Corporation + * Copyright (c) Arm Limited. + * + * All rights reserved. + * + * BSD License + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * Redistributions of source code must retain the above copyright notice, this list + * of conditions and the following disclaimer. + * + * 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. + * + * 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. + */ + +#define STR_TRACE_USER_TA "fTPM" + +#include +#include +#include +#include +#include +#include + +#include "fTPM.h" + +#define TA_ALL_PARAM_TYPE(type) TEE_PARAM_TYPES(type, type, type, type) + +// +// Ensure we have only one active session +// +static bool fTPMSessionActive = false; + +// +// Initialization +// +bool fTPMInitialized = false; + +// +// Local (SW) command buffer +// +static uint8_t fTPMCommand[MAX_COMMAND_SIZE]; + +// +// A subset of TPM return codes (see TpmTypes.h) +// +typedef uint32_t TPM_RC; +#define RC_VER1 (TPM_RC) (0x100) +#define TPM_RC_SUCCESS (TPM_RC) (0x000) +#define TPM_RC_FAILURE (TPM_RC) (RC_VER1+0x001) + +// +// Helper function to read response codes from TPM responses +// +static uint32_t fTPMResponseCode(uint32_t ResponseSize, + uint8_t *ResponseBuffer) +{ + uint32_t ResponseCode; + union { + uint32_t Data; + uint8_t Index[4]; + } Value; + + // In case of too-small response size, assume failure. + if (ResponseSize < 0xA) { + return TPM_RC_FAILURE; + } + + Value.Index[0] = ResponseBuffer[6]; + Value.Index[1] = ResponseBuffer[7]; + Value.Index[2] = ResponseBuffer[8]; + Value.Index[3] = ResponseBuffer[9]; + ResponseCode = SwapBytes32(Value.Data); + + return ResponseCode; +} + +#ifdef MEASURED_BOOT +static TEE_Result get_tpm_event_log(unsigned char *buf, size_t *len) +{ + const TEE_UUID system_uuid = PTA_SYSTEM_UUID; + TEE_TASessionHandle session = TEE_HANDLE_NULL; + TEE_Result res = TEE_ERROR_GENERIC; + uint32_t ret_origin = 0; + const uint32_t param_types = TEE_PARAM_TYPES(TEE_PARAM_TYPE_MEMREF_OUTPUT, + TEE_PARAM_TYPE_NONE, + TEE_PARAM_TYPE_NONE, + TEE_PARAM_TYPE_NONE); + TEE_Param params[TEE_NUM_PARAMS] = {0}; + + res = TEE_OpenTASession(&system_uuid, TEE_TIMEOUT_INFINITE, + 0, NULL, &session, &ret_origin); + if (res != TEE_SUCCESS) + return res; + + params[0].memref.buffer = (void *)buf; + params[0].memref.size = *len; + + res = TEE_InvokeTACommand(session, TEE_TIMEOUT_INFINITE, + PTA_SYSTEM_GET_TPM_EVENT_LOG, + param_types, params, &ret_origin); + + *len = params[0].memref.size; + + TEE_CloseTASession(session); + + return res; +} +#endif // MEASURED_BOOT + +// +// Called when TA instance is created. This is the first call to the TA. +// +TEE_Result TA_CreateEntryPoint(void) +{ + #define STARTUP_SIZE 0x0C + + uint8_t startupClear[STARTUP_SIZE] = { 0x80, 0x01, 0x00, 0x00, 0x00, 0x0c, + 0x00, 0x00, 0x01, 0x44, 0x00, 0x00 }; + uint8_t startupState[STARTUP_SIZE] = { 0x80, 0x01, 0x00, 0x00, 0x00, 0x0c, + 0x00, 0x00, 0x01, 0x44, 0x00, 0x01 }; + uint32_t respLen; + uint8_t *respBuf; +#ifdef MEASURED_BOOT + unsigned char tpm_event_log_buf[EVENT_LOG_SIZE]; + size_t tpm_event_log_len = EVENT_LOG_SIZE; +#endif + +#ifdef fTPMDebug + DMSG("Entry Point\n"); +#endif + + // If we've been here before, don't init again. + if (fTPMInitialized) { + // We may have had TA_DestroyEntryPoint called but we didn't + // actually get torn down. Re-NVEnable, just in case. + if (_plat__NVEnable(NULL) == 0) { + TEE_Panic(TEE_ERROR_BAD_STATE); + } + return TEE_SUCCESS; + } + + // Initialize NV admin state + _admin__NvInitState(); + + // If we fail to open fTPM storage we cannot continue. + if (_plat__NVEnable(NULL) == 0) { + TEE_Panic(TEE_ERROR_BAD_STATE); + } + +#ifdef fTPMDebug + DMSG("NVEnable Complete\n"); +#endif + + // This only occurs when there is no previous NV state, i.e., on first + // boot, after recovering from data loss, we reset the platform, etc. + if (_plat__NvNeedsManufacture()) { +#ifdef fTPMDebug + DMSG("TPM_Manufacture\n"); +#endif + TPM_Manufacture(1); + } + + // "Power-On" the platform + _plat__Signal_PowerOn(); + + // Internal init for reference implementation + _TPM_Init(); + +#ifdef fTPMDebug + DMSG("Init Complete\n"); +#endif + + // Startup with state + if (g_chipFlags.fields.TpmStatePresent) { + + // Re-use request buffer for response (ignored) + respBuf = startupState; + respLen = STARTUP_SIZE; + + ExecuteCommand(STARTUP_SIZE, startupState, &respLen, &respBuf); + if (fTPMResponseCode(respLen, respBuf) == TPM_RC_SUCCESS) { + goto Exit; + } + +#ifdef fTPMDebug + DMSG("Fall through to startup clear\n"); +#endif + + goto Clear; + } + +#ifdef fTPMDebug + DMSG("No TPM state present\n"); +#endif + +Clear: + // Re-use request buffer for response (ignored) + respBuf = startupClear; + respLen = STARTUP_SIZE; + + // Fall back to a Startup Clear + ExecuteCommand(STARTUP_SIZE, startupClear, &respLen, &respBuf); + +Exit: + // Init is complete, indicate so in fTPM admin state. + g_chipFlags.fields.TpmStatePresent = 1; + _admin__SaveChipFlags(); + + // Initialization complete + fTPMInitialized = true; + +#ifdef MEASURED_BOOT + // Extend existing TPM Event Log. + if (get_tpm_event_log(tpm_event_log_buf, + &tpm_event_log_len) == TEE_SUCCESS) + { + +#ifdef fTPMDebug + // Dump the event log + unsigned char* buff = tpm_event_log_buf; + size_t buff_len = tpm_event_log_len; + MSG("Preparing to extend the following TPM Event Log:"); + dump_event_log(tpm_event_log_buf, tpm_event_log_len); +#endif + process_eventlog(tpm_event_log_buf, tpm_event_log_len); + + } +#endif + + return TEE_SUCCESS; +} + + +// +// Called when TA instance destroyed. This is the last call in the TA. +// +void TA_DestroyEntryPoint(void) +{ + // We should only see this called after the OS has shutdown and there + // will be no further commands sent to the TPM. Right now, just close + // our storage object, becasue the TPM driver should have already + // shutdown cleanly. + _plat__NVDisable(); + return; +} + + +// +// Called when a new session is opened to the TA. +// +TEE_Result TA_OpenSessionEntryPoint(uint32_t param_types, + TEE_Param params[4], + void **sess_ctx) +{ + uint32_t exp_param_types = TA_ALL_PARAM_TYPE(TEE_PARAM_TYPE_NONE); + + // Unreferenced parameters + UNREFERENCED_PARAMETER(params); + UNREFERENCED_PARAMETER(sess_ctx); + + // Validate parameter types + if (param_types != exp_param_types) { + return TEE_ERROR_BAD_PARAMETERS; + } + + // Only one active session to the fTPM is permitted + if (fTPMSessionActive) { + return TEE_ERROR_ACCESS_CONFLICT; + } + + // Active session + fTPMSessionActive = true; + + // If return value != TEE_SUCCESS the session will not be created. + return TEE_SUCCESS; +} + + +// +// Called when a session is closed. +// +void TA_CloseSessionEntryPoint(void *sess_ctx) +{ + // Unused parameter(s) + UNREFERENCED_PARAMETER(sess_ctx); + + // Clear active session + if (fTPMSessionActive) { + fTPMSessionActive = false; + } +} + +// +// Called to handle command submission. +// +static TEE_Result fTPM_Submit_Command(uint32_t param_types, + TEE_Param params[4] +) +{ + uint8_t *cmdBuf, *respBuf; + uint32_t cmdLen, respLen; + uint32_t exp_param_types = TEE_PARAM_TYPES(TEE_PARAM_TYPE_MEMREF_INPUT, + TEE_PARAM_TYPE_MEMREF_INOUT, + TEE_PARAM_TYPE_NONE, + TEE_PARAM_TYPE_NONE); + + // Validate parameter types + if (param_types != exp_param_types) { +#ifdef fTPMDebug + IMSG("Bad param type(s)\n"); +#endif + return TEE_ERROR_BAD_PARAMETERS; + } + + // Sanity check our buffer sizes + if ((params[0].memref.size == 0) || + (params[1].memref.size == 0) || + (params[0].memref.size > MAX_COMMAND_SIZE) || + (params[1].memref.size > MAX_RESPONSE_SIZE)) { +#ifdef fTPMDebug + IMSG("Bad param size(s)\n"); +#endif + return TEE_ERROR_BAD_PARAMETERS; + } + + // Copy command locally + memcpy(fTPMCommand, params[0].memref.buffer, params[0].memref.size); + + // Pull the command length from the actual TPM command. The memref size + // field descibes the buffer containing the command, not the command. + cmdBuf = fTPMCommand; + cmdLen = BYTE_ARRAY_TO_UINT32((uint8_t *)&(cmdBuf[2])); + + // Sanity check cmd length included in TPM command + if (cmdLen > params[0].memref.size) { + return TEE_ERROR_BAD_PARAMETERS; + } + + respBuf = (uint8_t *)(params[1].memref.buffer); + respLen = params[1].memref.size; + + // Check if this is a PPI Command + if (!_admin__PPICommand(cmdLen, cmdBuf, &respLen, &respBuf)) { + // If not, pass through to TPM + ExecuteCommand(cmdLen, cmdBuf, &respLen, &respBuf); + } + + // Unfortunately, this cannot be done until after we have our response in + // hand. We will, however, make an effort to return at least a portion of + // the response along with TEE_ERROR_SHORT_BUFFER. + if (respLen > params[1].memref.size) + { +#ifdef fTPMDebug + IMSG("Insufficient buffer length RS: 0x%x > BL: 0x%x\n", respLen, params[1].memref.size); +#endif + return TEE_ERROR_SHORT_BUFFER; + } + +#ifdef fTPMDebug + DMSG("Success, RS: 0x%x\n", respLen); +#endif + + return TEE_SUCCESS; +} + +// +// Called to handle PPI commands +// +static TEE_Result fTPM_Emulate_PPI(uint32_t param_types, + TEE_Param params[4] +) +{ + uint8_t *cmdBuf, *respBuf; + uint32_t cmdLen, respLen; + uint32_t exp_param_types = TEE_PARAM_TYPES(TEE_PARAM_TYPE_MEMREF_INPUT, + TEE_PARAM_TYPE_MEMREF_INOUT, + TEE_PARAM_TYPE_NONE, + TEE_PARAM_TYPE_NONE); + + // Validate parameter types + if (param_types != exp_param_types) { +#ifdef fTPMDebug + IMSG("Bad param type(s)\n"); +#endif + return TEE_ERROR_BAD_PARAMETERS; + } + + // Sanity check our buffer sizes + if ((params[0].memref.size == 0) || + (params[1].memref.size == 0) || + (params[0].memref.size > MAX_COMMAND_SIZE) || + (params[1].memref.size > MAX_RESPONSE_SIZE)) { +#ifdef fTPMDebug + IMSG("Bad param size(s)\n"); +#endif + return TEE_ERROR_BAD_PARAMETERS; + } + + // Copy command locally + memcpy(fTPMCommand, params[0].memref.buffer, params[0].memref.size); + + cmdBuf = fTPMCommand; + cmdLen = params[0].memref.size; + + respBuf = (uint8_t *)(params[1].memref.buffer); + respLen = params[1].memref.size; + + // Pass along to platform PPI processing + if (_admin__PPIRequest(cmdLen, cmdBuf, &respLen, &respBuf)) { +#ifdef fTPMDebug + DMSG("Handled PPI command via TA interface\n"); +#endif + } + else { +#ifdef fTPMDebug + IMSG("Failed to handle PPI command via TA interface\n"); +#endif + } + + if (respLen > params[1].memref.size) { +#ifdef fTPMDebug + IMSG("Insufficient buffer length RS: 0x%x > BL: 0x%x\n", respLen, params[1].memref.size); +#endif + return TEE_ERROR_SHORT_BUFFER; + } + + params[1].memref.size = respLen; + return TEE_SUCCESS; +} + +// +// Called when a TA is invoked. Note, paramters come from normal world. +// +TEE_Result TA_InvokeCommandEntryPoint(void *sess_ctx, + uint32_t cmd_id, + uint32_t param_types, + TEE_Param params[4]) +{ + // Unused parameter(s) + UNREFERENCED_PARAMETER(sess_ctx); + + // Handle command invocation + switch (cmd_id) { + + case TA_FTPM_SUBMIT_COMMAND: { + return fTPM_Submit_Command(param_types, params); + } + + case TA_FTPM_EMULATE_PPI: { + return fTPM_Emulate_PPI(param_types, params); + } + + default: { + return TEE_ERROR_BAD_PARAMETERS; + } + } +} diff --git a/ta/ftpm/include/Wolf/TpmToWolfHash.h b/ta/ftpm/include/Wolf/TpmToWolfHash.h new file mode 100644 index 00000000000..4ce03528dd4 --- /dev/null +++ b/ta/ftpm/include/Wolf/TpmToWolfHash.h @@ -0,0 +1,199 @@ +/* Microsoft Reference Implementation for TPM 2.0 + * + * The copyright in this software is being made available under the BSD License, + * included below. This software may be subject to other third party and + * contributor rights, including patent rights, and no such rights are granted + * under this license. + * + * Copyright (c) Microsoft Corporation + * + * All rights reserved. + * + * BSD License + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * Redistributions of source code must retain the above copyright notice, this list + * of conditions and the following disclaimer. + * + * 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. + * + * 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. + */ + +//** Introduction +// +// This header file is used to 'splice' the wolfcrypt hash code into the TPM code. +// +#ifndef HASH_LIB_DEFINED +#define HASH_LIB_DEFINED + +#define HASH_LIB_WOLF + +#define HASH_ALIGNMENT RADIX_BYTES + +#ifndef WOLFSSL_USER_SETTINGS +#define WOLFSSL_USER_SETTINGS +#endif + +#if ALG_SHA384 || ALG_SHA512 +#define WOLFSSL_SHA512 +#endif + +#if ALG_SM3_256 +#undef ALG_SM3_256 +#define ALG_SM3_256 ALG_NO +//#error "SM3 is not available" +#endif + +#include +#include +#include + + +//*************************************************************** +//** Links to the wolfcrypt HASH code +//*************************************************************** + +// Redefine the internal name used for each of the hash state structures to the +// name used by the library. +// These defines need to be known in all parts of the TPM so that the structure +// sizes can be properly computed when needed. + +#define tpmHashStateSHA1_t wc_Sha +#define tpmHashStateSHA256_t wc_Sha256 +#define tpmHashStateSHA384_t wc_Sha512 +#define tpmHashStateSHA512_t wc_Sha512 + +#if ALG_SM3 +# error "The version of WolfCrypt used by this code does not support SM3" +#endif + +// The defines below are only needed when compiling CryptHash.c or CryptSmac.c. +// This isolation is primarily to avoid name space collision. However, if there +// is a real collision, it will likely show up when the linker tries to put things +// together. + +#ifdef _CRYPT_HASH_C_ + +typedef BYTE *PBYTE; +typedef const BYTE *PCBYTE; + +// Define the interface between CryptHash.c to the functions provided by the +// library. For each method, define the calling parameters of the method and then +// define how the method is invoked in CryptHash.c. +// +// All hashes are required to have the same calling sequence. If they don't, create +// a simple adaptation function that converts from the "standard" form of the call +// to the form used by the specific hash (and then send a nasty letter to the +// person who wrote the hash function for the library). +// +// The macro that calls the method also defines how the +// parameters get swizzled between the default form (in CryptHash.c)and the +// library form. +// +// Initialize the hash context +#define HASH_START_METHOD_DEF void (HASH_START_METHOD)(PANY_HASH_STATE state) +#define HASH_START(hashState) \ + ((hashState)->def->method.start)(&(hashState)->state); + +// Add data to the hash +#define HASH_DATA_METHOD_DEF \ + void (HASH_DATA_METHOD)(PANY_HASH_STATE state, \ + PCBYTE buffer, \ + size_t size) +#define HASH_DATA(hashState, dInSize, dIn) \ + ((hashState)->def->method.data)(&(hashState)->state, dIn, dInSize) + +// Finalize the hash and get the digest +#define HASH_END_METHOD_DEF \ + void (HASH_END_METHOD)(PANY_HASH_STATE state, BYTE *buffer) +#define HASH_END(hashState, buffer) \ + ((hashState)->def->method.end)(&(hashState)->state, buffer) + +// Copy the hash context +// Note: For import, export, and copy, memcpy() is used since there is no +// reformatting necessary between the internal and external forms. +#define HASH_STATE_COPY_METHOD_DEF \ + void (HASH_STATE_COPY_METHOD)(PANY_HASH_STATE to, \ + PCANY_HASH_STATE from, \ + size_t size) +#define HASH_STATE_COPY(hashStateOut, hashStateIn) \ + ((hashStateIn)->def->method.copy)(&(hashStateOut)->state, \ + &(hashStateIn)->state, \ + (hashStateIn)->def->contextSize) + +// Copy (with reformatting when necessary) an internal hash structure to an +// external blob +#define HASH_STATE_EXPORT_METHOD_DEF \ + void (HASH_STATE_EXPORT_METHOD)(BYTE *to, \ + PCANY_HASH_STATE from, \ + size_t size) +#define HASH_STATE_EXPORT(to, hashStateFrom) \ + ((hashStateFrom)->def->method.copyOut) \ + (&(((BYTE *)(to))[offsetof(HASH_STATE, state)]), \ + &(hashStateFrom)->state, \ + (hashStateFrom)->def->contextSize) + +// Copy from an external blob to an internal formate (with reformatting when +// necessary +#define HASH_STATE_IMPORT_METHOD_DEF \ + void (HASH_STATE_IMPORT_METHOD)(PANY_HASH_STATE to, \ + const BYTE *from, \ + size_t size) +#define HASH_STATE_IMPORT(hashStateTo, from) \ + ((hashStateTo)->def->method.copyIn) \ + (&(hashStateTo)->state, \ + &(((const BYTE *)(from))[offsetof(HASH_STATE, state)]),\ + (hashStateTo)->def->contextSize) + + +// Function aliases. The code in CryptHash.c uses the internal designation for the +// functions. These need to be translated to the function names of the library. +// Internal External +// Designation Designation +#define tpmHashStart_SHA1 wc_InitSha // external name of the + // initialization method +#define tpmHashData_SHA1 wc_ShaUpdate +#define tpmHashEnd_SHA1 wc_ShaFinal +#define tpmHashStateCopy_SHA1 memcpy +#define tpmHashStateExport_SHA1 memcpy +#define tpmHashStateImport_SHA1 memcpy +#define tpmHashStart_SHA256 wc_InitSha256 +#define tpmHashData_SHA256 wc_Sha256Update +#define tpmHashEnd_SHA256 wc_Sha256Final +#define tpmHashStateCopy_SHA256 memcpy +#define tpmHashStateExport_SHA256 memcpy +#define tpmHashStateImport_SHA256 memcpy +#define tpmHashStart_SHA384 wc_InitSha384 +#define tpmHashData_SHA384 wc_Sha384Update +#define tpmHashEnd_SHA384 wc_Sha384Final +#define tpmHashStateCopy_SHA384 memcpy +#define tpmHashStateExport_SHA384 memcpy +#define tpmHashStateImport_SHA384 memcpy +#define tpmHashStart_SHA512 wc_InitSha512 +#define tpmHashData_SHA512 wc_Sha512Update +#define tpmHashEnd_SHA512 wc_Sha512Final +#define tpmHashStateCopy_SHA512 memcpy +#define tpmHashStateExport_SHA512 memcpy +#define tpmHashStateImport_SHA512 memcpy + +#endif // _CRYPT_HASH_C_ + +#define LibHashInit() +// This definition would change if there were something to report +#define HashLibSimulationEnd() + +#endif // HASH_LIB_DEFINED diff --git a/ta/ftpm/include/Wolf/TpmToWolfMath.h b/ta/ftpm/include/Wolf/TpmToWolfMath.h new file mode 100644 index 00000000000..1543499ba9c --- /dev/null +++ b/ta/ftpm/include/Wolf/TpmToWolfMath.h @@ -0,0 +1,91 @@ +/* Microsoft Reference Implementation for TPM 2.0 + * + * The copyright in this software is being made available under the BSD License, + * included below. This software may be subject to other third party and + * contributor rights, including patent rights, and no such rights are granted + * under this license. + * + * Copyright (c) Microsoft Corporation + * + * All rights reserved. + * + * BSD License + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * Redistributions of source code must retain the above copyright notice, this list + * of conditions and the following disclaimer. + * + * 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. + * + * 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. + */ + +//** Introduction +// This file contains the structure definitions used for ECC in the LibTomCrypt +// version of the code. These definitions would change, based on the library. +// The ECC-related structures that cross the TPM interface are defined +// in TpmTypes.h +// + +#ifndef MATH_LIB_DEFINED +#define MATH_LIB_DEFINED + +#define MATH_LIB_WOLF + +#if ALG_ECC +#define HAVE_ECC +#endif + +#include +#include + +#define MP_VAR(name) \ + mp_int _##name; \ + mp_int *name = MpInitialize(&_##name); + +// Allocate a mp_int and initialize with the values in a mp_int* initializer +#define MP_INITIALIZED(name, initializer) \ + MP_VAR(name); \ + BnToWolf(name, initializer); + +#define POINT_CREATE(name, initializer) \ + ecc_point *name = EcPointInitialized(initializer); + +#define POINT_DELETE(name) \ + wc_ecc_del_point(name); \ + name = NULL; + +typedef ECC_CURVE_DATA bnCurve_t; + +typedef bnCurve_t *bigCurve; + +#define AccessCurveData(E) (E) + +#define CURVE_INITIALIZED(name, initializer) \ + bnCurve_t *name = (ECC_CURVE_DATA *)GetCurveData(initializer) + +#define CURVE_FREE(E) + +#include "TpmToWolfSupport_fp.h" + +#define WOLF_ENTER() + +#define WOLF_LEAVE() + +// This definition would change if there were something to report +#define MathLibSimulationEnd() + +#endif // MATH_LIB_DEFINED diff --git a/ta/ftpm/include/Wolf/TpmToWolfSym.h b/ta/ftpm/include/Wolf/TpmToWolfSym.h new file mode 100644 index 00000000000..0c042eb3521 --- /dev/null +++ b/ta/ftpm/include/Wolf/TpmToWolfSym.h @@ -0,0 +1,120 @@ +/* Microsoft Reference Implementation for TPM 2.0 + * + * The copyright in this software is being made available under the BSD License, + * included below. This software may be subject to other third party and + * contributor rights, including patent rights, and no such rights are granted + * under this license. + * + * Copyright (c) Microsoft Corporation + * + * All rights reserved. + * + * BSD License + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * Redistributions of source code must retain the above copyright notice, this list + * of conditions and the following disclaimer. + * + * 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. + * + * 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. + */ + +//** Introduction +// +// This header file is used to 'splice' the wolfcrypt library into the TPM code. + +#ifndef SYM_LIB_DEFINED +#define SYM_LIB_DEFINED + +#define SYM_LIB_WOLF + +#define SYM_ALIGNMENT RADIX_BYTES + +#include +#include + +//*************************************************************** +//** Links to the wolfCrypt AES code +//*************************************************************** +#if ALG_SM4 +#undef ALG_SM4 +#define ALG_SM4 ALG_NO +//#error "SM4 is not available" +#endif + +#if ALG_CAMELLIA +#undef ALG_CAMELLIA +#define ALG_CAMELLIA ALG_NO +//#error "Camellia is not available" +#endif + +// Define the order of parameters to the library functions that do block encryption +// and decryption. +typedef void(*TpmCryptSetSymKeyCall_t)( + void *keySchedule, + BYTE *out, + const BYTE *in + ); + +// The Crypt functions that call the block encryption function use the parameters +// in the order: +// 1) keySchedule +// 2) in buffer +// 3) out buffer +// Since wolfcrypt uses the order in encryptoCall_t above, need to swizzle the +// values to the order required by the library. +#define SWIZZLE(keySchedule, in, out) \ + (void *)(keySchedule), (BYTE *)(out), (const BYTE *)(in) + +// Macros to set up the encryption/decryption key schedules +// +// AES: +#define TpmCryptSetEncryptKeyAES(key, keySizeInBits, schedule) \ + wc_AesSetKeyDirect((tpmKeyScheduleAES *)(schedule), key, BITS_TO_BYTES(keySizeInBits), 0, AES_ENCRYPTION) +#define TpmCryptSetDecryptKeyAES(key, keySizeInBits, schedule) \ + wc_AesSetKeyDirect((tpmKeyScheduleAES *)(schedule), key, BITS_TO_BYTES(keySizeInBits), 0, AES_DECRYPTION) + +// TDES: +#define TpmCryptSetEncryptKeyTDES(key, keySizeInBits, schedule) \ + TDES_setup_encrypt_key((key), (keySizeInBits), (tpmKeyScheduleTDES *)(schedule)) +#define TpmCryptSetDecryptKeyTDES(key, keySizeInBits, schedule) \ + TDES_setup_decrypt_key((key), (keySizeInBits), (tpmKeyScheduleTDES *)(schedule)) + +// Macros to alias encryption calls to specific algorithms. This should be used +// sparingly. Currently, only used by CryptRand.c +// +// When using these calls, to call the AES block encryption code, the caller +// should use: +// TpmCryptEncryptAES(SWIZZLE(keySchedule, in, out)); +#define TpmCryptEncryptAES wc_AesEncryptDirect +#define TpmCryptDecryptAES wc_AesDecryptDirect +#define tpmKeyScheduleAES Aes + +#define TpmCryptEncryptTDES TDES_encrypt +#define TpmCryptDecryptTDES TDES_decrypt +#define tpmKeyScheduleTDES Des3 + +typedef union tpmCryptKeySchedule_t tpmCryptKeySchedule_t; + +#if ALG_TDES +#include "TpmToWolfDesSupport_fp.h" +#endif + +// This definition would change if there were something to report +#define SymLibSimulationEnd() + +#endif // SYM_LIB_DEFINED diff --git a/ta/ftpm/include/Wolf/user_settings.h b/ta/ftpm/include/Wolf/user_settings.h new file mode 100644 index 00000000000..de0dfd321f3 --- /dev/null +++ b/ta/ftpm/include/Wolf/user_settings.h @@ -0,0 +1,108 @@ +/* Microsoft Reference Implementation for TPM 2.0 + * + * The copyright in this software is being made available under the BSD License, + * included below. This software may be subject to other third party and + * contributor rights, including patent rights, and no such rights are granted + * under this license. + * + * Copyright (c) Microsoft Corporation + * + * All rights reserved. + * + * BSD License + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * Redistributions of source code must retain the above copyright notice, this list + * of conditions and the following disclaimer. + * + * 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. + * + * 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. + */ + + +/* TPM specific preprocessor flags for wolfcrypt */ + + +#ifndef WOLF_CRYPT_USER_SETTINGS_H +#define WOLF_CRYPT_USER_SETTINGS_H + +#include + +/* Remove the automatic setting of the default I/O functions EmbedSend() + and EmbedReceive(). */ +#define WOLFSSL_USER_IO + +/* Avoid naming conflicts */ +#define NO_OLD_WC_NAMES + +/* Use stack based fast math for all big integer math */ +#define USE_FAST_MATH +#define TFM_TIMING_RESISTANT + +/* Expose direct encryption functions */ +#define WOLFSSL_AES_DIRECT + +/* Enable/Disable algorithm support based on TPM implementation header */ +#if ALG_SHA256 + #define WOLFSSL_SHA256 +#endif +#if ALG_SHA384 || ALG_SHA512 + #define WOLFSSL_SHA384 + #define WOLFSSL_SHA512 +#endif +#if ALG_TDES + #define WOLFSSL_DES_ECB +#endif +#if ALG_RSA + /* Turn on RSA key generation functionality */ + #define WOLFSSL_KEY_GEN +#endif +#if ALG_ECC || defined(WOLFSSL_LIB) + #define HAVE_ECC + + /* Expose additional ECC primitives */ + #define WOLFSSL_PUBLIC_ECC_ADD_DBL + #define ECC_TIMING_RESISTANT + + /* Enables Shamir calc method */ + #define ECC_SHAMIR + + /* The TPM only needs low level ECC crypto */ + #define NO_ECC_SIGN + #define NO_ECC_VERIFY + #define NO_ECC_SECP + + #undef ECC_BN_P256 + #undef ECC_SM2_P256 + #undef ECC_BN_P638 + #define ECC_BN_P256 NO + #define ECC_SM2_P256 NO + #define ECC_BN_P638 NO + +#endif + +/* Disable explicit RSA. The TPM support for RSA is dependent only on TFM */ +#define NO_RSA +#define NO_RC4 +#define NO_ASN + +/* Enable debug wolf library check */ +//#define LIBRARY_COMPATIBILITY_CHECK + +#define WOLFSSL_ + +#endif // WOLF_CRYPT_USER_SETTINGS_H diff --git a/ta/ftpm/include/fTPM.h b/ta/ftpm/include/fTPM.h new file mode 100644 index 00000000000..6d6b1a0ff97 --- /dev/null +++ b/ta/ftpm/include/fTPM.h @@ -0,0 +1,106 @@ +/* Microsoft Reference Implementation for TPM 2.0 + * + * The copyright in this software is being made available under the BSD License, + * included below. This software may be subject to other third party and + * contributor rights, including patent rights, and no such rights are granted + * under this license. + * + * Copyright (c) Microsoft Corporation + * + * All rights reserved. + * + * BSD License + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * Redistributions of source code must retain the above copyright notice, this list + * of conditions and the following disclaimer. + * + * 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. + * + * 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 FTPM_TA_H +#define FTPM_TA_H + +#include + +/* This UUID is generated with uuidgen */ +#define TA_FTPM_UUID { 0xBC50D971, 0xD4C9, 0x42C4, \ + {0x82, 0xCB, 0x34, 0x3F, 0xB7, 0xF3, 0x78, 0x96}} + +/* The TAFs ID implemented in this TA */ +#define TA_FTPM_SUBMIT_COMMAND (0) +#define TA_FTPM_EMULATE_PPI (1) + +// +// These must match values from reference/TPM/include/TpmProfile.h +// +#define MAX_COMMAND_SIZE 4096 +#define MAX_RESPONSE_SIZE 4096 + +// +// Macro for intentionally unreferenced parameters +// +#define UNREFERENCED_PARAMETER(_Parameter_) (void)(_Parameter_) + +// +// Shorthand for TA functions taking uniform arg types +// +#define TA_ALL_PARAM_TYPE(a) TEE_PARAM_TYPES((a), (a), (a), (a)) + +// +// Used to extract size field from TPM command buffers +// +#define BYTE_ARRAY_TO_UINT32(b) (uint32_t)( ((b)[0] << 24) \ + + ((b)[1] << 16) \ + + ((b)[2] << 8 ) \ + + (b)[3]) +// +// Entrypoint for reference implemntation +// +extern void ExecuteCommand( + uint32_t requestSize, // IN: command buffer size + unsigned char *request, // IN: command buffer + uint32_t *responseSize, // OUT: response buffer size + unsigned char **response // OUT: response buffer + ); + +// +// External functions supporting TPM initialization +// +extern int _plat__NVEnable(void *platParameter); +extern int TPM_Manufacture(bool firstTime); +extern bool _plat__NvNeedsManufacture(void); +extern void _TPM_Init(void); +extern void _plat__Signal_PowerOn(void); +extern void _plat__NVDisable(void); +extern void _admin__SaveChipFlags(void); + +// +// External types/data supporting TPM initialization +// +typedef union { + uint32_t flags; + struct { + uint32_t Remanufacture : 1; // Perform a TPM_Remanufacture() on startup (SET by default) + uint32_t TpmStatePresent : 1; // Init TPM and NV with contents of TpmState and NVState on startup + uint32_t Reserved : 30; + } fields; +} TPM_CHIP_STATE; + +extern TPM_CHIP_STATE g_chipFlags; +#endif /* FTPM_TA_H */ \ No newline at end of file diff --git a/ta/ftpm/include/fTPM_event_log.h b/ta/ftpm/include/fTPM_event_log.h new file mode 100644 index 00000000000..18618acef82 --- /dev/null +++ b/ta/ftpm/include/fTPM_event_log.h @@ -0,0 +1,13 @@ +/* + * Copyright (c) 2021, Arm Limited. All rights reserved. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +#ifndef _FTPM_EVENT_LOG_ +#define _FTPM_EVENT_LOG_ + +bool process_eventlog(const unsigned char *const buf, const size_t log_size); +void dump_event_log(uint8_t *log_addr, size_t log_size); + +#endif /* _FTPM_EVENT_LOG_*/ diff --git a/ta/ftpm/include/fTPM_event_log_private.h b/ta/ftpm/include/fTPM_event_log_private.h new file mode 100644 index 00000000000..f972fc7f018 --- /dev/null +++ b/ta/ftpm/include/fTPM_event_log_private.h @@ -0,0 +1,269 @@ +/* + * Copyright (c) 2021, Arm Limited. All rights reserved. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +#ifndef _FTPM_EVENT_LOG_PRIVATE_H +#define _FTPM_EVENT_LOG_PRIVATE_H + +#include +#include + +#define TCG_STARTUP_LOCALITY_SIGNATURE "StartupLocality" + +/* Event types */ +#define EV_PREBOOT_CERT 0x00000000 +#define EV_POST_CODE 0x00000001 +#define EV_NO_ACTION 0x00000003 +#define EV_SEPARATOR 0x00000004 +#define EV_ACTION 0x00000005 +#define EV_S_CRTM_CONTENTS 0x00000007 +#define EV_S_CRTM_VERSION 0x00000008 +#define EV_CPU_MICROCODE 0x00000009 +#define EV_PLATFORM_CONFIG_FLAGS 0x0000000A +#define EV_TABLE_OF_DEVICES 0x0000000B +#define EV_COMPACT_HASH 0x0000000C +#define EV_NONHOST_CODE 0x0000000F +#define EV_NONHOST_CONFIG 0x00000010 +#define EV_NONHOST_INFO 0x00000011 +#define EV_OMIT_BOOT_DEVICE_EVENTS 0x00000012 + +/* + * Section 5.3 of TCG EFI Protocol Specification. Family 2.0. + * Level 00 Revision 00.13 + * March 30, 2016 + */ +#define HEADER_DIGEST_SIZE 20 + +/* + * Section 4.40 of Trusted Platform Module Library. Part 1. + * Level 00 Revision 01.38. September 29, 2016. + */ +#define TPM_RS_PW 0x40000009 +#define AUTH_SIZE 0x00000009 + +#define TPM_PCR_EXTEND 0x00000182 +#define TPM_ST_SESS 0x8002 + +#pragma pack(1) + +/* + * Log Header Entry Data + * Ref. Table 14 TCG_EfiSpecIdEventAlgorithmSize + * TCG PC Client Platform Firmware Profile 9.4.5.1 + */ + +typedef struct tcg_efi_spec_id_event_algorithm_size { + /* Algorithm ID (hashAlg) of the Hash used by BIOS */ + uint16_t algorithm_id; + /* The size of the digest produced by the implemented Hash algorithm */ + uint16_t digest_size; +} id_event_algorithm_size_t; + +/* + * TCG_EfiSpecIdEvent structure + * Ref. Table 15 TCG_EfiSpecIdEvent + * TCG PC Client Platform Firmware Profile 9.4.5.1 + */ + +typedef struct id_event_struct_header { + /* + * The NUL-terminated ASCII string "Spec ID Event03". + * SHALL be set to {0x53, 0x70, 0x65, 0x63, 0x20, 0x49, 0x44, + * 0x20, 0x45, 0x76, 0x65, 0x6e, 0x74, 0x30, 0x33, 0x00}. + */ + uint8_t signature[16]; + + /* + * The value for the Platform Class. + * The enumeration is defined in the TCG ACPI Specification Client + * Common Header. + */ + uint32_t platform_class; + + /* + * The PC Client Platform Profile Specification minor version number + * this BIOS supports. + * Any BIOS supporting this version (2.0) MUST set this value to 0x00. + */ + uint8_t spec_version_minor; + + /* + * The PC Client Platform Profile Specification major version number + * this BIOS supports. + * Any BIOS supporting this version (2.0) MUST set this value to 0x02. + */ + uint8_t spec_version_major; + + /* + * The PC Client Platform Profile Specification errata version number + * this BIOS supports. + * Any BIOS supporting this version (2.0) MUST set this value to 0x02. + */ + uint8_t spec_errata; + + /* + * Specifies the size of the UINTN fields used in various data + * structures used in this specification. + * 0x01 indicates UINT32 and 0x02 indicates UINT64. + */ + uint8_t uintn_size; + + /* + * The number of Hash algorithms in the digestSizes field. + * This field MUST be set to a value of 0x01 or greater. + */ + uint32_t number_of_algorithms; + + /* + * Each TCG_EfiSpecIdEventAlgorithmSize SHALL contain an algorithmId + * and digestSize for each hash algorithm used in the TCG_PCR_EVENT2 + * structure, the first of which is a Hash algorithmID and the second + * is the size of the respective digest. + */ + id_event_algorithm_size_t digest_size[]; /* number_of_algorithms */ +} id_event_struct_header_t; + +typedef struct id_event_struct_data { + /* + * Size in bytes of the VendorInfo field. + * Maximum value MUST be FFh bytes. + */ + uint8_t vendor_info_size; + + /* + * Provided for use by Platform Firmware implementer. The value might + * be used, for example, to provide more detailed information about the + * specific BIOS such as BIOS revision numbers, etc. The values within + * this field are not standardized and are implementer-specific. + * Platform-specific or -unique information MUST NOT be provided in + * this field. + * + */ + uint8_t vendor_info[]; /* [vendorInfoSize] */ +} id_event_struct_data_t; + +typedef struct tcg_efi_spec_id_event_struct { + id_event_struct_header_t struct_header; + id_event_struct_data_t struct_data; +} id_event_struct_t; + +typedef uint16_t TPM_ST; +typedef uint32_t TPM_CC; +typedef uint32_t TPM_HANDLE; +typedef TPM_HANDLE TPMI_DH_PCR; + +typedef struct { + TPM_ST tag; + uint32_t paramSize; + TPM_CC commandCode; +} TPM2_COMMAND_HEADER; + +typedef struct { + TPM2_COMMAND_HEADER Header; + TPMI_DH_PCR PcrHandle; + uint32_t AuthorizationSize; + TPMS_AUTH_COMMAND AuthSessionPcr; + TPML_DIGEST_VALUES DigestValues; +} TPM2_PCR_EXTEND_COMMAND; + +/* + * PCR Event Header + * TCG EFI Protocol Specification + * 5.3 Event Log Header + */ +typedef struct { + /* PCRIndex: + * The PCR Index to which this event is extended + */ + uint32_t pcr_index; + + /* EventType: + * SHALL be an EV_NO_ACTION event + */ + uint32_t event_type; + + /* SHALL be 20 Bytes of 0x00 */ + uint8_t digest[SHA1_DIGEST_SIZE]; + + /* The size of the event */ + uint32_t event_size; + + /* SHALL be a TCG_EfiSpecIdEvent */ + uint8_t event[]; /* [event_data_size] */ +} tcg_pcr_event_t; + +typedef struct { + tcg_pcr_event_t header; + id_event_struct_header_t struct_header; +} id_event_headers_t; + +/* TPMT_HA Structure */ +typedef struct { + /* Selector of the hash contained in the digest that implies + * the size of the digest + */ + uint16_t algorithm_id; /* AlgorithmId */ + + /* Digest, depends on AlgorithmId */ + uint8_t digest[]; /* Digest[] */ +} tpmt_ha; + +/* + * TPML_DIGEST_VALUES Structure + */ +typedef struct { + /* The number of digests in the list */ + uint32_t count; /* Count */ + + /* The list of tagged digests, as sent to the TPM as part of a + * TPM2_PCR_Extend or as received from a TPM2_PCR_Event command + */ + tpmt_ha digests[]; /* Digests[Count] */ /* FIXME: TPM_TA@TpmTypes.h */ +} tpml_digest_values; + +/* + * TCG_PCR_EVENT2 header + */ +typedef struct { + /* The PCR Index to which this event was extended */ + uint32_t pcr_index; /* PCRIndex */ + + /* Type of event */ + uint32_t event_type; /* EventType */ + + /* Digests: + * A counted list of tagged digests, which contain the digest of + * the event data (or external data) for all active PCR banks + */ + tpml_digest_values digests; /* Digests */ +} event2_header_t; + +typedef struct event2_data { + /* The size of the event data */ + uint32_t event_size; /* EventSize */ + + /* The data of the event */ + uint8_t event[]; /* Event[EventSize] */ +} event2_data_t; + +/* + * Startup Locality Event + * Ref. TCG PC Client Platform Firmware Profile 9.4.5.3 + */ +typedef struct { + /* + * The NUL-terminated ASCII string "StartupLocality" SHALL be + * set to {0x53 0x74 0x61 0x72 0x74 0x75 0x70 0x4C 0x6F 0x63 + * 0x61 0x6C 0x69 0x74 0x79 0x00} + */ + uint8_t signature[16]; + + /* The Locality Indicator which sent the TPM2_Startup command */ + uint8_t startup_locality; +} startup_locality_event_t; + +#pragma pack() + +#endif /* _FTPM_EVENT_LOG_PRIVATE_H */ diff --git a/ta/ftpm/include/fTPM_helpers.h b/ta/ftpm/include/fTPM_helpers.h new file mode 100644 index 00000000000..31bbaae8927 --- /dev/null +++ b/ta/ftpm/include/fTPM_helpers.h @@ -0,0 +1,15 @@ +/* + * Copyright (c) 2021, Arm Limited. All rights reserverd. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +#ifndef _FTPM_HELPERS_ +#define _FTPM_HELPERS_ + +#include + +uint16_t SwapBytes16(uint16_t Value); +uint32_t SwapBytes32(uint32_t Value); + +#endif /* _FTPM_HELPERS_ */ diff --git a/ta/ftpm/lib/sub.mk b/ta/ftpm/lib/sub.mk new file mode 100644 index 00000000000..79205e62625 --- /dev/null +++ b/ta/ftpm/lib/sub.mk @@ -0,0 +1,8 @@ +.PHONY: create_lib_symlinks +create_lib_symlinks: ./lib/tpm/tpm_symlink ./lib/wolf/wolf_symlink + +.PHONY: clean_lib_symlinks +clean_lib_symlinks: remove_tpm_symlink remove_wolf_symlink + +subdirs-y += wolf +subdirs-y += tpm \ No newline at end of file diff --git a/ta/ftpm/lib/tpm/sub.mk b/ta/ftpm/lib/tpm/sub.mk new file mode 100644 index 00000000000..68bdfe276c8 --- /dev/null +++ b/ta/ftpm/lib/tpm/sub.mk @@ -0,0 +1,274 @@ +FTPM_FLAGS = -DGCC -DUSE_WOLFCRYPT -DSIMULATION=NO -DVTPM -D_ARM_ +FTPM_DEBUG = -DCOMPILER_CHECKS=YES -DfTPMDebug -DRUNTIME_SIZE_CHECKS -DLIBRARY_COMPATIBILITY_CHECK +FTPM_RELEASE = -DCOMPILER_CHECKS=NO -DRUNTIME_SIZE_CHECKS=NO -DLIBRARY_COMPATIBILITY_CHECK=NO + +# +# The fTPM needs to overwrite some of the header files used in the reference implementation. The search order GCC +# uses is dependent on the order the '-I/include/path' arguments are passed in. This is depended on the optee_os build +# system which makes it brittle. Force including these files here will make sure the correct files are used first. +# + +FTPM_INCLUDES = -include ./reference/include/VendorString.h \ + -include ./reference/include/TpmProfile.h \ + -include ./platform/include/Platform.h + +# +# The TPM causes a few warnings when compiled with GCC which are not critical. +# + +FTPM_WARNING_SUPPRESS = -Wno-cast-align \ + -Wno-cast-function-type \ + -Wno-implicit-fallthrough \ + -Wno-missing-braces \ + -Wno-sign-compare \ + -Wno-suggest-attribute=noreturn \ + -Wno-switch-default + +cflags-y += $(FTPM_FLAGS) $(WOLF_SSL_FLAGS) $(FTPM_INCLUDES) $(FTPM_WARNING_SUPPRESS) + +ifeq ($(CFG_TA_DEBUG),y) +cflags-y += $(FTPM_DEBUG) +else +cflags-y += $(FTPM_RELEASE) +endif + +# +# For the purposes of this command the current working directory is the makefile root (/fTPM) folder, +# but the symlink will be created relative to THIS directory so the source requires an extra '../../'. +# +# Symlinks are needed since all build output is placed relative to the root. External libraries would result in +# binaries located outside the ouptut folder. +# +./lib/tpm/tpm_symlink: + @echo Checking symlink to the TPM folder: $(abspath $(TPM_ROOT)) + @if [ -L ./lib/tpm/tpm_symlink ] ; \ + then \ + echo Symlink already established ; \ + else \ + echo Establishing symlink. ; \ + ln -s ../../$(TPM_ROOT) ./lib/tpm/tpm_symlink; \ + fi + +.PHONY: remove_tpm_symlink +remove_tpm_symlink: + @if [ -e ./lib/tpm/tpm_symlink ] ; \ + then \ + unlink ./lib/tpm/tpm_symlink ; \ + echo Clearing symlink to the TPM folder: $(abspath $(TPM_ROOT)) ; \ + fi + +global-incdirs-y += tpm_symlink/TPMCmd/tpm/include +global-incdirs-y += tpm_symlink/TPMCmd/tpm/include/Ltc +global-incdirs-y += tpm_symlink/TPMCmd/tpm/include/prototypes +global-incdirs-y += tpm_symlink/TPMCmd/Platform/include + +# +# Generated in WSL using: +# find -name *.c | while read line; do echo XXXX$line; done | \ +# sed -e 's/XXXX.\//srcs-y += tpm_symlink\/TPMCmd\/tpm\/src\//g' +# This may need to be updated if there are any changes to the reference +# implementation. + +srcs-y += tpm_symlink/TPMCmd/tpm/src/X509/X509_ECC.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/X509/X509_RSA.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/X509/TpmASN1.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/X509/X509_spt.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/command/Attestation/CertifyX509.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/command/Attestation/GetCommandAuditDigest.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/command/Attestation/GetSessionAuditDigest.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/command/Attestation/Attest_spt.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/command/Attestation/Quote.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/command/Attestation/Certify.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/command/Attestation/CertifyCreation.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/command/Attestation/GetTime.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/command/Random/GetRandom.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/command/Random/StirRandom.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/command/NVStorage/NV_WriteLock.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/command/NVStorage/NV_ReadPublic.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/command/NVStorage/NV_spt.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/command/NVStorage/NV_Increment.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/command/NVStorage/NV_ChangeAuth.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/command/NVStorage/NV_UndefineSpaceSpecial.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/command/NVStorage/NV_SetBits.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/command/NVStorage/NV_Write.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/command/NVStorage/NV_GlobalWriteLock.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/command/NVStorage/NV_Read.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/command/NVStorage/NV_Extend.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/command/NVStorage/NV_Certify.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/command/NVStorage/NV_ReadLock.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/command/NVStorage/NV_DefineSpace.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/command/NVStorage/NV_UndefineSpace.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/command/HashHMAC/HashSequenceStart.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/command/HashHMAC/SequenceUpdate.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/command/HashHMAC/MAC_Start.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/command/HashHMAC/EventSequenceComplete.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/command/HashHMAC/HMAC_Start.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/command/HashHMAC/SequenceComplete.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/command/Vendor/Vendor_TCG_Test.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/command/Ecdaa/Commit.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/command/Startup/Startup.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/command/Startup/Shutdown.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/command/FieldUpgrade/FieldUpgradeData.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/command/FieldUpgrade/FirmwareRead.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/command/FieldUpgrade/FieldUpgradeStart.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/command/Capability/TestParms.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/command/Capability/GetCapability.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/command/ClockTimer/ACT_spt.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/command/ClockTimer/ClockRateAdjust.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/command/ClockTimer/ACT_SetTimeout.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/command/ClockTimer/ClockSet.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/command/ClockTimer/ReadClock.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/command/Session/PolicyRestart.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/command/Session/StartAuthSession.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/command/EA/PolicyDuplicationSelect.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/command/EA/PolicyPCR.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/command/EA/PolicySecret.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/command/EA/PolicyTicket.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/command/EA/PolicyTemplate.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/command/EA/PolicyNV.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/command/EA/PolicyGetDigest.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/command/EA/PolicyCpHash.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/command/EA/PolicyOR.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/command/EA/Policy_spt.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/command/EA/PolicyLocality.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/command/EA/PolicyAuthorize.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/command/EA/PolicyAuthorizeNV.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/command/EA/PolicyPassword.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/command/EA/PolicyCounterTimer.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/command/EA/PolicyAuthValue.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/command/EA/PolicySigned.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/command/EA/PolicyNameHash.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/command/EA/PolicyNvWritten.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/command/EA/PolicyPhysicalPresence.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/command/EA/PolicyCommandCode.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/command/Hierarchy/ChangePPS.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/command/Hierarchy/HierarchyControl.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/command/Hierarchy/HierarchyChangeAuth.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/command/Hierarchy/ChangeEPS.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/command/Hierarchy/ClearControl.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/command/Hierarchy/Clear.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/command/Hierarchy/SetPrimaryPolicy.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/command/Hierarchy/CreatePrimary.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/command/CommandAudit/SetCommandCodeAuditStatus.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/command/Object/Object_spt.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/command/Object/ReadPublic.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/command/Object/Load.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/command/Object/LoadExternal.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/command/Object/MakeCredential.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/command/Object/Unseal.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/command/Object/CreateLoaded.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/command/Object/ObjectChangeAuth.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/command/Object/ActivateCredential.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/command/Object/Create.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/command/AttachedComponent/AC_GetCapability.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/command/AttachedComponent/AC_spt.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/command/AttachedComponent/AC_Send.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/command/AttachedComponent/Policy_AC_SendSelect.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/command/Signature/VerifySignature.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/command/Signature/Sign.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/command/Duplication/Import.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/command/Duplication/Rewrap.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/command/Duplication/Duplicate.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/command/Symmetric/EncryptDecrypt2.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/command/Symmetric/EncryptDecrypt_spt.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/command/Symmetric/HMAC.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/command/Symmetric/Hash.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/command/Symmetric/EncryptDecrypt.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/command/Symmetric/MAC.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/command/Context/ContextSave.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/command/Context/FlushContext.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/command/Context/Context_spt.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/command/Context/ContextLoad.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/command/Context/EvictControl.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/command/PCR/PCR_Reset.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/command/PCR/PCR_Allocate.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/command/PCR/PCR_Extend.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/command/PCR/PCR_SetAuthValue.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/command/PCR/PCR_Event.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/command/PCR/PCR_SetAuthPolicy.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/command/PCR/PCR_Read.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/command/DA/DictionaryAttackParameters.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/command/DA/DictionaryAttackLockReset.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/command/Misc/PP_Commands.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/command/Misc/SetAlgorithmSet.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/command/Testing/GetTestResult.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/command/Testing/SelfTest.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/command/Testing/IncrementalSelfTest.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/command/Asymmetric/ECC_Parameters.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/command/Asymmetric/RSA_Encrypt.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/command/Asymmetric/ECDH_ZGen.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/command/Asymmetric/ECDH_KeyGen.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/command/Asymmetric/ZGen_2Phase.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/command/Asymmetric/ECC_Decrypt.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/command/Asymmetric/RSA_Decrypt.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/command/Asymmetric/EC_Ephemeral.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/command/Asymmetric/ECC_Encrypt.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/subsystem/DA.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/subsystem/NvDynamic.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/subsystem/Object.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/subsystem/PP.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/subsystem/Session.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/subsystem/NvReserved.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/subsystem/Hierarchy.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/subsystem/Time.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/subsystem/PCR.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/subsystem/CommandAudit.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/events/_TPM_Hash_Start.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/events/_TPM_Init.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/events/_TPM_Hash_Data.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/events/_TPM_Hash_End.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/crypt/CryptSmac.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/crypt/CryptEccData.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/crypt/CryptCmac.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/crypt/BnMath.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/crypt/CryptEccSignature.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/crypt/wolf/TpmToWolfDesSupport.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/crypt/wolf/TpmToWolfMath.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/crypt/wolf/TpmToWolfSupport.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/crypt/AlgorithmTests.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/crypt/CryptSelfTest.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/crypt/Ticket.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/crypt/CryptDes.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/crypt/BnMemory.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/crypt/CryptPrimeSieve.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/crypt/ossl/TpmToOsslSupport.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/crypt/ossl/TpmToOsslDesSupport.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/crypt/ossl/TpmToOsslMath.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/crypt/CryptEccKeyExchange.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/crypt/BnConvert.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/crypt/CryptRand.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/crypt/ltc/TpmToLtcSupport.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/crypt/ltc/TpmToLtcDesSupport.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/crypt/ltc/TpmToLtcMath.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/crypt/CryptEccMain.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/crypt/CryptSym.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/crypt/RsaKeyCache.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/crypt/CryptUtil.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/crypt/CryptEccCrypt.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/crypt/CryptRsa.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/crypt/CryptPrime.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/crypt/PrimeData.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/crypt/CryptHash.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/support/Marshal.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/support/MathOnByteBuffers.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/support/TableDrivenMarshal.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/support/PropertyCap.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/support/Locality.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/support/TableMarshalData.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/support/Memory.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/support/Response.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/support/ResponseCodeProcessing.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/support/Global.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/support/Power.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/support/AlgorithmCap.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/support/CommandCodeAttributes.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/support/Entity.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/support/Handle.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/support/TpmFail.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/support/TpmSizeChecks.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/support/Manufacture.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/support/IoBuffers.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/support/Bits.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/main/SessionProcess.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/main/CommandDispatcher.c +srcs-y += tpm_symlink/TPMCmd/tpm/src/main/ExecCommand.c diff --git a/ta/ftpm/lib/wolf/sub.mk b/ta/ftpm/lib/wolf/sub.mk new file mode 100644 index 00000000000..0a43f46e50b --- /dev/null +++ b/ta/ftpm/lib/wolf/sub.mk @@ -0,0 +1,58 @@ + +WOLF_SSL_FLAGS = -DSINGLE_THREADED \ + -DNO_WOLFSSL_CLIENT \ + -DNO_WOLFSSL_SERVER \ + -DOPENSSL_EXTRA \ + -DNO_FILESYSTEM \ + -DWOLFSSL_USER_SETTINGS \ + -DTIME_OVERRIDES \ + -DSTRING_USER \ + -DCTYPE_USER \ + -DCERTIFYX509_DEBUG=NO + +# +# Wolfcrypt has multiple unused functions, unfortunately the OPTEE build system can only turn off compiler flags for +# files in the same directory as the sub.mk file. It is not possible to place sub.mk files in the git submodules without +# creating a new fork of each submodule repo. To avoid spurious warnings these warnings are disabled here globally. +# + +WOLF_WARNING_SUPPRESS = -Wno-unused-function + +cflags-y += $(WOLF_SSL_FLAGS) $(WOLF_WARNING_SUPPRESS) + +# +# For the purposes of this command the current working directory is the makefile root (/fTPM) folder, +# but the symlink will be created relative to THIS directory so the source requires an extra '../../'. +# +./lib/wolf/wolf_symlink: + @echo Checking symlink to the WolfSSL folder: $(abspath $(WOLF_ROOT)) + @if [ -L ./lib/wolf/wolf_symlink ] ; \ + then \ + echo Symlink already established ; \ + else \ + echo Establishing symlink. ; \ + ln -s ../../$(WOLF_ROOT) ./lib/wolf/wolf_symlink; \ + fi + +.PHONY: remove_wolf_symlink +remove_wolf_symlink: + @if [ -e ./lib/wolf/wolf_symlink ] ; \ + then \ + unlink ./lib/wolf/wolf_symlink ; \ + echo Clearing symlink to the Wolf folder: $(abspath $(WOLF_ROOT)) ; \ + fi + +global-incdirs-y += wolf_symlink + +srcs-y += wolf_symlink/wolfcrypt/src/aes.c +srcs-y += wolf_symlink/wolfcrypt/src/asn.c +srcs-y += wolf_symlink/wolfcrypt/src/ecc.c +srcs-y += wolf_symlink/wolfcrypt/src/integer.c +srcs-y += wolf_symlink/wolfcrypt/src/memory.c +srcs-y += wolf_symlink/wolfcrypt/src/sha.c +srcs-y += wolf_symlink/wolfcrypt/src/sha256.c +srcs-y += wolf_symlink/wolfcrypt/src/sha512.c +srcs-y += wolf_symlink/wolfcrypt/src/tfm.c +srcs-y += wolf_symlink/wolfcrypt/src/wolfmath.c +srcs-y += wolf_symlink/wolfcrypt/src/des3.c +srcs-y += wolf_symlink/wolfcrypt/src/random.c diff --git a/ta/ftpm/platform/AdminPPI.c b/ta/ftpm/platform/AdminPPI.c new file mode 100644 index 00000000000..01d382d72a4 --- /dev/null +++ b/ta/ftpm/platform/AdminPPI.c @@ -0,0 +1,426 @@ +/* Microsoft Reference Implementation for TPM 2.0 + * + * The copyright in this software is being made available under the BSD License, + * included below. This software may be subject to other third party and + * contributor rights, including patent rights, and no such rights are granted + * under this license. + * + * Copyright (c) Microsoft Corporation + * + * All rights reserved. + * + * BSD License + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * Redistributions of source code must retain the above copyright notice, this list + * of conditions and the following disclaimer. + * + * 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. + * + * 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. + */ + +//**Introduction +// This file contains the emulated Physical Presence Interface. + +#include "assert.h" +#include "Admin.h" +#include "string.h" + +#include +#include + +#define TPM_CC_EmulatePPI 0x200001FF + +// +// Hand marshaling, unmarshaling, and maximally sized structures for EmulatePPI +// +#pragma pack (push, 1) +typedef struct { + TPM_ST tag; + UINT32 paramSize; + TPM_CC commandCode; +} TPM2_COMMAND_HEADER; + +typedef struct { + TPM_ST tag; + UINT32 paramSize; + TPM_RC responseCode; +} TPM2_RESPONSE_HEADER; + +typedef struct{ + UINT32 FunctionIndex; + UINT32 Op; +} EmulatePPI_In; + +typedef struct{ + UINT32 Result1; + UINT32 Result2; + UINT32 Result3; +} EmulatePPI_Out; + +typedef struct{ + TPM2_COMMAND_HEADER header; + EmulatePPI_In inputParameters; +} TPM2_EmulatePPI_cmd_t; + +typedef struct{ + TPM2_RESPONSE_HEADER header; + EmulatePPI_Out outputParameters; +} TPM2_EmulatePPI_res_t; +#pragma pack (pop) + +FTPM_PPI_STATE s_PPIState; + +extern int _plat__NvCommit(void); + +static void +ExecutePPICommand( + _In_ UINT32 FunctionIndex, + _In_ UINT32 Op, + _Out_ UINT32 *Result1, + _Out_ UINT32 *Result2, + _Out_ UINT32 *Result3 + ) +{ + UINT32 retVal1 = 0; + UINT32 retVal2 = 0; + UINT32 retVal3 = 0; + + _admin__RestorePPIState(); + + memset(Result1, 0, sizeof(UINT32)); + memset(Result2, 0, sizeof(UINT32)); + memset(Result3, 0, sizeof(UINT32)); + + switch (FunctionIndex) { + case FTPM_PPI_CMD_QUERY: + retVal1 = 0x1AB; // Per PPI 1.2 specification + break; + + case FTPM_PPI_CMD_VERSION: + retVal1 = FTPM_PPI_VERSION; // String "1.2" + break; + + case FTPM_PPI_CMD_SUBMIT_OP_REQ: + case FTPM_PPI_CMD_GET_PLATFORM_ACTION: + retVal1 = 2; // Reboot/General Failure + break; + + case FTPM_PPI_CMD_GET_PENDING_OP: + retVal1 = 0; // Success + retVal2 = s_PPIState.PendingPseudoOp; + break; + + case FTPM_PPI_CMD_RETURN_OP_RESP: + retVal1 = 0; // Success + retVal2 = s_PPIState.PseudoOpFromLastBoot; + retVal3 = s_PPIState.ReturnResponse; + break; + + case FTPM_PPI_CMD_SUBMIT_USER_LANG: + retVal1 = 3; // Not Implemented + break; + + case FTPM_PPI_CMD_SUBMIT_OP_REQ2: + switch (Op) { + case FTPM_PPI_OP_NOP: + case FTPM_PPI_OP_ENABLE: + case FTPM_PPI_OP_DISABLE: + case FTPM_PPI_OP_ACTIVATE: + case FTPM_PPI_OP_DEACTIVATE: + case FTPM_PPI_OP_CLEAR: // Causes Clear + case FTPM_PPI_OP_E_A: + case FTPM_PPI_OP_D_D: + case FTPM_PPI_OP_OWNERINSTALL_TRUE: + case FTPM_PPI_OP_OWNERINSTALL_FALSE: + case FTPM_PPI_OP_E_A_OI_TRUE: + case FTPM_PPI_OP_OI_FALSE_D_D: + case FTPM_PPI_OP_FIELD_UPGRADE: + case FTPM_PPI_OP_OPERATOR_AUTH: + case FTPM_PPI_OP_C_E_A: // Causes Clear + case FTPM_PPI_OP_SET_NO_PROV_FALSE: + case FTPM_PPI_OP_SET_NO_PROV_TRUE: + case FTPM_PPI_OP_SET_NO_MAINT_FALSE: + case FTPM_PPI_OP_SET_NO_MAINT_TRUE: + case FTPM_PPI_OP_E_A_C: // Causes Clear + case FTPM_PPI_OP_E_A_C_E_A: // Causes Clear + retVal1 = 0; // Success + s_PPIState.PendingPseudoOp = Op; + _admin__SavePPIState(); + break; + + case FTPM_PPI_OP_SET_NO_CLEAR_FALSE: + case FTPM_PPI_OP_SET_NO_CLEAR_TRUE: + default: + retVal1 = 1; // Not Implemented + break; + } + break; + + case FTPM_PPI_CMD_GET_USER_CONF: + switch (Op) { + case FTPM_PPI_OP_NOP: + case FTPM_PPI_OP_ENABLE: + case FTPM_PPI_OP_DISABLE: + case FTPM_PPI_OP_ACTIVATE: + case FTPM_PPI_OP_DEACTIVATE: + case FTPM_PPI_OP_E_A: + case FTPM_PPI_OP_D_D: + case FTPM_PPI_OP_OWNERINSTALL_TRUE: + case FTPM_PPI_OP_OWNERINSTALL_FALSE: + case FTPM_PPI_OP_E_A_OI_TRUE: + case FTPM_PPI_OP_OI_FALSE_D_D: + retVal1 = 4; // Allowed and PP user NOT required + break; + + case FTPM_PPI_OP_CLEAR: + case FTPM_PPI_OP_C_E_A: + case FTPM_PPI_OP_E_A_C: + case FTPM_PPI_OP_E_A_C_E_A: + retVal1 = 3; // Allowed and PP user required + break; + + default: + retVal1 = 0; // Not Implemented + break; + } + break; + + default: + break; + } + + memcpy(Result1, &retVal1, sizeof(UINT32)); + memcpy(Result2, &retVal2, sizeof(UINT32)); + memcpy(Result3, &retVal3, sizeof(UINT32)); +} + +static TPM2_EmulatePPI_res_t PPIResponse; + +#pragma warning(push) +#pragma warning(disable:28196) +// +// The fTPM TA (OpTEE) may receive, from the TrEE driver, a PPI request +// thru it's ACPI inteface rather than via the TPM_Emulate_PPI command +// we're used to. This function creates a well formes TPM_Emulate_PPI +// command and forwards the request on to _admin__PPICommand to handle. +// +// Return: +// 0 - Omproperly formatted PPI command. +// Otherwise - Return from _admin__PPICommand +// +int +_admin__PPIRequest( + UINT32 CommandSize, + __in_ecount(CommandSize) UINT8 *CommandBuffer, + UINT32 *ResponseSize, + __deref_out_ecount(*ResponseSize) UINT8 **ResponseBuffer + ) +{ + TPM2_EmulatePPI_cmd_t cmd; + TPM2_EmulatePPI_res_t rsp; + TPM2_EmulatePPI_res_t *rspPtr = &rsp; + UINT32 rspLen = sizeof(TPM2_EmulatePPI_res_t); + UINT8 *CmdBuffer; + + // Drop request if CommandSize is invalid + if (CommandSize < sizeof(UINT32)) { + return 0; + } + + CmdBuffer = CommandBuffer; + + cmd.header.tag = __builtin_bswap16(TPM_ST_NO_SESSIONS); + cmd.header.paramSize = __builtin_bswap32(sizeof(TPM2_EmulatePPI_cmd_t)); + cmd.header.commandCode = __builtin_bswap32(TPM_CC_EmulatePPI); + + cmd.inputParameters.FunctionIndex = BYTE_ARRAY_TO_UINT32(CmdBuffer); + CmdBuffer += sizeof(UINT32); + CommandSize -= sizeof(UINT32); + + // Parameter checking is done in _admin__PPICommand but we still need + // to sanity check the size field so as not to overrun CommandBuffer. + if (CommandSize > 0) { + + if (CommandSize < sizeof(UINT32)) + return 0; + + cmd.inputParameters.Op = BYTE_ARRAY_TO_UINT32(CmdBuffer); + } + + if (!_admin__PPICommand(sizeof(TPM2_EmulatePPI_cmd_t), + (UINT8 *)&cmd, + &rspLen, + (UINT8**)&rspPtr)) { + return 0; + } + + memcpy(*ResponseBuffer, &(rsp.outputParameters.Result1), (rspLen - sizeof(TPM2_RESPONSE_HEADER))); + *ResponseSize = (rspLen - sizeof(TPM2_RESPONSE_HEADER)); + return 1; +} + +// +// Return: +// 1 - Command has been consumed +// 0 - Not a properly formated PPI command, caller should pass through to TPM +// +int +_admin__PPICommand( + UINT32 CommandSize, + __in_ecount(CommandSize) UINT8 *CommandBuffer, + UINT32 *ResponseSize, + __deref_out_ecount(*ResponseSize) UINT8 **ResponseBuffer +) +{ + TPM2_EmulatePPI_cmd_t cmd; + UINT8 *CmdBuffer; + UINT32 FunctionIndex; + UINT32 Op; + UINT32 NumberResults = 0; + UINT16 Tag; + + memset(&PPIResponse, 0, sizeof(PPIResponse)); + memset(&cmd, 0, sizeof(cmd)); + + CmdBuffer = CommandBuffer; + + if (CommandSize < sizeof(TPM2_COMMAND_HEADER)) { + PPIResponse.header.responseCode = TPM_RC_COMMAND_SIZE; + goto Exit; + } + + cmd.header.tag = BYTE_ARRAY_TO_UINT16(CmdBuffer); + CmdBuffer += sizeof(UINT16); + CommandSize -= sizeof(UINT16); + + cmd.header.paramSize = BYTE_ARRAY_TO_UINT32(CmdBuffer); + CmdBuffer += sizeof(UINT32); + CommandSize -= sizeof(UINT32); + + cmd.header.commandCode = BYTE_ARRAY_TO_UINT32(CmdBuffer); + CmdBuffer += sizeof(UINT32); + CommandSize -= sizeof(UINT32); + + // + // First check that this must be the command we want to execute + // + if (cmd.header.commandCode != TPM_CC_EmulatePPI) { + return 0; + } + + // + // Must not be a session + // + if (cmd.header.tag != TPM_ST_NO_SESSIONS) { + PPIResponse.header.responseCode = TPM_RC_BAD_TAG; + goto Exit; + } + + // + // Must have enough command space left + // + if (cmd.header.paramSize < CommandSize) { + PPIResponse.header.responseCode = TPM_RC_COMMAND_SIZE; + goto Exit; + } + + if (CommandSize < sizeof(UINT32)) { + PPIResponse.header.responseCode = TPM_RC_COMMAND_SIZE; + goto Exit; + } + + FunctionIndex = BYTE_ARRAY_TO_UINT32(CmdBuffer); + CmdBuffer += sizeof(UINT32); + CommandSize -= sizeof(UINT32); + + switch (FunctionIndex) { + case FTPM_PPI_CMD_QUERY: + case FTPM_PPI_CMD_VERSION: + case FTPM_PPI_CMD_SUBMIT_OP_REQ: + case FTPM_PPI_CMD_GET_PLATFORM_ACTION: + case FTPM_PPI_CMD_SUBMIT_USER_LANG: + NumberResults = 1; + Op = 0; + break; + + case FTPM_PPI_CMD_GET_PENDING_OP: + NumberResults = 2; + Op = 0; + break; + + case FTPM_PPI_CMD_RETURN_OP_RESP: + NumberResults = 3; + Op = 0; + break; + + case FTPM_PPI_CMD_SUBMIT_OP_REQ2: + case FTPM_PPI_CMD_GET_USER_CONF: + NumberResults = 1; + + if (CommandSize < sizeof(UINT32)) { + PPIResponse.header.responseCode = TPM_RC_COMMAND_SIZE; + goto Exit; + } + + Op = BYTE_ARRAY_TO_UINT32(CmdBuffer); + CmdBuffer += sizeof(UINT32); + CommandSize -= sizeof(UINT32); + break; + + default: + NumberResults = 0; + PPIResponse.header.responseCode = TPM_RC_FAILURE; + goto Exit; + } + + + ExecutePPICommand(FunctionIndex, + Op, +#pragma warning (push) +#pragma warning (disable:4366) // The result of unary '&' may be unaligned + &PPIResponse.outputParameters.Result1, + &PPIResponse.outputParameters.Result2, + &PPIResponse.outputParameters.Result3); +#pragma warning (pop) + + PPIResponse.header.responseCode = TPM_RC_SUCCESS; + +Exit: + if (PPIResponse.header.responseCode != TPM_RC_SUCCESS) { + NumberResults = 0; + } + + *ResponseSize = sizeof(TPM2_RESPONSE_HEADER) + (NumberResults * sizeof(UINT32)); + + // + // Fill in tag, and size + // + Tag = TPM_ST_NO_SESSIONS; + PPIResponse.header.tag = BYTE_ARRAY_TO_UINT16((BYTE *)&Tag); + PPIResponse.header.paramSize = BYTE_ARRAY_TO_UINT32((BYTE *)ResponseSize); + PPIResponse.header.responseCode = BYTE_ARRAY_TO_UINT32((BYTE *)&PPIResponse.header.responseCode); + + // + // Results are in host byte order + // + memcpy(*ResponseBuffer, &PPIResponse, (sizeof(PPIResponse) < *ResponseSize) ? sizeof(PPIResponse) : *ResponseSize); + + return 1; +} +#pragma warning(pop) + diff --git a/ta/ftpm/platform/Cancel.c b/ta/ftpm/platform/Cancel.c new file mode 100644 index 00000000000..304a0703e14 --- /dev/null +++ b/ta/ftpm/platform/Cancel.c @@ -0,0 +1,80 @@ +/* Microsoft Reference Implementation for TPM 2.0 + * + * The copyright in this software is being made available under the BSD License, + * included below. This software may be subject to other third party and + * contributor rights, including patent rights, and no such rights are granted + * under this license. + * + * Copyright (c) Microsoft Corporation + * + * All rights reserved. + * + * BSD License + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * Redistributions of source code must retain the above copyright notice, this list + * of conditions and the following disclaimer. + * + * 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. + * + * 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. + */ +//** Description +// +// This module simulates the cancel pins on the TPM. +// +//** Includes, Typedefs, Structures, and Defines +#include "PlatformData.h" +#include "Platform_fp.h" + +//** Functions + +//***_plat__IsCanceled() +// Check if the cancel flag is set +// return type: BOOL +// TRUE(1) if cancel flag is set +// FALSE(0) if cancel flag is not set +LIB_EXPORT int +_plat__IsCanceled( + void + ) +{ + // return cancel flag + return s_isCanceled; +} + +//***_plat__SetCancel() + +// Set cancel flag. +LIB_EXPORT void +_plat__SetCancel( + void + ) +{ + s_isCanceled = TRUE; + return; +} + +//***_plat__ClearCancel() +// Clear cancel flag +LIB_EXPORT void +_plat__ClearCancel( + void + ) +{ + s_isCanceled = FALSE; + return; +} \ No newline at end of file diff --git a/ta/ftpm/platform/Clock.c b/ta/ftpm/platform/Clock.c new file mode 100644 index 00000000000..5bfd5b7a4a7 --- /dev/null +++ b/ta/ftpm/platform/Clock.c @@ -0,0 +1,302 @@ +/* Microsoft Reference Implementation for TPM 2.0 + * + * The copyright in this software is being made available under the BSD License, + * included below. This software may be subject to other third party and + * contributor rights, including patent rights, and no such rights are granted + * under this license. + * + * Copyright (c) Microsoft Corporation + * + * All rights reserved. + * + * BSD License + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * Redistributions of source code must retain the above copyright notice, this list + * of conditions and the following disclaimer. + * + * 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. + * + * 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. + */ +//** Description +// +// This file contains the routines that are used by the simulator to mimic +// a hardware clock on a TPM. +// +// In this implementation, all the time values are measured in millisecond. +// However, the precision of the clock functions may be implementation dependent. + +//** Includes and Data Definitions +#include "PlatformData.h" +#include "Platform_fp.h" +#include "TpmFail_fp.h" +#include +#include + +//** Simulator Functions +//*** Introduction +// This set of functions is intended to be called by the simulator environment in +// order to simulate hardware events. + +//***_plat__TimerReset() +// This function sets current system clock time as t0 for counting TPM time. +// This function is called at a power on event to reset the clock. When the clock +// is reset, the indication that the clock was stopped is also set. +LIB_EXPORT void +_plat__TimerReset( + void + ) +{ +TEE_Result Result; + TEE_Time Time = { 0 }; + + // Reset our TA persistent time, this affects all instances. + Result = TEE_SetTAPersistentTime(&Time); + + // Nothing we can do on failure here. + assert(Result == TEE_SUCCESS); + + s_adjustRate = 0; + s_lastSystemTime = 0; + s_tpmTime = 0; + s_adjustRate = CLOCK_NOMINAL; + s_timerReset = TRUE; + s_timerStopped = TRUE; + + return; +} + +//*** _plat__TimerRestart() +// This function should be called in order to simulate the restart of the timer +// should it be stopped while power is still applied. +LIB_EXPORT void +_plat__TimerRestart( + void + ) +{ + s_timerStopped = TRUE; + return; +} + +//** Functions Used by TPM +//*** Introduction +// These functions are called by the TPM code. They should be replaced by +// appropriated hardware functions. + +#include +TEE_Time debugTime; + +//*** _plat__RealTime() +// This is another, probably futile, attempt to define a portable function +// that will return a 64-bit clock value that has mSec resolution. +uint64_t +_plat__RealTime( + void +) +{ + TEE_Result Result; + TEE_Time Time; + uint64_t Elapsed, Temp; + + Result = TEE_GetTAPersistentTime(&Time); + + // Error conditions from GetTime may be resolved with a clock reset + if ((Result == TEE_ERROR_TIME_NOT_SET) || + (Result == TEE_ERROR_TIME_NEEDS_RESET)) { + // + // REVISIT: Since error conditions from get time may be resolved + // by resetting time. Determine if, when this happens, we see + // an issue with timing in the reference implementaiton. + // + _plat__TimerReset(); + + Result = TEE_GetTAPersistentTime(&Time); + // If the reset didn't resolve the error condision, give up. + assert(Result == TEE_SUCCESS); + } + assert(Result == TEE_SUCCESS); + + Elapsed = ((Time.seconds * 1000) + (Time.millis)); + + return Elapsed; +} + +//***_plat__TimerRead() +// This function provides access to the tick timer of the platform. The TPM code +// uses this value to drive the TPM Clock. +// +// The tick timer is supposed to run when power is applied to the device. This timer +// should not be reset by time events including _TPM_Init. It should only be reset +// when TPM power is re-applied. +// +// If the TPM is run in a protected environment, that environment may provide the +// tick time to the TPM as long as the time provided by the environment is not +// allowed to go backwards. If the time provided by the system can go backwards +// during a power discontinuity, then the _plat__Signal_PowerOn should call +// _plat__TimerReset(). +LIB_EXPORT uint64_t +_plat__TimerRead( + void + ) +{ +#ifdef HARDWARE_CLOCK +#error "need a defintion for reading the hardware clock" + return HARDWARE_CLOCK +#else + clock64_t timeDiff; + clock64_t adjustedTimeDiff; + clock64_t timeNow; + clock64_t readjustedTimeDiff; + + // This produces a timeNow that is basically locked to the system clock. + timeNow = _plat__RealTime(); + + // if this hasn't been initialized, initialize it + if(s_lastSystemTime == 0) + { + s_lastSystemTime = timeNow; + TEE_GetSystemTime(&debugTime); + s_lastReportedTime = 0; + s_realTimePrevious = 0; + } + // The system time can bounce around and that's OK as long as we don't allow + // time to go backwards. When the time does appear to go backwards, set + // lastSystemTime to be the new value and then update the reported time. + if(timeNow < s_lastReportedTime) + s_lastSystemTime = timeNow; + s_lastReportedTime = s_lastReportedTime + timeNow - s_lastSystemTime; + s_lastSystemTime = timeNow; + timeNow = s_lastReportedTime; + + // The code above produces a timeNow that is similar to the value returned + // by Clock(). The difference is that timeNow does not max out, and it is + // at a ms. rate rather than at a CLOCKS_PER_SEC rate. The code below + // uses that value and does the rate adjustment on the time value. + // If there is no difference in time, then skip all the computations + if(s_realTimePrevious >= timeNow) + return s_tpmTime; + // Compute the amount of time since the last update of the system clock + timeDiff = timeNow - s_realTimePrevious; + + // Do the time rate adjustment and conversion from CLOCKS_PER_SEC to mSec + adjustedTimeDiff = (timeDiff * CLOCK_NOMINAL) / ((uint64_t)s_adjustRate); + + // update the TPM time with the adjusted timeDiff + s_tpmTime += (clock64_t)adjustedTimeDiff; + + // Might have some rounding error that would loose CLOCKS. See what is not + // being used. As mentioned above, this could result in putting back more than + // is taken out. Here, we are trying to recreate timeDiff. + readjustedTimeDiff = (adjustedTimeDiff * (uint64_t)s_adjustRate ) + / CLOCK_NOMINAL; + + // adjusted is now converted back to being the amount we should advance the + // previous sampled time. It should always be less than or equal to timeDiff. + // That is, we could not have use more time than we started with. + s_realTimePrevious = s_realTimePrevious + readjustedTimeDiff; + +#ifdef DEBUGGING_TIME + // Put this in so that TPM time will pass much faster than real time when + // doing debug. + // A value of 1000 for DEBUG_TIME_MULTIPLER will make each ms into a second + // A good value might be 100 + return (s_tpmTime * DEBUG_TIME_MULTIPLIER); +#endif + return s_tpmTime; +#endif +} + + + +//*** _plat__TimerWasReset() +// This function is used to interrogate the flag indicating if the tick timer has +// been reset. +// +// If the resetFlag parameter is SET, then the flag will be CLEAR before the +// function returns. +LIB_EXPORT BOOL +_plat__TimerWasReset( + void + ) +{ + BOOL retVal = s_timerReset; + s_timerReset = FALSE; + return retVal; +} + +//*** _plat__TimerWasStopped() +// This function is used to interrogate the flag indicating if the tick timer has +// been stopped. If so, this is typically a reason to roll the nonce. +// +// This function will CLEAR the s_timerStopped flag before returning. This provides +// functionality that is similar to status register that is cleared when read. This +// is the model used here because it is the one that has the most impact on the TPM +// code as the flag can only be accessed by one entity in the TPM. Any other +// implementation of the hardware can be made to look like a read-once register. +LIB_EXPORT BOOL +_plat__TimerWasStopped( + void + ) +{ + BOOL retVal = s_timerStopped; + s_timerStopped = FALSE; + return retVal; +} + +//***_plat__ClockAdjustRate() +// Adjust the clock rate +LIB_EXPORT void +_plat__ClockAdjustRate( + int adjust // IN: the adjust number. It could be positive + // or negative + ) +{ + // We expect the caller should only use a fixed set of constant values to + // adjust the rate + switch(adjust) + { + case CLOCK_ADJUST_COARSE: + s_adjustRate += CLOCK_ADJUST_COARSE; + break; + case -CLOCK_ADJUST_COARSE: + s_adjustRate -= CLOCK_ADJUST_COARSE; + break; + case CLOCK_ADJUST_MEDIUM: + s_adjustRate += CLOCK_ADJUST_MEDIUM; + break; + case -CLOCK_ADJUST_MEDIUM: + s_adjustRate -= CLOCK_ADJUST_MEDIUM; + break; + case CLOCK_ADJUST_FINE: + s_adjustRate += CLOCK_ADJUST_FINE; + break; + case -CLOCK_ADJUST_FINE: + s_adjustRate -= CLOCK_ADJUST_FINE; + break; + default: + // ignore any other values; + break; + } + + if(s_adjustRate > (CLOCK_NOMINAL + CLOCK_ADJUST_LIMIT)) + s_adjustRate = CLOCK_NOMINAL + CLOCK_ADJUST_LIMIT; + if(s_adjustRate < (CLOCK_NOMINAL - CLOCK_ADJUST_LIMIT)) + s_adjustRate = CLOCK_NOMINAL - CLOCK_ADJUST_LIMIT; + + return; +} + diff --git a/ta/ftpm/platform/EPS.c b/ta/ftpm/platform/EPS.c new file mode 100644 index 00000000000..75d694d36c6 --- /dev/null +++ b/ta/ftpm/platform/EPS.c @@ -0,0 +1,90 @@ +/* Microsoft Reference Implementation for TPM 2.0 + * + * The copyright in this software is being made available under the BSD License, + * included below. This software may be subject to other third party and + * contributor rights, including patent rights, and no such rights are granted + * under this license. + * + * Copyright (c) Microsoft Corporation + * + * All rights reserved. + * + * BSD License + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * Redistributions of source code must retain the above copyright notice, this list + * of conditions and the following disclaimer. + * + * 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. + * + * 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. + */ + +// +// Platform Endorsement Primary Seed +// + +#include "TpmError.h" +#include "Admin.h" + +#include +#include + +#define TEE_EPS_SIZE (256/2) // From TPM2B_RSA_TEST_PRIME in Hierarchy.c + +void +_plat__GetEPS(UINT16 Size, uint8_t *EndorsementSeed) +{ + TEE_Result Result = TEE_ERROR_ITEM_NOT_FOUND; + uint8_t EPS[TEE_EPS_SIZE] = { 0 }; + size_t EPSLen; + + IMSG("Size=%" PRIu16 "",Size); + IMSG("EPS=%d",TEE_EPS_SIZE); + + pAssert(Size <= (TEE_EPS_SIZE)); + + Result = TEE_GetPropertyAsBinaryBlock(TEE_PROPSET_CURRENT_TA, + "com.microsoft.ta.endorsementSeed", + EPS, + &EPSLen); + + if ((EPSLen < Size) || (Result != TEE_SUCCESS)) { + // We failed to access the property. We can't continue without it + // and we can't just fail to manufacture, so randomize EPS and + // continue. If necessary, fTPM TA storage can be cleared, or the + // TA updated, and we can trigger remanufacture and try again. + _plat__GetEntropy(EndorsementSeed, TEE_EPS_SIZE); + return; + } + + memcpy(EndorsementSeed, EPS, Size); + +#ifdef fTPMDebug + { + uint32_t x; + uint8_t *seed = EndorsementSeed; + DMSG("TEE_GetProperty 0x%x, seedLen 0x%x\n", Result, Size); + for (x = 0; x < Size; x = x + 8) { + DMSG(" seed(%2.2d): %2.2x,%2.2x,%2.2x,%2.2x,%2.2x,%2.2x,%2.2x,%2.2x\n", x, + seed[x + 0], seed[x + 1], seed[x + 2], seed[x + 3], + seed[x + 4], seed[x + 5], seed[x + 6], seed[x + 7]); + } + } +#endif + + return; +} diff --git a/ta/ftpm/platform/Entropy.c b/ta/ftpm/platform/Entropy.c new file mode 100644 index 00000000000..3ca2fede785 --- /dev/null +++ b/ta/ftpm/platform/Entropy.c @@ -0,0 +1,128 @@ +/* Microsoft Reference Implementation for TPM 2.0 + * + * The copyright in this software is being made available under the BSD License, + * included below. This software may be subject to other third party and + * contributor rights, including patent rights, and no such rights are granted + * under this license. + * + * Copyright (c) Microsoft Corporation + * + * All rights reserved. + * + * BSD License + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * Redistributions of source code must retain the above copyright notice, this list + * of conditions and the following disclaimer. + * + * 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. + * + * 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. + */ +//** Includes and Local Values + +#define _CRT_RAND_S +#include +#include +#include "PlatformData.h" +#include "Platform_fp.h" +#include + +#include + +#ifdef _MSC_VER +#include +#else +#include +#endif + +// This is the last 32-bits of hardware entropy produced. We have to check to +// see that two consecutive 32-bit values are not the same because +// (according to FIPS 140-2, annex C +// +// 1. If each call to a RNG produces blocks of n bits (where n > 15), the first +// n-bit block generated after power-up, initialization, or reset shall not be +// used, but shall be saved for comparison with the next n-bit block to be +// generated. Each subsequent generation of an n-bit block shall be compared with +// the previously generated block. The test shall fail if any two compared n-bit +// blocks are equal. +extern uint32_t lastEntropy; + +//** Functions + +//*** rand32() +// Local function to get a 32-bit random number +static uint32_t +rand32( + void +) +{ + + uint32_t rndNum; + TEE_GenerateRandom((void *)(&rndNum), sizeof(uint32_t)); + return rndNum; +} + + +//** _plat__GetEntropy() +// This function is used to get available hardware entropy. In a hardware +// implementation of this function, there would be no call to the system +// to get entropy. +// return type: int32_t +// < 0 hardware failure of the entropy generator, this is sticky +// >= 0 the returned amount of entropy (bytes) +// +LIB_EXPORT int32_t +_plat__GetEntropy( + unsigned char *entropy, // output buffer + uint32_t amount // amount requested +) +{ + uint32_t rndNum; + int32_t ret; + + if(amount == 0) + { + lastEntropy = rand32(); + ret = 0; + } + else + { + rndNum = rand32(); + if(rndNum == lastEntropy) + { + ret = -1; + } + else + { + lastEntropy = rndNum; + // Each process will have its random number generator initialized according + // to the process id and the initialization time. This is not a lot of + // entropy so, to add a bit more, XOR the current time value into the + // returned entropy value. + // NOTE: the reason for including the time here rather than have it in + // in the value assigned to lastEntropy is that rand() could be broken and + // using the time would in the lastEntropy value would hide this. + rndNum ^= (uint32_t)_plat__RealTime(); + + // Only provide entropy 32 bits at a time to test the ability + // of the caller to deal with partial results. + ret = MIN(amount, sizeof(rndNum)); + memcpy(entropy, &rndNum, ret); + } + } + return ret; +} \ No newline at end of file diff --git a/ta/ftpm/platform/EventLogPrint.c b/ta/ftpm/platform/EventLogPrint.c new file mode 100644 index 00000000000..9c95c30afea --- /dev/null +++ b/ta/ftpm/platform/EventLogPrint.c @@ -0,0 +1,283 @@ +/* + * Copyright (c) 2021, Arm Limited. All rights reserved. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +#ifdef EVENT_LOG_LEVEL +#undef EVENT_LOG_LEVEL +#endif + +#ifdef LOG_LEVEL +#undef LOG_LEVEL +#endif + +#define EVENT_LOG_LEVEL 1 +#define LOG_LEVEL 1 + +#if LOG_LEVEL >= EVENT_LOG_LEVEL + +/* + * Print TCG_EfiSpecIDEventStruct + * + * @param[in/out] log_addr Pointer to Event Log + * @param[in/out] log_size Pointer to Event Log size + */ +static void id_event_print(uint8_t **log_addr, size_t *log_size) +{ + unsigned int i; + uint8_t info_size, *info_size_ptr; + void *ptr = *log_addr; + id_event_headers_t *event = (id_event_headers_t *)ptr; + id_event_algorithm_size_t *alg_ptr; + uint32_t event_size, number_of_algorithms; + size_t digest_len; + const uint8_t *end_ptr = *log_addr + *log_size; + char str_buf[1024]; + + assert(*log_size >= sizeof(id_event_headers_t)); + + /* The fields of the event log header are defined to be PCRIndex of 0, + * EventType of EV_NO_ACTION, Digest of 20 bytes of 0, and + * Event content defined as TCG_EfiSpecIDEventStruct. + */ + MSG("TCG_EfiSpecIDEvent:\n"); + MSG(" PCRIndex : %u\n", event->header.pcr_index); + MSG(" EventType : %u\n", event->header.event_type); + str_buf[0] = 0; + snprintf(str_buf, 1024, " Digest :"); + for (i = 0U; i < sizeof(event->header.digest); ++i) { + uint8_t val = event->header.digest[i]; + + snprintf(str_buf, 1024, "%s %02x", str_buf, val); + if ((i & U(0xF)) == 0U) { + MSG("%s\n", str_buf); + str_buf[0] = 0; + snprintf(str_buf, 1024, "\t\t\t :"); + } + } + MSG("%s\n", str_buf); + str_buf[0] = 0; + + /* EventSize */ + event_size = event->header.event_size; + MSG(" EventSize : %u\n", event_size); + + MSG(" Signature : %s\n", + event->struct_header.signature); + MSG(" PlatformClass : %u\n", + event->struct_header.platform_class); + MSG(" SpecVersion : %u.%u.%u\n", + event->struct_header.spec_version_major, + event->struct_header.spec_version_minor, + event->struct_header.spec_errata); + MSG(" UintnSize : %u\n", + event->struct_header.uintn_size); + + /* NumberOfAlgorithms */ + number_of_algorithms = event->struct_header.number_of_algorithms; + MSG(" NumberOfAlgorithms : %u\n", number_of_algorithms); + + /* Address of DigestSizes[] */ + alg_ptr = event->struct_header.digest_size; + + /* Size of DigestSizes[] */ + digest_len = number_of_algorithms * sizeof(id_event_algorithm_size_t); + + assert(((uint8_t *)alg_ptr + digest_len) <= end_ptr); + + MSG(" DigestSizes :\n"); + for (i = 0U; i < number_of_algorithms; ++i) { + snprintf(str_buf, 1024, " #%u AlgorithmId : SHA", i); + uint16_t algorithm_id = alg_ptr[i].algorithm_id; + + switch (algorithm_id) { + case TPM_ALG_SHA256: + snprintf(str_buf, 1024, "%s256\n", str_buf); + break; + case TPM_ALG_SHA384: + snprintf(str_buf, 1024, "%s384\n", str_buf); + break; + case TPM_ALG_SHA512: + snprintf(str_buf, 1024, "%s512\n", str_buf); + break; + default: + snprintf(str_buf, 1024, "%s?\n", str_buf); + EMSG("Algorithm 0x%x not found\n", algorithm_id); + assert(false); + } + + MSG("%s", str_buf); + MSG(" DigestSize : %u\n", + alg_ptr[i].digest_size); + str_buf[0] = 0; + } + + /* Address of VendorInfoSize */ + info_size_ptr = (uint8_t *)alg_ptr + digest_len; + assert(info_size_ptr <= end_ptr); + + info_size = *info_size_ptr++; + MSG(" VendorInfoSize : %u\n", info_size); + + /* Check VendorInfo end address */ + assert((info_size_ptr + info_size) <= end_ptr); + + /* Check EventSize */ + assert(event_size == (sizeof(id_event_struct_t) + + digest_len + info_size)); + if (info_size != 0U) { + snprintf(str_buf, 1024, " VendorInfo :"); + for (i = 0U; i < info_size; ++i) { + snprintf(str_buf, 1024, "%s %02x", str_buf, + *info_size_ptr++); + } + MSG("%s\n", str_buf); + str_buf[0] = 0; + } + + *log_size -= (uintptr_t)info_size_ptr - (uintptr_t)*log_addr; + *log_addr = info_size_ptr; +} + +/* + * Print TCG_PCR_EVENT2 + * + * @param[in/out] log_addr Pointer to Event Log + * @param[in/out] log_size Pointer to Event Log size + */ +static void event2_print(uint8_t **log_addr, size_t *log_size) +{ + uint32_t event_size, count; + size_t sha_size, digests_size = 0U; + void *ptr = *log_addr; + char str_buf[1024]; + + const uint8_t *end_ptr = *log_addr + *log_size; + + assert(*log_size >= sizeof(event2_header_t)); + + MSG("PCR_Event2:\n"); + MSG(" PCRIndex : %u\n", + ((event2_header_t *)ptr)->pcr_index); + MSG(" EventType : %u\n", + ((event2_header_t *)ptr)->event_type); + + count = ((event2_header_t *)ptr)->digests.count; + MSG(" Digests Count : %u\n", count); + + /* Address of TCG_PCR_EVENT2.Digests[] */ + ptr = (uint8_t *)ptr + sizeof(event2_header_t); + assert(((uintptr_t)ptr <= (uintptr_t)end_ptr) && (count != 0U)); + + str_buf[0] = 0; + for (unsigned int i = 0U; i < count; ++i) { + /* Check AlgorithmId address */ + assert(((uint8_t *)ptr + offsetof(tpmt_ha, digest)) <= end_ptr); + + snprintf(str_buf, 1024, " #%u AlgorithmId : SHA", i); + switch (((tpmt_ha *)ptr)->algorithm_id) { + case TPM_ALG_SHA256: + sha_size = SHA256_DIGEST_SIZE; + snprintf(str_buf, 1024, "%s256\n", str_buf); + break; + case TPM_ALG_SHA384: + sha_size = SHA384_DIGEST_SIZE; + snprintf(str_buf, 1024, "%s384\n", str_buf); + break; + case TPM_ALG_SHA512: + sha_size = SHA512_DIGEST_SIZE; + snprintf(str_buf, 1024, "%s512\n", str_buf); + break; + default: + snprintf(str_buf, 1024, "%s?\n", str_buf); + EMSG("Algorithm 0x%x not found\n", + ((tpmt_ha *)ptr)->algorithm_id); + assert(true); + } + MSG("%s", str_buf); + str_buf[0] = 0; + + /* End of Digest[] */ + ptr = (uint8_t *)ptr + offsetof(tpmt_ha, digest); + assert(((uint8_t *)ptr + sha_size) <= end_ptr); + + /* Total size of all digests */ + digests_size += sha_size; + + snprintf(str_buf, 1024, " Digest :"); + for (unsigned int j = 0U; j < sha_size; ++j) { + snprintf(str_buf, 1024, "%s %02x", str_buf, + *(uint8_t *)ptr++); + if ((j & U(0xF)) == U(0xF)) { + MSG("%s\n", str_buf); + str_buf[0] = 0; + if (j < (sha_size - 1U)) { + snprintf(str_buf, 1024, "\t\t\t :"); + } + } + } + } + + /* TCG_PCR_EVENT2.EventSize */ + assert(((uint8_t *)ptr + offsetof(event2_data_t, event)) <= end_ptr); + + event_size = ((event2_data_t *)ptr)->event_size; + MSG(" EventSize : %u\n", event_size); + + /* Address of TCG_PCR_EVENT2.Event[EventSize] */ + ptr = (uint8_t *)ptr + offsetof(event2_data_t, event); + + /* End of TCG_PCR_EVENT2.Event[EventSize] */ + assert(((uint8_t *)ptr + event_size) <= end_ptr); + + if ((event_size == sizeof(startup_locality_event_t)) && + (strcmp((const char *)ptr, TCG_STARTUP_LOCALITY_SIGNATURE) == 0)) { + MSG(" Signature : %s\n", + ((startup_locality_event_t *)ptr)->signature); + MSG(" StartupLocality : %u\n", + ((startup_locality_event_t *)ptr)->startup_locality); + } else { + MSG(" Event : %s\n", (uint8_t *)ptr); + } + + *log_size -= (uintptr_t)ptr + event_size - (uintptr_t)*log_addr; + *log_addr = (uint8_t *)ptr + event_size; +} +#endif /* LOG_LEVEL >= EVENT_LOG_LEVEL */ + +/* + * Print Event Log + * + * @param[in] log_addr Pointer to Event Log + * @param[in] log_size Event Log size + */ +void dump_event_log(uint8_t *log_addr, size_t log_size) +{ +#if LOG_LEVEL >= EVENT_LOG_LEVEL + assert(log_addr != NULL); + + /* Print TCG_EfiSpecIDEvent */ + id_event_print(&log_addr, &log_size); + + while (log_size != 0U) { + event2_print(&log_addr, &log_size); + } +#endif +} diff --git a/ta/ftpm/platform/LocalityPlat.c b/ta/ftpm/platform/LocalityPlat.c new file mode 100644 index 00000000000..1d74c57061b --- /dev/null +++ b/ta/ftpm/platform/LocalityPlat.c @@ -0,0 +1,65 @@ +/* Microsoft Reference Implementation for TPM 2.0 + * + * The copyright in this software is being made available under the BSD License, + * included below. This software may be subject to other third party and + * contributor rights, including patent rights, and no such rights are granted + * under this license. + * + * Copyright (c) Microsoft Corporation + * + * All rights reserved. + * + * BSD License + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * Redistributions of source code must retain the above copyright notice, this list + * of conditions and the following disclaimer. + * + * 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. + * + * 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. + */ +//** Includes + +#include "PlatformData.h" +#include "Platform_fp.h" + +//** Functions + +//***_plat__LocalityGet() +// Get the most recent command locality in locality value form. +// This is an integer value for locality and not a locality structure +// The locality can be 0-4 or 32-255. 5-31 is not allowed. +LIB_EXPORT unsigned char +_plat__LocalityGet( + void + ) +{ + return s_locality; +} + +//***_plat__LocalitySet() +// Set the most recent command locality in locality value form +LIB_EXPORT void +_plat__LocalitySet( + unsigned char locality + ) +{ + if(locality > 4 && locality < 32) + locality = 0; + s_locality = locality; + return; +} \ No newline at end of file diff --git a/ta/ftpm/platform/NVMem.c b/ta/ftpm/platform/NVMem.c new file mode 100644 index 00000000000..23db9d07544 --- /dev/null +++ b/ta/ftpm/platform/NVMem.c @@ -0,0 +1,646 @@ +/* Microsoft Reference Implementation for TPM 2.0 + * + * The copyright in this software is being made available under the BSD License, + * included below. This software may be subject to other third party and + * contributor rights, including patent rights, and no such rights are granted + * under this license. + * + * Copyright (c) Microsoft Corporation + * + * All rights reserved. + * + * BSD License + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * Redistributions of source code must retain the above copyright notice, this list + * of conditions and the following disclaimer. + * + * 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. + * + * 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. + */ +//** Description +// +// This file contains the NV read and write access methods. This implementation +// uses RAM/file and does not manage the RAM/file as NV blocks. +// The implementation may become more sophisticated over time. +// + +#include "TpmError.h" +#include "Admin.h" +#include "VendorString.h" +#include "stdint.h" +#include "malloc.h" +#include "string.h" + +#include +#include + +// +// Overall size of NV, not just the TPM's NV storage +// +#define NV_CHIP_MEMORY_SIZE (NV_MEMORY_SIZE + NV_TPM_STATE_SIZE) + +// +// OpTEE still has an all or nothing approach to reads/writes. To provide +// more performant access to storage, break up NV accross 1Kbyte blocks. +// +// Note that NV_CHIP_MEMORY_SIZE *MUST* be a factor of NV_BLOCK_SIZE. +// +#define NV_BLOCK_SIZE 0x200 +#define NV_BLOCK_COUNT ((NV_CHIP_MEMORY_SIZE) / (NV_BLOCK_SIZE)) + +// +// For cleaner descriptor validation +// +#define IS_VALID(a) ((a) != (TEE_HANDLE_NULL)) + +// +// Storage flags +// +#define TA_STORAGE_FLAGS (TEE_DATA_FLAG_ACCESS_READ | \ + TEE_DATA_FLAG_ACCESS_WRITE | \ + TEE_DATA_FLAG_ACCESS_WRITE_META) + +// +// The base Object ID for fTPM storage +// +static const UINT32 s_StorageObjectID = 0x54504D00; // 'TPM00' + +// +// Object handle list for persistent storage objects containing NV +// +static TEE_ObjectHandle s_NVStore[NV_BLOCK_COUNT] = { TEE_HANDLE_NULL }; + +// +// Bitmap for NV blocks. Moving from UINT64 requires change to NV_DIRTY_ALL. +// +static UINT64 s_blockMap = 0x0ULL; + +// +// Shortcut for 'dirty'ing all NV blocks. Note the type. +// +#if NV_BLOCK_COUNT < 64 +#define NV_DIRTY_ALL ((UINT64)((0x1ULL << NV_BLOCK_COUNT) - 1)) +#elif NV_BLOCK_COUNT == 64 +#define NV_DIRTY_ALL (~(0x0ULL)) +#else +#error "NV block count exceeds 64 bit block map. Adjust block or NV size." +#endif + +// +// NV state +// +static BOOL s_NVChipFileNeedsManufacture = FALSE; +static BOOL s_NVInitialized = FALSE; +static UCHAR s_NV[NV_CHIP_MEMORY_SIZE]; + +// +// Firmware revision +// +static const UINT32 firmwareV1 = FIRMWARE_V1; +static const UINT32 firmwareV2 = FIRMWARE_V2; + +// +// Revision fro NVChip +// +static UINT64 s_chipRevision = 0; + +// +// This offset puts the revision field immediately following the TPM Admin +// state. The Admin space in NV is down to ~16 bytes but is padded out to +// 256bytes to avoid alignment issues and allow for growth. +// +#define NV_CHIP_REVISION_OFFSET ((NV_MEMORY_SIZE) + (TPM_STATE_SIZE)) + +VOID +_plat__NvInitFromStorage() +{ + DMSG("_plat__NvInitFromStorage()"); + UINT32 i; + BOOL initialized; + UINT32 objID; + UINT32 bytesRead; + TEE_Result Result; + + // Don't re-initialize. + if (s_NVInitialized) { + return; + } + + // + // If the NV file is successfully read from the storage then + // initialized must be set. We are setting initialized to true + // here but if an error is encountered reading the NV file it will + // be reset. + // + + initialized = TRUE; + + // Collect storage objects and init NV. + for (i = 0; i < NV_BLOCK_COUNT; i++) { + + // Form storage object ID for this block. + objID = s_StorageObjectID + i; + + // Attempt to open TEE persistent storage object. + Result = TEE_OpenPersistentObject(TEE_STORAGE_PRIVATE, + (void *)&objID, + sizeof(objID), + TA_STORAGE_FLAGS, + &s_NVStore[i]); + + // If the open failed, try to create this storage object. + if (Result != TEE_SUCCESS) { + + // There was an error, fail the init, NVEnable can retry. + if (Result != TEE_ERROR_ITEM_NOT_FOUND) { +#ifdef fTPMDebug + DMSG("Failed to open fTPM storage object"); +#endif + goto Error; + } + + // Storage object was not found, create it. + Result = TEE_CreatePersistentObject(TEE_STORAGE_PRIVATE, + (void *)&objID, + sizeof(objID), + TA_STORAGE_FLAGS, + NULL, + (void *)&(s_NV[i * NV_BLOCK_SIZE]), + NV_BLOCK_SIZE, + &s_NVStore[i]); + + // There was an error, fail the init, NVEnable can retry. + if (Result != TEE_SUCCESS) { +#ifdef fTPMDebug + DMSG("Failed to create fTPM storage object"); +#endif + goto Error; + } + + // A clean storage object was created, we must (re)manufacture. + s_NVChipFileNeedsManufacture = TRUE; + + // To ensure NV is consistent, force a write back of all NV blocks + s_blockMap = NV_DIRTY_ALL; + + // Need to re-initialize + initialized = FALSE; + +#ifdef fTPMDebug + IMSG("Created fTPM storage object, i: 0x%x, s: 0x%x, id: 0x%x, h:0x%x\n", + i, NV_BLOCK_SIZE, objID, s_NVStore[i]); +#endif + } + else { + // Successful open, now read fTPM storage object. + Result = TEE_ReadObjectData(s_NVStore[i], + (void *)&(s_NV[i * NV_BLOCK_SIZE]), + NV_BLOCK_SIZE, + &bytesRead); + + // Give up on failed or incomplete reads. + if ((Result != TEE_SUCCESS) || (bytesRead != NV_BLOCK_SIZE)) { +#ifdef fTPMDebug + DMSG("Failed to read fTPM storage object"); +#endif + goto Error; + } + +#ifdef fTPMDebug + IMSG("Read fTPM storage object, i: 0x%x, s: 0x%x, id: 0x%x, h:0x%x\n", + i, bytesRead, objID, s_NVStore[i]); +#endif + } + } + + // Storage objects are open and valid, next validate revision + s_chipRevision = ((((UINT64)firmwareV2) << 32) | (firmwareV1)); + if ((s_chipRevision != *(UINT64*)&(s_NV[NV_CHIP_REVISION_OFFSET]))) { + + // Failure to validate revision, re-init. + memset(s_NV, 0, NV_CHIP_MEMORY_SIZE); + + // Dirty the block map, we're going to re-init. + s_blockMap = NV_DIRTY_ALL; + + // Init with proper revision + s_chipRevision = ((((UINT64)firmwareV2) << 32) | (firmwareV1)); + *(UINT64*)&(s_NV[NV_CHIP_REVISION_OFFSET]) = s_chipRevision; + +#ifdef fTPMDebug + DMSG("Failed to validate revision."); +#endif + + // Force (re)manufacture. + s_NVChipFileNeedsManufacture = TRUE; + + // Need to re-initialize + initialized = FALSE; + + return; + } + + s_NVInitialized = initialized; + + return; + +Error: + s_NVInitialized = FALSE; + for (i = 0; i < NV_BLOCK_COUNT; i++) { + if (IS_VALID(s_NVStore[i])) { + TEE_CloseObject(s_NVStore[i]); + s_NVStore[i] = TEE_HANDLE_NULL; + } + } + + return; +} + + +static void +_plat__NvWriteBack() +{ + UINT32 i; + UINT32 objID; + TEE_Result Result; + + // Exit if no dirty blocks. + if ((!s_blockMap) || (!s_NVInitialized)) { + return; + } + +#ifdef fTPMDebug + DMSG("bMap: 0x%x\n", s_blockMap); +#endif + + // Write dirty blocks. + for (i = 0; i < NV_BLOCK_COUNT; i++) { + + if ((s_blockMap & (0x1ULL << i))) { + + // Form storage object ID for this block. + objID = s_StorageObjectID + i; + + // Move data position associated with handle to start of block. + Result = TEE_SeekObjectData(s_NVStore[i], 0, TEE_DATA_SEEK_SET); + if (Result != TEE_SUCCESS) { + goto Error; + } + + // Write out this block. + Result = TEE_WriteObjectData(s_NVStore[i], + (void *)&(s_NV[i * NV_BLOCK_SIZE]), + NV_BLOCK_SIZE); + if (Result != TEE_SUCCESS) { + goto Error; + } + + // Force storage stack to update its backing store + TEE_CloseObject(s_NVStore[i]); + + Result = TEE_OpenPersistentObject(TEE_STORAGE_PRIVATE, + (void *)&objID, + sizeof(objID), + TA_STORAGE_FLAGS, + &s_NVStore[i]); + // Success? + if (Result != TEE_SUCCESS) { + goto Error; + } + + // Clear dirty bit. + s_blockMap &= ~(0x1ULL << i); + } + } + + return; + +Error: + // Error path. +#ifdef fTPMDebug + DMSG("NV write back failed"); +#endif + s_NVInitialized = FALSE; + for (i = 0; i < NV_BLOCK_COUNT; i++) { + if (IS_VALID(s_NVStore[i])) { + TEE_CloseObject(s_NVStore[i]); + s_NVStore[i] = TEE_HANDLE_NULL; + } + } + + return; +} + + +BOOL +_plat__NvNeedsManufacture() +{ + return s_NVChipFileNeedsManufacture; +} + +//***_plat__NVEnable() +// Enable NV memory. +// +// This version just pulls in data from a file. In a real TPM, with NV on chip, +// this function would verify the integrity of the saved context. If the NV +// memory was not on chip but was in something like RPMB, the NV state would be +// read in, decrypted and integrity checked. +// +// The recovery from an integrity failure depends on where the error occurred. It +// it was in the state that is discarded by TPM Reset, then the error is +// recoverable if the TPM is reset. Otherwise, the TPM must go into failure mode. +// return type: int +// 0 if success +// > 0 if receive recoverable error +// <0 if unrecoverable error +LIB_EXPORT int +_plat__NVEnable( + void *platParameter // IN: platform specific parameters + ) +{ + UNREFERENCED_PARAMETER(platParameter); + DMSG("_plat__NVEnable()"); + + + UINT32 retVal = 0; + UINT32 firmwareV1 = FIRMWARE_V1; + UINT32 firmwareV2 = FIRMWARE_V2; + + // Don't re-open the backing store. + if (s_NVInitialized) { + return 0; + } + + // Clear NV + memset(s_NV, 0, NV_CHIP_MEMORY_SIZE); + + // Prepare for potential failure to retreieve NV from storage + s_chipRevision = ((((UINT64)firmwareV2) << 32) | (firmwareV1)); + *(UINT64*)&(s_NV[NV_CHIP_REVISION_OFFSET]) = s_chipRevision; + + // Pick up our NV memory. + _plat__NvInitFromStorage(); + + // Were we successful? + if (!s_NVInitialized) { + // Arriving here means one of two things: Either there existed no + // NV state before we came along and we just (re)initialized our + // storage. Or there is an error condition preventing us from + // accessing storage. Check which is the case. + if (s_NVChipFileNeedsManufacture == FALSE) { + // This condition means we cannot access storage. However, it + // isn't up to the platform layer to decide what to do in this + // case. The decision to proceed is made in the fTPM init code + // in TA_CreateEntryPoint. Here, we're going to make sure that, + // should we decide not to just TEE_Panic, we can continue + // execution after (re)manufacture. Later an attempt at re-init + // can be made by calling _plat__NvInitFromStorage again. + retVal = 0; + } + else { + retVal = 1; + } + + // Going to manufacture, zero flags + g_chipFlags.flags = 0; + + // Save flags + _admin__SaveChipFlags(); + + // Now we're done + s_NVInitialized = TRUE; + + return retVal; + } + else { + // In the transition out of UEFI to Windows, we may not tear down + // the TA. We close out one session and start another. This means + // our s_NVChipFileNeedsManufacture flag, if set, will be stale. + // Make sure we don't re-manufacture. + s_NVChipFileNeedsManufacture = FALSE; + + // We successfully initialized NV now pickup TPM state. + _admin__RestoreChipFlags(); + + // Success + retVal = 1; + } + + return retVal; +} + +//***_plat__NVDisable() +// Disable NV memory +LIB_EXPORT void +_plat__NVDisable( + void + ) +{ + UINT32 i; + + if (!s_NVInitialized) { + return; + } + + // Final write + _plat__NvWriteBack(); + + // Close out all handles + for (i = 0; i < NV_BLOCK_COUNT; i++) { + if (IS_VALID(s_NVStore[i])) { + TEE_CloseObject(s_NVStore[i]); + s_NVStore[i] = TEE_HANDLE_NULL; + } + } + + // We're no longer init-ed + s_NVInitialized = FALSE; + + return; +} + +//***_plat__IsNvAvailable() +// Check if NV is available +// return type: int +// 0 NV is available +// 1 NV is not available due to write failure +// 2 NV is not available due to rate limit +LIB_EXPORT int +_plat__IsNvAvailable( + void + ) +{ + // This is not enabled for OpTEE TA. Storage is always available. + return 0; +} + + + +//***_plat__NvMemoryRead() +// Function: Read a chunk of NV memory +LIB_EXPORT void +_plat__NvMemoryRead( + unsigned int startOffset, // IN: read start + unsigned int size, // IN: size of bytes to read + void *data // OUT: data buffer + ) +{ + pAssert((startOffset + size) <= NV_CHIP_MEMORY_SIZE); + pAssert(s_NV != NULL); + + memcpy(data, &s_NV[startOffset], size); +} + +//*** _plat__NvIsDifferent() +// This function checks to see if the NV is different from the test value. This is +// so that NV will not be written if it has not changed. +// return value: int +// TRUE(1) the NV location is different from the test value +// FALSE(0) the NV location is the same as the test value +LIB_EXPORT int +_plat__NvIsDifferent( + unsigned int startOffset, // IN: read start + unsigned int size, // IN: size of bytes to read + void *data // IN: data buffer + ) +{ + return (memcmp(&s_NV[startOffset], data, size) != 0); +} + +static +void +_plat__MarkDirtyBlocks ( + unsigned int startOffset, + unsigned int size +) +{ + unsigned int blockEnd; + unsigned int blockStart; + unsigned int i; + + // + // Integer math will round down to the start of the block. + // blockEnd is actually the last block + 1. + // + + blockStart = startOffset / NV_BLOCK_SIZE; + blockEnd = (startOffset + size) / NV_BLOCK_SIZE; + if ((startOffset + size) % NV_BLOCK_SIZE != 0) { + blockEnd += 1; + } + + for (i = blockStart; i < blockEnd; i++) { + s_blockMap |= (0x1ULL << i); + } +} + +//***_plat__NvMemoryWrite() +// This function is used to update NV memory. The "write" is to a memory copy of +// NV. At the end of the current command, any changes are written to +// the actual NV memory. +// NOTE: A useful optimization would be for this code to compare the current +// contents of NV with the local copy and note the blocks that have changed. Then +// only write those blocks when _plat__NvCommit() is called. +LIB_EXPORT void +_plat__NvMemoryWrite( + unsigned int startOffset, // IN: write start + unsigned int size, // IN: size of bytes to write + void *data // OUT: data buffer + ) +{ + pAssert(startOffset + size <= NV_CHIP_MEMORY_SIZE); + pAssert(s_NV != NULL); + + _plat__MarkDirtyBlocks(startOffset, size); + memcpy(&s_NV[startOffset], data, size); +} + +//***_plat__NvMemoryClear() +// Function is used to set a range of NV memory bytes to an implementation-dependent +// value. The value represents the erase state of the memory. +LIB_EXPORT void +_plat__NvMemoryClear( + unsigned int start, // IN: clear start + unsigned int size // IN: number of bytes to clear + ) +{ + pAssert(start + size <= NV_MEMORY_SIZE); + + _plat__MarkDirtyBlocks(start, size); + memset(&s_NV[start], 0, size); +} + +//***_plat__NvMemoryMove() +// Function: Move a chunk of NV memory from source to destination +// This function should ensure that if there overlap, the original data is +// copied before it is written +LIB_EXPORT void +_plat__NvMemoryMove( + unsigned int sourceOffset, // IN: source offset + unsigned int destOffset, // IN: destination offset + unsigned int size // IN: size of data being moved + ) +{ + pAssert(sourceOffset + size <= NV_CHIP_MEMORY_SIZE); + pAssert(destOffset + size <= NV_CHIP_MEMORY_SIZE); + pAssert(s_NV != NULL); + + _plat__MarkDirtyBlocks(sourceOffset, size); + _plat__MarkDirtyBlocks(destOffset, size); + + memmove(&s_NV[destOffset], &s_NV[sourceOffset], size); +} + +//***_plat__NvCommit() +// This function writes the local copy of NV to NV for permanent store. It will write +// NV_MEMORY_SIZE bytes to NV. If a file is use, the entire file is written. +// return type: int +// 0 NV write success +// non-0 NV write fail +LIB_EXPORT int +_plat__NvCommit( + void + ) +{ + _plat__NvWriteBack(); + return 0; +} + +//***_plat__SetNvAvail() +// Set the current NV state to available. This function is for testing purpose +// only. It is not part of the platform NV logic +LIB_EXPORT void +_plat__SetNvAvail( + void + ) +{ + // NV will not be made unavailable on this platform + return; +} + +//***_plat__ClearNvAvail() +// Set the current NV state to unavailable. This function is for testing purpose +// only. It is not part of the platform NV logic +LIB_EXPORT void +_plat__ClearNvAvail( + void + ) +{ + // The anti-set; not on this platform. + return; +} diff --git a/ta/ftpm/platform/NvAdmin.c b/ta/ftpm/platform/NvAdmin.c new file mode 100644 index 00000000000..257600153ba --- /dev/null +++ b/ta/ftpm/platform/NvAdmin.c @@ -0,0 +1,151 @@ +/* Microsoft Reference Implementation for TPM 2.0 + * + * The copyright in this software is being made available under the BSD License, + * included below. This software may be subject to other third party and + * contributor rights, including patent rights, and no such rights are granted + * under this license. + * + * Copyright (c) Microsoft Corporation + * + * All rights reserved. + * + * BSD License + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * Redistributions of source code must retain the above copyright notice, this list + * of conditions and the following disclaimer. + * + * 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. + * + * 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. + */ + +//**Includes +// Force Global.h contents inclusion +#define GLOBAL_C + +#include "Admin.h" + +//**Types, Structures, and Defines +// +// List of pre-defined address of TPM state data +// +static UINT32 s_stateAddr[NV_TPM_STATE_LAST]; + +// +// List of pre-defined TPM state data size in byte +// +static UINT32 s_stateSize[NV_TPM_STATE_LAST]; + +// +// The current chip state +// +TPM_CHIP_STATE g_chipFlags; + +// +// The current PPI state +// +extern FTPM_PPI_STATE s_PPIState; + +//***_admin__NvInitState() +// Initialize the state NV runtime state values +void +_admin__NvInitState() +{ + UINT16 i; + UINT32 stateAddr; + + // + // Initialize TPM saved runtime state + // + s_stateSize[NV_TPM_STATE_FLAGS] = sizeof(TPM_CHIP_STATE); + s_stateSize[NV_TPM_STATE_PPI] = sizeof(FTPM_PPI_STATE); + + // + // Initialize TPM state data addresses. Stored after the main NV space. + // + stateAddr = NV_MEMORY_SIZE; + for (i = 0; i < NV_TPM_STATE_LAST; i++) { + s_stateAddr[i] = stateAddr; + stateAddr += s_stateSize[i]; + } + + pAssert(stateAddr <= (NV_MEMORY_SIZE + NV_TPM_STATE_SIZE)); +} + +//***_admin__SaveChipFlags() +// Save the g_chipFlags runtime state +void +_admin__SaveChipFlags() +{ + _admin__NvWriteState(NV_TPM_STATE_FLAGS, &g_chipFlags); +} + +//***_admin__RestoreChipFlags() +// Restore the g_chipFlags runtime state +void +_admin__RestoreChipFlags() +{ + _admin__NvReadState(NV_TPM_STATE_FLAGS, &g_chipFlags); +} + +//***_admin__SavePPIState() +// Save the s_PPIState runtime state +void +_admin__SavePPIState() +{ + _admin__NvWriteState(NV_TPM_STATE_PPI, &s_PPIState); + + _plat__NvCommit(); +} + +//***_admin__RestorePPIState() +// Restore the s_PPIState runtime state +void +_admin__RestorePPIState() +{ + _admin__NvReadState(NV_TPM_STATE_PPI, &s_PPIState); +} + +//***_admin__NvReadState() +// Read TPM state data from NV memory to RAM +void +_admin__NvReadState( + NV_TPM_STATE type, // IN: type of state data + void *buffer // OUT: data buffer + ) +{ + // Input type should be valid + pAssert(type >= 0 && type < NV_TPM_STATE_LAST); + + _plat__NvMemoryRead(s_stateAddr[type], s_stateSize[type], buffer); + return; +} + +//***_admin__NvWriteState() +// Write TPM state data to NV memory +void +_admin__NvWriteState( + NV_TPM_STATE type, // IN: type of state data + void *buffer // IN: data buffer + ) +{ + // Input type should be valid + pAssert(type >= 0 && type < NV_TPM_STATE_LAST); + + _plat__NvMemoryWrite(s_stateAddr[type], s_stateSize[type], buffer); + return; +} \ No newline at end of file diff --git a/ta/ftpm/platform/PPPlat.c b/ta/ftpm/platform/PPPlat.c new file mode 100644 index 00000000000..8b837a1c3a8 --- /dev/null +++ b/ta/ftpm/platform/PPPlat.c @@ -0,0 +1,80 @@ +/* Microsoft Reference Implementation for TPM 2.0 + * + * The copyright in this software is being made available under the BSD License, + * included below. This software may be subject to other third party and + * contributor rights, including patent rights, and no such rights are granted + * under this license. + * + * Copyright (c) Microsoft Corporation + * + * All rights reserved. + * + * BSD License + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * Redistributions of source code must retain the above copyright notice, this list + * of conditions and the following disclaimer. + * + * 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. + * + * 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. + */ +//** Description + +// This module simulates the physical presence interface pins on the TPM. + +//** Includes +#include "PlatformData.h" +#include "Platform_fp.h" + +//** Functions + +//***_plat__PhysicalPresenceAsserted() +// Check if physical presence is signaled +// return type: int +// TRUE(1) if physical presence is signaled +// FALSE(0) if physical presence is not signaled +LIB_EXPORT int +_plat__PhysicalPresenceAsserted( + void + ) +{ + // Do not know how to check physical presence without real hardware. + // so always return TRUE; + return s_physicalPresence; +} + +//***_plat__Signal_PhysicalPresenceOn() +// Signal physical presence on +LIB_EXPORT void +_plat__Signal_PhysicalPresenceOn( + void + ) +{ + s_physicalPresence = TRUE; + return; +} + +//***_plat__Signal_PhysicalPresenceOff() +// Signal physical presence off +LIB_EXPORT void +_plat__Signal_PhysicalPresenceOff( + void + ) +{ + s_physicalPresence = FALSE; + return; +} \ No newline at end of file diff --git a/ta/ftpm/platform/PlatformACT.c b/ta/ftpm/platform/PlatformACT.c new file mode 100644 index 00000000000..9528b08c1f9 --- /dev/null +++ b/ta/ftpm/platform/PlatformACT.c @@ -0,0 +1,345 @@ +/* Microsoft Reference Implementation for TPM 2.0 + * + * The copyright in this software is being made available under the BSD License, + * included below. This software may be subject to other third party and + * contributor rights, including patent rights, and no such rights are granted + * under this license. + * + * Copyright (c) Microsoft Corporation + * + * All rights reserved. + * + * BSD License + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * Redistributions of source code must retain the above copyright notice, this list + * of conditions and the following disclaimer. + * + * 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. + * + * 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. + */ +//** Includes +#include "Platform.h" + +//** Global variables +#define DEFINE_ACT(N) ACT_DATA ACT_##N; +FOR_EACH_ACT(DEFINE_ACT) + +int actTicksAllowed; + +//** Functions + +//*** ActSignal() +// Function called when there is an ACT event to signal or unsignal +static void +ActSignal( + P_ACT_DATA actData, + int on +) +{ + if(actData == NULL) + return; + // If this is to turn a signal on, don't do anything if it is already on. If this + // is to turn the signal off, do it anyway because this might be for + // initialization. + if(on && (actData->signaled == TRUE)) + return; + actData->signaled = (uint8_t)on; + + // If there is an action, then replace the "Do something" with the correct action. + // It should test 'on' to see if it is turning the signal on or off. + switch(actData->number) + { +#if RH_ACT_0 + case 0: // Do something + return; +#endif +#if RH_ACT_1 + case 1: // Do something + return; +#endif +#if RH_ACT_2 + case 2: // Do something + return; +#endif +#if RH_ACT_3 + case 3: // Do something + return; +#endif +#if RH_ACT_4 + case 4: // Do something + return; +#endif +#if RH_ACT_5 + case 5: // Do something + return; +#endif +#if RH_ACT_6 + case 6: // Do something + return; +#endif +#if RH_ACT_7 + case 7: // Do something + return; +#endif +#if RH_ACT_8 + case 8: // Do something + return; +#endif +#if RH_ACT_9 + case 9: // Do something + return; +#endif +#if RH_ACT_A + case 0xA: // Do something + return; +#endif +#if RH_ACT_B + case 0xB: + // Do something + return; +#endif +#if RH_ACT_C + case 0xC: // Do something + return; +#endif +#if RH_ACT_D + case 0xD: // Do something + return; +#endif +#if RH_ACT_E + case 0xE: // Do something + return; +#endif +#if RH_ACT_F + case 0xF: // Do something + return; +#endif + default: + return; + } +} + +//*** ActGetDataPointer() +static P_ACT_DATA +ActGetDataPointer( + uint32_t act +) +{ + +#define RETURN_ACT_POINTER(N) if(0x##N == act) return &ACT_##N; + + FOR_EACH_ACT(RETURN_ACT_POINTER) + + return (P_ACT_DATA)NULL; +} + +//*** _plat__ACT_GetImplemented() +// This function tests to see if an ACT is implemented. It is a belt and suspenders +// function because the TPM should not be calling to manipulate an ACT that is not +// implemented. However, this could help the simulator code which doesn't necessarily +// know if an ACT is implemented or not. +LIB_EXPORT int +_plat__ACT_GetImplemented( + uint32_t act +) +{ + return (ActGetDataPointer(act) != NULL); +} + +//*** _plat__ACT_GetRemaining() +// This function returns the remaining time. If an update is pending, 'newValue' is +// returned. Otherwise, the current counter value is returned. Note that since the +// timers keep running, the returned value can get stale immediately. The actual count +// value will be no greater than the returned value. +LIB_EXPORT uint32_t +_plat__ACT_GetRemaining( + uint32_t act //IN: the ACT selector +) +{ + P_ACT_DATA actData = ActGetDataPointer(act); + uint32_t remain; +// + if(actData == NULL) + return 0; + remain = actData->remaining; + if(actData->pending) + remain = actData->newValue; + return remain; +} + +//*** _plat__ACT_GetSignaled() +LIB_EXPORT int +_plat__ACT_GetSignaled( + uint32_t act //IN: number of ACT to check +) +{ + P_ACT_DATA actData = ActGetDataPointer(act); +// + if(actData == NULL) + return 0; + return (int )actData->signaled; +} + +//*** _plat__ACT_SetSignaled() +LIB_EXPORT void +_plat__ACT_SetSignaled( + uint32_t act, + int on +) +{ + ActSignal(ActGetDataPointer(act), on); +} + +//*** _plat__ACT_GetPending() +LIB_EXPORT int +_plat__ACT_GetPending( + uint32_t act //IN: number of ACT to check +) +{ + P_ACT_DATA actData = ActGetDataPointer(act); +// + if(actData == NULL) + return 0; + return (int )actData->pending; +} + + +//*** _plat__ACT_UpdateCounter() +// This function is used to write the newValue for the counter. If an update is +// pending, then no update occurs and the function returns FALSE. If 'setSignaled' +// is TRUE, then the ACT signaled state is SET and if 'newValue' is 0, nothing +// is posted. +LIB_EXPORT int +_plat__ACT_UpdateCounter( + uint32_t act, // IN: ACT to update + uint32_t newValue // IN: the value to post +) +{ + P_ACT_DATA actData = ActGetDataPointer(act); + // + if(actData == NULL) + // actData doesn't exist but pretend update is pending rather than indicate + // that a retry is necessary. + return TRUE; + // if an update is pending then return FALSE so that there will be a retry + if(actData->pending != 0) + return FALSE; + actData->newValue = newValue; + actData->pending = TRUE; + + return TRUE; +} + +//***_plat__ACT_EnableTicks() +// This enables and disables the processing of the once-per-second ticks. This should +// be turned off ('enable' = FALSE) by _TPM_Init and turned on ('enable' = TRUE) by +// TPM2_Startup() after all the initializations have completed. +LIB_EXPORT void +_plat__ACT_EnableTicks( + int enable +) +{ + actTicksAllowed = enable; +} + +//*** ActDecrement() +// If 'newValue' is non-zero it is copied to 'remaining' and then 'newValue' is +// set to zero. Then 'remaining' is decremented by one if it is not already zero. If +// the value is decremented to zero, then the associated event is signaled. If setting +// 'remaining' causes it to be greater than 1, then the signal associated with the ACT +// is turned off. +static void +ActDecrement( + P_ACT_DATA actData +) +{ + // Check to see if there is an update pending + if(actData->pending) + { + // If this update will cause the count to go from non-zero to zero, set + // the newValue to 1 so that it will timeout when decremented below. + if((actData->newValue == 0) && (actData->remaining != 0)) + actData->newValue = 1; + actData->remaining = actData->newValue; + + // Update processed + actData->pending = 0; + } + // no update so countdown if the count is non-zero but not max + if((actData->remaining != 0) && (actData->remaining != UINT32_MAX)) + { + // If this countdown causes the count to go to zero, then turn the signal for + // the ACT on. + if((actData->remaining -= 1) == 0) + ActSignal(actData, TRUE); + } + // If the current value of the counter is non-zero, then the signal should be + // off. + if(actData->signaled && (actData->remaining > 0)) + ActSignal(actData, FALSE); +} + +//*** _plat__ACT_Tick() +// This processes the once-per-second clock tick from the hardware. This is set up +// for the simulator to use the control interface to send ticks to the TPM. These +// ticks do not have to be on a per second basis. They can be as slow or as fast as +// desired so that the simulation can be tested. +LIB_EXPORT void +_plat__ACT_Tick( + void +) +{ + // Ticks processing is turned off at certain times just to make sure that nothing + // strange is happening before pointers and things are + if(actTicksAllowed) + { + // Handle the update for each counter. +#define DECREMENT_COUNT(N) ActDecrement(&ACT_##N); + + FOR_EACH_ACT(DECREMENT_COUNT) + } +} + +//*** ActZero() +// This function initializes a single ACT +static void +ActZero( + uint32_t act, + P_ACT_DATA actData +) +{ + actData->remaining = 0; + actData->newValue = 0; + actData->pending = 0; + actData->number = (uint8_t)act; + ActSignal(actData, FALSE); +} + +//***_plat__ACT_Initialize() +// This function initializes the ACT hardware and data structures +LIB_EXPORT int +_plat__ACT_Initialize( + void +) +{ + actTicksAllowed = 0; +#define ZERO_ACT(N) ActZero(0x##N, &ACT_##N); + FOR_EACH_ACT(ZERO_ACT) + + return TRUE; +} diff --git a/ta/ftpm/platform/PlatformData.c b/ta/ftpm/platform/PlatformData.c new file mode 100644 index 00000000000..5fcc9dbd987 --- /dev/null +++ b/ta/ftpm/platform/PlatformData.c @@ -0,0 +1,82 @@ +/* Microsoft Reference Implementation for TPM 2.0 + * + * The copyright in this software is being made available under the BSD License, + * included below. This software may be subject to other third party and + * contributor rights, including patent rights, and no such rights are granted + * under this license. + * + * Copyright (c) Microsoft Corporation + * + * All rights reserved. + * + * BSD License + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * Redistributions of source code must retain the above copyright notice, this list + * of conditions and the following disclaimer. + * + * 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. + * + * 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. + */ +//** Description +// This file will instance the TPM variables that are not stack allocated. The +// descriptions for these variables are in Global.h for this project. + +//** Includes +#include "TpmProfile.h" +#include "PlatformData.h" + +// From Cancel.c +BOOL s_isCanceled; + +// From Clock.c +unsigned int s_adjustRate; +BOOL s_timerReset; +BOOL s_timerStopped; + +#ifndef HARDWARE_CLOCK +clock64_t s_realTimePrevious; +clock64_t s_tpmTime; + +clock64_t s_lastSystemTime; +clock64_t s_lastReportedTime; + + +#endif + + +// From LocalityPlat.c +unsigned char s_locality; + +// From Power.c +BOOL s_powerLost; + +// From Entropy.c +// This values is used to determine if the entropy generator is broken. If two +// consecutive values are the same, then the entropy generator is considered to be +// broken. +uint32_t lastEntropy; + + +// For NVMem.c +unsigned char s_NV[NV_MEMORY_SIZE]; +BOOL s_NvIsAvailable; +BOOL s_NV_unrecoverable; +BOOL s_NV_recoverable; + +// From PPPlat.c +BOOL s_physicalPresence; \ No newline at end of file diff --git a/ta/ftpm/platform/PowerPlat.c b/ta/ftpm/platform/PowerPlat.c new file mode 100644 index 00000000000..c562d444b60 --- /dev/null +++ b/ta/ftpm/platform/PowerPlat.c @@ -0,0 +1,113 @@ +/* Microsoft Reference Implementation for TPM 2.0 + * + * The copyright in this software is being made available under the BSD License, + * included below. This software may be subject to other third party and + * contributor rights, including patent rights, and no such rights are granted + * under this license. + * + * Copyright (c) Microsoft Corporation + * + * All rights reserved. + * + * BSD License + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * Redistributions of source code must retain the above copyright notice, this list + * of conditions and the following disclaimer. + * + * 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. + * + * 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. + */ +//** Includes and Function Prototypes + +#include "PlatformData.h" +#include "Platform_fp.h" +#include "_TPM_Init_fp.h" + +//** Functions + +//***_plat__Signal_PowerOn() +// Signal platform power on +LIB_EXPORT int +_plat__Signal_PowerOn( + void + ) +{ + // Reset the timer + _plat__TimerReset(); + + // Need to indicate that we lost power + s_powerLost = TRUE; + + return 0; +} + +//*** _plat__WasPowerLost() +// Test whether power was lost before a _TPM_Init. +// +// This function will clear the "hardware" indication of power loss before return. +// This means that there can only be one spot in the TPM code where this value +// gets read. This method is used here as it is the most difficult to manage in the +// TPM code and, if the hardware actually works this way, it is hard to make it +// look like anything else. So, the burden is placed on the TPM code rather than the +// platform code +// return type: int +// TRUE(1) power was lost +// FALSE(0) power was not lost +LIB_EXPORT int +_plat__WasPowerLost( + void + ) +{ + BOOL retVal = s_powerLost; + s_powerLost = FALSE; + return retVal; +} + +//*** _plat_Signal_Reset() +// This a TPM reset without a power loss. +LIB_EXPORT int +_plat__Signal_Reset( + void + ) +{ + // Initialize locality + s_locality = 0; + + // Command cancel + s_isCanceled = FALSE; + + _TPM_Init(); + + // if we are doing reset but did not have a power failure, then we should + // not need to reload NV ... + + return 0; +} + +//***_plat__Signal_PowerOff() +// Signal platform power off +LIB_EXPORT void +_plat__Signal_PowerOff( + void + ) +{ + // Prepare NV memory for power off + _plat__NVDisable(); + + return; +} \ No newline at end of file diff --git a/ta/ftpm/platform/RunCommand.c b/ta/ftpm/platform/RunCommand.c new file mode 100644 index 00000000000..3fdd51f1b95 --- /dev/null +++ b/ta/ftpm/platform/RunCommand.c @@ -0,0 +1,90 @@ +/* Microsoft Reference Implementation for TPM 2.0 + * + * The copyright in this software is being made available under the BSD License, + * included below. This software may be subject to other third party and + * contributor rights, including patent rights, and no such rights are granted + * under this license. + * + * Copyright (c) Microsoft Corporation + * + * All rights reserved. + * + * BSD License + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * Redistributions of source code must retain the above copyright notice, this list + * of conditions and the following disclaimer. + * + * 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. + * + * 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. + */ +//**Introduction +// This module provides the platform specific entry and fail processing. The +// _plat__RunCommand() function is used to call to ExecuteCommand() in the TPM code. +// This function does whatever processing is necessary to set up the platform +// in anticipation of the call to the TPM including settup for error processing. +// +// The _plat__Fail() function is called when there is a failure in the TPM. The TPM +// code will have set the flag to indicate that the TPM is in failure mode. +// This call will then recursively call ExecuteCommand in order to build the +// failure mode response. When ExecuteCommand() returns to _plat__Fail(), the +// platform will do some platform specif operation to return to the environment in +// which the TPM is executing. For a simulator, setjmp/longjmp is used. For an OS, +// a system exit to the OS would be appropriate. + +//** Includes and locals +#include "PlatformData.h" +#include "Platform_fp.h" +#include +#include "ExecCommand_fp.h" + +#include +#include + +jmp_buf s_jumpBuffer; + +//** Functions + +//***_plat__RunCommand() +// This version of RunCommand will set up a jum_buf and call ExecuteCommand(). If +// the command executes without failing, it will return and RunCommand will return. +// If there is a failure in the command, then _plat__Fail() is called and it will +// longjump back to RunCommand which will call ExecuteCommand again. However, this +// time, the TPM will be in failure mode so ExecuteCommand will simply build +// a failure response and return. +LIB_EXPORT void +_plat__RunCommand( + uint32_t requestSize, // IN: command buffer size + unsigned char *request, // IN: command buffer + uint32_t *responseSize, // IN/OUT: response buffer size + unsigned char **response // IN/OUT: response buffer + ) +{ + setjmp(s_jumpBuffer); + ExecuteCommand(requestSize, request, responseSize, response); +} + + +//***_plat__Fail() +// This is the platform depended failure exit for the TPM. +LIB_EXPORT NORETURN void +_plat__Fail( + void + ) +{ + TEE_Panic(TEE_ERROR_BAD_STATE); +} \ No newline at end of file diff --git a/ta/ftpm/platform/Unique.c b/ta/ftpm/platform/Unique.c new file mode 100644 index 00000000000..47026704d11 --- /dev/null +++ b/ta/ftpm/platform/Unique.c @@ -0,0 +1,102 @@ +/* Microsoft Reference Implementation for TPM 2.0 + * + * The copyright in this software is being made available under the BSD License, + * included below. This software may be subject to other third party and + * contributor rights, including patent rights, and no such rights are granted + * under this license. + * + * Copyright (c) Microsoft Corporation + * + * All rights reserved. + * + * BSD License + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * Redistributions of source code must retain the above copyright notice, this list + * of conditions and the following disclaimer. + * + * 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. + * + * 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. + */ +//** Introduction +// In some implementations of the TPM, the hardware can provide a secret +// value to the TPM. This secret value is statistically unique to the +// instance of the TPM. Typical uses of this value are to provide +// personalization to the random number generation and as a shared secret +// between the TPM and the manufacturer. + +//** Includes +#include "PlatformData.h" +#include "Platform_fp.h" + +#include +#include + +//static TEE_UUID deviceUniqueValue = { 0 }; +static char *deviceUniqueValue[sizeof(TEE_UUID)+1]; +static bool initializedUniqueValue = false; + +//** _plat__GetUnique() +// This function is used to access the platform-specific unique value. +// This function places the unique value in the provided buffer ('b') +// and returns the number of bytes transferred. The function will not +// copy more data than 'bSize'. +// NOTE: If a platform unique value has unequal distribution of uniqueness +// and 'bSize' is smaller than the size of the unique value, the 'bSize' +// portion with the most uniqueness should be returned. +LIB_EXPORT uint32_t +_plat__GetUnique( + uint32_t which, // authorities (0) or details + uint32_t bSize, // size of the buffer + unsigned char *b // output buffer + ) +{ + const char *from = (char *)&deviceUniqueValue; + uint32_t uSize = sizeof(TEE_UUID) + 1; + uint32_t retVal = 0; + TEE_Result teeResult; + + // Check if we've initialized our unique platform value. + if (!initializedUniqueValue) { + teeResult = TEE_GetPropertyAsUUID(TEE_PROPSET_TEE_IMPLEMENTATION, + "gpd.tee.deviceID", + (TEE_UUID*)&deviceUniqueValue); + assert(teeResult == TEE_SUCCESS); + } + deviceUniqueValue[uSize-1] = '\0'; + + if(which == 0) // the authorities value + { + for(retVal = 0; + *from != 0 && retVal < bSize; + retVal++) + { + *b++ = *from++; + } + } + else + { + b = &b[((bSize < uSize) ? bSize : uSize) - 1]; + for(retVal = 0; + *from != 0 && retVal < bSize; + retVal++) + { + *b-- = *from++; + } + } + return retVal; +} \ No newline at end of file diff --git a/ta/ftpm/platform/fTPM_event_log.c b/ta/ftpm/platform/fTPM_event_log.c new file mode 100644 index 00000000000..27f52b42e68 --- /dev/null +++ b/ta/ftpm/platform/fTPM_event_log.c @@ -0,0 +1,391 @@ +/* + * Copyright (c) 2021, Arm Limited. All rights reserved. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +/* + * Global variables. + */ +static bool log_extended = false; +static id_event_struct_header_t *event_header_ptr; + +static int check_header_digest(const unsigned char *const digest) +{ + /* + * Checks the header digest according to section 5.3 of + * TCG EFI Protocol Specification. Family 2.0. Level 00 Revision 00.13 + * March 30, 2016. + */ + + unsigned int i; + + for (i = 0U; i < HEADER_DIGEST_SIZE; i++) { + if (digest[i] != 0) { + return 0; + } + } + + return 1; +} + +/* + * Function to process a TPM event log header. + * + * @buf_index Offset where the header is expected to start in the event log. + * @buf Pointer to a buffer where the TPM event log is. + * @log_size Size of the TPM event log. + * + * The function returns the offset on the event log after the header. + */ +static unsigned int process_header(unsigned int buf_index, + const unsigned char *const buf, + const size_t log_size) +{ + uint32_t event_size; + uint32_t digest_size; + uint8_t vendor_info_size; + + if (buf_index + sizeof(tcg_pcr_event_t) + sizeof(id_event_struct_header_t) + >= log_size) { +#ifdef fTPMDebug + EMSG("TPM Event log header extends beyond the scope of the event log buffer\n"); +#endif + } + + /* + * Check PcrIndex. + */ + if (*((uint32_t *)(buf + buf_index)) != 0U) { + /* + * PCR Index must be 0 on the header. + * Ref. Section 5.3 of TCG EFI Protocol Specification. Family 2.0 + * Level 00 Revision 00.13. March 30, 2016 + */ + return 0U; + } + buf_index += sizeof(uint32_t); + + /* + * Check EventType + */ + if (*((uint32_t *)(buf + buf_index)) != EV_NO_ACTION) { + /* + * Event type must be EV_NO_ACTION on the header. + * Ref. Section 5.3 of TCG EFI Protocol Specification. Family 2.0 + * Level 00 Revision 00.13. March 30, 2016 + */ + return 0U; + } + buf_index += sizeof(uint32_t); + + if (!check_header_digest(buf + buf_index)) { + return 0U; + } + + buf_index += HEADER_DIGEST_SIZE; + + memcpy(&event_size, buf + buf_index, sizeof(event_size)); + buf_index += sizeof(event_size); + + event_header_ptr = (id_event_struct_header_t *)(buf + buf_index); + + buf_index += sizeof(id_event_struct_header_t); + + digest_size = (event_header_ptr->number_of_algorithms * + sizeof(id_event_algorithm_size_t)); + + if (buf_index + digest_size >= log_size) { +#ifdef fTPMDebug + EMSG("TPM Event log header extends beyond the scope of the event log buffer\n"); +#endif + event_header_ptr = NULL; + return 0U; + } + + buf_index += digest_size; + + if (buf_index + sizeof(vendor_info_size) >= log_size) { +#ifdef fTPMDebug + EMSG("TPM Event log header extends beyond the scope of the event log buffer\n"); +#endif + event_header_ptr = NULL; + return 0U; + } + + memcpy(&vendor_info_size, buf + buf_index, sizeof(vendor_info_size)); + + if (digest_size + vendor_info_size + sizeof(vendor_info_size) + + sizeof(id_event_struct_header_t) != event_size) { +#ifdef fTPMDebug + EMSG("The parsed event size does not match the event size on the header\n"); +#endif + return 0U; + } + + buf_index += sizeof(vendor_info_size); + + if (buf_index + vendor_info_size > log_size) { +#ifdef fTPMDebug + EMSG("Event size larger than the log size\n"); +#endif + event_header_ptr = NULL; + return 0U; + } + + /* + * Skips the vendor info. + */ + buf_index += vendor_info_size; + + return buf_index; +} + +/* + * Function to proccess (and extend) an event from the TPM event log. + * + * @buf_index Offset where the event is expected to start in the event log. + * @buf Pointer to a buffer where the TPM event log is. + * @log_size Size of the TPM event log. + * + * The function returns the offset of the next event in the TPM event log + * or 0 if fails. + */ +static unsigned int process_event(unsigned int buf_index, + const unsigned char *const buf, + const size_t log_size) +{ + TPM2_PCR_EXTEND_COMMAND cmd; + unsigned char *digest_array; + uint32_t count; + uint32_t event_size; + uint16_t alg_id; + unsigned int digest_size; + unsigned int i; + unsigned char *response; + uint32_t resplen; + event2_header_t event; + void *cmd_end = (void *)(&cmd + 1); + + if (buf_index + sizeof(event2_header_t) >= log_size) { +#ifdef fTPMDebug + EMSG("Event header size larger than the log size\n"); +#endif + return 0U; + } + + memcpy(&event, buf + buf_index, sizeof(event2_header_t)); + buf_index += sizeof(event2_header_t); + + if (event.digests.count > HASH_COUNT) { +#ifdef fTPMDebug + EMSG("Number of digests on this event exceeds the maximum allowed\n"); +#endif + return 0U; + } + + memset(&cmd, 0, sizeof(TPM2_PCR_EXTEND_COMMAND)); + + cmd.Header.paramSize = sizeof(cmd.PcrHandle) + + sizeof(cmd.AuthorizationSize) + + sizeof(cmd.Header); + + cmd.PcrHandle = SwapBytes32(event.pcr_index); + + cmd.Header.commandCode = SwapBytes32(TPM_PCR_EXTEND); + cmd.Header.tag = SwapBytes16(TPM_ST_SESS); + + /* + * We are not using authorization sessions in this prototype code so + * populate the auth session info based on how it is handled in + * CopyAuthSessionCommand() with a NULL auth session. See + * SecurityPkg/Library/Tpm2CommandLib/Tpm2Help.c in EDK2. + */ + cmd.AuthSessionPcr.sessionHandle = SwapBytes32(TPM_RS_PW); + cmd.AuthSessionPcr.nonce.b.size = 0U; + *((uint8_t *)&cmd.AuthSessionPcr.sessionAttributes) = 0U; + cmd.AuthSessionPcr.hmac.b.size = 0U; + cmd.AuthorizationSize = SwapBytes32(AUTH_SIZE); + cmd.Header.paramSize += (AUTH_SIZE); + + /* + * As we are not using authorization sessions for this prototype, + * AuthSessionPcr is empty and therefore the digests are allocated + * straight after the empty AuthSessionPcr structure, so make the + * pointer for the digests to point right after the empty + * AuthSessionPcr structure. + */ + digest_array = ((uint8_t *)&cmd.AuthSessionPcr) + AUTH_SIZE; + + /* + * Populate the digest. + */ + count = SwapBytes32(event.digests.count); + memcpy(digest_array, &count, sizeof(count)); + digest_array += sizeof(count); + + cmd.Header.paramSize += sizeof(count); + + for (i = 0U; i < event.digests.count; i++) { + unsigned int j; + + if (buf_index + sizeof(alg_id) >= log_size) { + return 0U; + } + memcpy(&alg_id, buf + buf_index, sizeof(alg_id)); + alg_id = SwapBytes16(alg_id); + buf_index += sizeof(alg_id); + /* + * Algorithm ID. + */ + if ((void *)(digest_array + sizeof(alg_id)) >= cmd_end) { +#ifdef fTPMDebug + EMSG("Not enough space for digest %u of %u\n", i, + event.digests.count); +#endif + return 0U; + } + memcpy(digest_array, &alg_id, sizeof(alg_id)); + digest_array += sizeof(alg_id); + cmd.Header.paramSize += sizeof(alg_id); + + for (j = 0U; j < event_header_ptr->number_of_algorithms; j++) { + if (SwapBytes16(alg_id) == + event_header_ptr->digest_size[i].algorithm_id) { + digest_size = event_header_ptr->digest_size[i].digest_size; + break; + } + } + + if (j > event_header_ptr->number_of_algorithms) { +#ifdef fTPMDebug + EMSG("Algorithm ID %i not found\n", alg_id); +#endif + return 0U; + } + + cmd.Header.paramSize += digest_size; + + if (buf_index + digest_size >= log_size || + digest_size > (sizeof(TPMT_HA) - sizeof(TPMI_ALG_HASH))) { + /* + * Sanity check: If the log extends beyond the + * maximum size of the log buffer or if the digest is + * bigger than the allocated space on the command structure, abort. + */ +#ifdef fTPMDebug + EMSG("Log extends beyond the maximum size of the log buffer.\n"); + EMSG("alg_id = %i\n", alg_id); + EMSG("log_size = %i\n", log_size); + EMSG("buf_index = %i, digest_size = %i\n", buf_index, digest_size); + EMSG("TPMH_HA = %i\n", sizeof(TPMT_HA)); + EMSG("TPMI_ALG_HASH = %i\n", sizeof(TPMI_ALG_HASH)); +#endif + return 0U; + } + memcpy(digest_array, buf + buf_index, digest_size); + digest_array += digest_size; + buf_index += digest_size; + } + + cmd.Header.paramSize = SwapBytes32(cmd.Header.paramSize); + + if (buf_index + sizeof(event2_data_t) > log_size) { + return 0U; + } + memcpy(&event_size, buf + buf_index, sizeof(event_size)); + buf_index += sizeof(event_size); + buf_index += event_size; + + if (buf_index > log_size) { +#ifdef fTPMDebug + EMSG("The event log extends beyond the log buffer:"); + EMSG("\tbuf_index = %i, log_size = %i\n", buf_index, log_size); +#endif + return 0U; + } + + resplen = 1024; + response = (unsigned char *)malloc(resplen); + + if (response == NULL) { +#ifdef fTPMDebug + EMSG("Not enough memory to allocate a response\n"); +#endif + return 0U; + } + + memset(response, 0, resplen); + + ExecuteCommand(SwapBytes32(cmd.Header.paramSize), &cmd, + &resplen, &response); + +#ifdef fTPMDebug + uint16_t ret_tag; + uint32_t resp_size; + uint32_t tpm_rc; + + memcpy(&ret_tag, response, sizeof(ret_tag)); + memcpy(&resp_size, response + sizeof(ret_tag), sizeof(resp_size)); + memcpy(&tpm_rc, response + sizeof(ret_tag) + sizeof(resp_size), + sizeof(tpm_rc)); + + MSG("TPM2_PCR_EXTEND_COMMAND returned value:\n"); + MSG("\tret_tag = 0x%.4x, size = 0x%.8x, rc = 0x%.8x\n", + SwapBytes16(ret_tag), SwapBytes32(resp_size), SwapBytes32(tpm_rc)); +#endif + + free(response); + + return buf_index; +} + +bool process_eventlog(const unsigned char *const buf, const size_t log_size) +{ + unsigned int buf_index = 0U; + unsigned int event_count = 0U; + + if (log_extended == true) { +#ifdef fTPMDebug + MSG("The event log has already been extended. Ignoring\n"); +#endif + return false; + } + + log_extended = true; + buf_index = process_header(buf_index, buf, log_size); + if (buf_index == 0) { +#ifdef fTPMDebug + EMSG("Fail to process TPM event log header. Skiping.\n"); +#endif + return false; + } + + while (buf_index < log_size) { + /* + * Process the rest of the Event Log. + */ + buf_index = process_event(buf_index, buf, log_size); + event_count++; + } + +#ifdef fTPMDebug + MSG("%i Event logs processed\n", event_count); +#endif + + event_header_ptr = NULL; + + return true; +} diff --git a/ta/ftpm/platform/fTPM_helpers.c b/ta/ftpm/platform/fTPM_helpers.c new file mode 100644 index 00000000000..98368614ec1 --- /dev/null +++ b/ta/ftpm/platform/fTPM_helpers.c @@ -0,0 +1,26 @@ +/* + * Copyright (c) 2021, Arm Limited. All rights reserved. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +#include + +// +// Helper functions for byte ordering of TPM commands/responses +// +uint16_t SwapBytes16(uint16_t Value) +{ + return (uint16_t)((Value << 8) | (Value >> 8)); +} + +uint32_t SwapBytes32(uint32_t Value) +{ + uint32_t LowerBytes; + uint32_t HigherBytes; + + LowerBytes = (uint32_t)SwapBytes16((uint16_t)Value); + HigherBytes = (uint32_t)SwapBytes16((uint16_t)(Value >> 16)); + + return (LowerBytes << 16 | HigherBytes); +} diff --git a/ta/ftpm/platform/include/Admin.h b/ta/ftpm/platform/include/Admin.h new file mode 100644 index 00000000000..84efcaf7aa9 --- /dev/null +++ b/ta/ftpm/platform/include/Admin.h @@ -0,0 +1,230 @@ +/* Microsoft Reference Implementation for TPM 2.0 + * + * The copyright in this software is being made available under the BSD License, + * included below. This software may be subject to other third party and + * contributor rights, including patent rights, and no such rights are granted + * under this license. + * + * Copyright (c) Microsoft Corporation + * + * All rights reserved. + * + * BSD License + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * Redistributions of source code must retain the above copyright notice, this list + * of conditions and the following disclaimer. + * + * 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. + * + * 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. + */ + +//**Introduction +/* + This file contains the admin interfaces. +*/ + +#ifndef _ADMIN_H +#define _ADMIN_H + +//**Includes +#include +#include +#include "swap.h" +#include "TpmProfile.h" +#include "TpmSal.h" +#include "TpmError.h" + +// Parameter reference and types from ref impl headers +#ifndef UNREFERENCED_PARAMETER +#define UNREFERENCED_PARAMETER(a) do { (void)(a); } while (0) +#endif + +#define FAIL(errorCode) (TpmFail(__FUNCTION__, __LINE__, errorCode)) + +#if defined(EMPTY_ASSERT) +#define pAssert(a) ((void)0) +#else +#define pAssert(a) \ + do { \ + if (!(a)) { \ + EMSG("## ASSERT:" #a "##\n"); \ + FAIL(FATAL_ERROR_PARAMETER); \ + } \ + } while (0) +#endif + +#if defined(__GNUC__) +typedef unsigned char UCHAR; +typedef unsigned char * PUCHAR; +typedef void VOID; +typedef void * PVOID; +#endif + +// Admin space tacked on to NV, padded out to NV_BLOCK_SIZE alignment. +#define NV_TPM_STATE_SIZE 0x200 + +// Actual size of Admin space used. (See note in NVMem.c) +#define TPM_STATE_SIZE 0x10 + +// Select TPM types/defines for AdminPPI.c +typedef UINT16 TPM_ST; +#define TPM_ST_NO_SESSIONS (TPM_ST)(0x8001) + +typedef UINT32 TPM_RC; +#define TPM_RC_SUCCESS (TPM_RC)(0x000) +#define RC_VER1 (TPM_RC)(0x100) +#define TPM_RC_BAD_TAG (TPM_RC)(0x01E) +#define TPM_RC_FAILURE (TPM_RC)(RC_VER1+0x001) +#define TPM_RC_COMMAND_SIZE (TPM_RC)(RC_VER1+0x042) + +// Chip flags +typedef union { + UINT32 flags; + struct { + UINT32 Remanufacture : 1; // Ignored on OpTEE platforms + UINT32 TpmStatePresent : 1; // Set when sate present (startup STATE) + UINT32 Reserved : 30; + } fields; +} TPM_CHIP_STATE; + +// +// The current NV Chip state +// +extern TPM_CHIP_STATE g_chipFlags; + +// +// Simulated Physical Presence Interface (PPI) +// +#define FTPM_PPI_CMD_QUERY 0 +#define FTPM_PPI_CMD_VERSION 1 +#define FTPM_PPI_CMD_SUBMIT_OP_REQ 2 +#define FTPM_PPI_CMD_GET_PENDING_OP 3 +#define FTPM_PPI_CMD_GET_PLATFORM_ACTION 4 +#define FTPM_PPI_CMD_RETURN_OP_RESP 5 +#define FTPM_PPI_CMD_SUBMIT_USER_LANG 6 +#define FTPM_PPI_CMD_SUBMIT_OP_REQ2 7 +#define FTPM_PPI_CMD_GET_USER_CONF 8 + +#define FTPM_PPI_OP_NOP 0 +#define FTPM_PPI_OP_ENABLE 1 +#define FTPM_PPI_OP_DISABLE 2 +#define FTPM_PPI_OP_ACTIVATE 3 +#define FTPM_PPI_OP_DEACTIVATE 4 +#define FTPM_PPI_OP_CLEAR 5 +#define FTPM_PPI_OP_E_A 6 +#define FTPM_PPI_OP_D_D 7 +#define FTPM_PPI_OP_OWNERINSTALL_TRUE 8 +#define FTPM_PPI_OP_OWNERINSTALL_FALSE 9 +#define FTPM_PPI_OP_E_A_OI_TRUE 10 +#define FTPM_PPI_OP_OI_FALSE_D_D 11 +#define FTPM_PPI_OP_FIELD_UPGRADE 12 +#define FTPM_PPI_OP_OPERATOR_AUTH 13 +#define FTPM_PPI_OP_C_E_A 14 +#define FTPM_PPI_OP_SET_NO_PROV_FALSE 15 +#define FTPM_PPI_OP_SET_NO_PROV_TRUE 16 +#define FTPM_PPI_OP_SET_NO_CLEAR_FALSE 17 +#define FTPM_PPI_OP_SET_NO_CLEAR_TRUE 18 +#define FTPM_PPI_OP_SET_NO_MAINT_FALSE 19 +#define FTPM_PPI_OP_SET_NO_MAINT_TRUE 20 +#define FTPM_PPI_OP_E_A_C 21 +#define FTPM_PPI_OP_E_A_C_E_A 22 +#define FTPM_PPI_OP_RESERVED_FIRST 23 +#define FTPM_PPI_OP_RESERVED_LAST 127 +#define FTPM_PPI_OP_VENDOR_FIRST 128 + +#define FTPM_PPI_VERSION 0x00322E31 // "1.2" + +#define FTPM_PPI_OP_NOT_IMPLEMENTED 0xFFFFFFFF // Any Op other than E_A_C_E_A + +#pragma pack(1) +typedef struct { + UINT32 PendingPseudoOp; + UINT32 PseudoOpFromLastBoot; + UINT32 ReturnResponse; +} FTPM_PPI_STATE; +#pragma pack() + +// +// The types of TPM runtime state stored to NV +// +typedef enum { + NV_TPM_STATE_FLAGS = 0, + NV_TPM_STATE_PPI, + NV_TPM_STATE_LAST // A mark of the end of the TPM state +} NV_TPM_STATE; + +//***_admin__NvInitState() +// Initialize the NV admin state +void +_admin__NvInitState(); + +//***_admin__NvReadState() +// Read TPM state data from NV memory to RAM +void +_admin__NvReadState( + NV_TPM_STATE type, // IN: type of state data + void *buffer // OUT: data buffer + ); + +//***_admin__NvWriteState() +// Write TPM state data to NV memory +void +_admin__NvWriteState( + NV_TPM_STATE type, // IN: type of state data + void *buffer // IN: data buffer + ); + +// +// Save and restore runtime state +// + + +//***_admin__SaveChipFlags() +// Save the g_chipFlags runtime state +void +_admin__SaveChipFlags(); + +//***_admin__RestoreChipFlags() +// Restore the g_chipFlags runtime state +void +_admin__RestoreChipFlags(); + +//***_admin__SavePPIState() +// Save the s_PPIState runtime state +void +_admin__SavePPIState(); + +//***_admin__RestorePPIState() +// Restore the s_PPIState runtime state +void +_admin__RestorePPIState(); + +//***_admin__PPICommand() +// Returns 1 when PPI command has been consumed +// Returns 0 when it is not a properly formated PPI command, +// caller should pass through to TPM +// +int +_admin__PPICommand( + UINT32 CommandSize, + __in_ecount(CommandSize) UINT8 *CommandBuffer, + UINT32 *ResponseSize, + __deref_out_ecount(*ResponseSize) UINT8 **ResponseBuffer +); + +#endif diff --git a/ta/ftpm/platform/include/Platform.h b/ta/ftpm/platform/include/Platform.h new file mode 100644 index 00000000000..b95a1932e27 --- /dev/null +++ b/ta/ftpm/platform/include/Platform.h @@ -0,0 +1,52 @@ +/* Microsoft Reference Implementation for TPM 2.0 + * + * The copyright in this software is being made available under the BSD License, + * included below. This software may be subject to other third party and + * contributor rights, including patent rights, and no such rights are granted + * under this license. + * + * Copyright (c) Microsoft Corporation + * + * All rights reserved. + * + * BSD License + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * Redistributions of source code must retain the above copyright notice, this list + * of conditions and the following disclaimer. + * + * 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. + * + * 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 _PLATFORM_H_ +#define _PLATFORM_H_ + +#include "TpmBuildSwitches.h" +#include "BaseTypes.h" +#include "TPMB.h" +#include "MinMax.h" + +#include "TpmProfile.h" + +#include "PlatformACT.h" +#include "PlatformClock.h" +#include "PlatformData.h" +#include "Platform_fp.h" + + +#endif // _PLATFORM_H_ diff --git a/ta/ftpm/platform/include/PlatformData.h b/ta/ftpm/platform/include/PlatformData.h new file mode 100644 index 00000000000..f05493b7639 --- /dev/null +++ b/ta/ftpm/platform/include/PlatformData.h @@ -0,0 +1,137 @@ +/* Microsoft Reference Implementation for TPM 2.0 + * + * The copyright in this software is being made available under the BSD License, + * included below. This software may be subject to other third party and + * contributor rights, including patent rights, and no such rights are granted + * under this license. + * + * Copyright (c) Microsoft Corporation + * + * All rights reserved. + * + * BSD License + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * Redistributions of source code must retain the above copyright notice, this list + * of conditions and the following disclaimer. + * + * 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. + * + * 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. + */ +// This file contains the instance data for the Platform module. It is collected +// in this file so that the state of the module is easier to manage. + +#ifndef _PLATFORM_DATA_H_ +#define _PLATFORM_DATA_H_ + + +#include "TpmProfile.h" + +// From Cancel.c +// Cancel flag. It is initialized as FALSE, which indicate the command is not +// being canceled +extern int s_isCanceled; + +#ifndef HARDWARE_CLOCK +typedef uint64_t clock64_t; +// This is the value returned the last time that the system clock was read. This +// is only relevant for a simulator or virtual TPM. +extern clock64_t s_realTimePrevious; + +// These values are used to try to synthesize a long lived version of clock(). +extern clock64_t s_lastSystemTime; +extern clock64_t s_lastReportedTime; + +// This is the rate adjusted value that is the equivalent of what would be read from +// a hardware register that produced rate adjusted time. +extern clock64_t s_tpmTime; +#endif // HARDWARE_CLOCK + +// This value indicates that the timer was reset +extern BOOL s_timerReset; +// This value indicates that the timer was stopped. It causes a clock discontinuity. +extern BOOL s_timerStopped; + +// CLOCK_NOMINAL is the number of hardware ticks per mS. A value of 300000 means +// that the nominal clock rate used to drive the hardware clock is 30 MHz. The +// adjustment rates are used to determine the conversion of the hardware ticks to +// internal hardware clock value. In practice, we would expect that there woudl be +// a hardware register will accumulated mS. It would be incremented by the output +// of a pre-scaler. The pre-scaler would divide the ticks from the clock by some +// value that would compensate for the difference between clock time and real time. +// The code in Clock does the emulation of this function. +#define CLOCK_NOMINAL 30000 +// A 1% change in rate is 300 counts +#define CLOCK_ADJUST_COARSE 300 +// A 0.1% change in rate is 30 counts +#define CLOCK_ADJUST_MEDIUM 30 +// A minimum change in rate is 1 count +#define CLOCK_ADJUST_FINE 1 +// The clock tolerance is +/-15% (4500 counts) +// Allow some guard band (16.7%) +#define CLOCK_ADJUST_LIMIT 5000 + +// This variable records the time when _plat__TimerReset is called. This mechanism +// allow us to subtract the time when TPM is power off from the total +// time reported by clock() function +extern uint64_t s_initClock; + +// This variable records the timer adjustment factor. +extern unsigned int s_adjustRate; + +// For LocalityPlat.c +// Locality of current command +extern unsigned char s_locality; + +// For NVMem.c +// Choose if the NV memory should be backed by RAM or by file. +// If this macro is defined, then a file is used as NV. If it is not defined, +// then RAM is used to back NV memory. Comment out to use RAM. + +#if (!defined VTPM) || ((VTPM != NO) && (VTPM != YES)) +# undef VTPM +# define VTPM YES // Default: Either YES or NO +#endif + +// For a simulation, use a file to back up the NV +#if (!defined FILE_BACKED_NV) || ((FILE_BACKED_NV != NO) && (FILE_BACKED_NV != YES)) +# undef FILE_BACKED_NV +# define FILE_BACKED_NV (VTPM && YES) // Default: Either YES or NO +#endif + +#if !SIMULATION +# undef FILE_BACKED_NV +# define FILE_BACKED_NV NO +#endif // SIMULATION + +extern unsigned char s_NV[NV_MEMORY_SIZE]; +extern BOOL s_NvIsAvailable; +extern BOOL s_NV_unrecoverable; +extern BOOL s_NV_recoverable; + + +// For PPPlat.c +// Physical presence. It is initialized to FALSE +extern BOOL s_physicalPresence; + +// From Power +extern BOOL s_powerLost; + +// For Entropy.c +extern uint32_t lastEntropy; + +#endif // _PLATFORM_DATA_H_ diff --git a/ta/ftpm/platform/include/Platform_fp.h b/ta/ftpm/platform/include/Platform_fp.h new file mode 100644 index 00000000000..74069e69ab8 --- /dev/null +++ b/ta/ftpm/platform/include/Platform_fp.h @@ -0,0 +1,492 @@ +/* Microsoft Reference Implementation for TPM 2.0 + * + * The copyright in this software is being made available under the BSD License, + * included below. This software may be subject to other third party and + * contributor rights, including patent rights, and no such rights are granted + * under this license. + * + * Copyright (c) Microsoft Corporation + * + * All rights reserved. + * + * BSD License + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * Redistributions of source code must retain the above copyright notice, this list + * of conditions and the following disclaimer. + * + * 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. + * + * 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. + */ +/*(Auto-generated) + * Created by TpmPrototypes; Version 3.0 July 18, 2017 + * Date: Aug 7, 2018 Time: 03:39:35PM + */ + +#ifndef _PLATFORM_FP_H_ +#define _PLATFORM_FP_H_ + +//** From EPS.c + +LIB_EXPORT void +_plat__GetEPS(UINT16 Size, uint8_t *EndorsementSeed); + +//** From Cancel.c + +//***_plat__IsCanceled() +// Check if the cancel flag is set +// return type: BOOL +// TRUE(1) if cancel flag is set +// FALSE(0) if cancel flag is not set +LIB_EXPORT int +_plat__IsCanceled( + void + ); + +// Set cancel flag. +LIB_EXPORT void +_plat__SetCancel( + void + ); + +//***_plat__ClearCancel() +// Clear cancel flag +LIB_EXPORT void +_plat__ClearCancel( + void + ); + + +//** From Clock.c + +//***_plat__TimerReset() +// This function sets current system clock time as t0 for counting TPM time. +// This function is called at a power on event to reset the clock. When the clock +// is reset, the indication that the clock was stopped is also set. +LIB_EXPORT void +_plat__TimerReset( + void + ); + +//*** _plat__TimerRestart() +// This function should be called in order to simulate the restart of the timer +// should it be stopped while power is still applied. +LIB_EXPORT void +_plat__TimerRestart( + void + ); + +//*** _plat__RealTime() +// This is another, probably futile, attempt to define a portable function +// that will return a 64-bit clock value that has mSec resolution. +uint64_t +_plat__RealTime( + void +); + +//***_plat__TimerRead() +// This function provides access to the tick timer of the platform. The TPM code +// uses this value to drive the TPM Clock. +// +// The tick timer is supposed to run when power is applied to the device. This timer +// should not be reset by time events including _TPM_Init. It should only be reset +// when TPM power is re-applied. +// +// If the TPM is run in a protected environment, that environment may provide the +// tick time to the TPM as long as the time provided by the environment is not +// allowed to go backwards. If the time provided by the system can go backwards +// during a power discontinuity, then the _plat__Signal_PowerOn should call +// _plat__TimerReset(). +LIB_EXPORT uint64_t +_plat__TimerRead( + void + ); + +//*** _plat__TimerWasReset() +// This function is used to interrogate the flag indicating if the tick timer has +// been reset. +// +// If the resetFlag parameter is SET, then the flag will be CLEAR before the +// function returns. +LIB_EXPORT BOOL +_plat__TimerWasReset( + void + ); + +//*** _plat__TimerWasStopped() +// This function is used to interrogate the flag indicating if the tick timer has +// been stopped. If so, this is typically a reason to roll the nonce. +// +// This function will CLEAR the s_timerStopped flag before returning. This provides +// functionality that is similar to status register that is cleared when read. This +// is the model used here because it is the one that has the most impact on the TPM +// code as the flag can only be accessed by one entity in the TPM. Any other +// implementation of the hardware can be made to look like a read-once register. +LIB_EXPORT BOOL +_plat__TimerWasStopped( + void + ); + +//***_plat__ClockAdjustRate() +// Adjust the clock rate +LIB_EXPORT void +_plat__ClockAdjustRate( + int adjust // IN: the adjust number. It could be positive + // or negative + ); + + +//** From Entropy.c + +//** _plat__GetEntropy() +// This function is used to get available hardware entropy. In a hardware +// implementation of this function, there would be no call to the system +// to get entropy. +// return type: int32_t +// < 0 hardware failure of the entropy generator, this is sticky +// >= 0 the returned amount of entropy (bytes) +// +LIB_EXPORT int32_t +_plat__GetEntropy( + unsigned char *entropy, // output buffer + uint32_t amount // amount requested + ); + + +//** From LocalityPlat.c + +//***_plat__LocalityGet() +// Get the most recent command locality in locality value form. +// This is an integer value for locality and not a locality structure +// The locality can be 0-4 or 32-255. 5-31 is not allowed. +LIB_EXPORT unsigned char +_plat__LocalityGet( + void + ); + +//***_plat__LocalitySet() +// Set the most recent command locality in locality value form +LIB_EXPORT void +_plat__LocalitySet( + unsigned char locality + ); + + +//** From NVMem.c + +//*** _plat__NvErrors() +// This function is used by the simulator to set the error flags in the NV +// subsystem to simulate an error in the NV loading process +LIB_EXPORT void +_plat__NvErrors( + int recoverable, + int unrecoverable + ); + +//***_plat__NVEnable() +// Enable NV memory. +// +// This version just pulls in data from a file. In a real TPM, with NV on chip, +// this function would verify the integrity of the saved context. If the NV +// memory was not on chip but was in something like RPMB, the NV state would be +// read in, decrypted and integrity checked. +// +// The recovery from an integrity failure depends on where the error occurred. It +// it was in the state that is discarded by TPM Reset, then the error is +// recoverable if the TPM is reset. Otherwise, the TPM must go into failure mode. +// return type: int +// 0 if success +// > 0 if receive recoverable error +// <0 if unrecoverable error +LIB_EXPORT int +_plat__NVEnable( + void *platParameter // IN: platform specific parameters + ); + +//***_plat__NVDisable() +// Disable NV memory +LIB_EXPORT void +_plat__NVDisable( + void + ); + +//***_plat__IsNvAvailable() +// Check if NV is available +// return type: int +// 0 NV is available +// 1 NV is not available due to write failure +// 2 NV is not available due to rate limit +LIB_EXPORT int +_plat__IsNvAvailable( + void + ); + +//***_plat__NvMemoryRead() +// Function: Read a chunk of NV memory +LIB_EXPORT void +_plat__NvMemoryRead( + unsigned int startOffset, // IN: read start + unsigned int size, // IN: size of bytes to read + void *data // OUT: data buffer + ); + +//*** _plat__NvIsDifferent() +// This function checks to see if the NV is different from the test value. This is +// so that NV will not be written if it has not changed. +// return value: int +// TRUE(1) the NV location is different from the test value +// FALSE(0) the NV location is the same as the test value +LIB_EXPORT int +_plat__NvIsDifferent( + unsigned int startOffset, // IN: read start + unsigned int size, // IN: size of bytes to read + void *data // IN: data buffer + ); + +//***_plat__NvMemoryWrite() +// This function is used to update NV memory. The "write" is to a memory copy of +// NV. At the end of the current command, any changes are written to +// the actual NV memory. +// NOTE: A useful optimization would be for this code to compare the current +// contents of NV with the local copy and note the blocks that have changed. Then +// only write those blocks when _plat__NvCommit() is called. +LIB_EXPORT int +_plat__NvMemoryWrite( + unsigned int startOffset, // IN: write start + unsigned int size, // IN: size of bytes to write + void *data // OUT: data buffer + ); + +//***_plat__NvMemoryClear() +// Function is used to set a range of NV memory bytes to an implementation-dependent +// value. The value represents the erase state of the memory. +LIB_EXPORT void +_plat__NvMemoryClear( + unsigned int start, // IN: clear start + unsigned int size // IN: number of bytes to clear + ); + +//***_plat__NvMemoryMove() +// Function: Move a chunk of NV memory from source to destination +// This function should ensure that if there overlap, the original data is +// copied before it is written +LIB_EXPORT void +_plat__NvMemoryMove( + unsigned int sourceOffset, // IN: source offset + unsigned int destOffset, // IN: destination offset + unsigned int size // IN: size of data being moved + ); + +//***_plat__NvCommit() +// This function writes the local copy of NV to NV for permanent store. It will write +// NV_MEMORY_SIZE bytes to NV. If a file is use, the entire file is written. +// return type: int +// 0 NV write success +// non-0 NV write fail +LIB_EXPORT int +_plat__NvCommit( + void + ); + +//***_plat__SetNvAvail() +// Set the current NV state to available. This function is for testing purpose +// only. It is not part of the platform NV logic +LIB_EXPORT void +_plat__SetNvAvail( + void + ); + +//***_plat__ClearNvAvail() +// Set the current NV state to unavailable. This function is for testing purpose +// only. It is not part of the platform NV logic +LIB_EXPORT void +_plat__ClearNvAvail( + void + ); + + +//** From PowerPlat.c + +//***_plat__Signal_PowerOn() +// Signal platform power on +LIB_EXPORT int +_plat__Signal_PowerOn( + void + ); + +//*** _plat__WasPowerLost() +// Test whether power was lost before a _TPM_Init. +// +// This function will clear the "hardware" indication of power loss before return. +// This means that there can only be one spot in the TPM code where this value +// gets read. This method is used here as it is the most difficult to manage in the +// TPM code and, if the hardware actually works this way, it is hard to make it +// look like anything else. So, the burden is placed on the TPM code rather than the +// platform code +// return type: int +// TRUE(1) power was lost +// FALSE(0) power was not lost +LIB_EXPORT int +_plat__WasPowerLost( + void + ); + +//*** _plat_Signal_Reset() +// This a TPM reset without a power loss. +LIB_EXPORT int +_plat__Signal_Reset( + void + ); + +//***_plat__Signal_PowerOff() +// Signal platform power off +LIB_EXPORT void +_plat__Signal_PowerOff( + void + ); + + +//** From PPPlat.c + +//***_plat__PhysicalPresenceAsserted() +// Check if physical presence is signaled +// return type: int +// TRUE(1) if physical presence is signaled +// FALSE(0) if physical presence is not signaled +LIB_EXPORT int +_plat__PhysicalPresenceAsserted( + void + ); + +//***_plat__Signal_PhysicalPresenceOn() +// Signal physical presence on +LIB_EXPORT void +_plat__Signal_PhysicalPresenceOn( + void + ); + +//***_plat__Signal_PhysicalPresenceOff() +// Signal physical presence off +LIB_EXPORT void +_plat__Signal_PhysicalPresenceOff( + void + ); + + +//*** _plat__ACT_UpdateCounter() +// This function is used to write the newValue for the counter. If an update is +// pending, then no update occurs and the function returns FALSE. If 'setSignaled' +// is TRUE, then the ACT signaled state is SET and if 'newValue' is 0, nothing +// is posted. +LIB_EXPORT int +_plat__ACT_UpdateCounter( + uint32_t act, // IN: ACT to update + uint32_t newValue // IN: the value to post +); + +//*** _plat__ACT_SetSignaled() +LIB_EXPORT void +_plat__ACT_SetSignaled( + uint32_t act, + int on +); + +//***_plat__ACT_Initialize() +// This function initializes the ACT hardware and data structures +LIB_EXPORT int +_plat__ACT_Initialize( + void +); + +//***_plat__ACT_EnableTicks() +// This enables and disables the processing of the once-per-second ticks. This should +// be turned off ('enable' = FALSE) by _TPM_Init and turned on ('enable' = TRUE) by +// TPM2_Startup() after all the initializations have completed. +LIB_EXPORT void +_plat__ACT_EnableTicks( + int enable +); + +//*** _plat__ACT_GetRemaining() +// This function returns the remaining time. If an update is pending, 'newValue' is +// returned. Otherwise, the current counter value is returned. Note that since the +// timers keep running, the returned value can get stale immediately. The actual count +// value will be no greater than the returned value. +LIB_EXPORT uint32_t +_plat__ACT_GetRemaining( + uint32_t act //IN: the ACT selector +); + +//*** _plat__ACT_GetSignaled() +LIB_EXPORT int +_plat__ACT_GetSignaled( + uint32_t act //IN: number of ACT to check +); + +//*** _plat__ACT_GetImplemented() +// This function tests to see if an ACT is implemented. It is a belt and suspenders +// function because the TPM should not be calling to manipulate an ACT that is not +// implemented. However, this could help the simulator code which doesn't necessarily +// know if an ACT is implemented or not. +LIB_EXPORT int +_plat__ACT_GetImplemented( + uint32_t act +); + +//** From RunCommand.c + +//***_plat__RunCommand() +// This version of RunCommand will set up a jum_buf and call ExecuteCommand(). If +// the command executes without failing, it will return and RunCommand will return. +// If there is a failure in the command, then _plat__Fail() is called and it will +// longjump back to RunCommand which will call ExecuteCommand again. However, this +// time, the TPM will be in failure mode so ExecuteCommand will simply build +// a failure response and return. +LIB_EXPORT void +_plat__RunCommand( + uint32_t requestSize, // IN: command buffer size + unsigned char *request, // IN: command buffer + uint32_t *responseSize, // IN/OUT: response buffer size + unsigned char **response // IN/OUT: response buffer + ); + +//***_plat__Fail() +// This is the platform depended failure exit for the TPM. +LIB_EXPORT NORETURN void +_plat__Fail( + void + ); + + +//** From Unique.c + +//** _plat__GetUnique() +// This function is used to access the platform-specific unique value. +// This function places the unique value in the provided buffer ('b') +// and returns the number of bytes transferred. The function will not +// copy more data than 'bSize'. +// NOTE: If a platform unique value has unequal distribution of uniqueness +// and 'bSize' is smaller than the size of the unique value, the 'bSize' +// portion with the most uniqueness should be returned. +LIB_EXPORT uint32_t +_plat__GetUnique( + uint32_t which, // authorities (0) or details + uint32_t bSize, // size of the buffer + unsigned char *b // output buffer + ); + +#endif // _PLATFORM_FP_H_ diff --git a/ta/ftpm/reference/RuntimeSupport.c b/ta/ftpm/reference/RuntimeSupport.c new file mode 100644 index 00000000000..0998f050834 --- /dev/null +++ b/ta/ftpm/reference/RuntimeSupport.c @@ -0,0 +1,84 @@ +/* Microsoft Reference Implementation for TPM 2.0 + * + * The copyright in this software is being made available under the BSD License, + * included below. This software may be subject to other third party and + * contributor rights, including patent rights, and no such rights are granted + * under this license. + * + * Copyright (c) Microsoft Corporation + * + * All rights reserved. + * + * BSD License + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * Redistributions of source code must retain the above copyright notice, this list + * of conditions and the following disclaimer. + * + * 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. + * + * 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 + +/** + * Implementation of tolower() commonly found in ctype.h + * Returns an ASCII character, changing to lowercase if the character is + * in the range 'A'-'Z'. + */ + +int tolower (int c) +{ + if(c >= 'A' && c <= 'Z') + { + c -= ('A' - 'a'); + } + return c; +} + +int toupper (int c) +{ + if(c >= 'a' && c <= 'z') + { + c += ('A' - 'a'); + } + return c; +} + +int strncasecmp(const char *str1, const char *str2, size_t n) +{ + size_t i = 0; + for(i = 0; i < n && str1[i] && str2[i]; i++) + { + char delta = tolower(str1[i]) - tolower(str2[i]); + if (delta != 0) + { + return delta; + } + } + return 0; +} + +#ifdef CUSTOM_RAND_GENERATE_BLOCK +#include +int wolfRand(unsigned char* output, unsigned int sz) +{ + TEE_GenerateRandom((void *)output, (uint32_t)sz); + + return 0; +} +#endif \ No newline at end of file diff --git a/ta/ftpm/reference/include/RuntimeSupport.h b/ta/ftpm/reference/include/RuntimeSupport.h new file mode 100644 index 00000000000..b0a851ee029 --- /dev/null +++ b/ta/ftpm/reference/include/RuntimeSupport.h @@ -0,0 +1,93 @@ +/* Microsoft Reference Implementation for TPM 2.0 + * + * The copyright in this software is being made available under the BSD License, + * included below. This software may be subject to other third party and + * contributor rights, including patent rights, and no such rights are granted + * under this license. + * + * Copyright (c) Microsoft Corporation + * + * All rights reserved. + * + * BSD License + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * Redistributions of source code must retain the above copyright notice, this list + * of conditions and the following disclaimer. + * + * 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. + * + * 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 _RUNTIMESUPPORT_H_ +#define _RUNTIMESUPPORT_H_ + +// OPTEE provides simple versions of these headers +#include +#include +#include +#include + +typedef uint64_t clock_t; + +#ifndef XMEMCPY +#define XMEMCPY(pdest, psrc, size) memcpy((pdest), (psrc), (size)) +#endif + +#ifndef XMEMSET +#define XMEMSET(pdest, value, size) memset((pdest), (value), (size)) +#endif + +#ifndef XSTRLEN +#define XSTRLEN(str) strlen((str)) +#endif + +#ifndef XSTRNCPY +#define XSTRNCPY(str1,str2,n) strncpy((str1),(str2),(n)) +#endif + +#ifndef XSTRNCASECMP +int strncasecmp(const char *str1, const char *str2, size_t n); +#define XSTRNCASECMP(str1,str2,n) strncasecmp((str1),(str2),(n)) +#endif + +#ifndef XSTRNCMP +#define XSTRNCMP(str1,str2,n) strncmp((str1),(str2),(n)) +#endif + +#ifndef XMEMCMP +#define XMEMCMP(str1,str2,n) memcmp((str1),(str2),(n)) +#endif + +#ifndef XTOUPPER +int toupper (int c); +#define XTOUPPER(str1) toupper((str1)) +#endif + +#ifndef XTOLOWER +int tolower (int c); +#define XTOLOWER(str1) tolower((str1)) +#endif + +#undef WC_NO_HASHDRBG +#define WC_NO_HASHDRBG + +/* Bypass P-RNG and use only HW RNG */ +extern int wolfRand(unsigned char* output, unsigned int sz); +#undef CUSTOM_RAND_GENERATE_BLOCK +#define CUSTOM_RAND_GENERATE_BLOCK wolfRand +#endif diff --git a/ta/ftpm/reference/include/TpmProfile.h b/ta/ftpm/reference/include/TpmProfile.h new file mode 100644 index 00000000000..76ce2bb8357 --- /dev/null +++ b/ta/ftpm/reference/include/TpmProfile.h @@ -0,0 +1,810 @@ +/* Microsoft Reference Implementation for TPM 2.0 + * + * The copyright in this software is being made available under the BSD License, + * included below. This software may be subject to other third party and + * contributor rights, including patent rights, and no such rights are granted + * under this license. + * + * Copyright (c) Microsoft Corporation + * + * All rights reserved. + * + * BSD License + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * Redistributions of source code must retain the above copyright notice, this list + * of conditions and the following disclaimer. + * + * 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. + * + * 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. + */ +/*(Auto-generated) + * Created by TpmStructures; Version 4.4 Mar 26, 2019 + * Date: Mar 4, 2020 Time: 02:36:43PM + */ + +#ifndef _TPM_PROFILE_H_ +#define _TPM_PROFILE_H_ + +#include "RuntimeSupport.h" + +#include +#include +#include + +#undef MAX +#define MAX(a, b) ((a) > (b) ? (a) : (b)) + +#undef MIN +#define MIN(a, b) ((a) < (b) ? (a) : (b)) + +// Table 2:4 - Defines for Logic Values +#undef TRUE +#define TRUE 1 +#undef FALSE +#define FALSE 0 +#undef YES +#define YES 1 +#undef NO +#define NO 0 +#undef SET +#define SET 1 +#undef CLEAR +#define CLEAR 0 + +// Table 0:1 - Defines for Processor Values +#ifndef BIG_ENDIAN_TPM +#define BIG_ENDIAN_TPM NO +#endif +#ifndef LITTLE_ENDIAN_TPM +#define LITTLE_ENDIAN_TPM !BIG_ENDIAN_TPM +#endif +#ifndef MOST_SIGNIFICANT_BIT_0 +#define MOST_SIGNIFICANT_BIT_0 NO +#endif +#ifndef LEAST_SIGNIFICANT_BIT_0 +#define LEAST_SIGNIFICANT_BIT_0 !MOST_SIGNIFICANT_BIT_0 +#endif +#ifndef AUTO_ALIGN +#define AUTO_ALIGN NO +#endif + +// Table 0:4 - Defines for Implemented Curves +#ifndef ECC_NIST_P192 +#define ECC_NIST_P192 NO +#endif +#ifndef ECC_NIST_P224 +#define ECC_NIST_P224 NO +#endif +#ifndef ECC_NIST_P256 +#define ECC_NIST_P256 YES +#endif +#ifndef ECC_NIST_P384 +#define ECC_NIST_P384 YES +#endif +#ifndef ECC_NIST_P521 +#define ECC_NIST_P521 NO +#endif +#ifndef ECC_BN_P256 +#define ECC_BN_P256 YES +#endif +#ifndef ECC_BN_P638 +#define ECC_BN_P638 NO +#endif +#ifndef ECC_SM2_P256 +#define ECC_SM2_P256 YES +#endif + +// Table 0:6 - Defines for Implemented ACT +#ifndef RH_ACT_0 +#define RH_ACT_0 YES +#endif +#ifndef RH_ACT_1 +#define RH_ACT_1 NO +#endif +#ifndef RH_ACT_A +#define RH_ACT_A YES +#endif + +// Table 0:7 - Defines for Implementation Values +#ifdef USE_WOLFCRYPT +#define HASH_LIB Wolf +#define SYM_LIB Wolf +#define MATH_LIB Wolf +#else +#define HASH_LIB Ossl +#define SYM_LIB Ossl +#define MATH_LIB Ossl +#endif + +typedef UINT32 TPM_CC; + +// Table 0:7 - Defines for Implementation Values +#ifndef FIELD_UPGRADE_IMPLEMENTED +#define FIELD_UPGRADE_IMPLEMENTED NO +#endif +#ifdef USE_WOLFCRYPT +#define HASH_LIB Wolf +#define SYM_LIB Wolf +#define MATH_LIB Wolf +#else +#define HASH_LIB Ossl +#define SYM_LIB Ossl +#define MATH_LIB Ossl +#endif +#ifndef IMPLEMENTATION_PCR +#define IMPLEMENTATION_PCR 24 +#endif +#ifndef PLATFORM_PCR +#define PLATFORM_PCR 24 +#endif +#ifndef DRTM_PCR +#define DRTM_PCR 17 +#endif +#ifndef HCRTM_PCR +#define HCRTM_PCR 0 +#endif +#ifndef NUM_LOCALITIES +#define NUM_LOCALITIES 5 +#endif +#ifndef MAX_HANDLE_NUM +#define MAX_HANDLE_NUM 3 +#endif +#ifndef MAX_ACTIVE_SESSIONS +#define MAX_ACTIVE_SESSIONS 64 +#endif +#ifndef CONTEXT_SLOT +#define CONTEXT_SLOT UINT16 +#endif +#ifndef MAX_LOADED_SESSIONS +#define MAX_LOADED_SESSIONS 3 +#endif +#ifndef MAX_SESSION_NUM +#define MAX_SESSION_NUM 3 +#endif +#ifndef MAX_LOADED_OBJECTS +#define MAX_LOADED_OBJECTS 3 +#endif +#ifndef MIN_EVICT_OBJECTS +#define MIN_EVICT_OBJECTS 2 +#endif +#ifndef NUM_POLICY_PCR_GROUP +#define NUM_POLICY_PCR_GROUP 1 +#endif +#ifndef NUM_AUTHVALUE_PCR_GROUP +#define NUM_AUTHVALUE_PCR_GROUP 1 +#endif +#ifndef MAX_CONTEXT_SIZE +#define MAX_CONTEXT_SIZE 1344 +#endif +#ifndef MAX_DIGEST_BUFFER +#define MAX_DIGEST_BUFFER 1024 +#endif +#ifndef MAX_NV_INDEX_SIZE +#define MAX_NV_INDEX_SIZE 2048 +#endif +#ifndef MAX_NV_BUFFER_SIZE +#define MAX_NV_BUFFER_SIZE 1024 +#endif +#ifndef MAX_CAP_BUFFER +#define MAX_CAP_BUFFER 1024 +#endif +#ifndef NV_MEMORY_SIZE +#define NV_MEMORY_SIZE 16384 +#endif +#ifndef MIN_COUNTER_INDICES +#define MIN_COUNTER_INDICES 8 +#endif +#ifndef NUM_STATIC_PCR +#define NUM_STATIC_PCR 16 +#endif +#ifndef MAX_ALG_LIST_SIZE +#define MAX_ALG_LIST_SIZE 64 +#endif +#ifndef PRIMARY_SEED_SIZE +#define PRIMARY_SEED_SIZE 32 +#endif +#ifndef CONTEXT_ENCRYPT_ALGORITHM +#define CONTEXT_ENCRYPT_ALGORITHM AES +#endif +#ifndef NV_CLOCK_UPDATE_INTERVAL +#define NV_CLOCK_UPDATE_INTERVAL 12 +#endif +#ifndef NUM_POLICY_PCR +#define NUM_POLICY_PCR 1 +#endif +#ifndef MAX_COMMAND_SIZE +#define MAX_COMMAND_SIZE 4096 +#endif +#ifndef MAX_RESPONSE_SIZE +#define MAX_RESPONSE_SIZE 4096 +#endif +#ifndef ORDERLY_BITS +#define ORDERLY_BITS 8 +#endif +#ifndef MAX_SYM_DATA +#define MAX_SYM_DATA 128 +#endif +#ifndef MAX_RNG_ENTROPY_SIZE +#define MAX_RNG_ENTROPY_SIZE 64 +#endif +#ifndef RAM_INDEX_SPACE +#define RAM_INDEX_SPACE 512 +#endif +#ifndef RSA_DEFAULT_PUBLIC_EXPONENT +#define RSA_DEFAULT_PUBLIC_EXPONENT 0x00010001 +#endif +#ifndef ENABLE_PCR_NO_INCREMENT +#define ENABLE_PCR_NO_INCREMENT YES +#endif +#ifndef CRT_FORMAT_RSA +#define CRT_FORMAT_RSA YES +#endif +#ifndef VENDOR_COMMAND_COUNT +#define VENDOR_COMMAND_COUNT 0 +#endif +#ifndef MAX_VENDOR_BUFFER_SIZE +#define MAX_VENDOR_BUFFER_SIZE 1024 +#endif +#ifndef SIZE_OF_X509_SERIAL_NUMBER +#define SIZE_OF_X509_SERIAL_NUMBER 20 +#endif +#ifndef PRIVATE_VENDOR_SPECIFIC_BYTES +#define PRIVATE_VENDOR_SPECIFIC_BYTES RSA_PRIVATE_SIZE +#endif + +// Table 0:2 - Defines for Implemented Algorithms +#ifndef ALG_AES +#define ALG_AES ALG_YES +#endif +#ifndef ALG_CAMELLIA +#define ALG_CAMELLIA ALG_NO +#endif +#ifndef ALG_CBC +#define ALG_CBC ALG_YES +#endif +#ifndef ALG_CFB +#define ALG_CFB ALG_YES +#endif +#ifndef ALG_CMAC +#define ALG_CMAC ALG_YES +#endif +#ifndef ALG_CTR +#define ALG_CTR ALG_YES +#endif +#ifndef ALG_ECB +#define ALG_ECB ALG_YES +#endif +#ifndef ALG_ECC +#define ALG_ECC ALG_YES +#endif +#ifndef ALG_ECDAA +#define ALG_ECDAA (ALG_YES && ALG_ECC) +#endif +#ifndef ALG_ECDH +#define ALG_ECDH (ALG_YES && ALG_ECC) +#endif +#ifndef ALG_ECDSA +#define ALG_ECDSA (ALG_YES && ALG_ECC) +#endif +#ifndef ALG_ECMQV +#define ALG_ECMQV (ALG_NO && ALG_ECC) +#endif +#ifndef ALG_ECSCHNORR +#define ALG_ECSCHNORR (ALG_YES && ALG_ECC) +#endif +#ifndef ALG_HMAC +#define ALG_HMAC ALG_YES +#endif +#ifndef ALG_KDF1_SP800_108 +#define ALG_KDF1_SP800_108 ALG_YES +#endif +#ifndef ALG_KDF1_SP800_56A +#define ALG_KDF1_SP800_56A (ALG_YES && ALG_ECC) +#endif +#ifndef ALG_KDF2 +#define ALG_KDF2 ALG_NO +#endif +#ifndef ALG_KEYEDHASH +#define ALG_KEYEDHASH ALG_YES +#endif +#ifndef ALG_MGF1 +#define ALG_MGF1 ALG_YES +#endif +#ifndef ALG_OAEP +#define ALG_OAEP (ALG_YES && ALG_RSA) +#endif +#ifndef ALG_OFB +#define ALG_OFB ALG_YES +#endif +#ifndef ALG_RSA +#define ALG_RSA ALG_YES +#endif +#ifndef ALG_RSAES +#define ALG_RSAES (ALG_YES && ALG_RSA) +#endif +#ifndef ALG_RSAPSS +#define ALG_RSAPSS (ALG_YES && ALG_RSA) +#endif +#ifndef ALG_RSASSA +#define ALG_RSASSA (ALG_YES && ALG_RSA) +#endif +#ifndef ALG_SHA +#define ALG_SHA ALG_NO /* Not specified by vendor */ +#endif +#ifndef ALG_SHA1 +#define ALG_SHA1 ALG_YES +#endif +#ifndef ALG_SHA256 +#define ALG_SHA256 ALG_YES +#endif +#ifndef ALG_SHA384 +#define ALG_SHA384 ALG_YES +#endif +#ifndef ALG_SHA3_256 +#define ALG_SHA3_256 ALG_NO /* Not specified by vendor */ +#endif +#ifndef ALG_SHA3_384 +#define ALG_SHA3_384 ALG_NO /* Not specified by vendor */ +#endif +#ifndef ALG_SHA3_512 +#define ALG_SHA3_512 ALG_NO /* Not specified by vendor */ +#endif +#ifndef ALG_SHA512 +#define ALG_SHA512 ALG_NO +#endif +#ifndef ALG_SM2 +#define ALG_SM2 (ALG_NO && ALG_ECC) +#endif +#ifndef ALG_SM3_256 +#define ALG_SM3_256 ALG_NO +#endif +#ifndef ALG_SM4 +#define ALG_SM4 ALG_NO +#endif +#ifndef ALG_SYMCIPHER +#define ALG_SYMCIPHER ALG_YES +#endif +#ifndef ALG_TDES +#define ALG_TDES ALG_NO +#endif +#ifndef ALG_XOR +#define ALG_XOR ALG_YES +#endif + +// Table 1:3 - Defines for RSA Asymmetric Cipher Algorithm Constants +#ifndef RSA_1024 +#define RSA_1024 (ALG_RSA && YES) +#endif +#ifndef RSA_2048 +#define RSA_2048 (ALG_RSA && YES) +#endif +#ifndef RSA_3072 +#define RSA_3072 (ALG_RSA && NO) +#endif +#ifndef RSA_4096 +#define RSA_4096 (ALG_RSA && NO) +#endif +#ifndef RSA_16384 +#define RSA_16384 (ALG_RSA && NO) +#endif + +// Table 1:21 - Defines for AES Symmetric Cipher Algorithm Constants +#ifndef AES_128 +#define AES_128 (ALG_AES && YES) +#endif +#ifndef AES_192 +#define AES_192 (ALG_AES && NO) +#endif +#ifndef AES_256 +#define AES_256 (ALG_AES && YES) +#endif + +// Table 1:22 - Defines for SM4 Symmetric Cipher Algorithm Constants +#ifndef SM4_128 +#define SM4_128 (ALG_SM4 && YES) +#endif + +// Table 1:23 - Defines for CAMELLIA Symmetric Cipher Algorithm Constants +#ifndef CAMELLIA_128 +#define CAMELLIA_128 (ALG_CAMELLIA && YES) +#endif +#ifndef CAMELLIA_192 +#define CAMELLIA_192 (ALG_CAMELLIA && NO) +#endif +#ifndef CAMELLIA_256 +#define CAMELLIA_256 (ALG_CAMELLIA && YES) +#endif + +// Table 1:24 - Defines for TDES Symmetric Cipher Algorithm Constants +#ifndef TDES_128 +#define TDES_128 (ALG_TDES && YES) +#endif +#ifndef TDES_192 +#define TDES_192 (ALG_TDES && YES) +#endif + +// Table 0:5 - Defines for Implemented Commands +#ifndef CC_ACT_SetTimeout +#define CC_ACT_SetTimeout CC_YES +#endif +#ifndef CC_AC_GetCapability +#define CC_AC_GetCapability CC_YES +#endif +#ifndef CC_AC_Send +#define CC_AC_Send CC_YES +#endif +#ifndef CC_ActivateCredential +#define CC_ActivateCredential CC_YES +#endif +#ifndef CC_Certify +#define CC_Certify CC_YES +#endif +#ifndef CC_CertifyCreation +#define CC_CertifyCreation CC_YES +#endif +#ifndef CC_CertifyX509 +#define CC_CertifyX509 CC_YES +#endif +#ifndef CC_ChangeEPS +#define CC_ChangeEPS CC_YES +#endif +#ifndef CC_ChangePPS +#define CC_ChangePPS CC_YES +#endif +#ifndef CC_Clear +#define CC_Clear CC_YES +#endif +#ifndef CC_ClearControl +#define CC_ClearControl CC_YES +#endif +#ifndef CC_ClockRateAdjust +#define CC_ClockRateAdjust CC_YES +#endif +#ifndef CC_ClockSet +#define CC_ClockSet CC_YES +#endif +#ifndef CC_Commit +#define CC_Commit (CC_YES && ALG_ECC) +#endif +#ifndef CC_ContextLoad +#define CC_ContextLoad CC_YES +#endif +#ifndef CC_ContextSave +#define CC_ContextSave CC_YES +#endif +#ifndef CC_Create +#define CC_Create CC_YES +#endif +#ifndef CC_CreateLoaded +#define CC_CreateLoaded CC_YES +#endif +#ifndef CC_CreatePrimary +#define CC_CreatePrimary CC_YES +#endif +#ifndef CC_DictionaryAttackLockReset +#define CC_DictionaryAttackLockReset CC_YES +#endif +#ifndef CC_DictionaryAttackParameters +#define CC_DictionaryAttackParameters CC_YES +#endif +#ifndef CC_Duplicate +#define CC_Duplicate CC_YES +#endif +#ifndef CC_ECC_Decrypt +#define CC_ECC_Decrypt (CC_YES && ALG_ECC) +#endif +#ifndef CC_ECC_Encrypt +#define CC_ECC_Encrypt (CC_YES && ALG_ECC) +#endif +#ifndef CC_ECC_Parameters +#define CC_ECC_Parameters (CC_YES && ALG_ECC) +#endif +#ifndef CC_ECDH_KeyGen +#define CC_ECDH_KeyGen (CC_YES && ALG_ECC) +#endif +#ifndef CC_ECDH_ZGen +#define CC_ECDH_ZGen (CC_YES && ALG_ECC) +#endif +#ifndef CC_EC_Ephemeral +#define CC_EC_Ephemeral (CC_YES && ALG_ECC) +#endif +#ifndef CC_EncryptDecrypt +#define CC_EncryptDecrypt CC_YES +#endif +#ifndef CC_EncryptDecrypt2 +#define CC_EncryptDecrypt2 CC_YES +#endif +#ifndef CC_EventSequenceComplete +#define CC_EventSequenceComplete CC_YES +#endif +#ifndef CC_EvictControl +#define CC_EvictControl CC_YES +#endif +#ifndef CC_FieldUpgradeData +#define CC_FieldUpgradeData CC_NO +#endif +#ifndef CC_FieldUpgradeStart +#define CC_FieldUpgradeStart CC_NO +#endif +#ifndef CC_FirmwareRead +#define CC_FirmwareRead CC_NO +#endif +#ifndef CC_FlushContext +#define CC_FlushContext CC_YES +#endif +#ifndef CC_GetCapability +#define CC_GetCapability CC_YES +#endif +#ifndef CC_GetCommandAuditDigest +#define CC_GetCommandAuditDigest CC_YES +#endif +#ifndef CC_GetRandom +#define CC_GetRandom CC_YES +#endif +#ifndef CC_GetSessionAuditDigest +#define CC_GetSessionAuditDigest CC_YES +#endif +#ifndef CC_GetTestResult +#define CC_GetTestResult CC_YES +#endif +#ifndef CC_GetTime +#define CC_GetTime CC_YES +#endif +#ifndef CC_HMAC +#define CC_HMAC (CC_YES && !ALG_CMAC) +#endif +#ifndef CC_HMAC_Start +#define CC_HMAC_Start (CC_YES && !ALG_CMAC) +#endif +#ifndef CC_Hash +#define CC_Hash CC_YES +#endif +#ifndef CC_HashSequenceStart +#define CC_HashSequenceStart CC_YES +#endif +#ifndef CC_HierarchyChangeAuth +#define CC_HierarchyChangeAuth CC_YES +#endif +#ifndef CC_HierarchyControl +#define CC_HierarchyControl CC_YES +#endif +#ifndef CC_Import +#define CC_Import CC_YES +#endif +#ifndef CC_IncrementalSelfTest +#define CC_IncrementalSelfTest CC_YES +#endif +#ifndef CC_Load +#define CC_Load CC_YES +#endif +#ifndef CC_LoadExternal +#define CC_LoadExternal CC_YES +#endif +#ifndef CC_MAC +#define CC_MAC (CC_YES && ALG_CMAC) +#endif +#ifndef CC_MAC_Start +#define CC_MAC_Start (CC_YES && ALG_CMAC) +#endif +#ifndef CC_MakeCredential +#define CC_MakeCredential CC_YES +#endif +#ifndef CC_NV_Certify +#define CC_NV_Certify CC_YES +#endif +#ifndef CC_NV_ChangeAuth +#define CC_NV_ChangeAuth CC_YES +#endif +#ifndef CC_NV_DefineSpace +#define CC_NV_DefineSpace CC_YES +#endif +#ifndef CC_NV_Extend +#define CC_NV_Extend CC_YES +#endif +#ifndef CC_NV_GlobalWriteLock +#define CC_NV_GlobalWriteLock CC_YES +#endif +#ifndef CC_NV_Increment +#define CC_NV_Increment CC_YES +#endif +#ifndef CC_NV_Read +#define CC_NV_Read CC_YES +#endif +#ifndef CC_NV_ReadLock +#define CC_NV_ReadLock CC_YES +#endif +#ifndef CC_NV_ReadPublic +#define CC_NV_ReadPublic CC_YES +#endif +#ifndef CC_NV_SetBits +#define CC_NV_SetBits CC_YES +#endif +#ifndef CC_NV_UndefineSpace +#define CC_NV_UndefineSpace CC_YES +#endif +#ifndef CC_NV_UndefineSpaceSpecial +#define CC_NV_UndefineSpaceSpecial CC_YES +#endif +#ifndef CC_NV_Write +#define CC_NV_Write CC_YES +#endif +#ifndef CC_NV_WriteLock +#define CC_NV_WriteLock CC_YES +#endif +#ifndef CC_ObjectChangeAuth +#define CC_ObjectChangeAuth CC_YES +#endif +#ifndef CC_PCR_Allocate +#define CC_PCR_Allocate CC_YES +#endif +#ifndef CC_PCR_Event +#define CC_PCR_Event CC_YES +#endif +#ifndef CC_PCR_Extend +#define CC_PCR_Extend CC_YES +#endif +#ifndef CC_PCR_Read +#define CC_PCR_Read CC_YES +#endif +#ifndef CC_PCR_Reset +#define CC_PCR_Reset CC_YES +#endif +#ifndef CC_PCR_SetAuthPolicy +#define CC_PCR_SetAuthPolicy CC_YES +#endif +#ifndef CC_PCR_SetAuthValue +#define CC_PCR_SetAuthValue CC_YES +#endif +#ifndef CC_PP_Commands +#define CC_PP_Commands CC_YES +#endif +#ifndef CC_PolicyAuthValue +#define CC_PolicyAuthValue CC_YES +#endif +#ifndef CC_PolicyAuthorize +#define CC_PolicyAuthorize CC_YES +#endif +#ifndef CC_PolicyAuthorizeNV +#define CC_PolicyAuthorizeNV CC_YES +#endif +#ifndef CC_PolicyCommandCode +#define CC_PolicyCommandCode CC_YES +#endif +#ifndef CC_PolicyCounterTimer +#define CC_PolicyCounterTimer CC_YES +#endif +#ifndef CC_PolicyCpHash +#define CC_PolicyCpHash CC_YES +#endif +#ifndef CC_PolicyDuplicationSelect +#define CC_PolicyDuplicationSelect CC_YES +#endif +#ifndef CC_PolicyGetDigest +#define CC_PolicyGetDigest CC_YES +#endif +#ifndef CC_PolicyLocality +#define CC_PolicyLocality CC_YES +#endif +#ifndef CC_PolicyNV +#define CC_PolicyNV CC_YES +#endif +#ifndef CC_PolicyNameHash +#define CC_PolicyNameHash CC_YES +#endif +#ifndef CC_PolicyNvWritten +#define CC_PolicyNvWritten CC_YES +#endif +#ifndef CC_PolicyOR +#define CC_PolicyOR CC_YES +#endif +#ifndef CC_PolicyPCR +#define CC_PolicyPCR CC_YES +#endif +#ifndef CC_PolicyPassword +#define CC_PolicyPassword CC_YES +#endif +#ifndef CC_PolicyPhysicalPresence +#define CC_PolicyPhysicalPresence CC_YES +#endif +#ifndef CC_PolicyRestart +#define CC_PolicyRestart CC_YES +#endif +#ifndef CC_PolicySecret +#define CC_PolicySecret CC_YES +#endif +#ifndef CC_PolicySigned +#define CC_PolicySigned CC_YES +#endif +#ifndef CC_PolicyTemplate +#define CC_PolicyTemplate CC_YES +#endif +#ifndef CC_PolicyTicket +#define CC_PolicyTicket CC_YES +#endif +#ifndef CC_Policy_AC_SendSelect +#define CC_Policy_AC_SendSelect CC_YES +#endif +#ifndef CC_Quote +#define CC_Quote CC_YES +#endif +#ifndef CC_RSA_Decrypt +#define CC_RSA_Decrypt (CC_YES && ALG_RSA) +#endif +#ifndef CC_RSA_Encrypt +#define CC_RSA_Encrypt (CC_YES && ALG_RSA) +#endif +#ifndef CC_ReadClock +#define CC_ReadClock CC_YES +#endif +#ifndef CC_ReadPublic +#define CC_ReadPublic CC_YES +#endif +#ifndef CC_Rewrap +#define CC_Rewrap CC_YES +#endif +#ifndef CC_SelfTest +#define CC_SelfTest CC_YES +#endif +#ifndef CC_SequenceComplete +#define CC_SequenceComplete CC_YES +#endif +#ifndef CC_SequenceUpdate +#define CC_SequenceUpdate CC_YES +#endif +#ifndef CC_SetAlgorithmSet +#define CC_SetAlgorithmSet CC_YES +#endif +#ifndef CC_SetCommandCodeAuditStatus +#define CC_SetCommandCodeAuditStatus CC_YES +#endif +#ifndef CC_SetPrimaryPolicy +#define CC_SetPrimaryPolicy CC_YES +#endif +#ifndef CC_Shutdown +#define CC_Shutdown CC_YES +#endif +#ifndef CC_Sign +#define CC_Sign CC_YES +#endif +#ifndef CC_StartAuthSession +#define CC_StartAuthSession CC_YES +#endif +#ifndef CC_Startup +#define CC_Startup CC_YES +#endif +#ifndef CC_StirRandom +#define CC_StirRandom CC_YES +#endif +#ifndef CC_TestParms +#define CC_TestParms CC_YES +#endif +#ifndef CC_Unseal +#define CC_Unseal CC_YES +#endif +#ifndef CC_Vendor_TCG_Test +#define CC_Vendor_TCG_Test CC_YES +#endif +#ifndef CC_VerifySignature +#define CC_VerifySignature CC_YES +#endif +#ifndef CC_ZGen_2Phase +#define CC_ZGen_2Phase (CC_YES && ALG_ECC) +#endif + + +#endif // _TPM_PROFILE_H_ diff --git a/ta/ftpm/reference/include/TpmSal.h b/ta/ftpm/reference/include/TpmSal.h new file mode 100644 index 00000000000..020ac0d1689 --- /dev/null +++ b/ta/ftpm/reference/include/TpmSal.h @@ -0,0 +1,115 @@ +/* Microsoft Reference Implementation for TPM 2.0 + * + * The copyright in this software is being made available under the BSD License, + * included below. This software may be subject to other third party and + * contributor rights, including patent rights, and no such rights are granted + * under this license. + * + * Copyright (c) Microsoft Corporation + * + * All rights reserved. + * + * BSD License + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * Redistributions of source code must retain the above copyright notice, this list + * of conditions and the following disclaimer. + * + * 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. + * + * 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. + */ + +/*** +* TpmSal.h provides a set of #defines that allow SymCrypt to be built +* in VS. +* +****/ + +#ifndef _TPM_SAL_H_ +#define _TPM_SAL_H_ + +#ifndef _Out_writes_bytes_ + +#define _Out_writes_( cbData ) +#define _Out_writes_bytes_( cbData ) +#define _Out_writes_opt_( cbData ) +#define _Out_writes_to_(n, c) +#define _In_reads_( cbBytes ) +#define _In_reads_opt_( cbAuthData ) +#define _In_reads_bytes_(size) +#define _Inout_updates_( nStates ) +#define _Inout_updates_bytes_(size) +#define _Field_size_( size ) +#define _Field_range_( min, max ) +#define _Writable_elements_(c) +#define _Ret_writes_bytes_to_(n, c) + +#define _Analysis_assume_(x) +#define _Analysis_noreturn_ + +#define _Use_decl_annotations_ + +#define __success(x) + +#define __assume +#define __analysis_assume +#define _In_ +#define _Out_ +#define __in +#define __in_opt +#define __in_bcount(x) +#define __in_bcount_opt(x) +#define __in_ecount(x) +#define __in_ecount_opt(x) +#define __in_xcount(x) +#define __out +#define __out_ecount(x) +#define __out_ecount_opt(x) +#define __out_ecount_full(x) +#define __out_ecount_part(x, y) +#define __out_bcount(x) +#define __out_bcount_part_opt(x, y) +#define __out_bcount_full(x) +#define __out_xcount(x) +#define __out_xcount_opt(x) +#define __out_ecount_part(x, y) +#define __out_ecount_part_opt(x, y) +#define __out_opt +#define __inout_ecount(x) +#define __inout_bcount(x) +#define __bound +#define __inout +#define __inout_opt +#define __inout_ecount_opt(x) +#define __deref_out_ecount(x) +#define __deref_opt_out_ecount(x) +#define __field_ecount(x) +#define _Post_invalid_ +#define _Pre_maybenull_ +#define __checkReturn +#define _In_bytecount_(x) + +#endif /* no SAL macros defined */ + +#ifndef _Interlocked_operand_ + +#define _Interlocked_operand_ + +#endif + + +#endif diff --git a/ta/ftpm/reference/include/VendorString.h b/ta/ftpm/reference/include/VendorString.h new file mode 100644 index 00000000000..b2b798ef36f --- /dev/null +++ b/ta/ftpm/reference/include/VendorString.h @@ -0,0 +1,93 @@ +/* Microsoft Reference Implementation for TPM 2.0 + * + * The copyright in this software is being made available under the BSD License, + * included below. This software may be subject to other third party and + * contributor rights, including patent rights, and no such rights are granted + * under this license. + * + * Copyright (c) Microsoft Corporation + * + * All rights reserved. + * + * BSD License + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * Redistributions of source code must retain the above copyright notice, this list + * of conditions and the following disclaimer. + * + * 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. + * + * 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 _VENDOR_STRING_H +#define _VENDOR_STRING_H + +// Define up to 4-byte values for MANUFACTURER. This value defines the response +// for TPM_PT_MANUFACTURER in TPM2_GetCapability. +// The following line should be un-commented and a vendor specific string +// should be provided here. +#define MANUFACTURER "MSFT" + +// The following #if macro may be deleted after a proper MANUFACTURER is provided. +#ifndef MANUFACTURER +#error MANUFACTURER is not provided. \ +Please modify include\VendorString.h to provide a specific \ +manufacturer name. +#endif + +// Define up to 4, 4-byte values. The values must each be 4 bytes long and the last +// value used may contain trailing zeros. +// These values define the response for TPM_PT_VENDOR_STRING_(1-4) +// in TPM2_GetCapability. +// The following line should be un-commented and a vendor specific string +// should be provided here. +// The vendor strings 2-4 may also be defined as appropriately. +#define VENDOR_STRING_1 "SSE " +#define VENDOR_STRING_2 "fTPM" +//#define VENDOR_STRING_3 +//#define VENDOR_STRING_4 + +// The following #if macro may be deleted after a proper VENDOR_STRING_1 +// is provided. +#ifndef VENDOR_STRING_1 +#error VENDOR_STRING_1 is not provided. \ +Please modify include\VendorString.h to provide a vendor specific \ +string. +#endif + +// the more significant 32-bits of a vendor-specific value +// indicating the version of the firmware +// The following line should be un-commented and a vendor-specific firmware V1 +// should be provided here. +// The FIRMWARE_V2 may also be defined as appropriate. + +//Date of last update: (0xYYYMMDD) +#define FIRMWARE_V1 (0x20180710) +// the less significant 32-bits of a vendor-specific value +// indicating the version of the firmware + +//Time of last update: (0x00HHMMSS) +#define FIRMWARE_V2 (0x00105300) + +// The following #if macro may be deleted after a proper FIRMWARE_V1 is provided. +#ifndef FIRMWARE_V1 +#error FIRMWARE_V1 is not provided. \ +Please modify include\VendorString.h to provide a vendor-specific firmware \ +version +#endif + +#endif diff --git a/ta/ftpm/reference/include/bool.h b/ta/ftpm/reference/include/bool.h new file mode 100644 index 00000000000..60b55ee2f2c --- /dev/null +++ b/ta/ftpm/reference/include/bool.h @@ -0,0 +1,51 @@ +/* Microsoft Reference Implementation for TPM 2.0 + * + * The copyright in this software is being made available under the BSD License, + * included below. This software may be subject to other third party and + * contributor rights, including patent rights, and no such rights are granted + * under this license. + * + * Copyright (c) Microsoft Corporation + * + * All rights reserved. + * + * BSD License + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * Redistributions of source code must retain the above copyright notice, this list + * of conditions and the following disclaimer. + * + * 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. + * + * 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 _BOOL_H +#define _BOOL_H + +#if defined(TRUE) +#undef TRUE +#endif + +#if defined FALSE +#undef FALSE +#endif + +typedef int BOOL; +#define FALSE ((BOOL)0) +#define TRUE ((BOOL)1) + +#endif diff --git a/ta/ftpm/sub.mk b/ta/ftpm/sub.mk new file mode 100644 index 00000000000..2d9ba2411e0 --- /dev/null +++ b/ta/ftpm/sub.mk @@ -0,0 +1,77 @@ +WARNS := 0 +NOWERROR := 0 +CFG_TA_MEASURED_BOOT ?= n +CFG_TA_DEBUG ?= n +CFG_TEE_TA_LOG_LEVEL ?= 0 +CFG_TA_EVENT_LOG_SIZE ?= 1024 + +cflags-y += -DTHIRTY_TWO_BIT \ + -DCFG_TEE_TA_LOG_LEVEL=$(CFG_TEE_TA_LOG_LEVEL) \ + -D_ARM_ \ + -w \ + -Wno-strict-prototypes \ + -mcpu=$(TA_CPU) \ + -fstack-protector \ + -Wstack-protector + +ifeq ($(CFG_TA_MEASURED_BOOT),y) +cflags-y += -DEVENT_LOG_SIZE=$(CFG_TA_EVENT_LOG_SIZE) +cflags-y += -DMEASURED_BOOT +endif + +ifeq ($(CFG_ARM64_ta_arm64),y) +cflags-y += -mstrict-align +else +cflags-y += -mno-unaligned-access +endif + +ifeq ($(CFG_TA_DEBUG),y) +cflags-y += -DfTPMDebug=1 +cflags-y += -DDBG=1 +cflags-y += -O0 +cflags-y += -DDEBUG +cflags-y += -DTRACE_LEVEL=$(CFG_TEE_TA_LOG_LEVEL) +else +cflags-y += -Os +cflags-y += -DNDEBUG +endif + +# +# Link the required external code into the libraries folder. OP-TEE build +# does not work well when accessing anything below the root directory. Use +# symlinks to trick it. +# +all: create_lib_symlinks +clean: clean_lib_symlinks + +subdirs-y += lib + +global-incdirs-y += include +global-incdirs-y += include/Wolf +global-incdirs-y += reference/include +global-incdirs-y += platform/include + +srcs-y += platform/AdminPPI.c +srcs-y += platform/Cancel.c +srcs-y += platform/Clock.c +srcs-y += platform/Entropy.c +srcs-y += platform/LocalityPlat.c +srcs-y += platform/NvAdmin.c +srcs-y += platform/NVMem.c +srcs-y += platform/PowerPlat.c +srcs-y += platform/PlatformData.c +srcs-y += platform/PPPlat.c +srcs-y += platform/RunCommand.c +srcs-y += platform/Unique.c +srcs-y += platform/EPS.c +srcs-y += platform/PlatformACT.c +srcs-y += reference/RuntimeSupport.c +srcs-y += platform/fTPM_helpers.c + +srcs-y += fTPM.c + +ifeq ($(CFG_TA_MEASURED_BOOT),y) +# Support for Trusted Firmware Measured Boot. +srcs-y += platform/fTPM_event_log.c +srcs-y += platform/EventLogPrint.c +endif diff --git a/ta/ftpm/user_ta_header_defines.h b/ta/ftpm/user_ta_header_defines.h new file mode 100644 index 00000000000..92c33c16932 --- /dev/null +++ b/ta/ftpm/user_ta_header_defines.h @@ -0,0 +1,56 @@ +/* Microsoft Reference Implementation for TPM 2.0 + * + * The copyright in this software is being made available under the BSD License, + * included below. This software may be subject to other third party and + * contributor rights, including patent rights, and no such rights are granted + * under this license. + * + * Copyright (c) Microsoft Corporation + * + * All rights reserved. + * + * BSD License + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * Redistributions of source code must retain the above copyright notice, this list + * of conditions and the following disclaimer. + * + * 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. + * + * 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. + */ + +/* + * The name of this file must not be modified + */ + +#ifndef USER_TA_HEADER_DEFINES_H +#define USER_TA_HEADER_DEFINES_H + +#include + +#define TA_UUID TA_FTPM_UUID + +#define TA_FLAGS (TA_FLAG_SINGLE_INSTANCE | TA_FLAG_INSTANCE_KEEP_ALIVE) +#define TA_STACK_SIZE (64 * 1024) +#define TA_DATA_SIZE (32 * 1024) + +#define TA_CURRENT_TA_EXT_PROPERTIES \ + { "gp.ta.description", USER_TA_PROP_TYPE_STRING, \ + "fTPM TA" }, \ + { "gp.ta.version", USER_TA_PROP_TYPE_U32, &(const uint32_t){ 0x0010 } } + +#endif /*USER_TA_HEADER_DEFINES_H*/ From e282593e12ef137b04fb233791f3b1e15f1f630e Mon Sep 17 00:00:00 2001 From: Jens Wiklander Date: Wed, 18 Sep 2024 17:30:25 +0200 Subject: [PATCH 08/27] ftpm: import TEE crypto API wrappers Import TEE crypto API wrappers from https://github.com/zeschg/ms-tpm-20-ref/ from commit ea7f4b3c3f82 ("feat: exchange wolfcrypt backend with op-tee crypto api") with the exception of src/crypt/tee/TpmToTEEHash.c and include/TEE/TpmToTEEHash.h. Samples/ARM32-FirmwareTPM/optee_ta/fTPM/reference/include/TpmProfile.h to ta/ftpm/reference/include/TpmProfile.h Source directory TPMCmd/tpm to destination directory ta/ftpm src/crypt/tee/TpmToTEEMath.c -> tee/TpmToTEEMath.c src/crypt/tee/TpmToTEESupport.c -> tee/TpmToTEESupport.c src/crypt/tee/TpmToTEESym.c -> tee/TpmToTEESym.c include/TEE/TpmToTEEMath.h -> include/TEE/TpmToTEEMath.h include/TEE/TpmToTEESym.h -> include/TEE/TpmToTEESym.h Signed-off-by: Jens Wiklander --- ta/ftpm/include/TEE/TpmToTEEMath.h | 70 ++ ta/ftpm/include/TEE/TpmToTEESym.h | 163 ++++ ta/ftpm/reference/include/TpmProfile.h | 25 +- ta/ftpm/tee/TpmToTEEMath.c | 1030 ++++++++++++++++++++++++ ta/ftpm/tee/TpmToTEESupport.c | 16 + ta/ftpm/tee/TpmToTEESym.c | 445 ++++++++++ 6 files changed, 1738 insertions(+), 11 deletions(-) create mode 100644 ta/ftpm/include/TEE/TpmToTEEMath.h create mode 100644 ta/ftpm/include/TEE/TpmToTEESym.h create mode 100644 ta/ftpm/tee/TpmToTEEMath.c create mode 100644 ta/ftpm/tee/TpmToTEESupport.c create mode 100644 ta/ftpm/tee/TpmToTEESym.c diff --git a/ta/ftpm/include/TEE/TpmToTEEMath.h b/ta/ftpm/include/TEE/TpmToTEEMath.h new file mode 100644 index 00000000000..6aaebf71abf --- /dev/null +++ b/ta/ftpm/include/TEE/TpmToTEEMath.h @@ -0,0 +1,70 @@ +/* SPDX-License-Identifier: BSD-2-Clause */ +/********************************************************************** + * Copyright (c) 2024, Siemens AG + * All rights reserved. + * + * Based on the original code by Microsoft. Modified to support using + * TEE functions to provide cryptographic functionality. + * + * Portions Copyright Microsoft Corporation, see below for details: + * + * The copyright in this software is being made available under the BSD License, + * included below. This software may be subject to other third party and + * contributor rights, including patent rights, and no such rights are granted + * under this license. + * + * Copyright (c) Microsoft Corporation + * + * All rights reserved. + * + * BSD License + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * Redistributions of source code must retain the above copyright notice, this list + * of conditions and the following disclaimer. + * + * 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. + * + * 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. + */ + +//** Introduction +// This file contains the structure definitions used for ECC in the LibTomCrypt +// version of the code. These definitions would change, based on the library. +// The ECC-related structures that cross the TPM interface are defined +// in TpmTypes.h +// + +#ifndef MATH_LIB_DEFINED +#define MATH_LIB_DEFINED + +#define MATH_LIB_TEE + +#include +#include + +typedef ECC_CURVE_DATA bnCurve_t; + +typedef bnCurve_t* bigCurve; + +#define AccessCurveData(E) (E) + +#define CURVE_INITIALIZED(name, initializer) \ + bnCurve_t* name = (ECC_CURVE_DATA*)GetCurveData(initializer) + +#define CURVE_FREE(E) + +#endif // MATH_LIB_DEFINED diff --git a/ta/ftpm/include/TEE/TpmToTEESym.h b/ta/ftpm/include/TEE/TpmToTEESym.h new file mode 100644 index 00000000000..17d167d257c --- /dev/null +++ b/ta/ftpm/include/TEE/TpmToTEESym.h @@ -0,0 +1,163 @@ +/* SPDX-License-Identifier: BSD-2-Clause */ +/********************************************************************** + * Copyright (c) 2024, Siemens AG + * All rights reserved. + * + * Based on the original code by Microsoft. Modified to support using + * TEE functions to provide cryptographic functionality. + * + * Portions Copyright Microsoft Corporation, see below for details: + * + * The copyright in this software is being made available under the BSD License, + * included below. This software may be subject to other third party and + * contributor rights, including patent rights, and no such rights are granted + * under this license. + * + * Copyright (c) Microsoft Corporation + * + * All rights reserved. + * + * BSD License + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * Redistributions of source code must retain the above copyright notice, this list + * of conditions and the following disclaimer. + * + * 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. + * + * 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. + */ + +//** Introduction +// +// This header file is used to 'splice' the TEE sym code into the TPM code. + +#ifndef SYM_LIB_DEFINED +#define SYM_LIB_DEFINED + +#define SYM_LIB_TEE + +#define SYM_ALIGNMENT RADIX_BYTES + +#include +#include + +/// @brief The TEE does not export a key schedule, so this is not really a key schedule but rather a copy of the key. +typedef struct +{ + uint16_t keySizeInBytes; + uint8_t key[32]; +} tpmKeyScheduleAES; + +/// @brief The TEE does not export a key schedule, so this is not really a key schedule but rather a copy of the key. +typedef struct +{ + uint16_t keySizeInBytes; + uint8_t key[24]; +} tpmKeyScheduleTDES; + +/// @brief The TEE does not export a key schedule, so this is not really a key schedule but rather a copy of the key. +typedef struct +{ + uint16_t keySizeInBytes; + uint8_t key[16]; +} tpmKeyScheduleSM4; + +int TEE_SetKeyAES( + tpmKeyScheduleAES* key_schedule, const uint8_t* key, uint16_t keySizeInBytes); +int TEE_SetKeyTDES( + tpmKeyScheduleTDES* key_schedule, const uint8_t* key, uint16_t keySizeInBytes); +int TEE_SetKeySM4( + tpmKeyScheduleSM4* key_schedule, const uint8_t* key, uint16_t keySizeInBytes); + +void TEE_AESEncrypt( + uint8_t* out, const tpmKeyScheduleAES* key_schedule, const uint8_t* in); +void TEE_AESDecrypt( + uint8_t* out, const tpmKeyScheduleAES* key_schedule, const uint8_t* in); +void TEE_TDESEncrypt( + uint8_t* out, const tpmKeyScheduleTDES* key_schedule, const uint8_t* in); +void TEE_TDESDecrypt( + uint8_t* out, const tpmKeyScheduleTDES* key_schedule, const uint8_t* in); +void TEE_SM4Encrypt( + uint8_t* out, const tpmKeyScheduleSM4* key_schedule, const uint8_t* in); +void TEE_SM4Decrypt( + uint8_t* out, const tpmKeyScheduleSM4* key_schedule, const uint8_t* in); + +//*************************************************************** +//** Links to the TEE sym code +//*************************************************************** + +#if ALG_CAMELLIA +# undef ALG_CAMELLIA +# define ALG_CAMELLIA ALG_NO +//#error "Camellia is not available" +#endif + +// Define the order of parameters to the library functions that do block encryption +// and decryption. +typedef void (*TpmCryptSetSymKeyCall_t)(void* keySchedule, BYTE* out, const BYTE* in); + +// The Crypt functions that call the block encryption function use the parameters +// in the order: +// 1) keySchedule +// 2) in buffer +// 3) out buffer +// Since the functions TEE_Encrypt* uses a different order, we need to swizzle the +// values to the order required by the library. +#define SWIZZLE(keySchedule, in, out) \ + (BYTE*)(out), (void*)(keySchedule), (const BYTE*)(in) + +// Macros to set up the encryption/decryption key schedules +// +// AES: +#define TpmCryptSetEncryptKeyAES(key, keySizeInBits, schedule) \ + TEE_SetKeyAES((tpmKeyScheduleAES*)(schedule), key, BITS_TO_BYTES(keySizeInBits)) +#define TpmCryptSetDecryptKeyAES(key, keySizeInBits, schedule) \ + TEE_SetKeyAES((tpmKeyScheduleAES*)(schedule), key, BITS_TO_BYTES(keySizeInBits)) + +// TDES: +#define TpmCryptSetEncryptKeyTDES(key, keySizeInBits, schedule) \ + TEE_SetKeyTDES((tpmKeyScheduleTDES*)(schedule), (key), BITS_TO_BYTES(keySizeInBits)) +#define TpmCryptSetDecryptKeyTDES(key, keySizeInBits, schedule) \ + TEE_SetKeyTDES((tpmKeyScheduleTDES*)(schedule), (key), BITS_TO_BYTES(keySizeInBits)) + +// SM4: +#define TpmCryptSetEncryptKeySM4(key, keySizeInBits, schedule) \ + TEE_SetKeySM4((tpmKeyScheduleSM4*)(schedule), (key), BITS_TO_BYTES(keySizeInBits)) +#define TpmCryptSetDecryptKeySM4(key, keySizeInBits, schedule) \ + TEE_SetKeySM4((tpmKeyScheduleSM4*)(schedule), (key), BITS_TO_BYTES(keySizeInBits)) + +// Macros to alias encryption calls to specific algorithms. This should be used +// sparingly. Currently, only used by CryptRand.c +// +// When using these calls, to call the AES block encryption code, the caller +// should use: +// TpmCryptEncryptAES(SWIZZLE(keySchedule, in, out)); +#define TpmCryptEncryptAES TEE_AESEncrypt +#define TpmCryptDecryptAES TEE_AESDecrypt + +#define TpmCryptEncryptTDES TEE_TDESEncrypt +#define TpmCryptDecryptTDES TEE_TDESDecrypt + +#define TpmCryptEncryptSM4 TEE_SM4Encrypt +#define TpmCryptDecryptSM4 TEE_SM4Decrypt + +typedef union tpmCryptKeySchedule_t tpmCryptKeySchedule_t; + +// This definition would change if there were something to report +#define SymLibSimulationEnd() + +#endif // SYM_LIB_DEFINED diff --git a/ta/ftpm/reference/include/TpmProfile.h b/ta/ftpm/reference/include/TpmProfile.h index 76ce2bb8357..bd83749bf63 100644 --- a/ta/ftpm/reference/include/TpmProfile.h +++ b/ta/ftpm/reference/include/TpmProfile.h @@ -1,4 +1,12 @@ -/* Microsoft Reference Implementation for TPM 2.0 +/* SPDX-License-Identifier: BSD-2-Clause */ +/********************************************************************** + * Copyright (c) 2024, Siemens AG + * All rights reserved. + * + * Based on the original code by Microsoft. Modified to support using + * TEE functions to provide cryptographic functionality. + * + * Portions Copyright Microsoft Corporation, see below for details: * * The copyright in this software is being made available under the BSD License, * included below. This software may be subject to other third party and @@ -121,10 +129,14 @@ #endif // Table 0:7 - Defines for Implementation Values -#ifdef USE_WOLFCRYPT +#if defined(USE_WOLFCRYPT) #define HASH_LIB Wolf #define SYM_LIB Wolf #define MATH_LIB Wolf +#elif defined(USE_TEE) +#define HASH_LIB TEE +#define SYM_LIB TEE +#define MATH_LIB TEE #else #define HASH_LIB Ossl #define SYM_LIB Ossl @@ -137,15 +149,6 @@ typedef UINT32 TPM_CC; #ifndef FIELD_UPGRADE_IMPLEMENTED #define FIELD_UPGRADE_IMPLEMENTED NO #endif -#ifdef USE_WOLFCRYPT -#define HASH_LIB Wolf -#define SYM_LIB Wolf -#define MATH_LIB Wolf -#else -#define HASH_LIB Ossl -#define SYM_LIB Ossl -#define MATH_LIB Ossl -#endif #ifndef IMPLEMENTATION_PCR #define IMPLEMENTATION_PCR 24 #endif diff --git a/ta/ftpm/tee/TpmToTEEMath.c b/ta/ftpm/tee/TpmToTEEMath.c new file mode 100644 index 00000000000..f973d18485e --- /dev/null +++ b/ta/ftpm/tee/TpmToTEEMath.c @@ -0,0 +1,1030 @@ +/* SPDX-License-Identifier: BSD-2-Clause */ +/********************************************************************** + * Copyright (c) 2024, Siemens AG + * All rights reserved. + */ + +#include "Tpm.h" + +#ifdef MATH_LIB_TEE + +# include + +# ifdef DEBUG_OUTPUT_TEE_MATH +# include +# define DEBUG_PRINT_RESULT(f) printf(" " #f " returns %" PRIx32 "\n", f) +void printf_bigint(const TEE_BigInt* bigint) +{ + size_t buffer_len = 1024; + uint8_t buffer[buffer_len]; + if(TEE_BigIntConvertToOctetString(buffer, &buffer_len, bigint) == TEE_SUCCESS) + { + if(buffer_len != 0) + { + for(size_t k = 0; k < buffer_len; ++k) + { + printf("%.2x", buffer[k]); + } + } else { + printf("0"); + } + } else { + printf("ERROR!\n"); + } +} +# else +# define DEBUG_PRINT_RESULT(f) f +# endif + +/// @todo Internal representation of big integers in the TEE is implementation +/// defined. If we used the fact that we know how OP-TEE represents big integers +/// internally, then we could directly convert between the TPM representation +/// and the TEE representation rather than go through representation as a byte +/// string. +/// @brief Return the maximum size of to bigNum in crypt_uword_t +/// @param a +/// @param b +/// @return max(BnGetSize(a), BnGetSize(b)) +static inline crypt_uword_t max_size(bigConst a, bigConst b) +{ + return BnGetSize(a) > BnGetSize(b) ? BnGetSize(a) : BnGetSize(b); +} + +/// @brief Return the minimum size of to bigNum in crypt_uword_t +/// @param a +/// @param b +/// @return min(BnGetSize(a), BnGetSize(b)) +static inline crypt_uword_t min_size(bigConst a, bigConst b) +{ + return BnGetSize(a) < BnGetSize(b) ? BnGetSize(a) : BnGetSize(b); +} + +/// @brief Return the size of a bigNum in bit (rounded up to the nearest multiple of 8*sizeof(crypt_uword_t)). +/// @param a a bigNum +/// @return Size of a in bit rounded up to the nearest multiple of 8*sizeof(crypt_uword_t) +static inline size_t BnGetSizeInBit(bigConst a) +{ + return 8 * sizeof(crypt_uword_t) * BnGetSize(a); +} + +/// @brief Return the size of a bigNum in bytes (rounded up to the nearest multiple of ) +/// @param a +/// @return +static inline size_t BnGetSizeInBytes(bigConst a) +{ + return sizeof(crypt_uword_t) * BnGetSize(a); +} + +LIB_EXPORT BOOL BnDiv( + bigNum quotient, bigNum remainder, bigConst dividend, bigConst divisor) +{ +# ifdef DEBUG_OUTPUT_TEE_MATH + printf("BnDiv\n"); +# endif + const NUMBYTES buffer_size = sizeof(crypt_uword_t) * max_size(dividend, divisor); + BYTE buffer[buffer_size]; + + size_t len = TEE_BigIntSizeInU32(BnGetSizeInBit(dividend)); + TEE_BigInt tee_dividend[len]; + TEE_BigIntInit(tee_dividend, len); + TEE_BigInt tee_quotient[len]; /// Yes, this may be too much. + TEE_BigIntInit(tee_quotient, len); + + len = TEE_BigIntSizeInU32(BnGetSizeInBit(divisor)); + TEE_BigInt tee_divisor[TEE_BigIntSizeInU32(BnGetSizeInBit(divisor))]; + TEE_BigIntInit(tee_divisor, len); + TEE_BigInt tee_remainder[len]; + TEE_BigIntInit(tee_remainder, len); + + NUMBYTES size = BnGetSizeInBytes(dividend); + BnToBytes(dividend, buffer, &size); + TEE_BigIntConvertFromOctetString( + tee_dividend, + buffer, + size, + 0); /// @todo Check that all numbers are non-negative. + + size = BnGetSizeInBytes(divisor); + BnToBytes(divisor, buffer, &size); + TEE_BigIntConvertFromOctetString( + tee_divisor, + buffer, + size, + 0); /// @todo Check that all numbers are non-negative. +# ifdef DEBUG_OUTPUT_TEE_MATH + printf(" TEE_BigIntGetBitCount(tee_divisor) returns %" PRIu32 "\n", + TEE_BigIntGetBitCount(tee_divisor)); +# endif + + TEE_BigIntDiv(tee_quotient, tee_remainder, tee_dividend, tee_divisor); + + if(quotient != 0) + { + size_t tee_size = buffer_size; + DEBUG_PRINT_RESULT( + TEE_BigIntConvertToOctetString(buffer, &tee_size, tee_quotient)); + VERIFY(BnFromBytes(quotient, buffer, tee_size)); + } + + if(remainder != 0) + { + size_t tee_size = buffer_size; + DEBUG_PRINT_RESULT( + TEE_BigIntConvertToOctetString(buffer, &tee_size, tee_remainder)); + VERIFY(BnFromBytes(remainder, buffer, tee_size)); + } + return TRUE; +Error: + return FALSE; +} + +LIB_EXPORT BOOL BnMult(bigNum result, bigConst multiplicand, bigConst multiplier) +{ +# ifdef DEBUG_OUTPUT_TEE_MATH + printf("BnMult\n"); +# endif + const NUMBYTES buffer_size = + sizeof(crypt_uword_t) * (BnGetSize(multiplicand) + BnGetSize(multiplier)); + BYTE buffer[buffer_size]; + + size_t len = TEE_BigIntSizeInU32(BnGetSizeInBit(multiplicand)); + TEE_BigInt tee_multiplicand[len]; + TEE_BigIntInit(tee_multiplicand, len); + + len = TEE_BigIntSizeInU32(BnGetSizeInBit(multiplier)); + TEE_BigInt tee_multiplier[len]; + TEE_BigIntInit(tee_multiplier, len); + + len = TEE_BigIntSizeInU32(8 * buffer_size); + TEE_BigInt tee_result[len]; + TEE_BigIntInit(tee_result, len); + + NUMBYTES size = BnGetSizeInBytes(multiplicand); + BnToBytes(multiplicand, buffer, &size); + TEE_BigIntConvertFromOctetString( + tee_multiplicand, + buffer, + size, + 0); /// @todo Check that all numbers are non-negative. + size = BnGetSizeInBytes(multiplier); + BnToBytes(multiplier, buffer, &size); + TEE_BigIntConvertFromOctetString( + tee_multiplier, + buffer, + size, + 0); /// @todo Check that all numbers are non-negative. + + TEE_BigIntMul(tee_result, tee_multiplicand, tee_multiplier); + + size_t tee_size = buffer_size; + TEE_BigIntConvertToOctetString(buffer, &tee_size, tee_result); + VERIFY(BnFromBytes(result, buffer, tee_size)); + return TRUE; +Error: + return FALSE; +} + +LIB_EXPORT BOOL BnModInverse(bigNum result, bigConst number, bigConst modulus) +{ +# ifdef DEBUG_OUTPUT_TEE_MATH + printf("BnModInverse\n"); +# endif + const NUMBYTES buffer_size = sizeof(crypt_uword_t) * max_size(modulus, number); + BYTE buffer[buffer_size]; + + size_t len = TEE_BigIntSizeInU32(BnGetSizeInBit(modulus)); + TEE_BigInt tee_modulus[len]; + TEE_BigIntInit(tee_modulus, len); + TEE_BigInt tee_result[len]; + TEE_BigIntInit(tee_result, len); + + len = TEE_BigIntSizeInU32(BnGetSizeInBit(number)); + TEE_BigInt tee_number[len]; + TEE_BigIntInit(tee_number, len); + + NUMBYTES size = BnGetSizeInBytes(modulus); + BnToBytes(modulus, buffer, &size); + TEE_BigIntConvertFromOctetString( + tee_modulus, + buffer, + size, + 0); /// @todo Check that all numbers are non-negative. + size = BnGetSizeInBytes(number); + BnToBytes(number, buffer, &size); + TEE_BigIntConvertFromOctetString( + tee_number, + buffer, + size, + 0); /// @todo Check that all numbers are non-negative. + + TEE_BigIntMod( + tee_number, tee_number, tee_modulus); // Just in case number >= modulus. + TEE_BigIntInvMod(tee_result, tee_number, tee_modulus); + + size_t tee_size = buffer_size; + TEE_BigIntConvertToOctetString(buffer, &tee_size, tee_result); + VERIFY(BnFromBytes(result, buffer, tee_size)); + return TRUE; +Error: + return FALSE; +} + +LIB_EXPORT BOOL BnModMult(bigNum result, bigConst op1, bigConst op2, bigConst modulus) +{ +# ifdef DEBUG_OUTPUT_TEE_MATH + printf("BnModMult\n"); +# endif + const NUMBYTES buffer_size = sizeof(crypt_uword_t) + * (BnGetSize(modulus) > max_size(op1, op2) + ? BnGetSize(modulus) + : max_size(op1, op2)); + BYTE buffer[buffer_size]; + + size_t len = TEE_BigIntSizeInU32(BnGetSizeInBit(modulus)); + TEE_BigInt tee_modulus[len]; + TEE_BigIntInit(tee_modulus, len); + TEE_BigInt tee_result[len]; + TEE_BigIntInit(tee_result, len); + + len = TEE_BigIntSizeInU32(BnGetSizeInBit(op1)); + TEE_BigInt tee_op1[len]; + TEE_BigIntInit(tee_op1, len); + + len = TEE_BigIntSizeInU32(BnGetSizeInBit(op2)); + TEE_BigInt tee_op2[len]; + TEE_BigIntInit(tee_op2, len); + + NUMBYTES size = BnGetSizeInBytes(modulus); + BnToBytes(modulus, buffer, &size); + TEE_BigIntConvertFromOctetString( + tee_modulus, + buffer, + size, + 0); /// @todo Check that all numbers are non-negative. + size = BnGetSizeInBytes(op1); + BnToBytes(op1, buffer, &size); + TEE_BigIntConvertFromOctetString( + tee_op1, buffer, size, 0); /// @todo Check that all numbers are non-negative. + size = BnGetSizeInBytes(op2); + BnToBytes(op2, buffer, &size); + TEE_BigIntConvertFromOctetString( + tee_op2, buffer, size, 0); /// @todo Check that all numbers are non-negative. + + TEE_BigIntMod(tee_op1, tee_op1, tee_modulus); + TEE_BigIntMod(tee_op2, tee_op2, tee_modulus); + TEE_BigIntMulMod(tee_result, tee_op1, tee_op2, tee_modulus); + + size_t tee_size = buffer_size; + TEE_BigIntConvertToOctetString(buffer, &tee_size, tee_result); + VERIFY(BnFromBytes(result, buffer, tee_size)); + return TRUE; +Error: + return FALSE; +} + +LIB_EXPORT BOOL BnModExp(bigNum result, // OUT: the result + bigConst number, // IN: number to exponentiate + bigConst exponent, // IN: + bigConst modulus // IN: +) +{ +# ifdef DEBUG_OUTPUT_TEE_MATH + printf("BnModExp\n"); +# endif + const NUMBYTES buffer_size = sizeof(crypt_uword_t) + * (BnGetSize(modulus) > max_size(number, exponent) + ? BnGetSize(modulus) + : max_size(number, exponent)); + BYTE buffer[buffer_size]; + + size_t len = TEE_BigIntSizeInU32(BnGetSizeInBit(modulus)); + TEE_BigInt tee_modulus[len]; + TEE_BigIntInit(tee_modulus, len); + TEE_BigInt tee_result[len]; + TEE_BigIntInit(tee_result, len); + + len = TEE_BigIntSizeInU32(BnGetSizeInBit(number)); + TEE_BigInt tee_number[len]; + TEE_BigIntInit(tee_number, len); + + len = TEE_BigIntSizeInU32(BnGetSizeInBit(exponent)); + TEE_BigInt tee_exponent[len]; + TEE_BigIntInit(tee_exponent, len); + + NUMBYTES size = BnGetSizeInBytes(modulus); + BnToBytes(modulus, buffer, &size); + TEE_BigIntConvertFromOctetString( + tee_modulus, + buffer, + size, + 0); /// @todo Check that all numbers are non-negative. + size = BnGetSizeInBytes(number); + BnToBytes(number, buffer, &size); + TEE_BigIntConvertFromOctetString( + tee_number, + buffer, + size, + 0); /// @todo Check that all numbers are non-negative. + size = BnGetSizeInBytes(exponent); + BnToBytes(exponent, buffer, &size); + TEE_BigIntConvertFromOctetString( + tee_exponent, + buffer, + size, + 0); /// @todo Check that all numbers are non-negative. + + TEE_BigIntMod(tee_number, tee_number, tee_modulus); + const size_t fmm_ctx_size = + TEE_BigIntFMMContextSizeInU32(BnGetSizeInBit(modulus)); + uint32_t fmm_ctx[fmm_ctx_size]; + DEBUG_PRINT_RESULT(TEE_BigIntInitFMMContext1( + (TEE_BigIntFMMContext*)fmm_ctx, fmm_ctx_size, tee_modulus)); + DEBUG_PRINT_RESULT(TEE_BigIntExpMod(tee_result, + tee_number, + tee_exponent, + tee_modulus, + (TEE_BigIntFMMContext*)fmm_ctx)); + + size_t tee_size = buffer_size; + DEBUG_PRINT_RESULT(TEE_BigIntConvertToOctetString(buffer, &tee_size, tee_result)); + VERIFY(BnFromBytes(result, buffer, tee_size)); + return TRUE; +Error: + return FALSE; +} + +LIB_EXPORT BOOL BnGcd(bigNum gcd, // OUT: the common divisor + bigConst number1, // IN: + bigConst number2 // IN: +) +{ +# ifdef DEBUG_OUTPUT_TEE_MATH + printf("BnGcd\n"); +# endif + const NUMBYTES buffer_size = sizeof(crypt_uword_t) * max_size(number1, number2); + BYTE buffer[buffer_size]; + + size_t len = TEE_BigIntSizeInU32(BnGetSizeInBit(number1)); + TEE_BigInt tee_number1[len]; + TEE_BigIntInit(tee_number1, len); + + len = TEE_BigIntSizeInU32(BnGetSizeInBit(number1)); + TEE_BigInt tee_number2[len]; + TEE_BigIntInit(tee_number2, len); + + len = TEE_BigIntSizeInU32(8 * sizeof(crypt_uword_t) * min_size(number1, number2)); + TEE_BigInt tee_gcd[len]; + TEE_BigIntInit(tee_gcd, len); + + NUMBYTES size = BnGetSizeInBytes(number1); + BnToBytes(number1, buffer, &size); + TEE_BigIntConvertFromOctetString( + tee_number1, + buffer, + size, + 0); /// @todo Check that all numbers are non-negative. + size = BnGetSizeInBytes(number2); + BnToBytes(number2, buffer, &size); + TEE_BigIntConvertFromOctetString( + tee_number2, + buffer, + size, + 0); /// @todo Check that all numbers are non-negative. + + TEE_BigIntComputeExtendedGcd(tee_gcd, 0, 0, tee_number1, tee_number2); + + size_t tee_size = buffer_size; + TEE_BigIntConvertToOctetString(buffer, &tee_size, tee_gcd); + VERIFY(BnFromBytes(gcd, buffer, tee_size)); + return TRUE; +Error: + return FALSE; +} + +/** + * This is an implementation of https://www.hyperelliptic.org/EFD/g1p/auto-shortw-jacobian.html#doubling-dbl-2007-bl +*/ +static void double_point_jacobi(TEE_BigInt* x3, + TEE_BigInt* y3, + TEE_BigInt* z3, + const TEE_BigInt* x1, + const TEE_BigInt* y1, + const TEE_BigInt* z1, + const TEE_BigInt* a, + const TEE_BigInt* p) +{ + size_t number_size = TEE_BigIntSizeInU32(TEE_BigIntGetBitCount(p)); + + TEE_BigInt xx[number_size]; + TEE_BigIntInit(xx, number_size); + // xx = x1^2 + TEE_BigIntSquareMod(xx, x1, p); + TEE_BigInt yy[number_size]; + TEE_BigIntInit(yy, number_size); + // yy = y1^2 + TEE_BigIntSquareMod(yy, y1, p); + TEE_BigInt yyyy[number_size]; + TEE_BigIntInit(yyyy, number_size); + // yyyy = yy^2 + TEE_BigIntSquareMod(yyyy, yy, p); + TEE_BigInt zz[number_size]; + TEE_BigIntInit(zz, number_size); + // zz = z1^2 + TEE_BigIntSquareMod(zz, z1, p); + TEE_BigInt s[number_size]; + TEE_BigIntInit(s, number_size); + // s = 2*((x1 + yy)^2 - xx - yyyy) + TEE_BigIntAddMod(s, x1, yy, p); + TEE_BigIntSquareMod(s, s, p); + TEE_BigIntSubMod(s, s, xx, p); + TEE_BigIntSubMod(s, s, yyyy, p); + TEE_BigIntAddMod(s, s, s, p); + TEE_BigInt m[number_size]; + TEE_BigIntInit(m, number_size); + // m = 3*xx + a + zz^2 + TEE_BigIntSquareMod(m, zz, p); + TEE_BigIntMulMod(m, m, a, p); + TEE_BigIntAddMod(m, m, xx, p); + TEE_BigIntAddMod(m, m, xx, p); + TEE_BigIntAddMod(m, m, xx, p); + // x3 = m^2 - 2*s + TEE_BigIntSquareMod(x3, m, p); + TEE_BigIntSubMod(x3, x3, s, p); + TEE_BigIntSubMod(x3, x3, s, p); + // y3 = m * (x - x3) - 8*yyyy + TEE_BigIntSubMod(y3, s, x3, p); + TEE_BigIntMulMod(y3, y3, m, p); + TEE_BigIntAddMod(z3, yyyy, yyyy, p); + TEE_BigIntAddMod(z3, z3, z3, p); + TEE_BigIntAddMod(z3, z3, z3, p); + TEE_BigIntSubMod(y3, y3, z3, p); + // z3 = (y1 + z1)^2 - yy -zz + TEE_BigIntAddMod(z3, y1, z1, p); + TEE_BigIntSquareMod(z3, z3, p); + TEE_BigIntSubMod(z3, z3, yy, p); + TEE_BigIntSubMod(z3, z3, zz, p); +} + +/// @brief Return 0xffffffff if a TEE_BigInt is zero, 0 otherwise +/// @param z TEE_BigInt to test +/// @return 0xffffffff if z is zer0 and0 otherwise +static uint32_t is_zero(TEE_BigInt* z) +{ + uint32_t result = (uint32_t)TEE_BigIntCmpS32(z, 0); + result--; + result &= result >> 16; + result &= result >> 8; + result &= result >> 4; + result &= result >> 2; + result &= result >> 1; + result = -result; + return result; +} + +/// @brief Copy src over dst if mask is 0xffffffff, do not if mask is 0. +/// @todo This requires dst and src to have exactly the same size +/// @param dst +/// @param src +/// @param len size of dst and src in uint32_t +/// @param mask +static void conditional_copy(TEE_BigInt* dst, const TEE_BigInt* src, size_t len, uint32_t mask) +{ + for(size_t k = 0; k < len; ++k) + { + dst[k] = ((~mask) & dst[k]) | (mask & src[k]); + } +} +/** + * This is an explicit implementation of https://www.hyperelliptic.org/EFD/g1p/auto-shortw-jacobian.html#addition-add-2007-bl. + * output areas must not overlap with input areas +*/ +static void add_points_jacobi(TEE_BigInt* x3, + TEE_BigInt* y3, + TEE_BigInt* z3, + const TEE_BigInt* x1, + const TEE_BigInt* y1, + const TEE_BigInt* z1, + const TEE_BigInt* x2, + const TEE_BigInt* y2, + const TEE_BigInt* z2, + const TEE_BigInt* p) +{ + size_t number_size = TEE_BigIntSizeInU32(TEE_BigIntGetBitCount(p)); + + TEE_BigInt z1z1[number_size]; + TEE_BigIntInit(z1z1, number_size); + // z1z1 = (z1 * z1) % p + TEE_BigIntSquareMod(z1z1, z1, p); + TEE_BigInt z2z2[number_size]; + TEE_BigIntInit(z2z2, number_size); + // z2z2 = (z2 * z2) % p + TEE_BigIntSquareMod(z2z2, z2, p); + TEE_BigInt u1[number_size]; + TEE_BigIntInit(u1, number_size); + // u1 = (x1 * z2z2) % p + TEE_BigIntMulMod(u1, x1, z2z2, p); + TEE_BigInt u2[number_size]; + TEE_BigIntInit(u2, number_size); + // u2 = (x2 * z1z1) % p + TEE_BigIntMulMod(u2, x2, z1z1, p); + //s1 = (y1 * z2 * z2z2) % p + TEE_BigInt s1[number_size]; + TEE_BigIntInit(s1, number_size); + TEE_BigIntMulMod(s1, y1, z2, p); + TEE_BigIntMulMod(s1, s1, z2z2, p); + TEE_BigInt s2[number_size]; + TEE_BigIntInit(s2, number_size); + // s2 = (y2 * z1 * z1z1) % p + TEE_BigIntMulMod(s2, y2, z1, p); + TEE_BigIntMulMod(s2, s2, z1z1, p); + TEE_BigInt h[number_size]; + TEE_BigIntInit(h, number_size); + // h = (u2 - u1) % p + TEE_BigIntSubMod(h, u2, u1, p); + TEE_BigInt i[number_size]; + TEE_BigIntInit(i, number_size); + // i = (2 * h) % p + TEE_BigIntAddMod(i, h, h, p); + // i = (i * i) % p + TEE_BigIntSquareMod(i, i, p); + TEE_BigInt j[number_size]; + TEE_BigIntInit(j, number_size); + // j = (h * i) % p + TEE_BigIntMulMod(j, h, i, p); + TEE_BigInt r[number_size]; + TEE_BigIntInit(r, number_size); + // r = (2 * (s2 - s1)) % p + TEE_BigIntSubMod(r, s2, s1, p); + TEE_BigIntAddMod(r, r, r, p); + TEE_BigInt v[number_size]; + TEE_BigIntInit(v, number_size); + // v = (u1 * i) % p + TEE_BigIntMulMod(v, u1, i, p); + // x3 = (r * r - j - 2 * v) % p + TEE_BigIntSquareMod(x3, r, p); + TEE_BigIntSubMod(x3, x3, j, p); + TEE_BigIntSubMod(x3, x3, v, p); + TEE_BigIntSubMod(x3, x3, v, p); + // y3 = (r * (v - x3) - 2 * s1 * j) % p + TEE_BigIntSubMod(y3, v, x3, p); + TEE_BigIntMulMod(y3, y3, r, p); + TEE_BigIntMulMod(z3, s1, j, p); + TEE_BigIntSubMod(y3, y3, z3, p); + TEE_BigIntSubMod(y3, y3, z3, p); + // z3 = (z1 + z2) % p + TEE_BigIntAddMod(z3, z1, z2, p); + // z3 = ((z3 * z3 - z1z1 - z2z2) * h) % p + TEE_BigIntSquareMod(z3, z3, p); + TEE_BigIntSubMod(z3, z3, z1z1, p); + TEE_BigIntSubMod(z3, z3, z2z2, p); + TEE_BigIntMulMod(z3, z3, h, p); + + // Handle the case that one of the points is the point at infinity, i.e., z1=0 or z2=0. + uint32_t z1_is_zero = is_zero(z1); + uint32_t z2_is_zero = is_zero(z2); + conditional_copy(x3, x2, number_size, z1_is_zero); + conditional_copy(y3, y2, number_size, z1_is_zero); + conditional_copy(z3, z2, number_size, z1_is_zero); + conditional_copy(x3, x1, number_size, z2_is_zero); + conditional_copy(y3, y1, number_size, z2_is_zero); + conditional_copy(z3, z1, number_size, z2_is_zero); +} + +static void scalar_multiplication_jacobi(TEE_BigInt* x3, + TEE_BigInt* y3, + TEE_BigInt* z3, + const TEE_BigInt* x1, + const TEE_BigInt* y1, + const TEE_BigInt* z1, + const uint8_t* scalar, + size_t scalar_size, + const TEE_BigInt* a, + const TEE_BigInt* p) +{ +# ifdef DEBUG_OUTPUT_TEE_MATH + printf("scalar_multiplication_jacobi\n"); + printf(" x1 = 0x"); + printf_bigint(x1); + printf("\n y1 = 0x"); + printf_bigint(y1); + printf("\n z1 = 0x"); + printf_bigint(z1); + printf("\n s = 0x"); + for(size_t k = 0; k < scalar_size; ++k) + { + printf("%.2x", scalar[k]); + } + printf("\n"); +# endif + if(scalar_size == 0) + { + TEE_BigIntConvertFromS32(x3, 1); + TEE_BigIntConvertFromS32(y3, 1); + TEE_BigIntConvertFromS32(z3, 0); + return; + } +// Macros to access x, y, z coordinates of point k in the buffer of pre-computed points. +# define PRE_X(k) (precomputed + (k) * 3 * number_size) +# define PRE_Y(k) (precomputed + (k) * 3 * number_size + number_size) +# define PRE_Z(k) (precomputed + (k) * 3 * number_size + 2 * number_size) + + size_t number_size = TEE_BigIntSizeInU32(TEE_BigIntGetBitCount(p)); + // Pre-compute multiples 0, 1, 2, ... 15 times the point. + TEE_BigInt precomputed[16 * 3 * number_size]; + for(uint_fast8_t k = 0; k < 3 * 16; ++k) + { + TEE_BigIntInit(precomputed + k * number_size, number_size); + } + TEE_BigIntConvertFromS32(PRE_X(0), 1); + TEE_BigIntConvertFromS32(PRE_Y(0), 1); + TEE_BigIntConvertFromS32(PRE_Z(0), 0); + TEE_BigIntAssign(PRE_X(1), x1); + TEE_BigIntAssign(PRE_Y(1), y1); + TEE_BigIntAssign(PRE_Z(1), z1); + double_point_jacobi( + PRE_X(2), PRE_Y(2), PRE_Z(2), PRE_X(1), PRE_Y(1), PRE_Z(1), a, p); + double_point_jacobi( + PRE_X(4), PRE_Y(4), PRE_Z(4), PRE_X(2), PRE_Y(2), PRE_Z(2), a, p); + double_point_jacobi( + PRE_X(8), PRE_Y(8), PRE_Z(8), PRE_X(4), PRE_Y(4), PRE_Z(4), a, p); + add_points_jacobi(PRE_X(3), + PRE_Y(3), + PRE_Z(3), + PRE_X(1), + PRE_Y(1), + PRE_Z(1), + PRE_X(2), + PRE_Y(2), + PRE_Z(2), + p); + add_points_jacobi(PRE_X(5), + PRE_Y(5), + PRE_Z(5), + PRE_X(1), + PRE_Y(1), + PRE_Z(1), + PRE_X(4), + PRE_Y(4), + PRE_Z(4), + p); + double_point_jacobi( + PRE_X(6), PRE_Y(6), PRE_Z(6), PRE_X(3), PRE_Y(3), PRE_Z(3), a, p); + add_points_jacobi(PRE_X(7), + PRE_Y(7), + PRE_Z(7), + PRE_X(1), + PRE_Y(1), + PRE_Z(1), + PRE_X(6), + PRE_Y(6), + PRE_Z(6), + p); + add_points_jacobi(PRE_X(9), + PRE_Y(9), + PRE_Z(9), + PRE_X(1), + PRE_Y(1), + PRE_Z(1), + PRE_X(8), + PRE_Y(8), + PRE_Z(8), + p); + double_point_jacobi( + PRE_X(10), PRE_Y(10), PRE_Z(10), PRE_X(5), PRE_Y(5), PRE_Z(5), a, p); + add_points_jacobi(PRE_X(11), + PRE_Y(11), + PRE_Z(11), + PRE_X(1), + PRE_Y(1), + PRE_Z(1), + PRE_X(10), + PRE_Y(10), + PRE_Z(10), + p); + double_point_jacobi( + PRE_X(12), PRE_Y(12), PRE_Z(12), PRE_X(6), PRE_Y(6), PRE_Z(6), a, p); + add_points_jacobi(PRE_X(13), + PRE_Y(13), + PRE_Z(13), + PRE_X(1), + PRE_Y(1), + PRE_Z(1), + PRE_X(12), + PRE_Y(12), + PRE_Z(12), + p); + double_point_jacobi( + PRE_X(14), PRE_Y(14), PRE_Z(14), PRE_X(7), PRE_Y(7), PRE_Z(7), a, p); + add_points_jacobi(PRE_X(15), + PRE_Y(15), + PRE_Z(15), + PRE_X(1), + PRE_Y(1), + PRE_Z(1), + PRE_X(14), + PRE_Y(14), + PRE_Z(14), + p); + + TEE_BigInt tmp_buffer[2 * 3 * number_size]; + for(uint_fast8_t k = 0; k < 6; ++k) + { + TEE_BigIntInit(tmp_buffer + k * number_size, number_size); + } + TEE_BigInt* tmp1 = tmp_buffer; + TEE_BigInt* tmp2 = tmp_buffer + 3 * number_size; + TEE_BigInt* t; + int w = scalar[0] >> 4; + TEE_BigIntAssign(tmp1, PRE_X(w)); + TEE_BigIntAssign(tmp1 + number_size, PRE_Y(w)); + TEE_BigIntAssign(tmp1 + 2 * number_size, PRE_Z(w)); + + // Double four times, then add the appropriate pre-computed multiple. + for(int k = 1; k < 2 * scalar_size; ++k) + { + double_point_jacobi(tmp2, + tmp2 + number_size, + tmp2 + 2 * number_size, + tmp1, + tmp1 + number_size, + tmp1 + 2 * number_size, + a, + p); + double_point_jacobi(tmp1, + tmp1 + number_size, + tmp1 + 2 * number_size, + tmp2, + tmp2 + number_size, + tmp2 + 2 * number_size, + a, + p); + double_point_jacobi(tmp2, + tmp2 + number_size, + tmp2 + 2 * number_size, + tmp1, + tmp1 + number_size, + tmp1 + 2 * number_size, + a, + p); + double_point_jacobi(tmp1, + tmp1 + number_size, + tmp1 + 2 * number_size, + tmp2, + tmp2 + number_size, + tmp2 + 2 * number_size, + a, + p); + w = scalar[k >> 1]; + if(k & 1) + { + w &= 0xf; + } + else + { + w >>= 4; + } + add_points_jacobi(tmp2, + tmp2 + number_size, + tmp2 + 2 * number_size, + tmp1, + tmp1 + number_size, + tmp1 + 2 * number_size, + PRE_X(w), + PRE_Y(w), + PRE_Z(w), + p); + // Swap tmp1, tmp2. + t = tmp1; + tmp1 = tmp2; + tmp2 = t; + } + TEE_BigIntAssign(x3, tmp1); + TEE_BigIntAssign(y3, tmp1 + number_size); + TEE_BigIntAssign(z3, tmp1 + 2 * number_size); + +# ifdef DEBUG_OUTPUT_TEE_MATH + printf(" x3 = 0x"); + printf_bigint(x3); + printf("\n y3 = 0x"); + printf_bigint(y3); + printf("\n z3 = 0x"); + printf_bigint(z3); + printf("\n"); +# endif +} + +static void jacobi_to_affine(TEE_BigInt* x3, + TEE_BigInt* y3, + const TEE_BigInt* x1, + const TEE_BigInt* y1, + const TEE_BigInt* z1, + const TEE_BigInt* p) +{ +# ifdef DEBUG_OUTPUT_TEE_MATH + printf("jacobi_to_affine\n"); +# endif + size_t number_size = TEE_BigIntSizeInU32(TEE_BigIntGetBitCount(p)); + TEE_BigInt zi[number_size]; + TEE_BigIntInit(zi, number_size); + TEE_BigInt pm2[number_size]; + TEE_BigIntInit(pm2, number_size); + + const size_t fmm_ctx_size = + TEE_BigIntFMMContextSizeInU32(TEE_BigIntGetBitCount(p)); + uint32_t fmm_ctx[fmm_ctx_size]; + TEE_BigIntInitFMMContext1((TEE_BigIntFMMContext*)fmm_ctx, fmm_ctx_size, p); + + TEE_BigIntConvertFromS32(pm2, 2); + TEE_BigIntSub(pm2, p, pm2); // pm2 <- p-2 + TEE_BigIntExpMod( + zi, z1, pm2, p, (TEE_BigIntFMMContext*)fmm_ctx); // Use Fermat for inversion. + TEE_BigIntMulMod(pm2, zi, zi, p); // pm2 <- zi^2 + TEE_BigIntMulMod(x3, x1, pm2, p); + TEE_BigIntMulMod(pm2, pm2, zi, p); // pm2 <- zi^3 + TEE_BigIntMulMod(y3, y1, pm2, p); +# ifdef DEBUG_OUTPUT_TEE_MATH + printf(" return\n"); +# endif +} + +LIB_EXPORT BOOL BnEccModMult(bigPoint R, // OUT: computed point + pointConst S, // IN: point to multiply by 'd' + bigConst d, // IN: scalar for [d]S + bigCurve E) +{ +# ifdef DEBUG_OUTPUT_TEE_MATH + printf("BnEccModMult(%p, %p, %p, %p)\n", R, S, d, E); +# endif + + if(S == 0) + { + S = CurveGetG(AccessCurveData(E)); + } + + // We assume that everything is sane and coordinates are < p and the + // scalar is at most one word longer than p. + const NUMBYTES buffer_size = sizeof(crypt_uword_t) * (BnGetSize(E->prime) + 1); + BYTE buffer[buffer_size]; + + size_t len = TEE_BigIntSizeInU32(BnGetSizeInBit(E->prime)); + TEE_BigInt tee_p[len]; + TEE_BigIntInit(tee_p, len); + TEE_BigInt tee_x1[len]; + TEE_BigIntInit(tee_x1, len); + TEE_BigInt tee_y1[len]; + TEE_BigIntInit(tee_y1, len); + TEE_BigInt tee_z1[len]; + TEE_BigIntInit(tee_z1, len); + TEE_BigInt tee_x3[len]; + TEE_BigIntInit(tee_x3, len); + TEE_BigInt tee_y3[len]; + TEE_BigIntInit(tee_y3, len); + TEE_BigInt tee_z3[len]; + TEE_BigIntInit(tee_z3, len); + + len = TEE_BigIntSizeInU32(BnGetSizeInBit(E->a)); + TEE_BigInt tee_a[len]; + TEE_BigIntInit(tee_a, len); + + NUMBYTES size = BnGetSizeInBytes(E->prime); + BnToBytes(E->prime, buffer, &size); + TEE_BigIntConvertFromOctetString( + tee_p, buffer, size, 0); /// @todo Check that all numbers are non-negative. + size = BnGetSizeInBytes(E->a); + BnToBytes(E->a, buffer, &size); + TEE_BigIntConvertFromOctetString( + tee_a, buffer, size, 0); /// @todo Check that all numbers are non-negative. + size = BnGetSizeInBytes(S->x); + BnToBytes(S->x, buffer, &size); + TEE_BigIntConvertFromOctetString( + tee_x1, buffer, size, 0); /// @todo Check that all numbers are non-negative. + size = BnGetSizeInBytes(S->y); + BnToBytes(S->y, buffer, &size); + TEE_BigIntConvertFromOctetString( + tee_y1, buffer, size, 0); /// @todo Check that all numbers are non-negative. + TEE_BigIntConvertFromS32(tee_z1, 1); + size = BnGetSizeInBytes(d); + BnToBytes(d, buffer, &size); + + scalar_multiplication_jacobi( + tee_x3, tee_y3, tee_z3, tee_x1, tee_y1, tee_z1, buffer, size, tee_a, tee_p); + jacobi_to_affine(tee_x1, tee_y1, tee_x3, tee_y3, tee_z3, tee_p); + + size_t tee_size = buffer_size; + TEE_BigIntConvertToOctetString(buffer, &tee_size, tee_x1); + VERIFY(BnFromBytes(R->x, buffer, tee_size)); + tee_size = buffer_size; + TEE_BigIntConvertToOctetString(buffer, &tee_size, tee_y1); + VERIFY(BnFromBytes(R->y, buffer, tee_size)); + buffer[0] = 1; + VERIFY(BnFromBytes(R->z, buffer, 1)); + return TRUE; +Error: + return FALSE; +} + +LIB_EXPORT BOOL BnEccModMult2(bigPoint R, // OUT: computed point + pointConst S, // IN: optional point + bigConst d, // IN: scalar for [d]S or [d]G + pointConst Q, // IN: second point + bigConst u, // IN: second scalar + bigCurve E // IN: curve +) +{ +# ifdef DEBUG_OUTPUT_TEE_MATH + printf("BnEccModMult2\n"); +# endif + // We assume that everything is sane and coordinates are < p and the + // scalar is at most one word longer than p. + const NUMBYTES buffer_size = sizeof(crypt_uword_t) * (BnGetSize(E->prime) + 1); + BYTE buffer[buffer_size]; + + size_t len = TEE_BigIntSizeInU32(BnGetSizeInBit(E->prime)); + TEE_BigInt tee_p[len]; + TEE_BigIntInit(tee_p, len); + TEE_BigInt tee_x1[len]; + TEE_BigIntInit(tee_x1, len); + TEE_BigInt tee_y1[len]; + TEE_BigIntInit(tee_y1, len); + TEE_BigInt tee_z1[len]; + TEE_BigIntInit(tee_z1, len); + TEE_BigInt tee_x2[len]; + TEE_BigIntInit(tee_x2, len); + TEE_BigInt tee_y2[len]; + TEE_BigIntInit(tee_y2, len); + TEE_BigInt tee_z2[len]; + TEE_BigIntInit(tee_z2, len); + TEE_BigInt tee_x3[len]; + TEE_BigIntInit(tee_x3, len); + TEE_BigInt tee_y3[len]; + TEE_BigIntInit(tee_y3, len); + TEE_BigInt tee_z3[len]; + TEE_BigIntInit(tee_z3, len); + + len = TEE_BigIntSizeInU32(BnGetSizeInBit(E->a)); + TEE_BigInt tee_a[len]; + TEE_BigIntInit(tee_a, len); + + NUMBYTES size = BnGetSizeInBytes(E->prime); + BnToBytes(E->prime, buffer, &size); + TEE_BigIntConvertFromOctetString( + tee_p, buffer, size, 0); /// @todo Check that all numbers are non-negative. + size = BnGetSizeInBytes(E->a); + BnToBytes(E->a, buffer, &size); + TEE_BigIntConvertFromOctetString( + tee_a, buffer, size, 0); /// @todo Check that all numbers are non-negative. + size = BnGetSizeInBytes(S->x); + BnToBytes(S->x, buffer, &size); + TEE_BigIntConvertFromOctetString( + tee_x1, buffer, size, 0); /// @todo Check that all numbers are non-negative. + size = BnGetSizeInBytes(S->y); + BnToBytes(S->y, buffer, &size); + TEE_BigIntConvertFromOctetString( + tee_y1, buffer, size, 0); /// @todo Check that all numbers are non-negative. + TEE_BigIntConvertFromS32(tee_z1, 1); + size = BnGetSizeInBytes(d); + BnToBytes(d, buffer, &size); + size = BnGetSizeInBytes(Q->x); + BnToBytes(Q->x, buffer, &size); + TEE_BigIntConvertFromOctetString( + tee_x2, buffer, size, 0); /// @todo Check that all numbers are non-negative. + size = BnGetSizeInBytes(Q->y); + BnToBytes(Q->y, buffer, &size); + TEE_BigIntConvertFromOctetString( + tee_y2, buffer, size, 0); /// @todo Check that all numbers are non-negative. + TEE_BigIntConvertFromS32(tee_z2, 1); + size = BnGetSizeInBytes(d); + BnToBytes(d, buffer, &size); + + /// @todo Use a more efficient algorithm for multiple scalar multiplication. + scalar_multiplication_jacobi( + tee_x3, tee_y3, tee_z3, tee_x1, tee_y1, tee_z1, buffer, size, tee_a, tee_p); + size = BnGetSizeInBytes(u); + BnToBytes(u, buffer, &size); + scalar_multiplication_jacobi( + tee_x1, tee_y1, tee_z1, tee_x2, tee_y2, tee_z2, buffer, size, tee_a, tee_p); + add_points_jacobi(tee_x2, + tee_y2, + tee_z2, + tee_x1, + tee_y1, + tee_z1, + tee_x3, + tee_y3, + tee_z3, + tee_p); + jacobi_to_affine(tee_x1, tee_y1, tee_x2, tee_y2, tee_z2, tee_p); + + size_t tee_size = buffer_size; + TEE_BigIntConvertToOctetString(buffer, &tee_size, tee_x1); + VERIFY(BnFromBytes(R->x, buffer, tee_size)); + tee_size = buffer_size; + TEE_BigIntConvertToOctetString(buffer, &tee_size, tee_y1); + VERIFY(BnFromBytes(R->y, buffer, tee_size)); + buffer[0] = 1; + VERIFY(BnFromBytes(R->z, buffer, 1)); + return TRUE; +Error: + return FALSE; +} +#endif diff --git a/ta/ftpm/tee/TpmToTEESupport.c b/ta/ftpm/tee/TpmToTEESupport.c new file mode 100644 index 00000000000..643494c7376 --- /dev/null +++ b/ta/ftpm/tee/TpmToTEESupport.c @@ -0,0 +1,16 @@ +/* SPDX-License-Identifier: BSD-2-Clause */ +/********************************************************************** + * Copyright (c) 2024, Siemens AG + * All rights reserved. + */ + +#include "Tpm.h" + +#if defined(HASH_LIB_TEE) || defined(MATH_LIB_TEE) || defined(SYM_LIB_TEE) + +LIB_EXPORT int SupportLibInit(void) +{ + return TRUE; +} + +#endif diff --git a/ta/ftpm/tee/TpmToTEESym.c b/ta/ftpm/tee/TpmToTEESym.c new file mode 100644 index 00000000000..aaa161fafdc --- /dev/null +++ b/ta/ftpm/tee/TpmToTEESym.c @@ -0,0 +1,445 @@ +/* SPDX-License-Identifier: BSD-2-Clause */ +/********************************************************************** + * Copyright (c) 2024, Siemens AG + * All rights reserved. + */ + +#include +#include +#ifdef DEBUG_OUTPUT_TEE_SYM +# include +#endif + +#ifdef DEBUG_OUTPUT_TEE_SYM +# define DEBUG_PRINT_RESULT(f) printf(" " #f " returns %" PRIx32 "\n", f) +#else +# define DEBUG_PRINT_RESULT(f) f +#endif + +/// @todo It is ugly to repeat these definitions here rather than just include TpmToTEESym.h, but this would require a major re-structuring of h-files. + +/// @brief The TEE does not export a key schedule, so this is not really a key schedule but rather a copy of the key. +typedef struct +{ + uint16_t keySizeInBytes; + uint8_t key[32]; +} tpmKeyScheduleAES; + +/// @brief The TEE does not export a key schedule, so this is not really a key schedule but rather a copy of the key. +typedef struct +{ + uint16_t keySizeInBytes; + uint8_t key[24]; +} tpmKeyScheduleTDES; + +/// @brief The TEE does not export a key schedule, so this is not really a key schedule but rather a copy of the key. +typedef struct +{ + uint16_t keySizeInBytes; + uint8_t key[16]; +} tpmKeyScheduleSM4; + +/// @brief Set AES key. +/// @param[out] key_schedule pointer to space for storing the key schedule +/// @param[in] key pointer to the key +/// @param[in] keySizeInBytes length of the key in bytes +/// @return 0 if ok, any other value otherwise +/// @todo There is no `finalize` function, so we can't allocate the key schedule here, because we could never free it. +int TEE_SetKeyAES( + tpmKeyScheduleAES* key_schedule, const uint8_t* key, uint16_t keySizeInBytes) +{ +#ifdef DEBUG_OUTPUT_TEE_SYM + printf("TEE_SetKeyAES(%p, %p, %d)\n", key_schedule, key, (int)keySizeInBytes); + printf(" key = "); + for(uint16_t k = 0; k < keySizeInBytes; ++k) + { + printf("%.2x", (unsigned int)(key[k])); + } + printf("\n"); +#endif + if(((keySizeInBytes == 16) || (keySizeInBytes == 24) || (keySizeInBytes == 32)) + && (keySizeInBytes <= sizeof(key_schedule->key))) + { + key_schedule->keySizeInBytes = keySizeInBytes; + memcpy(key_schedule->key, key, keySizeInBytes); + return 0; + } + else + { + return 1; + } +} + +/// @brief Set DES key. +/// @param[out] key_schedule pointer to space for storing the key schedule +/// @param[in] key pointer to the key +/// @param[in] keySizeInBytes length of the key in bytes +/// @return 0 if ok, any other value otherwise +/// @todo There is no `finalize` function, so we can't allocate the key schedule here, because we could never free it. +int TEE_SetKeyTDES( + tpmKeyScheduleTDES* key_schedule, const uint8_t* key, uint16_t keySizeInBytes) +{ +#ifdef DEBUG_OUTPUT_TEE_SYM + printf("TEE_SetKeyTDES(%p, %p, %d)\n", key_schedule, key, (int)keySizeInBytes); + printf(" key = "); + for(uint16_t k = 0; k < keySizeInBytes; ++k) + { + printf("%.2x", (unsigned int)(key[k])); + } + printf("\n"); +#endif + if(((keySizeInBytes == 16) || (keySizeInBytes == 24)) + && (keySizeInBytes <= sizeof(key_schedule->key))) + { + key_schedule->keySizeInBytes = keySizeInBytes; + memcpy(key_schedule->key, key, keySizeInBytes); + return 0; + } + else + { + return 1; + } +} + +/// @brief Set SM4 key. +/// @param[out] key_schedule pointer to space for storing the key schedule +/// @param[in] key pointer to the key +/// @param[in] keySizeInBytes length of the key in bytes +/// @return 0 if ok, any other value otherwise +/// @todo There is no `finalize` function, so we can't allocate the key schedule here, because we could never free it. +int TEE_SetKeySM4( + tpmKeyScheduleSM4* key_schedule, const uint8_t* key, uint16_t keySizeInBytes) +{ +#ifdef DEBUG_OUTPUT_TEE_SYM + printf("TEE_SetKeySM4(%p, %p, %d)\n", key_schedule, key, (int)keySizeInBytes); + printf(" key = "); + for(uint16_t k = 0; k < keySizeInBytes; ++k) + { + printf("%.2x", (unsigned int)(key[k])); + } + printf("\n"); +#endif + if((keySizeInBytes == 16) && (keySizeInBytes <= sizeof(key_schedule->key))) + { + key_schedule->keySizeInBytes = keySizeInBytes; + memcpy(key_schedule->key, key, keySizeInBytes); + return 0; + } + else + { + return 1; + } +} + +typedef enum +{ + ALGO_AES, + ALGO_TDES, + ALGO_SM4 +} SymAlgoType; + +typedef enum +{ + OP_ENCRYPT, + OP_DECRYPT +} SymOp; + +/// @brief Encrypt or decrypt one block of data with AES, TDES or SM4 +/// @param[out] out pointer to space for one block of output data (16 bytes for AES and SM4, 8 bytes for TDES) +/// @param[in] algo algorithm +/// @param[in] op operation +/// @param[in] key pointer to key +/// @param[in] keySizeInBytes length of key in bytes +/// @param[in] in pointer to one block of input data (16 bytes for AES and SM4, 8 bytes for TDES) +static void TEE_sym(uint8_t* out, + SymAlgoType algo, + SymOp op, + const uint8_t* key, + uint16_t keySizeInBytes, + const uint8_t* in) +{ + uint32_t objectType; + uint32_t mode; + uint32_t algorithm; + unsigned int blockSize; + switch(algo) + { + case ALGO_AES: + objectType = TEE_TYPE_AES; + algorithm = TEE_ALG_AES_ECB_NOPAD; + blockSize = 16; + break; + case ALGO_TDES: + objectType = TEE_TYPE_DES3; + algorithm = TEE_ALG_DES3_ECB_NOPAD; + blockSize = 8; + break; + case ALGO_SM4: + objectType = TEE_TYPE_SM4; + algorithm = TEE_ALG_SM4_ECB_NOPAD; + blockSize = 16; + break; + default: + /// @todo Do error handling! + break; + } + switch(op) + { + case OP_ENCRYPT: + mode = TEE_MODE_ENCRYPT; + break; + case OP_DECRYPT: + mode = TEE_MODE_DECRYPT; + break; + default: + /// @todo Do error handling! + break; + } + + TEE_ObjectHandle object; + DEBUG_PRINT_RESULT( + TEE_AllocateTransientObject(objectType, 8 * keySizeInBytes, &object)); + TEE_Attribute attr; + TEE_InitRefAttribute(&attr, TEE_ATTR_SECRET_VALUE, key, keySizeInBytes); + DEBUG_PRINT_RESULT(TEE_PopulateTransientObject(object, &attr, 1)); + TEE_OperationHandle operation; + DEBUG_PRINT_RESULT( + TEE_AllocateOperation(&operation, algorithm, mode, 8 * keySizeInBytes)); + DEBUG_PRINT_RESULT(TEE_SetOperationKey(operation, object)); + + TEE_CipherInit(operation, 0, 0); + size_t outlen = blockSize; +#ifdef DEBUG_OUTPUT_TEE_SYM + printf("TEE_CipherDoFinal(operation, in, blockSize, out, &outlen) - BEFORE CALL\n"); + printf(" in = "); + for(size_t k = 0; k < blockSize; ++k) + { + printf("%.2x", in[k]); + } + printf("\n"); + printf(" out = "); + for(size_t k = 0; k < blockSize; ++k) + { + printf("%.2x", out[k]); + } + printf("\n"); +#endif + DEBUG_PRINT_RESULT(TEE_CipherDoFinal(operation, in, blockSize, out, &outlen)); +#ifdef DEBUG_OUTPUT_TEE_SYM + printf("TEE_CipherDoFinal(operation, in, blockSize, out, &outlen) - AFTER CALL\n"); + printf(" in = "); + for(size_t k = 0; k < blockSize; ++k) + { + printf("%.2x", in[k]); + } + printf("\n"); + printf(" out = "); + for(size_t k = 0; k < blockSize; ++k) + { + printf("%.2x", out[k]); + } + printf("\n"); +#endif + + TEE_FreeOperation(operation); + TEE_FreeTransientObject(object); + /// @todo Do proper error handling. +} + +/// @brief Encrypt a single 16 byte block of data with AES. +/// @param out pointer to 16 bytes space for output +/// @param key_schedule pointer to the key schedule, initialized with TEE_SetKeyAES(). +/// @param in pointer to 16 bytes input +/// @todo This is a very thin wrapper that may not be needed. +void TEE_AESEncrypt( + uint8_t* out, const tpmKeyScheduleAES* key_schedule, const uint8_t* in) +{ +#ifdef DEBUG_OUTPUT_TEE_SYM + printf("TEE_AESEncrypt(%p, %p, %p)\n", out, key_schedule, in); + printf(" in = "); + for(size_t k = 0; k < 16; ++k) + { + printf("%.2x", (unsigned int)(in[k])); + } + printf("\n"); +#endif + TEE_sym(out, + ALGO_AES, + OP_ENCRYPT, + key_schedule->key, + key_schedule->keySizeInBytes, + in); +#ifdef DEBUG_OUTPUT_TEE_SYM + printf(" out = "); + for(size_t k = 0; k < 16; ++k) + { + printf("%.2x", (unsigned int)(out[k])); + } + printf("\n"); +#endif +} + +/// @brief Decrypt a single 16 byte block of data with AES. +/// @param out pointer to 16 bytes space for output +/// @param key_schedule pointer to the key schedule, initialized with TEE_SetKeyAES(). +/// @param in pointer to 16 bytes input +/// @todo This is a very thin wrapper that may not be needed. +void TEE_AESDecrypt( + uint8_t* out, const tpmKeyScheduleAES* key_schedule, const uint8_t* in) +{ +#ifdef DEBUG_OUTPUT_TEE_SYM + printf("TEE_AESDecrypt(%p, %p, %p)\n", out, key_schedule, in); + printf(" in = "); + for(size_t k = 0; k < 16; ++k) + { + printf("%.2x", (unsigned int)(in[k])); + } + printf("\n"); +#endif + TEE_sym(out, + ALGO_AES, + OP_DECRYPT, + key_schedule->key, + key_schedule->keySizeInBytes, + in); +#ifdef DEBUG_OUTPUT_TEE_SYM + printf(" out = "); + for(size_t k = 0; k < 16; ++k) + { + printf("%.2x", (unsigned int)(in[k])); + } + printf("\n"); +#endif +} + +/// @brief Encrypt a single 8 byte block of data with TDES. +/// @param out pointer to 8 bytes space for output +/// @param key_schedule pointer to the key schedule, initialized with TEE_SetKeyTDES(). +/// @param in pointer to 8 bytes input +/// @todo This is a very thin wrapper that may not be needed. +void TEE_TDESEncrypt( + uint8_t* out, const tpmKeyScheduleTDES* key_schedule, const uint8_t* in) +{ +#ifdef DEBUG_OUTPUT_TEE_SYM + printf("TEE_TDESEncrypt(%p, %p, %p)\n", out, key_schedule, in); + printf(" in = "); + for(size_t k = 0; k < 8; ++k) + { + printf("%.2x", (unsigned int)(in[k])); + } + printf("\n"); +#endif + TEE_sym(out, + ALGO_TDES, + OP_ENCRYPT, + key_schedule->key, + key_schedule->keySizeInBytes, + in); +#ifdef DEBUG_OUTPUT_TEE_SYM + printf(" out = "); + for(size_t k = 0; k < 8; ++k) + { + printf("%.2x", (unsigned int)(in[k])); + } + printf("\n"); +#endif +} + +/// @brief Decrypt a single 8 byte block of data with TDES. +/// @param out pointer to 8 bytes space for output +/// @param key_schedule pointer to the key schedule, initialized with TEE_SetKeyTDES(). +/// @param in pointer to 8 bytes input +/// @todo This is a very thin wrapper that may not be needed. +void TEE_TDESDecrypt( + uint8_t* out, const tpmKeyScheduleTDES* key_schedule, const uint8_t* in) +{ +#ifdef DEBUG_OUTPUT_TEE_SYM + printf("TEE_TDESDecrypt(%p, %p, %p)\n", out, key_schedule, in); + printf(" in = "); + for(size_t k = 0; k < 8; ++k) + { + printf("%.2x", (unsigned int)(in[k])); + } + printf("\n"); +#endif + TEE_sym(out, + ALGO_TDES, + OP_DECRYPT, + key_schedule->key, + key_schedule->keySizeInBytes, + in); +#ifdef DEBUG_OUTPUT_TEE_SYM + printf(" out = "); + for(size_t k = 0; k < 8; ++k) + { + printf("%.2x", (unsigned int)(in[k])); + } + printf("\n"); +#endif +} + +/// @brief Encrypt a single 16 byte block of data with SM4. +/// @param out pointer to 16 bytes space for output +/// @param key_schedule pointer to the key schedule, initialized with TEE_SetKeySM4(). +/// @param in pointer to 16 bytes input +/// @todo This is a very thin wrapper that may not be needed. +void TEE_SM4Encrypt( + uint8_t* out, const tpmKeyScheduleSM4* key_schedule, const uint8_t* in) +{ +#ifdef DEBUG_OUTPUT_TEE_SYM + printf("TEE_SM4Encrypt(%p, %p, %p)\n", out, key_schedule, in); + printf(" in = "); + for(size_t k = 0; k < 16; ++k) + { + printf("%.2x", (unsigned int)(in[k])); + } + printf("\n"); +#endif + TEE_sym(out, + ALGO_SM4, + OP_ENCRYPT, + key_schedule->key, + key_schedule->keySizeInBytes, + in); +#ifdef DEBUG_OUTPUT_TEE_SYM + printf(" out = "); + for(size_t k = 0; k < 16; ++k) + { + printf("%.2x", (unsigned int)(in[k])); + } + printf("\n"); +#endif +} + +/// @brief Decrypt a single 16 byte block of data with SM4. +/// @param out pointer to 16 bytes space for output +/// @param key_schedule pointer to the key schedule, initialized with TEE_SetKeySM4(). +/// @param in pointer to 16 bytes input +/// @todo This is a very thin wrapper that may not be needed. +void TEE_SM4Decrypt( + uint8_t* out, const tpmKeyScheduleSM4* key_schedule, const uint8_t* in) +{ +#ifdef DEBUG_OUTPUT_TEE_SYM + printf("TEE_SM4Decrypt(%p, %p, %p)\n", out, key_schedule, in); + printf(" in = "); + for(size_t k = 0; k < 16; ++k) + { + printf("%.2x", (unsigned int)(in[k])); + } + printf("\n"); +#endif + TEE_sym(out, + ALGO_SM4, + OP_DECRYPT, + key_schedule->key, + key_schedule->keySizeInBytes, + in); +#ifdef DEBUG_OUTPUT_TEE_SYM + printf(" out = "); + for(size_t k = 0; k < 16; ++k) + { + printf("%.2x", (unsigned int)(in[k])); + } + printf("\n"); +#endif +} From aaf5a95e2c4deb8ec18358278ca762b025f9b941 Mon Sep 17 00:00:00 2001 From: Jens Wiklander Date: Tue, 15 Oct 2024 18:13:08 +0200 Subject: [PATCH 09/27] ftpm: fixup TEE crypto API wrappers Refactors the imported TEE crypto API wrappers to better follow the OP-TEE coding style. On touched files, set Microsoft copyright year to 2018 based on git history in the reference source. Add Linaro copyright. Signed-off-by: Jens Wiklander --- ta/ftpm/include/TEE/TpmToTEEMath.h | 74 +- ta/ftpm/include/TEE/TpmToTEESym.h | 206 ++-- ta/ftpm/tee/TpmToTEEMath.c | 1602 +++++++++++----------------- ta/ftpm/tee/TpmToTEESym.c | 532 +++------ 4 files changed, 911 insertions(+), 1503 deletions(-) diff --git a/ta/ftpm/include/TEE/TpmToTEEMath.h b/ta/ftpm/include/TEE/TpmToTEEMath.h index 6aaebf71abf..b7fcf58aed6 100644 --- a/ta/ftpm/include/TEE/TpmToTEEMath.h +++ b/ta/ftpm/include/TEE/TpmToTEEMath.h @@ -1,70 +1,72 @@ /* SPDX-License-Identifier: BSD-2-Clause */ -/********************************************************************** +/* * Copyright (c) 2024, Siemens AG * All rights reserved. + * Copyright (c) 2024, Linaro Limited * * Based on the original code by Microsoft. Modified to support using * TEE functions to provide cryptographic functionality. * * Portions Copyright Microsoft Corporation, see below for details: * - * The copyright in this software is being made available under the BSD License, - * included below. This software may be subject to other third party and - * contributor rights, including patent rights, and no such rights are granted - * under this license. + * The copyright in this software is being made available under the BSD + * License, included below. This software may be subject to other third + * party and contributor rights, including patent rights, and no such + * rights are granted under this license. * - * Copyright (c) Microsoft Corporation + * Copyright (c) 2018 Microsoft Corporation * - * All rights reserved. + * All rights reserved. * - * BSD License + * BSD License * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: * - * Redistributions of source code must retain the above copyright notice, this list - * of conditions and the following disclaimer. + * Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. * - * 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. + * 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. * - * 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. + * 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. */ -//** Introduction -// This file contains the structure definitions used for ECC in the LibTomCrypt -// version of the code. These definitions would change, based on the library. -// The ECC-related structures that cross the TPM interface are defined -// in TpmTypes.h -// +/* + * This file contains the structure definitions used for ECC in the TEE + * crypto API version of the code. These definitions would change, based on + * the library. The ECC-related structures that cross the TPM interface + * are defined in TpmTypes.h + */ #ifndef MATH_LIB_DEFINED #define MATH_LIB_DEFINED #define MATH_LIB_TEE -#include -#include - typedef ECC_CURVE_DATA bnCurve_t; typedef bnCurve_t* bigCurve; +#define SYMMETRIC_ALIGNMENT RADIX_BYTES + #define AccessCurveData(E) (E) #define CURVE_INITIALIZED(name, initializer) \ - bnCurve_t* name = (ECC_CURVE_DATA*)GetCurveData(initializer) + bnCurve_t* name = (ECC_CURVE_DATA*)GetCurveData(initializer) #define CURVE_FREE(E) -#endif // MATH_LIB_DEFINED +#endif /*MATH_LIB_DEFINED*/ diff --git a/ta/ftpm/include/TEE/TpmToTEESym.h b/ta/ftpm/include/TEE/TpmToTEESym.h index 17d167d257c..88b0a16598e 100644 --- a/ta/ftpm/include/TEE/TpmToTEESym.h +++ b/ta/ftpm/include/TEE/TpmToTEESym.h @@ -1,49 +1,52 @@ /* SPDX-License-Identifier: BSD-2-Clause */ -/********************************************************************** +/* * Copyright (c) 2024, Siemens AG * All rights reserved. + * Copyright (c) 2024, Linaro Limited * * Based on the original code by Microsoft. Modified to support using * TEE functions to provide cryptographic functionality. * * Portions Copyright Microsoft Corporation, see below for details: * - * The copyright in this software is being made available under the BSD License, - * included below. This software may be subject to other third party and - * contributor rights, including patent rights, and no such rights are granted - * under this license. + * The copyright in this software is being made available under the BSD + * License, included below. This software may be subject to other third + * party and contributor rights, including patent rights, and no such + * rights are granted under this license. * - * Copyright (c) Microsoft Corporation + * Copyright (c) 2018 Microsoft Corporation * - * All rights reserved. + * All rights reserved. * - * BSD License + * BSD License * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: * - * Redistributions of source code must retain the above copyright notice, this list - * of conditions and the following disclaimer. + * Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. * - * 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. + * 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. * - * 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. + * 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. */ -//** Introduction -// -// This header file is used to 'splice' the TEE sym code into the TPM code. +/* + * This header file is used to 'splice' the TEE sym code into the TPM code. + */ #ifndef SYM_LIB_DEFINED #define SYM_LIB_DEFINED @@ -55,97 +58,106 @@ #include #include -/// @brief The TEE does not export a key schedule, so this is not really a key schedule but rather a copy of the key. -typedef struct -{ - uint16_t keySizeInBytes; - uint8_t key[32]; +/* + * The TEE does not export a key schedule, so these structs do not not + * really represent a key schedule but rather a copy of the key. + */ +typedef struct { + uint16_t keySizeInBytes; + uint8_t key[32]; } tpmKeyScheduleAES; -/// @brief The TEE does not export a key schedule, so this is not really a key schedule but rather a copy of the key. -typedef struct -{ - uint16_t keySizeInBytes; - uint8_t key[24]; +typedef struct { + uint16_t keySizeInBytes; + uint8_t key[24]; } tpmKeyScheduleTDES; -/// @brief The TEE does not export a key schedule, so this is not really a key schedule but rather a copy of the key. -typedef struct -{ - uint16_t keySizeInBytes; - uint8_t key[16]; +typedef struct { + uint16_t keySizeInBytes; + uint8_t key[16]; } tpmKeyScheduleSM4; -int TEE_SetKeyAES( - tpmKeyScheduleAES* key_schedule, const uint8_t* key, uint16_t keySizeInBytes); -int TEE_SetKeyTDES( - tpmKeyScheduleTDES* key_schedule, const uint8_t* key, uint16_t keySizeInBytes); -int TEE_SetKeySM4( - tpmKeyScheduleSM4* key_schedule, const uint8_t* key, uint16_t keySizeInBytes); - -void TEE_AESEncrypt( - uint8_t* out, const tpmKeyScheduleAES* key_schedule, const uint8_t* in); -void TEE_AESDecrypt( - uint8_t* out, const tpmKeyScheduleAES* key_schedule, const uint8_t* in); -void TEE_TDESEncrypt( - uint8_t* out, const tpmKeyScheduleTDES* key_schedule, const uint8_t* in); -void TEE_TDESDecrypt( - uint8_t* out, const tpmKeyScheduleTDES* key_schedule, const uint8_t* in); -void TEE_SM4Encrypt( - uint8_t* out, const tpmKeyScheduleSM4* key_schedule, const uint8_t* in); -void TEE_SM4Decrypt( - uint8_t* out, const tpmKeyScheduleSM4* key_schedule, const uint8_t* in); - -//*************************************************************** -//** Links to the TEE sym code -//*************************************************************** +int TEE_SetKeyAES(tpmKeyScheduleAES *key_schedule, const uint8_t *key, + uint16_t keySizeInBytes); +int TEE_SetKeyTDES(tpmKeyScheduleTDES *key_schedule, const uint8_t *key, + uint16_t keySizeInBytes); +int TEE_SetKeySM4(tpmKeyScheduleSM4 *key_schedule, const uint8_t *key, + uint16_t keySizeInBytes); + +void TEE_AESEncrypt(uint8_t *out, const tpmKeyScheduleAES *key_schedule, + const uint8_t *in); +void TEE_AESDecrypt(uint8_t *out, const tpmKeyScheduleAES *key_schedule, + const uint8_t *in); +void TEE_TDESEncrypt(uint8_t *out, const tpmKeyScheduleTDES *key_schedule, + const uint8_t *in); +void TEE_TDESDecrypt(uint8_t *out, const tpmKeyScheduleTDES *key_schedule, + const uint8_t *in); +void TEE_SM4Encrypt(uint8_t *out, const tpmKeyScheduleSM4 *key_schedule, + const uint8_t *in); +void TEE_SM4Decrypt(uint8_t *out, const tpmKeyScheduleSM4 *key_schedule, + const uint8_t *in); + +/* + * Links to the TEE sym code + */ #if ALG_CAMELLIA # undef ALG_CAMELLIA # define ALG_CAMELLIA ALG_NO -//#error "Camellia is not available" #endif -// Define the order of parameters to the library functions that do block encryption -// and decryption. +/* + * Define the order of parameters to the library functions that do block + * encryption and decryption. + */ typedef void (*TpmCryptSetSymKeyCall_t)(void* keySchedule, BYTE* out, const BYTE* in); -// The Crypt functions that call the block encryption function use the parameters -// in the order: -// 1) keySchedule -// 2) in buffer -// 3) out buffer -// Since the functions TEE_Encrypt* uses a different order, we need to swizzle the -// values to the order required by the library. +/* + * The Crypt functions that call the block encryption function use the + * parameters in the order: + * 1) keySchedule + * 2) in buffer + * 3) out buffer + * Since the functions TEE_Encrypt* uses a different order, we need to + * swizzle the values to the order required by the library. + */ #define SWIZZLE(keySchedule, in, out) \ - (BYTE*)(out), (void*)(keySchedule), (const BYTE*)(in) + (BYTE *)(out), (void *)(keySchedule), (const BYTE *)(in) -// Macros to set up the encryption/decryption key schedules -// -// AES: +/* + * Macros to set up the encryption/decryption key schedules + */ +/* AES */ #define TpmCryptSetEncryptKeyAES(key, keySizeInBits, schedule) \ - TEE_SetKeyAES((tpmKeyScheduleAES*)(schedule), key, BITS_TO_BYTES(keySizeInBits)) + TEE_SetKeyAES((tpmKeyScheduleAES *)(schedule), key, \ + BITS_TO_BYTES(keySizeInBits)) #define TpmCryptSetDecryptKeyAES(key, keySizeInBits, schedule) \ - TEE_SetKeyAES((tpmKeyScheduleAES*)(schedule), key, BITS_TO_BYTES(keySizeInBits)) + TEE_SetKeyAES((tpmKeyScheduleAES *)(schedule), key, \ + BITS_TO_BYTES(keySizeInBits)) -// TDES: +/* TDES */ #define TpmCryptSetEncryptKeyTDES(key, keySizeInBits, schedule) \ - TEE_SetKeyTDES((tpmKeyScheduleTDES*)(schedule), (key), BITS_TO_BYTES(keySizeInBits)) + TEE_SetKeyTDES((tpmKeyScheduleTDES *)(schedule), (key), \ + BITS_TO_BYTES(keySizeInBits)) #define TpmCryptSetDecryptKeyTDES(key, keySizeInBits, schedule) \ - TEE_SetKeyTDES((tpmKeyScheduleTDES*)(schedule), (key), BITS_TO_BYTES(keySizeInBits)) + TEE_SetKeyTDES((tpmKeyScheduleTDES *)(schedule), (key), \ + BITS_TO_BYTES(keySizeInBits)) -// SM4: +/* SM4 */ #define TpmCryptSetEncryptKeySM4(key, keySizeInBits, schedule) \ - TEE_SetKeySM4((tpmKeyScheduleSM4*)(schedule), (key), BITS_TO_BYTES(keySizeInBits)) + TEE_SetKeySM4((tpmKeyScheduleSM4 *)(schedule), (key), \ + BITS_TO_BYTES(keySizeInBits)) #define TpmCryptSetDecryptKeySM4(key, keySizeInBits, schedule) \ - TEE_SetKeySM4((tpmKeyScheduleSM4*)(schedule), (key), BITS_TO_BYTES(keySizeInBits)) - -// Macros to alias encryption calls to specific algorithms. This should be used -// sparingly. Currently, only used by CryptRand.c -// -// When using these calls, to call the AES block encryption code, the caller -// should use: -// TpmCryptEncryptAES(SWIZZLE(keySchedule, in, out)); + TEE_SetKeySM4((tpmKeyScheduleSM4 *)(schedule), (key), \ + BITS_TO_BYTES(keySizeInBits)) +/* + * Macros to alias encryption calls to specific algorithms. This should be + * used sparingly. Currently, only used by CryptRand.c + * + * When using these calls, to call the AES block encryption code, the + * caller should use: + * TpmCryptEncryptAES(SWIZZLE(keySchedule, in, out)); + */ #define TpmCryptEncryptAES TEE_AESEncrypt #define TpmCryptDecryptAES TEE_AESDecrypt @@ -157,7 +169,7 @@ typedef void (*TpmCryptSetSymKeyCall_t)(void* keySchedule, BYTE* out, const BYTE typedef union tpmCryptKeySchedule_t tpmCryptKeySchedule_t; -// This definition would change if there were something to report +/* This definition would change if there were something to report */ #define SymLibSimulationEnd() -#endif // SYM_LIB_DEFINED +#endif /*SYM_LIB_DEFINED*/ diff --git a/ta/ftpm/tee/TpmToTEEMath.c b/ta/ftpm/tee/TpmToTEEMath.c index f973d18485e..7b662bfc4f2 100644 --- a/ta/ftpm/tee/TpmToTEEMath.c +++ b/ta/ftpm/tee/TpmToTEEMath.c @@ -1,1030 +1,708 @@ -/* SPDX-License-Identifier: BSD-2-Clause */ -/********************************************************************** +// SPDX-License-Identifier: BSD-2-Clause +/* * Copyright (c) 2024, Siemens AG * All rights reserved. + * Copyright (c) 2024, Linaro Limited */ #include "Tpm.h" #ifdef MATH_LIB_TEE -# include +#include -# ifdef DEBUG_OUTPUT_TEE_MATH -# include -# define DEBUG_PRINT_RESULT(f) printf(" " #f " returns %" PRIx32 "\n", f) -void printf_bigint(const TEE_BigInt* bigint) +#include +static void __maybe_unused printf_bigint(const TEE_BigInt *bigint) { - size_t buffer_len = 1024; - uint8_t buffer[buffer_len]; - if(TEE_BigIntConvertToOctetString(buffer, &buffer_len, bigint) == TEE_SUCCESS) - { - if(buffer_len != 0) - { - for(size_t k = 0; k < buffer_len; ++k) - { - printf("%.2x", buffer[k]); - } - } else { - printf("0"); - } - } else { - printf("ERROR!\n"); - } + size_t buffer_len = 1024; + uint8_t buffer[buffer_len]; + if (TEE_BigIntConvertToOctetString(buffer, &buffer_len, bigint) == + TEE_SUCCESS) { + if (buffer_len != 0) { + for (size_t k = 0; k < buffer_len; ++k) { + printf("%.2x", buffer[k]); + } + } else { + printf("0"); + } + } else { + printf("ERROR!\n"); + } } -# else -# define DEBUG_PRINT_RESULT(f) f -# endif - -/// @todo Internal representation of big integers in the TEE is implementation -/// defined. If we used the fact that we know how OP-TEE represents big integers -/// internally, then we could directly convert between the TPM representation -/// and the TEE representation rather than go through representation as a byte -/// string. -/// @brief Return the maximum size of to bigNum in crypt_uword_t -/// @param a -/// @param b -/// @return max(BnGetSize(a), BnGetSize(b)) -static inline crypt_uword_t max_size(bigConst a, bigConst b) + +/* + * The internal representation of big integers in the TEE is implementation + * defined. If we used the fact that we know how OP-TEE represents big integers + * internally, then we could directly convert between the TPM representation + * and the TEE representation rather than go through representation as a byte + * string. + */ + +/* + * Return the size of a bigNum in bytes (rounded up to the nearest multiple + * of sizeof(crypt_uword_t)). + */ +static NUMBYTES bn_size_in_bytes(bigConst a) +{ + return sizeof(crypt_uword_t) * BnGetSize(a); +} + +/* + * Return the size of a bigNum in bytes (rounded up to the nearest multiple + * of sizeof(crypt_uword_t) * 8). + */ +static NUMBYTES bn_size_in_bits(bigConst a) +{ + return bn_size_in_bytes(a) * 8; +} + +static bool bignum_to_bigint(bigConst bn, TEE_BigInt *bi) { - return BnGetSize(a) > BnGetSize(b) ? BnGetSize(a) : BnGetSize(b); + NUMBYTES sz = bn_size_in_bytes(bn); + BYTE buf[sz]; + + if (!BnToBytes(bn, buf, &sz)) + return false; + + if (TEE_BigIntConvertFromOctetString(bi, buf, sz, 0)) + return false; + + return true; } -/// @brief Return the minimum size of to bigNum in crypt_uword_t -/// @param a -/// @param b -/// @return min(BnGetSize(a), BnGetSize(b)) -static inline crypt_uword_t min_size(bigConst a, bigConst b) +static size_t bigint_size_in_bytes(TEE_BigInt *bi) { - return BnGetSize(a) < BnGetSize(b) ? BnGetSize(a) : BnGetSize(b); + size_t sz = 0; + + TEE_BigIntConvertToOctetString(NULL, &sz, bi); + return sz; } -/// @brief Return the size of a bigNum in bit (rounded up to the nearest multiple of 8*sizeof(crypt_uword_t)). -/// @param a a bigNum -/// @return Size of a in bit rounded up to the nearest multiple of 8*sizeof(crypt_uword_t) -static inline size_t BnGetSizeInBit(bigConst a) +static bool bigint_to_bignum(TEE_BigInt *bi, bigNum bn) { - return 8 * sizeof(crypt_uword_t) * BnGetSize(a); + size_t sz = bigint_size_in_bytes(bi); + BYTE buf[sz]; + + if (TEE_BigIntConvertToOctetString(buf, &sz, bi)) + return false; + + if (!BnFromBytes(bn, buf, sz)) + return false; + + return true; } -/// @brief Return the size of a bigNum in bytes (rounded up to the nearest multiple of ) -/// @param a -/// @return -static inline size_t BnGetSizeInBytes(bigConst a) +static bool bigint_init_from_bn(TEE_BigInt *bi, size_t len, bigConst bn) { - return sizeof(crypt_uword_t) * BnGetSize(a); + TEE_BigIntInit(bi, len); + return bignum_to_bigint(bn, bi); } -LIB_EXPORT BOOL BnDiv( - bigNum quotient, bigNum remainder, bigConst dividend, bigConst divisor) +#ifndef ARRAY_SIZE +#define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0])) +#endif +#define BIGINT_INIT(bi) TEE_BigIntInit((bi), ARRAY_SIZE(bi)) +#define BIGINT_INIT_FROM_BN(bi, bn) \ + bigint_init_from_bn((bi), ARRAY_SIZE(bi), (bn)) + +static size_t bigint_len_from_bn(bigConst bn) { -# ifdef DEBUG_OUTPUT_TEE_MATH - printf("BnDiv\n"); -# endif - const NUMBYTES buffer_size = sizeof(crypt_uword_t) * max_size(dividend, divisor); - BYTE buffer[buffer_size]; - - size_t len = TEE_BigIntSizeInU32(BnGetSizeInBit(dividend)); - TEE_BigInt tee_dividend[len]; - TEE_BigIntInit(tee_dividend, len); - TEE_BigInt tee_quotient[len]; /// Yes, this may be too much. - TEE_BigIntInit(tee_quotient, len); - - len = TEE_BigIntSizeInU32(BnGetSizeInBit(divisor)); - TEE_BigInt tee_divisor[TEE_BigIntSizeInU32(BnGetSizeInBit(divisor))]; - TEE_BigIntInit(tee_divisor, len); - TEE_BigInt tee_remainder[len]; - TEE_BigIntInit(tee_remainder, len); - - NUMBYTES size = BnGetSizeInBytes(dividend); - BnToBytes(dividend, buffer, &size); - TEE_BigIntConvertFromOctetString( - tee_dividend, - buffer, - size, - 0); /// @todo Check that all numbers are non-negative. - - size = BnGetSizeInBytes(divisor); - BnToBytes(divisor, buffer, &size); - TEE_BigIntConvertFromOctetString( - tee_divisor, - buffer, - size, - 0); /// @todo Check that all numbers are non-negative. -# ifdef DEBUG_OUTPUT_TEE_MATH - printf(" TEE_BigIntGetBitCount(tee_divisor) returns %" PRIu32 "\n", - TEE_BigIntGetBitCount(tee_divisor)); -# endif - - TEE_BigIntDiv(tee_quotient, tee_remainder, tee_dividend, tee_divisor); - - if(quotient != 0) - { - size_t tee_size = buffer_size; - DEBUG_PRINT_RESULT( - TEE_BigIntConvertToOctetString(buffer, &tee_size, tee_quotient)); - VERIFY(BnFromBytes(quotient, buffer, tee_size)); - } - - if(remainder != 0) - { - size_t tee_size = buffer_size; - DEBUG_PRINT_RESULT( - TEE_BigIntConvertToOctetString(buffer, &tee_size, tee_remainder)); - VERIFY(BnFromBytes(remainder, buffer, tee_size)); - } - return TRUE; -Error: - return FALSE; + return TEE_BigIntSizeInU32(bn_size_in_bits(bn)); } -LIB_EXPORT BOOL BnMult(bigNum result, bigConst multiplicand, bigConst multiplier) +static size_t fmm_ctx_size_from_bn(bigConst bn) { -# ifdef DEBUG_OUTPUT_TEE_MATH - printf("BnMult\n"); -# endif - const NUMBYTES buffer_size = - sizeof(crypt_uword_t) * (BnGetSize(multiplicand) + BnGetSize(multiplier)); - BYTE buffer[buffer_size]; - - size_t len = TEE_BigIntSizeInU32(BnGetSizeInBit(multiplicand)); - TEE_BigInt tee_multiplicand[len]; - TEE_BigIntInit(tee_multiplicand, len); - - len = TEE_BigIntSizeInU32(BnGetSizeInBit(multiplier)); - TEE_BigInt tee_multiplier[len]; - TEE_BigIntInit(tee_multiplier, len); - - len = TEE_BigIntSizeInU32(8 * buffer_size); - TEE_BigInt tee_result[len]; - TEE_BigIntInit(tee_result, len); - - NUMBYTES size = BnGetSizeInBytes(multiplicand); - BnToBytes(multiplicand, buffer, &size); - TEE_BigIntConvertFromOctetString( - tee_multiplicand, - buffer, - size, - 0); /// @todo Check that all numbers are non-negative. - size = BnGetSizeInBytes(multiplier); - BnToBytes(multiplier, buffer, &size); - TEE_BigIntConvertFromOctetString( - tee_multiplier, - buffer, - size, - 0); /// @todo Check that all numbers are non-negative. - - TEE_BigIntMul(tee_result, tee_multiplicand, tee_multiplier); - - size_t tee_size = buffer_size; - TEE_BigIntConvertToOctetString(buffer, &tee_size, tee_result); - VERIFY(BnFromBytes(result, buffer, tee_size)); - return TRUE; -Error: - return FALSE; + return TEE_BigIntFMMContextSizeInU32(bn_size_in_bits(bn)); +} + +LIB_EXPORT BOOL BnDiv(bigNum quotient, bigNum remainder, bigConst dividend, + bigConst divisor) +{ + const size_t dividend_len = bigint_len_from_bn(dividend); + const size_t divisor_len = bigint_len_from_bn(divisor); + TEE_BigInt tee_dividend[dividend_len]; + TEE_BigInt tee_quotient[dividend_len]; + TEE_BigInt tee_divisor[divisor_len]; + TEE_BigInt tee_remainder[divisor_len]; + + BIGINT_INIT(tee_quotient); + BIGINT_INIT(tee_remainder); + if (!BIGINT_INIT_FROM_BN(tee_dividend, dividend) || + !BIGINT_INIT_FROM_BN(tee_divisor, divisor)) + return FALSE; + + TEE_BigIntDiv(tee_quotient, tee_remainder, tee_dividend, tee_divisor); + + if (quotient && !bigint_to_bignum(tee_quotient, quotient)) + return FALSE; + if (remainder && !bigint_to_bignum(tee_remainder, remainder)) + return FALSE; + + return TRUE; +} + +LIB_EXPORT BOOL BnMult(bigNum result, bigConst multiplicand, + bigConst multiplier) +{ + const size_t multiplicand_len = bigint_len_from_bn(multiplicand); + const size_t multiplier_len = bigint_len_from_bn(multiplier); + TEE_BigInt tee_result[multiplicand_len + multiplier_len]; + TEE_BigInt tee_multiplicand[multiplicand_len]; + TEE_BigInt tee_multiplier[multiplier_len]; + + BIGINT_INIT(tee_result); + if (!BIGINT_INIT_FROM_BN(tee_multiplicand, multiplicand) || + !BIGINT_INIT_FROM_BN(tee_multiplier, multiplier)) + return FALSE; + + TEE_BigIntMul(tee_result, tee_multiplicand, tee_multiplier); + + return bigint_to_bignum(tee_result, result); } LIB_EXPORT BOOL BnModInverse(bigNum result, bigConst number, bigConst modulus) { -# ifdef DEBUG_OUTPUT_TEE_MATH - printf("BnModInverse\n"); -# endif - const NUMBYTES buffer_size = sizeof(crypt_uword_t) * max_size(modulus, number); - BYTE buffer[buffer_size]; - - size_t len = TEE_BigIntSizeInU32(BnGetSizeInBit(modulus)); - TEE_BigInt tee_modulus[len]; - TEE_BigIntInit(tee_modulus, len); - TEE_BigInt tee_result[len]; - TEE_BigIntInit(tee_result, len); - - len = TEE_BigIntSizeInU32(BnGetSizeInBit(number)); - TEE_BigInt tee_number[len]; - TEE_BigIntInit(tee_number, len); - - NUMBYTES size = BnGetSizeInBytes(modulus); - BnToBytes(modulus, buffer, &size); - TEE_BigIntConvertFromOctetString( - tee_modulus, - buffer, - size, - 0); /// @todo Check that all numbers are non-negative. - size = BnGetSizeInBytes(number); - BnToBytes(number, buffer, &size); - TEE_BigIntConvertFromOctetString( - tee_number, - buffer, - size, - 0); /// @todo Check that all numbers are non-negative. - - TEE_BigIntMod( - tee_number, tee_number, tee_modulus); // Just in case number >= modulus. - TEE_BigIntInvMod(tee_result, tee_number, tee_modulus); - - size_t tee_size = buffer_size; - TEE_BigIntConvertToOctetString(buffer, &tee_size, tee_result); - VERIFY(BnFromBytes(result, buffer, tee_size)); - return TRUE; -Error: - return FALSE; + const size_t modulus_len = bigint_len_from_bn(modulus); + const size_t number_len = bigint_len_from_bn(number); + TEE_BigInt tee_modulus[modulus_len]; + TEE_BigInt tee_result[modulus_len]; + TEE_BigInt tee_number[number_len]; + + BIGINT_INIT(tee_result); + if (!BIGINT_INIT_FROM_BN(tee_modulus, modulus) || + !BIGINT_INIT_FROM_BN(tee_number, number)) + return FALSE; + + // Just in case number >= modulus. JW: why? + //TEE_BigIntMod(tee_number, tee_number, tee_modulus); + TEE_BigIntInvMod(tee_result, tee_number, tee_modulus); + + return bigint_to_bignum(tee_result, result); } -LIB_EXPORT BOOL BnModMult(bigNum result, bigConst op1, bigConst op2, bigConst modulus) +LIB_EXPORT BOOL BnModMult(bigNum result, bigConst op1, bigConst op2, + bigConst modulus) { -# ifdef DEBUG_OUTPUT_TEE_MATH - printf("BnModMult\n"); -# endif - const NUMBYTES buffer_size = sizeof(crypt_uword_t) - * (BnGetSize(modulus) > max_size(op1, op2) - ? BnGetSize(modulus) - : max_size(op1, op2)); - BYTE buffer[buffer_size]; - - size_t len = TEE_BigIntSizeInU32(BnGetSizeInBit(modulus)); - TEE_BigInt tee_modulus[len]; - TEE_BigIntInit(tee_modulus, len); - TEE_BigInt tee_result[len]; - TEE_BigIntInit(tee_result, len); - - len = TEE_BigIntSizeInU32(BnGetSizeInBit(op1)); - TEE_BigInt tee_op1[len]; - TEE_BigIntInit(tee_op1, len); - - len = TEE_BigIntSizeInU32(BnGetSizeInBit(op2)); - TEE_BigInt tee_op2[len]; - TEE_BigIntInit(tee_op2, len); - - NUMBYTES size = BnGetSizeInBytes(modulus); - BnToBytes(modulus, buffer, &size); - TEE_BigIntConvertFromOctetString( - tee_modulus, - buffer, - size, - 0); /// @todo Check that all numbers are non-negative. - size = BnGetSizeInBytes(op1); - BnToBytes(op1, buffer, &size); - TEE_BigIntConvertFromOctetString( - tee_op1, buffer, size, 0); /// @todo Check that all numbers are non-negative. - size = BnGetSizeInBytes(op2); - BnToBytes(op2, buffer, &size); - TEE_BigIntConvertFromOctetString( - tee_op2, buffer, size, 0); /// @todo Check that all numbers are non-negative. - - TEE_BigIntMod(tee_op1, tee_op1, tee_modulus); - TEE_BigIntMod(tee_op2, tee_op2, tee_modulus); - TEE_BigIntMulMod(tee_result, tee_op1, tee_op2, tee_modulus); - - size_t tee_size = buffer_size; - TEE_BigIntConvertToOctetString(buffer, &tee_size, tee_result); - VERIFY(BnFromBytes(result, buffer, tee_size)); - return TRUE; -Error: - return FALSE; + const size_t modulus_len = bigint_len_from_bn(modulus); + TEE_BigInt tee_modulus[modulus_len]; + TEE_BigInt tee_result[modulus_len]; + TEE_BigInt tee_op1[bigint_len_from_bn(op1)]; + TEE_BigInt tee_op2[bigint_len_from_bn(op2)]; + + BIGINT_INIT(tee_result); + if (!BIGINT_INIT_FROM_BN(tee_modulus, modulus) || + !BIGINT_INIT_FROM_BN(tee_op1, op1) || + !BIGINT_INIT_FROM_BN(tee_op2, op2)) + return FALSE; + + TEE_BigIntMod(tee_op1, tee_op1, tee_modulus); + TEE_BigIntMod(tee_op2, tee_op2, tee_modulus); + TEE_BigIntMulMod(tee_result, tee_op1, tee_op2, tee_modulus); + + return bigint_to_bignum(tee_result, result); } -LIB_EXPORT BOOL BnModExp(bigNum result, // OUT: the result - bigConst number, // IN: number to exponentiate - bigConst exponent, // IN: - bigConst modulus // IN: -) +LIB_EXPORT BOOL BnModExp(bigNum result, bigConst number, bigConst exponent, + bigConst modulus) { -# ifdef DEBUG_OUTPUT_TEE_MATH - printf("BnModExp\n"); -# endif - const NUMBYTES buffer_size = sizeof(crypt_uword_t) - * (BnGetSize(modulus) > max_size(number, exponent) - ? BnGetSize(modulus) - : max_size(number, exponent)); - BYTE buffer[buffer_size]; - - size_t len = TEE_BigIntSizeInU32(BnGetSizeInBit(modulus)); - TEE_BigInt tee_modulus[len]; - TEE_BigIntInit(tee_modulus, len); - TEE_BigInt tee_result[len]; - TEE_BigIntInit(tee_result, len); - - len = TEE_BigIntSizeInU32(BnGetSizeInBit(number)); - TEE_BigInt tee_number[len]; - TEE_BigIntInit(tee_number, len); - - len = TEE_BigIntSizeInU32(BnGetSizeInBit(exponent)); - TEE_BigInt tee_exponent[len]; - TEE_BigIntInit(tee_exponent, len); - - NUMBYTES size = BnGetSizeInBytes(modulus); - BnToBytes(modulus, buffer, &size); - TEE_BigIntConvertFromOctetString( - tee_modulus, - buffer, - size, - 0); /// @todo Check that all numbers are non-negative. - size = BnGetSizeInBytes(number); - BnToBytes(number, buffer, &size); - TEE_BigIntConvertFromOctetString( - tee_number, - buffer, - size, - 0); /// @todo Check that all numbers are non-negative. - size = BnGetSizeInBytes(exponent); - BnToBytes(exponent, buffer, &size); - TEE_BigIntConvertFromOctetString( - tee_exponent, - buffer, - size, - 0); /// @todo Check that all numbers are non-negative. - - TEE_BigIntMod(tee_number, tee_number, tee_modulus); - const size_t fmm_ctx_size = - TEE_BigIntFMMContextSizeInU32(BnGetSizeInBit(modulus)); - uint32_t fmm_ctx[fmm_ctx_size]; - DEBUG_PRINT_RESULT(TEE_BigIntInitFMMContext1( - (TEE_BigIntFMMContext*)fmm_ctx, fmm_ctx_size, tee_modulus)); - DEBUG_PRINT_RESULT(TEE_BigIntExpMod(tee_result, - tee_number, - tee_exponent, - tee_modulus, - (TEE_BigIntFMMContext*)fmm_ctx)); - - size_t tee_size = buffer_size; - DEBUG_PRINT_RESULT(TEE_BigIntConvertToOctetString(buffer, &tee_size, tee_result)); - VERIFY(BnFromBytes(result, buffer, tee_size)); - return TRUE; -Error: - return FALSE; + const size_t modulus_len = bigint_len_from_bn(modulus); + TEE_BigInt tee_modulus[modulus_len]; + TEE_BigInt tee_result[modulus_len]; + TEE_BigInt tee_number[bigint_len_from_bn(number)]; + TEE_BigInt tee_exponent[bigint_len_from_bn(exponent)]; + TEE_BigIntFMMContext fmm_ctx[fmm_ctx_size_from_bn(modulus)]; + + BIGINT_INIT(tee_result); + if (!BIGINT_INIT_FROM_BN(tee_modulus, modulus) || + !BIGINT_INIT_FROM_BN(tee_number, number) || + !BIGINT_INIT_FROM_BN(tee_exponent, exponent) || + TEE_BigIntInitFMMContext1(fmm_ctx, ARRAY_SIZE(fmm_ctx), + tee_modulus)) + return FALSE; + + TEE_BigIntMod(tee_number, tee_number, tee_modulus); + if (TEE_BigIntExpMod(tee_result, tee_number, tee_exponent, tee_modulus, + fmm_ctx)) + return FALSE; + + return bigint_to_bignum(tee_result, result); } -LIB_EXPORT BOOL BnGcd(bigNum gcd, // OUT: the common divisor - bigConst number1, // IN: - bigConst number2 // IN: -) +LIB_EXPORT BOOL BnGcd(bigNum gcd, bigConst number1, bigConst number2) { -# ifdef DEBUG_OUTPUT_TEE_MATH - printf("BnGcd\n"); -# endif - const NUMBYTES buffer_size = sizeof(crypt_uword_t) * max_size(number1, number2); - BYTE buffer[buffer_size]; - - size_t len = TEE_BigIntSizeInU32(BnGetSizeInBit(number1)); - TEE_BigInt tee_number1[len]; - TEE_BigIntInit(tee_number1, len); - - len = TEE_BigIntSizeInU32(BnGetSizeInBit(number1)); - TEE_BigInt tee_number2[len]; - TEE_BigIntInit(tee_number2, len); - - len = TEE_BigIntSizeInU32(8 * sizeof(crypt_uword_t) * min_size(number1, number2)); - TEE_BigInt tee_gcd[len]; - TEE_BigIntInit(tee_gcd, len); - - NUMBYTES size = BnGetSizeInBytes(number1); - BnToBytes(number1, buffer, &size); - TEE_BigIntConvertFromOctetString( - tee_number1, - buffer, - size, - 0); /// @todo Check that all numbers are non-negative. - size = BnGetSizeInBytes(number2); - BnToBytes(number2, buffer, &size); - TEE_BigIntConvertFromOctetString( - tee_number2, - buffer, - size, - 0); /// @todo Check that all numbers are non-negative. - - TEE_BigIntComputeExtendedGcd(tee_gcd, 0, 0, tee_number1, tee_number2); - - size_t tee_size = buffer_size; - TEE_BigIntConvertToOctetString(buffer, &tee_size, tee_gcd); - VERIFY(BnFromBytes(gcd, buffer, tee_size)); - return TRUE; -Error: - return FALSE; + TEE_BigInt tee_number1[bigint_len_from_bn(number1)]; + TEE_BigInt tee_number2[bigint_len_from_bn(number2)]; + TEE_BigInt tee_gcd[MIN(ARRAY_SIZE(tee_number1), + ARRAY_SIZE(tee_number2))]; + + BIGINT_INIT(tee_gcd); + if (!BIGINT_INIT_FROM_BN(tee_number1, number1) || + !BIGINT_INIT_FROM_BN(tee_number2, number2)) + return FALSE; + + TEE_BigIntComputeExtendedGcd(tee_gcd, 0, 0, tee_number1, tee_number2); + + return bigint_to_bignum(tee_gcd, gcd); } /** * This is an implementation of https://www.hyperelliptic.org/EFD/g1p/auto-shortw-jacobian.html#doubling-dbl-2007-bl */ -static void double_point_jacobi(TEE_BigInt* x3, - TEE_BigInt* y3, - TEE_BigInt* z3, - const TEE_BigInt* x1, - const TEE_BigInt* y1, - const TEE_BigInt* z1, - const TEE_BigInt* a, - const TEE_BigInt* p) +static void double_point_jacobi(TEE_BigInt *x3, TEE_BigInt *y3, TEE_BigInt *z3, + const TEE_BigInt *x1, const TEE_BigInt *y1, + const TEE_BigInt *z1, const TEE_BigInt *a, + const TEE_BigInt *p) { - size_t number_size = TEE_BigIntSizeInU32(TEE_BigIntGetBitCount(p)); - - TEE_BigInt xx[number_size]; - TEE_BigIntInit(xx, number_size); - // xx = x1^2 - TEE_BigIntSquareMod(xx, x1, p); - TEE_BigInt yy[number_size]; - TEE_BigIntInit(yy, number_size); - // yy = y1^2 - TEE_BigIntSquareMod(yy, y1, p); - TEE_BigInt yyyy[number_size]; - TEE_BigIntInit(yyyy, number_size); - // yyyy = yy^2 - TEE_BigIntSquareMod(yyyy, yy, p); - TEE_BigInt zz[number_size]; - TEE_BigIntInit(zz, number_size); - // zz = z1^2 - TEE_BigIntSquareMod(zz, z1, p); - TEE_BigInt s[number_size]; - TEE_BigIntInit(s, number_size); - // s = 2*((x1 + yy)^2 - xx - yyyy) - TEE_BigIntAddMod(s, x1, yy, p); - TEE_BigIntSquareMod(s, s, p); - TEE_BigIntSubMod(s, s, xx, p); - TEE_BigIntSubMod(s, s, yyyy, p); - TEE_BigIntAddMod(s, s, s, p); - TEE_BigInt m[number_size]; - TEE_BigIntInit(m, number_size); - // m = 3*xx + a + zz^2 - TEE_BigIntSquareMod(m, zz, p); - TEE_BigIntMulMod(m, m, a, p); - TEE_BigIntAddMod(m, m, xx, p); - TEE_BigIntAddMod(m, m, xx, p); - TEE_BigIntAddMod(m, m, xx, p); - // x3 = m^2 - 2*s - TEE_BigIntSquareMod(x3, m, p); - TEE_BigIntSubMod(x3, x3, s, p); - TEE_BigIntSubMod(x3, x3, s, p); - // y3 = m * (x - x3) - 8*yyyy - TEE_BigIntSubMod(y3, s, x3, p); - TEE_BigIntMulMod(y3, y3, m, p); - TEE_BigIntAddMod(z3, yyyy, yyyy, p); - TEE_BigIntAddMod(z3, z3, z3, p); - TEE_BigIntAddMod(z3, z3, z3, p); - TEE_BigIntSubMod(y3, y3, z3, p); - // z3 = (y1 + z1)^2 - yy -zz - TEE_BigIntAddMod(z3, y1, z1, p); - TEE_BigIntSquareMod(z3, z3, p); - TEE_BigIntSubMod(z3, z3, yy, p); - TEE_BigIntSubMod(z3, z3, zz, p); + size_t number_size = TEE_BigIntSizeInU32(TEE_BigIntGetBitCount(p)); + TEE_BigInt xx[number_size]; + TEE_BigInt yy[number_size]; + TEE_BigInt yyyy[number_size]; + TEE_BigInt zz[number_size]; + TEE_BigInt s[number_size]; + TEE_BigInt m[number_size]; + + BIGINT_INIT(xx); + BIGINT_INIT(yy); + BIGINT_INIT(yyyy); + BIGINT_INIT(zz); + BIGINT_INIT(s); + BIGINT_INIT(m); + + /* xx = x1^2 */ + TEE_BigIntSquareMod(xx, x1, p); + /* yy = y1^2 */ + TEE_BigIntSquareMod(yy, y1, p); + /* yyyy = yy^2 */ + TEE_BigIntSquareMod(yyyy, yy, p); + /* zz = z1^2 */ + TEE_BigIntSquareMod(zz, z1, p); + /* s = 2*((x1 + yy)^2 - xx - yyyy) */ + TEE_BigIntAddMod(s, x1, yy, p); + TEE_BigIntSquareMod(s, s, p); + TEE_BigIntSubMod(s, s, xx, p); + TEE_BigIntSubMod(s, s, yyyy, p); + TEE_BigIntAddMod(s, s, s, p); + /* m = 3*xx + a + zz^2 */ + TEE_BigIntSquareMod(m, zz, p); + TEE_BigIntMulMod(m, m, a, p); + TEE_BigIntAddMod(m, m, xx, p); + TEE_BigIntAddMod(m, m, xx, p); + TEE_BigIntAddMod(m, m, xx, p); + /* x3 = m^2 - 2*s */ + TEE_BigIntSquareMod(x3, m, p); + TEE_BigIntSubMod(x3, x3, s, p); + TEE_BigIntSubMod(x3, x3, s, p); + /* y3 = m * (x - x3) - 8 * yyyy */ + TEE_BigIntSubMod(y3, s, x3, p); + TEE_BigIntMulMod(y3, y3, m, p); + TEE_BigIntAddMod(z3, yyyy, yyyy, p); + TEE_BigIntAddMod(z3, z3, z3, p); + TEE_BigIntAddMod(z3, z3, z3, p); + TEE_BigIntSubMod(y3, y3, z3, p); + /* z3 = (y1 + z1)^2 - yy - zz */ + TEE_BigIntAddMod(z3, y1, z1, p); + TEE_BigIntSquareMod(z3, z3, p); + TEE_BigIntSubMod(z3, z3, yy, p); + TEE_BigIntSubMod(z3, z3, zz, p); } -/// @brief Return 0xffffffff if a TEE_BigInt is zero, 0 otherwise -/// @param z TEE_BigInt to test -/// @return 0xffffffff if z is zer0 and0 otherwise -static uint32_t is_zero(TEE_BigInt* z) +/* return 0xffffffff if z is zer0 and 0 otherwise */ +static uint32_t is_zero(const TEE_BigInt *z) { - uint32_t result = (uint32_t)TEE_BigIntCmpS32(z, 0); - result--; - result &= result >> 16; - result &= result >> 8; - result &= result >> 4; - result &= result >> 2; - result &= result >> 1; - result = -result; - return result; + uint32_t result = (uint32_t)TEE_BigIntCmpS32(z, 0); + + /* + * This looks like an attempt of protection against a side channel + * attack. + * JW: why is it needed or effective here? + */ + result--; + result &= result >> 16; + result &= result >> 8; + result &= result >> 4; + result &= result >> 2; + result &= result >> 1; + result = -result; + return result; } -/// @brief Copy src over dst if mask is 0xffffffff, do not if mask is 0. -/// @todo This requires dst and src to have exactly the same size -/// @param dst -/// @param src -/// @param len size of dst and src in uint32_t -/// @param mask -static void conditional_copy(TEE_BigInt* dst, const TEE_BigInt* src, size_t len, uint32_t mask) +/* + * Copy src over dst if mask is 0xffffffff, do not if mask is 0. + * This requires dst and src to have exactly the same size + */ +static void conditional_copy(TEE_BigInt *dst, const TEE_BigInt *src, size_t len, + uint32_t mask) { - for(size_t k = 0; k < len; ++k) - { - dst[k] = ((~mask) & dst[k]) | (mask & src[k]); - } + size_t k = 0; + + /* + * This looks like an attempt of protection against a side channel + * attack. + * JW: why? + */ + for (k = 0; k < len; ++k) + dst[k] = ((~mask) & dst[k]) | (mask & src[k]); } -/** - * This is an explicit implementation of https://www.hyperelliptic.org/EFD/g1p/auto-shortw-jacobian.html#addition-add-2007-bl. - * output areas must not overlap with input areas -*/ -static void add_points_jacobi(TEE_BigInt* x3, - TEE_BigInt* y3, - TEE_BigInt* z3, - const TEE_BigInt* x1, - const TEE_BigInt* y1, - const TEE_BigInt* z1, - const TEE_BigInt* x2, - const TEE_BigInt* y2, - const TEE_BigInt* z2, - const TEE_BigInt* p) + +/* + * This is an explicit implementation of + * https://www.hyperelliptic.org/EFD/g1p/auto-shortw-jacobian.html#addition-add-2007-bl. + * output areas must not overlap with input areas. + */ +static void add_points_jacobi(TEE_BigInt *x3, TEE_BigInt *y3, TEE_BigInt *z3, + const TEE_BigInt *x1, const TEE_BigInt *y1, + const TEE_BigInt *z1, const TEE_BigInt *x2, + const TEE_BigInt *y2, const TEE_BigInt *z2, + const TEE_BigInt *p) { - size_t number_size = TEE_BigIntSizeInU32(TEE_BigIntGetBitCount(p)); - - TEE_BigInt z1z1[number_size]; - TEE_BigIntInit(z1z1, number_size); - // z1z1 = (z1 * z1) % p - TEE_BigIntSquareMod(z1z1, z1, p); - TEE_BigInt z2z2[number_size]; - TEE_BigIntInit(z2z2, number_size); - // z2z2 = (z2 * z2) % p - TEE_BigIntSquareMod(z2z2, z2, p); - TEE_BigInt u1[number_size]; - TEE_BigIntInit(u1, number_size); - // u1 = (x1 * z2z2) % p - TEE_BigIntMulMod(u1, x1, z2z2, p); - TEE_BigInt u2[number_size]; - TEE_BigIntInit(u2, number_size); - // u2 = (x2 * z1z1) % p - TEE_BigIntMulMod(u2, x2, z1z1, p); - //s1 = (y1 * z2 * z2z2) % p - TEE_BigInt s1[number_size]; - TEE_BigIntInit(s1, number_size); - TEE_BigIntMulMod(s1, y1, z2, p); - TEE_BigIntMulMod(s1, s1, z2z2, p); - TEE_BigInt s2[number_size]; - TEE_BigIntInit(s2, number_size); - // s2 = (y2 * z1 * z1z1) % p - TEE_BigIntMulMod(s2, y2, z1, p); - TEE_BigIntMulMod(s2, s2, z1z1, p); - TEE_BigInt h[number_size]; - TEE_BigIntInit(h, number_size); - // h = (u2 - u1) % p - TEE_BigIntSubMod(h, u2, u1, p); - TEE_BigInt i[number_size]; - TEE_BigIntInit(i, number_size); - // i = (2 * h) % p - TEE_BigIntAddMod(i, h, h, p); - // i = (i * i) % p - TEE_BigIntSquareMod(i, i, p); - TEE_BigInt j[number_size]; - TEE_BigIntInit(j, number_size); - // j = (h * i) % p - TEE_BigIntMulMod(j, h, i, p); - TEE_BigInt r[number_size]; - TEE_BigIntInit(r, number_size); - // r = (2 * (s2 - s1)) % p - TEE_BigIntSubMod(r, s2, s1, p); - TEE_BigIntAddMod(r, r, r, p); - TEE_BigInt v[number_size]; - TEE_BigIntInit(v, number_size); - // v = (u1 * i) % p - TEE_BigIntMulMod(v, u1, i, p); - // x3 = (r * r - j - 2 * v) % p - TEE_BigIntSquareMod(x3, r, p); - TEE_BigIntSubMod(x3, x3, j, p); - TEE_BigIntSubMod(x3, x3, v, p); - TEE_BigIntSubMod(x3, x3, v, p); - // y3 = (r * (v - x3) - 2 * s1 * j) % p - TEE_BigIntSubMod(y3, v, x3, p); - TEE_BigIntMulMod(y3, y3, r, p); - TEE_BigIntMulMod(z3, s1, j, p); - TEE_BigIntSubMod(y3, y3, z3, p); - TEE_BigIntSubMod(y3, y3, z3, p); - // z3 = (z1 + z2) % p - TEE_BigIntAddMod(z3, z1, z2, p); - // z3 = ((z3 * z3 - z1z1 - z2z2) * h) % p - TEE_BigIntSquareMod(z3, z3, p); - TEE_BigIntSubMod(z3, z3, z1z1, p); - TEE_BigIntSubMod(z3, z3, z2z2, p); - TEE_BigIntMulMod(z3, z3, h, p); - - // Handle the case that one of the points is the point at infinity, i.e., z1=0 or z2=0. - uint32_t z1_is_zero = is_zero(z1); - uint32_t z2_is_zero = is_zero(z2); - conditional_copy(x3, x2, number_size, z1_is_zero); - conditional_copy(y3, y2, number_size, z1_is_zero); - conditional_copy(z3, z2, number_size, z1_is_zero); - conditional_copy(x3, x1, number_size, z2_is_zero); - conditional_copy(y3, y1, number_size, z2_is_zero); - conditional_copy(z3, z1, number_size, z2_is_zero); + size_t number_size = TEE_BigIntSizeInU32(TEE_BigIntGetBitCount(p)); + TEE_BigInt z1z1[number_size]; + TEE_BigInt z2z2[number_size]; + TEE_BigInt u1[number_size]; + TEE_BigInt u2[number_size]; + TEE_BigInt s1[number_size]; + TEE_BigInt s2[number_size]; + TEE_BigInt h[number_size]; + TEE_BigInt i[number_size]; + TEE_BigInt j[number_size]; + TEE_BigInt r[number_size]; + TEE_BigInt v[number_size]; + uint32_t z1_is_zero = 0; + uint32_t z2_is_zero = 0; + + + BIGINT_INIT(z1z1); + BIGINT_INIT(z2z2); + BIGINT_INIT(u1); + BIGINT_INIT(u2); + BIGINT_INIT(s1); + BIGINT_INIT(s2); + BIGINT_INIT(h); + BIGINT_INIT(i); + BIGINT_INIT(j); + BIGINT_INIT(r); + BIGINT_INIT(v); + + /* z1z1 = (z1 * z1) % p */ + TEE_BigIntSquareMod(z1z1, z1, p); + /* z2z2 = (z2 * z2) % p */ + TEE_BigIntSquareMod(z2z2, z2, p); + /* u1 = (x1 * z2z2) % p */ + TEE_BigIntMulMod(u1, x1, z2z2, p); + /* u2 = (x2 * z1z1) % p */ + TEE_BigIntMulMod(u2, x2, z1z1, p); + /* = (y1 * z2 * z2z2) % p */ + TEE_BigIntMulMod(s1, y1, z2, p); + TEE_BigIntMulMod(s1, s1, z2z2, p); + /* s2 = (y2 * z1 * z1z1) % p */ + TEE_BigIntMulMod(s2, y2, z1, p); + TEE_BigIntMulMod(s2, s2, z1z1, p); + /* h = (u2 - u1) % p */ + TEE_BigIntSubMod(h, u2, u1, p); + /* i = (2 * h) % p */ + TEE_BigIntAddMod(i, h, h, p); + /* i = (i * i) % p */ + TEE_BigIntSquareMod(i, i, p); + /* j = (h * i) % p */ + TEE_BigIntMulMod(j, h, i, p); + /* r = (2 * (s2 - s1)) % p */ + TEE_BigIntSubMod(r, s2, s1, p); + TEE_BigIntAddMod(r, r, r, p); + /* v = (u1 * i) % p */ + TEE_BigIntMulMod(v, u1, i, p); + /* x3 = (r * r - j - 2 * v) % p */ + TEE_BigIntSquareMod(x3, r, p); + TEE_BigIntSubMod(x3, x3, j, p); + TEE_BigIntSubMod(x3, x3, v, p); + TEE_BigIntSubMod(x3, x3, v, p); + /* y3 = (r * (v - x3) - 2 * s1 * j) % p */ + TEE_BigIntSubMod(y3, v, x3, p); + TEE_BigIntMulMod(y3, y3, r, p); + TEE_BigIntMulMod(z3, s1, j, p); + TEE_BigIntSubMod(y3, y3, z3, p); + TEE_BigIntSubMod(y3, y3, z3, p); + /* z3 = (z1 + z2) % p */ + TEE_BigIntAddMod(z3, z1, z2, p); + /* z3 = ((z3 * z3 - z1z1 - z2z2) * h) % p */ + TEE_BigIntSquareMod(z3, z3, p); + TEE_BigIntSubMod(z3, z3, z1z1, p); + TEE_BigIntSubMod(z3, z3, z2z2, p); + TEE_BigIntMulMod(z3, z3, h, p); + + /* + * Handle the case that one of the points is the point at infinity, + * i.e., z1=0 or z2=0. + */ + z1_is_zero = is_zero(z1); + z2_is_zero = is_zero(z2); + conditional_copy(x3, x2, number_size, z1_is_zero); + conditional_copy(y3, y2, number_size, z1_is_zero); + conditional_copy(z3, z2, number_size, z1_is_zero); + conditional_copy(x3, x1, number_size, z2_is_zero); + conditional_copy(y3, y1, number_size, z2_is_zero); + conditional_copy(z3, z1, number_size, z2_is_zero); } -static void scalar_multiplication_jacobi(TEE_BigInt* x3, - TEE_BigInt* y3, - TEE_BigInt* z3, - const TEE_BigInt* x1, - const TEE_BigInt* y1, - const TEE_BigInt* z1, - const uint8_t* scalar, - size_t scalar_size, - const TEE_BigInt* a, - const TEE_BigInt* p) +static void scalar_multiplication_jacobi(TEE_BigInt *x3, TEE_BigInt *y3, + TEE_BigInt *z3, const TEE_BigInt *x1, + const TEE_BigInt *y1, + const TEE_BigInt *z1, + const uint8_t *scalar, + size_t scalar_size, + const TEE_BigInt *a, + const TEE_BigInt *p) { -# ifdef DEBUG_OUTPUT_TEE_MATH - printf("scalar_multiplication_jacobi\n"); - printf(" x1 = 0x"); - printf_bigint(x1); - printf("\n y1 = 0x"); - printf_bigint(y1); - printf("\n z1 = 0x"); - printf_bigint(z1); - printf("\n s = 0x"); - for(size_t k = 0; k < scalar_size; ++k) - { - printf("%.2x", scalar[k]); - } - printf("\n"); -# endif - if(scalar_size == 0) - { - TEE_BigIntConvertFromS32(x3, 1); - TEE_BigIntConvertFromS32(y3, 1); - TEE_BigIntConvertFromS32(z3, 0); - return; - } -// Macros to access x, y, z coordinates of point k in the buffer of pre-computed points. -# define PRE_X(k) (precomputed + (k) * 3 * number_size) -# define PRE_Y(k) (precomputed + (k) * 3 * number_size + number_size) -# define PRE_Z(k) (precomputed + (k) * 3 * number_size + 2 * number_size) - - size_t number_size = TEE_BigIntSizeInU32(TEE_BigIntGetBitCount(p)); - // Pre-compute multiples 0, 1, 2, ... 15 times the point. - TEE_BigInt precomputed[16 * 3 * number_size]; - for(uint_fast8_t k = 0; k < 3 * 16; ++k) - { - TEE_BigIntInit(precomputed + k * number_size, number_size); - } - TEE_BigIntConvertFromS32(PRE_X(0), 1); - TEE_BigIntConvertFromS32(PRE_Y(0), 1); - TEE_BigIntConvertFromS32(PRE_Z(0), 0); - TEE_BigIntAssign(PRE_X(1), x1); - TEE_BigIntAssign(PRE_Y(1), y1); - TEE_BigIntAssign(PRE_Z(1), z1); - double_point_jacobi( - PRE_X(2), PRE_Y(2), PRE_Z(2), PRE_X(1), PRE_Y(1), PRE_Z(1), a, p); - double_point_jacobi( - PRE_X(4), PRE_Y(4), PRE_Z(4), PRE_X(2), PRE_Y(2), PRE_Z(2), a, p); - double_point_jacobi( - PRE_X(8), PRE_Y(8), PRE_Z(8), PRE_X(4), PRE_Y(4), PRE_Z(4), a, p); - add_points_jacobi(PRE_X(3), - PRE_Y(3), - PRE_Z(3), - PRE_X(1), - PRE_Y(1), - PRE_Z(1), - PRE_X(2), - PRE_Y(2), - PRE_Z(2), - p); - add_points_jacobi(PRE_X(5), - PRE_Y(5), - PRE_Z(5), - PRE_X(1), - PRE_Y(1), - PRE_Z(1), - PRE_X(4), - PRE_Y(4), - PRE_Z(4), - p); - double_point_jacobi( - PRE_X(6), PRE_Y(6), PRE_Z(6), PRE_X(3), PRE_Y(3), PRE_Z(3), a, p); - add_points_jacobi(PRE_X(7), - PRE_Y(7), - PRE_Z(7), - PRE_X(1), - PRE_Y(1), - PRE_Z(1), - PRE_X(6), - PRE_Y(6), - PRE_Z(6), - p); - add_points_jacobi(PRE_X(9), - PRE_Y(9), - PRE_Z(9), - PRE_X(1), - PRE_Y(1), - PRE_Z(1), - PRE_X(8), - PRE_Y(8), - PRE_Z(8), - p); - double_point_jacobi( - PRE_X(10), PRE_Y(10), PRE_Z(10), PRE_X(5), PRE_Y(5), PRE_Z(5), a, p); - add_points_jacobi(PRE_X(11), - PRE_Y(11), - PRE_Z(11), - PRE_X(1), - PRE_Y(1), - PRE_Z(1), - PRE_X(10), - PRE_Y(10), - PRE_Z(10), - p); - double_point_jacobi( - PRE_X(12), PRE_Y(12), PRE_Z(12), PRE_X(6), PRE_Y(6), PRE_Z(6), a, p); - add_points_jacobi(PRE_X(13), - PRE_Y(13), - PRE_Z(13), - PRE_X(1), - PRE_Y(1), - PRE_Z(1), - PRE_X(12), - PRE_Y(12), - PRE_Z(12), - p); - double_point_jacobi( - PRE_X(14), PRE_Y(14), PRE_Z(14), PRE_X(7), PRE_Y(7), PRE_Z(7), a, p); - add_points_jacobi(PRE_X(15), - PRE_Y(15), - PRE_Z(15), - PRE_X(1), - PRE_Y(1), - PRE_Z(1), - PRE_X(14), - PRE_Y(14), - PRE_Z(14), - p); - - TEE_BigInt tmp_buffer[2 * 3 * number_size]; - for(uint_fast8_t k = 0; k < 6; ++k) - { - TEE_BigIntInit(tmp_buffer + k * number_size, number_size); - } - TEE_BigInt* tmp1 = tmp_buffer; - TEE_BigInt* tmp2 = tmp_buffer + 3 * number_size; - TEE_BigInt* t; - int w = scalar[0] >> 4; - TEE_BigIntAssign(tmp1, PRE_X(w)); - TEE_BigIntAssign(tmp1 + number_size, PRE_Y(w)); - TEE_BigIntAssign(tmp1 + 2 * number_size, PRE_Z(w)); - - // Double four times, then add the appropriate pre-computed multiple. - for(int k = 1; k < 2 * scalar_size; ++k) - { - double_point_jacobi(tmp2, - tmp2 + number_size, - tmp2 + 2 * number_size, - tmp1, - tmp1 + number_size, - tmp1 + 2 * number_size, - a, - p); - double_point_jacobi(tmp1, - tmp1 + number_size, - tmp1 + 2 * number_size, - tmp2, - tmp2 + number_size, - tmp2 + 2 * number_size, - a, - p); - double_point_jacobi(tmp2, - tmp2 + number_size, - tmp2 + 2 * number_size, - tmp1, - tmp1 + number_size, - tmp1 + 2 * number_size, - a, - p); - double_point_jacobi(tmp1, - tmp1 + number_size, - tmp1 + 2 * number_size, - tmp2, - tmp2 + number_size, - tmp2 + 2 * number_size, - a, - p); - w = scalar[k >> 1]; - if(k & 1) - { - w &= 0xf; - } - else - { - w >>= 4; - } - add_points_jacobi(tmp2, - tmp2 + number_size, - tmp2 + 2 * number_size, - tmp1, - tmp1 + number_size, - tmp1 + 2 * number_size, - PRE_X(w), - PRE_Y(w), - PRE_Z(w), - p); - // Swap tmp1, tmp2. - t = tmp1; - tmp1 = tmp2; - tmp2 = t; - } - TEE_BigIntAssign(x3, tmp1); - TEE_BigIntAssign(y3, tmp1 + number_size); - TEE_BigIntAssign(z3, tmp1 + 2 * number_size); - -# ifdef DEBUG_OUTPUT_TEE_MATH - printf(" x3 = 0x"); - printf_bigint(x3); - printf("\n y3 = 0x"); - printf_bigint(y3); - printf("\n z3 = 0x"); - printf_bigint(z3); - printf("\n"); -# endif + size_t number_size = TEE_BigIntSizeInU32(TEE_BigIntGetBitCount(p)); + TEE_BigInt tmp_buffer[2 * 3 * number_size]; + TEE_BigInt pre_x[16][number_size]; + TEE_BigInt pre_y[16][number_size]; + TEE_BigInt pre_z[16][number_size]; + TEE_BigInt *tmp1 = NULL; + TEE_BigInt *tmp2 = NULL; + TEE_BigInt *t = NULL; + size_t k = 0; + int w = 0; + +#ifdef DEBUG_OUTPUT_TEE_MATH + printf("scalar_multiplication_jacobi\n"); + printf(" x1 = 0x"); + printf_bigint(x1); + printf("\n y1 = 0x"); + printf_bigint(y1); + printf("\n z1 = 0x"); + printf_bigint(z1); + printf("\n s = 0x"); + for (size_t k = 0; k < scalar_size; ++k) { + printf("%.2x", scalar[k]); + } + printf("\n"); +#endif + if (scalar_size == 0) { + TEE_BigIntConvertFromS32(x3, 1); + TEE_BigIntConvertFromS32(y3, 1); + TEE_BigIntConvertFromS32(z3, 0); + return; + } + + for (k = 0; k < 16; ++k) { + BIGINT_INIT(pre_x[k]); + BIGINT_INIT(pre_y[k]); + BIGINT_INIT(pre_z[k]); + } + + TEE_BigIntConvertFromS32(pre_x[0], 1); + TEE_BigIntConvertFromS32(pre_y[0], 1); + TEE_BigIntConvertFromS32(pre_z[0], 0); + TEE_BigIntAssign(pre_x[1], x1); + TEE_BigIntAssign(pre_y[1], y1); + TEE_BigIntAssign(pre_z[1], z1); + double_point_jacobi(pre_x[2], pre_y[2], pre_z[2], pre_x[1], pre_y[1], + pre_z[1], a, p); + double_point_jacobi(pre_x[4], pre_y[4], pre_z[4], pre_x[2], pre_y[2], + pre_z[2], a, p); + double_point_jacobi(pre_x[8], pre_y[8], pre_z[8], pre_x[4], pre_y[4], + pre_z[4], a, p); + add_points_jacobi(pre_x[3], pre_y[3], pre_z[3], pre_x[1], pre_y[1], + pre_z[1], pre_x[2], pre_y[2], pre_z[2], p); + add_points_jacobi(pre_x[5], pre_y[5], pre_z[5], pre_x[1], pre_y[1], + pre_z[1], pre_x[4], pre_y[4], pre_z[4], p); + double_point_jacobi(pre_x[6], pre_y[6], pre_z[6], pre_x[3], pre_y[3], + pre_z[3], a, p); + add_points_jacobi(pre_x[7], pre_y[7], pre_z[7], pre_x[1], pre_y[1], + pre_z[1], pre_x[6], pre_y[6], pre_z[6], p); + add_points_jacobi(pre_x[9], pre_y[9], pre_z[9], pre_x[1], pre_y[1], + pre_z[1], pre_x[8], pre_y[8], pre_z[8], p); + double_point_jacobi(pre_x[10], pre_y[10], pre_z[10], pre_x[5], pre_y[5], + pre_z[5], a, p); + add_points_jacobi(pre_x[11], pre_y[11], pre_z[11], pre_x[1], pre_y[1], + pre_z[1], pre_x[10], pre_y[10], pre_z[10], p); + double_point_jacobi(pre_x[12], pre_y[12], pre_z[12], pre_x[6], pre_y[6], + pre_z[6], a, p); + add_points_jacobi(pre_x[13], pre_y[13], pre_z[13], pre_x[1], pre_y[1], + pre_z[1], pre_x[12], pre_y[12], pre_z[12], p); + double_point_jacobi(pre_x[14], pre_y[14], pre_z[14], pre_x[7], pre_y[7], + pre_z[7], a, p); + add_points_jacobi(pre_x[15], pre_y[15], pre_z[15], pre_x[1], pre_y[1], + pre_z[1], pre_x[14], pre_y[14], pre_z[14], p); + + for (k = 0; k < 6; k++) + TEE_BigIntInit(tmp_buffer + k * number_size, number_size); + tmp1 = tmp_buffer; + tmp2 = tmp_buffer + 3 * number_size; + w = scalar[0] >> 4; + TEE_BigIntAssign(tmp1, pre_x[w]); + TEE_BigIntAssign(tmp1 + number_size, pre_y[w]); + TEE_BigIntAssign(tmp1 + 2 * number_size, pre_z[w]); + + /* Double four times, then add the appropriate pre-computed multiple. */ + for (k = 1; k < 2 * scalar_size; ++k) { + double_point_jacobi(tmp2, tmp2 + number_size, + tmp2 + 2 * number_size, tmp1, + tmp1 + number_size, tmp1 + 2 * number_size, + a, p); + double_point_jacobi(tmp1, tmp1 + number_size, + tmp1 + 2 * number_size, tmp2, + tmp2 + number_size, tmp2 + 2 * number_size, + a, p); + double_point_jacobi(tmp2, tmp2 + number_size, + tmp2 + 2 * number_size, tmp1, + tmp1 + number_size, tmp1 + 2 * number_size, + a, p); + double_point_jacobi(tmp1, tmp1 + number_size, + tmp1 + 2 * number_size, tmp2, + tmp2 + number_size, tmp2 + 2 * number_size, + a, p); + w = scalar[k >> 1]; + if (k & 1) { + w &= 0xf; + } else { + w >>= 4; + } + add_points_jacobi(tmp2, tmp2 + number_size, + tmp2 + 2 * number_size, tmp1, + tmp1 + number_size, tmp1 + 2 * number_size, + pre_x[w], pre_y[w], pre_z[w], p); + /* Swap tmp1, tmp2. */ + t = tmp1; + tmp1 = tmp2; + tmp2 = t; + } + TEE_BigIntAssign(x3, tmp1); + TEE_BigIntAssign(y3, tmp1 + number_size); + TEE_BigIntAssign(z3, tmp1 + 2 * number_size); + +#ifdef DEBUG_OUTPUT_TEE_MATH + printf(" x3 = 0x"); + printf_bigint(x3); + printf("\n y3 = 0x"); + printf_bigint(y3); + printf("\n z3 = 0x"); + printf_bigint(z3); + printf("\n"); +#endif } -static void jacobi_to_affine(TEE_BigInt* x3, - TEE_BigInt* y3, - const TEE_BigInt* x1, - const TEE_BigInt* y1, - const TEE_BigInt* z1, - const TEE_BigInt* p) +static void jacobi_to_affine(TEE_BigInt *x3, TEE_BigInt *y3, + const TEE_BigInt *x1, const TEE_BigInt *y1, + const TEE_BigInt *z1, const TEE_BigInt *p) { -# ifdef DEBUG_OUTPUT_TEE_MATH - printf("jacobi_to_affine\n"); -# endif - size_t number_size = TEE_BigIntSizeInU32(TEE_BigIntGetBitCount(p)); - TEE_BigInt zi[number_size]; - TEE_BigIntInit(zi, number_size); - TEE_BigInt pm2[number_size]; - TEE_BigIntInit(pm2, number_size); - - const size_t fmm_ctx_size = - TEE_BigIntFMMContextSizeInU32(TEE_BigIntGetBitCount(p)); - uint32_t fmm_ctx[fmm_ctx_size]; - TEE_BigIntInitFMMContext1((TEE_BigIntFMMContext*)fmm_ctx, fmm_ctx_size, p); - - TEE_BigIntConvertFromS32(pm2, 2); - TEE_BigIntSub(pm2, p, pm2); // pm2 <- p-2 - TEE_BigIntExpMod( - zi, z1, pm2, p, (TEE_BigIntFMMContext*)fmm_ctx); // Use Fermat for inversion. - TEE_BigIntMulMod(pm2, zi, zi, p); // pm2 <- zi^2 - TEE_BigIntMulMod(x3, x1, pm2, p); - TEE_BigIntMulMod(pm2, pm2, zi, p); // pm2 <- zi^3 - TEE_BigIntMulMod(y3, y1, pm2, p); -# ifdef DEBUG_OUTPUT_TEE_MATH - printf(" return\n"); -# endif + const size_t p_bitcount = TEE_BigIntGetBitCount(p); + const size_t number_size = TEE_BigIntSizeInU32(p_bitcount); + TEE_BigInt zi[number_size]; + TEE_BigInt pm2[number_size]; + TEE_BigIntFMMContext fmm_ctx[TEE_BigIntFMMContextSizeInU32(p_bitcount)]; + + BIGINT_INIT(zi); + BIGINT_INIT(pm2); + if (TEE_BigIntInitFMMContext1(fmm_ctx, ARRAY_SIZE(fmm_ctx), p)) + TEE_Panic(0); + + TEE_BigIntConvertFromS32(pm2, 2); + TEE_BigIntSub(pm2, p, pm2); /* pm2 = p - 2 */ + TEE_BigIntExpMod(zi, z1, pm2, p, fmm_ctx); /* Use Fermat for inversion*/ + TEE_BigIntMulMod(pm2, zi, zi, p); /* pm2 = zi^2 */ + TEE_BigIntMulMod(x3, x1, pm2, p); + TEE_BigIntMulMod(pm2, pm2, zi, p); /* pm2 = zi^3 */ + TEE_BigIntMulMod(y3, y1, pm2, p); } -LIB_EXPORT BOOL BnEccModMult(bigPoint R, // OUT: computed point - pointConst S, // IN: point to multiply by 'd' - bigConst d, // IN: scalar for [d]S - bigCurve E) +LIB_EXPORT BOOL BnEccModMult(bigPoint R, pointConst S, bigConst d, bigCurve E) { -# ifdef DEBUG_OUTPUT_TEE_MATH - printf("BnEccModMult(%p, %p, %p, %p)\n", R, S, d, E); -# endif - - if(S == 0) - { - S = CurveGetG(AccessCurveData(E)); - } - - // We assume that everything is sane and coordinates are < p and the - // scalar is at most one word longer than p. - const NUMBYTES buffer_size = sizeof(crypt_uword_t) * (BnGetSize(E->prime) + 1); - BYTE buffer[buffer_size]; - - size_t len = TEE_BigIntSizeInU32(BnGetSizeInBit(E->prime)); - TEE_BigInt tee_p[len]; - TEE_BigIntInit(tee_p, len); - TEE_BigInt tee_x1[len]; - TEE_BigIntInit(tee_x1, len); - TEE_BigInt tee_y1[len]; - TEE_BigIntInit(tee_y1, len); - TEE_BigInt tee_z1[len]; - TEE_BigIntInit(tee_z1, len); - TEE_BigInt tee_x3[len]; - TEE_BigIntInit(tee_x3, len); - TEE_BigInt tee_y3[len]; - TEE_BigIntInit(tee_y3, len); - TEE_BigInt tee_z3[len]; - TEE_BigIntInit(tee_z3, len); - - len = TEE_BigIntSizeInU32(BnGetSizeInBit(E->a)); - TEE_BigInt tee_a[len]; - TEE_BigIntInit(tee_a, len); - - NUMBYTES size = BnGetSizeInBytes(E->prime); - BnToBytes(E->prime, buffer, &size); - TEE_BigIntConvertFromOctetString( - tee_p, buffer, size, 0); /// @todo Check that all numbers are non-negative. - size = BnGetSizeInBytes(E->a); - BnToBytes(E->a, buffer, &size); - TEE_BigIntConvertFromOctetString( - tee_a, buffer, size, 0); /// @todo Check that all numbers are non-negative. - size = BnGetSizeInBytes(S->x); - BnToBytes(S->x, buffer, &size); - TEE_BigIntConvertFromOctetString( - tee_x1, buffer, size, 0); /// @todo Check that all numbers are non-negative. - size = BnGetSizeInBytes(S->y); - BnToBytes(S->y, buffer, &size); - TEE_BigIntConvertFromOctetString( - tee_y1, buffer, size, 0); /// @todo Check that all numbers are non-negative. - TEE_BigIntConvertFromS32(tee_z1, 1); - size = BnGetSizeInBytes(d); - BnToBytes(d, buffer, &size); - - scalar_multiplication_jacobi( - tee_x3, tee_y3, tee_z3, tee_x1, tee_y1, tee_z1, buffer, size, tee_a, tee_p); - jacobi_to_affine(tee_x1, tee_y1, tee_x3, tee_y3, tee_z3, tee_p); - - size_t tee_size = buffer_size; - TEE_BigIntConvertToOctetString(buffer, &tee_size, tee_x1); - VERIFY(BnFromBytes(R->x, buffer, tee_size)); - tee_size = buffer_size; - TEE_BigIntConvertToOctetString(buffer, &tee_size, tee_y1); - VERIFY(BnFromBytes(R->y, buffer, tee_size)); - buffer[0] = 1; - VERIFY(BnFromBytes(R->z, buffer, 1)); - return TRUE; -Error: - return FALSE; + const size_t prime_len = bigint_len_from_bn(E->prime); + TEE_BigInt tee_a[bigint_len_from_bn(E->a)]; + BYTE buffer[bn_size_in_bytes(E->prime) + 1]; + TEE_BigInt tee_p[prime_len]; + TEE_BigInt tee_x1[prime_len]; + TEE_BigInt tee_y1[prime_len]; + TEE_BigInt tee_z1[prime_len]; + TEE_BigInt tee_x3[prime_len]; + TEE_BigInt tee_y3[prime_len]; + TEE_BigInt tee_z3[prime_len]; + NUMBYTES size = 0; + + if (!S) + S = CurveGetG(AccessCurveData(E)); + + BIGINT_INIT(tee_x3); + BIGINT_INIT(tee_y3); + BIGINT_INIT(tee_z3); + + if (!BIGINT_INIT_FROM_BN(tee_p, E->prime) || + !BIGINT_INIT_FROM_BN(tee_a, E->a) || + !BIGINT_INIT_FROM_BN(tee_x1, S->x) || + !BIGINT_INIT_FROM_BN(tee_y1, S->y) || + !BIGINT_INIT_FROM_BN(tee_z1, S->z)) + return FALSE; + + size = bn_size_in_bytes(d); + if (!BnToBytes(d, buffer, &size)) + return FALSE; + scalar_multiplication_jacobi(tee_x3, tee_y3, tee_z3, tee_x1, tee_y1, + tee_z1, buffer, size, tee_a, tee_p); + jacobi_to_affine(tee_x1, tee_y1, tee_x3, tee_y3, tee_z3, tee_p); + + if (!bigint_to_bignum(tee_x1, R->x) || + !bigint_to_bignum(tee_y1, R->y) || + !BnFromBytes(R->z, &(const BYTE){1}, 1)) + return FALSE; + return TRUE; } -LIB_EXPORT BOOL BnEccModMult2(bigPoint R, // OUT: computed point - pointConst S, // IN: optional point - bigConst d, // IN: scalar for [d]S or [d]G - pointConst Q, // IN: second point - bigConst u, // IN: second scalar - bigCurve E // IN: curve -) +LIB_EXPORT BOOL BnEccModMult2(bigPoint R, pointConst S, bigConst d, + pointConst Q, bigConst u, bigCurve E) { -# ifdef DEBUG_OUTPUT_TEE_MATH - printf("BnEccModMult2\n"); -# endif - // We assume that everything is sane and coordinates are < p and the - // scalar is at most one word longer than p. - const NUMBYTES buffer_size = sizeof(crypt_uword_t) * (BnGetSize(E->prime) + 1); - BYTE buffer[buffer_size]; - - size_t len = TEE_BigIntSizeInU32(BnGetSizeInBit(E->prime)); - TEE_BigInt tee_p[len]; - TEE_BigIntInit(tee_p, len); - TEE_BigInt tee_x1[len]; - TEE_BigIntInit(tee_x1, len); - TEE_BigInt tee_y1[len]; - TEE_BigIntInit(tee_y1, len); - TEE_BigInt tee_z1[len]; - TEE_BigIntInit(tee_z1, len); - TEE_BigInt tee_x2[len]; - TEE_BigIntInit(tee_x2, len); - TEE_BigInt tee_y2[len]; - TEE_BigIntInit(tee_y2, len); - TEE_BigInt tee_z2[len]; - TEE_BigIntInit(tee_z2, len); - TEE_BigInt tee_x3[len]; - TEE_BigIntInit(tee_x3, len); - TEE_BigInt tee_y3[len]; - TEE_BigIntInit(tee_y3, len); - TEE_BigInt tee_z3[len]; - TEE_BigIntInit(tee_z3, len); - - len = TEE_BigIntSizeInU32(BnGetSizeInBit(E->a)); - TEE_BigInt tee_a[len]; - TEE_BigIntInit(tee_a, len); - - NUMBYTES size = BnGetSizeInBytes(E->prime); - BnToBytes(E->prime, buffer, &size); - TEE_BigIntConvertFromOctetString( - tee_p, buffer, size, 0); /// @todo Check that all numbers are non-negative. - size = BnGetSizeInBytes(E->a); - BnToBytes(E->a, buffer, &size); - TEE_BigIntConvertFromOctetString( - tee_a, buffer, size, 0); /// @todo Check that all numbers are non-negative. - size = BnGetSizeInBytes(S->x); - BnToBytes(S->x, buffer, &size); - TEE_BigIntConvertFromOctetString( - tee_x1, buffer, size, 0); /// @todo Check that all numbers are non-negative. - size = BnGetSizeInBytes(S->y); - BnToBytes(S->y, buffer, &size); - TEE_BigIntConvertFromOctetString( - tee_y1, buffer, size, 0); /// @todo Check that all numbers are non-negative. - TEE_BigIntConvertFromS32(tee_z1, 1); - size = BnGetSizeInBytes(d); - BnToBytes(d, buffer, &size); - size = BnGetSizeInBytes(Q->x); - BnToBytes(Q->x, buffer, &size); - TEE_BigIntConvertFromOctetString( - tee_x2, buffer, size, 0); /// @todo Check that all numbers are non-negative. - size = BnGetSizeInBytes(Q->y); - BnToBytes(Q->y, buffer, &size); - TEE_BigIntConvertFromOctetString( - tee_y2, buffer, size, 0); /// @todo Check that all numbers are non-negative. - TEE_BigIntConvertFromS32(tee_z2, 1); - size = BnGetSizeInBytes(d); - BnToBytes(d, buffer, &size); - - /// @todo Use a more efficient algorithm for multiple scalar multiplication. - scalar_multiplication_jacobi( - tee_x3, tee_y3, tee_z3, tee_x1, tee_y1, tee_z1, buffer, size, tee_a, tee_p); - size = BnGetSizeInBytes(u); - BnToBytes(u, buffer, &size); - scalar_multiplication_jacobi( - tee_x1, tee_y1, tee_z1, tee_x2, tee_y2, tee_z2, buffer, size, tee_a, tee_p); - add_points_jacobi(tee_x2, - tee_y2, - tee_z2, - tee_x1, - tee_y1, - tee_z1, - tee_x3, - tee_y3, - tee_z3, - tee_p); - jacobi_to_affine(tee_x1, tee_y1, tee_x2, tee_y2, tee_z2, tee_p); - - size_t tee_size = buffer_size; - TEE_BigIntConvertToOctetString(buffer, &tee_size, tee_x1); - VERIFY(BnFromBytes(R->x, buffer, tee_size)); - tee_size = buffer_size; - TEE_BigIntConvertToOctetString(buffer, &tee_size, tee_y1); - VERIFY(BnFromBytes(R->y, buffer, tee_size)); - buffer[0] = 1; - VERIFY(BnFromBytes(R->z, buffer, 1)); - return TRUE; -Error: - return FALSE; + size_t prime_len = bigint_len_from_bn(E->prime); + size_t a_len = bigint_len_from_bn(E->a); + BYTE buffer[bn_size_in_bytes(E->prime) + 1]; + TEE_BigInt tee_p[prime_len]; + TEE_BigInt tee_x1[prime_len]; + TEE_BigInt tee_y1[prime_len]; + TEE_BigInt tee_z1[prime_len]; + TEE_BigInt tee_x2[prime_len]; + TEE_BigInt tee_y2[prime_len]; + TEE_BigInt tee_z2[prime_len]; + TEE_BigInt tee_x3[prime_len]; + TEE_BigInt tee_y3[prime_len]; + TEE_BigInt tee_z3[prime_len]; + TEE_BigInt tee_a[a_len]; + NUMBYTES size = 0; + + BIGINT_INIT(tee_z2); + BIGINT_INIT(tee_x3); + BIGINT_INIT(tee_y3); + BIGINT_INIT(tee_z3); + if (!BIGINT_INIT_FROM_BN(tee_p, E->prime) || + !BIGINT_INIT_FROM_BN(tee_a, E->a) || + !BIGINT_INIT_FROM_BN(tee_x1, S->x) || + !BIGINT_INIT_FROM_BN(tee_y1, S->y) || + !BIGINT_INIT_FROM_BN(tee_z1, S->z) || + !BIGINT_INIT_FROM_BN(tee_x2, Q->x) || + !BIGINT_INIT_FROM_BN(tee_y2, Q->y)) + return FALSE; + + TEE_BigIntConvertFromS32(tee_z2, 1); + + size = bn_size_in_bytes(d); + BnToBytes(d, buffer, &size); + + /* + * TODO Use a more efficient algorithm for multiple scalar + * multiplication. + */ + scalar_multiplication_jacobi(tee_x3, tee_y3, tee_z3, tee_x1, tee_y1, + tee_z1, buffer, size, tee_a, tee_p); + size = bn_size_in_bytes(u); + BnToBytes(u, buffer, &size); + scalar_multiplication_jacobi(tee_x1, tee_y1, tee_z1, tee_x2, tee_y2, + tee_z2, buffer, size, tee_a, tee_p); + add_points_jacobi(tee_x2, tee_y2, tee_z2, tee_x1, tee_y1, tee_z1, + tee_x3, tee_y3, tee_z3, tee_p); + jacobi_to_affine(tee_x1, tee_y1, tee_x2, tee_y2, tee_z2, tee_p); + + if (!bigint_to_bignum(tee_x1, R->x) || + !bigint_to_bignum(tee_y1, R->y) || + !BnFromBytes(R->z, &(const BYTE){1}, 1)) + return FALSE; + return TRUE; } #endif diff --git a/ta/ftpm/tee/TpmToTEESym.c b/ta/ftpm/tee/TpmToTEESym.c index aaa161fafdc..e92f867dd88 100644 --- a/ta/ftpm/tee/TpmToTEESym.c +++ b/ta/ftpm/tee/TpmToTEESym.c @@ -4,442 +4,158 @@ * All rights reserved. */ +#include "Tpm.h" #include #include -#ifdef DEBUG_OUTPUT_TEE_SYM -# include -#endif - -#ifdef DEBUG_OUTPUT_TEE_SYM -# define DEBUG_PRINT_RESULT(f) printf(" " #f " returns %" PRIx32 "\n", f) -#else -# define DEBUG_PRINT_RESULT(f) f -#endif - -/// @todo It is ugly to repeat these definitions here rather than just include TpmToTEESym.h, but this would require a major re-structuring of h-files. - -/// @brief The TEE does not export a key schedule, so this is not really a key schedule but rather a copy of the key. -typedef struct -{ - uint16_t keySizeInBytes; - uint8_t key[32]; -} tpmKeyScheduleAES; - -/// @brief The TEE does not export a key schedule, so this is not really a key schedule but rather a copy of the key. -typedef struct -{ - uint16_t keySizeInBytes; - uint8_t key[24]; -} tpmKeyScheduleTDES; - -/// @brief The TEE does not export a key schedule, so this is not really a key schedule but rather a copy of the key. -typedef struct -{ - uint16_t keySizeInBytes; - uint8_t key[16]; -} tpmKeyScheduleSM4; - -/// @brief Set AES key. -/// @param[out] key_schedule pointer to space for storing the key schedule -/// @param[in] key pointer to the key -/// @param[in] keySizeInBytes length of the key in bytes -/// @return 0 if ok, any other value otherwise -/// @todo There is no `finalize` function, so we can't allocate the key schedule here, because we could never free it. -int TEE_SetKeyAES( - tpmKeyScheduleAES* key_schedule, const uint8_t* key, uint16_t keySizeInBytes) +#include + +/* + * TEE_SetKeyAES() - Set AES key. + * @ks pointer to space for storing the key schedule + * @key pointer to the key + * @sz length of the key in bytes + * + * There is no "finalize" function, so we can't allocate the key schedule + * here, because we could never free it. + * + * return 0 if ok, any other value otherwise + */ +int TEE_SetKeyAES(tpmKeyScheduleAES *ks, const uint8_t *key, uint16_t sz) { -#ifdef DEBUG_OUTPUT_TEE_SYM - printf("TEE_SetKeyAES(%p, %p, %d)\n", key_schedule, key, (int)keySizeInBytes); - printf(" key = "); - for(uint16_t k = 0; k < keySizeInBytes; ++k) - { - printf("%.2x", (unsigned int)(key[k])); - } - printf("\n"); -#endif - if(((keySizeInBytes == 16) || (keySizeInBytes == 24) || (keySizeInBytes == 32)) - && (keySizeInBytes <= sizeof(key_schedule->key))) - { - key_schedule->keySizeInBytes = keySizeInBytes; - memcpy(key_schedule->key, key, keySizeInBytes); - return 0; - } - else - { - return 1; - } + if (sz == 16 || sz == 24 || sz == 32) { + ks->keySizeInBytes = sz; + memcpy(ks->key, key, sz); + return 0; + } else { + return 1; + } } -/// @brief Set DES key. -/// @param[out] key_schedule pointer to space for storing the key schedule -/// @param[in] key pointer to the key -/// @param[in] keySizeInBytes length of the key in bytes -/// @return 0 if ok, any other value otherwise -/// @todo There is no `finalize` function, so we can't allocate the key schedule here, because we could never free it. -int TEE_SetKeyTDES( - tpmKeyScheduleTDES* key_schedule, const uint8_t* key, uint16_t keySizeInBytes) +/* + * TEE_SetKeyTDES() - Set DES key. + * @ks pointer to space for storing the key schedule + * @key pointer to the key + * @sz length of the key in bytes + * + * There is no "finalize" function, so we can't allocate the key schedule + * here, because we could never free it. + * + * return 0 if ok, any other value otherwise + */ +int TEE_SetKeyTDES(tpmKeyScheduleTDES *ks, const uint8_t *key, uint16_t sz) { -#ifdef DEBUG_OUTPUT_TEE_SYM - printf("TEE_SetKeyTDES(%p, %p, %d)\n", key_schedule, key, (int)keySizeInBytes); - printf(" key = "); - for(uint16_t k = 0; k < keySizeInBytes; ++k) - { - printf("%.2x", (unsigned int)(key[k])); - } - printf("\n"); -#endif - if(((keySizeInBytes == 16) || (keySizeInBytes == 24)) - && (keySizeInBytes <= sizeof(key_schedule->key))) - { - key_schedule->keySizeInBytes = keySizeInBytes; - memcpy(key_schedule->key, key, keySizeInBytes); - return 0; - } - else - { - return 1; - } + if (sz == 16 || sz == 24) { + ks->keySizeInBytes = sz; + memcpy(ks->key, key, sz); + return 0; + } else { + return 1; + } } -/// @brief Set SM4 key. -/// @param[out] key_schedule pointer to space for storing the key schedule -/// @param[in] key pointer to the key -/// @param[in] keySizeInBytes length of the key in bytes -/// @return 0 if ok, any other value otherwise -/// @todo There is no `finalize` function, so we can't allocate the key schedule here, because we could never free it. -int TEE_SetKeySM4( - tpmKeyScheduleSM4* key_schedule, const uint8_t* key, uint16_t keySizeInBytes) +/* + * TEE_SetKeySM4() - Set SM4 key. + * @ks pointer to space for storing the key schedule + * @key pointer to the key + * @sz length of the key in bytes + * + * return 0 if ok, any other value otherwise + * + * There is no "finalize" function, so we can't allocate the key schedule + * here, because we could never free it. + */ +int TEE_SetKeySM4(tpmKeyScheduleSM4 *ks, const uint8_t *key, uint16_t sz) { -#ifdef DEBUG_OUTPUT_TEE_SYM - printf("TEE_SetKeySM4(%p, %p, %d)\n", key_schedule, key, (int)keySizeInBytes); - printf(" key = "); - for(uint16_t k = 0; k < keySizeInBytes; ++k) - { - printf("%.2x", (unsigned int)(key[k])); - } - printf("\n"); -#endif - if((keySizeInBytes == 16) && (keySizeInBytes <= sizeof(key_schedule->key))) - { - key_schedule->keySizeInBytes = keySizeInBytes; - memcpy(key_schedule->key, key, keySizeInBytes); - return 0; - } - else - { - return 1; - } + if (sz == 16) { + ks->keySizeInBytes = sz; + memcpy(ks->key, key, sz); + return 0; + } else { + return 1; + } } -typedef enum -{ - ALGO_AES, - ALGO_TDES, - ALGO_SM4 -} SymAlgoType; - -typedef enum -{ - OP_ENCRYPT, - OP_DECRYPT -} SymOp; - -/// @brief Encrypt or decrypt one block of data with AES, TDES or SM4 -/// @param[out] out pointer to space for one block of output data (16 bytes for AES and SM4, 8 bytes for TDES) -/// @param[in] algo algorithm -/// @param[in] op operation -/// @param[in] key pointer to key -/// @param[in] keySizeInBytes length of key in bytes -/// @param[in] in pointer to one block of input data (16 bytes for AES and SM4, 8 bytes for TDES) -static void TEE_sym(uint8_t* out, - SymAlgoType algo, - SymOp op, - const uint8_t* key, - uint16_t keySizeInBytes, - const uint8_t* in) +/* + * The functions calling this function can't return an error so neither can + * this. In case of error we panic since the alternative is to carry out + * the operation incorrectly. + */ +static void block_op(uint8_t *out, uint32_t algo, uint32_t mode, + size_t block_size, TEE_ObjectType obj_type, + const uint8_t *key, uint16_t keySizeInBytes, + const uint8_t *in) { - uint32_t objectType; - uint32_t mode; - uint32_t algorithm; - unsigned int blockSize; - switch(algo) - { - case ALGO_AES: - objectType = TEE_TYPE_AES; - algorithm = TEE_ALG_AES_ECB_NOPAD; - blockSize = 16; - break; - case ALGO_TDES: - objectType = TEE_TYPE_DES3; - algorithm = TEE_ALG_DES3_ECB_NOPAD; - blockSize = 8; - break; - case ALGO_SM4: - objectType = TEE_TYPE_SM4; - algorithm = TEE_ALG_SM4_ECB_NOPAD; - blockSize = 16; - break; - default: - /// @todo Do error handling! - break; - } - switch(op) - { - case OP_ENCRYPT: - mode = TEE_MODE_ENCRYPT; - break; - case OP_DECRYPT: - mode = TEE_MODE_DECRYPT; - break; - default: - /// @todo Do error handling! - break; - } - - TEE_ObjectHandle object; - DEBUG_PRINT_RESULT( - TEE_AllocateTransientObject(objectType, 8 * keySizeInBytes, &object)); - TEE_Attribute attr; - TEE_InitRefAttribute(&attr, TEE_ATTR_SECRET_VALUE, key, keySizeInBytes); - DEBUG_PRINT_RESULT(TEE_PopulateTransientObject(object, &attr, 1)); - TEE_OperationHandle operation; - DEBUG_PRINT_RESULT( - TEE_AllocateOperation(&operation, algorithm, mode, 8 * keySizeInBytes)); - DEBUG_PRINT_RESULT(TEE_SetOperationKey(operation, object)); - - TEE_CipherInit(operation, 0, 0); - size_t outlen = blockSize; -#ifdef DEBUG_OUTPUT_TEE_SYM - printf("TEE_CipherDoFinal(operation, in, blockSize, out, &outlen) - BEFORE CALL\n"); - printf(" in = "); - for(size_t k = 0; k < blockSize; ++k) - { - printf("%.2x", in[k]); - } - printf("\n"); - printf(" out = "); - for(size_t k = 0; k < blockSize; ++k) - { - printf("%.2x", out[k]); - } - printf("\n"); -#endif - DEBUG_PRINT_RESULT(TEE_CipherDoFinal(operation, in, blockSize, out, &outlen)); -#ifdef DEBUG_OUTPUT_TEE_SYM - printf("TEE_CipherDoFinal(operation, in, blockSize, out, &outlen) - AFTER CALL\n"); - printf(" in = "); - for(size_t k = 0; k < blockSize; ++k) - { - printf("%.2x", in[k]); - } - printf("\n"); - printf(" out = "); - for(size_t k = 0; k < blockSize; ++k) - { - printf("%.2x", out[k]); - } - printf("\n"); -#endif - - TEE_FreeOperation(operation); - TEE_FreeTransientObject(object); - /// @todo Do proper error handling. + TEE_OperationHandle op = TEE_HANDLE_NULL; + TEE_ObjectHandle obj = TEE_HANDLE_NULL; + TEE_Result res = TEE_SUCCESS; + size_t outlen = block_size; + TEE_Attribute attr = {}; + + res = TEE_AllocateTransientObject(obj_type, 8 * keySizeInBytes, &obj); + if (res) + TEE_Panic(res); + + TEE_InitRefAttribute(&attr, TEE_ATTR_SECRET_VALUE, key, keySizeInBytes); + res = TEE_PopulateTransientObject(obj, &attr, 1); + if (res) + TEE_Panic(res); + + res = TEE_AllocateOperation(&op, algo, mode, 8 * keySizeInBytes); + if (res) + TEE_Panic(res); + + res = TEE_SetOperationKey(op, obj); + if (res) + TEE_Panic(res); + + TEE_CipherInit(op, 0, 0); + outlen = block_size; + res = TEE_CipherDoFinal(op, in, block_size, out, &outlen); + if (res) + TEE_Panic(res); + + TEE_FreeOperation(op); + TEE_FreeTransientObject(obj); } -/// @brief Encrypt a single 16 byte block of data with AES. -/// @param out pointer to 16 bytes space for output -/// @param key_schedule pointer to the key schedule, initialized with TEE_SetKeyAES(). -/// @param in pointer to 16 bytes input -/// @todo This is a very thin wrapper that may not be needed. -void TEE_AESEncrypt( - uint8_t* out, const tpmKeyScheduleAES* key_schedule, const uint8_t* in) +void TEE_AESEncrypt(uint8_t *out, const tpmKeyScheduleAES *ks, + const uint8_t *in) { -#ifdef DEBUG_OUTPUT_TEE_SYM - printf("TEE_AESEncrypt(%p, %p, %p)\n", out, key_schedule, in); - printf(" in = "); - for(size_t k = 0; k < 16; ++k) - { - printf("%.2x", (unsigned int)(in[k])); - } - printf("\n"); -#endif - TEE_sym(out, - ALGO_AES, - OP_ENCRYPT, - key_schedule->key, - key_schedule->keySizeInBytes, - in); -#ifdef DEBUG_OUTPUT_TEE_SYM - printf(" out = "); - for(size_t k = 0; k < 16; ++k) - { - printf("%.2x", (unsigned int)(out[k])); - } - printf("\n"); -#endif + block_op(out, TEE_ALG_AES_ECB_NOPAD, TEE_MODE_ENCRYPT, 16, TEE_TYPE_AES, + ks->key, ks->keySizeInBytes, in); } -/// @brief Decrypt a single 16 byte block of data with AES. -/// @param out pointer to 16 bytes space for output -/// @param key_schedule pointer to the key schedule, initialized with TEE_SetKeyAES(). -/// @param in pointer to 16 bytes input -/// @todo This is a very thin wrapper that may not be needed. -void TEE_AESDecrypt( - uint8_t* out, const tpmKeyScheduleAES* key_schedule, const uint8_t* in) +void TEE_AESDecrypt(uint8_t *out, const tpmKeyScheduleAES *ks, + const uint8_t *in) { -#ifdef DEBUG_OUTPUT_TEE_SYM - printf("TEE_AESDecrypt(%p, %p, %p)\n", out, key_schedule, in); - printf(" in = "); - for(size_t k = 0; k < 16; ++k) - { - printf("%.2x", (unsigned int)(in[k])); - } - printf("\n"); -#endif - TEE_sym(out, - ALGO_AES, - OP_DECRYPT, - key_schedule->key, - key_schedule->keySizeInBytes, - in); -#ifdef DEBUG_OUTPUT_TEE_SYM - printf(" out = "); - for(size_t k = 0; k < 16; ++k) - { - printf("%.2x", (unsigned int)(in[k])); - } - printf("\n"); -#endif + block_op(out, TEE_ALG_AES_ECB_NOPAD, TEE_MODE_DECRYPT, 16, TEE_TYPE_AES, + ks->key, ks->keySizeInBytes, in); } -/// @brief Encrypt a single 8 byte block of data with TDES. -/// @param out pointer to 8 bytes space for output -/// @param key_schedule pointer to the key schedule, initialized with TEE_SetKeyTDES(). -/// @param in pointer to 8 bytes input -/// @todo This is a very thin wrapper that may not be needed. -void TEE_TDESEncrypt( - uint8_t* out, const tpmKeyScheduleTDES* key_schedule, const uint8_t* in) +void TEE_TDESEncrypt(uint8_t *out, const tpmKeyScheduleTDES *ks, + const uint8_t *in) { -#ifdef DEBUG_OUTPUT_TEE_SYM - printf("TEE_TDESEncrypt(%p, %p, %p)\n", out, key_schedule, in); - printf(" in = "); - for(size_t k = 0; k < 8; ++k) - { - printf("%.2x", (unsigned int)(in[k])); - } - printf("\n"); -#endif - TEE_sym(out, - ALGO_TDES, - OP_ENCRYPT, - key_schedule->key, - key_schedule->keySizeInBytes, - in); -#ifdef DEBUG_OUTPUT_TEE_SYM - printf(" out = "); - for(size_t k = 0; k < 8; ++k) - { - printf("%.2x", (unsigned int)(in[k])); - } - printf("\n"); -#endif + block_op(out, TEE_ALG_DES3_ECB_NOPAD, TEE_MODE_ENCRYPT, 8, + TEE_TYPE_DES3, ks->key, ks->keySizeInBytes, in); } -/// @brief Decrypt a single 8 byte block of data with TDES. -/// @param out pointer to 8 bytes space for output -/// @param key_schedule pointer to the key schedule, initialized with TEE_SetKeyTDES(). -/// @param in pointer to 8 bytes input -/// @todo This is a very thin wrapper that may not be needed. -void TEE_TDESDecrypt( - uint8_t* out, const tpmKeyScheduleTDES* key_schedule, const uint8_t* in) +void TEE_TDESDecrypt(uint8_t *out, const tpmKeyScheduleTDES *ks, + const uint8_t *in) { -#ifdef DEBUG_OUTPUT_TEE_SYM - printf("TEE_TDESDecrypt(%p, %p, %p)\n", out, key_schedule, in); - printf(" in = "); - for(size_t k = 0; k < 8; ++k) - { - printf("%.2x", (unsigned int)(in[k])); - } - printf("\n"); -#endif - TEE_sym(out, - ALGO_TDES, - OP_DECRYPT, - key_schedule->key, - key_schedule->keySizeInBytes, - in); -#ifdef DEBUG_OUTPUT_TEE_SYM - printf(" out = "); - for(size_t k = 0; k < 8; ++k) - { - printf("%.2x", (unsigned int)(in[k])); - } - printf("\n"); -#endif + block_op(out, TEE_ALG_DES3_ECB_NOPAD, TEE_MODE_DECRYPT, 8, + TEE_TYPE_DES3, ks->key, ks->keySizeInBytes, in); } -/// @brief Encrypt a single 16 byte block of data with SM4. -/// @param out pointer to 16 bytes space for output -/// @param key_schedule pointer to the key schedule, initialized with TEE_SetKeySM4(). -/// @param in pointer to 16 bytes input -/// @todo This is a very thin wrapper that may not be needed. -void TEE_SM4Encrypt( - uint8_t* out, const tpmKeyScheduleSM4* key_schedule, const uint8_t* in) +void TEE_SM4Encrypt(uint8_t *out, const tpmKeyScheduleSM4 *ks, + const uint8_t *in) { -#ifdef DEBUG_OUTPUT_TEE_SYM - printf("TEE_SM4Encrypt(%p, %p, %p)\n", out, key_schedule, in); - printf(" in = "); - for(size_t k = 0; k < 16; ++k) - { - printf("%.2x", (unsigned int)(in[k])); - } - printf("\n"); -#endif - TEE_sym(out, - ALGO_SM4, - OP_ENCRYPT, - key_schedule->key, - key_schedule->keySizeInBytes, - in); -#ifdef DEBUG_OUTPUT_TEE_SYM - printf(" out = "); - for(size_t k = 0; k < 16; ++k) - { - printf("%.2x", (unsigned int)(in[k])); - } - printf("\n"); -#endif + block_op(out, TEE_ALG_SM4_ECB_NOPAD, TEE_MODE_ENCRYPT, 16, TEE_TYPE_SM4, + ks->key, ks->keySizeInBytes, in); } -/// @brief Decrypt a single 16 byte block of data with SM4. -/// @param out pointer to 16 bytes space for output -/// @param key_schedule pointer to the key schedule, initialized with TEE_SetKeySM4(). -/// @param in pointer to 16 bytes input -/// @todo This is a very thin wrapper that may not be needed. -void TEE_SM4Decrypt( - uint8_t* out, const tpmKeyScheduleSM4* key_schedule, const uint8_t* in) +void TEE_SM4Decrypt(uint8_t *out, const tpmKeyScheduleSM4 *ks, + const uint8_t *in) { -#ifdef DEBUG_OUTPUT_TEE_SYM - printf("TEE_SM4Decrypt(%p, %p, %p)\n", out, key_schedule, in); - printf(" in = "); - for(size_t k = 0; k < 16; ++k) - { - printf("%.2x", (unsigned int)(in[k])); - } - printf("\n"); -#endif - TEE_sym(out, - ALGO_SM4, - OP_DECRYPT, - key_schedule->key, - key_schedule->keySizeInBytes, - in); -#ifdef DEBUG_OUTPUT_TEE_SYM - printf(" out = "); - for(size_t k = 0; k < 16; ++k) - { - printf("%.2x", (unsigned int)(in[k])); - } - printf("\n"); -#endif + block_op(out, TEE_ALG_SM4_ECB_NOPAD, TEE_MODE_DECRYPT, 16, TEE_TYPE_SM4, + ks->key, ks->keySizeInBytes, in); } From 9fa7212d89ff1d3378b8ab637d4bcfdc837a7ec0 Mon Sep 17 00:00:00 2001 From: Jens Wiklander Date: Thu, 26 Sep 2024 09:44:06 +0200 Subject: [PATCH 10/27] ftpm: implement hashlib using mbedtls Add and use hashlib wrappers for MbedTLS. Disabling ALG_SM3_256 since it's not supported by MbedTLS. Signed-off-by: Jens Wiklander --- ta/ftpm/include/MBEDTLS/TpmToMBEDTLSHash.h | 142 +++++++++++++++++++++ 1 file changed, 142 insertions(+) create mode 100644 ta/ftpm/include/MBEDTLS/TpmToMBEDTLSHash.h diff --git a/ta/ftpm/include/MBEDTLS/TpmToMBEDTLSHash.h b/ta/ftpm/include/MBEDTLS/TpmToMBEDTLSHash.h new file mode 100644 index 00000000000..c06c7d1906c --- /dev/null +++ b/ta/ftpm/include/MBEDTLS/TpmToMBEDTLSHash.h @@ -0,0 +1,142 @@ +/* SPDX-License-Identifier: BSD-2-Clause */ +/* + * Copyright (c) 2024, Linaro Limited + */ + +#ifndef __TPMTOMBEDTLSHASH_H +#define __TPMTOMBEDTLSHASH_H + +#define HASH_ALIGNMENT RADIX_BYTES + +#include +#include +#include +#include + +/* + * Define the internal name used for each of the hash state structures to + * the name used by the library. + * These defines need to be known in all parts of the TPM so that the + * structure sizes can be properly computed when needed. + */ + +#define tpmHashStateSHA1_t mbedtls_sha1_context +#define tpmHashStateSHA256_t mbedtls_sha256_context +#define tpmHashStateSHA384_t mbedtls_sha512_context +#define tpmHashStateSHA512_t mbedtls_sha512_context + +/* + * The defines below are only needed when compiling CryptHash.c or + * CryptSmac.c. + */ +#ifdef _CRYPT_HASH_C_ + +/* + * TPMCmd/tpm/src//crypt/CryptHash.c needs this to be defined here. + */ +typedef BYTE *PBYTE; + +#define HASH_START_METHOD_DEF void(HASH_START_METHOD)(PANY_HASH_STATE state) +#define HASH_START(_hs) ((_hs)->def->method.start)(&(_hs)->state); + +#define HASH_DATA_METHOD_DEF \ + void(HASH_DATA_METHOD)(PANY_HASH_STATE state, const BYTE *buffer, \ + size_t size) +#define HASH_DATA(_hs, dInSize, dIn) \ + ((_hs)->def->method.data)(&(_hs)->state, dIn, dInSize) + +#define HASH_END_METHOD_DEF \ + void(HASH_END_METHOD)(PANY_HASH_STATE state, BYTE * buffer) +#define HASH_END(_hs, buffer) ((_hs)->def->method.end)(&(_hs)->state, buffer) + +#define HASH_STATE_COPY_METHOD_DEF \ + void(HASH_STATE_COPY_METHOD)(PANY_HASH_STATE to, \ + PCANY_HASH_STATE from, size_t size) +#define HASH_STATE_COPY(hs_out, hs_in) \ + ((hs_in)->def->method.copy)(&(hs_out)->state, &(hs_in)->state, \ + (hs_in)->def->contextSize) + +#define HASH_STATE_EXPORT_METHOD_DEF \ + void(HASH_STATE_EXPORT_METHOD)(BYTE * to, PCANY_HASH_STATE from, \ + size_t size) +#define HASH_STATE_EXPORT(to, _hs) \ + ((_hs)->def->method.copyOut)( \ + &(((BYTE *)(to))[offsetof(HASH_STATE, state)]), \ + &(_hs)->state, (_hs)->def->contextSize) + +#define HASH_STATE_IMPORT_METHOD_DEF \ + void(HASH_STATE_IMPORT_METHOD)(PANY_HASH_STATE to, const BYTE *from, \ + size_t size) +#define HASH_STATE_IMPORT(_hs, from) \ + ((_hs)->def->method.copyIn)( \ + &(_hs)->state, \ + &(((const BYTE *)(from))[offsetof(HASH_STATE, state)]), \ + (_hs)->def->contextSize) + +static inline int tpmHashStart_SHA1(mbedtls_sha1_context *ctx) +{ + mbedtls_sha1_init(ctx); + return mbedtls_sha1_starts(ctx); +} +#define tpmHashData_SHA1 mbedtls_sha1_update +static inline int tpmHashEnd_SHA1(mbedtls_sha1_context *ctx, BYTE *buffer) +{ + int e = mbedtls_sha1_finish(ctx, buffer); + + mbedtls_sha1_free(ctx); + return e; +} +#define tpmHashStateCopy_SHA1 memcpy +#define tpmHashStateExport_SHA1 memcpy +#define tpmHashStateImport_SHA1 memcpy + +static inline int tpmHashStart_SHA256(mbedtls_sha256_context *ctx) +{ + mbedtls_sha256_init(ctx); + return mbedtls_sha256_starts(ctx, 0); +} +#define tpmHashData_SHA256 mbedtls_sha256_update +static inline int tpmHashEnd_SHA256(mbedtls_sha256_context *ctx, BYTE *buffer) +{ + int e = mbedtls_sha256_finish(ctx, buffer); + mbedtls_sha256_free(ctx); + return e; +} +#define tpmHashStateCopy_SHA256 memcpy +#define tpmHashStateExport_SHA256 memcpy +#define tpmHashStateImport_SHA256 memcpy + +/* SHA-384 is implemented using SHA-512, only initialized differently. */ +static inline int tpmHashStart_SHA384(mbedtls_sha512_context *ctx) +{ + mbedtls_sha512_init(ctx); + return mbedtls_sha512_starts(ctx, 1); +} +#define tpmHashData_SHA384 mbedtls_sha512_update +#define tpmHashEnd_SHA384 tpmHashEnd_SHA512 +#define tpmHashStateCopy_SHA384 tpmHashStateCopy_SHA512 +#define tpmHashStateExport_SHA384 tpmHashStateExport_SHA512 +#define tpmHashStateImport_SHA384 tpmHashStateImport_SHA512 + +static inline int tpmHashStart_SHA512(mbedtls_sha512_context *ctx) +{ + mbedtls_sha512_init(ctx); + return mbedtls_sha512_starts(ctx, 0); +} +#define tpmHashData_SHA512 mbedtls_sha512_update +static inline int tpmHashEnd_SHA512(mbedtls_sha512_context *ctx, BYTE *buffer) +{ + int e = mbedtls_sha512_finish(ctx, buffer); + mbedtls_sha512_free(ctx); + return e; +} +#define tpmHashStateCopy_SHA512 memcpy +#define tpmHashStateExport_SHA512 memcpy +#define tpmHashStateImport_SHA512 memcpy + +#endif /*_CRYPT_HASH_C_*/ + +#define LibHashInit() +#define HashLibSimulationEnd() + +#endif /*__TPMTOMBEDTLSHASH_H*/ From 67d099e8461f57903341a2ce80f1dd2e44f290f7 Mon Sep 17 00:00:00 2001 From: Jens Wiklander Date: Thu, 19 Sep 2024 11:39:35 +0200 Subject: [PATCH 11/27] ftpm: build the in-tree TA Build the in-tree fTPM TA if CFG_MS_TPM_20_REF is supplied as a non-empty path. Signed-off-by: Jens Wiklander --- Makefile | 4 ++++ ta/ftpm/ftpm_user_ta.mk | 2 ++ 2 files changed, 6 insertions(+) create mode 100644 ta/ftpm/ftpm_user_ta.mk diff --git a/Makefile b/Makefile index 8908849d50f..3c25bbbc2e1 100644 --- a/Makefile +++ b/Makefile @@ -98,6 +98,10 @@ include ta/mk/build-user-ta.mk endef $(foreach t, $(sort $(wildcard ta/*/user_ta.mk)), $(eval $(call build-user-ta,$(t)))) endif +ifneq ($(CFG_MS_TPM_20_REF),) +ta-mk-file := ta/ftpm/ftpm_user_ta.mk +include ta/mk/build-user-ta.mk +endif endif include mk/cleandirs.mk diff --git a/ta/ftpm/ftpm_user_ta.mk b/ta/ftpm/ftpm_user_ta.mk new file mode 100644 index 00000000000..7c673c53ed6 --- /dev/null +++ b/ta/ftpm/ftpm_user_ta.mk @@ -0,0 +1,2 @@ +user-ta-uuid := bc50d971-d4c9-42c4-82cb-343fb7f37896 +user-ta-version := 0 From aed2671a536f38f1a558cac5e01181b260cb9563 Mon Sep 17 00:00:00 2001 From: Jens Wiklander Date: Fri, 20 Sep 2024 15:39:29 +0200 Subject: [PATCH 12/27] ftpm: add secure storage TA flag Add TA_FLAG_DEVICE_ENUM_TEE_STORAGE_PRIVATE to TA_FLAGS to enumerate the TA once secure storage is available. Signed-off-by: Jens Wiklander --- ta/ftpm/user_ta_header_defines.h | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/ta/ftpm/user_ta_header_defines.h b/ta/ftpm/user_ta_header_defines.h index 92c33c16932..4c362360f3d 100644 --- a/ta/ftpm/user_ta_header_defines.h +++ b/ta/ftpm/user_ta_header_defines.h @@ -44,7 +44,9 @@ #define TA_UUID TA_FTPM_UUID -#define TA_FLAGS (TA_FLAG_SINGLE_INSTANCE | TA_FLAG_INSTANCE_KEEP_ALIVE) +#define TA_FLAGS (TA_FLAG_SINGLE_INSTANCE | \ + TA_FLAG_INSTANCE_KEEP_ALIVE | \ + TA_FLAG_DEVICE_ENUM_TEE_STORAGE_PRIVATE) #define TA_STACK_SIZE (64 * 1024) #define TA_DATA_SIZE (32 * 1024) From 2d8527f50754720a5e2f47470849a0ba69223691 Mon Sep 17 00:00:00 2001 From: Jens Wiklander Date: Tue, 24 Sep 2024 12:35:19 +0200 Subject: [PATCH 13/27] ftpm: PlatformData: remove redundant s_NV* Removes the redundant or invalid s_NV* declarations Signed-off-by: Jens Wiklander --- ta/ftpm/platform/PlatformData.c | 9 +-------- ta/ftpm/platform/include/PlatformData.h | 6 ------ 2 files changed, 1 insertion(+), 14 deletions(-) diff --git a/ta/ftpm/platform/PlatformData.c b/ta/ftpm/platform/PlatformData.c index 5fcc9dbd987..ce37940ec49 100644 --- a/ta/ftpm/platform/PlatformData.c +++ b/ta/ftpm/platform/PlatformData.c @@ -71,12 +71,5 @@ BOOL s_powerLost; // broken. uint32_t lastEntropy; - -// For NVMem.c -unsigned char s_NV[NV_MEMORY_SIZE]; -BOOL s_NvIsAvailable; -BOOL s_NV_unrecoverable; -BOOL s_NV_recoverable; - // From PPPlat.c -BOOL s_physicalPresence; \ No newline at end of file +BOOL s_physicalPresence; diff --git a/ta/ftpm/platform/include/PlatformData.h b/ta/ftpm/platform/include/PlatformData.h index f05493b7639..0beb4c2a691 100644 --- a/ta/ftpm/platform/include/PlatformData.h +++ b/ta/ftpm/platform/include/PlatformData.h @@ -118,12 +118,6 @@ extern unsigned char s_locality; # define FILE_BACKED_NV NO #endif // SIMULATION -extern unsigned char s_NV[NV_MEMORY_SIZE]; -extern BOOL s_NvIsAvailable; -extern BOOL s_NV_unrecoverable; -extern BOOL s_NV_recoverable; - - // For PPPlat.c // Physical presence. It is initialized to FALSE extern BOOL s_physicalPresence; From fd99d4a09639866ee749b5cc5570324f4f449f05 Mon Sep 17 00:00:00 2001 From: Jens Wiklander Date: Tue, 24 Sep 2024 12:38:18 +0200 Subject: [PATCH 14/27] ftpm: _plat__Fail() fix __noreturn _plat__Fail() is declared with a __noreturn since it's guaranteed to not return, but it only calls TEE_Panic() which doesn't have the same attribute. TEE_Panic() does indeed never return so add a while(true) after the TEE_Panic() so silence the warning. Signed-off-by: Jens Wiklander --- ta/ftpm/platform/RunCommand.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/ta/ftpm/platform/RunCommand.c b/ta/ftpm/platform/RunCommand.c index 3fdd51f1b95..78c641a7793 100644 --- a/ta/ftpm/platform/RunCommand.c +++ b/ta/ftpm/platform/RunCommand.c @@ -87,4 +87,5 @@ _plat__Fail( ) { TEE_Panic(TEE_ERROR_BAD_STATE); -} \ No newline at end of file + while (true); /* Not reached */ +} From 6b902d4078b9dee5549e728f3fae530bcb94f6c6 Mon Sep 17 00:00:00 2001 From: Jens Wiklander Date: Tue, 24 Sep 2024 12:46:09 +0200 Subject: [PATCH 15/27] ftpm: fix conflicting types for _plat__NvMemoryWrite() Fix conflicting types for _plat__NvMemoryWrite() by adding the return type used in the declaration. _plat__NvMemoryWrite() is updated to always return TRUE since that's the expectation of success in NvWrite in TPMCmd/tpm/src/subsystem/NvReserved.c in the reference implementation (ms-tpm-20-ref). Signed-off-by: Jens Wiklander --- ta/ftpm/platform/NVMem.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/ta/ftpm/platform/NVMem.c b/ta/ftpm/platform/NVMem.c index 23db9d07544..fad411b9dd4 100644 --- a/ta/ftpm/platform/NVMem.c +++ b/ta/ftpm/platform/NVMem.c @@ -556,7 +556,7 @@ _plat__MarkDirtyBlocks ( // NOTE: A useful optimization would be for this code to compare the current // contents of NV with the local copy and note the blocks that have changed. Then // only write those blocks when _plat__NvCommit() is called. -LIB_EXPORT void +LIB_EXPORT int _plat__NvMemoryWrite( unsigned int startOffset, // IN: write start unsigned int size, // IN: size of bytes to write @@ -568,6 +568,7 @@ _plat__NvMemoryWrite( _plat__MarkDirtyBlocks(startOffset, size); memcpy(&s_NV[startOffset], data, size); + return TRUE; } //***_plat__NvMemoryClear() From b0dfcf8df543e497c6be39d3500ee1c8ea428510 Mon Sep 17 00:00:00 2001 From: Jens Wiklander Date: Tue, 24 Sep 2024 12:50:09 +0200 Subject: [PATCH 16/27] ftpm: remove _plat__Signal_PowerOn() from fTPM.h Remove the mismatching _plat__Signal_PowerOn() prototype from fTPM.h. The real prototype is in ta/ftpm/platform/include/Platform_fp.h. Signed-off-by: Jens Wiklander --- ta/ftpm/include/fTPM.h | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/ta/ftpm/include/fTPM.h b/ta/ftpm/include/fTPM.h index 6d6b1a0ff97..1f834a91f56 100644 --- a/ta/ftpm/include/fTPM.h +++ b/ta/ftpm/include/fTPM.h @@ -86,7 +86,6 @@ extern int _plat__NVEnable(void *platParameter); extern int TPM_Manufacture(bool firstTime); extern bool _plat__NvNeedsManufacture(void); extern void _TPM_Init(void); -extern void _plat__Signal_PowerOn(void); extern void _plat__NVDisable(void); extern void _admin__SaveChipFlags(void); @@ -103,4 +102,4 @@ typedef union { } TPM_CHIP_STATE; extern TPM_CHIP_STATE g_chipFlags; -#endif /* FTPM_TA_H */ \ No newline at end of file +#endif /* FTPM_TA_H */ From d0dcb63456df689a72c947d90e761a3786cb224b Mon Sep 17 00:00:00 2001 From: Jens Wiklander Date: Tue, 24 Sep 2024 12:52:19 +0200 Subject: [PATCH 17/27] ftpm: remove TA_ALL_PARAM_TYPE() from fTPM.c Remove the redefinition of TA_ALL_PARAM_TYPE() from fTPM.c, it's originally defined in ta/ftpm/include/fTPM.h. Signed-off-by: Jens Wiklander --- ta/ftpm/fTPM.c | 2 -- 1 file changed, 2 deletions(-) diff --git a/ta/ftpm/fTPM.c b/ta/ftpm/fTPM.c index 65d44976c84..7f5a5080e0f 100644 --- a/ta/ftpm/fTPM.c +++ b/ta/ftpm/fTPM.c @@ -45,8 +45,6 @@ #include "fTPM.h" -#define TA_ALL_PARAM_TYPE(type) TEE_PARAM_TYPES(type, type, type, type) - // // Ensure we have only one active session // From d5f77af2e35925a676746b0da1aa98c22ac17815 Mon Sep 17 00:00:00 2001 From: Jens Wiklander Date: Tue, 24 Sep 2024 12:55:13 +0200 Subject: [PATCH 18/27] ftpm: move user_ta_header_defines.h to include Move user_ta_header_defines.h to the common include directory for fTPM. Signed-off-by: Jens Wiklander --- ta/ftpm/{ => include}/user_ta_header_defines.h | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename ta/ftpm/{ => include}/user_ta_header_defines.h (100%) diff --git a/ta/ftpm/user_ta_header_defines.h b/ta/ftpm/include/user_ta_header_defines.h similarity index 100% rename from ta/ftpm/user_ta_header_defines.h rename to ta/ftpm/include/user_ta_header_defines.h From 10a516e739742eb328783af939c17f0361c1ebe2 Mon Sep 17 00:00:00 2001 From: Jens Wiklander Date: Tue, 24 Sep 2024 12:57:30 +0200 Subject: [PATCH 19/27] ftpm: remove redundant to{upp,low}er() declarations lib/libutils/isoc/include/ctype.h already declares toupper() and tolower() so remove the redundant declarations from RuntimeSupport.h. Signed-off-by: Jens Wiklander --- ta/ftpm/reference/include/RuntimeSupport.h | 10 ---------- 1 file changed, 10 deletions(-) diff --git a/ta/ftpm/reference/include/RuntimeSupport.h b/ta/ftpm/reference/include/RuntimeSupport.h index b0a851ee029..692db47c68e 100644 --- a/ta/ftpm/reference/include/RuntimeSupport.h +++ b/ta/ftpm/reference/include/RuntimeSupport.h @@ -73,16 +73,6 @@ int strncasecmp(const char *str1, const char *str2, size_t n); #define XMEMCMP(str1,str2,n) memcmp((str1),(str2),(n)) #endif -#ifndef XTOUPPER -int toupper (int c); -#define XTOUPPER(str1) toupper((str1)) -#endif - -#ifndef XTOLOWER -int tolower (int c); -#define XTOLOWER(str1) tolower((str1)) -#endif - #undef WC_NO_HASHDRBG #define WC_NO_HASHDRBG From ab498ffe161e07519700161d5904a5486add3435 Mon Sep 17 00:00:00 2001 From: Jens Wiklander Date: Wed, 25 Sep 2024 15:36:50 +0200 Subject: [PATCH 20/27] ftpm: provide and use ftpm_ta.h Separate TA_FTPM_UUID and the command IDs into ftpm_ta.h. Update user_ta_header_defines.h to include ftpm_ta.h instead of the old fTPM.h to minimize the include file dependencies. Set Microsoft copyright year to 2018 based on git history in the reference source. Add missing SPDX-License-Identifier and Linaro copyright. Signed-off-by: Jens Wiklander --- ta/ftpm/include/fTPM.h | 70 ++++++++++++------------ ta/ftpm/include/ftpm_ta.h | 51 +++++++++++++++++ ta/ftpm/include/user_ta_header_defines.h | 57 ++++++++++--------- 3 files changed, 118 insertions(+), 60 deletions(-) create mode 100644 ta/ftpm/include/ftpm_ta.h diff --git a/ta/ftpm/include/fTPM.h b/ta/ftpm/include/fTPM.h index 1f834a91f56..58c7d9c0e33 100644 --- a/ta/ftpm/include/fTPM.h +++ b/ta/ftpm/include/fTPM.h @@ -1,50 +1,50 @@ +/* SPDX-License-Identifier: BSD-2-Clause */ +/* + * Copyright (c) 2024, Linaro Limited + */ + /* Microsoft Reference Implementation for TPM 2.0 * - * The copyright in this software is being made available under the BSD License, - * included below. This software may be subject to other third party and - * contributor rights, including patent rights, and no such rights are granted - * under this license. + * The copyright in this software is being made available under the BSD + * License, included below. This software may be subject to other third + * party and contributor rights, including patent rights, and no such + * rights are granted under this license. * - * Copyright (c) Microsoft Corporation + * Copyright (c) 2018 Microsoft Corporation * - * All rights reserved. + * All rights reserved. * - * BSD License + * BSD License * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: * - * Redistributions of source code must retain the above copyright notice, this list - * of conditions and the following disclaimer. + * Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. * - * 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. + * 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. * - * 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. + * 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 FTPM_TA_H -#define FTPM_TA_H +#ifndef FTPM_H +#define FTPM_H #include - -/* This UUID is generated with uuidgen */ -#define TA_FTPM_UUID { 0xBC50D971, 0xD4C9, 0x42C4, \ - {0x82, 0xCB, 0x34, 0x3F, 0xB7, 0xF3, 0x78, 0x96}} - -/* The TAFs ID implemented in this TA */ -#define TA_FTPM_SUBMIT_COMMAND (0) -#define TA_FTPM_EMULATE_PPI (1) +#include // // These must match values from reference/TPM/include/TpmProfile.h @@ -102,4 +102,4 @@ typedef union { } TPM_CHIP_STATE; extern TPM_CHIP_STATE g_chipFlags; -#endif /* FTPM_TA_H */ +#endif /* FTPM_H */ diff --git a/ta/ftpm/include/ftpm_ta.h b/ta/ftpm/include/ftpm_ta.h new file mode 100644 index 00000000000..1cb6be20c9b --- /dev/null +++ b/ta/ftpm/include/ftpm_ta.h @@ -0,0 +1,51 @@ +/* SPDX-License-Identifier: BSD-2-Clause */ +/* + * Copyright (c) 2024 Linaro Limited + * + * The copyright in this software is being made available under the BSD License, + * included below. This software may be subject to other third party and + * contributor rights, including patent rights, and no such rights are granted + * under this license. + * + * Copyright (c) 2018 Microsoft Corporation + * + * All rights reserved. + * + * BSD License + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 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. + * + * 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 FTPM_TA_H +#define FTPM_TA_H + +/* This UUID is generated with uuidgen */ +#define TA_FTPM_UUID { 0xBC50D971, 0xD4C9, 0x42C4, \ + {0x82, 0xCB, 0x34, 0x3F, 0xB7, 0xF3, 0x78, 0x96}} + +/* The TAFs ID implemented in this TA */ +#define TA_FTPM_SUBMIT_COMMAND (0) +#define TA_FTPM_EMULATE_PPI (1) + +#endif /*FTPM_TA_H*/ diff --git a/ta/ftpm/include/user_ta_header_defines.h b/ta/ftpm/include/user_ta_header_defines.h index 4c362360f3d..e3ef8b216f3 100644 --- a/ta/ftpm/include/user_ta_header_defines.h +++ b/ta/ftpm/include/user_ta_header_defines.h @@ -1,36 +1,43 @@ +/* SPDX-License-Identifier: BSD-2-Clause */ +/* + * Copyright (c) 2024, Linaro Limited + */ + /* Microsoft Reference Implementation for TPM 2.0 * - * The copyright in this software is being made available under the BSD License, - * included below. This software may be subject to other third party and - * contributor rights, including patent rights, and no such rights are granted - * under this license. + * The copyright in this software is being made available under the BSD + * License, included below. This software may be subject to other third + * party and contributor rights, including patent rights, and no such + * rights are granted under this license. * - * Copyright (c) Microsoft Corporation + * Copyright (c) 2018 Microsoft Corporation * - * All rights reserved. + * All rights reserved. * - * BSD License + * BSD License * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: * - * Redistributions of source code must retain the above copyright notice, this list - * of conditions and the following disclaimer. + * Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. * - * 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. + * 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. * - * 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. + * 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. */ /* @@ -40,7 +47,7 @@ #ifndef USER_TA_HEADER_DEFINES_H #define USER_TA_HEADER_DEFINES_H -#include +#include #define TA_UUID TA_FTPM_UUID From fee31fc400ffe572d0595050b8eae108632e80a8 Mon Sep 17 00:00:00 2001 From: Jens Wiklander Date: Wed, 25 Sep 2024 16:13:03 +0200 Subject: [PATCH 21/27] ftpm: remove TpmProfile.h Remove TpmProfile.h overriding the version in the reference source. The old TpmProfile.h included a few .h files not included in the reference TpmProfile.h, so add the missing includes the affected source files. Add SPDX-License-Identifier and add Linaro copyright for all modified files. Set Microsoft copyright year based on git history in the reference source. Signed-off-by: Jens Wiklander --- ta/ftpm/platform/AdminPPI.c | 55 +- ta/ftpm/platform/EPS.c | 55 +- ta/ftpm/platform/include/Admin.h | 71 +-- ta/ftpm/reference/include/TpmProfile.h | 813 ------------------------- ta/ftpm/tee/TpmToTEESym.c | 5 +- 5 files changed, 96 insertions(+), 903 deletions(-) delete mode 100644 ta/ftpm/reference/include/TpmProfile.h diff --git a/ta/ftpm/platform/AdminPPI.c b/ta/ftpm/platform/AdminPPI.c index 01d382d72a4..5dd0d984c32 100644 --- a/ta/ftpm/platform/AdminPPI.c +++ b/ta/ftpm/platform/AdminPPI.c @@ -1,41 +1,48 @@ +/* SPDX-License-Identifier: BSD-2-Clause */ +/* + * Copyright (c) 2024, Linaro Limited + */ /* Microsoft Reference Implementation for TPM 2.0 * - * The copyright in this software is being made available under the BSD License, - * included below. This software may be subject to other third party and - * contributor rights, including patent rights, and no such rights are granted - * under this license. + * The copyright in this software is being made available under the BSD + * License, included below. This software may be subject to other third + * party and contributor rights, including patent rights, and no such + * rights are granted under this license. * - * Copyright (c) Microsoft Corporation + * Copyright (c) 2018 Microsoft Corporation * - * All rights reserved. + * All rights reserved. * - * BSD License + * BSD License * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: * - * Redistributions of source code must retain the above copyright notice, this list - * of conditions and the following disclaimer. + * Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. * - * 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. + * 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. * - * 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. + * 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. */ //**Introduction // This file contains the emulated Physical Presence Interface. +#include #include "assert.h" #include "Admin.h" #include "string.h" diff --git a/ta/ftpm/platform/EPS.c b/ta/ftpm/platform/EPS.c index 75d694d36c6..d3bc26905da 100644 --- a/ta/ftpm/platform/EPS.c +++ b/ta/ftpm/platform/EPS.c @@ -1,36 +1,42 @@ +/* SPDX-License-Identifier: BSD-2-Clause */ +/* + * Copyright (c) 2024, Linaro Limited + */ /* Microsoft Reference Implementation for TPM 2.0 * - * The copyright in this software is being made available under the BSD License, - * included below. This software may be subject to other third party and - * contributor rights, including patent rights, and no such rights are granted - * under this license. + * The copyright in this software is being made available under the BSD + * License, included below. This software may be subject to other third + * party and contributor rights, including patent rights, and no such + * rights are granted under this license. * - * Copyright (c) Microsoft Corporation + * Copyright (c) 2018-2023 Microsoft Corporation * - * All rights reserved. + * All rights reserved. * - * BSD License + * BSD License * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: * - * Redistributions of source code must retain the above copyright notice, this list - * of conditions and the following disclaimer. + * Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. * - * 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. + * 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. * - * 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. + * 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. */ // @@ -40,6 +46,7 @@ #include "TpmError.h" #include "Admin.h" +#include #include #include diff --git a/ta/ftpm/platform/include/Admin.h b/ta/ftpm/platform/include/Admin.h index 84efcaf7aa9..cb7e4d9b2b9 100644 --- a/ta/ftpm/platform/include/Admin.h +++ b/ta/ftpm/platform/include/Admin.h @@ -1,36 +1,42 @@ +/* SPDX-License-Identifier: BSD-2-Clause */ +/* + * Copyright (c) 2024, Linaro Limited + */ /* Microsoft Reference Implementation for TPM 2.0 * - * The copyright in this software is being made available under the BSD License, - * included below. This software may be subject to other third party and - * contributor rights, including patent rights, and no such rights are granted - * under this license. + * The copyright in this software is being made available under the BSD + * License, included below. This software may be subject to other third + * party and contributor rights, including patent rights, and no such + * rights are granted under this license. * - * Copyright (c) Microsoft Corporation + * Copyright (c) 2018 Microsoft Corporation * - * All rights reserved. + * All rights reserved. * - * BSD License + * BSD License * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: * - * Redistributions of source code must retain the above copyright notice, this list - * of conditions and the following disclaimer. + * Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. * - * 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. + * 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. * - * 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. + * 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. */ //**Introduction @@ -48,26 +54,13 @@ #include "TpmProfile.h" #include "TpmSal.h" #include "TpmError.h" +#include "GpMacros.h" // Parameter reference and types from ref impl headers #ifndef UNREFERENCED_PARAMETER #define UNREFERENCED_PARAMETER(a) do { (void)(a); } while (0) #endif -#define FAIL(errorCode) (TpmFail(__FUNCTION__, __LINE__, errorCode)) - -#if defined(EMPTY_ASSERT) -#define pAssert(a) ((void)0) -#else -#define pAssert(a) \ - do { \ - if (!(a)) { \ - EMSG("## ASSERT:" #a "##\n"); \ - FAIL(FATAL_ERROR_PARAMETER); \ - } \ - } while (0) -#endif - #if defined(__GNUC__) typedef unsigned char UCHAR; typedef unsigned char * PUCHAR; @@ -89,8 +82,6 @@ typedef UINT32 TPM_RC; #define TPM_RC_SUCCESS (TPM_RC)(0x000) #define RC_VER1 (TPM_RC)(0x100) #define TPM_RC_BAD_TAG (TPM_RC)(0x01E) -#define TPM_RC_FAILURE (TPM_RC)(RC_VER1+0x001) -#define TPM_RC_COMMAND_SIZE (TPM_RC)(RC_VER1+0x042) // Chip flags typedef union { diff --git a/ta/ftpm/reference/include/TpmProfile.h b/ta/ftpm/reference/include/TpmProfile.h deleted file mode 100644 index bd83749bf63..00000000000 --- a/ta/ftpm/reference/include/TpmProfile.h +++ /dev/null @@ -1,813 +0,0 @@ -/* SPDX-License-Identifier: BSD-2-Clause */ -/********************************************************************** - * Copyright (c) 2024, Siemens AG - * All rights reserved. - * - * Based on the original code by Microsoft. Modified to support using - * TEE functions to provide cryptographic functionality. - * - * Portions Copyright Microsoft Corporation, see below for details: - * - * The copyright in this software is being made available under the BSD License, - * included below. This software may be subject to other third party and - * contributor rights, including patent rights, and no such rights are granted - * under this license. - * - * Copyright (c) Microsoft Corporation - * - * All rights reserved. - * - * BSD License - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * Redistributions of source code must retain the above copyright notice, this list - * of conditions and the following disclaimer. - * - * 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. - * - * 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. - */ -/*(Auto-generated) - * Created by TpmStructures; Version 4.4 Mar 26, 2019 - * Date: Mar 4, 2020 Time: 02:36:43PM - */ - -#ifndef _TPM_PROFILE_H_ -#define _TPM_PROFILE_H_ - -#include "RuntimeSupport.h" - -#include -#include -#include - -#undef MAX -#define MAX(a, b) ((a) > (b) ? (a) : (b)) - -#undef MIN -#define MIN(a, b) ((a) < (b) ? (a) : (b)) - -// Table 2:4 - Defines for Logic Values -#undef TRUE -#define TRUE 1 -#undef FALSE -#define FALSE 0 -#undef YES -#define YES 1 -#undef NO -#define NO 0 -#undef SET -#define SET 1 -#undef CLEAR -#define CLEAR 0 - -// Table 0:1 - Defines for Processor Values -#ifndef BIG_ENDIAN_TPM -#define BIG_ENDIAN_TPM NO -#endif -#ifndef LITTLE_ENDIAN_TPM -#define LITTLE_ENDIAN_TPM !BIG_ENDIAN_TPM -#endif -#ifndef MOST_SIGNIFICANT_BIT_0 -#define MOST_SIGNIFICANT_BIT_0 NO -#endif -#ifndef LEAST_SIGNIFICANT_BIT_0 -#define LEAST_SIGNIFICANT_BIT_0 !MOST_SIGNIFICANT_BIT_0 -#endif -#ifndef AUTO_ALIGN -#define AUTO_ALIGN NO -#endif - -// Table 0:4 - Defines for Implemented Curves -#ifndef ECC_NIST_P192 -#define ECC_NIST_P192 NO -#endif -#ifndef ECC_NIST_P224 -#define ECC_NIST_P224 NO -#endif -#ifndef ECC_NIST_P256 -#define ECC_NIST_P256 YES -#endif -#ifndef ECC_NIST_P384 -#define ECC_NIST_P384 YES -#endif -#ifndef ECC_NIST_P521 -#define ECC_NIST_P521 NO -#endif -#ifndef ECC_BN_P256 -#define ECC_BN_P256 YES -#endif -#ifndef ECC_BN_P638 -#define ECC_BN_P638 NO -#endif -#ifndef ECC_SM2_P256 -#define ECC_SM2_P256 YES -#endif - -// Table 0:6 - Defines for Implemented ACT -#ifndef RH_ACT_0 -#define RH_ACT_0 YES -#endif -#ifndef RH_ACT_1 -#define RH_ACT_1 NO -#endif -#ifndef RH_ACT_A -#define RH_ACT_A YES -#endif - -// Table 0:7 - Defines for Implementation Values -#if defined(USE_WOLFCRYPT) -#define HASH_LIB Wolf -#define SYM_LIB Wolf -#define MATH_LIB Wolf -#elif defined(USE_TEE) -#define HASH_LIB TEE -#define SYM_LIB TEE -#define MATH_LIB TEE -#else -#define HASH_LIB Ossl -#define SYM_LIB Ossl -#define MATH_LIB Ossl -#endif - -typedef UINT32 TPM_CC; - -// Table 0:7 - Defines for Implementation Values -#ifndef FIELD_UPGRADE_IMPLEMENTED -#define FIELD_UPGRADE_IMPLEMENTED NO -#endif -#ifndef IMPLEMENTATION_PCR -#define IMPLEMENTATION_PCR 24 -#endif -#ifndef PLATFORM_PCR -#define PLATFORM_PCR 24 -#endif -#ifndef DRTM_PCR -#define DRTM_PCR 17 -#endif -#ifndef HCRTM_PCR -#define HCRTM_PCR 0 -#endif -#ifndef NUM_LOCALITIES -#define NUM_LOCALITIES 5 -#endif -#ifndef MAX_HANDLE_NUM -#define MAX_HANDLE_NUM 3 -#endif -#ifndef MAX_ACTIVE_SESSIONS -#define MAX_ACTIVE_SESSIONS 64 -#endif -#ifndef CONTEXT_SLOT -#define CONTEXT_SLOT UINT16 -#endif -#ifndef MAX_LOADED_SESSIONS -#define MAX_LOADED_SESSIONS 3 -#endif -#ifndef MAX_SESSION_NUM -#define MAX_SESSION_NUM 3 -#endif -#ifndef MAX_LOADED_OBJECTS -#define MAX_LOADED_OBJECTS 3 -#endif -#ifndef MIN_EVICT_OBJECTS -#define MIN_EVICT_OBJECTS 2 -#endif -#ifndef NUM_POLICY_PCR_GROUP -#define NUM_POLICY_PCR_GROUP 1 -#endif -#ifndef NUM_AUTHVALUE_PCR_GROUP -#define NUM_AUTHVALUE_PCR_GROUP 1 -#endif -#ifndef MAX_CONTEXT_SIZE -#define MAX_CONTEXT_SIZE 1344 -#endif -#ifndef MAX_DIGEST_BUFFER -#define MAX_DIGEST_BUFFER 1024 -#endif -#ifndef MAX_NV_INDEX_SIZE -#define MAX_NV_INDEX_SIZE 2048 -#endif -#ifndef MAX_NV_BUFFER_SIZE -#define MAX_NV_BUFFER_SIZE 1024 -#endif -#ifndef MAX_CAP_BUFFER -#define MAX_CAP_BUFFER 1024 -#endif -#ifndef NV_MEMORY_SIZE -#define NV_MEMORY_SIZE 16384 -#endif -#ifndef MIN_COUNTER_INDICES -#define MIN_COUNTER_INDICES 8 -#endif -#ifndef NUM_STATIC_PCR -#define NUM_STATIC_PCR 16 -#endif -#ifndef MAX_ALG_LIST_SIZE -#define MAX_ALG_LIST_SIZE 64 -#endif -#ifndef PRIMARY_SEED_SIZE -#define PRIMARY_SEED_SIZE 32 -#endif -#ifndef CONTEXT_ENCRYPT_ALGORITHM -#define CONTEXT_ENCRYPT_ALGORITHM AES -#endif -#ifndef NV_CLOCK_UPDATE_INTERVAL -#define NV_CLOCK_UPDATE_INTERVAL 12 -#endif -#ifndef NUM_POLICY_PCR -#define NUM_POLICY_PCR 1 -#endif -#ifndef MAX_COMMAND_SIZE -#define MAX_COMMAND_SIZE 4096 -#endif -#ifndef MAX_RESPONSE_SIZE -#define MAX_RESPONSE_SIZE 4096 -#endif -#ifndef ORDERLY_BITS -#define ORDERLY_BITS 8 -#endif -#ifndef MAX_SYM_DATA -#define MAX_SYM_DATA 128 -#endif -#ifndef MAX_RNG_ENTROPY_SIZE -#define MAX_RNG_ENTROPY_SIZE 64 -#endif -#ifndef RAM_INDEX_SPACE -#define RAM_INDEX_SPACE 512 -#endif -#ifndef RSA_DEFAULT_PUBLIC_EXPONENT -#define RSA_DEFAULT_PUBLIC_EXPONENT 0x00010001 -#endif -#ifndef ENABLE_PCR_NO_INCREMENT -#define ENABLE_PCR_NO_INCREMENT YES -#endif -#ifndef CRT_FORMAT_RSA -#define CRT_FORMAT_RSA YES -#endif -#ifndef VENDOR_COMMAND_COUNT -#define VENDOR_COMMAND_COUNT 0 -#endif -#ifndef MAX_VENDOR_BUFFER_SIZE -#define MAX_VENDOR_BUFFER_SIZE 1024 -#endif -#ifndef SIZE_OF_X509_SERIAL_NUMBER -#define SIZE_OF_X509_SERIAL_NUMBER 20 -#endif -#ifndef PRIVATE_VENDOR_SPECIFIC_BYTES -#define PRIVATE_VENDOR_SPECIFIC_BYTES RSA_PRIVATE_SIZE -#endif - -// Table 0:2 - Defines for Implemented Algorithms -#ifndef ALG_AES -#define ALG_AES ALG_YES -#endif -#ifndef ALG_CAMELLIA -#define ALG_CAMELLIA ALG_NO -#endif -#ifndef ALG_CBC -#define ALG_CBC ALG_YES -#endif -#ifndef ALG_CFB -#define ALG_CFB ALG_YES -#endif -#ifndef ALG_CMAC -#define ALG_CMAC ALG_YES -#endif -#ifndef ALG_CTR -#define ALG_CTR ALG_YES -#endif -#ifndef ALG_ECB -#define ALG_ECB ALG_YES -#endif -#ifndef ALG_ECC -#define ALG_ECC ALG_YES -#endif -#ifndef ALG_ECDAA -#define ALG_ECDAA (ALG_YES && ALG_ECC) -#endif -#ifndef ALG_ECDH -#define ALG_ECDH (ALG_YES && ALG_ECC) -#endif -#ifndef ALG_ECDSA -#define ALG_ECDSA (ALG_YES && ALG_ECC) -#endif -#ifndef ALG_ECMQV -#define ALG_ECMQV (ALG_NO && ALG_ECC) -#endif -#ifndef ALG_ECSCHNORR -#define ALG_ECSCHNORR (ALG_YES && ALG_ECC) -#endif -#ifndef ALG_HMAC -#define ALG_HMAC ALG_YES -#endif -#ifndef ALG_KDF1_SP800_108 -#define ALG_KDF1_SP800_108 ALG_YES -#endif -#ifndef ALG_KDF1_SP800_56A -#define ALG_KDF1_SP800_56A (ALG_YES && ALG_ECC) -#endif -#ifndef ALG_KDF2 -#define ALG_KDF2 ALG_NO -#endif -#ifndef ALG_KEYEDHASH -#define ALG_KEYEDHASH ALG_YES -#endif -#ifndef ALG_MGF1 -#define ALG_MGF1 ALG_YES -#endif -#ifndef ALG_OAEP -#define ALG_OAEP (ALG_YES && ALG_RSA) -#endif -#ifndef ALG_OFB -#define ALG_OFB ALG_YES -#endif -#ifndef ALG_RSA -#define ALG_RSA ALG_YES -#endif -#ifndef ALG_RSAES -#define ALG_RSAES (ALG_YES && ALG_RSA) -#endif -#ifndef ALG_RSAPSS -#define ALG_RSAPSS (ALG_YES && ALG_RSA) -#endif -#ifndef ALG_RSASSA -#define ALG_RSASSA (ALG_YES && ALG_RSA) -#endif -#ifndef ALG_SHA -#define ALG_SHA ALG_NO /* Not specified by vendor */ -#endif -#ifndef ALG_SHA1 -#define ALG_SHA1 ALG_YES -#endif -#ifndef ALG_SHA256 -#define ALG_SHA256 ALG_YES -#endif -#ifndef ALG_SHA384 -#define ALG_SHA384 ALG_YES -#endif -#ifndef ALG_SHA3_256 -#define ALG_SHA3_256 ALG_NO /* Not specified by vendor */ -#endif -#ifndef ALG_SHA3_384 -#define ALG_SHA3_384 ALG_NO /* Not specified by vendor */ -#endif -#ifndef ALG_SHA3_512 -#define ALG_SHA3_512 ALG_NO /* Not specified by vendor */ -#endif -#ifndef ALG_SHA512 -#define ALG_SHA512 ALG_NO -#endif -#ifndef ALG_SM2 -#define ALG_SM2 (ALG_NO && ALG_ECC) -#endif -#ifndef ALG_SM3_256 -#define ALG_SM3_256 ALG_NO -#endif -#ifndef ALG_SM4 -#define ALG_SM4 ALG_NO -#endif -#ifndef ALG_SYMCIPHER -#define ALG_SYMCIPHER ALG_YES -#endif -#ifndef ALG_TDES -#define ALG_TDES ALG_NO -#endif -#ifndef ALG_XOR -#define ALG_XOR ALG_YES -#endif - -// Table 1:3 - Defines for RSA Asymmetric Cipher Algorithm Constants -#ifndef RSA_1024 -#define RSA_1024 (ALG_RSA && YES) -#endif -#ifndef RSA_2048 -#define RSA_2048 (ALG_RSA && YES) -#endif -#ifndef RSA_3072 -#define RSA_3072 (ALG_RSA && NO) -#endif -#ifndef RSA_4096 -#define RSA_4096 (ALG_RSA && NO) -#endif -#ifndef RSA_16384 -#define RSA_16384 (ALG_RSA && NO) -#endif - -// Table 1:21 - Defines for AES Symmetric Cipher Algorithm Constants -#ifndef AES_128 -#define AES_128 (ALG_AES && YES) -#endif -#ifndef AES_192 -#define AES_192 (ALG_AES && NO) -#endif -#ifndef AES_256 -#define AES_256 (ALG_AES && YES) -#endif - -// Table 1:22 - Defines for SM4 Symmetric Cipher Algorithm Constants -#ifndef SM4_128 -#define SM4_128 (ALG_SM4 && YES) -#endif - -// Table 1:23 - Defines for CAMELLIA Symmetric Cipher Algorithm Constants -#ifndef CAMELLIA_128 -#define CAMELLIA_128 (ALG_CAMELLIA && YES) -#endif -#ifndef CAMELLIA_192 -#define CAMELLIA_192 (ALG_CAMELLIA && NO) -#endif -#ifndef CAMELLIA_256 -#define CAMELLIA_256 (ALG_CAMELLIA && YES) -#endif - -// Table 1:24 - Defines for TDES Symmetric Cipher Algorithm Constants -#ifndef TDES_128 -#define TDES_128 (ALG_TDES && YES) -#endif -#ifndef TDES_192 -#define TDES_192 (ALG_TDES && YES) -#endif - -// Table 0:5 - Defines for Implemented Commands -#ifndef CC_ACT_SetTimeout -#define CC_ACT_SetTimeout CC_YES -#endif -#ifndef CC_AC_GetCapability -#define CC_AC_GetCapability CC_YES -#endif -#ifndef CC_AC_Send -#define CC_AC_Send CC_YES -#endif -#ifndef CC_ActivateCredential -#define CC_ActivateCredential CC_YES -#endif -#ifndef CC_Certify -#define CC_Certify CC_YES -#endif -#ifndef CC_CertifyCreation -#define CC_CertifyCreation CC_YES -#endif -#ifndef CC_CertifyX509 -#define CC_CertifyX509 CC_YES -#endif -#ifndef CC_ChangeEPS -#define CC_ChangeEPS CC_YES -#endif -#ifndef CC_ChangePPS -#define CC_ChangePPS CC_YES -#endif -#ifndef CC_Clear -#define CC_Clear CC_YES -#endif -#ifndef CC_ClearControl -#define CC_ClearControl CC_YES -#endif -#ifndef CC_ClockRateAdjust -#define CC_ClockRateAdjust CC_YES -#endif -#ifndef CC_ClockSet -#define CC_ClockSet CC_YES -#endif -#ifndef CC_Commit -#define CC_Commit (CC_YES && ALG_ECC) -#endif -#ifndef CC_ContextLoad -#define CC_ContextLoad CC_YES -#endif -#ifndef CC_ContextSave -#define CC_ContextSave CC_YES -#endif -#ifndef CC_Create -#define CC_Create CC_YES -#endif -#ifndef CC_CreateLoaded -#define CC_CreateLoaded CC_YES -#endif -#ifndef CC_CreatePrimary -#define CC_CreatePrimary CC_YES -#endif -#ifndef CC_DictionaryAttackLockReset -#define CC_DictionaryAttackLockReset CC_YES -#endif -#ifndef CC_DictionaryAttackParameters -#define CC_DictionaryAttackParameters CC_YES -#endif -#ifndef CC_Duplicate -#define CC_Duplicate CC_YES -#endif -#ifndef CC_ECC_Decrypt -#define CC_ECC_Decrypt (CC_YES && ALG_ECC) -#endif -#ifndef CC_ECC_Encrypt -#define CC_ECC_Encrypt (CC_YES && ALG_ECC) -#endif -#ifndef CC_ECC_Parameters -#define CC_ECC_Parameters (CC_YES && ALG_ECC) -#endif -#ifndef CC_ECDH_KeyGen -#define CC_ECDH_KeyGen (CC_YES && ALG_ECC) -#endif -#ifndef CC_ECDH_ZGen -#define CC_ECDH_ZGen (CC_YES && ALG_ECC) -#endif -#ifndef CC_EC_Ephemeral -#define CC_EC_Ephemeral (CC_YES && ALG_ECC) -#endif -#ifndef CC_EncryptDecrypt -#define CC_EncryptDecrypt CC_YES -#endif -#ifndef CC_EncryptDecrypt2 -#define CC_EncryptDecrypt2 CC_YES -#endif -#ifndef CC_EventSequenceComplete -#define CC_EventSequenceComplete CC_YES -#endif -#ifndef CC_EvictControl -#define CC_EvictControl CC_YES -#endif -#ifndef CC_FieldUpgradeData -#define CC_FieldUpgradeData CC_NO -#endif -#ifndef CC_FieldUpgradeStart -#define CC_FieldUpgradeStart CC_NO -#endif -#ifndef CC_FirmwareRead -#define CC_FirmwareRead CC_NO -#endif -#ifndef CC_FlushContext -#define CC_FlushContext CC_YES -#endif -#ifndef CC_GetCapability -#define CC_GetCapability CC_YES -#endif -#ifndef CC_GetCommandAuditDigest -#define CC_GetCommandAuditDigest CC_YES -#endif -#ifndef CC_GetRandom -#define CC_GetRandom CC_YES -#endif -#ifndef CC_GetSessionAuditDigest -#define CC_GetSessionAuditDigest CC_YES -#endif -#ifndef CC_GetTestResult -#define CC_GetTestResult CC_YES -#endif -#ifndef CC_GetTime -#define CC_GetTime CC_YES -#endif -#ifndef CC_HMAC -#define CC_HMAC (CC_YES && !ALG_CMAC) -#endif -#ifndef CC_HMAC_Start -#define CC_HMAC_Start (CC_YES && !ALG_CMAC) -#endif -#ifndef CC_Hash -#define CC_Hash CC_YES -#endif -#ifndef CC_HashSequenceStart -#define CC_HashSequenceStart CC_YES -#endif -#ifndef CC_HierarchyChangeAuth -#define CC_HierarchyChangeAuth CC_YES -#endif -#ifndef CC_HierarchyControl -#define CC_HierarchyControl CC_YES -#endif -#ifndef CC_Import -#define CC_Import CC_YES -#endif -#ifndef CC_IncrementalSelfTest -#define CC_IncrementalSelfTest CC_YES -#endif -#ifndef CC_Load -#define CC_Load CC_YES -#endif -#ifndef CC_LoadExternal -#define CC_LoadExternal CC_YES -#endif -#ifndef CC_MAC -#define CC_MAC (CC_YES && ALG_CMAC) -#endif -#ifndef CC_MAC_Start -#define CC_MAC_Start (CC_YES && ALG_CMAC) -#endif -#ifndef CC_MakeCredential -#define CC_MakeCredential CC_YES -#endif -#ifndef CC_NV_Certify -#define CC_NV_Certify CC_YES -#endif -#ifndef CC_NV_ChangeAuth -#define CC_NV_ChangeAuth CC_YES -#endif -#ifndef CC_NV_DefineSpace -#define CC_NV_DefineSpace CC_YES -#endif -#ifndef CC_NV_Extend -#define CC_NV_Extend CC_YES -#endif -#ifndef CC_NV_GlobalWriteLock -#define CC_NV_GlobalWriteLock CC_YES -#endif -#ifndef CC_NV_Increment -#define CC_NV_Increment CC_YES -#endif -#ifndef CC_NV_Read -#define CC_NV_Read CC_YES -#endif -#ifndef CC_NV_ReadLock -#define CC_NV_ReadLock CC_YES -#endif -#ifndef CC_NV_ReadPublic -#define CC_NV_ReadPublic CC_YES -#endif -#ifndef CC_NV_SetBits -#define CC_NV_SetBits CC_YES -#endif -#ifndef CC_NV_UndefineSpace -#define CC_NV_UndefineSpace CC_YES -#endif -#ifndef CC_NV_UndefineSpaceSpecial -#define CC_NV_UndefineSpaceSpecial CC_YES -#endif -#ifndef CC_NV_Write -#define CC_NV_Write CC_YES -#endif -#ifndef CC_NV_WriteLock -#define CC_NV_WriteLock CC_YES -#endif -#ifndef CC_ObjectChangeAuth -#define CC_ObjectChangeAuth CC_YES -#endif -#ifndef CC_PCR_Allocate -#define CC_PCR_Allocate CC_YES -#endif -#ifndef CC_PCR_Event -#define CC_PCR_Event CC_YES -#endif -#ifndef CC_PCR_Extend -#define CC_PCR_Extend CC_YES -#endif -#ifndef CC_PCR_Read -#define CC_PCR_Read CC_YES -#endif -#ifndef CC_PCR_Reset -#define CC_PCR_Reset CC_YES -#endif -#ifndef CC_PCR_SetAuthPolicy -#define CC_PCR_SetAuthPolicy CC_YES -#endif -#ifndef CC_PCR_SetAuthValue -#define CC_PCR_SetAuthValue CC_YES -#endif -#ifndef CC_PP_Commands -#define CC_PP_Commands CC_YES -#endif -#ifndef CC_PolicyAuthValue -#define CC_PolicyAuthValue CC_YES -#endif -#ifndef CC_PolicyAuthorize -#define CC_PolicyAuthorize CC_YES -#endif -#ifndef CC_PolicyAuthorizeNV -#define CC_PolicyAuthorizeNV CC_YES -#endif -#ifndef CC_PolicyCommandCode -#define CC_PolicyCommandCode CC_YES -#endif -#ifndef CC_PolicyCounterTimer -#define CC_PolicyCounterTimer CC_YES -#endif -#ifndef CC_PolicyCpHash -#define CC_PolicyCpHash CC_YES -#endif -#ifndef CC_PolicyDuplicationSelect -#define CC_PolicyDuplicationSelect CC_YES -#endif -#ifndef CC_PolicyGetDigest -#define CC_PolicyGetDigest CC_YES -#endif -#ifndef CC_PolicyLocality -#define CC_PolicyLocality CC_YES -#endif -#ifndef CC_PolicyNV -#define CC_PolicyNV CC_YES -#endif -#ifndef CC_PolicyNameHash -#define CC_PolicyNameHash CC_YES -#endif -#ifndef CC_PolicyNvWritten -#define CC_PolicyNvWritten CC_YES -#endif -#ifndef CC_PolicyOR -#define CC_PolicyOR CC_YES -#endif -#ifndef CC_PolicyPCR -#define CC_PolicyPCR CC_YES -#endif -#ifndef CC_PolicyPassword -#define CC_PolicyPassword CC_YES -#endif -#ifndef CC_PolicyPhysicalPresence -#define CC_PolicyPhysicalPresence CC_YES -#endif -#ifndef CC_PolicyRestart -#define CC_PolicyRestart CC_YES -#endif -#ifndef CC_PolicySecret -#define CC_PolicySecret CC_YES -#endif -#ifndef CC_PolicySigned -#define CC_PolicySigned CC_YES -#endif -#ifndef CC_PolicyTemplate -#define CC_PolicyTemplate CC_YES -#endif -#ifndef CC_PolicyTicket -#define CC_PolicyTicket CC_YES -#endif -#ifndef CC_Policy_AC_SendSelect -#define CC_Policy_AC_SendSelect CC_YES -#endif -#ifndef CC_Quote -#define CC_Quote CC_YES -#endif -#ifndef CC_RSA_Decrypt -#define CC_RSA_Decrypt (CC_YES && ALG_RSA) -#endif -#ifndef CC_RSA_Encrypt -#define CC_RSA_Encrypt (CC_YES && ALG_RSA) -#endif -#ifndef CC_ReadClock -#define CC_ReadClock CC_YES -#endif -#ifndef CC_ReadPublic -#define CC_ReadPublic CC_YES -#endif -#ifndef CC_Rewrap -#define CC_Rewrap CC_YES -#endif -#ifndef CC_SelfTest -#define CC_SelfTest CC_YES -#endif -#ifndef CC_SequenceComplete -#define CC_SequenceComplete CC_YES -#endif -#ifndef CC_SequenceUpdate -#define CC_SequenceUpdate CC_YES -#endif -#ifndef CC_SetAlgorithmSet -#define CC_SetAlgorithmSet CC_YES -#endif -#ifndef CC_SetCommandCodeAuditStatus -#define CC_SetCommandCodeAuditStatus CC_YES -#endif -#ifndef CC_SetPrimaryPolicy -#define CC_SetPrimaryPolicy CC_YES -#endif -#ifndef CC_Shutdown -#define CC_Shutdown CC_YES -#endif -#ifndef CC_Sign -#define CC_Sign CC_YES -#endif -#ifndef CC_StartAuthSession -#define CC_StartAuthSession CC_YES -#endif -#ifndef CC_Startup -#define CC_Startup CC_YES -#endif -#ifndef CC_StirRandom -#define CC_StirRandom CC_YES -#endif -#ifndef CC_TestParms -#define CC_TestParms CC_YES -#endif -#ifndef CC_Unseal -#define CC_Unseal CC_YES -#endif -#ifndef CC_Vendor_TCG_Test -#define CC_Vendor_TCG_Test CC_YES -#endif -#ifndef CC_VerifySignature -#define CC_VerifySignature CC_YES -#endif -#ifndef CC_ZGen_2Phase -#define CC_ZGen_2Phase (CC_YES && ALG_ECC) -#endif - - -#endif // _TPM_PROFILE_H_ diff --git a/ta/ftpm/tee/TpmToTEESym.c b/ta/ftpm/tee/TpmToTEESym.c index e92f867dd88..d688590f3dd 100644 --- a/ta/ftpm/tee/TpmToTEESym.c +++ b/ta/ftpm/tee/TpmToTEESym.c @@ -1,7 +1,8 @@ -/* SPDX-License-Identifier: BSD-2-Clause */ -/********************************************************************** +// SPDX-License-Identifier: BSD-2-Clause +/* * Copyright (c) 2024, Siemens AG * All rights reserved. + * Copyright (c) 2024, Linaro Limited */ #include "Tpm.h" From 052109c39d60d58a90ecc9ab786844a9facd262b Mon Sep 17 00:00:00 2001 From: Jens Wiklander Date: Tue, 24 Sep 2024 13:02:27 +0200 Subject: [PATCH 22/27] ftpm: update sub.mk to make it compile Updates the fTPM sub.mk file to make it compile the source files. Many warnings are disabled Signed-off-by: Jens Wiklander --- ta/ftpm/sub.mk | 306 ++++++++++++++++++++++++++++++++++++++++++------- 1 file changed, 262 insertions(+), 44 deletions(-) diff --git a/ta/ftpm/sub.mk b/ta/ftpm/sub.mk index 2d9ba2411e0..2bb893c809b 100644 --- a/ta/ftpm/sub.mk +++ b/ta/ftpm/sub.mk @@ -1,56 +1,72 @@ -WARNS := 0 -NOWERROR := 0 -CFG_TA_MEASURED_BOOT ?= n -CFG_TA_DEBUG ?= n -CFG_TEE_TA_LOG_LEVEL ?= 0 -CFG_TA_EVENT_LOG_SIZE ?= 1024 - -cflags-y += -DTHIRTY_TWO_BIT \ - -DCFG_TEE_TA_LOG_LEVEL=$(CFG_TEE_TA_LOG_LEVEL) \ - -D_ARM_ \ - -w \ - -Wno-strict-prototypes \ - -mcpu=$(TA_CPU) \ - -fstack-protector \ - -Wstack-protector - -ifeq ($(CFG_TA_MEASURED_BOOT),y) -cflags-y += -DEVENT_LOG_SIZE=$(CFG_TA_EVENT_LOG_SIZE) -cflags-y += -DMEASURED_BOOT -endif +# +# The fTPM needs to overwrite some of the header files used in the +# reference implementation. The search order GCC uses is dependent on the +# order the '-I/include/path' arguments are passed in. This is depended on +# the optee_os build system which makes it brittle. Force including these +# files here will make sure the correct files are used first. +# -ifeq ($(CFG_ARM64_ta_arm64),y) -cflags-y += -mstrict-align -else -cflags-y += -mno-unaligned-access -endif +cppflags-y += -include ta/ftpm/reference/include/VendorString.h +cppflags-y += -include ta/ftpm/platform/include/Platform.h +cppflags-y += -DHASH_LIB=MBEDTLS -DSYM_LIB=TEE -DMATH_LIB=TEE +cppflags-y += -DALG_CAMELLIA=ALG_NO -DALG_KDF2=ALG_NO +cppflags-y += -DALG_SM3_256=NO -DALG_SM4=YES +cppflags-y += -D_ARM_ -DFAIL_TRACE=NO +cppflags-y += -DGCC -DSIMULATION=NO -DVTPM +cppflags-y += -DRSA_INSTRUMENT=NO +cppflags-y += -DCERTIFYX509_DEBUG=NO ifeq ($(CFG_TA_DEBUG),y) -cflags-y += -DfTPMDebug=1 -cflags-y += -DDBG=1 -cflags-y += -O0 -cflags-y += -DDEBUG -cflags-y += -DTRACE_LEVEL=$(CFG_TEE_TA_LOG_LEVEL) +cppflags-y += -DCOMPILER_CHECKS=YES -DfTPMDebug -DRUNTIME_SIZE_CHECKS +cppflags-y += -DLIBRARY_COMPATIBILITY_CHECK +cppflags-y += -DTRACE_LEVEL=$(CFG_TEE_TA_LOG_LEVEL) else -cflags-y += -Os -cflags-y += -DNDEBUG +cppflags-y += -DCOMPILER_CHECKS=NO -DRUNTIME_SIZE_CHECKS=NO +cppflags-y += -DLIBRARY_COMPATIBILITY_CHECK=NO endif -# -# Link the required external code into the libraries folder. OP-TEE build -# does not work well when accessing anything below the root directory. Use -# symlinks to trick it. -# -all: create_lib_symlinks -clean: clean_lib_symlinks - -subdirs-y += lib - global-incdirs-y += include -global-incdirs-y += include/Wolf global-incdirs-y += reference/include global-incdirs-y += platform/include +global-incdirs_ext-y += $(CFG_MS_TPM_20_REF)/TPMCmd/tpm/include +global-incdirs_ext-y += $(CFG_MS_TPM_20_REF)/TPMCmd/tpm/include/prototypes +global-incdirs_ext-y += $(CFG_MS_TPM_20_REF)/TPMCmd/Platform/include + +cflags-y += -Wno-cast-align +cflags-y += -Wno-implicit-fallthrough +cflags-y += -Wno-cast-function-type +cflags-y += -Wno-suggest-attribute=noreturn +cflags-y += -Wno-switch-default +cflags-y += -Wno-redundant-decls +cflags-y += -Wno-strict-prototypes +cflags-y += -Wno-undef + +cflags-platform/NVMem.c-y += -Wno-shadow +cflags-platform/NVMem.c-y += -Wno-incompatible-pointer-types +cflags-platform/NVMem.c-y += -Wno-declaration-after-statement +cflags-platform/NVMem.c-y += -Wno-old-style-definition +cflags-platform/NVMem.c-y += -Wno-nested-externs +cflags-platform/NVMem.c-y += -Wno-implicit-function-declaration +cflags-platform/NVMem.c-y += -Wno-missing-declarations +cflags-platform/NVMem.c-y += -Wno-missing-prototypes +cflags-platform/NvAdmin.c-y += -Wno-old-style-definition +cflags-platform/NvAdmin.c-y += -Wno-nested-externs +cflags-platform/NvAdmin.c-y += -Wno-implicit-function-declaration +cflags-platform/NvAdmin.c-y += -Wno-missing-prototypes +cflags-platform/Clock.c-y += -Wno-unused-variable +cflags-fTPM.c-y += -Wno-nested-externs +cflags-fTPM.c-y += -Wno-implicit-function-declaration +cflags-platform/EPS.c-y += -Wno-nested-externs +cflags-platform/EPS.c-y += -Wno-implicit-function-declaration +cflags-platform/AdminPPI.c-y += -Wno-missing-declarations +cflags-platform/AdminPPI.c-y += -Wno-missing-prototypes +cflags-platform/AdminPPI.c-y += -Wno-unknown-pragmas +cflags-platform/PlatformACT.c-y += -Wno-missing-declarations +cflags-platform/PlatformACT.c-y += -Wno-missing-prototypes +cflags-platform/fTPM_helpers.c-y += -Wno-missing-declarations +cflags-platform/fTPM_helpers.c-y += -Wno-missing-prototypes + srcs-y += platform/AdminPPI.c srcs-y += platform/Cancel.c srcs-y += platform/Clock.c @@ -65,7 +81,6 @@ srcs-y += platform/RunCommand.c srcs-y += platform/Unique.c srcs-y += platform/EPS.c srcs-y += platform/PlatformACT.c -srcs-y += reference/RuntimeSupport.c srcs-y += platform/fTPM_helpers.c srcs-y += fTPM.c @@ -74,4 +89,207 @@ ifeq ($(CFG_TA_MEASURED_BOOT),y) # Support for Trusted Firmware Measured Boot. srcs-y += platform/fTPM_event_log.c srcs-y += platform/EventLogPrint.c +cppflags-y += -DEVENT_LOG_SIZE=$(CFG_TA_EVENT_LOG_SIZE) +cppflags-y += -DMEASURED_BOOT endif + + +srcs-y += tee/TpmToTEEMath.c +srcs-y += tee/TpmToTEESupport.c +srcs-y += tee/TpmToTEESym.c + +srcs_ext_base-y := $(CFG_MS_TPM_20_REF)/TPMCmd/tpm/src/ +srcs_ext-y += X509/X509_ECC.c +srcs_ext-y += X509/X509_RSA.c +srcs_ext-y += X509/TpmASN1.c +srcs_ext-y += X509/X509_spt.c +srcs_ext-y += command/Attestation/CertifyX509.c +srcs_ext-y += command/Attestation/GetCommandAuditDigest.c +srcs_ext-y += command/Attestation/GetSessionAuditDigest.c +srcs_ext-y += command/Attestation/Attest_spt.c +srcs_ext-y += command/Attestation/Quote.c +srcs_ext-y += command/Attestation/Certify.c +srcs_ext-y += command/Attestation/CertifyCreation.c +srcs_ext-y += command/Attestation/GetTime.c +srcs_ext-y += command/Random/GetRandom.c +srcs_ext-y += command/Random/StirRandom.c +srcs_ext-y += command/NVStorage/NV_WriteLock.c +srcs_ext-y += command/NVStorage/NV_ReadPublic.c +srcs_ext-y += command/NVStorage/NV_spt.c +srcs_ext-y += command/NVStorage/NV_Increment.c +srcs_ext-y += command/NVStorage/NV_ChangeAuth.c +srcs_ext-y += command/NVStorage/NV_UndefineSpaceSpecial.c +srcs_ext-y += command/NVStorage/NV_SetBits.c +srcs_ext-y += command/NVStorage/NV_Write.c +srcs_ext-y += command/NVStorage/NV_GlobalWriteLock.c +srcs_ext-y += command/NVStorage/NV_Read.c +srcs_ext-y += command/NVStorage/NV_Extend.c +srcs_ext-y += command/NVStorage/NV_Certify.c +srcs_ext-y += command/NVStorage/NV_ReadLock.c +srcs_ext-y += command/NVStorage/NV_DefineSpace.c +srcs_ext-y += command/NVStorage/NV_UndefineSpace.c +srcs_ext-y += command/HashHMAC/HashSequenceStart.c +srcs_ext-y += command/HashHMAC/SequenceUpdate.c +srcs_ext-y += command/HashHMAC/MAC_Start.c +srcs_ext-y += command/HashHMAC/EventSequenceComplete.c +srcs_ext-y += command/HashHMAC/HMAC_Start.c +srcs_ext-y += command/HashHMAC/SequenceComplete.c +srcs_ext-y += command/Vendor/Vendor_TCG_Test.c +srcs_ext-y += command/Ecdaa/Commit.c +srcs_ext-y += command/Startup/Startup.c +srcs_ext-y += command/Startup/Shutdown.c +srcs_ext-y += command/FieldUpgrade/FieldUpgradeData.c +srcs_ext-y += command/FieldUpgrade/FirmwareRead.c +srcs_ext-y += command/FieldUpgrade/FieldUpgradeStart.c +srcs_ext-y += command/Capability/TestParms.c +srcs_ext-y += command/Capability/GetCapability.c +srcs_ext-y += command/ClockTimer/ACT_spt.c +srcs_ext-y += command/ClockTimer/ClockRateAdjust.c +srcs_ext-y += command/ClockTimer/ACT_SetTimeout.c +srcs_ext-y += command/ClockTimer/ClockSet.c +srcs_ext-y += command/ClockTimer/ReadClock.c +srcs_ext-y += command/Session/PolicyRestart.c +srcs_ext-y += command/Session/StartAuthSession.c +srcs_ext-y += command/EA/PolicyDuplicationSelect.c +srcs_ext-y += command/EA/PolicyPCR.c +srcs_ext-y += command/EA/PolicySecret.c +srcs_ext-y += command/EA/PolicyTicket.c +srcs_ext-y += command/EA/PolicyTemplate.c +srcs_ext-y += command/EA/PolicyNV.c +srcs_ext-y += command/EA/PolicyGetDigest.c +srcs_ext-y += command/EA/PolicyCpHash.c +srcs_ext-y += command/EA/PolicyOR.c +srcs_ext-y += command/EA/Policy_spt.c +srcs_ext-y += command/EA/PolicyLocality.c +srcs_ext-y += command/EA/PolicyAuthorize.c +srcs_ext-y += command/EA/PolicyAuthorizeNV.c +srcs_ext-y += command/EA/PolicyPassword.c +srcs_ext-y += command/EA/PolicyCounterTimer.c +srcs_ext-y += command/EA/PolicyAuthValue.c +srcs_ext-y += command/EA/PolicySigned.c +srcs_ext-y += command/EA/PolicyNameHash.c +srcs_ext-y += command/EA/PolicyNvWritten.c +srcs_ext-y += command/EA/PolicyPhysicalPresence.c +srcs_ext-y += command/EA/PolicyCommandCode.c +srcs_ext-y += command/Hierarchy/ChangePPS.c +srcs_ext-y += command/Hierarchy/HierarchyControl.c +srcs_ext-y += command/Hierarchy/HierarchyChangeAuth.c +srcs_ext-y += command/Hierarchy/ChangeEPS.c +srcs_ext-y += command/Hierarchy/ClearControl.c +srcs_ext-y += command/Hierarchy/Clear.c +srcs_ext-y += command/Hierarchy/SetPrimaryPolicy.c +srcs_ext-y += command/Hierarchy/CreatePrimary.c +srcs_ext-y += command/CommandAudit/SetCommandCodeAuditStatus.c +srcs_ext-y += command/Object/Object_spt.c +srcs_ext-y += command/Object/ReadPublic.c +srcs_ext-y += command/Object/Load.c +srcs_ext-y += command/Object/LoadExternal.c +srcs_ext-y += command/Object/MakeCredential.c +srcs_ext-y += command/Object/Unseal.c +srcs_ext-y += command/Object/CreateLoaded.c +srcs_ext-y += command/Object/ObjectChangeAuth.c +srcs_ext-y += command/Object/ActivateCredential.c +srcs_ext-y += command/Object/Create.c +srcs_ext-y += command/AttachedComponent/AC_GetCapability.c +srcs_ext-y += command/AttachedComponent/AC_spt.c +srcs_ext-y += command/AttachedComponent/AC_Send.c +srcs_ext-y += command/AttachedComponent/Policy_AC_SendSelect.c +srcs_ext-y += command/Signature/VerifySignature.c +srcs_ext-y += command/Signature/Sign.c +srcs_ext-y += command/Duplication/Import.c +srcs_ext-y += command/Duplication/Rewrap.c +srcs_ext-y += command/Duplication/Duplicate.c +srcs_ext-y += command/Symmetric/EncryptDecrypt2.c +srcs_ext-y += command/Symmetric/EncryptDecrypt_spt.c +srcs_ext-y += command/Symmetric/HMAC.c +srcs_ext-y += command/Symmetric/Hash.c +srcs_ext-y += command/Symmetric/EncryptDecrypt.c +srcs_ext-y += command/Symmetric/MAC.c +srcs_ext-y += command/Context/ContextSave.c +srcs_ext-y += command/Context/FlushContext.c +srcs_ext-y += command/Context/Context_spt.c +srcs_ext-y += command/Context/ContextLoad.c +srcs_ext-y += command/Context/EvictControl.c +srcs_ext-y += command/PCR/PCR_Reset.c +srcs_ext-y += command/PCR/PCR_Allocate.c +srcs_ext-y += command/PCR/PCR_Extend.c +srcs_ext-y += command/PCR/PCR_SetAuthValue.c +srcs_ext-y += command/PCR/PCR_Event.c +srcs_ext-y += command/PCR/PCR_SetAuthPolicy.c +srcs_ext-y += command/PCR/PCR_Read.c +srcs_ext-y += command/DA/DictionaryAttackParameters.c +srcs_ext-y += command/DA/DictionaryAttackLockReset.c +srcs_ext-y += command/Misc/PP_Commands.c +srcs_ext-y += command/Misc/SetAlgorithmSet.c +srcs_ext-y += command/Testing/GetTestResult.c +srcs_ext-y += command/Testing/SelfTest.c +srcs_ext-y += command/Testing/IncrementalSelfTest.c +srcs_ext-y += command/Asymmetric/ECC_Parameters.c +srcs_ext-y += command/Asymmetric/RSA_Encrypt.c +srcs_ext-y += command/Asymmetric/ECDH_ZGen.c +srcs_ext-y += command/Asymmetric/ECDH_KeyGen.c +srcs_ext-y += command/Asymmetric/ZGen_2Phase.c +srcs_ext-y += command/Asymmetric/ECC_Decrypt.c +srcs_ext-y += command/Asymmetric/RSA_Decrypt.c +srcs_ext-y += command/Asymmetric/EC_Ephemeral.c +srcs_ext-y += command/Asymmetric/ECC_Encrypt.c +srcs_ext-y += subsystem/DA.c +srcs_ext-y += subsystem/NvDynamic.c +srcs_ext-y += subsystem/Object.c +srcs_ext-y += subsystem/PP.c +srcs_ext-y += subsystem/Session.c +srcs_ext-y += subsystem/NvReserved.c +srcs_ext-y += subsystem/Hierarchy.c +srcs_ext-y += subsystem/Time.c +srcs_ext-y += subsystem/PCR.c +srcs_ext-y += subsystem/CommandAudit.c +srcs_ext-y += events/_TPM_Hash_Start.c +srcs_ext-y += events/_TPM_Init.c +srcs_ext-y += events/_TPM_Hash_Data.c +srcs_ext-y += events/_TPM_Hash_End.c +srcs_ext-y += crypt/CryptSmac.c +srcs_ext-y += crypt/CryptEccData.c +srcs_ext-y += crypt/CryptCmac.c +srcs_ext-y += crypt/BnMath.c +srcs_ext-y += crypt/CryptEccSignature.c +srcs_ext-y += crypt/AlgorithmTests.c +srcs_ext-y += crypt/CryptSelfTest.c +srcs_ext-y += crypt/Ticket.c +srcs_ext-y += crypt/CryptDes.c +srcs_ext-y += crypt/BnMemory.c +srcs_ext-y += crypt/CryptPrimeSieve.c +srcs_ext-y += crypt/CryptEccKeyExchange.c +srcs_ext-y += crypt/BnConvert.c +srcs_ext-y += crypt/CryptRand.c +srcs_ext-y += crypt/CryptEccMain.c +srcs_ext-y += crypt/CryptSym.c +srcs_ext-y += crypt/RsaKeyCache.c +srcs_ext-y += crypt/CryptUtil.c +srcs_ext-y += crypt/CryptEccCrypt.c +srcs_ext-y += crypt/CryptRsa.c +srcs_ext-y += crypt/CryptPrime.c +srcs_ext-y += crypt/PrimeData.c +srcs_ext-y += crypt/CryptHash.c +srcs_ext-y += support/Marshal.c +srcs_ext-y += support/MathOnByteBuffers.c +srcs_ext-y += support/TableDrivenMarshal.c +srcs_ext-y += support/PropertyCap.c +srcs_ext-y += support/Locality.c +srcs_ext-y += support/TableMarshalData.c +srcs_ext-y += support/Memory.c +srcs_ext-y += support/Response.c +srcs_ext-y += support/ResponseCodeProcessing.c +srcs_ext-y += support/Global.c +srcs_ext-y += support/Power.c +srcs_ext-y += support/AlgorithmCap.c +srcs_ext-y += support/CommandCodeAttributes.c +srcs_ext-y += support/Entity.c +srcs_ext-y += support/Handle.c +srcs_ext-y += support/TpmFail.c +srcs_ext-y += support/TpmSizeChecks.c +srcs_ext-y += support/Manufacture.c +srcs_ext-y += support/IoBuffers.c +srcs_ext-y += support/Bits.c +srcs_ext-y += main/SessionProcess.c +srcs_ext-y += main/CommandDispatcher.c +srcs_ext-y += main/ExecCommand.c From d6bdcf5f5139be680c27d29164124e1b89eaa90e Mon Sep 17 00:00:00 2001 From: Jens Wiklander Date: Tue, 24 Sep 2024 13:04:15 +0200 Subject: [PATCH 23/27] ftpm: remove unused RuntimeSupport.c Remove the unused file RuntimeSupport.c. Signed-off-by: Jens Wiklander --- ta/ftpm/reference/RuntimeSupport.c | 84 ------------------------------ 1 file changed, 84 deletions(-) delete mode 100644 ta/ftpm/reference/RuntimeSupport.c diff --git a/ta/ftpm/reference/RuntimeSupport.c b/ta/ftpm/reference/RuntimeSupport.c deleted file mode 100644 index 0998f050834..00000000000 --- a/ta/ftpm/reference/RuntimeSupport.c +++ /dev/null @@ -1,84 +0,0 @@ -/* Microsoft Reference Implementation for TPM 2.0 - * - * The copyright in this software is being made available under the BSD License, - * included below. This software may be subject to other third party and - * contributor rights, including patent rights, and no such rights are granted - * under this license. - * - * Copyright (c) Microsoft Corporation - * - * All rights reserved. - * - * BSD License - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * Redistributions of source code must retain the above copyright notice, this list - * of conditions and the following disclaimer. - * - * 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. - * - * 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 - -/** - * Implementation of tolower() commonly found in ctype.h - * Returns an ASCII character, changing to lowercase if the character is - * in the range 'A'-'Z'. - */ - -int tolower (int c) -{ - if(c >= 'A' && c <= 'Z') - { - c -= ('A' - 'a'); - } - return c; -} - -int toupper (int c) -{ - if(c >= 'a' && c <= 'z') - { - c += ('A' - 'a'); - } - return c; -} - -int strncasecmp(const char *str1, const char *str2, size_t n) -{ - size_t i = 0; - for(i = 0; i < n && str1[i] && str2[i]; i++) - { - char delta = tolower(str1[i]) - tolower(str2[i]); - if (delta != 0) - { - return delta; - } - } - return 0; -} - -#ifdef CUSTOM_RAND_GENERATE_BLOCK -#include -int wolfRand(unsigned char* output, unsigned int sz) -{ - TEE_GenerateRandom((void *)output, (uint32_t)sz); - - return 0; -} -#endif \ No newline at end of file From 85d181929f07e7409d7a0ee158128dcdd36fa4a7 Mon Sep 17 00:00:00 2001 From: Jens Wiklander Date: Thu, 19 Sep 2024 17:06:20 +0200 Subject: [PATCH 24/27] ftpm: remove unused wolfssl crypto wrappers Remove the now unused wolfssl crypto wrapper. Signed-off-by: Jens Wiklander --- ta/ftpm/include/Wolf/TpmToWolfHash.h | 199 --------------------------- ta/ftpm/include/Wolf/TpmToWolfMath.h | 91 ------------ ta/ftpm/include/Wolf/TpmToWolfSym.h | 120 ---------------- ta/ftpm/include/Wolf/user_settings.h | 108 --------------- 4 files changed, 518 deletions(-) delete mode 100644 ta/ftpm/include/Wolf/TpmToWolfHash.h delete mode 100644 ta/ftpm/include/Wolf/TpmToWolfMath.h delete mode 100644 ta/ftpm/include/Wolf/TpmToWolfSym.h delete mode 100644 ta/ftpm/include/Wolf/user_settings.h diff --git a/ta/ftpm/include/Wolf/TpmToWolfHash.h b/ta/ftpm/include/Wolf/TpmToWolfHash.h deleted file mode 100644 index 4ce03528dd4..00000000000 --- a/ta/ftpm/include/Wolf/TpmToWolfHash.h +++ /dev/null @@ -1,199 +0,0 @@ -/* Microsoft Reference Implementation for TPM 2.0 - * - * The copyright in this software is being made available under the BSD License, - * included below. This software may be subject to other third party and - * contributor rights, including patent rights, and no such rights are granted - * under this license. - * - * Copyright (c) Microsoft Corporation - * - * All rights reserved. - * - * BSD License - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * Redistributions of source code must retain the above copyright notice, this list - * of conditions and the following disclaimer. - * - * 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. - * - * 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. - */ - -//** Introduction -// -// This header file is used to 'splice' the wolfcrypt hash code into the TPM code. -// -#ifndef HASH_LIB_DEFINED -#define HASH_LIB_DEFINED - -#define HASH_LIB_WOLF - -#define HASH_ALIGNMENT RADIX_BYTES - -#ifndef WOLFSSL_USER_SETTINGS -#define WOLFSSL_USER_SETTINGS -#endif - -#if ALG_SHA384 || ALG_SHA512 -#define WOLFSSL_SHA512 -#endif - -#if ALG_SM3_256 -#undef ALG_SM3_256 -#define ALG_SM3_256 ALG_NO -//#error "SM3 is not available" -#endif - -#include -#include -#include - - -//*************************************************************** -//** Links to the wolfcrypt HASH code -//*************************************************************** - -// Redefine the internal name used for each of the hash state structures to the -// name used by the library. -// These defines need to be known in all parts of the TPM so that the structure -// sizes can be properly computed when needed. - -#define tpmHashStateSHA1_t wc_Sha -#define tpmHashStateSHA256_t wc_Sha256 -#define tpmHashStateSHA384_t wc_Sha512 -#define tpmHashStateSHA512_t wc_Sha512 - -#if ALG_SM3 -# error "The version of WolfCrypt used by this code does not support SM3" -#endif - -// The defines below are only needed when compiling CryptHash.c or CryptSmac.c. -// This isolation is primarily to avoid name space collision. However, if there -// is a real collision, it will likely show up when the linker tries to put things -// together. - -#ifdef _CRYPT_HASH_C_ - -typedef BYTE *PBYTE; -typedef const BYTE *PCBYTE; - -// Define the interface between CryptHash.c to the functions provided by the -// library. For each method, define the calling parameters of the method and then -// define how the method is invoked in CryptHash.c. -// -// All hashes are required to have the same calling sequence. If they don't, create -// a simple adaptation function that converts from the "standard" form of the call -// to the form used by the specific hash (and then send a nasty letter to the -// person who wrote the hash function for the library). -// -// The macro that calls the method also defines how the -// parameters get swizzled between the default form (in CryptHash.c)and the -// library form. -// -// Initialize the hash context -#define HASH_START_METHOD_DEF void (HASH_START_METHOD)(PANY_HASH_STATE state) -#define HASH_START(hashState) \ - ((hashState)->def->method.start)(&(hashState)->state); - -// Add data to the hash -#define HASH_DATA_METHOD_DEF \ - void (HASH_DATA_METHOD)(PANY_HASH_STATE state, \ - PCBYTE buffer, \ - size_t size) -#define HASH_DATA(hashState, dInSize, dIn) \ - ((hashState)->def->method.data)(&(hashState)->state, dIn, dInSize) - -// Finalize the hash and get the digest -#define HASH_END_METHOD_DEF \ - void (HASH_END_METHOD)(PANY_HASH_STATE state, BYTE *buffer) -#define HASH_END(hashState, buffer) \ - ((hashState)->def->method.end)(&(hashState)->state, buffer) - -// Copy the hash context -// Note: For import, export, and copy, memcpy() is used since there is no -// reformatting necessary between the internal and external forms. -#define HASH_STATE_COPY_METHOD_DEF \ - void (HASH_STATE_COPY_METHOD)(PANY_HASH_STATE to, \ - PCANY_HASH_STATE from, \ - size_t size) -#define HASH_STATE_COPY(hashStateOut, hashStateIn) \ - ((hashStateIn)->def->method.copy)(&(hashStateOut)->state, \ - &(hashStateIn)->state, \ - (hashStateIn)->def->contextSize) - -// Copy (with reformatting when necessary) an internal hash structure to an -// external blob -#define HASH_STATE_EXPORT_METHOD_DEF \ - void (HASH_STATE_EXPORT_METHOD)(BYTE *to, \ - PCANY_HASH_STATE from, \ - size_t size) -#define HASH_STATE_EXPORT(to, hashStateFrom) \ - ((hashStateFrom)->def->method.copyOut) \ - (&(((BYTE *)(to))[offsetof(HASH_STATE, state)]), \ - &(hashStateFrom)->state, \ - (hashStateFrom)->def->contextSize) - -// Copy from an external blob to an internal formate (with reformatting when -// necessary -#define HASH_STATE_IMPORT_METHOD_DEF \ - void (HASH_STATE_IMPORT_METHOD)(PANY_HASH_STATE to, \ - const BYTE *from, \ - size_t size) -#define HASH_STATE_IMPORT(hashStateTo, from) \ - ((hashStateTo)->def->method.copyIn) \ - (&(hashStateTo)->state, \ - &(((const BYTE *)(from))[offsetof(HASH_STATE, state)]),\ - (hashStateTo)->def->contextSize) - - -// Function aliases. The code in CryptHash.c uses the internal designation for the -// functions. These need to be translated to the function names of the library. -// Internal External -// Designation Designation -#define tpmHashStart_SHA1 wc_InitSha // external name of the - // initialization method -#define tpmHashData_SHA1 wc_ShaUpdate -#define tpmHashEnd_SHA1 wc_ShaFinal -#define tpmHashStateCopy_SHA1 memcpy -#define tpmHashStateExport_SHA1 memcpy -#define tpmHashStateImport_SHA1 memcpy -#define tpmHashStart_SHA256 wc_InitSha256 -#define tpmHashData_SHA256 wc_Sha256Update -#define tpmHashEnd_SHA256 wc_Sha256Final -#define tpmHashStateCopy_SHA256 memcpy -#define tpmHashStateExport_SHA256 memcpy -#define tpmHashStateImport_SHA256 memcpy -#define tpmHashStart_SHA384 wc_InitSha384 -#define tpmHashData_SHA384 wc_Sha384Update -#define tpmHashEnd_SHA384 wc_Sha384Final -#define tpmHashStateCopy_SHA384 memcpy -#define tpmHashStateExport_SHA384 memcpy -#define tpmHashStateImport_SHA384 memcpy -#define tpmHashStart_SHA512 wc_InitSha512 -#define tpmHashData_SHA512 wc_Sha512Update -#define tpmHashEnd_SHA512 wc_Sha512Final -#define tpmHashStateCopy_SHA512 memcpy -#define tpmHashStateExport_SHA512 memcpy -#define tpmHashStateImport_SHA512 memcpy - -#endif // _CRYPT_HASH_C_ - -#define LibHashInit() -// This definition would change if there were something to report -#define HashLibSimulationEnd() - -#endif // HASH_LIB_DEFINED diff --git a/ta/ftpm/include/Wolf/TpmToWolfMath.h b/ta/ftpm/include/Wolf/TpmToWolfMath.h deleted file mode 100644 index 1543499ba9c..00000000000 --- a/ta/ftpm/include/Wolf/TpmToWolfMath.h +++ /dev/null @@ -1,91 +0,0 @@ -/* Microsoft Reference Implementation for TPM 2.0 - * - * The copyright in this software is being made available under the BSD License, - * included below. This software may be subject to other third party and - * contributor rights, including patent rights, and no such rights are granted - * under this license. - * - * Copyright (c) Microsoft Corporation - * - * All rights reserved. - * - * BSD License - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * Redistributions of source code must retain the above copyright notice, this list - * of conditions and the following disclaimer. - * - * 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. - * - * 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. - */ - -//** Introduction -// This file contains the structure definitions used for ECC in the LibTomCrypt -// version of the code. These definitions would change, based on the library. -// The ECC-related structures that cross the TPM interface are defined -// in TpmTypes.h -// - -#ifndef MATH_LIB_DEFINED -#define MATH_LIB_DEFINED - -#define MATH_LIB_WOLF - -#if ALG_ECC -#define HAVE_ECC -#endif - -#include -#include - -#define MP_VAR(name) \ - mp_int _##name; \ - mp_int *name = MpInitialize(&_##name); - -// Allocate a mp_int and initialize with the values in a mp_int* initializer -#define MP_INITIALIZED(name, initializer) \ - MP_VAR(name); \ - BnToWolf(name, initializer); - -#define POINT_CREATE(name, initializer) \ - ecc_point *name = EcPointInitialized(initializer); - -#define POINT_DELETE(name) \ - wc_ecc_del_point(name); \ - name = NULL; - -typedef ECC_CURVE_DATA bnCurve_t; - -typedef bnCurve_t *bigCurve; - -#define AccessCurveData(E) (E) - -#define CURVE_INITIALIZED(name, initializer) \ - bnCurve_t *name = (ECC_CURVE_DATA *)GetCurveData(initializer) - -#define CURVE_FREE(E) - -#include "TpmToWolfSupport_fp.h" - -#define WOLF_ENTER() - -#define WOLF_LEAVE() - -// This definition would change if there were something to report -#define MathLibSimulationEnd() - -#endif // MATH_LIB_DEFINED diff --git a/ta/ftpm/include/Wolf/TpmToWolfSym.h b/ta/ftpm/include/Wolf/TpmToWolfSym.h deleted file mode 100644 index 0c042eb3521..00000000000 --- a/ta/ftpm/include/Wolf/TpmToWolfSym.h +++ /dev/null @@ -1,120 +0,0 @@ -/* Microsoft Reference Implementation for TPM 2.0 - * - * The copyright in this software is being made available under the BSD License, - * included below. This software may be subject to other third party and - * contributor rights, including patent rights, and no such rights are granted - * under this license. - * - * Copyright (c) Microsoft Corporation - * - * All rights reserved. - * - * BSD License - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * Redistributions of source code must retain the above copyright notice, this list - * of conditions and the following disclaimer. - * - * 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. - * - * 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. - */ - -//** Introduction -// -// This header file is used to 'splice' the wolfcrypt library into the TPM code. - -#ifndef SYM_LIB_DEFINED -#define SYM_LIB_DEFINED - -#define SYM_LIB_WOLF - -#define SYM_ALIGNMENT RADIX_BYTES - -#include -#include - -//*************************************************************** -//** Links to the wolfCrypt AES code -//*************************************************************** -#if ALG_SM4 -#undef ALG_SM4 -#define ALG_SM4 ALG_NO -//#error "SM4 is not available" -#endif - -#if ALG_CAMELLIA -#undef ALG_CAMELLIA -#define ALG_CAMELLIA ALG_NO -//#error "Camellia is not available" -#endif - -// Define the order of parameters to the library functions that do block encryption -// and decryption. -typedef void(*TpmCryptSetSymKeyCall_t)( - void *keySchedule, - BYTE *out, - const BYTE *in - ); - -// The Crypt functions that call the block encryption function use the parameters -// in the order: -// 1) keySchedule -// 2) in buffer -// 3) out buffer -// Since wolfcrypt uses the order in encryptoCall_t above, need to swizzle the -// values to the order required by the library. -#define SWIZZLE(keySchedule, in, out) \ - (void *)(keySchedule), (BYTE *)(out), (const BYTE *)(in) - -// Macros to set up the encryption/decryption key schedules -// -// AES: -#define TpmCryptSetEncryptKeyAES(key, keySizeInBits, schedule) \ - wc_AesSetKeyDirect((tpmKeyScheduleAES *)(schedule), key, BITS_TO_BYTES(keySizeInBits), 0, AES_ENCRYPTION) -#define TpmCryptSetDecryptKeyAES(key, keySizeInBits, schedule) \ - wc_AesSetKeyDirect((tpmKeyScheduleAES *)(schedule), key, BITS_TO_BYTES(keySizeInBits), 0, AES_DECRYPTION) - -// TDES: -#define TpmCryptSetEncryptKeyTDES(key, keySizeInBits, schedule) \ - TDES_setup_encrypt_key((key), (keySizeInBits), (tpmKeyScheduleTDES *)(schedule)) -#define TpmCryptSetDecryptKeyTDES(key, keySizeInBits, schedule) \ - TDES_setup_decrypt_key((key), (keySizeInBits), (tpmKeyScheduleTDES *)(schedule)) - -// Macros to alias encryption calls to specific algorithms. This should be used -// sparingly. Currently, only used by CryptRand.c -// -// When using these calls, to call the AES block encryption code, the caller -// should use: -// TpmCryptEncryptAES(SWIZZLE(keySchedule, in, out)); -#define TpmCryptEncryptAES wc_AesEncryptDirect -#define TpmCryptDecryptAES wc_AesDecryptDirect -#define tpmKeyScheduleAES Aes - -#define TpmCryptEncryptTDES TDES_encrypt -#define TpmCryptDecryptTDES TDES_decrypt -#define tpmKeyScheduleTDES Des3 - -typedef union tpmCryptKeySchedule_t tpmCryptKeySchedule_t; - -#if ALG_TDES -#include "TpmToWolfDesSupport_fp.h" -#endif - -// This definition would change if there were something to report -#define SymLibSimulationEnd() - -#endif // SYM_LIB_DEFINED diff --git a/ta/ftpm/include/Wolf/user_settings.h b/ta/ftpm/include/Wolf/user_settings.h deleted file mode 100644 index de0dfd321f3..00000000000 --- a/ta/ftpm/include/Wolf/user_settings.h +++ /dev/null @@ -1,108 +0,0 @@ -/* Microsoft Reference Implementation for TPM 2.0 - * - * The copyright in this software is being made available under the BSD License, - * included below. This software may be subject to other third party and - * contributor rights, including patent rights, and no such rights are granted - * under this license. - * - * Copyright (c) Microsoft Corporation - * - * All rights reserved. - * - * BSD License - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * Redistributions of source code must retain the above copyright notice, this list - * of conditions and the following disclaimer. - * - * 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. - * - * 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. - */ - - -/* TPM specific preprocessor flags for wolfcrypt */ - - -#ifndef WOLF_CRYPT_USER_SETTINGS_H -#define WOLF_CRYPT_USER_SETTINGS_H - -#include - -/* Remove the automatic setting of the default I/O functions EmbedSend() - and EmbedReceive(). */ -#define WOLFSSL_USER_IO - -/* Avoid naming conflicts */ -#define NO_OLD_WC_NAMES - -/* Use stack based fast math for all big integer math */ -#define USE_FAST_MATH -#define TFM_TIMING_RESISTANT - -/* Expose direct encryption functions */ -#define WOLFSSL_AES_DIRECT - -/* Enable/Disable algorithm support based on TPM implementation header */ -#if ALG_SHA256 - #define WOLFSSL_SHA256 -#endif -#if ALG_SHA384 || ALG_SHA512 - #define WOLFSSL_SHA384 - #define WOLFSSL_SHA512 -#endif -#if ALG_TDES - #define WOLFSSL_DES_ECB -#endif -#if ALG_RSA - /* Turn on RSA key generation functionality */ - #define WOLFSSL_KEY_GEN -#endif -#if ALG_ECC || defined(WOLFSSL_LIB) - #define HAVE_ECC - - /* Expose additional ECC primitives */ - #define WOLFSSL_PUBLIC_ECC_ADD_DBL - #define ECC_TIMING_RESISTANT - - /* Enables Shamir calc method */ - #define ECC_SHAMIR - - /* The TPM only needs low level ECC crypto */ - #define NO_ECC_SIGN - #define NO_ECC_VERIFY - #define NO_ECC_SECP - - #undef ECC_BN_P256 - #undef ECC_SM2_P256 - #undef ECC_BN_P638 - #define ECC_BN_P256 NO - #define ECC_SM2_P256 NO - #define ECC_BN_P638 NO - -#endif - -/* Disable explicit RSA. The TPM support for RSA is dependent only on TFM */ -#define NO_RSA -#define NO_RC4 -#define NO_ASN - -/* Enable debug wolf library check */ -//#define LIBRARY_COMPATIBILITY_CHECK - -#define WOLFSSL_ - -#endif // WOLF_CRYPT_USER_SETTINGS_H From 4b7e1e6ef9253fe2434e9f6cb8eb4781fc14179f Mon Sep 17 00:00:00 2001 From: Jens Wiklander Date: Tue, 24 Sep 2024 13:22:57 +0200 Subject: [PATCH 25/27] ftpm: remove unused sub.mk files Remove the now unused sub.mk files. Signed-off-by: Jens Wiklander --- ta/ftpm/lib/sub.mk | 8 -- ta/ftpm/lib/tpm/sub.mk | 274 ---------------------------------------- ta/ftpm/lib/wolf/sub.mk | 58 --------- 3 files changed, 340 deletions(-) delete mode 100644 ta/ftpm/lib/sub.mk delete mode 100644 ta/ftpm/lib/tpm/sub.mk delete mode 100644 ta/ftpm/lib/wolf/sub.mk diff --git a/ta/ftpm/lib/sub.mk b/ta/ftpm/lib/sub.mk deleted file mode 100644 index 79205e62625..00000000000 --- a/ta/ftpm/lib/sub.mk +++ /dev/null @@ -1,8 +0,0 @@ -.PHONY: create_lib_symlinks -create_lib_symlinks: ./lib/tpm/tpm_symlink ./lib/wolf/wolf_symlink - -.PHONY: clean_lib_symlinks -clean_lib_symlinks: remove_tpm_symlink remove_wolf_symlink - -subdirs-y += wolf -subdirs-y += tpm \ No newline at end of file diff --git a/ta/ftpm/lib/tpm/sub.mk b/ta/ftpm/lib/tpm/sub.mk deleted file mode 100644 index 68bdfe276c8..00000000000 --- a/ta/ftpm/lib/tpm/sub.mk +++ /dev/null @@ -1,274 +0,0 @@ -FTPM_FLAGS = -DGCC -DUSE_WOLFCRYPT -DSIMULATION=NO -DVTPM -D_ARM_ -FTPM_DEBUG = -DCOMPILER_CHECKS=YES -DfTPMDebug -DRUNTIME_SIZE_CHECKS -DLIBRARY_COMPATIBILITY_CHECK -FTPM_RELEASE = -DCOMPILER_CHECKS=NO -DRUNTIME_SIZE_CHECKS=NO -DLIBRARY_COMPATIBILITY_CHECK=NO - -# -# The fTPM needs to overwrite some of the header files used in the reference implementation. The search order GCC -# uses is dependent on the order the '-I/include/path' arguments are passed in. This is depended on the optee_os build -# system which makes it brittle. Force including these files here will make sure the correct files are used first. -# - -FTPM_INCLUDES = -include ./reference/include/VendorString.h \ - -include ./reference/include/TpmProfile.h \ - -include ./platform/include/Platform.h - -# -# The TPM causes a few warnings when compiled with GCC which are not critical. -# - -FTPM_WARNING_SUPPRESS = -Wno-cast-align \ - -Wno-cast-function-type \ - -Wno-implicit-fallthrough \ - -Wno-missing-braces \ - -Wno-sign-compare \ - -Wno-suggest-attribute=noreturn \ - -Wno-switch-default - -cflags-y += $(FTPM_FLAGS) $(WOLF_SSL_FLAGS) $(FTPM_INCLUDES) $(FTPM_WARNING_SUPPRESS) - -ifeq ($(CFG_TA_DEBUG),y) -cflags-y += $(FTPM_DEBUG) -else -cflags-y += $(FTPM_RELEASE) -endif - -# -# For the purposes of this command the current working directory is the makefile root (/fTPM) folder, -# but the symlink will be created relative to THIS directory so the source requires an extra '../../'. -# -# Symlinks are needed since all build output is placed relative to the root. External libraries would result in -# binaries located outside the ouptut folder. -# -./lib/tpm/tpm_symlink: - @echo Checking symlink to the TPM folder: $(abspath $(TPM_ROOT)) - @if [ -L ./lib/tpm/tpm_symlink ] ; \ - then \ - echo Symlink already established ; \ - else \ - echo Establishing symlink. ; \ - ln -s ../../$(TPM_ROOT) ./lib/tpm/tpm_symlink; \ - fi - -.PHONY: remove_tpm_symlink -remove_tpm_symlink: - @if [ -e ./lib/tpm/tpm_symlink ] ; \ - then \ - unlink ./lib/tpm/tpm_symlink ; \ - echo Clearing symlink to the TPM folder: $(abspath $(TPM_ROOT)) ; \ - fi - -global-incdirs-y += tpm_symlink/TPMCmd/tpm/include -global-incdirs-y += tpm_symlink/TPMCmd/tpm/include/Ltc -global-incdirs-y += tpm_symlink/TPMCmd/tpm/include/prototypes -global-incdirs-y += tpm_symlink/TPMCmd/Platform/include - -# -# Generated in WSL using: -# find -name *.c | while read line; do echo XXXX$line; done | \ -# sed -e 's/XXXX.\//srcs-y += tpm_symlink\/TPMCmd\/tpm\/src\//g' -# This may need to be updated if there are any changes to the reference -# implementation. - -srcs-y += tpm_symlink/TPMCmd/tpm/src/X509/X509_ECC.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/X509/X509_RSA.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/X509/TpmASN1.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/X509/X509_spt.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/command/Attestation/CertifyX509.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/command/Attestation/GetCommandAuditDigest.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/command/Attestation/GetSessionAuditDigest.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/command/Attestation/Attest_spt.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/command/Attestation/Quote.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/command/Attestation/Certify.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/command/Attestation/CertifyCreation.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/command/Attestation/GetTime.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/command/Random/GetRandom.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/command/Random/StirRandom.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/command/NVStorage/NV_WriteLock.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/command/NVStorage/NV_ReadPublic.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/command/NVStorage/NV_spt.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/command/NVStorage/NV_Increment.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/command/NVStorage/NV_ChangeAuth.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/command/NVStorage/NV_UndefineSpaceSpecial.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/command/NVStorage/NV_SetBits.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/command/NVStorage/NV_Write.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/command/NVStorage/NV_GlobalWriteLock.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/command/NVStorage/NV_Read.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/command/NVStorage/NV_Extend.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/command/NVStorage/NV_Certify.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/command/NVStorage/NV_ReadLock.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/command/NVStorage/NV_DefineSpace.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/command/NVStorage/NV_UndefineSpace.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/command/HashHMAC/HashSequenceStart.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/command/HashHMAC/SequenceUpdate.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/command/HashHMAC/MAC_Start.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/command/HashHMAC/EventSequenceComplete.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/command/HashHMAC/HMAC_Start.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/command/HashHMAC/SequenceComplete.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/command/Vendor/Vendor_TCG_Test.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/command/Ecdaa/Commit.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/command/Startup/Startup.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/command/Startup/Shutdown.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/command/FieldUpgrade/FieldUpgradeData.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/command/FieldUpgrade/FirmwareRead.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/command/FieldUpgrade/FieldUpgradeStart.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/command/Capability/TestParms.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/command/Capability/GetCapability.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/command/ClockTimer/ACT_spt.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/command/ClockTimer/ClockRateAdjust.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/command/ClockTimer/ACT_SetTimeout.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/command/ClockTimer/ClockSet.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/command/ClockTimer/ReadClock.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/command/Session/PolicyRestart.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/command/Session/StartAuthSession.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/command/EA/PolicyDuplicationSelect.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/command/EA/PolicyPCR.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/command/EA/PolicySecret.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/command/EA/PolicyTicket.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/command/EA/PolicyTemplate.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/command/EA/PolicyNV.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/command/EA/PolicyGetDigest.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/command/EA/PolicyCpHash.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/command/EA/PolicyOR.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/command/EA/Policy_spt.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/command/EA/PolicyLocality.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/command/EA/PolicyAuthorize.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/command/EA/PolicyAuthorizeNV.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/command/EA/PolicyPassword.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/command/EA/PolicyCounterTimer.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/command/EA/PolicyAuthValue.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/command/EA/PolicySigned.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/command/EA/PolicyNameHash.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/command/EA/PolicyNvWritten.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/command/EA/PolicyPhysicalPresence.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/command/EA/PolicyCommandCode.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/command/Hierarchy/ChangePPS.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/command/Hierarchy/HierarchyControl.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/command/Hierarchy/HierarchyChangeAuth.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/command/Hierarchy/ChangeEPS.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/command/Hierarchy/ClearControl.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/command/Hierarchy/Clear.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/command/Hierarchy/SetPrimaryPolicy.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/command/Hierarchy/CreatePrimary.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/command/CommandAudit/SetCommandCodeAuditStatus.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/command/Object/Object_spt.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/command/Object/ReadPublic.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/command/Object/Load.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/command/Object/LoadExternal.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/command/Object/MakeCredential.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/command/Object/Unseal.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/command/Object/CreateLoaded.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/command/Object/ObjectChangeAuth.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/command/Object/ActivateCredential.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/command/Object/Create.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/command/AttachedComponent/AC_GetCapability.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/command/AttachedComponent/AC_spt.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/command/AttachedComponent/AC_Send.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/command/AttachedComponent/Policy_AC_SendSelect.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/command/Signature/VerifySignature.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/command/Signature/Sign.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/command/Duplication/Import.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/command/Duplication/Rewrap.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/command/Duplication/Duplicate.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/command/Symmetric/EncryptDecrypt2.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/command/Symmetric/EncryptDecrypt_spt.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/command/Symmetric/HMAC.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/command/Symmetric/Hash.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/command/Symmetric/EncryptDecrypt.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/command/Symmetric/MAC.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/command/Context/ContextSave.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/command/Context/FlushContext.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/command/Context/Context_spt.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/command/Context/ContextLoad.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/command/Context/EvictControl.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/command/PCR/PCR_Reset.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/command/PCR/PCR_Allocate.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/command/PCR/PCR_Extend.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/command/PCR/PCR_SetAuthValue.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/command/PCR/PCR_Event.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/command/PCR/PCR_SetAuthPolicy.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/command/PCR/PCR_Read.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/command/DA/DictionaryAttackParameters.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/command/DA/DictionaryAttackLockReset.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/command/Misc/PP_Commands.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/command/Misc/SetAlgorithmSet.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/command/Testing/GetTestResult.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/command/Testing/SelfTest.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/command/Testing/IncrementalSelfTest.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/command/Asymmetric/ECC_Parameters.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/command/Asymmetric/RSA_Encrypt.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/command/Asymmetric/ECDH_ZGen.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/command/Asymmetric/ECDH_KeyGen.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/command/Asymmetric/ZGen_2Phase.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/command/Asymmetric/ECC_Decrypt.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/command/Asymmetric/RSA_Decrypt.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/command/Asymmetric/EC_Ephemeral.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/command/Asymmetric/ECC_Encrypt.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/subsystem/DA.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/subsystem/NvDynamic.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/subsystem/Object.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/subsystem/PP.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/subsystem/Session.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/subsystem/NvReserved.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/subsystem/Hierarchy.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/subsystem/Time.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/subsystem/PCR.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/subsystem/CommandAudit.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/events/_TPM_Hash_Start.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/events/_TPM_Init.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/events/_TPM_Hash_Data.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/events/_TPM_Hash_End.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/crypt/CryptSmac.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/crypt/CryptEccData.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/crypt/CryptCmac.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/crypt/BnMath.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/crypt/CryptEccSignature.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/crypt/wolf/TpmToWolfDesSupport.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/crypt/wolf/TpmToWolfMath.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/crypt/wolf/TpmToWolfSupport.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/crypt/AlgorithmTests.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/crypt/CryptSelfTest.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/crypt/Ticket.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/crypt/CryptDes.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/crypt/BnMemory.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/crypt/CryptPrimeSieve.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/crypt/ossl/TpmToOsslSupport.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/crypt/ossl/TpmToOsslDesSupport.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/crypt/ossl/TpmToOsslMath.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/crypt/CryptEccKeyExchange.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/crypt/BnConvert.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/crypt/CryptRand.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/crypt/ltc/TpmToLtcSupport.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/crypt/ltc/TpmToLtcDesSupport.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/crypt/ltc/TpmToLtcMath.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/crypt/CryptEccMain.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/crypt/CryptSym.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/crypt/RsaKeyCache.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/crypt/CryptUtil.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/crypt/CryptEccCrypt.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/crypt/CryptRsa.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/crypt/CryptPrime.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/crypt/PrimeData.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/crypt/CryptHash.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/support/Marshal.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/support/MathOnByteBuffers.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/support/TableDrivenMarshal.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/support/PropertyCap.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/support/Locality.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/support/TableMarshalData.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/support/Memory.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/support/Response.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/support/ResponseCodeProcessing.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/support/Global.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/support/Power.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/support/AlgorithmCap.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/support/CommandCodeAttributes.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/support/Entity.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/support/Handle.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/support/TpmFail.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/support/TpmSizeChecks.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/support/Manufacture.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/support/IoBuffers.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/support/Bits.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/main/SessionProcess.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/main/CommandDispatcher.c -srcs-y += tpm_symlink/TPMCmd/tpm/src/main/ExecCommand.c diff --git a/ta/ftpm/lib/wolf/sub.mk b/ta/ftpm/lib/wolf/sub.mk deleted file mode 100644 index 0a43f46e50b..00000000000 --- a/ta/ftpm/lib/wolf/sub.mk +++ /dev/null @@ -1,58 +0,0 @@ - -WOLF_SSL_FLAGS = -DSINGLE_THREADED \ - -DNO_WOLFSSL_CLIENT \ - -DNO_WOLFSSL_SERVER \ - -DOPENSSL_EXTRA \ - -DNO_FILESYSTEM \ - -DWOLFSSL_USER_SETTINGS \ - -DTIME_OVERRIDES \ - -DSTRING_USER \ - -DCTYPE_USER \ - -DCERTIFYX509_DEBUG=NO - -# -# Wolfcrypt has multiple unused functions, unfortunately the OPTEE build system can only turn off compiler flags for -# files in the same directory as the sub.mk file. It is not possible to place sub.mk files in the git submodules without -# creating a new fork of each submodule repo. To avoid spurious warnings these warnings are disabled here globally. -# - -WOLF_WARNING_SUPPRESS = -Wno-unused-function - -cflags-y += $(WOLF_SSL_FLAGS) $(WOLF_WARNING_SUPPRESS) - -# -# For the purposes of this command the current working directory is the makefile root (/fTPM) folder, -# but the symlink will be created relative to THIS directory so the source requires an extra '../../'. -# -./lib/wolf/wolf_symlink: - @echo Checking symlink to the WolfSSL folder: $(abspath $(WOLF_ROOT)) - @if [ -L ./lib/wolf/wolf_symlink ] ; \ - then \ - echo Symlink already established ; \ - else \ - echo Establishing symlink. ; \ - ln -s ../../$(WOLF_ROOT) ./lib/wolf/wolf_symlink; \ - fi - -.PHONY: remove_wolf_symlink -remove_wolf_symlink: - @if [ -e ./lib/wolf/wolf_symlink ] ; \ - then \ - unlink ./lib/wolf/wolf_symlink ; \ - echo Clearing symlink to the Wolf folder: $(abspath $(WOLF_ROOT)) ; \ - fi - -global-incdirs-y += wolf_symlink - -srcs-y += wolf_symlink/wolfcrypt/src/aes.c -srcs-y += wolf_symlink/wolfcrypt/src/asn.c -srcs-y += wolf_symlink/wolfcrypt/src/ecc.c -srcs-y += wolf_symlink/wolfcrypt/src/integer.c -srcs-y += wolf_symlink/wolfcrypt/src/memory.c -srcs-y += wolf_symlink/wolfcrypt/src/sha.c -srcs-y += wolf_symlink/wolfcrypt/src/sha256.c -srcs-y += wolf_symlink/wolfcrypt/src/sha512.c -srcs-y += wolf_symlink/wolfcrypt/src/tfm.c -srcs-y += wolf_symlink/wolfcrypt/src/wolfmath.c -srcs-y += wolf_symlink/wolfcrypt/src/des3.c -srcs-y += wolf_symlink/wolfcrypt/src/random.c From b0a3d154583b763aaafb9a577166032c0066eb21 Mon Sep 17 00:00:00 2001 From: Jens Wiklander Date: Tue, 1 Oct 2024 13:39:29 +0200 Subject: [PATCH 26/27] ftpm: Makefile: update for building externally Update the fTPM Makefile to support building externally. Remove WolfSSL leftovers. Signed-off-by: Jens Wiklander --- ta/ftpm/Makefile | 15 +++++---------- 1 file changed, 5 insertions(+), 10 deletions(-) diff --git a/ta/ftpm/Makefile b/ta/ftpm/Makefile index c71eecd6d17..344c1c8313c 100644 --- a/ta/ftpm/Makefile +++ b/ta/ftpm/Makefile @@ -1,13 +1,8 @@ BINARY=bc50d971-d4c9-42c4-82cb-343fb7f37896 -O ?= ../out/fTPM -WOLF_ROOT := ../../../../external/wolfssl/ -TPM_ROOT := ../../../../ - -include $(TA_DEV_KIT_DIR)/mk/ta_dev_kit.mk - -clean: clean_stripped_file -.PHONY: clean_stripped_file -clean_stripped_file: - rm -f $(BINARY).stripped.elf +-include $(TA_DEV_KIT_DIR)/mk/ta_dev_kit.mk +ifeq ($(wildcard $(TA_DEV_KIT_DIR)/mk/ta_dev_kit.mk), ) +clean: + @echo 'Note: $$(TA_DEV_KIT_DIR)/mk/ta_dev_kit.mk not found, cannot clean TA' +endif From 6b5c2d002cd75157bf83148e29f55e3a006a80ca Mon Sep 17 00:00:00 2001 From: Jens Wiklander Date: Mon, 7 Oct 2024 09:34:16 +0200 Subject: [PATCH 27/27] ftpm: disable PPI emulation by default Add the configuration variable CFG_FTPM_EMULATE_PPI, default disabled, to control whether PPI emulation is enabled. Signed-off-by: Jens Wiklander --- ta/ftpm/fTPM.c | 3 +++ ta/ftpm/sub.mk | 2 ++ 2 files changed, 5 insertions(+) diff --git a/ta/ftpm/fTPM.c b/ta/ftpm/fTPM.c index 7f5a5080e0f..24602a34f28 100644 --- a/ta/ftpm/fTPM.c +++ b/ta/ftpm/fTPM.c @@ -36,6 +36,7 @@ #define STR_TRACE_USER_TA "fTPM" +#include #include #include #include @@ -467,6 +468,8 @@ TEE_Result TA_InvokeCommandEntryPoint(void *sess_ctx, } case TA_FTPM_EMULATE_PPI: { + if (!IS_ENABLED(CFG_FTPM_EMULATE_PPI)) + return TEE_ERROR_NOT_SUPPORTED; return fTPM_Emulate_PPI(param_types, params); } diff --git a/ta/ftpm/sub.mk b/ta/ftpm/sub.mk index 2bb893c809b..d795569a013 100644 --- a/ta/ftpm/sub.mk +++ b/ta/ftpm/sub.mk @@ -1,3 +1,5 @@ +CFG_FTPM_EMULATE_PPI ?= n + # # The fTPM needs to overwrite some of the header files used in the # reference implementation. The search order GCC uses is dependent on the