diff --git a/Makefile b/Makefile index 73502a707..19bc05ab3 100644 --- a/Makefile +++ b/Makefile @@ -30,7 +30,7 @@ # include buildenv.mk -.PHONY: all preparation psw sdk clean rebuild sdk_install_pkg psw_install_pkg tdx +.PHONY: all tips preparation psw sdk_no_mitigation sdk clean rebuild tdx servtd_attest servtd_attest_preparation ipp sdk_install_pkg_no_mitigation sdk_install_pkg sdk_install_pkg_from_source psw_install_pkg all: tips @@ -51,6 +51,8 @@ preparation: # As SDK build needs to clone and patch openmp, we cannot support the mode that download the source from github as zip. # Only enable the download from git git submodule update --init --recursive + cd external/dcap_source/external/jwt-cpp && git apply ../0001-Add-a-macro-to-disable-time-support-in-jwt-for-SGX.patch >/dev/null 2>&1 || \ + git apply ../0001-Add-a-macro-to-disable-time-support-in-jwt-for-SGX.patch -R --check ./external/dcap_source/QuoteVerification/prepare_sgxssl.sh nobuild cd external/openmp/openmp_code && git apply ../0001-Enable-OpenMP-in-SGX.patch >/dev/null 2>&1 || git apply ../0001-Enable-OpenMP-in-SGX.patch --check -R cd external/protobuf/protobuf_code && git apply ../sgx_protobuf.patch >/dev/null 2>&1 || git apply ../sgx_protobuf.patch --check -R @@ -60,6 +62,8 @@ preparation: cd external/cbor && cp -r libcbor sgx_libcbor cd external/cbor/libcbor && git apply ../raw_cbor.patch >/dev/null 2>&1 || git apply ../raw_cbor.patch --check -R cd external/cbor/sgx_libcbor && git apply ../sgx_cbor.patch >/dev/null 2>&1 || git apply ../sgx_cbor.patch --check -R + cd external/ippcp_internal/ipp-crypto && git apply ../0001-IPP-crypto-for-SGX.patch > /dev/null 2>&1 || git apply ../0001-IPP-crypto-for-SGX.patch --check -R + cd external/ippcp_internal/ipp-crypto && mkdir -p build ./download_prebuilt.sh ./external/dcap_source/QuoteGeneration/download_prebuilt.sh @@ -101,6 +105,14 @@ servtd_attest_preparation: ./external/sgx-emm/create_symlink.sh ./external/dcap_source/QuoteVerification/prepare_sgxssl.sh nobuild +ipp: + $(MAKE) -C external/ippcp_internal/ clean + $(MAKE) -C external/ippcp_internal/ MITIGATION-CVE-2020-0551=LOAD + $(MAKE) -C external/ippcp_internal/ clean + $(MAKE) -C external/ippcp_internal/ MITIGATION-CVE-2020-0551=CF + $(MAKE) -C external/ippcp_internal/ clean + $(MAKE) -C external/ippcp_internal/ + # Generate SE SDK Install package sdk_install_pkg_no_mitigation: sdk_no_mitigation ./linux/installer/bin/build-installpkg.sh sdk @@ -108,6 +120,11 @@ sdk_install_pkg_no_mitigation: sdk_no_mitigation sdk_install_pkg: sdk ./linux/installer/bin/build-installpkg.sh sdk cve-2020-0551 +sdk_install_pkg_from_source: + $(MAKE) ipp + $(MAKE) sdk + ./linux/installer/bin/build-installpkg.sh sdk cve-2020-0551 + psw_install_pkg: psw ifeq ("$(wildcard ./external/dcap_source/QuoteGeneration/psw/ae/data/prebuilt/libsgx_qe3.signed.so)", "") ./external/dcap_source/QuoteGeneration/download_prebuilt.sh @@ -231,11 +248,6 @@ deb_libsgx_dcap_default_qpl: $(MAKE) -C external/dcap_source/QuoteGeneration deb_sgx_dcap_default_qpl_pkg $(CP) external/dcap_source/QuoteGeneration/installer/linux/deb/libsgx-dcap-default-qpl/libsgx-dcap-default-qpl*deb ./linux/installer/deb/sgx-aesm-service/ -.PHONY: deb_libsgx_dcap_pccs -deb_libsgx_dcap_pccs: - $(MAKE) -C external/dcap_source/QuoteGeneration deb_sgx_dcap_pccs_pkg - $(CP) external/dcap_source/QuoteGeneration/installer/linux/deb/sgx-dcap-pccs/sgx-dcap-pccs*deb ./linux/installer/deb/sgx-aesm-service/ - .PHONY: deb_libsgx_dcap_ql deb_libsgx_dcap_ql: deb_libsgx_pce_logic $(MAKE) -C external/dcap_source/QuoteGeneration deb_sgx_dcap_ql_pkg @@ -284,7 +296,6 @@ deb_psw_pkg: deb_libsgx_headers_pkg \ deb_libsgx_ae_qe3 \ deb_libsgx_ae_id_enclave \ deb_libsgx_dcap_default_qpl \ - deb_libsgx_dcap_pccs \ deb_libsgx_dcap_ql \ deb_libsgx_ae_qve \ deb_sgx_dcap_quote_verify \ @@ -410,11 +421,6 @@ rpm_libsgx_dcap_default_qpl: $(MAKE) -C external/dcap_source/QuoteGeneration rpm_sgx_dcap_default_qpl_pkg $(CP) external/dcap_source/QuoteGeneration/installer/linux/rpm/libsgx-dcap-default-qpl/libsgx-dcap-default-qpl*.rpm ./linux/installer/rpm/sgx-aesm-service/ -.PHONY: rpm_libsgx_dcap_pccs -rpm_libsgx_dcap_pccs: - $(MAKE) -C external/dcap_source/QuoteGeneration rpm_sgx_dcap_pccs_pkg - $(CP) external/dcap_source/QuoteGeneration/installer/linux/rpm/sgx-dcap-pccs/sgx-dcap-pccs*.rpm ./linux/installer/rpm/sgx-aesm-service/ - .PHONY: rpm_libsgx_dcap_ql rpm_libsgx_dcap_ql: $(MAKE) -C external/dcap_source/QuoteGeneration rpm_sgx_dcap_ql_pkg @@ -463,7 +469,6 @@ rpm_psw_pkg: rpm_libsgx_headers_pkg \ rpm_libsgx_ae_qe3 \ rpm_libsgx_ae_id_enclave \ rpm_libsgx_dcap_default_qpl \ - rpm_libsgx_dcap_pccs \ rpm_libsgx_dcap_ql \ rpm_libsgx_ae_qve \ rpm_sgx_dcap_quote_verify \ @@ -486,8 +491,6 @@ clean: @$(RM) -r $(ROOT_DIR)/build @$(RM) -r linux/installer/bin/install-sgx-*.bin*.withLicense @$(RM) -r linux/installer/bin/sgx_linux*.bin - @$(RM) -f ./linux/installer/deb/sgx-aesm-service/sgx-dcap-pccs*deb - @$(RM) -f ./linux/installer/rpm/sgx-aesm-service/sgx-dcap-pccs*rpm ./linux/installer/deb/sgx-aesm-service/clean.sh ./linux/installer/deb/libsgx-epid/clean.sh ./linux/installer/deb/libsgx-launch/clean.sh @@ -507,6 +510,7 @@ clean: ./linux/installer/rpm/libsgx-headers/clean.sh ./linux/installer/rpm/sdk/clean.sh ./linux/installer/common/local_repo_builder/local_repo_builder.sh rpm clean + $(MAKE) -C external/ippcp_internal/ clean ifeq ("$(shell test -f external/dcap_source/QuoteVerification/dcap_tvl/Makefile && echo TVL Makefile exists)", "TVL Makefile exists") $(MAKE) -C external/dcap_source/QuoteVerification/dcap_tvl MITIGATION-CVE-2020-0551=LOAD clean $(MAKE) -C external/dcap_source/QuoteVerification/dcap_tvl MITIGATION-CVE-2020-0551=CF clean @@ -527,7 +531,6 @@ ifeq ("$(shell test -f external/dcap_source/QuoteVerification/Makefile && echo M ./external/dcap_source/QuoteGeneration/installer/linux/deb/libsgx-pce-logic/clean.sh ./external/dcap_source/QuoteGeneration/installer/linux/deb/libsgx-qe3-logic/clean.sh ./external/dcap_source/QuoteGeneration/installer/linux/deb/libsgx-dcap-quote-verify/clean.sh - ./external/dcap_source/QuoteGeneration/installer/linux/deb/sgx-dcap-pccs/clean.sh ./external/dcap_source/QuoteGeneration/installer/linux/deb/tee-appraisal-tool/clean.sh ./external/dcap_source/QuoteGeneration/installer/linux/rpm/libsgx-ae-qve/clean.sh ./external/dcap_source/QuoteGeneration/installer/linux/rpm/libsgx-ae-qe3/clean.sh @@ -541,7 +544,6 @@ ifeq ("$(shell test -f external/dcap_source/QuoteVerification/Makefile && echo M ./external/dcap_source/QuoteGeneration/installer/linux/rpm/libsgx-pce-logic/clean.sh ./external/dcap_source/QuoteGeneration/installer/linux/rpm/libsgx-qe3-logic/clean.sh ./external/dcap_source/QuoteGeneration/installer/linux/rpm/libsgx-dcap-quote-verify/clean.sh - ./external/dcap_source/QuoteGeneration/installer/linux/rpm/sgx-dcap-pccs/clean.sh ./external/dcap_source/QuoteGeneration/installer/linux/rpm/tee-appraisal-tool/clean.sh endif @@ -560,3 +562,4 @@ distclean: $(RM) -rf external/dcap_source/QuoteGeneration/'Intel redistributable binary.txt' $(RM) -rf external/dcap_source/QuoteVerification/sgxssl/ git submodule deinit --all -f + $(RM) -rf dcap-trunk external/dcap_source external/openmp/openmp_code external/protobuf/protobuf_code diff --git a/README.md b/README.md index 9a2976b5d..d5b53c6b8 100644 --- a/README.md +++ b/README.md @@ -91,7 +91,7 @@ Build the Intel(R) SGX SDK and Intel(R) SGX PSW Package * Ubuntu\* 20.04 LTS Desktop 64bits * Ubuntu\* 20.04 LTS Server 64bits * Ubuntu\* 22.04 LTS Server 64bits - * Ubuntu\* 23.10 Server 64bits + * Ubuntu\* 24.04 LTS Server 64bits * Red Hat Enterprise Linux Server release 9.2 64bits * CentOS Stream 9 64bits * CentOS 8.3 64bits @@ -105,7 +105,7 @@ Build the Intel(R) SGX SDK and Intel(R) SGX PSW Package $ sudo apt-get install build-essential ocaml ocamlbuild automake autoconf libtool wget python3 libssl-dev git cmake perl $ sudo update-alternatives --install /usr/bin/python python /usr/bin/python3 1 ``` - * On Ubuntu 20.04, Ubuntu 22.04 and Ubuntu 23.10: + * On Ubuntu 20.04, Ubuntu 22.04 and Ubuntu 24.04: ``` $ sudo apt-get install build-essential ocaml ocamlbuild automake autoconf libtool wget python-is-python3 libssl-dev git cmake perl ``` @@ -142,9 +142,9 @@ Build the Intel(R) SGX SDK and Intel(R) SGX PSW Package 1) To install the additional required tools: * On Debian 10: ``` - $ sudo apt-get install libssl-dev libcurl4-openssl-dev protobuf-compiler libprotobuf-dev debhelper cmake reprepro unzip lsb-release libsystemd0 + $ sudo apt-get install libssl-dev libcurl4-openssl-dev protobuf-compiler libprotobuf-dev debhelper cmake reprepro unzip pkgconf libboost-dev libboost-system-dev libboost-thread-dev lsb-release libsystemd0 ``` - * On Ubuntu 20.04, Ubuntu 22.04 and Ubuntu 23.10: + * On Ubuntu 20.04, Ubuntu 22.04 and Ubuntu 24.04: ``` $ sudo apt-get install libssl-dev libcurl4-openssl-dev protobuf-compiler libprotobuf-dev debhelper cmake reprepro unzip pkgconf libboost-dev libboost-system-dev libboost-thread-dev lsb-release libsystemd0 ``` @@ -166,7 +166,7 @@ Build the Intel(R) SGX SDK and Intel(R) SGX PSW Package ``` * On SUSE Linux Enterprise Server 15.4: ``` - $ sudo zypper install libopenssl-devel libcurl-devel protobuf-devel cmake rpm-build createrepo libsystemd0 + $ sudo zypper install libopenssl-devel libcurl-devel protobuf-devel cmake rpm-build createrepo_c libsystemd0 libboost_system1_66_0-devel libboost_thread1_66_0-devel ``` 2) To install latest Intel(R) SGX SDK Installer Ensure that you have downloaded latest Intel(R) SGX SDK Installer from the [Intel(R) SGX SDK](https://software.intel.com/en-us/sgx-sdk/download) and followed the Installation Guide in the same page to install latest Intel(R) SGX SDK Installer. @@ -256,7 +256,7 @@ You can find the tools and libraries generated in the `build/linux` directory. $ make ``` - To build the Intel(R) SGX PSW installer, enter the following command: - * On Ubuntu 20.04, Ubuntu 22.04, Ubuntu 23.10 and Debian 10: + * On Ubuntu 20.04, Ubuntu 22.04, Ubuntu 24.04 and Debian 10: ``` $ make deb_psw_pkg ``` @@ -297,9 +297,9 @@ You can find the tools and libraries generated in the `build/linux` directory. ``` deb [trusted=yes arch=amd64] file:/PATH_TO_LOCAL_REPO jammy main ``` - * On Ubuntu 23.10: + * On Ubuntu 24.04: ``` - deb [trusted=yes arch=amd64] file:/PATH_TO_LOCAL_REPO mantic main + deb [trusted=yes arch=amd64] file:/PATH_TO_LOCAL_REPO noble main ``` * On Debian 10: ``` @@ -344,7 +344,7 @@ Install the Intel(R) SGX SDK * Ubuntu\* 20.04 LTS Desktop 64bits * Ubuntu\* 20.04 LTS Server 64bits * Ubuntu\* 22.04 LTS Server 64bits - * Ubuntu\* 23.10 Server 64bits + * Ubuntu\* 24.04 LTS Server 64bits * Red Hat Enterprise Linux Server release 9.2 64bits * CentOS Stream 9 64bits * CentOS 8.3 64bits @@ -357,7 +357,7 @@ Install the Intel(R) SGX SDK $ sudo apt-get install build-essential python3 $ sudo update-alternatives --install /usr/bin/python python /usr/bin/python3 1 ``` - * On Ubuntu 20.04, Ubuntu 22.04 and Ubuntu 23.10: + * On Ubuntu 20.04, Ubuntu 22.04 and Ubuntu 24.04: ``` $ sudo apt-get install build-essential python-is-python3 ``` @@ -435,7 +435,7 @@ Install the Intel(R) SGX PSW * Ubuntu\* 20.04 LTS Desktop 64bits * Ubuntu\* 20.04 LTS Server 64bits * Ubuntu\* 22.04 LTS Server 64bits - * Ubuntu\* 23.10 Server 64bits + * Ubuntu\* 24.04 LTS Server 64bits * Red Hat Enterprise Linux Server release 9.2 64bits * CentOS Stream 9 64bits * CentOS 8.3 64bits @@ -447,7 +447,7 @@ Install the Intel(R) SGX PSW - Configure the system with the **Intel SGX hardware enabled** option and install Intel(R) SGX driver in advance. See the earlier topic, *Build and Install the Intel(R) SGX Driver*, for information on how to install the Intel(R) SGX driver. - Install the library using the following command: - * On Ubuntu 20.04, Ubuntu 22.04, Ubuntu 23.10 and Debian 10: + * On Ubuntu 20.04, Ubuntu 22.04, Ubuntu 24.04 and Debian 10: ``` $ sudo apt-get install libssl-dev libcurl4-openssl-dev libprotobuf-dev ``` @@ -477,7 +477,7 @@ The SGX PSW provides 3 services: launch, EPID-based attestation, and algorithm a #### Using the local repo(recommended) -| |Ubuntu 20.04, Ubuntu 22.04, Ubuntu 23.10 and Debian 10|Red Hat Enterprise Linux 9.2, CentOS Stream 9, CentOS 8.3 and Anolis OS 8.6| SUSE Linux Enterprise Server 15| +| |Ubuntu 20.04, Ubuntu 22.04, Ubuntu 24.04 and Debian 10|Red Hat Enterprise Linux 9.2, CentOS Stream 9, CentOS 8.3 and Anolis OS 8.6| SUSE Linux Enterprise Server 15| | ------------ | ------------ | ------------ | ------------ | |launch service |apt-get install libsgx-launch libsgx-urts|yum install libsgx-launch libsgx-urts|zypper install libsgx-launch libsgx-urts| |EPID-based attestation service|apt-get install libsgx-epid libsgx-urts|yum install libsgx-epid libsgx-urts|zypper install libsgx-epid libsgx-urts| @@ -498,7 +498,7 @@ apt-get dist-upgrade -o Dpkg::Options::="--force-overwrite" ``` #### Configure the installation Some packages are configured with recommended dependency on other packages that are not required for certain usage. For instance, the background daemon is not required for container usage. It will be installed by default, but you can drop it by using the additional option during the installation. -* On Ubuntu 20.04, Ubuntu 22.04, Ubuntu 23.10 and Debian 10: +* On Ubuntu 20.04, Ubuntu 22.04, Ubuntu 24.04 and Debian 10: ``` --no-install-recommends ``` diff --git a/SampleCode/Cxx11SGXDemo/Makefile b/SampleCode/Cxx11SGXDemo/Makefile index be048aa72..1f91a1c53 100644 --- a/SampleCode/Cxx11SGXDemo/Makefile +++ b/SampleCode/Cxx11SGXDemo/Makefile @@ -37,21 +37,21 @@ SGX_ARCH ?= x64 SGX_DEBUG ?= 1 ifeq ($(shell getconf LONG_BIT), 32) - SGX_ARCH := x86 + SGX_ARCH := x86 else ifeq ($(findstring -m32, $(CXXFLAGS)), -m32) - SGX_ARCH := x86 + SGX_ARCH := x86 endif ifeq ($(SGX_ARCH), x86) - SGX_COMMON_FLAGS := -m32 - SGX_LIBRARY_PATH := $(SGX_SDK)/lib - SGX_ENCLAVE_SIGNER := $(SGX_SDK)/bin/x86/sgx_sign - SGX_EDGER8R := $(SGX_SDK)/bin/x86/sgx_edger8r + SGX_COMMON_FLAGS := -m32 + SGX_LIBRARY_PATH := $(SGX_SDK)/lib + SGX_ENCLAVE_SIGNER := $(SGX_SDK)/bin/x86/sgx_sign + SGX_EDGER8R := $(SGX_SDK)/bin/x86/sgx_edger8r else - SGX_COMMON_FLAGS := -m64 - SGX_LIBRARY_PATH := $(SGX_SDK)/lib64 - SGX_ENCLAVE_SIGNER := $(SGX_SDK)/bin/x64/sgx_sign - SGX_EDGER8R := $(SGX_SDK)/bin/x64/sgx_edger8r + SGX_COMMON_FLAGS := -m64 + SGX_LIBRARY_PATH := $(SGX_SDK)/lib64 + SGX_ENCLAVE_SIGNER := $(SGX_SDK)/bin/x64/sgx_sign + SGX_EDGER8R := $(SGX_SDK)/bin/x64/sgx_edger8r endif ifeq ($(SGX_DEBUG), 1) @@ -76,9 +76,9 @@ SGX_COMMON_CXXFLAGS := $(SGX_COMMON_FLAGS) -Wnon-virtual-dtor -std=c++11 ######## App Settings ######## ifneq ($(SGX_MODE), HW) - Urts_Library_Name := sgx_urts_sim + Urts_Library_Name := sgx_urts_sim else - Urts_Library_Name := sgx_urts + Urts_Library_Name := sgx_urts endif App_Cpp_Files := App/App.cpp $(wildcard App/TrustedLibrary/*.cpp) @@ -111,18 +111,18 @@ Enclave_Version_Script := Enclave/Enclave_debug.lds ifeq ($(SGX_MODE), HW) ifneq ($(SGX_DEBUG), 1) ifneq ($(SGX_PRERELEASE), 1) - # Choose to use 'Enclave.lds' for HW release mode - Enclave_Version_Script = Enclave/Enclave.lds + # Choose to use 'Enclave.lds' for HW release mode + Enclave_Version_Script = Enclave/Enclave.lds endif endif endif ifneq ($(SGX_MODE), HW) - Trts_Library_Name := sgx_trts_sim - Service_Library_Name := sgx_tservice_sim + Trts_Library_Name := sgx_trts_sim + Service_Library_Name := sgx_tservice_sim else - Trts_Library_Name := sgx_trts - Service_Library_Name := sgx_tservice + Trts_Library_Name := sgx_trts + Service_Library_Name := sgx_tservice endif Crypto_Library_Name := sgx_tcrypto @@ -160,19 +160,19 @@ Enclave_Test_Key := Enclave/Enclave_private_test.pem ifeq ($(SGX_MODE), HW) ifeq ($(SGX_DEBUG), 1) - Build_Mode = HW_DEBUG + Build_Mode = HW_DEBUG else ifeq ($(SGX_PRERELEASE), 1) - Build_Mode = HW_PRERELEASE + Build_Mode = HW_PRERELEASE else - Build_Mode = HW_RELEASE + Build_Mode = HW_RELEASE endif else ifeq ($(SGX_DEBUG), 1) - Build_Mode = SIM_DEBUG + Build_Mode = SIM_DEBUG else ifeq ($(SGX_PRERELEASE), 1) - Build_Mode = SIM_PRERELEASE + Build_Mode = SIM_PRERELEASE else - Build_Mode = SIM_RELEASE + Build_Mode = SIM_RELEASE endif endif diff --git a/SampleCode/Cxx14SGXDemo/Makefile b/SampleCode/Cxx14SGXDemo/Makefile index e0bfba4b5..1c71044b7 100644 --- a/SampleCode/Cxx14SGXDemo/Makefile +++ b/SampleCode/Cxx14SGXDemo/Makefile @@ -37,21 +37,21 @@ SGX_ARCH ?= x64 SGX_DEBUG ?= 1 ifeq ($(shell getconf LONG_BIT), 32) - SGX_ARCH := x86 + SGX_ARCH := x86 else ifeq ($(findstring -m32, $(CXXFLAGS)), -m32) - SGX_ARCH := x86 + SGX_ARCH := x86 endif ifeq ($(SGX_ARCH), x86) - SGX_COMMON_FLAGS := -m32 - SGX_LIBRARY_PATH := $(SGX_SDK)/lib - SGX_ENCLAVE_SIGNER := $(SGX_SDK)/bin/x86/sgx_sign - SGX_EDGER8R := $(SGX_SDK)/bin/x86/sgx_edger8r + SGX_COMMON_FLAGS := -m32 + SGX_LIBRARY_PATH := $(SGX_SDK)/lib + SGX_ENCLAVE_SIGNER := $(SGX_SDK)/bin/x86/sgx_sign + SGX_EDGER8R := $(SGX_SDK)/bin/x86/sgx_edger8r else - SGX_COMMON_FLAGS := -m64 - SGX_LIBRARY_PATH := $(SGX_SDK)/lib64 - SGX_ENCLAVE_SIGNER := $(SGX_SDK)/bin/x64/sgx_sign - SGX_EDGER8R := $(SGX_SDK)/bin/x64/sgx_edger8r + SGX_COMMON_FLAGS := -m64 + SGX_LIBRARY_PATH := $(SGX_SDK)/lib64 + SGX_ENCLAVE_SIGNER := $(SGX_SDK)/bin/x64/sgx_sign + SGX_EDGER8R := $(SGX_SDK)/bin/x64/sgx_edger8r endif ifeq ($(SGX_DEBUG), 1) @@ -76,9 +76,9 @@ SGX_COMMON_CXXFLAGS := $(SGX_COMMON_FLAGS) -Wnon-virtual-dtor -std=c++14 ######## App Settings ######## ifneq ($(SGX_MODE), HW) - Urts_Library_Name := sgx_urts_sim + Urts_Library_Name := sgx_urts_sim else - Urts_Library_Name := sgx_urts + Urts_Library_Name := sgx_urts endif App_Cpp_Files := App/App.cpp $(wildcard App/TrustedLibrary/*.cpp) @@ -111,18 +111,18 @@ Enclave_Version_Script := Enclave/Enclave_debug.lds ifeq ($(SGX_MODE), HW) ifneq ($(SGX_DEBUG), 1) ifneq ($(SGX_PRERELEASE), 1) - # Choose to use 'Enclave.lds' for HW release mode - Enclave_Version_Script = Enclave/Enclave.lds + # Choose to use 'Enclave.lds' for HW release mode + Enclave_Version_Script = Enclave/Enclave.lds endif endif endif ifneq ($(SGX_MODE), HW) - Trts_Library_Name := sgx_trts_sim - Service_Library_Name := sgx_tservice_sim + Trts_Library_Name := sgx_trts_sim + Service_Library_Name := sgx_tservice_sim else - Trts_Library_Name := sgx_trts - Service_Library_Name := sgx_tservice + Trts_Library_Name := sgx_trts + Service_Library_Name := sgx_tservice endif Crypto_Library_Name := sgx_tcrypto @@ -160,19 +160,19 @@ Enclave_Test_Key := Enclave/Enclave_private_test.pem ifeq ($(SGX_MODE), HW) ifeq ($(SGX_DEBUG), 1) - Build_Mode = HW_DEBUG + Build_Mode = HW_DEBUG else ifeq ($(SGX_PRERELEASE), 1) - Build_Mode = HW_PRERELEASE + Build_Mode = HW_PRERELEASE else - Build_Mode = HW_RELEASE + Build_Mode = HW_RELEASE endif else ifeq ($(SGX_DEBUG), 1) - Build_Mode = SIM_DEBUG + Build_Mode = SIM_DEBUG else ifeq ($(SGX_PRERELEASE), 1) - Build_Mode = SIM_PRERELEASE + Build_Mode = SIM_PRERELEASE else - Build_Mode = SIM_RELEASE + Build_Mode = SIM_RELEASE endif endif diff --git a/SampleCode/Cxx17SGXDemo/Makefile b/SampleCode/Cxx17SGXDemo/Makefile index e37726622..b97abd4a4 100644 --- a/SampleCode/Cxx17SGXDemo/Makefile +++ b/SampleCode/Cxx17SGXDemo/Makefile @@ -37,21 +37,21 @@ SGX_ARCH ?= x64 SGX_DEBUG ?= 1 ifeq ($(shell getconf LONG_BIT), 32) - SGX_ARCH := x86 + SGX_ARCH := x86 else ifeq ($(findstring -m32, $(CXXFLAGS)), -m32) - SGX_ARCH := x86 + SGX_ARCH := x86 endif ifeq ($(SGX_ARCH), x86) - SGX_COMMON_FLAGS := -m32 - SGX_LIBRARY_PATH := $(SGX_SDK)/lib - SGX_ENCLAVE_SIGNER := $(SGX_SDK)/bin/x86/sgx_sign - SGX_EDGER8R := $(SGX_SDK)/bin/x86/sgx_edger8r + SGX_COMMON_FLAGS := -m32 + SGX_LIBRARY_PATH := $(SGX_SDK)/lib + SGX_ENCLAVE_SIGNER := $(SGX_SDK)/bin/x86/sgx_sign + SGX_EDGER8R := $(SGX_SDK)/bin/x86/sgx_edger8r else - SGX_COMMON_FLAGS := -m64 - SGX_LIBRARY_PATH := $(SGX_SDK)/lib64 - SGX_ENCLAVE_SIGNER := $(SGX_SDK)/bin/x64/sgx_sign - SGX_EDGER8R := $(SGX_SDK)/bin/x64/sgx_edger8r + SGX_COMMON_FLAGS := -m64 + SGX_LIBRARY_PATH := $(SGX_SDK)/lib64 + SGX_ENCLAVE_SIGNER := $(SGX_SDK)/bin/x64/sgx_sign + SGX_EDGER8R := $(SGX_SDK)/bin/x64/sgx_edger8r endif ifeq ($(SGX_DEBUG), 1) @@ -76,9 +76,9 @@ SGX_COMMON_CXXFLAGS := $(SGX_COMMON_FLAGS) -Wnon-virtual-dtor -std=c++17 ######## App Settings ######## ifneq ($(SGX_MODE), HW) - Urts_Library_Name := sgx_urts_sim + Urts_Library_Name := sgx_urts_sim else - Urts_Library_Name := sgx_urts + Urts_Library_Name := sgx_urts endif App_Cpp_Files := App/App.cpp $(wildcard App/TrustedLibrary/*.cpp) @@ -111,18 +111,18 @@ Enclave_Version_Script := Enclave/Enclave_debug.lds ifeq ($(SGX_MODE), HW) ifneq ($(SGX_DEBUG), 1) ifneq ($(SGX_PRERELEASE), 1) - # Choose to use 'Enclave.lds' for HW release mode - Enclave_Version_Script = Enclave/Enclave.lds + # Choose to use 'Enclave.lds' for HW release mode + Enclave_Version_Script = Enclave/Enclave.lds endif endif endif ifneq ($(SGX_MODE), HW) - Trts_Library_Name := sgx_trts_sim - Service_Library_Name := sgx_tservice_sim + Trts_Library_Name := sgx_trts_sim + Service_Library_Name := sgx_tservice_sim else - Trts_Library_Name := sgx_trts - Service_Library_Name := sgx_tservice + Trts_Library_Name := sgx_trts + Service_Library_Name := sgx_tservice endif Crypto_Library_Name := sgx_tcrypto @@ -160,19 +160,19 @@ Enclave_Test_Key := Enclave/Enclave_private_test.pem ifeq ($(SGX_MODE), HW) ifeq ($(SGX_DEBUG), 1) - Build_Mode = HW_DEBUG + Build_Mode = HW_DEBUG else ifeq ($(SGX_PRERELEASE), 1) - Build_Mode = HW_PRERELEASE + Build_Mode = HW_PRERELEASE else - Build_Mode = HW_RELEASE + Build_Mode = HW_RELEASE endif else ifeq ($(SGX_DEBUG), 1) - Build_Mode = SIM_DEBUG + Build_Mode = SIM_DEBUG else ifeq ($(SGX_PRERELEASE), 1) - Build_Mode = SIM_PRERELEASE + Build_Mode = SIM_PRERELEASE else - Build_Mode = SIM_RELEASE + Build_Mode = SIM_RELEASE endif endif diff --git a/SampleCode/LocalAttestation/App/Makefile b/SampleCode/LocalAttestation/App/Makefile index b205778cc..d2ed9e534 100644 --- a/SampleCode/LocalAttestation/App/Makefile +++ b/SampleCode/LocalAttestation/App/Makefile @@ -36,9 +36,9 @@ TARGET = app RM = rm -f ifneq ($(SGX_MODE), HW) - URTS_LIB_NAME := sgx_urts_sim + URTS_LIB_NAME := sgx_urts_sim else - URTS_LIB_NAME := sgx_urts + URTS_LIB_NAME := sgx_urts endif INC:=-I$(SGX_SDK)/include -I../Include @@ -47,14 +47,14 @@ CXXFLAGS += $(INC) $(LIB) CFLAGS += $(INC) $(LIB) ifeq ($(SGX_DEBUG), 1) - CXXFLAGS += -DDEBUG -UNDEBUG -UEDEBUG - CFLAGS += -DDEBUG -UNDEBUG -UEDEBUG + CXXFLAGS += -DDEBUG -UNDEBUG -UEDEBUG + CFLAGS += -DDEBUG -UNDEBUG -UEDEBUG else ifeq ($(SGX_PRERELEASE), 1) - CXXFLAGS += -DEDEBUG -DNDEBUG -UDEBUG - CFLAGS += -DEDEBUG -DNDEBUG -UDEBUG + CXXFLAGS += -DEDEBUG -DNDEBUG -UDEBUG + CFLAGS += -DEDEBUG -DNDEBUG -UDEBUG else - CXXFLAGS += -DNDEBUG -UEDEBUG -UDEBUG - CFLAGS += -DNDEBUG -UEDEBUG -UDEBUG + CXXFLAGS += -DNDEBUG -UEDEBUG -UDEBUG + CFLAGS += -DNDEBUG -UEDEBUG -UDEBUG endif SRC_CPP=$(wildcard *.cpp) diff --git a/SampleCode/LocalAttestation/AppInitiator/Makefile b/SampleCode/LocalAttestation/AppInitiator/Makefile index 47f2d27bd..1aa545c1c 100644 --- a/SampleCode/LocalAttestation/AppInitiator/Makefile +++ b/SampleCode/LocalAttestation/AppInitiator/Makefile @@ -36,9 +36,9 @@ TARGET = appinitiator RM = rm -f ifneq ($(SGX_MODE), HW) - URTS_LIB_NAME := sgx_urts_sim + URTS_LIB_NAME := sgx_urts_sim else - URTS_LIB_NAME := sgx_urts + URTS_LIB_NAME := sgx_urts endif INC:=-I$(SGX_SDK)/include -I../Include diff --git a/SampleCode/LocalAttestation/AppResponder/CPServer.h b/SampleCode/LocalAttestation/AppResponder/CPServer.h index 3327f118b..76ace4bbe 100644 --- a/SampleCode/LocalAttestation/AppResponder/CPServer.h +++ b/SampleCode/LocalAttestation/AppResponder/CPServer.h @@ -37,9 +37,10 @@ class CPServer { public: - CPServer(CPTask* task) : m_cptask(task) - , m_server_sock_fd(-1) + CPServer(CPTask* task) : + m_server_sock_fd(-1) , m_shutdown(0) + , m_cptask(task) {} ~CPServer(){}; diff --git a/SampleCode/LocalAttestation/AppResponder/Makefile b/SampleCode/LocalAttestation/AppResponder/Makefile index 78b98b602..43666ae17 100644 --- a/SampleCode/LocalAttestation/AppResponder/Makefile +++ b/SampleCode/LocalAttestation/AppResponder/Makefile @@ -36,9 +36,9 @@ TARGET = appresponder RM = rm -f ifneq ($(SGX_MODE), HW) - URTS_LIB_NAME := sgx_urts_sim + URTS_LIB_NAME := sgx_urts_sim else - URTS_LIB_NAME := sgx_urts + URTS_LIB_NAME := sgx_urts endif INC:=-I$(SGX_SDK)/include -I../Include diff --git a/SampleCode/LocalAttestation/EnclaveInitiator/Makefile b/SampleCode/LocalAttestation/EnclaveInitiator/Makefile index cb52847f7..62ef733f3 100644 --- a/SampleCode/LocalAttestation/EnclaveInitiator/Makefile +++ b/SampleCode/LocalAttestation/EnclaveInitiator/Makefile @@ -87,15 +87,15 @@ Enclave_Include_Paths := -I$(SGX_SDK)/include -I$(SGX_SDK)/include/tlibc -I$(SGX Enclave_C_Flags := $(Enclave_Include_Paths) -nostdinc -fvisibility=hidden -fpie -ffunction-sections -fdata-sections CC_BELOW_4_9 := $(shell expr "`$(CC) -dumpversion`" \< "4.9") ifeq ($(CC_BELOW_4_9), 1) - Enclave_C_Flags += -fstack-protector + Enclave_C_Flags += -fstack-protector else - Enclave_C_Flags += -fstack-protector-strong + Enclave_C_Flags += -fstack-protector-strong endif Enclave_Cpp_Flags := $(Enclave_C_Flags) -nostdinc++ ifeq ($(LAv2), 1) - Enclave_C_Flags += -DSGX_USE_LAv2_INITIATOR - Enclave_Cpp_Flags += -DSGX_USE_LAv2_INITIATOR + Enclave_C_Flags += -DSGX_USE_LAv2_INITIATOR + Enclave_Cpp_Flags += -DSGX_USE_LAv2_INITIATOR endif Enclave_Cpp_Files := $(wildcard *.cpp) diff --git a/SampleCode/LocalAttestation/Makefile b/SampleCode/LocalAttestation/Makefile index 8ec307924..8c3632846 100644 --- a/SampleCode/LocalAttestation/Makefile +++ b/SampleCode/LocalAttestation/Makefile @@ -33,21 +33,21 @@ include buildenv.mk ifeq ($(SGX_MODE), HW) ifeq ($(SGX_DEBUG), 1) - Build_Mode = HW_DEBUG + Build_Mode = HW_DEBUG else ifeq ($(SGX_PRERELEASE), 1) - Build_Mode = HW_PRERELEASE + Build_Mode = HW_PRERELEASE else - Build_Mode = HW_RELEASE + Build_Mode = HW_RELEASE endif endif ifeq ($(SGX_MODE), SIM) ifeq ($(SGX_DEBUG), 1) - Build_Mode = SIM_DEBUG + Build_Mode = SIM_DEBUG else ifeq ($(SGX_PRERELEASE), 1) - Build_Mode = SIM_PRERELEASE + Build_Mode = SIM_PRERELEASE else - Build_Mode = SIM_RELEASE + Build_Mode = SIM_RELEASE endif endif diff --git a/SampleCode/PowerTransition/Makefile b/SampleCode/PowerTransition/Makefile index 780f7e5be..468374974 100644 --- a/SampleCode/PowerTransition/Makefile +++ b/SampleCode/PowerTransition/Makefile @@ -37,21 +37,21 @@ SGX_ARCH ?= x64 SGX_DEBUG ?= 1 ifeq ($(shell getconf LONG_BIT), 32) - SGX_ARCH := x86 + SGX_ARCH := x86 else ifeq ($(findstring -m32, $(CXXFLAGS)), -m32) - SGX_ARCH := x86 + SGX_ARCH := x86 endif ifeq ($(SGX_ARCH), x86) - SGX_COMMON_FLAGS := -m32 - SGX_LIBRARY_PATH := $(SGX_SDK)/lib - SGX_ENCLAVE_SIGNER := $(SGX_SDK)/bin/x86/sgx_sign - SGX_EDGER8R := $(SGX_SDK)/bin/x86/sgx_edger8r + SGX_COMMON_FLAGS := -m32 + SGX_LIBRARY_PATH := $(SGX_SDK)/lib + SGX_ENCLAVE_SIGNER := $(SGX_SDK)/bin/x86/sgx_sign + SGX_EDGER8R := $(SGX_SDK)/bin/x86/sgx_edger8r else - SGX_COMMON_FLAGS := -m64 - SGX_LIBRARY_PATH := $(SGX_SDK)/lib64 - SGX_ENCLAVE_SIGNER := $(SGX_SDK)/bin/x64/sgx_sign - SGX_EDGER8R := $(SGX_SDK)/bin/x64/sgx_edger8r + SGX_COMMON_FLAGS := -m64 + SGX_LIBRARY_PATH := $(SGX_SDK)/lib64 + SGX_ENCLAVE_SIGNER := $(SGX_SDK)/bin/x64/sgx_sign + SGX_EDGER8R := $(SGX_SDK)/bin/x64/sgx_edger8r endif ifeq ($(SGX_DEBUG), 1) @@ -61,9 +61,9 @@ endif endif ifeq ($(SGX_DEBUG), 1) - SGX_COMMON_FLAGS += -O0 -g + SGX_COMMON_FLAGS += -O0 -g else - SGX_COMMON_FLAGS += -O2 + SGX_COMMON_FLAGS += -O2 endif SGX_COMMON_FLAGS += -Wall -Wextra -Winit-self -Wpointer-arith -Wreturn-type \ @@ -76,9 +76,9 @@ SGX_COMMON_CXXFLAGS := $(SGX_COMMON_FLAGS) -Wnon-virtual-dtor -std=c++11 ######## App Settings ######## ifneq ($(SGX_MODE), HW) - Urts_Library_Name := sgx_urts_sim + Urts_Library_Name := sgx_urts_sim else - Urts_Library_Name := sgx_urts + Urts_Library_Name := sgx_urts endif App_Cpp_Files := $(wildcard App/*.cpp) @@ -111,11 +111,11 @@ App_Name := app ######## Enclave Settings ######## ifneq ($(SGX_MODE), HW) - Trts_Library_Name := sgx_trts_sim - Service_Library_Name := sgx_tservice_sim + Trts_Library_Name := sgx_trts_sim + Service_Library_Name := sgx_tservice_sim else - Trts_Library_Name := sgx_trts - Service_Library_Name := sgx_tservice + Trts_Library_Name := sgx_trts + Service_Library_Name := sgx_tservice endif Crypto_Library_Name := sgx_tcrypto @@ -125,9 +125,9 @@ Enclave_Include_Paths := -I$(SGX_SDK)/include -I$(SGX_SDK)/include/tlibc -I$(SGX CC_BELOW_4_9 := $(shell expr "`$(CC) -dumpversion`" \< "4.9") ifeq ($(CC_BELOW_4_9), 1) - Enclave_Compile_CFlags := -fstack-protector + Enclave_Compile_CFlags := -fstack-protector else - Enclave_Compile_CFlags := -fstack-protector-strong + Enclave_Compile_CFlags := -fstack-protector-strong endif Enclave_Compile_CFlags += -nostdinc -ffreestanding -fvisibility=hidden -fpie -ffunction-sections -fdata-sections $(Enclave_Include_Paths) Enclave_Compile_CXXFlags := -nostdinc++ $(Enclave_Compile_CFlags) @@ -162,19 +162,19 @@ Enclave_Test_Key := Enclave/Enclave_private_test.pem ifeq ($(SGX_MODE), HW) ifeq ($(SGX_DEBUG), 1) - Build_Mode = HW_DEBUG + Build_Mode = HW_DEBUG else ifeq ($(SGX_PRERELEASE), 1) - Build_Mode = HW_PRERELEASE + Build_Mode = HW_PRERELEASE else - Build_Mode = HW_RELEASE + Build_Mode = HW_RELEASE endif else ifeq ($(SGX_DEBUG), 1) - Build_Mode = SIM_DEBUG + Build_Mode = SIM_DEBUG else ifeq ($(SGX_PRERELEASE), 1) - Build_Mode = SIM_PRERELEASE + Build_Mode = SIM_PRERELEASE else - Build_Mode = SIM_RELEASE + Build_Mode = SIM_RELEASE endif endif diff --git a/SampleCode/ProtobufSGXDemo/Makefile b/SampleCode/ProtobufSGXDemo/Makefile index 5a9adda41..96aa14b7a 100644 --- a/SampleCode/ProtobufSGXDemo/Makefile +++ b/SampleCode/ProtobufSGXDemo/Makefile @@ -37,23 +37,23 @@ SGX_ARCH ?= x64 SGX_DEBUG ?= 1 ifeq ($(shell getconf LONG_BIT), 32) - SGX_ARCH := x86 + SGX_ARCH := x86 else ifeq ($(findstring -m32, $(CXXFLAGS)), -m32) - SGX_ARCH := x86 + SGX_ARCH := x86 endif ifeq ($(SGX_ARCH), x86) - SGX_COMMON_FLAGS := -m32 - SGX_LIBRARY_PATH := $(SGX_SDK)/lib - SGX_ENCLAVE_SIGNER := $(SGX_SDK)/bin/x86/sgx_sign - SGX_EDGER8R := $(SGX_SDK)/bin/x86/sgx_edger8r - SGX_PROTOC := $(SGX_SDK)/bin/x86/sgx_protoc + SGX_COMMON_FLAGS := -m32 + SGX_LIBRARY_PATH := $(SGX_SDK)/lib + SGX_ENCLAVE_SIGNER := $(SGX_SDK)/bin/x86/sgx_sign + SGX_EDGER8R := $(SGX_SDK)/bin/x86/sgx_edger8r + SGX_PROTOC := $(SGX_SDK)/bin/x86/sgx_protoc else - SGX_COMMON_FLAGS := -m64 - SGX_LIBRARY_PATH := $(SGX_SDK)/lib64 - SGX_ENCLAVE_SIGNER := $(SGX_SDK)/bin/x64/sgx_sign - SGX_EDGER8R := $(SGX_SDK)/bin/x64/sgx_edger8r - SGX_PROTOC := $(SGX_SDK)/bin/x64/sgx_protoc + SGX_COMMON_FLAGS := -m64 + SGX_LIBRARY_PATH := $(SGX_SDK)/lib64 + SGX_ENCLAVE_SIGNER := $(SGX_SDK)/bin/x64/sgx_sign + SGX_EDGER8R := $(SGX_SDK)/bin/x64/sgx_edger8r + SGX_PROTOC := $(SGX_SDK)/bin/x64/sgx_protoc endif ifeq ($(SGX_DEBUG), 1) @@ -86,9 +86,9 @@ endif ######## App Settings ######## ifneq ($(SGX_MODE), HW) - Urts_Library_Name := sgx_urts_sim + Urts_Library_Name := sgx_urts_sim else - Urts_Library_Name := sgx_urts + Urts_Library_Name := sgx_urts endif App_Cpp_Files := App/App.cpp @@ -121,18 +121,18 @@ Enclave_Version_Script := Enclave/Enclave_debug.lds ifeq ($(SGX_MODE), HW) ifneq ($(SGX_DEBUG), 1) ifneq ($(SGX_PRERELEASE), 1) - # Choose to use 'Enclave.lds' for HW release mode - Enclave_Version_Script = Enclave/Enclave.lds + # Choose to use 'Enclave.lds' for HW release mode + Enclave_Version_Script = Enclave/Enclave.lds endif endif endif ifneq ($(SGX_MODE), HW) - Trts_Library_Name := sgx_trts_sim - Service_Library_Name := sgx_tservice_sim + Trts_Library_Name := sgx_trts_sim + Service_Library_Name := sgx_tservice_sim else - Trts_Library_Name := sgx_trts - Service_Library_Name := sgx_tservice + Trts_Library_Name := sgx_trts + Service_Library_Name := sgx_tservice endif Crypto_Library_Name := sgx_tcrypto @@ -170,19 +170,19 @@ Enclave_Test_Key := Enclave/Enclave_private_test.pem ifeq ($(SGX_MODE), HW) ifeq ($(SGX_DEBUG), 1) - Build_Mode = HW_DEBUG + Build_Mode = HW_DEBUG else ifeq ($(SGX_PRERELEASE), 1) - Build_Mode = HW_PRERELEASE + Build_Mode = HW_PRERELEASE else - Build_Mode = HW_RELEASE + Build_Mode = HW_RELEASE endif else ifeq ($(SGX_DEBUG), 1) - Build_Mode = SIM_DEBUG + Build_Mode = SIM_DEBUG else ifeq ($(SGX_PRERELEASE), 1) - Build_Mode = SIM_PRERELEASE + Build_Mode = SIM_PRERELEASE else - Build_Mode = SIM_RELEASE + Build_Mode = SIM_RELEASE endif endif diff --git a/SampleCode/RemoteAttestation/Makefile b/SampleCode/RemoteAttestation/Makefile index 9b9f5aae1..3c887f1ef 100644 --- a/SampleCode/RemoteAttestation/Makefile +++ b/SampleCode/RemoteAttestation/Makefile @@ -37,21 +37,21 @@ SGX_ARCH ?= x64 SGX_DEBUG ?= 1 ifeq ($(shell getconf LONG_BIT), 32) - SGX_ARCH := x86 + SGX_ARCH := x86 else ifeq ($(findstring -m32, $(CXXFLAGS)), -m32) - SGX_ARCH := x86 + SGX_ARCH := x86 endif ifeq ($(SGX_ARCH), x86) - SGX_COMMON_FLAGS := -m32 - SGX_LIBRARY_PATH := $(SGX_SDK)/lib - SGX_ENCLAVE_SIGNER := $(SGX_SDK)/bin/x86/sgx_sign - SGX_EDGER8R := $(SGX_SDK)/bin/x86/sgx_edger8r + SGX_COMMON_FLAGS := -m32 + SGX_LIBRARY_PATH := $(SGX_SDK)/lib + SGX_ENCLAVE_SIGNER := $(SGX_SDK)/bin/x86/sgx_sign + SGX_EDGER8R := $(SGX_SDK)/bin/x86/sgx_edger8r else - SGX_COMMON_FLAGS := -m64 - SGX_LIBRARY_PATH := $(SGX_SDK)/lib64 - SGX_ENCLAVE_SIGNER := $(SGX_SDK)/bin/x64/sgx_sign - SGX_EDGER8R := $(SGX_SDK)/bin/x64/sgx_edger8r + SGX_COMMON_FLAGS := -m64 + SGX_LIBRARY_PATH := $(SGX_SDK)/lib64 + SGX_ENCLAVE_SIGNER := $(SGX_SDK)/bin/x64/sgx_sign + SGX_EDGER8R := $(SGX_SDK)/bin/x64/sgx_edger8r endif ifeq ($(SGX_DEBUG), 1) @@ -80,9 +80,9 @@ SGX_COMMON_CXXFLAGS := $(SGX_COMMON_FLAGS) -Wnon-virtual-dtor -std=c++11 ######## App Settings ######## ifneq ($(SGX_MODE), HW) - Urts_Library_Name := sgx_urts_sim + Urts_Library_Name := sgx_urts_sim else - Urts_Library_Name := sgx_urts + Urts_Library_Name := sgx_urts endif App_Cpp_Files := isv_app/isv_app.cpp @@ -106,9 +106,9 @@ App_Cpp_Flags := $(App_C_Flags) App_Link_Flags := -L$(SGX_LIBRARY_PATH) -l$(Urts_Library_Name) -L. -lsgx_ukey_exchange -lpthread -lservice_provider -Wl,-rpath=$(CURDIR)/sample_libcrypto -Wl,-rpath=$(CURDIR) ifneq ($(SGX_MODE), HW) - App_Link_Flags += -lsgx_epid_sim -lsgx_quote_ex_sim + App_Link_Flags += -lsgx_epid_sim -lsgx_quote_ex_sim else - App_Link_Flags += -lsgx_epid -lsgx_quote_ex + App_Link_Flags += -lsgx_epid -lsgx_quote_ex endif App_Cpp_Objects := $(App_Cpp_Files:.cpp=.o) @@ -129,11 +129,11 @@ ServiceProvider_Cpp_Objects := $(ServiceProvider_Cpp_Files:.cpp=.o) ######## Enclave Settings ######## ifneq ($(SGX_MODE), HW) - Trts_Library_Name := sgx_trts_sim - Service_Library_Name := sgx_tservice_sim + Trts_Library_Name := sgx_trts_sim + Service_Library_Name := sgx_tservice_sim else - Trts_Library_Name := sgx_trts - Service_Library_Name := sgx_tservice + Trts_Library_Name := sgx_trts + Service_Library_Name := sgx_tservice endif Crypto_Library_Name := sgx_tcrypto @@ -143,9 +143,9 @@ Enclave_Include_Paths := -I$(SGX_SDK)/include -I$(SGX_SDK)/include/tlibc -I$(SGX Enclave_C_Flags := $(Enclave_Include_Paths) -nostdinc -fvisibility=hidden -fpie -ffunction-sections -fdata-sections CC_BELOW_4_9 := $(shell expr "`$(CC) -dumpversion`" \< "4.9") ifeq ($(CC_BELOW_4_9), 1) - Enclave_C_Flags += -fstack-protector + Enclave_C_Flags += -fstack-protector else - Enclave_C_Flags += -fstack-protector-strong + Enclave_C_Flags += -fstack-protector-strong endif Enclave_Cpp_Flags := $(Enclave_C_Flags) -nostdinc++ @@ -177,19 +177,19 @@ Enclave_Test_Key := isv_enclave/isv_enclave_private_test.pem ifeq ($(SGX_MODE), HW) ifeq ($(SGX_DEBUG), 1) - Build_Mode = HW_DEBUG + Build_Mode = HW_DEBUG else ifeq ($(SGX_PRERELEASE), 1) - Build_Mode = HW_PRERELEASE + Build_Mode = HW_PRERELEASE else - Build_Mode = HW_RELEASE + Build_Mode = HW_RELEASE endif else ifeq ($(SGX_DEBUG), 1) - Build_Mode = SIM_DEBUG + Build_Mode = SIM_DEBUG else ifeq ($(SGX_PRERELEASE), 1) - Build_Mode = SIM_PRERELEASE + Build_Mode = SIM_PRERELEASE else - Build_Mode = SIM_RELEASE + Build_Mode = SIM_RELEASE endif endif diff --git a/SampleCode/SampleAEXNotify/Makefile b/SampleCode/SampleAEXNotify/Makefile index 289d8ca79..f5549fa87 100644 --- a/SampleCode/SampleAEXNotify/Makefile +++ b/SampleCode/SampleAEXNotify/Makefile @@ -39,21 +39,21 @@ SGX_DEBUG ?= 1 include $(SGX_SDK)/buildenv.mk ifeq ($(shell getconf LONG_BIT), 32) - SGX_ARCH := x86 + SGX_ARCH := x86 else ifeq ($(findstring -m32, $(CXXFLAGS)), -m32) - SGX_ARCH := x86 + SGX_ARCH := x86 endif ifeq ($(SGX_ARCH), x86) - SGX_COMMON_FLAGS := -m32 - SGX_LIBRARY_PATH := $(SGX_SDK)/lib - SGX_ENCLAVE_SIGNER := $(SGX_SDK)/bin/x86/sgx_sign - SGX_EDGER8R := $(SGX_SDK)/bin/x86/sgx_edger8r + SGX_COMMON_FLAGS := -m32 + SGX_LIBRARY_PATH := $(SGX_SDK)/lib + SGX_ENCLAVE_SIGNER := $(SGX_SDK)/bin/x86/sgx_sign + SGX_EDGER8R := $(SGX_SDK)/bin/x86/sgx_edger8r else - SGX_COMMON_FLAGS := -m64 - SGX_LIBRARY_PATH := $(SGX_SDK)/lib64 - SGX_ENCLAVE_SIGNER := $(SGX_SDK)/bin/x64/sgx_sign - SGX_EDGER8R := $(SGX_SDK)/bin/x64/sgx_edger8r + SGX_COMMON_FLAGS := -m64 + SGX_LIBRARY_PATH := $(SGX_SDK)/lib64 + SGX_ENCLAVE_SIGNER := $(SGX_SDK)/bin/x64/sgx_sign + SGX_EDGER8R := $(SGX_SDK)/bin/x64/sgx_edger8r endif ifeq ($(SGX_DEBUG), 1) @@ -67,9 +67,9 @@ $(error Only support HW mode for AEX Notify!!) endif ifeq ($(SGX_DEBUG), 1) - SGX_COMMON_FLAGS += -O0 -g + SGX_COMMON_FLAGS += -O0 -g else - SGX_COMMON_FLAGS += -O2 + SGX_COMMON_FLAGS += -O2 endif SGX_COMMON_FLAGS += -Wall -Wextra -Winit-self -Wpointer-arith -Wreturn-type \ @@ -93,11 +93,11 @@ App_C_Flags := -fPIC -Wno-attributes $(App_Include_Paths) # Prerelease - Macro NDEBUG and EDEBUG enabled. # Release - Macro NDEBUG enabled. ifeq ($(SGX_DEBUG), 1) - App_C_Flags += -DDEBUG -UNDEBUG -UEDEBUG + App_C_Flags += -DDEBUG -UNDEBUG -UEDEBUG else ifeq ($(SGX_PRERELEASE), 1) - App_C_Flags += -DNDEBUG -DEDEBUG -UDEBUG + App_C_Flags += -DNDEBUG -DEDEBUG -UDEBUG else - App_C_Flags += -DNDEBUG -UEDEBUG -UDEBUG + App_C_Flags += -DNDEBUG -UEDEBUG -UDEBUG endif App_Cpp_Flags := $(App_C_Flags) @@ -120,9 +120,9 @@ Enclave_Include_Paths := -IInclude -IEnclave -I$(SGX_SDK)/include -I$(SGX_SDK)/i Enclave_C_Flags := $(Enclave_Include_Paths) -nostdinc -fvisibility=hidden -fpie -ffunction-sections -fdata-sections $(MITIGATION_CFLAGS) CC_BELOW_4_9 := $(shell expr "`$(CC) -dumpversion`" \< "4.9") ifeq ($(CC_BELOW_4_9), 1) - Enclave_C_Flags += -fstack-protector + Enclave_C_Flags += -fstack-protector else - Enclave_C_Flags += -fstack-protector-strong + Enclave_C_Flags += -fstack-protector-strong endif Enclave_Cpp_Flags := $(Enclave_C_Flags) -nostdinc++ @@ -155,11 +155,11 @@ Enclave_Test_Key := Enclave/Enclave_private_test.pem ifeq ($(SGX_MODE), HW) ifeq ($(SGX_DEBUG), 1) - Build_Mode = HW_DEBUG + Build_Mode = HW_DEBUG else ifeq ($(SGX_PRERELEASE), 1) - Build_Mode = HW_PRERELEASE + Build_Mode = HW_PRERELEASE else - Build_Mode = HW_RELEASE + Build_Mode = HW_RELEASE endif endif diff --git a/SampleCode/SampleAttestedTLS/prepare_sgxssl.sh b/SampleCode/SampleAttestedTLS/prepare_sgxssl.sh index 37f3e43d5..451710084 100755 --- a/SampleCode/SampleAttestedTLS/prepare_sgxssl.sh +++ b/SampleCode/SampleAttestedTLS/prepare_sgxssl.sh @@ -35,13 +35,13 @@ project_dir="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" echo "project_dir is $project_dir" sgxssl_dir=$project_dir/sgxssl openssl_out_dir=$sgxssl_dir/openssl_source -openssl_ver_name=openssl-3.0.10 +openssl_ver_name=openssl-3.0.13 intel_sgx_ssl_url=https://github.com/intel/intel-sgx-ssl support_tls_branch=support_tls_openssl3 build_script=$sgxssl_dir/Linux/build_openssl.sh server_url_path=https://www.openssl.org/source full_openssl_url=$server_url_path/$openssl_ver_name.tar.gz -full_openssl_url_old=$server_url_path/old/3.0.10/$openssl_ver_name.tar.gz +full_openssl_url_old=$server_url_path/old/3.0.13/$openssl_ver_name.tar.gz FileExists() { pushd $sgxssl_dir/Linux/ @@ -62,7 +62,7 @@ if [ $debug == true ] ; then read -n 1 -p "download souce code only, because we need to build ourselves" fi -openssl_chksum=1761d4f5b13a1028b9b6f3d4b8e17feb0cedc9370f6afe61d7193d2cdce83323 +openssl_chksum=88525753f79d3bec27d2fa7c66aa0b92b3aa9498dafd93d7cfa4b3780cdae313 rm -f check_sum_openssl.txt if [ ! -f $build_script ]; then git clone $intel_sgx_ssl_url -b $support_tls_branch $sgxssl_dir || exit 1 diff --git a/SampleCode/SampleDNNL/Makefile b/SampleCode/SampleDNNL/Makefile index dc46173aa..210a20fda 100644 --- a/SampleCode/SampleDNNL/Makefile +++ b/SampleCode/SampleDNNL/Makefile @@ -37,9 +37,9 @@ SGX_ARCH ?= x64 SGX_DEBUG ?= 1 ifeq ($(shell getconf LONG_BIT), 32) - SGX_ARCH := x86 + SGX_ARCH := x86 else ifeq ($(findstring -m32, $(CXXFLAGS)), -m32) - SGX_ARCH := x86 + SGX_ARCH := x86 endif SGX_COMMON_FLAGS := -m64 @@ -54,9 +54,9 @@ endif endif ifeq ($(SGX_DEBUG), 1) - SGX_COMMON_FLAGS += -O0 -g + SGX_COMMON_FLAGS += -O0 -g else - SGX_COMMON_FLAGS += -O2 + SGX_COMMON_FLAGS += -O2 endif SGX_COMMON_FLAGS += -Wall -Wextra -Winit-self -Wpointer-arith -Wreturn-type \ @@ -104,11 +104,11 @@ App_Name := app ######## Enclave Settings ######## ifneq ($(SGX_MODE), HW) - Trts_Library_Name := sgx_trts_sim - Service_Library_Name := sgx_tservice_sim + Trts_Library_Name := sgx_trts_sim + Service_Library_Name := sgx_tservice_sim else - Trts_Library_Name := sgx_trts - Service_Library_Name := sgx_tservice + Trts_Library_Name := sgx_trts + Service_Library_Name := sgx_tservice endif Crypto_Library_Name := sgx_tcrypto @@ -121,9 +121,9 @@ Enclave_Include_Paths += -I$(SGX_SDK)/include/libcxx CC_BELOW_4_9 := $(shell expr "`$(CC) -dumpversion`" \< "4.9") ifeq ($(CC_BELOW_4_9), 1) - Enclave_Compile_CFlags := -fstack-protector + Enclave_Compile_CFlags := -fstack-protector else - Enclave_Compile_CFlags := -fstack-protector-strong + Enclave_Compile_CFlags := -fstack-protector-strong endif Enclave_Compile_CFlags += -nostdinc -ffreestanding -fvisibility=hidden -fpie -ffunction-sections -fdata-sections $(Enclave_Include_Paths) -fomit-frame-pointer -fno-builtin-printf Enclave_Compile_CXXFlags := -nostdinc++ $(Enclave_Compile_CFlags) -fomit-frame-pointer @@ -160,19 +160,19 @@ Enclave_Test_Key := Enclave/Enclave_private_test.pem ifeq ($(SGX_MODE), HW) ifeq ($(SGX_DEBUG), 1) - Build_Mode = HW_DEBUG + Build_Mode = HW_DEBUG else ifeq ($(SGX_PRERELEASE), 1) - Build_Mode = HW_PRERELEASE + Build_Mode = HW_PRERELEASE else - Build_Mode = HW_RELEASE + Build_Mode = HW_RELEASE endif else ifeq ($(SGX_DEBUG), 1) - Build_Mode = SIM_DEBUG + Build_Mode = SIM_DEBUG else ifeq ($(SGX_PRERELEASE), 1) - Build_Mode = SIM_PRERELEASE + Build_Mode = SIM_PRERELEASE else - Build_Mode = SIM_RELEASE + Build_Mode = SIM_RELEASE endif endif diff --git a/SampleCode/SampleEnclave/Makefile b/SampleCode/SampleEnclave/Makefile index f7b0af371..1d5a3d6e8 100644 --- a/SampleCode/SampleEnclave/Makefile +++ b/SampleCode/SampleEnclave/Makefile @@ -39,21 +39,21 @@ SGX_DEBUG ?= 1 include $(SGX_SDK)/buildenv.mk ifeq ($(shell getconf LONG_BIT), 32) - SGX_ARCH := x86 + SGX_ARCH := x86 else ifeq ($(findstring -m32, $(CXXFLAGS)), -m32) - SGX_ARCH := x86 + SGX_ARCH := x86 endif ifeq ($(SGX_ARCH), x86) - SGX_COMMON_FLAGS := -m32 - SGX_LIBRARY_PATH := $(SGX_SDK)/lib - SGX_ENCLAVE_SIGNER := $(SGX_SDK)/bin/x86/sgx_sign - SGX_EDGER8R := $(SGX_SDK)/bin/x86/sgx_edger8r + SGX_COMMON_FLAGS := -m32 + SGX_LIBRARY_PATH := $(SGX_SDK)/lib + SGX_ENCLAVE_SIGNER := $(SGX_SDK)/bin/x86/sgx_sign + SGX_EDGER8R := $(SGX_SDK)/bin/x86/sgx_edger8r else - SGX_COMMON_FLAGS := -m64 - SGX_LIBRARY_PATH := $(SGX_SDK)/lib64 - SGX_ENCLAVE_SIGNER := $(SGX_SDK)/bin/x64/sgx_sign - SGX_EDGER8R := $(SGX_SDK)/bin/x64/sgx_edger8r + SGX_COMMON_FLAGS := -m64 + SGX_LIBRARY_PATH := $(SGX_SDK)/lib64 + SGX_ENCLAVE_SIGNER := $(SGX_SDK)/bin/x64/sgx_sign + SGX_EDGER8R := $(SGX_SDK)/bin/x64/sgx_edger8r endif ifeq ($(SGX_DEBUG), 1) @@ -78,9 +78,9 @@ SGX_COMMON_CXXFLAGS := $(SGX_COMMON_FLAGS) -Wnon-virtual-dtor -std=c++11 ######## App Settings ######## ifneq ($(SGX_MODE), HW) - Urts_Library_Name := sgx_urts_sim + Urts_Library_Name := sgx_urts_sim else - Urts_Library_Name := sgx_urts + Urts_Library_Name := sgx_urts endif App_Cpp_Files := App/App.cpp $(wildcard App/Edger8rSyntax/*.cpp) $(wildcard App/TrustedLibrary/*.cpp) @@ -110,11 +110,11 @@ App_Name := app ######## Enclave Settings ######## ifneq ($(SGX_MODE), HW) - Trts_Library_Name := sgx_trts_sim - Service_Library_Name := sgx_tservice_sim + Trts_Library_Name := sgx_trts_sim + Service_Library_Name := sgx_tservice_sim else - Trts_Library_Name := sgx_trts - Service_Library_Name := sgx_tservice + Trts_Library_Name := sgx_trts + Service_Library_Name := sgx_tservice endif Crypto_Library_Name := sgx_tcrypto @@ -124,9 +124,9 @@ Enclave_Include_Paths := -IInclude -IEnclave -I$(SGX_SDK)/include -I$(SGX_SDK)/i Enclave_C_Flags := $(Enclave_Include_Paths) -nostdinc -fvisibility=hidden -fpie -ffunction-sections -fdata-sections $(MITIGATION_CFLAGS) CC_BELOW_4_9 := $(shell expr "`$(CC) -dumpversion`" \< "4.9") ifeq ($(CC_BELOW_4_9), 1) - Enclave_C_Flags += -fstack-protector + Enclave_C_Flags += -fstack-protector else - Enclave_C_Flags += -fstack-protector-strong + Enclave_C_Flags += -fstack-protector-strong endif Enclave_Cpp_Flags := $(Enclave_C_Flags) -nostdinc++ @@ -159,19 +159,19 @@ Enclave_Test_Key := Enclave/Enclave_private_test.pem ifeq ($(SGX_MODE), HW) ifeq ($(SGX_DEBUG), 1) - Build_Mode = HW_DEBUG + Build_Mode = HW_DEBUG else ifeq ($(SGX_PRERELEASE), 1) - Build_Mode = HW_PRERELEASE + Build_Mode = HW_PRERELEASE else - Build_Mode = HW_RELEASE + Build_Mode = HW_RELEASE endif else ifeq ($(SGX_DEBUG), 1) - Build_Mode = SIM_DEBUG + Build_Mode = SIM_DEBUG else ifeq ($(SGX_PRERELEASE), 1) - Build_Mode = SIM_PRERELEASE + Build_Mode = SIM_PRERELEASE else - Build_Mode = SIM_RELEASE + Build_Mode = SIM_RELEASE endif endif diff --git a/SampleCode/SampleEnclaveGMIPP/App/App.cpp b/SampleCode/SampleEnclaveGMIPP/App/App.cpp index c4ad71dae..6d314ac92 100644 --- a/SampleCode/SampleEnclaveGMIPP/App/App.cpp +++ b/SampleCode/SampleEnclaveGMIPP/App/App.cpp @@ -195,19 +195,19 @@ int ecall_sm2_sign_verify_functions() return rev; } -/* GM SM2 encrypt and decrypt functions(GM version) */ -int ecall_sm2_encrypt_decrypt_gm_functions() +/* GM SM2 key exchange functions */ +int ecall_sm2_key_exchange_functions() { int rev = -1; - ecall_sm2_encrypt_decrypt_gm(global_eid, &rev); + ecall_sm2_key_exchange(global_eid, &rev); return rev; } -/* GM SM2 encrypt and decrypt functions(IEEE version) */ -int ecall_sm2_encrypt_decrypt_ieee_functions() +/* GM SM2 encrypt and decrypt functions(GM version) */ +int ecall_sm2_encrypt_decrypt_gm_functions() { int rev = -1; - ecall_sm2_encrypt_decrypt_ieee(global_eid, &rev); + ecall_sm2_encrypt_decrypt_gm(global_eid, &rev); return rev; } @@ -256,16 +256,16 @@ int SGX_CDECL main(int argc, char *argv[]) else printf("GM SM2 - sign and verify: FAIL\n"); + if (ecall_sm2_key_exchange_functions() == 0) + printf("GM SM2 - key exchange: PASS\n"); + else + printf("GM SM2 - key exchange: FAIL\n"); + if (ecall_sm2_encrypt_decrypt_gm_functions() == 0) printf("GM SM2 - encrypt and decrypt(GM version): PASS\n"); else printf("GM SM2 - encrypt and decrypt(GM version): FAIL\n"); - if (ecall_sm2_encrypt_decrypt_ieee_functions() == 0) - printf("GM SM2 - encrypt and decrypt(IEEE version): PASS\n"); - else - printf("GM SM2 - encrypt and decrypt(IEEE version): FAIL\n"); - /* SM3 */ if (ecall_sm3_functions() == 0) printf("GM SM3 - compute digest of message: PASS\n"); diff --git a/SampleCode/SampleEnclaveGMIPP/App/App.h b/SampleCode/SampleEnclaveGMIPP/App/App.h index 2949a8b09..53b0b37a7 100644 --- a/SampleCode/SampleEnclaveGMIPP/App/App.h +++ b/SampleCode/SampleEnclaveGMIPP/App/App.h @@ -58,8 +58,8 @@ extern "C" { #endif int ecall_sm2_sign_verify_functions(void); +int ecall_sm2_key_exchange_functions(void); int ecall_sm2_encrypt_decrypt_gm_functions(void); -int ecall_sm2_encrypt_decrypt_ieee_functions(void); int ecall_sm3_functions(void); int ecall_sm4_cbc_functions(void); int ecall_sm4_ctr_functions(void); diff --git a/SampleCode/SampleEnclaveGMIPP/Enclave/Enclave.cpp b/SampleCode/SampleEnclaveGMIPP/Enclave/Enclave.cpp index e2ad3cdb8..11434272c 100644 --- a/SampleCode/SampleEnclaveGMIPP/Enclave/Enclave.cpp +++ b/SampleCode/SampleEnclaveGMIPP/Enclave/Enclave.cpp @@ -39,17 +39,27 @@ #include /* ipp library */ +const unsigned int order[] = {0x39D54123, 0x53BBF409, 0x21C6052B, 0x7203DF6B, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFE}; +const int ordSize = sizeof(order) / sizeof(unsigned int); + +//replace free() +#ifndef SAFE_FREE +#define SAFE_FREE(ptr) do {if (NULL != (ptr)) {free(ptr); (ptr) = NULL;}} while(0); +#endif + +//add a memset_s() for private key before free() +#ifndef SAEF_FREE_ECC_PRI_KEY +#define SAEF_FREE_ECC_PRI_KEY(ptr) do {int size; IppStatus status = ippStsNoErr; if ((NULL != (ptr))) {status = ippsBigNumGetSize(ordSize, &size); if (ippStsNoErr != status) {memset_s(ptr, size, 0, size);} free(ptr); (ptr) = NULL;}} while(0); +#endif + #ifndef SAFE_FREE_HEAP -#define SAFE_FREE_HEAP(ptr, size) do {if (NULL != (ptr)) {memset_s(ptr, size, 0, size); free(ptr); (ptr)=NULL;}} while(0); +#define SAFE_FREE_HEAP(ptr, size) do {if (NULL != (ptr)) {memset_s(ptr, size, 0, size); free(ptr); (ptr) = NULL;}} while(0); #endif #ifndef SAFE_FREE_STACK #define SAFE_FREE_STACK(ptr, size) do {if (NULL != (ptr)) {memset_s(ptr, size, 0, size);}} while(0); #endif -const unsigned int order[] = {0x39D54123, 0x53BBF409, 0x21C6052B, 0x7203DF6B, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFE}; -const int ordSize = sizeof(order) / sizeof(unsigned int); - /* * printf: * Invokes OCALL to display the enclave buffer to the terminal. @@ -183,1091 +193,689 @@ static int secure_rand(unsigned int* pX, int size) return 0; } -/* Define Pseudo-random generation context */ -static IppsPRNGState* new_PRNG(void) +/* Define a new random BN generator instead of IPP Crypto - ippsPRNGen */ +static IppStatus gen_random_BN(Ipp32u* pRand, int nBits, void* pCtx) { - int size = 0; - IppsPRNGState* pPRNG = NULL; - IppsBigNumState* pBN = NULL; - IppStatus ipp_ret = ippStsNoErr; - int seedBitsize = 160; - int seedSize = Bitsize2Wordsize(seedBitsize); - unsigned int* seed = NULL; - unsigned int* augm = NULL; - - ipp_ret = ippsPRNGGetSize(&size); - if (ipp_ret != ippStsNoErr) { - printf("Error: fail to get size of PRNG\n"); - return NULL; - } - - pPRNG = (IppsPRNGState*)malloc(size); - if (pPRNG == NULL) { - printf("Error: fail to allocate memory for PRNG\n"); - return NULL; + if (!pRand) { + printf("Error: pRand is NULL\n"); + return ippStsNullPtrErr; } - ipp_ret = ippsPRNGInit(seedBitsize, pPRNG); - if (ipp_ret != ippStsNoErr) { - printf("Error: fail to initialize PRNG\n"); - SAFE_FREE_HEAP(pPRNG, size); - return NULL; + if (0 != nBits % 8) { + printf("Error: nBits size is wrong\n"); + return ippStsSizeErr; } - seed = (unsigned int*)malloc(seedSize); - if (secure_rand(seed, seedSize) != 0) { - printf("Error: fail to generate a secure random number for seed\n"); - SAFE_FREE_HEAP(seed, seedSize); - return NULL; - } - ipp_ret = ippsPRNGSetSeed(pBN=new_BN(seedSize, seed), pPRNG); - if (ipp_ret != ippStsNoErr) { - printf("Error: fail to set the seed value of PRNG\n"); - SAFE_FREE_HEAP(pPRNG, size); - free(pBN); - SAFE_FREE_HEAP(seed, seedSize); - return NULL; - } - free(pBN); - augm = (unsigned int*)malloc(seedSize); - if (secure_rand(augm, seedSize) != 0) { - printf("Error: fail to generate a secure random number for augm\n"); - SAFE_FREE_HEAP(augm, seedSize); - return NULL; + if (SGX_SUCCESS != sgx_read_rand((uint8_t*)pRand, (uint32_t)nBits / 8)) { + printf("Error: fail to generate a pseudorandom unsigned big number of the specified bit length\n"); + return ippStsErr; } - ipp_ret = ippsPRNGSetAugment(pBN=new_BN(seedSize, augm), pPRNG); - if (ipp_ret != ippStsNoErr) { - printf("Error: fail to set the entropy augmentation of PRNG\n"); - SAFE_FREE_HEAP(pPRNG, size); - free(pBN); - SAFE_FREE_HEAP(augm, seedSize); - return NULL; - } - - free(pBN); - SAFE_FREE_HEAP(augm, seedSize); - SAFE_FREE_HEAP(seed, seedSize); - return pPRNG; + return ippStsNoErr; } -/* Calculate ZA = H256(ENTLA || IDA || a || b || xG || yG || xA || yA) */ -static int hash_digest_z(const IppsHashMethod *hash_method, const char *id, const int id_len, const IppsBigNumState *pubX, const IppsBigNumState *pubY, unsigned char *z_digest) +/* SM2 generate private key and public key */ +static int sm2_key_generation(IppsBigNumState** privateKey, IppsECCPPointState** publicKey) { - int ctx_size = 0; - IppsHashState_rmf* hash_handle = NULL; + IppsGFpECState *pEC = NULL; IppStatus ipp_ret = ippStsNoErr; int ret = 0; - int id_bit_len = id_len * 8; - unsigned char entl[2] = {0}; - entl[0] = (id_bit_len & 0xff00) >> 8; - entl[1] = id_bit_len & 0xff; - unsigned char a[32] = { - 0xff, 0xff, 0xff, 0xfe, 0xff, 0xff, 0xff, 0xff, - 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, - 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, - 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfc}; - unsigned char b[32] = { - 0x28, 0xe9, 0xfa, 0x9e, 0x9d, 0x9f, 0x5e, 0x34, - 0x4d, 0x5a, 0x9e, 0x4b, 0xcf, 0x65, 0x09, 0xa7, - 0xf3, 0x97, 0x89, 0xf5, 0x15, 0xab, 0x8f, 0x92, - 0xdd, 0xbc, 0xbd, 0x41, 0x4d, 0x94, 0x0e, 0x93}; - unsigned char xG[32] = { - 0x32, 0xc4, 0xae, 0x2c, 0x1f, 0x19, 0x81, 0x19, - 0x5f, 0x99, 0x04, 0x46, 0x6a, 0x39, 0xc9, 0x94, - 0x8f, 0xe3, 0x0b, 0xbf, 0xf2, 0x66, 0x0b, 0xe1, - 0x71, 0x5a, 0x45, 0x89, 0x33, 0x4c, 0x74, 0xc7}; - unsigned char yG[32] = { - 0xbc, 0x37, 0x36, 0xa2, 0xf4, 0xf6, 0x77, 0x9c, - 0x59, 0xbd, 0xce, 0xe3, 0x6b, 0x69, 0x21, 0x53, - 0xd0, 0xa9, 0x87, 0x7c, 0xc6, 0x2a, 0x47, 0x40, - 0x02, 0xdf, 0x32, 0xe5, 0x21, 0x39, 0xf0, 0xa0}; - unsigned char xA[32] = {0}; - unsigned char yA[32] = {0}; - do { - ipp_ret = ippsGetOctString_BN(xA, 32, pubX); - if (ipp_ret != ippStsNoErr) { - printf("Error: fail to Convert BN value pubX into octet string xA\n"); + // 1. Create ECC context for SM2 + pEC = (IppsGFpECState*)new_ECC_sm2(); + if (pEC == NULL) { + printf("Error: fail to create ecc context for sm2\n"); ret = -1; break; } - ipp_ret = ippsGetOctString_BN(yA, 32, pubY); - if (ipp_ret != ippStsNoErr) { - printf("Error: fail to Convert BN value pubY into octet string yA\n"); - ret = -2; - break; - } - - ipp_ret = ippsHashGetSize_rmf(&ctx_size); - if (ipp_ret != ippStsNoErr) - { - printf("Error: fail to get size of ippsHashGetSize_rmf\n"); - ret = -3; - break; - } - - hash_handle = (IppsHashState_rmf*)(malloc(ctx_size)); - if (!hash_handle) - { - printf("Error: fail to allocate memory for ippsHashGetSize_rmf\n"); - ret = -4; - break; - } - - // Set Hash 256 handler: - // SM3 - ippsHashMethod_SM3() - // SHA256 - ippsHashMethod_SHA256_TT() - ipp_ret = ippsHashInit_rmf(hash_handle, hash_method); - if (ipp_ret != ippStsNoErr) - { - printf("Error: fail to set hash 256 handler\n"); - ret = -5; - break; - } - - // ZA = H256(ENTLA || IDA || a || b || xG || yG || xA || yA) - ipp_ret = ippsHashUpdate_rmf(entl, sizeof(entl), hash_handle); - if (ipp_ret != ippStsNoErr) - { - printf("Error: fail to update hash value of ENTLA\n"); - ret = -6; - break; - } - ipp_ret = ippsHashUpdate_rmf((unsigned char*)id, id_len, hash_handle); - if (ipp_ret != ippStsNoErr) - { - printf("Error: fail to update hash value of IDA\n"); - ret = -7; - break; - } - ipp_ret = ippsHashUpdate_rmf(a, sizeof(a), hash_handle); - if (ipp_ret != ippStsNoErr) - { - printf("Error: fail to update hash value of a\n"); - ret = -8; - break; - } - ipp_ret = ippsHashUpdate_rmf(b, sizeof(b), hash_handle); - if (ipp_ret != ippStsNoErr) - { - printf("Error: fail to update hash value of b\n"); - ret = -9; - break; - } - ipp_ret = ippsHashUpdate_rmf(xG, sizeof(xG), hash_handle); - if (ipp_ret != ippStsNoErr) - { - printf("Error: fail to update hash value of xG\n"); - ret = -10; - break; - } - ipp_ret = ippsHashUpdate_rmf(yG, sizeof(yG), hash_handle); - if (ipp_ret != ippStsNoErr) - { - printf("Error: fail to update hash value of yG\n"); - ret = -11; - break; - } - ipp_ret = ippsHashUpdate_rmf(xA, sizeof(xA), hash_handle); - if (ipp_ret != ippStsNoErr) - { - printf("Error: fail to update hash value of xA\n"); - ret = -12; - break; - } - ipp_ret = ippsHashUpdate_rmf(yA, sizeof(yA), hash_handle); - if (ipp_ret != ippStsNoErr) - { - printf("Error: fail to update hash value of yA\n"); - ret = -13; - break; - } - ipp_ret = ippsHashFinal_rmf(z_digest, hash_handle); - if (ipp_ret != ippStsNoErr) - { - printf("Error: fail to complete message digesting and return digest\n"); - ret = -14; - break; - } - } while(0); - - SAFE_FREE_HEAP(hash_handle, ctx_size); - - return ret; -} - -/* Calculate ZA = H256(Z||M) */ -static int hash_digest_with_preprocess(const IppsHashMethod *hash_method, const char *msg, const int msg_len, const char *id, const int id_len, const IppsBigNumState* pubX, const IppsBigNumState* pubY, unsigned char *digest) -{ - int ctx_size = 0; - IppsHashState_rmf* hash_handle = NULL; - IppStatus ipp_ret = ippStsNoErr; - int ret = 0; - unsigned char z_digest[32] = {0}; - - do { - ret = hash_digest_z(hash_method, id, id_len, pubX, pubY, z_digest); - if (ret != 0) - { - printf("Error: fail to complete SM3 digest of leading data Z\n"); - return -1; - break; - } - ipp_ret = ippsHashGetSize_rmf(&ctx_size); - if (ipp_ret != ippStsNoErr) - { - printf("Error: fail to get size of IppsHashState_rmf\n"); + // 2. Generate private key and public key + *privateKey = new_BN(ordSize, 0); + if (*privateKey == NULL) { + printf("Error: fail to declare private key\n"); ret = -2; break; } - - hash_handle = (IppsHashState_rmf*)(malloc(ctx_size)); - if (!hash_handle) - { - printf("Error: fail to allocate memory for IppsHashState_rmf\n"); + *publicKey = new_ECC_Point(); + if (*publicKey == NULL) { + printf("Error: fail to declare public key\n"); ret = -3; break; } - - // Set Hash 256 handler: - // SM3 - ippsHashMethod_SM3() - // SHA256 - ippsHashMethod_SHA256_TT() - ipp_ret = ippsHashInit_rmf(hash_handle, hash_method); - if (ipp_ret != ippStsNoErr) - { - printf("Error: fail to initialize IppsHashState_rmf\n"); + ipp_ret = ippsECCPGenKeyPair(*privateKey, *publicKey, pEC, gen_random_BN, NULL); + if (ipp_ret != ippStsNoErr) { + printf("Error: fail to generate private and public key pairs\n"); ret = -4; break; } - - // ZA = H256(Z||M) - ipp_ret = ippsHashUpdate_rmf(z_digest, sizeof(z_digest), hash_handle); - if (ipp_ret != ippStsNoErr) - { - printf("Error: fail to update hash value of Z\n"); - ret = -5; - break; - } - ipp_ret = ippsHashUpdate_rmf((unsigned char *)msg, msg_len, hash_handle); - if (ipp_ret != ippStsNoErr) - { - printf("Error: fail to update hash value of M\n"); - ret = -6; - break; - } - ipp_ret = ippsHashFinal_rmf(digest, hash_handle); - if (ipp_ret != ippStsNoErr) - { - printf("Error: fail to complete message digesting and return digest\n"); - ret = -7; - break; - } } while(0); - SAFE_FREE_HEAP(hash_handle, ctx_size); + // 3. Final, release resource + SAFE_FREE(pEC); return ret; } /* SM2 sign */ -static int sm2_do_sign(const IppsBigNumState *regPrivateKey, const IppsHashMethod *hash_method, const char *id, const int id_len, const char *msg, const int msg_len, IppsBigNumState* signX, IppsBigNumState* signY) +static int sm2_sign(const IppsBigNumState* pMsgDigest, const IppsBigNumState* regPrivateKey, IppsBigNumState* signX, IppsBigNumState* signY) { - IppsECCPState *pECCPS = NULL; - IppsPRNGState *pPRNGS = NULL; + IppsGFpECState *pEC = NULL; IppsBigNumState *ephPrivateKey = NULL; - IppsECCPPointState *regPublicKey = NULL, *ephPublicKey = NULL; - IppsBigNumState *pMsg = NULL; - IppsBigNumState *pX = NULL, *pY = NULL; + IppsECCPPointState *ephPublicKey = NULL; IppStatus ipp_ret = ippStsNoErr; int ret = 0; - unsigned char hash[32] = {0}; do { // 1. Create ECC context for SM2 - pECCPS = new_ECC_sm2(); - if (pECCPS == NULL) { - printf("Error: fail to create pECCPS\n"); + pEC = (IppsGFpECState*)new_ECC_sm2(); + if (pEC == NULL) { + printf("Error: fail to create ecc context for sm2\n"); ret = -1; break; } - // 2. Create ephemeral private key and public key, regular public key - ephPrivateKey = new_BN(ordSize, 0); - if (ephPrivateKey == NULL) { - printf("Error: fail to create ephemeral private key\n"); - ret = -2; - break; - } - ephPublicKey = new_ECC_Point(); - if (ephPublicKey == NULL) { - printf("Error: fail to create ephemeral public key\n"); - ret = -3; - break; - } - regPublicKey = new_ECC_Point(); - if (regPublicKey == NULL) { - printf("Error: fail to create regular public key\n"); - ret = -4; - break; - } - ipp_ret = ippsECCPPublicKey(regPrivateKey, regPublicKey, pECCPS); - if (ipp_ret != ippStsNoErr) { - printf("Error: fail to calculate regular public key\n"); - ret = -5; - break; - } - - // 3. Generate ephemeral key pairs - pPRNGS = new_PRNG(); - if (pPRNGS == NULL) { - printf("Error: fail to create pPRNGS\n"); - ret = -6; - break; - } - ipp_ret = ippsECCPGenKeyPair(ephPrivateKey, ephPublicKey, pECCPS, ippsPRNGen, pPRNGS); - if (ipp_ret != ippStsNoErr) { - printf("Error: fail to generate ephemeral key pairs\n"); - ret = -7; - break; - } - - // 4. Create pX and pY - pX = new_BN(ordSize, 0); - if (pX == NULL){ - printf("Error: fail to create pX\n"); - ret = -8; - break; - } - pY = new_BN(ordSize, 0); - if (pY == NULL){ - printf("Error: fail to create pY\n"); - ret = -9; - break; - } - ipp_ret = ippsECCPGetPoint(pX, pY, regPublicKey, pECCPS); - if (ipp_ret != ippStsNoErr) { - printf("Error: fail to convert internal presentation EC point into regular affine coordinates EC point\n"); - ret = -10; - break; - } - - // 5. Do user message digest - ret = hash_digest_with_preprocess(hash_method, msg, msg_len, id, id_len, pX, pY, hash); + // 2. Generate ephemeral private key and public key + ret = sm2_key_generation(&ephPrivateKey, &ephPublicKey); if (ret != 0) { - printf("Error: fail to do hash digest with preprocess\n"); - ret = -11; - break; - } - pMsg = new_BN(ordSize, 0); - if (pMsg == NULL) { - printf("Error: fail to create BN\n"); - ret = -12; - break; - } - ipp_ret = ippsSetOctString_BN(hash, sizeof(hash), pMsg); - if (ipp_ret != ippStsNoErr) { - printf("Error: fail to convert octet string into BN value\n"); - ret = -13; + printf("Error: fail to generate ephemeral private key and public key\n"); + ret = -2; break; } - // 6. Sign using ECC context for SM2 - ipp_ret = ippsECCPSetKeyPair(ephPrivateKey, ephPublicKey, ippFalse, pECCPS); - if (ipp_ret != ippStsNoErr) { - printf("Error: fail to set ephemeral key pairs\n"); - ret = -14; - break; - } - ipp_ret = ippsECCPSignSM2(pMsg, regPrivateKey, ephPrivateKey, signX, signY, pECCPS); + // 3. Sign using ECC context for SM2 + ipp_ret = ippsECCPSignSM2(pMsgDigest, regPrivateKey, ephPrivateKey, signX, signY, pEC); if (ipp_ret != ippStsNoErr) { - printf("Error: fail to compute signature\n"); - ret = -15; + printf("Error: fail to sign the message\n"); + ret = -3; break; } } while(0); - // 7. Final, remove secret and release resources - // !!!Please clear secret including key/context related buffer/big number by manual!!! - free(pY); - free(pX); - free(pMsg); - free(regPublicKey); - free(ephPublicKey); - free(ephPrivateKey); - free(pPRNGS); - free(pECCPS); + // 4. Final, remove secret and release resource + // !!!Please clear secret including key/context related buffer/big number here!!! + SAFE_FREE(ephPublicKey); + SAEF_FREE_ECC_PRI_KEY(ephPrivateKey); + SAFE_FREE(pEC); return ret; } /* SM2 verify */ -static int sm2_do_verify(const IppsECCPPointState *regPublicKey, const IppsHashMethod *hash_method, const char *id, const int id_len, const char *msg, const int msg_len, IppsBigNumState* signX, IppsBigNumState* signY) +static int sm2_verify(const IppsBigNumState* pMsgDigest, const IppsECCPPointState* regPublicKey, const IppsBigNumState* signX, const IppsBigNumState* signY) { - IppsECCPState *pECCPS = NULL; - IppsBigNumState* pMsg = NULL; - IppsBigNumState *pX = NULL, *pY = NULL; + IppsGFpECState *pEC = NULL; IppStatus ipp_ret = ippStsNoErr; IppECResult eccResult = ippECValid; int ret = 0; - unsigned char hash[32] = {0}; do { // 1. Create ECC context for SM2 - pECCPS = new_ECC_sm2(); - if (pECCPS == NULL) { - printf("Error: fail to create pECCPS\n"); + pEC = (IppsGFpECState*)new_ECC_sm2(); + if (pEC == NULL) { + printf("Error: fail to create ecc context for sm2\n"); ret = -1; break; } - // 2. Create pX and pY - pX = new_BN(ordSize, 0); - if (pX == NULL){ - printf("Error: fail to create pX\n"); + // 2. Verify using ECC context for SM2 + ipp_ret = ippsECCPVerifySM2(pMsgDigest, regPublicKey, signX, signY, &eccResult, pEC); + if ((ipp_ret != ippStsNoErr) || (eccResult != ippECValid)) { + printf("Error: fail to verify the signature\n"); ret = -2; break; } - pY = new_BN(ordSize, 0); - if (pY == NULL){ - printf("Error: fail to create pY\n"); - ret = -3; - break; - } - ipp_ret = ippsECCPGetPoint(pX, pY, regPublicKey, pECCPS); - if (ipp_ret != ippStsNoErr) { - printf("Error: fail to convert internal presentation EC point into regular affine coordinates EC point\n"); - ret = -4; - break; - } - - // 3. Do user message digest - ret = hash_digest_with_preprocess(hash_method, msg, msg_len, id, id_len, pX, pY, hash); - if (ret != 0) { - printf("Error: fail to do hash digest with preprocess\n"); - ret = -5; - break; - } - pMsg = new_BN(ordSize, 0); - if (pMsg == NULL) { - printf("Error: fail to create BN\n"); - ret = -6; - break; - } - ipp_ret = ippsSetOctString_BN(hash, sizeof(hash), pMsg); - if (ipp_ret != ippStsNoErr) { - printf("Error: fail to convert octet string into BN value\n"); - ret = -7; - break; - } - - // 4. Verify using ECC context for SM2 - ipp_ret = ippsECCPSetKeyPair(NULL, regPublicKey, ippTrue, pECCPS); - if (ipp_ret != ippStsNoErr) { - printf("Error: fail to set regular public key\n"); - ret = -8; - break; - } - ipp_ret = ippsECCPVerifySM2(pMsg, regPublicKey, signX, signY, &eccResult, pECCPS); - if((ipp_ret != ippStsNoErr) || (eccResult != ippECValid)) { - printf("Error: fail to verify signature\n"); - ret = -9; - break; - } } while(0); - // 5. Final, remove secret and release resourcesz - // !!!Please clear secret including key/context related buffer/big number by manual!!! - free(pY); - free(pX); - free(pMsg); - free(pECCPS); + // 3. Final, release resource + SAFE_FREE(pEC); return ret; } -/* Signing and verification using ECC context for SM2 */ +/* SM2 sign and verify */ int ecall_sm2_sign_verify(void) { IppsECCPState *pECCPS = NULL; IppsBigNumState *regPrivateKey = NULL; IppsECCPPointState *regPublicKey = NULL; + int nScalars = 1; + int pBufferSize = 0; + Ipp8u *pScratchBuffer = NULL; + IppsBigNumState *pMsgDigest = NULL; IppsBigNumState *signX = NULL, *signY = NULL; IppStatus ipp_ret = ippStsNoErr; int ret = 0; - char *message = "context need to be signed"; - char *user_id = "1234567812345678"; - - /* - Generate a SM2 random key - !!! THIS IS ONLY A SIMPLE SAMPLE OF RANDOM KEY GENERATION, YOU STILL HAVE TO GENERATE YOUR KEY WITH ENOUGH ENTROPY !!! - */ - unsigned char priKey[32] = {0}; - if (secure_rand((unsigned int*)priKey, 32) != 0) { - printf("Error: fail to generate a SM2 random key\n"); - SAFE_FREE_STACK(priKey, 32); - return -1; - } + const char *message = "context need to be signed"; + const char *user_id = "1234567812345678"; do { // 1. Create ECC context for SM2 pECCPS = new_ECC_sm2(); if (pECCPS == NULL) { printf("Error: fail to create ecc context for sm2\n"); + ret = -1; + break; + } + + // 2. Generate regular private key and public key + ret = sm2_key_generation(®PrivateKey, ®PublicKey); + if (ret != 0) { + printf("Error: fail to generate regular private key and public key\n"); ret = -2; break; } - // 2. Create regular private key and public key - regPrivateKey = new_BN(ordSize, 0); - if (regPrivateKey == NULL) { - printf("Error: fail to create regular private key\n"); + // 3. Create signX and signY + signX = new_BN(ordSize, 0); + if (signX == NULL) { + printf("Error: fail to create signX\n"); ret = -3; break; } - regPublicKey = new_ECC_Point(); - if (regPublicKey == NULL) { - printf("Error: fail to create regular public key\n"); + signY = new_BN(ordSize, 0); + if (signY == NULL) { + printf("Error: fail to create signY\n"); ret = -4; break; } - // 3. Create regular private and public key pairs - ipp_ret = ippsSetOctString_BN(priKey, sizeof(priKey)-1, regPrivateKey); + // 4. Digest message + // Calculate Z = H256(ENTLA || IDA || a || b || xG || yG || xA || yA) + // Calculate ZA = H256(Z||M) + ipp_ret = ippsGFpECScratchBufferSize(nScalars, (IppsGFpECState*)pECCPS, &pBufferSize); if (ipp_ret != ippStsNoErr) { - printf("Error: fail to convert octet string into BN value\n"); + printf("Error: fail to get the size of the scratch buffer\n"); ret = -5; break; } - ipp_ret = ippsECCPPublicKey(regPrivateKey, regPublicKey, pECCPS); - if (ipp_ret != ippStsNoErr) { - printf("Error: fail to calculate regular public key\n"); + pScratchBuffer = (Ipp8u*)malloc(pBufferSize); + if (pScratchBuffer == NULL) { + printf("Error: fail to allocate memory for pScratchBuffer\n"); ret = -6; - break; + break; } - - // 4. Create signX and signY - signX = new_BN(ordSize, 0); - if (signX == NULL) { - printf("Error: fail to create signX\n"); + pMsgDigest = new_BN(ordSize, 0); + if (pMsgDigest == NULL) { + printf("Error: fail to create pointer to the resulting message digest\n"); ret = -7; break; } - signY = new_BN(ordSize, 0); - if (signY == NULL) { - printf("Error: fail to create signY\n"); + ipp_ret = ippsGFpECMessageRepresentationSM2(pMsgDigest, (const Ipp8u*)message, strlen(message), (const Ipp8u*)user_id, strlen(user_id), regPublicKey, pECCPS, pScratchBuffer); + if (ipp_ret != ippStsNoErr) { + printf("Error: fail to digest message\n"); ret = -8; break; } // 5. Sign using ECC context for SM2 - ret = sm2_do_sign(regPrivateKey, ippsHashMethod_SM3(), user_id, strlen(user_id), message, strlen(message), signX, signY); - if(ret != 0) - { + ret = sm2_sign(pMsgDigest, regPrivateKey, signX, signY); + if (ret != 0) { printf("Error: fail to sign\n"); ret = -9; break; } // 6. Verify using ECC context for SM2 - ret = sm2_do_verify(regPublicKey, ippsHashMethod_SM3(), user_id, strlen(user_id), message, strlen(message), signX, signY); - if (ret != 0) - { + ret = sm2_verify(pMsgDigest, regPublicKey, signX, signY); + if (ret != 0) { printf("Error: fail to verify\n"); ret = -10; break; } } while(0); - // 7. Final, remove secret and release resources - // !!!Please clear secret including key/context related buffer/big number by manual!!! - free(signY); - free(signX); - free(regPublicKey); - free(regPrivateKey); - free(pECCPS); - SAFE_FREE_STACK(priKey, 32); + // 7. Final, remove secret and release resource + // !!!Please clear secret including key/context related buffer/big number here!!! + SAFE_FREE(signY); + SAFE_FREE(signX); + SAFE_FREE(pMsgDigest); + SAFE_FREE_HEAP(pScratchBuffer, pBufferSize); + SAFE_FREE(regPublicKey); + SAEF_FREE_ECC_PRI_KEY(regPrivateKey); + SAFE_FREE(pECCPS); return ret; } -/* SM2 encrypt(GM version) */ -static int sm2_do_encrypt_gm(const char* message, int message_len, Ipp8u** cipher_text, int* cipher_len, IppsECCPState *pECCPS, IppsECCPPointState *regPublicKey, IppsECCPPointState *ephPublicKey, IppsBigNumState *ephPrivateKey) +/* SM2 compute hash */ +static int sm2_compute_hash(Ipp8u* hash_data, const char* message) { - int maxOutlen = 0; - int pOutSize = 0; - IppsGFpECState *pEC = NULL; - Ipp8u* pScratchBuffer = NULL; - IppStatus ipp_ret = ippStsNoErr; + int ctxSize = 0; + IppsSM3State* pSM3 = NULL; + IppStatus status = ippStsNoErr; int ret = 0; do { - maxOutlen = 64 + message_len + 32 + 1; // encrypt/decrypt buffer = pubkey (64B) + message (inpLen) + tag (32B) - *cipher_text = (Ipp8u*)malloc(maxOutlen); - memset(*cipher_text, 0, maxOutlen); - pEC = pECCPS; - pScratchBuffer = (Ipp8u*)malloc(1024 * 10); - - ipp_ret = ippsGFpECEncryptSM2_Ext(*cipher_text, maxOutlen, &pOutSize, (Ipp8u*)message, message_len, regPublicKey, ephPublicKey, ephPrivateKey, pEC, pScratchBuffer); - if (ipp_ret != ippStsNoErr) { - printf("Error: fail to encrypt.\n"); + //1. Initialize + status = ippsSM3GetSize(&ctxSize); + if (status != ippStsNoErr) { + printf("Error: fail to get size of SM3 context\n"); ret = -1; break; } - *cipher_len = pOutSize; - } while(0); - - SAFE_FREE_HEAP(pScratchBuffer, 1024 * 10); - - return ret; -} - -/* SM2 decrypt(GM version) */ -static int sm2_do_decrypt_gm(const Ipp8u* cipher_text, int message_len, Ipp8u** plain_text, int* plain_len, IppsECCPState *pECCPS, IppsBigNumState *regPrivateKey) -{ - int maxOutlen = 0; - int pOutSize = 0; - IppsGFpECState *pEC = NULL; - Ipp8u* pScratchBuffer = NULL; - IppStatus ipp_ret = ippStsNoErr; - int ret = 0; - - do { - maxOutlen = 64 + message_len + 32 + 1; // encrypt/decrypt buffer = pubkey (64B) + message (inpLen) + tag (32B) - *plain_text = (Ipp8u*)malloc(maxOutlen); - memset(*plain_text, 0, maxOutlen); - pEC = pECCPS; - pScratchBuffer = (Ipp8u*)malloc(1024 * 10); + pSM3 = (IppsSM3State*)(malloc(ctxSize)); + if (pSM3 == NULL) { + printf("Error: fail to allocate memory for SM3 context\n"); + ret = -2; + break; + } + status = ippsSM3Init(pSM3); + if (status != ippStsNoErr) { + printf("Error: fail to initialize SM3 context\n"); + ret = -3; + break; + } - ipp_ret = ippsGFpECDecryptSM2_Ext(*plain_text, maxOutlen, &pOutSize, cipher_text, maxOutlen, regPrivateKey, pEC, pScratchBuffer); - if (ipp_ret != ippStsNoErr) { - printf("Error: fail to decrypt.\n"); - ret = -1; + // 2. Compute + status = ippsSM3Update((const Ipp8u*)message, strlen((char*)message), pSM3); + if (status != ippStsNoErr) { + printf("Error: fail to digest the message of specified length\n"); + ret = -4; + break; + } + status = ippsSM3Final(hash_data, pSM3); + if (status != ippStsNoErr) { + printf("Error: fail to complete computation of the SM3 digest value\n"); + ret = -5; break; } - *plain_len = pOutSize; } while(0); - SAFE_FREE_HEAP(pScratchBuffer, 1024 * 10); + // 3. Final, release resource + SAFE_FREE_HEAP(pSM3, ctxSize); return ret; } -/* Encryption and decryption using ECC context for SM2 (GM version, standard is GM/T 0003-2012) */ -int ecall_sm2_encrypt_decrypt_gm(void) +/* SM2 Key Exchange */ +int ecall_sm2_key_exchange(void) { - IppsECCPState *pECCPS = NULL; - IppsBigNumState *regPrivateKey = NULL; - IppsECCPPointState *regPublicKey = NULL; - IppsPRNGState *pPRNGS = NULL; - IppsBigNumState *ephPrivateKey = NULL; - IppsECCPPointState *ephPublicKey = NULL; - Ipp8u *cipher_text = NULL, *plain_text = NULL; - int cipher_len = 0, plain_len = 0; - + IppsGFpECState *pEC = NULL; + IppsBigNumState *requesterRegPrivateKey = NULL, *responderRegPrivateKey = NULL, *requesterEphPrivateKey = NULL, *responderEphPrivateKey = NULL; + IppsECCPPointState *requesterRegPublicKey = NULL, *responderRegPublicKey = NULL, *requesterEphPublicKey = NULL, *responderEphPublicKey = NULL; + int pSize = 0; + IppsGFpECKeyExchangeSM2State *pKERequester = NULL, *pKEResponder = NULL; + int nScalars = 1; + int pBufferSize = 0; + Ipp8u *pScratchBuffer = NULL; + Ipp8u sharedKeyRequester[32] = {0}; + Ipp8u sharedKeyResponder[32] = {0}; + int sharedKeyRequesterSize = 32; + int sharedKeyResponderSize = 32; + char *user_id_requester = "1234567812345678"; + char *user_id_responder = "AABBCCDDEEFFGGHH"; + int user_id_len_requester = strlen(user_id_requester); + int user_id_len_responder = strlen(user_id_responder); + Ipp8u user_id_hash_requester[32] = {0}; + Ipp8u user_id_hash_responder[32] = {0}; + Ipp8u pSSelfRequester[32] = {0}; + Ipp8u pSPeerResponder[32] = {0}; + const char* pSSelfRequesterMsg = "this is requester"; + const char* pSPeerResponderMsg = "this is responder"; + int pStatusRequester = 0, pStatusResponder = 0; IppStatus ipp_ret = ippStsNoErr; int ret = 0; - char *message = "context need to be encrypted"; - int message_len = strlen(message); - - /* - Generate a SM2 random key - !!! THIS IS ONLY A SIMPLE SAMPLE OF RANDOM KEY GENERATION, YOU STILL HAVE TO GENERATE YOUR KEY WITH ENOUGH ENTROPY !!! - */ - unsigned char priKey[32] = {0}; - if (secure_rand((unsigned int*)priKey, 32) != 0) { - printf("Error: fail to generate a SM2 random key\n"); - SAFE_FREE_STACK(priKey, 32); - return -1; - } - do { // 1. Create ECC context for SM2 - pECCPS = new_ECC_sm2(); - if (pECCPS == NULL) { + pEC = (IppsGFpECState*)new_ECC_sm2(); + if (pEC == NULL) { printf("Error: fail to create ecc context for sm2\n"); + ret = -1; + break; + } + + // Requester: + // 2. Generate requester's regular private and public key + ret = sm2_key_generation(&requesterRegPrivateKey, &requesterRegPublicKey); + if (ret != 0) { + printf("Error: fail to generate requester's regular private key and public key\n"); ret = -2; break; } - // 2. Create regular private key and public key - regPrivateKey = new_BN(ordSize, 0); - if (regPrivateKey == NULL) { - printf("Error: fail to create regular private key\n"); + // 3. Generate requester's ephemeral private and public key + ret = sm2_key_generation(&requesterEphPrivateKey, &requesterEphPublicKey); + if (ret != 0) { + printf("Error: fail to generate requester's ephemeral private key and public key\n"); ret = -3; break; } - regPublicKey = new_ECC_Point(); - if (regPublicKey == NULL) { - printf("Error: fail to create regular public key\n"); + + // Responder: + // 4. Generate responder's regular private and public key + ret = sm2_key_generation(&responderRegPrivateKey, &responderRegPublicKey); + if (ret != 0) { + printf("Error: fail to generate responder's regular private key and public key\n"); ret = -4; break; } - // 3. Generate regular private and public key pairs - ipp_ret = ippsSetOctString_BN(priKey, sizeof(priKey)-1, regPrivateKey); - if (ipp_ret != ippStsNoErr) { - printf("Error: fail to convert octet string into BN value\n"); + // 5. Generate responder's ephemeral private and public key + ret = sm2_key_generation(&responderEphPrivateKey, &responderEphPublicKey); + if (ret != 0) { + printf("Error: fail to generate responder's ephemeral private key and public key\n"); ret = -5; break; } - ipp_ret = ippsECCPPublicKey(regPrivateKey, regPublicKey, pECCPS); + + // 6. Get the size of the SM2 Key Exchange ECC context + ipp_ret = ippsGFpECKeyExchangeSM2_GetSize(pEC, &pSize); if (ipp_ret != ippStsNoErr) { - printf("Error: fail to calculate regular public key\n"); + printf("Error: fail to get the size of the SM2 Key Exchange ECC context\n"); ret = -6; break; } - // 4. Generate ephemeral private and public key pairs - pPRNGS = new_PRNG(); - if (pPRNGS == NULL) { - printf("Error: fail to create pPRNGS\n"); + // 7. Initialize the SM2 Key Exchange ECC context + pKERequester = (IppsGFpECKeyExchangeSM2State*)malloc(pSize); + if (pKERequester == NULL) { + printf("Error: fail to allocate memory for pKERequester\n"); ret = -7; break; } - - ephPrivateKey = new_BN(ordSize, 0); - if (ephPrivateKey == NULL) { - printf("Error: fail to create ephemeral private key\n"); + ipp_ret = ippsGFpECKeyExchangeSM2_Init(pKERequester, ippKESM2Requester, pEC); + if (ipp_ret != ippStsNoErr) { + printf("Error: fail to initialize requester SM2 Key Exchange ECC context\n"); ret = -8; break; } - ephPublicKey = new_ECC_Point(); - if (ephPublicKey == NULL) { - printf("Error: fail to create ephemeral public key\n"); + pKEResponder = (IppsGFpECKeyExchangeSM2State*)malloc(pSize); + if (pKEResponder == NULL) { + printf("Error: fail to allocate memory for pKEResponder\n"); ret = -9; break; } - - ipp_ret = ippsECCPGenKeyPair(ephPrivateKey, ephPublicKey, pECCPS, ippsPRNGen, pPRNGS); + ipp_ret = ippsGFpECKeyExchangeSM2_Init(pKEResponder, ippKESM2Responder, pEC); if (ipp_ret != ippStsNoErr) { - printf("Error: fail to generate ephemeral key pairs.\n"); + printf("Error: fail to initialize responder SM2 Key Exchange ECC context\n"); ret = -10; break; } - ipp_ret = ippsECCPSetKeyPair(ephPrivateKey, ephPublicKey, ippFalse, pECCPS); + // 8. Compute user_id_hash_requester and user_id_hash_responder + // Za = SM3( ENTL || ID || a || b || xG || yG || xA || yA ) + ipp_ret = ippsGFpECScratchBufferSize(nScalars, pEC, &pBufferSize); if (ipp_ret != ippStsNoErr) { - printf("Error: fail to set ephemeral key pairs\n"); + printf("Error: fail to get the size of the scratch buffer\n"); ret = -11; break; } + pScratchBuffer = (Ipp8u*)malloc(pBufferSize); + if (pScratchBuffer == NULL) { + printf("Error: fail to allocate memory for pScratchBuffer\n"); + ret = -12; + break; + } + ipp_ret = ippsGFpECUserIDHashSM2(user_id_hash_requester, (const Ipp8u *)user_id_requester, user_id_len_requester, requesterRegPublicKey, pEC, pScratchBuffer); + if (ipp_ret != ippStsNoErr) { + printf("Error: fail to compute user_id_hash_requester\n"); + ret = -13; + break; + } + ipp_ret = ippsGFpECUserIDHashSM2(user_id_hash_responder, (const Ipp8u *)user_id_responder, user_id_len_responder, responderRegPublicKey, pEC, pScratchBuffer); + if (ipp_ret != ippStsNoErr) { + printf("Error: fail to compute user_id_hash_responder\n"); + ret = -14; + break; + } + + // 9. Set up the SM2 Key Exchange ECC context for further operation of the SM2 Key Exchange algorithm + ipp_ret = ippsGFpECKeyExchangeSM2_Setup(user_id_hash_requester, user_id_hash_responder, requesterRegPublicKey, responderRegPublicKey, requesterEphPublicKey, responderEphPublicKey, pKERequester); + if (ipp_ret != ippStsNoErr) { + printf("Error: fail to set up requester SM2 Key Exchange ECC context\n"); + ret = -15; + break; + } + ipp_ret = ippsGFpECKeyExchangeSM2_Setup(user_id_hash_responder, user_id_hash_requester, responderRegPublicKey, requesterRegPublicKey, responderEphPublicKey, requesterEphPublicKey, pKEResponder); + if (ipp_ret != ippStsNoErr) { + printf("Error: fail to set up responder SM2 Key Exchange ECC context\n"); + ret = -16; + break; + } - // 5. Encrypt - ret = sm2_do_encrypt_gm(message, message_len, &cipher_text, &cipher_len, pECCPS, regPublicKey, ephPublicKey, ephPrivateKey); + // 10. Compute requester shared key + ret = sm2_compute_hash(pSSelfRequester, pSSelfRequesterMsg); if (ret != 0) { - printf("Error: fail to encrypt.\n"); - ret = -12; + printf("Error: fail to compute requester self conformation hash data\n"); + ret = -17; + break; + } + ret = ippsGFpECKeyExchangeSM2_SharedKey(sharedKeyRequester, sharedKeyRequesterSize, pSSelfRequester, requesterRegPrivateKey, requesterEphPrivateKey, pKERequester, pScratchBuffer); + if (ret != 0) { + printf("Error: fail to compute requester shared key\n"); + ret = -18; break; } - // 6. Decrypt - ret = sm2_do_decrypt_gm(cipher_text, message_len, &plain_text, &plain_len, pECCPS, regPrivateKey); + // 11. Compute responder shared key + ret = sm2_compute_hash(pSPeerResponder, pSPeerResponderMsg); if (ret != 0) { - printf("Error: fail to decrypt.\n"); - ret = -13; + printf("Error: fail to compute responder peer conformation hash data\n"); + ret = -19; + break; + } + ret = ippsGFpECKeyExchangeSM2_SharedKey(sharedKeyResponder, sharedKeyResponderSize, pSPeerResponder, responderRegPrivateKey, responderEphPrivateKey, pKEResponder, pScratchBuffer); + if (ret != 0) { + printf("Error: fail to compute responder shared key\n"); + ret = -20; break; } - // 7. Compare decrypted message and original message - if(strlen((char*)message) != strlen((char*)plain_text) || memcmp(message, plain_text, strlen((char*)message)) != 0) + // 12. Confirm if requester shared key and responder shared key are correct, then compare if they are equal + ipp_ret = ippsGFpECKeyExchangeSM2_Confirm(pSPeerResponder, &pStatusRequester, pKERequester); + if (ipp_ret != ippStsNoErr) { + printf("Error: fail to confirm requester shared key\n"); + ret = -21; + break; + } + ipp_ret = ippsGFpECKeyExchangeSM2_Confirm(pSSelfRequester, &pStatusResponder, pKEResponder); + if (ipp_ret != ippStsNoErr) { + printf("Error: fail to confirm responder shared key\n"); + ret = -22; + break; + } + // pStatusRequester/pStatusResponder's value: + // 1, successful + // 0, bad confirmation + if (pStatusRequester != 1 || pStatusResponder != 1 || memcmp(sharedKeyRequester, sharedKeyResponder, 32)) { - printf("Error: decrypted message does not match original message!\n"); - ret = -14; + printf("Error: requester shared key and responder shared key are not equal\n"); + ret = -23; break; } - } while(0); - // 8. Final, remove secret and release resources - // !!!Please clear secret including key/context related buffer/big number by manual!!! - free(plain_text); - free(cipher_text); - free(ephPublicKey); - free(ephPrivateKey); - free(pPRNGS); - free(regPublicKey); - free(regPrivateKey); - free(pECCPS); - SAFE_FREE_STACK(priKey, 32); + SAFE_FREE_HEAP(pScratchBuffer, pBufferSize); + SAFE_FREE_HEAP(pKEResponder, pSize); + SAFE_FREE_HEAP(pKERequester, pSize); + SAFE_FREE(responderEphPublicKey); + SAEF_FREE_ECC_PRI_KEY(responderEphPrivateKey); + SAFE_FREE(requesterEphPublicKey); + SAEF_FREE_ECC_PRI_KEY(requesterEphPrivateKey); + SAFE_FREE(responderRegPublicKey); + SAEF_FREE_ECC_PRI_KEY(responderRegPrivateKey); + SAFE_FREE(requesterRegPublicKey); + SAEF_FREE_ECC_PRI_KEY(requesterRegPrivateKey); + SAFE_FREE(pEC); return ret; } -/* SM2 encrypt(IEEE version) */ -static int sm2_do_encrypt_ieee(const char* message, int message_len, Ipp8u** cipher_text, IppsECCPState *pECCPS, IppsBigNumState *regPrivateKey, IppsECCPPointState *ephPublicKey) +/* SM2 encrypt(GM version) */ +static int sm2_encrypt_gm(const char* message, int message_len, Ipp8u** cipher_text, int* cipher_len, IppsECCPState *pECCPS, IppsECCPPointState *regPublicKey, IppsECCPPointState *ephPublicKey, IppsBigNumState *ephPrivateKey) { - IppsGFpECState *pEC = pECCPS; - int pSize = 0; - IppsECESState_SM2 *pState = NULL; - Ipp8u* pEcScratchBuffer = NULL; + int maxOutlen = 0; + int pOutSize = 0; + IppsGFpECState *pEC = NULL; + int nScalars = 1; + int pBufferSize = 0; + Ipp8u* pScratchBuffer = NULL; IppStatus ipp_ret = ippStsNoErr; int ret = 0; do { - ipp_ret = ippsGFpECESGetSize_SM2(pEC, &pSize); - if (ipp_ret != ippStsNoErr) { - printf("Error: fail to get size of the SM2 ECC\n"); + maxOutlen = 64 + message_len + 32 + 1; // encrypt/decrypt buffer = pubkey (64B) + message (inpLen) + hash (32B) + *cipher_text = (Ipp8u*)malloc(maxOutlen); + if (*cipher_text == NULL) { + printf("Error: fail to allocate memory for cipher text\n"); ret = -1; break; } - - pState = (IppsECESState_SM2*)malloc(pSize); - ipp_ret = ippsGFpECESInit_SM2(pEC, pState, pSize); + memset(*cipher_text, 0, maxOutlen); + pEC = (IppsGFpECState*)pECCPS; + ipp_ret = ippsGFpECScratchBufferSize(nScalars, pEC, &pBufferSize); if (ipp_ret != ippStsNoErr) { - printf("Error: fail to init the SM2 ECC\n"); + printf("Error: fail to get the size of the scratch buffer\n"); ret = -2; break; } - - pEcScratchBuffer = (Ipp8u*)malloc(1024 * 10); - ipp_ret = ippsGFpECESSetKey_SM2(regPrivateKey, ephPublicKey, pState, pEC, pEcScratchBuffer); - if (ipp_ret != ippStsNoErr) { - printf("Error: fail to compute a shared secret\n"); + pScratchBuffer = (Ipp8u*)malloc(pBufferSize); + if (pScratchBuffer == NULL) { + printf("Error: fail to allocate memory for the scratch buffer\n"); ret = -3; break; } - - ipp_ret = ippsGFpECESStart_SM2(pState); + ipp_ret = ippsGFpECEncryptSM2_Ext(*cipher_text, maxOutlen, &pOutSize, (Ipp8u*)message, message_len, regPublicKey, ephPublicKey, ephPrivateKey, pEC, pScratchBuffer); if (ipp_ret != ippStsNoErr) { - printf("Error: fail to start the ECES SM2 encryption chain\n"); + printf("Error: fail to encrypt.\n"); ret = -4; break; } - - *cipher_text = (Ipp8u*)malloc(64 + message_len + 32); //encrypt/decrypt buffer = pubkey(64B) + message(len) + tag(32B) - memset(*cipher_text, 0, 64 + message_len + 32); - ipp_ret = ippsGFpECESEncrypt_SM2((Ipp8u*)message, *cipher_text, 64 + message_len + 32, pState); - if (ipp_ret != ippStsNoErr) { - printf("Error: fail to encrypt the plaintext data buffer\n"); - ret = -5; - break; - } - - ipp_ret = ippsGFpECESFinal_SM2(*cipher_text + 64 + message_len, 32, pState); - if (ipp_ret != ippStsNoErr) { - printf("Error: fail to complete the ECES SM2 encryption chain\n"); - ret = -6; - break; - } - + *cipher_len = pOutSize; } while(0); - SAFE_FREE_HEAP(pEcScratchBuffer, 1024 * 10); - SAFE_FREE_HEAP(pState, pSize); + SAFE_FREE_HEAP(pScratchBuffer, pBufferSize); return ret; } -/* SM2 decrypt(IEEE version) */ -static int sm2_do_decrypt_ieee(const Ipp8u* cipher_text, int message_len, Ipp8u** plain_text, IppsECCPState *pECCPS, IppsBigNumState *ephPrivateKey, IppsECCPPointState *regPublicKey) +/* SM2 decrypt(GM version) */ +static int sm2_decrypt_gm(const Ipp8u* cipher_text, int message_len, Ipp8u** plain_text, int* plain_len, IppsECCPState *pECCPS, IppsBigNumState *regPrivateKey) { - IppsGFpECState *pEC = pECCPS; - int pSize = 0; - IppsECESState_SM2 *pState = NULL; - Ipp8u* pEcScratchBuffer = NULL; + int maxOutlen = 0; + int pOutSize = 0; + IppsGFpECState *pEC = NULL; + int nScalars = 1; + int pBufferSize = 0; + Ipp8u* pScratchBuffer = NULL; IppStatus ipp_ret = ippStsNoErr; int ret = 0; do { - ipp_ret = ippsGFpECESGetSize_SM2(pEC, &pSize); - if (ipp_ret != ippStsNoErr) { - printf("Error: fail to get size of the SM2 ECC\n"); + maxOutlen = 64 + message_len + 32 + 1; // encrypt/decrypt buffer = pubkey (64B) + message (inpLen) + hash (32B) + *plain_text = (Ipp8u*)malloc(maxOutlen); + if (*plain_text == NULL) { + printf("Error: fail to allocate memory for plain text\n"); ret = -1; break; } - - pState = (IppsECESState_SM2*)malloc(pSize); - ipp_ret = ippsGFpECESInit_SM2(pEC, pState, pSize); + memset(*plain_text, 0, maxOutlen); + pEC = (IppsGFpECState*)pECCPS; + ipp_ret = ippsGFpECScratchBufferSize(nScalars, pEC, &pBufferSize); if (ipp_ret != ippStsNoErr) { - printf("Error: fail to init the SM2 ECC\n"); + printf("Error: fail to get the size of the scratch buffer\n"); ret = -2; break; } - - pEcScratchBuffer = (Ipp8u*)malloc(1024 * 10); - ipp_ret = ippsGFpECESSetKey_SM2(ephPrivateKey, regPublicKey, pState, pEC, pEcScratchBuffer); - if (ipp_ret != ippStsNoErr) { - printf("Error: fail to compute a shared secret\n"); + pScratchBuffer = (Ipp8u*)malloc(pBufferSize); + if (pScratchBuffer == NULL) { + printf("Error: fail to allocate memory for the scratch buffer\n"); ret = -3; break; } - - ipp_ret = ippsGFpECESStart_SM2(pState); + ipp_ret = ippsGFpECDecryptSM2_Ext(*plain_text, maxOutlen, &pOutSize, cipher_text, maxOutlen, regPrivateKey, pEC, pScratchBuffer); if (ipp_ret != ippStsNoErr) { - printf("Error: fail to start the ECES SM2 decryption chain\n"); + printf("Error: fail to decrypt.\n"); ret = -4; break; } - - *plain_text = (Ipp8u*)malloc(64 + message_len + 32); - memset(*plain_text, 0, 64 + message_len + 32); - ipp_ret = ippsGFpECESDecrypt_SM2(cipher_text, *plain_text, message_len, pState); - if (ipp_ret != ippStsNoErr) { - printf("Error: fail to decrypt the ciphertext data buffer\n"); - ret = -5; - break; - } - - ipp_ret = ippsGFpECESFinal_SM2(*plain_text + 64 + message_len, 32, pState); - if (ipp_ret != ippStsNoErr) { - printf("Error: fail to complete the ECES SM2 decryption chain\n"); - ret = -6; - break; - } + *plain_len = pOutSize; } while(0); - SAFE_FREE_HEAP(pEcScratchBuffer, 1024 * 10); - SAFE_FREE_HEAP(pState, pSize); + SAFE_FREE_HEAP(pScratchBuffer, pBufferSize); return ret; } -/* Encryption and decryption using ECC context for SM2 (IEEE version, standard is IEEE Std 1363A-2004) */ -int ecall_sm2_encrypt_decrypt_ieee(void) +/* SM2 encrypt and decrypt (GM version, standard is GM/T 0003-2012) */ +int ecall_sm2_encrypt_decrypt_gm(void) { IppsECCPState *pECCPS = NULL; - IppsBigNumState *user1PrivateKey = NULL; - IppsECCPPointState *user1PublicKey = NULL; - IppsPRNGState *pPRNGS = NULL; - IppsBigNumState *user2PrivateKey = NULL; - IppsECCPPointState *user2PublicKey = NULL; - IppsECESState_SM2 *pState = NULL; - Ipp8u* pEcScratchBuffer = NULL; + IppsBigNumState *regPrivateKey = NULL; + IppsECCPPointState *regPublicKey = NULL; + IppsBigNumState *ephPrivateKey = NULL; + IppsECCPPointState *ephPublicKey = NULL; Ipp8u *cipher_text = NULL, *plain_text = NULL; - + int cipher_len = 0, plain_len = 0; IppStatus ipp_ret = ippStsNoErr; int ret = 0; char *message = "context need to be encrypted"; int message_len = strlen(message); - /* - Generate a SM2 random key - !!! THIS IS ONLY A SIMPLE SAMPLE OF RANDOM KEY GENERATION, YOU STILL HAVE TO GENERATE YOUR KEY WITH ENOUGH ENTROPY !!! - */ - unsigned char priKey[32] = {0}; - if (secure_rand((unsigned int*)priKey, 32) != 0) { - printf("Error: fail to generate a SM2 random key\n"); - SAFE_FREE_STACK(priKey, 32); - return -1; - } - do { // 1. Create ECC context for SM2 pECCPS = new_ECC_sm2(); if (pECCPS == NULL) { - printf("Error: fail to create ECC context for SM2\n"); - ret = -2; + printf("Error: fail to create ecc context for sm2\n"); + ret = -1; break; } // 2. Create regular private key and public key - user1PrivateKey = new_BN(ordSize, 0); - if (user1PrivateKey == NULL) { - printf("Error: fail to create regular private key\n"); - ret = -3; - break; - } - user1PublicKey = new_ECC_Point(); - if (user1PublicKey == NULL) { - printf("Error: fail to create regular public key\n"); - ret = -4; - break; - } - - // 3. Generate regular private and public key pairs - ipp_ret = ippsSetOctString_BN(priKey, sizeof(priKey)-1, user1PrivateKey); - if (ipp_ret != ippStsNoErr) { - printf("Error: fail to convert octet string into BN value\n"); - ret = -5; - break; - } - ipp_ret = ippsECCPPublicKey(user1PrivateKey, user1PublicKey, pECCPS); - if (ipp_ret != ippStsNoErr) { - printf("Error: fail to calculate regular public key\n"); - ret = -6; - break; - } - - // 4. Generate ephemeral private and public key pairs - pPRNGS = new_PRNG(); - if (pPRNGS == NULL) { - printf("Error: fail to create pPRNGS\n"); - ret = -7; - break; - } - - user2PrivateKey = new_BN(ordSize, 0); - if (user2PrivateKey == NULL) { - printf("Error: fail to create ephemeral private key\n"); - ret = -8; - break; - } - user2PublicKey = new_ECC_Point(); - if (user2PublicKey == NULL) { - printf("Error: fail to create ephemeral public key\n"); - ret = -9; - break; - } - - ipp_ret = ippsECCPGenKeyPair(user2PrivateKey, user2PublicKey, pECCPS, ippsPRNGen, pPRNGS); - if (ipp_ret != ippStsNoErr) { - printf("Error: fail to generate ephemeral key pairs\n"); - ret = -10; + ret = sm2_key_generation(®PrivateKey, ®PublicKey); + if (ret != 0) { + printf("Error: fail to generate regular private key and public key\n"); + ret = -2; break; } - ipp_ret = ippsECCPSetKeyPair(user2PrivateKey, user2PublicKey, ippFalse, pECCPS); - if (ipp_ret != ippStsNoErr) { - printf("Error: fail to set ephemeral key pairs\n"); - ret = -11; + // 3. Generate ephemeral private and public key pairs + ret = sm2_key_generation(&ephPrivateKey, &ephPublicKey); + if (ret != 0) { + printf("Error: fail to generate ephemeral private key and public key\n"); + ret = -3; break; } - // 5. Encrypt - ret = sm2_do_encrypt_ieee(message, message_len, &cipher_text, pECCPS, user1PrivateKey, user2PublicKey); + // 4. Encrypt + ret = sm2_encrypt_gm(message, message_len, &cipher_text, &cipher_len, pECCPS, regPublicKey, ephPublicKey, ephPrivateKey); if (ret != 0) { printf("Error: fail to encrypt.\n"); - ret = -12; + ret = -4; break; } - // 6. Decrypt - ret = sm2_do_decrypt_ieee(cipher_text, message_len, &plain_text, pECCPS, user2PrivateKey, user1PublicKey); + // 5. Decrypt + ret = sm2_decrypt_gm(cipher_text, message_len, &plain_text, &plain_len, pECCPS, regPrivateKey); if (ret != 0) { printf("Error: fail to decrypt.\n"); - ret = -13; + ret = -5; break; } - // 7. Compare decrypted message and original message + // 6. Compare decrypted message and original message if(strlen((char*)message) != strlen((char*)plain_text) || memcmp(message, plain_text, strlen((char*)message)) != 0) { printf("Error: decrypted message does not match original message!\n"); - ret = -14; + ret = -6; break; } } while(0); - // 8. Final, remove secret and release resources - // !!!Please clear secret including key/context related buffer/big number by manual!!! - free(pEcScratchBuffer); - free(pState); - free(user2PublicKey); - free(user2PrivateKey); - free(pPRNGS); - free(user1PublicKey); - free(user1PrivateKey); - free(pECCPS); - SAFE_FREE_STACK(priKey, 32); + SAFE_FREE(plain_text); + SAFE_FREE(cipher_text); + SAFE_FREE(ephPublicKey); + SAEF_FREE_ECC_PRI_KEY(ephPrivateKey); + SAFE_FREE(regPublicKey); + SAEF_FREE_ECC_PRI_KEY(regPrivateKey); + SAFE_FREE(pECCPS); - return 0; + return ret; } /* Compute a SM3 digest of a message. */ @@ -1335,8 +943,7 @@ int ecall_sm3(void) } } while(0); - //Remove secret and release resources - // !!!Please clear secret including key/context related buffer/big number by manual!!! + //Release resource SAFE_FREE_HEAP(pSM3, ctxSize); return ret; @@ -1351,10 +958,7 @@ int ecall_sm4_cbc() 0xCC,0xCC,0xCC,0xCC,0xDD,0xDD,0xDD,0xDD }; - /* - Generate a SM4 random secret key - !!! THIS IS ONLY A SIMPLE SAMPLE OF RANDOM KEY GENERATION, YOU STILL HAVE TO GENERATE YOUR KEY WITH ENOUGH ENTROPY !!! - */ + // Generate a SM4 random secret key unsigned char key[16] = {0}; if (secure_rand((unsigned int*)key, 16) != 0) { printf("Error: fail to generate a SM4 random secret key\n"); @@ -1362,10 +966,7 @@ int ecall_sm4_cbc() return -1; } - /* - Generate a SM4 random initialization vector(iv) - !!! THIS IS ONLY A SIMPLE SAMPLE OF RANDOM IV GENERATION, YOU STILL HAVE TO GENERATE YOUR IV WITH ENOUGH ENTROPY !!! - */ + // Generate a SM4 random initialization vector(iv) unsigned char iv[16] = {0}; if (secure_rand((unsigned int*)iv, 16) != 0) { printf("Error: fail to generate a SM4 random initialization vector\n"); @@ -1428,8 +1029,8 @@ int ecall_sm4_cbc() } } while (0); - // 6. Remove secret and release resources - // !!!Please clear secret including key/context related buffer/big number by manual!!! + // 6. Remove secret and release resource + // !!!Please clear secret including key/context related buffer/big number here!!! SAFE_FREE_HEAP(pSM4, ctxSize); SAFE_FREE_STACK(key, 16); SAFE_FREE_STACK(iv, 16); @@ -1443,10 +1044,7 @@ int ecall_sm4_ctr() // message to be encrypted unsigned char msg[] = "the message to be encrypted"; - /* - Generate a SM4 random secret key - !!! THIS IS ONLY A SIMPLE SAMPLE OF RANDOM KEY GENERATION, YOU STILL HAVE TO GENERATE YOUR KEY WITH ENOUGH ENTROPY !!! - */ + // Generate a SM4 random secret key unsigned char key[16] = {0}; if (secure_rand((unsigned int*)key, 16) != 0) { printf("Error: fail to generate a SM4 random secret key\n"); @@ -1454,10 +1052,7 @@ int ecall_sm4_ctr() return -1; } - /* - Generate a SM4 random initial counter - !!! THIS IS ONLY A SIMPLE SAMPLE OF RANDOM COUNTER GENERATION, YOU STILL HAVE TO GENERATE YOUR COUNTER WITH ENOUGH ENTROPY !!! - */ + // Generate a SM4 random initial counter unsigned char ctr0[16] = {0}; if (secure_rand((unsigned int*)ctr0, 16) != 0) { printf("Error: fail to generate a SM4 random initial counter\n"); @@ -1505,7 +1100,7 @@ int ecall_sm4_ctr() // Initialize counter before encryption memcpy(ctr, ctr0, sizeof(ctr)); // Encrypt message - status1 = ippsSMS4EncryptCTR(msg, etext, sizeof(msg), pSM4, ctr, 64); + status1 = ippsSMS4EncryptCTR(msg, etext, sizeof(msg), pSM4, ctr, 128); if (status1 != ippStsNoErr) { printf("Erro: fail to encrypt the plaintext\n"); ret = -6; @@ -1514,7 +1109,7 @@ int ecall_sm4_ctr() // Initialize counter before decryption memcpy(ctr, ctr0, sizeof(ctr)); // Decrypt message - status2 = ippsSMS4DecryptCTR(etext, dtext, sizeof(etext), pSM4, ctr, 64); + status2 = ippsSMS4DecryptCTR(etext, dtext, sizeof(etext), pSM4, ctr, 128); if (status2 != ippStsNoErr) { printf("Error: fail to decrypt the ciphertext\n"); ret = -7; @@ -1529,8 +1124,8 @@ int ecall_sm4_ctr() } } while (0); - // 6. Remove secret and release resources - // !!!Please clear secret including key/context related buffer/big number by manual!!! + // 6. Remove secret and release resource + // !!!Please clear secret including key/context related buffer/big number here!!! SAFE_FREE_HEAP(pSM4, ctxSize); SAFE_FREE_STACK(key, 16); SAFE_FREE_STACK(ctr0, 16); diff --git a/SampleCode/SampleEnclaveGMIPP/Enclave/Enclave.edl b/SampleCode/SampleEnclaveGMIPP/Enclave/Enclave.edl index 2cb2d2dac..ed71ab2c6 100644 --- a/SampleCode/SampleEnclaveGMIPP/Enclave/Enclave.edl +++ b/SampleCode/SampleEnclaveGMIPP/Enclave/Enclave.edl @@ -40,8 +40,8 @@ enclave { */ trusted { public int ecall_sm2_sign_verify(void); + public int ecall_sm2_key_exchange(void); public int ecall_sm2_encrypt_decrypt_gm(void); - public int ecall_sm2_encrypt_decrypt_ieee(void); public int ecall_sm3(void); public int ecall_sm4_cbc(void); public int ecall_sm4_ctr(void); diff --git a/SampleCode/SampleEnclaveGMIPP/Enclave/Enclave.h b/SampleCode/SampleEnclaveGMIPP/Enclave/Enclave.h index 5aa07023a..7dd35be03 100644 --- a/SampleCode/SampleEnclaveGMIPP/Enclave/Enclave.h +++ b/SampleCode/SampleEnclaveGMIPP/Enclave/Enclave.h @@ -42,8 +42,8 @@ extern "C" { int printf(const char* fmt, ...); int ecall_sm2_sign_verify(void); +int ecall_sm2_key_exchange(void); int ecall_sm2_encrypt_decrypt_gm(void); -int ecall_sm2_encrypt_decrypt_ieee(void); int ecall_sm3(void); int ecall_sm4_cbc(void); int ecall_sm4_ctr(void); diff --git a/SampleCode/SampleEnclaveGMIPP/Makefile b/SampleCode/SampleEnclaveGMIPP/Makefile index 1235c3601..c94539a3b 100644 --- a/SampleCode/SampleEnclaveGMIPP/Makefile +++ b/SampleCode/SampleEnclaveGMIPP/Makefile @@ -39,21 +39,21 @@ SGX_DEBUG ?= 1 include $(SGX_SDK)/buildenv.mk ifeq ($(shell getconf LONG_BIT), 32) - SGX_ARCH := x86 + SGX_ARCH := x86 else ifeq ($(findstring -m32, $(CXXFLAGS)), -m32) - SGX_ARCH := x86 + SGX_ARCH := x86 endif ifeq ($(SGX_ARCH), x86) - SGX_COMMON_FLAGS := -m32 - SGX_LIBRARY_PATH := $(SGX_SDK)/lib - SGX_ENCLAVE_SIGNER := $(SGX_SDK)/bin/x86/sgx_sign - SGX_EDGER8R := $(SGX_SDK)/bin/x86/sgx_edger8r + SGX_COMMON_FLAGS := -m32 + SGX_LIBRARY_PATH := $(SGX_SDK)/lib + SGX_ENCLAVE_SIGNER := $(SGX_SDK)/bin/x86/sgx_sign + SGX_EDGER8R := $(SGX_SDK)/bin/x86/sgx_edger8r else - SGX_COMMON_FLAGS := -m64 - SGX_LIBRARY_PATH := $(SGX_SDK)/lib64 - SGX_ENCLAVE_SIGNER := $(SGX_SDK)/bin/x64/sgx_sign - SGX_EDGER8R := $(SGX_SDK)/bin/x64/sgx_edger8r + SGX_COMMON_FLAGS := -m64 + SGX_LIBRARY_PATH := $(SGX_SDK)/lib64 + SGX_ENCLAVE_SIGNER := $(SGX_SDK)/bin/x64/sgx_sign + SGX_EDGER8R := $(SGX_SDK)/bin/x64/sgx_edger8r endif ifeq ($(SGX_DEBUG), 1) @@ -78,9 +78,9 @@ SGX_COMMON_CXXFLAGS := $(SGX_COMMON_FLAGS) -Wnon-virtual-dtor -std=c++11 ######## App Settings ######## ifneq ($(SGX_MODE), HW) - Urts_Library_Name := sgx_urts_sim + Urts_Library_Name := sgx_urts_sim else - Urts_Library_Name := sgx_urts + Urts_Library_Name := sgx_urts endif App_Cpp_Files := App/App.cpp @@ -110,11 +110,11 @@ App_Name := app ######## Enclave Settings ######## ifneq ($(SGX_MODE), HW) - Trts_Library_Name := sgx_trts_sim - Service_Library_Name := sgx_tservice_sim + Trts_Library_Name := sgx_trts_sim + Service_Library_Name := sgx_tservice_sim else - Trts_Library_Name := sgx_trts - Service_Library_Name := sgx_tservice + Trts_Library_Name := sgx_trts + Service_Library_Name := sgx_tservice endif Crypto_Library_Name := sgx_tcrypto @@ -124,9 +124,9 @@ Enclave_Include_Paths := -IEnclave -I$(SGX_SDK)/include -I$(SGX_SDK)/include/tli Enclave_C_Flags := $(Enclave_Include_Paths) -nostdinc -fvisibility=hidden -fpie -ffunction-sections -fdata-sections $(MITIGATION_CFLAGS) CC_BELOW_4_9 := $(shell expr "`$(CC) -dumpversion`" \< "4.9") ifeq ($(CC_BELOW_4_9), 1) - Enclave_C_Flags += -fstack-protector + Enclave_C_Flags += -fstack-protector else - Enclave_C_Flags += -fstack-protector-strong + Enclave_C_Flags += -fstack-protector-strong endif Enclave_Cpp_Flags := $(Enclave_C_Flags) -nostdinc++ @@ -159,19 +159,19 @@ Enclave_Test_Key := Enclave/Enclave_private_test.pem ifeq ($(SGX_MODE), HW) ifeq ($(SGX_DEBUG), 1) - Build_Mode = HW_DEBUG + Build_Mode = HW_DEBUG else ifeq ($(SGX_PRERELEASE), 1) - Build_Mode = HW_PRERELEASE + Build_Mode = HW_PRERELEASE else - Build_Mode = HW_RELEASE + Build_Mode = HW_RELEASE endif else ifeq ($(SGX_DEBUG), 1) - Build_Mode = SIM_DEBUG + Build_Mode = SIM_DEBUG else ifeq ($(SGX_PRERELEASE), 1) - Build_Mode = SIM_PRERELEASE + Build_Mode = SIM_PRERELEASE else - Build_Mode = SIM_RELEASE + Build_Mode = SIM_RELEASE endif endif diff --git a/SampleCode/SampleEnclavePCL/Makefile b/SampleCode/SampleEnclavePCL/Makefile index c660f0046..56924e70e 100644 --- a/SampleCode/SampleEnclavePCL/Makefile +++ b/SampleCode/SampleEnclavePCL/Makefile @@ -38,9 +38,9 @@ SGX_DEBUG ?= 1 SGX_PCL ?= 1 ifeq ($(shell getconf LONG_BIT), 32) - SGX_ARCH := x86 + SGX_ARCH := x86 else ifeq ($(findstring -m32, $(CXXFLAGS)), -m32) - SGX_ARCH := x86 + SGX_ARCH := x86 endif @@ -48,16 +48,16 @@ ifeq ($(SGX_ARCH), x86) ifneq ($(SGX_PCL), 0) $(error SGX PCL feature is not supported for 32bit mode!) else - SGX_COMMON_FLAGS := -m32 - SGX_LIBRARY_PATH := $(SGX_SDK)/lib - SGX_ENCLAVE_SIGNER := $(SGX_SDK)/bin/x86/sgx_sign - SGX_EDGER8R := $(SGX_SDK)/bin/x86/sgx_edger8r + SGX_COMMON_FLAGS := -m32 + SGX_LIBRARY_PATH := $(SGX_SDK)/lib + SGX_ENCLAVE_SIGNER := $(SGX_SDK)/bin/x86/sgx_sign + SGX_EDGER8R := $(SGX_SDK)/bin/x86/sgx_edger8r endif else - SGX_COMMON_FLAGS := -m64 - SGX_LIBRARY_PATH := $(SGX_SDK)/lib64 - SGX_ENCLAVE_SIGNER := $(SGX_SDK)/bin/x64/sgx_sign - SGX_EDGER8R := $(SGX_SDK)/bin/x64/sgx_edger8r + SGX_COMMON_FLAGS := -m64 + SGX_LIBRARY_PATH := $(SGX_SDK)/lib64 + SGX_ENCLAVE_SIGNER := $(SGX_SDK)/bin/x64/sgx_sign + SGX_EDGER8R := $(SGX_SDK)/bin/x64/sgx_edger8r endif ifeq ($(SGX_DEBUG), 1) @@ -83,9 +83,9 @@ SGX_COMMON_CXXFLAGS := $(SGX_COMMON_FLAGS) -Wnon-virtual-dtor -std=c++11 ######## App Settings ######## ifneq ($(SGX_MODE), HW) - Urts_Library_Name := sgx_urts_sim + Urts_Library_Name := sgx_urts_sim else - Urts_Library_Name := sgx_urts + Urts_Library_Name := sgx_urts endif App_Cpp_Files := App/App.cpp $(wildcard App/Edger8rSyntax/*.cpp) $(wildcard App/TrustedLibrary/*.cpp) @@ -120,11 +120,11 @@ App_Name := app ######## Enclave Settings ######## ifneq ($(SGX_MODE), HW) - Trts_Library_Name := sgx_trts_sim - Service_Library_Name := sgx_tservice_sim + Trts_Library_Name := sgx_trts_sim + Service_Library_Name := sgx_tservice_sim else - Trts_Library_Name := sgx_trts - Service_Library_Name := sgx_tservice + Trts_Library_Name := sgx_trts + Service_Library_Name := sgx_tservice endif Crypto_Library_Name := sgx_tcrypto @@ -133,9 +133,9 @@ Enclave_Include_Paths := -IInclude -IEnclave -I$(SGX_SDK)/include -I$(SGX_SDK)/i CC_BELOW_4_9 := $(shell expr "`$(CC) -dumpversion`" \< "4.9") ifeq ($(CC_BELOW_4_9), 1) - Enclave_C_Flags := -nostdinc -fvisibility=hidden -fpie -ffunction-sections -fdata-sections -fstack-protector + Enclave_C_Flags := -nostdinc -fvisibility=hidden -fpie -ffunction-sections -fdata-sections -fstack-protector else - Enclave_C_Flags := -nostdinc -fvisibility=hidden -fpie -ffunction-sections -fdata-sections -fstack-protector-strong + Enclave_C_Flags := -nostdinc -fvisibility=hidden -fpie -ffunction-sections -fdata-sections -fstack-protector-strong endif Enclave_C_Flags += $(Enclave_Include_Paths) @@ -197,19 +197,19 @@ endif # ifneq ($(SGX_PCL),0) ifeq ($(SGX_MODE), HW) ifeq ($(SGX_DEBUG), 1) - Build_Mode = HW_DEBUG + Build_Mode = HW_DEBUG else ifeq ($(SGX_PRERELEASE), 1) - Build_Mode = HW_PRERELEASE + Build_Mode = HW_PRERELEASE else - Build_Mode = HW_RELEASE + Build_Mode = HW_RELEASE endif else ifeq ($(SGX_DEBUG), 1) - Build_Mode = SIM_DEBUG + Build_Mode = SIM_DEBUG else ifeq ($(SGX_PRERELEASE), 1) - Build_Mode = SIM_PRERELEASE + Build_Mode = SIM_PRERELEASE else - Build_Mode = SIM_RELEASE + Build_Mode = SIM_RELEASE endif endif diff --git a/SampleCode/SampleMbedCrypto/Makefile b/SampleCode/SampleMbedCrypto/Makefile index 13a30ce36..5ad822fc6 100644 --- a/SampleCode/SampleMbedCrypto/Makefile +++ b/SampleCode/SampleMbedCrypto/Makefile @@ -37,21 +37,21 @@ SGX_ARCH ?= x64 SGX_DEBUG ?= 1 ifeq ($(shell getconf LONG_BIT), 32) - SGX_ARCH := x86 + SGX_ARCH := x86 else ifeq ($(findstring -m32, $(CXXFLAGS)), -m32) - SGX_ARCH := x86 + SGX_ARCH := x86 endif ifeq ($(SGX_ARCH), x86) - SGX_COMMON_FLAGS := -m32 - SGX_LIBRARY_PATH := $(SGX_SDK)/lib - SGX_ENCLAVE_SIGNER := $(SGX_SDK)/bin/x86/sgx_sign - SGX_EDGER8R := $(SGX_SDK)/bin/x86/sgx_edger8r + SGX_COMMON_FLAGS := -m32 + SGX_LIBRARY_PATH := $(SGX_SDK)/lib + SGX_ENCLAVE_SIGNER := $(SGX_SDK)/bin/x86/sgx_sign + SGX_EDGER8R := $(SGX_SDK)/bin/x86/sgx_edger8r else - SGX_COMMON_FLAGS := -m64 - SGX_LIBRARY_PATH := $(SGX_SDK)/lib64 - SGX_ENCLAVE_SIGNER := $(SGX_SDK)/bin/x64/sgx_sign - SGX_EDGER8R := $(SGX_SDK)/bin/x64/sgx_edger8r + SGX_COMMON_FLAGS := -m64 + SGX_LIBRARY_PATH := $(SGX_SDK)/lib64 + SGX_ENCLAVE_SIGNER := $(SGX_SDK)/bin/x64/sgx_sign + SGX_EDGER8R := $(SGX_SDK)/bin/x64/sgx_edger8r endif ifeq ($(SGX_DEBUG), 1) @@ -76,9 +76,9 @@ SGX_COMMON_CXXFLAGS := $(SGX_COMMON_FLAGS) -Wnon-virtual-dtor -std=c++11 ######## App Settings ######## ifneq ($(SGX_MODE), HW) - Urts_Library_Name := sgx_urts_sim + Urts_Library_Name := sgx_urts_sim else - Urts_Library_Name := sgx_urts + Urts_Library_Name := sgx_urts endif App_Cpp_Files := App/App.cpp @@ -111,18 +111,18 @@ Enclave_Version_Script := Enclave/Enclave_debug.lds ifeq ($(SGX_MODE), HW) ifneq ($(SGX_DEBUG), 1) ifneq ($(SGX_PRERELEASE), 1) - # Choose to use 'Enclave.lds' for HW release mode - Enclave_Version_Script = Enclave/Enclave.lds + # Choose to use 'Enclave.lds' for HW release mode + Enclave_Version_Script = Enclave/Enclave.lds endif endif endif ifneq ($(SGX_MODE), HW) - Trts_Library_Name := sgx_trts_sim - Service_Library_Name := sgx_tservice_sim + Trts_Library_Name := sgx_trts_sim + Service_Library_Name := sgx_tservice_sim else - Trts_Library_Name := sgx_trts - Service_Library_Name := sgx_tservice + Trts_Library_Name := sgx_trts + Service_Library_Name := sgx_tservice endif Crypto_Library_Name := sgx_tcrypto @@ -160,19 +160,19 @@ Enclave_Test_Key := Enclave/Enclave_private_test.pem ifeq ($(SGX_MODE), HW) ifeq ($(SGX_DEBUG), 1) - Build_Mode = HW_DEBUG + Build_Mode = HW_DEBUG else ifeq ($(SGX_PRERELEASE), 1) - Build_Mode = HW_PRERELEASE + Build_Mode = HW_PRERELEASE else - Build_Mode = HW_RELEASE + Build_Mode = HW_RELEASE endif else ifeq ($(SGX_DEBUG), 1) - Build_Mode = SIM_DEBUG + Build_Mode = SIM_DEBUG else ifeq ($(SGX_PRERELEASE), 1) - Build_Mode = SIM_PRERELEASE + Build_Mode = SIM_PRERELEASE else - Build_Mode = SIM_RELEASE + Build_Mode = SIM_RELEASE endif endif diff --git a/SampleCode/SealUnseal/Makefile b/SampleCode/SealUnseal/Makefile index 750ed39f1..2cd21933d 100644 --- a/SampleCode/SealUnseal/Makefile +++ b/SampleCode/SealUnseal/Makefile @@ -37,21 +37,21 @@ SGX_ARCH ?= x64 SGX_DEBUG ?= 1 ifeq ($(shell getconf LONG_BIT), 32) - SGX_ARCH := x86 + SGX_ARCH := x86 else ifeq ($(findstring -m32, $(CXXFLAGS)), -m32) - SGX_ARCH := x86 + SGX_ARCH := x86 endif ifeq ($(SGX_ARCH), x86) - SGX_COMMON_FLAGS := -m32 - SGX_LIBRARY_PATH := $(SGX_SDK)/lib - SGX_ENCLAVE_SIGNER := $(SGX_SDK)/bin/x86/sgx_sign - SGX_EDGER8R := $(SGX_SDK)/bin/x86/sgx_edger8r + SGX_COMMON_FLAGS := -m32 + SGX_LIBRARY_PATH := $(SGX_SDK)/lib + SGX_ENCLAVE_SIGNER := $(SGX_SDK)/bin/x86/sgx_sign + SGX_EDGER8R := $(SGX_SDK)/bin/x86/sgx_edger8r else - SGX_COMMON_FLAGS := -m64 - SGX_LIBRARY_PATH := $(SGX_SDK)/lib64 - SGX_ENCLAVE_SIGNER := $(SGX_SDK)/bin/x64/sgx_sign - SGX_EDGER8R := $(SGX_SDK)/bin/x64/sgx_edger8r + SGX_COMMON_FLAGS := -m64 + SGX_LIBRARY_PATH := $(SGX_SDK)/lib64 + SGX_ENCLAVE_SIGNER := $(SGX_SDK)/bin/x64/sgx_sign + SGX_EDGER8R := $(SGX_SDK)/bin/x64/sgx_edger8r endif ifeq ($(SGX_DEBUG), 1) @@ -61,9 +61,9 @@ endif endif ifeq ($(SGX_DEBUG), 1) - SGX_COMMON_FLAGS += -O0 -g + SGX_COMMON_FLAGS += -O0 -g else - SGX_COMMON_FLAGS += -O2 + SGX_COMMON_FLAGS += -O2 endif SGX_COMMON_FLAGS += -Wall -Wextra -Winit-self -Wpointer-arith -Wreturn-type \ @@ -77,9 +77,9 @@ SGX_COMMON_CXXFLAGS = $(SGX_COMMON_FLAGS) -Wnon-virtual-dtor -std=c++11 ######## App Settings ######## ifneq ($(SGX_MODE), HW) - Urts_Library_Name := sgx_urts_sim + Urts_Library_Name := sgx_urts_sim else - Urts_Library_Name := sgx_urts + Urts_Library_Name := sgx_urts endif App_Cpp_Files := $(wildcard App/*.cpp) @@ -114,20 +114,20 @@ App_Name := app ######## Enclave Settings ######## ifneq ($(SGX_MODE), HW) - Trts_Library_Name := sgx_trts_sim - Service_Library_Name := sgx_tservice_sim + Trts_Library_Name := sgx_trts_sim + Service_Library_Name := sgx_tservice_sim else - Trts_Library_Name := sgx_trts - Service_Library_Name := sgx_tservice + Trts_Library_Name := sgx_trts + Service_Library_Name := sgx_tservice endif Crypto_Library_Name := sgx_tcrypto Enclave_Include_Paths := -I$(SGX_SDK)/include -I$(SGX_SDK)/include/tlibc -I$(SGX_SDK)/include/libcxx CC_BELOW_4_9 := $(shell expr "`$(CC) -dumpversion`" \< "4.9") ifeq ($(CC_BELOW_4_9), 1) - Enclave_Compile_CFlags := -fstack-protector + Enclave_Compile_CFlags := -fstack-protector else - Enclave_Compile_CFlags := -fstack-protector-strong + Enclave_Compile_CFlags := -fstack-protector-strong endif Enclave_Compile_CFlags += -nostdinc -ffreestanding -fvisibility=hidden -fpie -ffunction-sections -fdata-sections $(Enclave_Include_Paths) Enclave_Compile_CXXFlags := -nostdinc++ -std=c++11 $(Enclave_Compile_CFlags) @@ -177,19 +177,19 @@ Enclave_Unseal_Link_Flags := $(Enclave_Link_Flags) -Wl,--version-script=Enclave_ ifeq ($(SGX_MODE), HW) ifeq ($(SGX_DEBUG), 1) - Build_Mode = HW_DEBUG + Build_Mode = HW_DEBUG else ifeq ($(SGX_PRERELEASE), 1) - Build_Mode = HW_PRERELEASE + Build_Mode = HW_PRERELEASE else - Build_Mode = HW_RELEASE + Build_Mode = HW_RELEASE endif else ifeq ($(SGX_DEBUG), 1) - Build_Mode = SIM_DEBUG + Build_Mode = SIM_DEBUG else ifeq ($(SGX_PRERELEASE), 1) - Build_Mode = SIM_PRERELEASE + Build_Mode = SIM_PRERELEASE else - Build_Mode = SIM_RELEASE + Build_Mode = SIM_RELEASE endif endif diff --git a/buildenv.mk b/buildenv.mk index 41a937bb7..4689c6034 100644 --- a/buildenv.mk +++ b/buildenv.mk @@ -61,6 +61,22 @@ get_distr_info = $(patsubst "%",%,$(shell grep $(1) /etc/os-release 2> /dev/null DISTR_ID := $(call get_distr_info, '^ID=') DISTR_VER := $(call get_distr_info, '^VERSION_ID=') +#-------------------------------------------------------------------------------------- +# Function: get_full_version +# Arguments: 1: the version name of library +# Returns: Return the full version. +#--------------------------------------------------------------------------------------- +get_full_version = $(shell awk '$$2 ~ /$1/ { print substr($$3, 2, length($$3) - 2); }' $(COMMON_DIR)/inc/internal/se_version.h) + +#-------------------------------------------------------------------------------------- +# Function: get_major_version +# Arguments: 1: the version name of library +# Returns: Return the major version. +#--------------------------------------------------------------------------------------- +get_major_version = $(word 1,$(subst ., ,$(call get_full_version,$1))) + +# If the value of _FORTIFY_SOURCE is greater than 2, use the value, else use 2. +FORTIFY_SOURCE_VAL := $(lastword $(sort $(word 2,$(subst =, ,$(filter -D_FORTIFY_SOURCE=%,$(CFLAGS)))) 2)) COMMON_DIR := $(ROOT_DIR)/common LINUX_EXTERNAL_DIR := $(ROOT_DIR)/external @@ -71,6 +87,7 @@ DCAP_DIR := $(LINUX_EXTERNAL_DIR)/dcap_source LIBUNWIND_DIR := $(ROOT_DIR)/sdk/cpprt/linux/libunwind CP := cp -f +LN := ln -sf MKDIR := mkdir -p STRIP := strip OBJCOPY := objcopy @@ -105,7 +122,7 @@ ifdef DEBUG COMMON_FLAGS += -O0 -ggdb -DDEBUG -UNDEBUG COMMON_FLAGS += -DSE_DEBUG_LEVEL=SE_TRACE_DEBUG else - COMMON_FLAGS += -O2 -D_FORTIFY_SOURCE=2 -UDEBUG -DNDEBUG + COMMON_FLAGS += -O2 -D_FORTIFY_SOURCE=$(FORTIFY_SOURCE_VAL) -UDEBUG -DNDEBUG endif ifdef SE_SIM @@ -346,13 +363,11 @@ SGX_SDK ?= /opt/intel/sgxsdk SGX_HEADER_DIR ?= $(SGX_SDK)/include ifeq ($(ARCH), x86) - SGX_COMMON_CFLAGS := -m32 - SGX_LIB_DIR := $(SGX_SDK)/lib - SGX_BIN_DIR := $(SGX_SDK)/bin/x86 + SGX_COMMON_CFLAGS := -m32 + SGX_LIB_DIR := $(SGX_SDK)/lib + SGX_BIN_DIR := $(SGX_SDK)/bin/x86 else - SGX_COMMON_CFLAGS := -m64 - SGX_LIB_DIR := $(SGX_SDK)/lib64/$(MITIGATION_LIB_PATH) - SGX_BIN_DIR := $(SGX_SDK)/bin/x64 + SGX_COMMON_CFLAGS := -m64 + SGX_LIB_DIR := $(SGX_SDK)/lib64/$(MITIGATION_LIB_PATH) + SGX_BIN_DIR := $(SGX_SDK)/bin/x64 endif - -SPLIT_VERSION=$(word $2,$(subst ., ,$1)) diff --git a/common/buildenv.mk b/common/buildenv.mk index fe0095dd5..d34a45bd2 100644 --- a/common/buildenv.mk +++ b/common/buildenv.mk @@ -31,6 +31,7 @@ # Mitigation options +SGX_TRUSTED_INCLUDE_PATH ?= $(SGX_SDK)/include SGX_TRUSTED_LIBRARY_PATH ?= $(SGX_SDK)/lib64 CC ?= gcc diff --git a/common/inc/internal/global_data.h b/common/inc/internal/global_data.h index d3ae5e867..86ca5ed33 100644 --- a/common/inc/internal/global_data.h +++ b/common/inc/internal/global_data.h @@ -66,6 +66,8 @@ typedef struct _global_data_t uint64_t elrange_start_address; /* the base address provided in the enclave's SECS (SECS.BASEADDR) */ uint64_t elrange_size; /* the size of the enclave address range provided in the enclave's SECS (SECS.SIZE) */ sys_word_t edmm_bk_overhead; /* memory overhead used by edmm bookkeeping */ + uint32_t fips_on; + uint32_t reserved2; } global_data_t; #define ENCLAVE_INIT_NOT_STARTED 0 @@ -78,7 +80,7 @@ typedef struct _global_data_t #ifdef __cplusplus extern "C" { #endif -extern SE_DECLSPEC_EXPORT global_data_t const volatile g_global_data; +extern SE_DECLSPEC_EXPORT global_data_t volatile g_global_data; extern sdk_version_t g_sdk_version; extern int EDMM_supported; extern uint8_t __ImageBase; diff --git a/common/inc/internal/linux/linux-regs.h b/common/inc/internal/linux/linux-regs.h index 1f2c218f1..ff9d5297a 100644 --- a/common/inc/internal/linux/linux-regs.h +++ b/common/inc/internal/linux/linux-regs.h @@ -158,6 +158,10 @@ _CET_ENDBR .endm +.macro END_FUNC + .cfi_endproc +.endm + .macro NAKED_PROLOG push %xbp mov %xsp, %xbp @@ -253,7 +257,6 @@ #endif ret - .cfi_endproc .endm /*******************************************************************/ diff --git a/common/inc/internal/se_version.h b/common/inc/internal/se_version.h index 04abe1d40..567c03f63 100644 --- a/common/inc/internal/se_version.h +++ b/common/inc/internal/se_version.h @@ -31,25 +31,25 @@ #ifndef _SE_VERSION_H_ #define _SE_VERSION_H_ -#define STRFILEVER "2.24.100.3" +#define STRFILEVER "2.25.100.3" #define SGX_MAJOR_VERSION 2 -#define SGX_MINOR_VERSION 24 +#define SGX_MINOR_VERSION 25 #define SGX_REVISION_VERSION 100 #define MAKE_VERSION_UINT(major,minor,rev) (((uint64_t)major)<<32 | ((uint64_t)minor) << 16 | rev) #define VERSION_UINT MAKE_VERSION_UINT(SGX_MAJOR_VERSION, SGX_MINOR_VERSION, SGX_REVISION_VERSION) #define COPYRIGHT "Copyright (C) 2024 Intel Corporation" -#define UAE_SERVICE_VERSION "2.3.223.3" -#define URTS_VERSION "2.0.107.3" -#define ENCLAVE_COMMON_VERSION "1.2.107.3" -#define LAUNCH_VERSION "1.0.125.3" -#define EPID_VERSION "1.0.125.3" -#define QUOTE_EX_VERSION "1.1.125.3" +#define UAE_SERVICE_VERSION "2.3.224.3" +#define URTS_VERSION "2.0.108.3" +#define ENCLAVE_COMMON_VERSION "1.2.108.3" +#define LAUNCH_VERSION "1.0.126.3" +#define EPID_VERSION "1.0.126.3" +#define QUOTE_EX_VERSION "1.1.126.3" -#define PCE_VERSION "1.22.100.1" -#define LE_VERSION "1.22.100.1" -#define QE_VERSION "1.22.100.1" -#define PVE_VERSION "1.22.100.1" +#define PCE_VERSION "1.25.100.1" +#define LE_VERSION "1.25.100.1" +#define QE_VERSION "1.25.100.1" +#define PVE_VERSION "1.25.100.1" #endif diff --git a/common/inc/tlibc/time.h b/common/inc/tlibc/time.h index 3880d3e9a..baa4b67a2 100644 --- a/common/inc/tlibc/time.h +++ b/common/inc/tlibc/time.h @@ -94,6 +94,13 @@ double _TLIBC_CDECL_ difftime(time_t, time_t); char * _TLIBC_CDECL_ asctime(const struct tm *); size_t _TLIBC_CDECL_ strftime(char *, size_t, const char *, const struct tm *); +/* + * NOTE: The functions listed below only supports limited scenarios. + * Full functionality support requires locale, which is not avaiable inside enclave + */ +char *_TLIBC_CDECL_ strptime(const char *buf, const char *fmt, struct tm *tm); +time_t _TLIBC_CDECL_ mktime(struct tm *tmp); + /* * Non-C99 */ diff --git a/common/src/linux/xsave_gnu.S b/common/src/linux/xsave_gnu.S index 364e0caa4..1219ec455 100644 --- a/common/src/linux/xsave_gnu.S +++ b/common/src/linux/xsave_gnu.S @@ -101,7 +101,7 @@ DECLARE_LOCAL_FUNC restore_xregs DO_FXRSTOR 2: ret - .cfi_endproc +END_FUNC DECLARE_LOCAL_FUNC save_xregs #if defined(LINUX32) @@ -122,5 +122,5 @@ DECLARE_LOCAL_FUNC save_xregs DO_FXSAVE 2: ret - .cfi_endproc +END_FUNC diff --git a/download_prebuilt.sh b/download_prebuilt.sh index 462db2faf..09056f3d2 100755 --- a/download_prebuilt.sh +++ b/download_prebuilt.sh @@ -33,11 +33,11 @@ top_dir=`dirname $0` out_dir=$top_dir -optlib_name=optimized_libs_2.24.tar.gz -ae_file_name=prebuilt_ae_2.24.tar.gz +optlib_name=optimized_libs_2.25.tar.gz +ae_file_name=prebuilt_ae_2.25.tar.gz binutils_file_name=as.ld.objdump.r4.tar.gz -checksum_file=SHA256SUM_prebuilt_2.24.cfg -server_url_path=https://download.01.org/intel-sgx/sgx-linux/2.24 +checksum_file=SHA256SUM_prebuilt_2.25.cfg +server_url_path=https://download.01.org/intel-sgx/sgx-linux/2.25 server_optlib_url=$server_url_path/$optlib_name server_ae_url=$server_url_path/$ae_file_name server_binutils_url=$server_url_path/$binutils_file_name diff --git a/external/CppMicroServices/CMakeLists.txt b/external/CppMicroServices/CMakeLists.txt index 1c3876f0a..8d0aff3f4 100644 --- a/external/CppMicroServices/CMakeLists.txt +++ b/external/CppMicroServices/CMakeLists.txt @@ -407,9 +407,9 @@ else() set(US_CXX_FLAGS "${US_CXX_FLAGS} ${_have_visibility}") endif() - usFunctionCheckCompilerFlags("-O1 -D_FORTIFY_SOURCE=2" _fortify_source_flag) + usFunctionCheckCompilerFlags("-O1 -D_FORTIFY_SOURCE=${FORTIFY_SOURCE_VAL}" _fortify_source_flag) if(_fortify_source_flag) - set(US_CXX_FLAGS_RELEASE "${US_CXX_FLAGS_RELEASE} -U_FORTIFY_SOURCE -D_FORTIFY_SOURCE=2") + set(US_CXX_FLAGS_RELEASE "${US_CXX_FLAGS_RELEASE} -U_FORTIFY_SOURCE -D_FORTIFY_SOURCE=${FORTIFY_SOURCE_VAL}") endif() set(_orig_req_libs ${CMAKE_REQUIRED_LIBRARIES}) diff --git a/external/dcap_source b/external/dcap_source index e945c58bf..2562057f6 160000 --- a/external/dcap_source +++ b/external/dcap_source @@ -1 +1 @@ -Subproject commit e945c58bff60bb96e4daca57b73c93f96b14418a +Subproject commit 2562057f6a3149c03f5985826ffaba978ece58c2 diff --git a/external/epid-sdk/Makefile.in b/external/epid-sdk/Makefile.in index 5c9ae9528..cdce8849f 100644 --- a/external/epid-sdk/Makefile.in +++ b/external/epid-sdk/Makefile.in @@ -20,11 +20,11 @@ SIZE_CFLAGS := -O2 CC_FLAGS := $(CFLAGS) $(SIZE_CFLAGS) -Werror -Wall -Wextra -Wno-missing-braces \ -Wno-missing-field-initializers -Wno-unknown-pragmas -Wno-unused-function \ -fno-strict-aliasing -Wno-unused-but-set-variable -Wno-comment -Wformat \ - -Wformat-security -fstack-protector -DNDEBUG -D_FORTIFY_SOURCE=2 $(MITIGATION_CFLAGS) + -Wformat-security -fstack-protector -DNDEBUG -D_FORTIFY_SOURCE=$(FORTIFY_SOURCE_VAL) $(MITIGATION_CFLAGS) #intel c compiler flags ICC_FLAGS := $(CFLAGS) $(SIZE_CFLAGS) -Werror -Wall -Wextra -DNDEBUG \ - -fstack-protector -D_FORTIFY_SOURCE=2 \ + -fstack-protector -D_FORTIFY_SOURCE=$(FORTIFY_SOURCE_VAL) \ -Wformat -Wformat-security ifneq ($(OS),Windows_NT) diff --git a/external/ippcp_internal/0001-IPP-crypto-for-SGX.patch b/external/ippcp_internal/0001-IPP-crypto-for-SGX.patch new file mode 100644 index 000000000..ae8250302 --- /dev/null +++ b/external/ippcp_internal/0001-IPP-crypto-for-SGX.patch @@ -0,0 +1,41 @@ +From d59650049693250157d2b74f0987420288796a4e Mon Sep 17 00:00:00 2001 +From: "Zhang, Lili Z" +Date: Sun, 14 Apr 2024 21:09:36 +0800 +Subject: [PATCH] IPP crypto for SGX. + +Signed-off-by: Zhang, Lili Z +--- + CMakeLists.txt | 3 +++ + sources/cmake/linux/GNU8.2.0.cmake | 2 +- + 2 files changed, 4 insertions(+), 1 deletion(-) + +diff --git a/CMakeLists.txt b/CMakeLists.txt +index 27d9d3a7..c5e91f80 100644 +--- a/CMakeLists.txt ++++ b/CMakeLists.txt +@@ -20,6 +20,9 @@ + + cmake_minimum_required(VERSION 3.12) + ++set(SGX_PROGRAM_SEARCH_PATH) ++LIST(APPEND CMAKE_PROGRAM_PATH "/usr/local/bin/" ${SGX_PROGRAM_SEARCH_PATH} ...) ++ + include("${CMAKE_CURRENT_SOURCE_DIR}/sources/cmake/ippcp-utils.cmake") + ippcp_getlibversion("${CMAKE_CURRENT_SOURCE_DIR}/include/ippversion.h") + if ((NOT DEFINED IPPCP_VERSION_MAJOR) OR +diff --git a/sources/cmake/linux/GNU8.2.0.cmake b/sources/cmake/linux/GNU8.2.0.cmake +index 96658a8d..a4405c60 100644 +--- a/sources/cmake/linux/GNU8.2.0.cmake ++++ b/sources/cmake/linux/GNU8.2.0.cmake +@@ -96,7 +96,7 @@ if(${ARCH} MATCHES "ia32") + endif(${ARCH} MATCHES "ia32") + + # Optimization level = 3, no-debug definition (turns off asserts), warnings=errors +-set (CMAKE_C_FLAGS_RELEASE " -O3 -DNDEBUG -Werror") ++set (CMAKE_C_FLAGS_RELEASE " -O3 -DNDEBUG -Werror -Wno-stringop-overflow") + + set(w7_opt "${w7_opt} -march=pentium4 -msse2") + set(s8_opt "${s8_opt} -march=core2 -mssse3") +-- +2.25.1 + diff --git a/external/ippcp_internal/Makefile b/external/ippcp_internal/Makefile index b8461dcb2..a57c22a99 100644 --- a/external/ippcp_internal/Makefile +++ b/external/ippcp_internal/Makefile @@ -51,7 +51,7 @@ IPP_CONFIG += -DCMAKE_CXX_FLAGS="$(ENC_CXXFLAGS)" IPP_CONFIG += -DSGX_PROGRAM_SEARCH_PATH="$(EXT_BINUTILS_DIR)" # enables all FIPS-compliance changes in ipp-crypto -IPP_CONFIG += -DIPPCP_FIPS_MODE=on +IPP_CONFIG += -DIPPCP_FIPS_MODE=on -DFIPS_CUSTOM_IPPCP_API_HEADER=$(CURDIR)/inc/sgx_ippcp.h SUB_DIR = no_mitigation ifeq ($(MITIGATION-CVE-2020-0551), LOAD) @@ -77,7 +77,7 @@ all: build_ipp $(MKDIR) $(OUT_DIR) $(CP) ipp-crypto/build/.build/RELEASE/lib/libippcp.a $(OUT_DIR) $(CP) -r ipp-crypto/include/* ./inc/ - patch ipp-crypto/include/ippcp.h -i ./inc/ippcp21u11.patch -o ./inc/ippcp.h + patch ipp-crypto/include/ippcp.h -i ./inc/ippcp21u12.patch -o ./inc/ippcp.h $(MKDIR) license $(CP) ipp-crypto/LICENSE ./license/ @@ -89,8 +89,9 @@ ifeq ($(shell git rev-parse --is-inside-work-tree), true) git submodule update -f --init --recursive --remote -- $(IPP_SOURCE) else $(RM) -rf $(IPP_SOURCE) - git clone -b ipp-crypto_2021_11_0 https://github.com/intel/ipp-crypto.git --depth 1 $(IPP_SOURCE) + git clone -b ipp-crypto_2021_12_1 https://github.com/intel/ipp-crypto.git --depth 1 $(IPP_SOURCE) endif + cd $(IPP_SOURCE) && git apply ../0001-IPP-crypto-for-SGX.patch mkdir -p $(IPP_SOURCE)/build .PHONY: clean diff --git a/external/ippcp_internal/README.md b/external/ippcp_internal/README.md index 26f71e6a0..ec22b9358 100644 --- a/external/ippcp_internal/README.md +++ b/external/ippcp_internal/README.md @@ -1,6 +1,6 @@ The ippcp library is built based on the IPP Cryptography open source project: * https://github.com/intel/ipp-crypto/ - * tag: [ippcp_2021.11.0](https://github.com/intel/ipp-crypto/tree/ippcp_2021.11.0) + * tag: [ippcp_2021.12.1](https://github.com/intel/ipp-crypto/tree/ippcp_2021.12.1) In order to build your own IPP crypto, please follow below steps: 1. Download the prebuilt mitigation tools package `as.ld.objdump.{ver}.tar.gz` from [01.org](https://download.01.org/intel-sgx/latest/linux-latest/), extract the package and copy the tools to `/usr/local/bin`. diff --git a/external/ippcp_internal/inc/ippcp21u11.patch b/external/ippcp_internal/inc/ippcp21u12.patch similarity index 63% rename from external/ippcp_internal/inc/ippcp21u11.patch rename to external/ippcp_internal/inc/ippcp21u12.patch index 9830cbdbc..0dc8470fe 100644 --- a/external/ippcp_internal/inc/ippcp21u11.patch +++ b/external/ippcp_internal/inc/ippcp21u12.patch @@ -1,5 +1,5 @@ ---- ipp-crypto/include/ippcp.h 2024-02-22 19:41:23.658965440 +0800 -+++ inc/ippcp.h 2024-02-22 19:53:45.942962608 +0800 +--- ipp-crypto/include/ippcp.h 2024-06-18 11:13:31.626811418 +0800 ++++ inc/ippcp.h 2024-06-18 10:55:33.346815531 +0800 @@ -23,6 +23,9 @@ #if !defined( IPPCP_H__ ) || defined( _OWN_BLDPCS ) #define IPPCP_H__ diff --git a/external/ippcp_internal/inc/sgx_ippcp.h b/external/ippcp_internal/inc/sgx_ippcp.h index d8eff0d30..4b2aebe37 100644 --- a/external/ippcp_internal/inc/sgx_ippcp.h +++ b/external/ippcp_internal/inc/sgx_ippcp.h @@ -583,5 +583,12 @@ #define ippsXMSSSetSignatureState sgx_disp_ippsXMSSSetSignatureState #define ippsXMSSVerify sgx_disp_ippsXMSSVerify +#define ippsLMSBufferGetSize sgx_disp_ippsLMSBufferGetSize +#define ippsLMSSignatureStateGetSize sgx_disp_ippsLMSSignatureStateGetSize +#define ippsLMSPublicKeyStateGetSize sgx_disp_ippsLMSPublicKeyStateGetSize +#define ippsLMSSetPublicKeyState sgx_disp_ippsLMSSetPublicKeyState +#define ippsLMSSetSignatureState sgx_disp_ippsLMSSetSignatureState +#define ippsLMSVerify sgx_disp_ippsLMSVerify + #endif diff --git a/external/ippcp_internal/ipp-crypto b/external/ippcp_internal/ipp-crypto index a8d6774dd..7d6ac3495 160000 --- a/external/ippcp_internal/ipp-crypto +++ b/external/ippcp_internal/ipp-crypto @@ -1 +1 @@ -Subproject commit a8d6774ddbc27f6caeee9418eb52a10a549cac0a +Subproject commit 7d6ac349507258f49d00909df33d5dea4ff77f39 diff --git a/external/mbedtls/mbedtls_code b/external/mbedtls/mbedtls_code index daca7a397..2ca6c285a 160000 --- a/external/mbedtls/mbedtls_code +++ b/external/mbedtls/mbedtls_code @@ -1 +1 @@ -Subproject commit daca7a3979c22da155ec9dce49ab1abf3b65d3a9 +Subproject commit 2ca6c285a0dd3f33982dd57299012dacab1ff206 diff --git a/external/mbedtls/sgx_mbedtls.patch b/external/mbedtls/sgx_mbedtls.patch index cc08edc3e..28a8481d4 100644 --- a/external/mbedtls/sgx_mbedtls.patch +++ b/external/mbedtls/sgx_mbedtls.patch @@ -1,5 +1,21 @@ +diff --git a/CMakeLists.txt b/CMakeLists.txt +index 2eba16da5..ba0d28fa2 100644 +--- a/CMakeLists.txt ++++ b/CMakeLists.txt +@@ -283,11 +283,6 @@ if(LIB_INSTALL_DIR) + set(CMAKE_INSTALL_LIBDIR "${LIB_INSTALL_DIR}") + endif() + +-if (NOT EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/framework/CMakeLists.txt") +- message(FATAL_ERROR "${CMAKE_CURRENT_SOURCE_DIR}/framework/CMakeLists.txt not found. Run `git submodule update --init` from the source tree to fetch the submodule contents.") +-endif() +-add_subdirectory(framework) +- + add_subdirectory(include) + + add_subdirectory(3rdparty) diff --git a/include/mbedtls/mbedtls_config.h b/include/mbedtls/mbedtls_config.h -index e1456b9ae..a2bf860d5 100644 +index 35921412c..258610281 100644 --- a/include/mbedtls/mbedtls_config.h +++ b/include/mbedtls/mbedtls_config.h @@ -77,7 +77,7 @@ @@ -74,7 +90,16 @@ index e1456b9ae..a2bf860d5 100644 /** * \def MBEDTLS_ENTROPY_FORCE_SHA256 -@@ -2076,7 +2076,7 @@ +@@ -1791,7 +1791,7 @@ + * + * Uncomment this macro to enable the support for TLS 1.3. + */ +-#define MBEDTLS_SSL_PROTO_TLS1_3 ++//#define MBEDTLS_SSL_PROTO_TLS1_3 + + /** + * \def MBEDTLS_SSL_TLS1_3_COMPATIBILITY_MODE +@@ -2090,7 +2090,7 @@ * * Uncomment this to enable pthread mutexes. */ @@ -83,7 +108,7 @@ index e1456b9ae..a2bf860d5 100644 /** * \def MBEDTLS_USE_PSA_CRYPTO -@@ -2804,7 +2804,7 @@ +@@ -2871,7 +2871,7 @@ * * Uncomment to enable the LMS verification algorithm and public key operations. */ @@ -92,7 +117,7 @@ index e1456b9ae..a2bf860d5 100644 /** * \def MBEDTLS_LMS_PRIVATE -@@ -2955,7 +2955,7 @@ +@@ -3022,7 +3022,7 @@ * * This modules adds support for the VIA PadLock on x86. */ @@ -101,16 +126,16 @@ index e1456b9ae..a2bf860d5 100644 /** * \def MBEDTLS_PEM_PARSE_C -@@ -3137,7 +3137,7 @@ - * or MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG. - * +@@ -3204,7 +3204,7 @@ + * is enabled in PSA (unless it's fully accelerated, see + * docs/driver-only-builds.md about that). */ -#define MBEDTLS_PSA_CRYPTO_C +//#define MBEDTLS_PSA_CRYPTO_C /** * \def MBEDTLS_PSA_CRYPTO_SE_C -@@ -3166,7 +3166,7 @@ +@@ -3236,7 +3236,7 @@ * either MBEDTLS_PSA_ITS_FILE_C or a native implementation of * the PSA ITS interface */ @@ -119,7 +144,7 @@ index e1456b9ae..a2bf860d5 100644 /** * \def MBEDTLS_PSA_ITS_FILE_C -@@ -3178,7 +3178,7 @@ +@@ -3248,7 +3248,7 @@ * * Requires: MBEDTLS_FS_IO */ @@ -128,7 +153,7 @@ index e1456b9ae..a2bf860d5 100644 /** * \def MBEDTLS_RIPEMD160_C -@@ -3513,7 +3513,7 @@ +@@ -3609,7 +3609,7 @@ * * Enable this layer to allow use of mutexes within Mbed TLS */ @@ -137,7 +162,7 @@ index e1456b9ae..a2bf860d5 100644 /** * \def MBEDTLS_TIMING_C -@@ -3537,7 +3537,7 @@ +@@ -3633,7 +3633,7 @@ * * Module: library/timing.c */ @@ -147,7 +172,7 @@ index e1456b9ae..a2bf860d5 100644 /** * \def MBEDTLS_VERSION_C diff --git a/library/aesni.c b/library/aesni.c -index 59bcd3d92..73d9faf37 100644 +index 8e5bd55ab..982cff899 100644 --- a/library/aesni.c +++ b/library/aesni.c @@ -11,6 +11,7 @@ @@ -158,12 +183,12 @@ index 59bcd3d92..73d9faf37 100644 #if defined(MBEDTLS_AESNI_C) -@@ -39,21 +40,11 @@ int mbedtls_aesni_has_support(unsigned int what) +@@ -52,21 +53,11 @@ int mbedtls_aesni_has_support(unsigned int what) static unsigned int c = 0; if (!done) { -#if MBEDTLS_AESNI_HAVE_CODE == 2 -- static unsigned info[4] = { 0, 0, 0, 0 }; +- static int info[4] = { 0, 0, 0, 0 }; -#if defined(_MSC_VER) - __cpuid(info, 1); -#else @@ -179,7 +204,7 @@ index 59bcd3d92..73d9faf37 100644 -#endif /* MBEDTLS_AESNI_HAVE_CODE */ + int cpuinfo[4] = { -1 }; + int status = sgx_cpuid(cpuinfo, 1); -+ if ( 0 != status ) { ++ if ( 0 != status ) { + c = cpuinfo[2]; + } done = 1; @@ -218,7 +243,7 @@ index e3bc8516e..2fd5cb9d2 100644 { int ret = 0; diff --git a/library/rsa.c b/library/rsa.c -index 0ca0bfead..25a6c4177 100644 +index 7eb4a259e..3cea5ef00 100644 --- a/library/rsa.c +++ b/library/rsa.c @@ -22,6 +22,7 @@ @@ -229,7 +254,7 @@ index 0ca0bfead..25a6c4177 100644 #include "common.h" -@@ -2488,15 +2489,12 @@ void mbedtls_rsa_free(mbedtls_rsa_context *ctx) +@@ -2889,15 +2890,12 @@ void mbedtls_rsa_free(mbedtls_rsa_context *ctx) static int myrand(void *rng_state, unsigned char *output, size_t len) { #if !defined(__OpenBSD__) && !defined(__NetBSD__) diff --git a/external/sgxssl/prepare_sgxssl.sh b/external/sgxssl/prepare_sgxssl.sh index f1e9d3a88..a936eb7c0 100755 --- a/external/sgxssl/prepare_sgxssl.sh +++ b/external/sgxssl/prepare_sgxssl.sh @@ -32,16 +32,16 @@ top_dir="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" openssl_out_dir=$top_dir/openssl_source -openssl_ver=3.0.13 +openssl_ver=3.0.14 openssl_ver_name=openssl-$openssl_ver sgxssl_github_archive=https://github.com/intel/intel-sgx-ssl/archive -sgxssl_file_name=3.0_Rev2 +sgxssl_file_name=3.0_Rev4 build_script=$top_dir/Linux/build_openssl.sh server_url_path=https://www.openssl.org/source full_openssl_url=$server_url_path/old/3.0/$openssl_ver_name.tar.gz -sgxssl_chksum=269e1171f566ac6630d83c3b6cf9669e254b08a7f208cc8cf59f471f3d8a579b -openssl_chksum=88525753f79d3bec27d2fa7c66aa0b92b3aa9498dafd93d7cfa4b3780cdae313 +sgxssl_chksum=3ae56df48a56f58fce8d0472ea82cc4380e30442b49b931c027fda9e637cb3fa +openssl_chksum=eeca035d4dd4e84fc25846d952da6297484afa0650a6f84c682e39df3a4123ca rm -f check_sum_sgxssl.txt check_sum_openssl.txt if [ ! -f $build_script ]; then wget $sgxssl_github_archive/$sgxssl_file_name.zip -P $top_dir || exit 1 diff --git a/linux/installer/common/psw/BOMs/psw_base.txt b/linux/installer/common/psw/BOMs/psw_base.txt index 2a960a758..525129d8d 100644 --- a/linux/installer/common/psw/BOMs/psw_base.txt +++ b/linux/installer/common/psw/BOMs/psw_base.txt @@ -5,8 +5,8 @@ DeliveryName InstallName FileCheckSum FileFeature FileOwner /build/linux/libipc.so /package/aesm/libipc.so 0 main STP /build/linux/liboal.so /package/aesm/liboal.so 0 main STP /build/linux/libutils.so /package/aesm/libutils.so 0 main STP -/build/linux/libdcap_quoteprov.so /package/aesm/libdcap_quoteprov.so 0 main STP -/build/linux/libsgx_default_qcnl_wrapper.so /package/aesm/libsgx_default_qcnl_wrapper.so 0 main STP +/external/dcap_source/QuoteGeneration/build/linux/libdcap_quoteprov.so /package/aesm/libdcap_quoteprov.so 0 main STP +/external/dcap_source/QuoteGeneration/build/linux/libsgx_default_qcnl_wrapper.so /package/aesm/libsgx_default_qcnl_wrapper.so 0 main STP /build/linux/liburts_internal.so /package/aesm/liburts_internal.so 0 main STP /build/linux/libCppMicroServices.so.4.0.0 /package/aesm/libCppMicroServices.so.4.0.0 0 main STP /external/dcap_source/QuoteGeneration/build/linux/libsgx_pce_logic.so /package/aesm/libsgx_pce_logic.so.1 0 main STP diff --git a/linux/installer/common/sdk/BOMs/sdk_base.txt b/linux/installer/common/sdk/BOMs/sdk_base.txt index a6d4fd7e6..032479d86 100644 --- a/linux/installer/common/sdk/BOMs/sdk_base.txt +++ b/linux/installer/common/sdk/BOMs/sdk_base.txt @@ -1,45 +1,45 @@ DeliveryName InstallName FileCheckSum FileFeature FileOwner /build/linux/libsample_libcrypto.so /package/SampleCode/RemoteAttestation/sample_libcrypto/libsample_libcrypto.so 0 main STP -/common/inc/sgx_attributes.h /package/include/./sgx_attributes.h 0 main STP -/common/inc/sgx_capable.h /package/include/./sgx_capable.h 0 main STP -/common/inc/sgx_cpuid.h /package/include/./sgx_cpuid.h 0 main STP -/common/inc/sgx_defs.h /package/include/./sgx_defs.h 0 main STP -/common/inc/sgx_dh.h /package/include/./sgx_dh.h 0 main STP -/common/inc/sgx_ecp_types.h /package/include/./sgx_ecp_types.h 0 main STP -/common/inc/sgx_edger8r.h /package/include/./sgx_edger8r.h 0 main STP -/common/inc/sgx_lfence.h /package/include/./sgx_lfence.h 0 main STP -/common/inc/sgx_eid.h /package/include/./sgx_eid.h 0 main STP -/common/inc/sgx_error.h /package/include/./sgx_error.h 0 main STP -/common/inc/sgx.h /package/include/./sgx.h 0 main STP -/common/inc/sgx_intrin.h /package/include/./sgx_intrin.h 0 main STP -/common/inc/sgx_key_exchange.h /package/include/./sgx_key_exchange.h 0 main STP -/common/inc/sgx_key.h /package/include/./sgx_key.h 0 main STP -/common/inc/sgx_quote.h /package/include/./sgx_quote.h 0 main STP -/common/inc/sgx_report.h /package/include/./sgx_report.h 0 main STP -/common/inc/sgx_report2.h /package/include/./sgx_report2.h 0 main STP -/common/inc/sgx_spinlock.h /package/include/./sgx_spinlock.h 0 main STP -/common/inc/sgx_tcrypto.h /package/include/./sgx_tcrypto.h 0 main STP -/common/inc/sgx_thread.h /package/include/./sgx_thread.h 0 main STP -/common/inc/sgx_tkey_exchange.edl /package/include/./sgx_tkey_exchange.edl 0 main STP -/common/inc/sgx_tkey_exchange.h /package/include/./sgx_tkey_exchange.h 0 main STP -/common/inc/sgx_trts_exception.h /package/include/./sgx_trts_exception.h 0 main STP -/common/inc/sgx_trts.h /package/include/./sgx_trts.h 0 main STP -/common/inc/sgx_tseal.h /package/include/./sgx_tseal.h 0 main STP -/common/inc/sgx_tstdc.edl /package/include/./sgx_tstdc.edl 0 main STP -/common/inc/sgx_uae_service.h /package/include/./sgx_uae_service.h 0 main STP -/common/inc/sgx_uae_epid.h /package/include/./sgx_uae_epid.h 0 main STP -/common/inc/sgx_uae_launch.h /package/include/./sgx_uae_launch.h 0 main STP -/common/inc/sgx_uae_quote_ex.h /package/include/./sgx_uae_quote_ex.h 0 main STP -/common/inc/sgx_ukey_exchange.h /package/include/./sgx_ukey_exchange.h 0 main STP -/common/inc/sgx_urts.h /package/include/./sgx_urts.h 0 main STP -/common/inc/sgx_utils.h /package/include/./sgx_utils.h 0 main STP -/common/inc/sgx_uswitchless.h /package/include/./sgx_uswitchless.h 0 main STP -/common/inc/sgx_tswitchless.edl /package/include/./sgx_tswitchless.edl 0 main STP -/common/inc/sgx_tprotected_fs.h /package/include/./sgx_tprotected_fs.h 0 main STP -/common/inc/sgx_tprotected_fs.edl /package/include/./sgx_tprotected_fs.edl 0 main STP -/common/inc/sgx_pcl_guid.h /package/include/./sgx_pcl_guid.h 0 main STP -/common/inc/sgx_secure_align.h /package/include/./sgx_secure_align.h 0 main STP -/common/inc/sgx_secure_align_api.h /package/include/./sgx_secure_align_api.h 0 main STP +/common/inc/sgx_attributes.h /package/include/sgx_attributes.h 0 main STP +/common/inc/sgx_capable.h /package/include/sgx_capable.h 0 main STP +/common/inc/sgx_cpuid.h /package/include/sgx_cpuid.h 0 main STP +/common/inc/sgx_defs.h /package/include/sgx_defs.h 0 main STP +/common/inc/sgx_dh.h /package/include/sgx_dh.h 0 main STP +/common/inc/sgx_ecp_types.h /package/include/sgx_ecp_types.h 0 main STP +/common/inc/sgx_edger8r.h /package/include/sgx_edger8r.h 0 main STP +/common/inc/sgx_lfence.h /package/include/sgx_lfence.h 0 main STP +/common/inc/sgx_eid.h /package/include/sgx_eid.h 0 main STP +/common/inc/sgx_error.h /package/include/sgx_error.h 0 main STP +/common/inc/sgx.h /package/include/sgx.h 0 main STP +/common/inc/sgx_intrin.h /package/include/sgx_intrin.h 0 main STP +/common/inc/sgx_key_exchange.h /package/include/sgx_key_exchange.h 0 main STP +/common/inc/sgx_key.h /package/include/sgx_key.h 0 main STP +/common/inc/sgx_quote.h /package/include/sgx_quote.h 0 main STP +/common/inc/sgx_report.h /package/include/sgx_report.h 0 main STP +/common/inc/sgx_report2.h /package/include/sgx_report2.h 0 main STP +/common/inc/sgx_spinlock.h /package/include/sgx_spinlock.h 0 main STP +/common/inc/sgx_tcrypto.h /package/include/sgx_tcrypto.h 0 main STP +/common/inc/sgx_thread.h /package/include/sgx_thread.h 0 main STP +/common/inc/sgx_tkey_exchange.edl /package/include/sgx_tkey_exchange.edl 0 main STP +/common/inc/sgx_tkey_exchange.h /package/include/sgx_tkey_exchange.h 0 main STP +/common/inc/sgx_trts_exception.h /package/include/sgx_trts_exception.h 0 main STP +/common/inc/sgx_trts.h /package/include/sgx_trts.h 0 main STP +/common/inc/sgx_tseal.h /package/include/sgx_tseal.h 0 main STP +/common/inc/sgx_tstdc.edl /package/include/sgx_tstdc.edl 0 main STP +/common/inc/sgx_uae_service.h /package/include/sgx_uae_service.h 0 main STP +/common/inc/sgx_uae_epid.h /package/include/sgx_uae_epid.h 0 main STP +/common/inc/sgx_uae_launch.h /package/include/sgx_uae_launch.h 0 main STP +/common/inc/sgx_uae_quote_ex.h /package/include/sgx_uae_quote_ex.h 0 main STP +/common/inc/sgx_ukey_exchange.h /package/include/sgx_ukey_exchange.h 0 main STP +/common/inc/sgx_urts.h /package/include/sgx_urts.h 0 main STP +/common/inc/sgx_utils.h /package/include/sgx_utils.h 0 main STP +/common/inc/sgx_uswitchless.h /package/include/sgx_uswitchless.h 0 main STP +/common/inc/sgx_tswitchless.edl /package/include/sgx_tswitchless.edl 0 main STP +/common/inc/sgx_tprotected_fs.h /package/include/sgx_tprotected_fs.h 0 main STP +/common/inc/sgx_tprotected_fs.edl /package/include/sgx_tprotected_fs.edl 0 main STP +/common/inc/sgx_pcl_guid.h /package/include/sgx_pcl_guid.h 0 main STP +/common/inc/sgx_secure_align.h /package/include/sgx_secure_align.h 0 main STP +/common/inc/sgx_secure_align_api.h /package/include/sgx_secure_align_api.h 0 main STP /common/inc/sgx_rsrv_mem_mngr.h /package/include/sgx_rsrv_mem_mngr.h 0 main STP /common/inc/sgx_trts_aex.h /package/include/sgx_trts_aex.h 0 main STP /common/inc/stdc++/exception /package/include/stdc++/exception 0 main STP @@ -81,7 +81,7 @@ DeliveryName InstallName FileCheckSum FileFeature FileOwner /common/inc/sgx_utls.h /package/include/sgx_utls.h 0 main STP /common/inc/sgx_ttls.h /package/include/sgx_ttls.h 0 main STP /common/inc/sgx_ttls.edl /package/include/sgx_ttls.edl 0 main STP -/psw/enclave_common/sgx_enclave_common.h /package/include/./sgx_enclave_common.h 0 main STP +/psw/enclave_common/sgx_enclave_common.h /package/include/sgx_enclave_common.h 0 main STP /external/ippcp_internal/inc/ippcp.h /package/include/ipp/ippcp.h 0 main STP /external/ippcp_internal/inc/ippcpdefs.h /package/include/ipp/ippcpdefs.h 0 main STP /external/ippcp_internal/inc/ippversion.h /package/include/ipp/ippversion.h 0 main STP @@ -90,15 +90,17 @@ DeliveryName InstallName FileCheckSum FileFeature FileOwner /external/sgx-emm/emm_src/include/sgx_mm.h /package/include/sgx_mm.h 0 main STP /linux/installer/common/sdk/install.sh /scripts/install.sh 0 main STP /linux/installer/common/sdk/Makefile /Makefile 0 main STP -/external/dcap_source/QuoteGeneration/quote_wrapper/common/inc/sgx_ql_lib_common.h /package/include/./sgx_ql_lib_common.h 0 main STP -/external/dcap_source/QuoteGeneration/pce_wrapper/inc/sgx_pce.h /package/include/./sgx_pce.h 0 main STP -/external/dcap_source/QuoteGeneration/quote_wrapper/common/inc/sgx_quote_3.h /package/include/./sgx_quote_3.h 0 main STP -/external/dcap_source/QuoteGeneration/quote_wrapper/common/inc/sgx_quote_4.h /package/include/./sgx_quote_4.h 0 main STP -/external/dcap_source/QuoteGeneration/quote_wrapper/common/inc/sgx_quote_5.h /package/include/./sgx_quote_5.h 0 main STP -/external/dcap_source/QuoteGeneration/quote_wrapper/common/inc/sgx_ql_quote.h /package/include/./sgx_ql_quote.h 0 main STP -/external/dcap_source/QuoteVerification/QvE/Include/sgx_qve_header.h /package/include/./sgx_qve_header.h 0 main STP -/external/dcap_source/QuoteVerification/dcap_tvl/sgx_dcap_tvl.h /package/include/./sgx_dcap_tvl.h 0 main STP -/external/dcap_source/QuoteVerification/dcap_tvl/sgx_dcap_tvl.edl /package/include/./sgx_dcap_tvl.edl 0 main STP +/external/dcap_source/QuoteGeneration/quote_wrapper/common/inc/sgx_ql_lib_common.h /package/include/sgx_ql_lib_common.h 0 main STP +/external/dcap_source/QuoteGeneration/pce_wrapper/inc/sgx_pce.h /package/include/sgx_pce.h 0 main STP +/external/dcap_source/QuoteGeneration/quote_wrapper/common/inc/sgx_quote_3.h /package/include/sgx_quote_3.h 0 main STP +/external/dcap_source/QuoteGeneration/quote_wrapper/common/inc/sgx_quote_4.h /package/include/sgx_quote_4.h 0 main STP +/external/dcap_source/QuoteGeneration/quote_wrapper/common/inc/sgx_quote_5.h /package/include/sgx_quote_5.h 0 main STP +/external/dcap_source/QuoteGeneration/quote_wrapper/common/inc/sgx_ql_quote.h /package/include/sgx_ql_quote.h 0 main STP +/external/dcap_source/QuoteVerification/appraisal/qal/sgx_dcap_qal.h /package/include/sgx_dcap_qal.h 0 main STP +/external/dcap_source/QuoteVerification/QvE/Include/sgx_qve_header.h /package/include/sgx_qve_header.h 0 main STP +/external/dcap_source/QuoteVerification/dcap_tvl/sgx_dcap_tvl.h /package/include/sgx_dcap_tvl.h 0 main STP +/external/dcap_source/QuoteVerification/dcap_tvl/sgx_dcap_tvl.edl /package/include/sgx_dcap_tvl.edl 0 main STP +/external/dcap_source/QuoteVerification/dcap_tvl/sgx_dcap_qae_tvl.h /package/include/sgx_dcap_qae_tvl.h 0 main STP /SampleCode/LocalAttestation/App/App.cpp /package/SampleCode/LocalAttestation/App/App.cpp 0 main STP /SampleCode/LocalAttestation/AppInitiator/App.cpp /package/SampleCode/LocalAttestation/AppInitiator/App.cpp 0 main STP /SampleCode/LocalAttestation/AppInitiator/datatypes.h /package/SampleCode/LocalAttestation/AppInitiator/datatypes.h 0 main STP diff --git a/linux/installer/deb/local_repo_tool/conf/distributions b/linux/installer/deb/local_repo_tool/conf/distributions index add1ee61d..9f29de710 100644 --- a/linux/installer/deb/local_repo_tool/conf/distributions +++ b/linux/installer/deb/local_repo_tool/conf/distributions @@ -54,6 +54,14 @@ Components: main Description: ubuntu/mantic repository for SGX PSW DebIndices: Packages . +Origin: Intel Corporation +Label: Intel Corporation +Codename: noble +Architectures: amd64 +Components: main +Description: ubuntu/noble repository for SGX PSW +DebIndices: Packages . + Origin: Intel Corporation Label: Intel Corporation Codename: buster diff --git a/linux/installer/deb/sgx-aesm-service/sgx-aesm-service-1.0/debian/control b/linux/installer/deb/sgx-aesm-service/sgx-aesm-service-1.0/debian/control index 5e618f369..69f121346 100644 --- a/linux/installer/deb/sgx-aesm-service/sgx-aesm-service-1.0/debian/control +++ b/linux/installer/deb/sgx-aesm-service/sgx-aesm-service-1.0/debian/control @@ -37,12 +37,12 @@ Description: Unified Quote Plugin for Intel(R) Software Guard Extensions AESM Se Package: libsgx-aesm-ecdsa-plugin Architecture: amd64 -Depends: ${shlibs:Depends}, ${misc:Depends}, sgx-aesm-service(>= @dep_version@), libsgx-qe3-logic(>= 1.21), libsgx-aesm-pce-plugin(>= @dep_version@) +Depends: ${shlibs:Depends}, ${misc:Depends}, sgx-aesm-service(>= @dep_version@), libsgx-qe3-logic(>= 1.22), libsgx-aesm-pce-plugin(>= @dep_version@) Description: ECDSA Quote Plugin for Intel(R) Software Guard Extensions AESM Service Package: libsgx-aesm-pce-plugin Architecture: amd64 -Depends: ${shlibs:Depends}, ${misc:Depends}, sgx-aesm-service(>= @dep_version@), libsgx-pce-logic(>= 1.21), libsgx-ae-pce(>= @dep_version@) +Depends: ${shlibs:Depends}, ${misc:Depends}, sgx-aesm-service(>= @dep_version@), libsgx-pce-logic(>= 1.22), libsgx-ae-pce(>= @dep_version@) Description: PCE Plugin for Intel(R) Software Guard Extensions AESM Service Package: libsgx-ae-pce diff --git a/linux/installer/rpm/sgx-aesm-service/libsgx-aesm-ecdsa-plugin.spec b/linux/installer/rpm/sgx-aesm-service/libsgx-aesm-ecdsa-plugin.spec index 6f20e9a43..507bb3fc7 100644 --- a/linux/installer/rpm/sgx-aesm-service/libsgx-aesm-ecdsa-plugin.spec +++ b/linux/installer/rpm/sgx-aesm-service/libsgx-aesm-ecdsa-plugin.spec @@ -38,7 +38,7 @@ Version: @version@ Release: 1%{?dist} Summary: ECDSA Quote Plugin for Intel(R) Software Guard Extensions AESM Service Group: Development/System -Requires: sgx-aesm-service >= %{version}-%{release} libsgx-qe3-logic >= 1.21 libsgx-aesm-pce-plugin >= %{version}-%{release} +Requires: sgx-aesm-service >= %{version}-%{release} libsgx-qe3-logic >= 1.22 libsgx-aesm-pce-plugin >= %{version}-%{release} License: BSD License URL: https://github.com/intel/linux-sgx diff --git a/linux/installer/rpm/sgx-aesm-service/libsgx-aesm-pce-plugin.spec b/linux/installer/rpm/sgx-aesm-service/libsgx-aesm-pce-plugin.spec index 901a53a12..a814f4ae4 100644 --- a/linux/installer/rpm/sgx-aesm-service/libsgx-aesm-pce-plugin.spec +++ b/linux/installer/rpm/sgx-aesm-service/libsgx-aesm-pce-plugin.spec @@ -38,7 +38,7 @@ Version: @version@ Release: 1%{?dist} Summary: PCE Plugin for Intel(R) Software Guard Extensions AESM Service Group: Development/System -Requires: sgx-aesm-service >= %{version}-%{release} libsgx-pce-logic >= 1.21 +Requires: sgx-aesm-service >= %{version}-%{release} libsgx-pce-logic >= 1.22 License: BSD License URL: https://github.com/intel/linux-sgx diff --git a/linux/reproducibility/ae_reproducibility_verifier/README.md b/linux/reproducibility/ae_reproducibility_verifier/README.md index 00ea4f895..be2e68a10 100644 --- a/linux/reproducibility/ae_reproducibility_verifier/README.md +++ b/linux/reproducibility/ae_reproducibility_verifier/README.md @@ -63,4 +63,4 @@ This document outlines a process to guarantee Intel(R) prebuilt AEs are: Meanwhile, you can find the metadata of Intel and user are generated in *./output/intel_metadata.txt* and *./output/user_metadata.txt* - For one release, we may not sign all the AEs but only sign a portion of them. So please don't anticipate to reproduce all of the AEs in a single release. -You can refer to [README.md](/psw/ae/data/prebuilt/README.md) and [README.md](https://github.com/intel/SGXDataCenterAttestationPrimitives/blob/dcap_1.21_reproducible/QuoteGeneration/psw/ae/data/prebuilt/README.md) to obtain the appropriate reproducible release for each AE and utilize the corresponding release branch to reproduce the AE. +You can refer to [README.md](/psw/ae/data/prebuilt/README.md) and [README.md](https://github.com/intel/SGXDataCenterAttestationPrimitives/blob/dcap_1.22_reproducible/QuoteGeneration/psw/ae/data/prebuilt/README.md) to obtain the appropriate reproducible release for each AE and utilize the corresponding release branch to reproduce the AE. diff --git a/linux/reproducibility/build_and_launch_docker.sh b/linux/reproducibility/build_and_launch_docker.sh index 6091d0951..eb09f1f5d 100755 --- a/linux/reproducibility/build_and_launch_docker.sh +++ b/linux/reproducibility/build_and_launch_docker.sh @@ -75,8 +75,8 @@ mount_dir="/linux-sgx" sdk_installer="" sgx_src="" -default_sdk_installer=sgx_linux_x64_sdk_reproducible_2.24.100.1.bin -default_sdk_installer_url=https://download.01.org/intel-sgx/sgx-linux/2.24/distro/nix_reproducibility/$default_sdk_installer +default_sdk_installer=sgx_linux_x64_sdk_reproducible_2.25.100.1.bin +default_sdk_installer_url=https://download.01.org/intel-sgx/sgx-linux/2.25/distro/nix_reproducibility/$default_sdk_installer usage() @@ -177,7 +177,7 @@ prepare_sgx_src() if [ "$sgx_src" != "" ]; then mkdir -p "$sgx_repo" && cp -a "$sgx_src/." "$sgx_repo" else - git clone -b sgx_2.24_reproducible https://github.com/intel/linux-sgx.git $sgx_repo + git clone -b sgx_2.25_reproducible https://github.com/intel/linux-sgx.git $sgx_repo fi cd "$sgx_repo" && make preparation diff --git a/psw/ae/aesm_service/Makefile b/psw/ae/aesm_service/Makefile index 048953186..498d6e2fc 100644 --- a/psw/ae/aesm_service/Makefile +++ b/psw/ae/aesm_service/Makefile @@ -35,7 +35,7 @@ include $(TOP_DIR)/buildenv.mk CPPMICROSERVICES_DIR := $(LINUX_EXTERNAL_DIR)/CppMicroServices CPPMICROSERVICES_INSTALL := $(CPPMICROSERVICES_DIR)/local-install AESM_CONFIG := -DBUILD_SHARED_LIBS=ON -DUS_BUILD_SHARED_LIBS=ON -CPPMICROSERVICES_CONFIG := -DCMAKE_INSTALL_PREFIX=$(CPPMICROSERVICES_INSTALL) -DCMAKE_BUILD_TYPE=RelWithDebInfo -DCMAKE_C_FLAGS= -DCMAKE_CXX_FLAGS= +CPPMICROSERVICES_CONFIG := -DCMAKE_INSTALL_PREFIX=$(CPPMICROSERVICES_INSTALL) -DCMAKE_BUILD_TYPE=RelWithDebInfo -DCMAKE_C_FLAGS= -DCMAKE_CXX_FLAGS= -DFORTIFY_SOURCE_VAL=$(FORTIFY_SOURCE_VAL) ifdef DEBUG AESM_CONFIG += -DCMAKE_BUILD_TYPE=Debug else diff --git a/psw/ae/aesm_service/source/CMakeLists.txt b/psw/ae/aesm_service/source/CMakeLists.txt index ffc1bee7c..98c724a70 100644 --- a/psw/ae/aesm_service/source/CMakeLists.txt +++ b/psw/ae/aesm_service/source/CMakeLists.txt @@ -59,9 +59,6 @@ endif() if(REF_LE) add_definitions("-DREF_LE") endif() -if(SGX_DISABLE_PSE) - add_definitions("-DSGX_DISABLE_PSE") -endif() set(CMAKE_CXX_STANDARD_REQUIRED 1) set(CMAKE_CXX_STANDARD 11) @@ -169,6 +166,3 @@ ADD_SUBDIRECTORY(oal) ADD_SUBDIRECTORY(utils) ADD_SUBDIRECTORY(core) ADD_SUBDIRECTORY(bundles) -ADD_SUBDIRECTORY(qcnl) -ADD_SUBDIRECTORY(qpl) -ADD_SUBDIRECTORY(qcnl/pck_cert_selection) diff --git a/psw/ae/aesm_service/source/bundles/ecdsa_quote_service_bundle/CMakeLists.txt b/psw/ae/aesm_service/source/bundles/ecdsa_quote_service_bundle/CMakeLists.txt index 2ac14e279..4b9ae0209 100644 --- a/psw/ae/aesm_service/source/bundles/ecdsa_quote_service_bundle/CMakeLists.txt +++ b/psw/ae/aesm_service/source/bundles/ecdsa_quote_service_bundle/CMakeLists.txt @@ -30,6 +30,8 @@ # set(qe3_logic "${CMAKE_SOURCE_DIR}/../../../../external/dcap_source/QuoteGeneration/build/linux/libsgx_qe3_logic.so") +set(qpl "${CMAKE_SOURCE_DIR}/../../../../external/dcap_source/QuoteGeneration/build/linux/libdcap_quoteprov.so") +set(qcnl "${CMAKE_SOURCE_DIR}/../../../../external/dcap_source/QuoteGeneration/build/linux/libsgx_default_qcnl_wrapper.so") get_filename_component(bundle ${CMAKE_CURRENT_SOURCE_DIR} NAME) aux_source_directory(. _src) link_directories(${CMAKE_SOURCE_DIR}/../../../../build/linux @@ -56,7 +58,19 @@ add_custom_command(OUTPUT ${qe3_logic} COMMAND make all WORKING_DIRECTORY "${PROJECT_SOURCE_DIR}/../../../../external/dcap_source/QuoteGeneration/quote_wrapper/quote/linux" ) -add_custom_target(qe3_logic_lib DEPENDS ${qe3_logic}) + +add_custom_command(OUTPUT ${qpl} + COMMAND make all + WORKING_DIRECTORY "${PROJECT_SOURCE_DIR}/../../../../external/dcap_source/QuoteGeneration/qpl/linux" + DEPENDS ${qcnl} +) + +add_custom_command(OUTPUT ${qcnl} + COMMAND make all + WORKING_DIRECTORY "${PROJECT_SOURCE_DIR}/../../../../external/dcap_source/QuoteGeneration/qcnl/linux" +) + +add_custom_target(dcap_libs DEPENDS ${qe3_logic} ${qpl} ${qcnl}) target_link_libraries(${bundle} oal utils ${qe3_logic}) -add_dependencies(${bundle} qe3_logic_lib) +add_dependencies(${bundle} dcap_libs) set_property(TARGET ${bundle} APPEND_STRING PROPERTY LINK_FLAGS " -Wl,-z,defs") diff --git a/psw/ae/aesm_service/source/qcnl/CMakeLists.txt b/psw/ae/aesm_service/source/qcnl/CMakeLists.txt deleted file mode 100644 index 299ed470f..000000000 --- a/psw/ae/aesm_service/source/qcnl/CMakeLists.txt +++ /dev/null @@ -1,61 +0,0 @@ -# -# Copyright (C) 2011-2021 Intel Corporation. All rights reserved. -# -# 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. -# * Neither the name of Intel Corporation nor the names of its -# contributors may be used to endorse or promote products derived -# from this software without specific prior written permission. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -# OWNER 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. -# -# - -aux_source_directory(${PROJECT_SOURCE_DIR}/../../../../external/dcap_source/QuoteGeneration/qcnl _srcs) -aux_source_directory(${PROJECT_SOURCE_DIR}/../../../../external/dcap_source/QuoteGeneration/qcnl/linux _srcs) -add_library(sgx_default_qcnl_wrapper SHARED ${_srcs}) - -link_directories( - ${PROJECT_SOURCE_DIR}/../../../../external/dcap_source/prebuilt/openssl/lib/linux64 - ${PROJECT_SOURCE_DIR}/../../../../external/dcap_source/tools/PCKCertSelection/static_out -) - -target_include_directories(sgx_default_qcnl_wrapper PRIVATE - ${SGX_HEADER_DIR} - ${PROJECT_SOURCE_DIR}/../../../../external/dcap_source/QuoteGeneration/qcnl/inc - ${PROJECT_SOURCE_DIR}/../../../../external/dcap_source/QuoteGeneration/pce_wrapper/inc - ${PROJECT_SOURCE_DIR}/../../../../external/dcap_source/QuoteGeneration/quote_wrapper/common/inc - ${PROJECT_SOURCE_DIR}/../../../../external/dcap_source/QuoteGeneration/common/inc/internal - ${PROJECT_SOURCE_DIR}/../../../../external/dcap_source/QuoteVerification/QVL/Src/ThirdParty/rapidjson/include/rapidjson - ${PROJECT_SOURCE_DIR}/../../../../external/dcap_source/prebuilt/openssl/inc - ${PROJECT_SOURCE_DIR}/../../../../external/dcap_source/tools/PCKCertSelection/include -) - -add_dependencies(sgx_default_qcnl_wrapper PCKCertSelection) - -set_property(TARGET sgx_default_qcnl_wrapper APPEND_STRING PROPERTY LINK_FLAGS " -Wl,-z,defs") -set_property(TARGET sgx_default_qcnl_wrapper APPEND_STRING PROPERTY LINK_DEPENDS - ${PROJECT_SOURCE_DIR}/../../../../external/dcap_source/QuoteGeneration/qcnl/linux/sgx_default_qcnl.lds - ) -target_link_libraries(sgx_default_qcnl_wrapper - oal crypto ${CMAKE_CURRENT_BINARY_DIR}/../lib/libPCKCertSelection.a -) - diff --git a/psw/ae/aesm_service/source/qcnl/pck_cert_selection/CMakeLists.txt b/psw/ae/aesm_service/source/qcnl/pck_cert_selection/CMakeLists.txt deleted file mode 100644 index e51106752..000000000 --- a/psw/ae/aesm_service/source/qcnl/pck_cert_selection/CMakeLists.txt +++ /dev/null @@ -1,133 +0,0 @@ -# -# Copyright (C) 2011-2021 Intel Corporation. All rights reserved. -# -# 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. -# * Neither the name of Intel Corporation nor the names of its -# contributors may be used to endorse or promote products derived -# from this software without specific prior written permission. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -# OWNER 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. -# -# - -set(pck_cert_selection_dir - ${CMAKE_CURRENT_SOURCE_DIR}/../../../../../../external/dcap_source/tools/PCKCertSelection/PCKCertSelectionLib -) - -set(CMAKE_CXX_FLAGS "-DATTESTATIONPARSERS_STATIC -DPCK_CERT_SELECTION_WITH_COMPONENT -DIS_STATIC_LIB") - - -set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fPIC -fvisibility=hidden -fvisibility-inlines-hidden -Werror -DLINUX -m64 -fstack-protector -D_FORTIFY_SOURCE=2 -UDEBUG -DNDEBUG -ffunction-sections -fdata-sections -Wall -Wextra -Winit-self -Wpointer-arith -Wreturn-type -Waddress -Wsequence-point -Wformat-security -Wmissing-include-dirs -Wfloat-equal -Wundef -Wshadow -Wcast-align -Wconversion -Wredundant-decls -DITT_ARCH_IA64 -std=c++14") - -set(CMAKE_CXX_STANDARD 14) -set(CMAKE_CXX_STANDARD_REQUIRED ON) - -set(QVL_DIR "${pck_cert_selection_dir}/../../../QuoteVerification/QVL/Src") -# QG root directory -# include the se_version.h file from there - -set(QG_DIR "${pck_cert_selection_dir}/../../../QuoteGeneration") -# openssl include dir -set(OPENSSL_INC "${pck_cert_selection_dir}/../../../prebuilt/openssl/inc") -# openssl lib dir -set(OPENSSL_LIB "${pck_cert_selection_dir}/../../../prebuilt/openssl/lib/linux64") - -# JSON parser include dir -set(JSON_INC "${QVL_DIR}/ThirdParty/rapidjson/include") - -# QVL Attestation Parsers include directory -set(PARSERS_INC "${QVL_DIR}/AttestationParsers/include") -set(PARSERS_COMM_INC "${QVL_DIR}/AttestationCommons/include") -set(PARSERS_UTIL_INC "${QVL_DIR}/AttestationCommons/include/Utils") - - - -######## Library Settings ######## - -# QVL Attestation Parsers source dirs -set(PARSERS_DIR "${QVL_DIR}/AttestationParsers/src") -set(PARSERS_COMM_DIR "${QVL_DIR}/AttestationCommons/src") -set(JSON_DIR "${PARSERS_DIR}/Json") -set(X509_DIR "${PARSERS_DIR}/X509") -set(HELPERS_DIR "${PARSERS_DIR}/OpensslHelpers") -set(UTILS_DIR "${PARSERS_COMM_DIR}/Utils") -set(VER_DIR "${QG_DIR}/common/inc/internal") - -# source files from QVL Attestation Parsers dirs -set(PARSER_CPP_FILES - ${PARSERS_DIR}/ParserUtils.cpp - ) -set(X509_CPP_FILES - ${X509_DIR}/Certificate.cpp - ${X509_DIR}/DistinguishedName.cpp - ${X509_DIR}/Extension.cpp - ${X509_DIR}/PckCertificate.cpp - ${X509_DIR}/Signature.cpp - ${X509_DIR}/Tcb.cpp - ${X509_DIR}/Validity.cpp - ) -set(HELPERS_CPP_FILES - ${HELPERS_DIR}/OidUtils.cpp - ) -set(JSON_CPP_FILES - ${JSON_DIR}/JsonParser.cpp - ${JSON_DIR}/TcbInfo.cpp - ${JSON_DIR}/TcbLevel.cpp - ${JSON_DIR}/TdxModule.cpp - ${JSON_DIR}/TcbComponent.cpp - ${JSON_DIR}/TdxModuleTcb.cpp - ${JSON_DIR}/TdxModuleTcbLevel.cpp - ${JSON_DIR}/TdxModuleIdentity.cpp - ) -set(UTILS_CPP_FILES - ${UTILS_DIR}/GMTime.cpp - ${UTILS_DIR}/TimeUtils.cpp - ) -set(LOCAL_CPP_FILES - ${pck_cert_selection_dir}/pck_sorter.cpp - ${pck_cert_selection_dir}/pck_cert_selection.cpp - ${pck_cert_selection_dir}/config_selector.cpp - ${pck_cert_selection_dir}/tcb_manager.cpp -) - - -add_library(PCKCertSelection STATIC - ${PARSER_CPP_FILES} - ${X509_CPP_FILES} - ${HELPERS_CPP_FILES} - ${JSON_CPP_FILES} - ${UTILS_CPP_FILES} - ${LOCAL_CPP_FILES} -) - -# add the path to the search path for include files -target_include_directories(PCKCertSelection PRIVATE - ${OPENSSL_INC} - ${JSON_INC} - ${PARSERS_INC} - ${PARSERS_COMM_INC} - ${PARSERS_DIR} - ${VER_DIR} - ${PARSERS_UTIL_INC} - ${pck_cert_selection_dir}/../include -) - diff --git a/psw/ae/aesm_service/source/qpl/CMakeLists.txt b/psw/ae/aesm_service/source/qpl/CMakeLists.txt deleted file mode 100644 index d57c58f61..000000000 --- a/psw/ae/aesm_service/source/qpl/CMakeLists.txt +++ /dev/null @@ -1,57 +0,0 @@ -# -# Copyright (C) 2011-2021 Intel Corporation. All rights reserved. -# -# 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. -# * Neither the name of Intel Corporation nor the names of its -# contributors may be used to endorse or promote products derived -# from this software without specific prior written permission. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -# OWNER 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. -# -# - -aux_source_directory(${PROJECT_SOURCE_DIR}/../../../../external/dcap_source/QuoteGeneration/qpl _srcs) -aux_source_directory(${PROJECT_SOURCE_DIR}/../../../../external/dcap_source/QuoteGeneration/qpl/linux _srcs) - -link_directories( - ${PROJECT_SOURCE_DIR}/../../../../external/dcap_source/prebuilt/openssl/lib/linux64 -) - -add_library(dcap_quoteprov SHARED ${_srcs}) - -target_include_directories(dcap_quoteprov PRIVATE - ${SGX_HEADER_DIR} - ${PROJECT_SOURCE_DIR}/../../../../external/dcap_source/QuoteGeneration/qcnl/inc - ${PROJECT_SOURCE_DIR}/../../../../external/dcap_source/QuoteGeneration/qpl/inc - ${PROJECT_SOURCE_DIR}/../../../../external/dcap_source/QuoteGeneration/pce_wrapper/inc - ${PROJECT_SOURCE_DIR}/../../../../external/dcap_source/QuoteGeneration/quote_wrapper/common/inc - ${PROJECT_SOURCE_DIR}/../../../../external/dcap_source/QuoteGeneration/common/inc/internal - ${PROJECT_SOURCE_DIR}/../../../../external/dcap_source/prebuilt/openssl/inc -) - -set_property(TARGET dcap_quoteprov APPEND_STRING PROPERTY LINK_FLAGS " -Wl,-z,defs") -set_property(TARGET dcap_quoteprov APPEND_STRING PROPERTY LINK_DEPENDS - ${PROJECT_SOURCE_DIR}/../../../../external/dcap_source/QuoteGeneration/qpl/linux/sgx_default_quote_provider.lds - ) - -target_link_libraries(dcap_quoteprov sgx_default_qcnl_wrapper crypto pthread dl) - diff --git a/psw/ae/data/prebuilt/README.md b/psw/ae/data/prebuilt/README.md index 8e69f3d49..8efa49696 100644 --- a/psw/ae/data/prebuilt/README.md +++ b/psw/ae/data/prebuilt/README.md @@ -1,11 +1,11 @@ # LE source code -The LE is part of Intel(R) Software Guard Extensions for Linux\* OS which is published in [linux-sgx](https://github.com/intel/linux-sgx/) Github repository. The libsgx_le.signed.so in prebuilt package is built by [le](https://github.com/intel/linux-sgx/tree/master/psw/ae/le) with branch [sgx_2.22_reproducible](https://github.com/intel/linux-sgx/tree/sgx_2.22_reproducible) and signed by Intel. +The LE is part of Intel(R) Software Guard Extensions for Linux\* OS which is published in [linux-sgx](https://github.com/intel/linux-sgx/) Github repository. The libsgx_le.signed.so in prebuilt package is built by [le](https://github.com/intel/linux-sgx/tree/master/psw/ae/le) with branch [sgx_2.25_reproducible](https://github.com/intel/linux-sgx/tree/sgx_2.25_reproducible) and signed by Intel. # PVE source code -The PVE is part of Intel(R) Software Guard Extensions for Linux\* OS which is published in [linux-sgx](https://github.com/intel/linux-sgx/) Github repository. The libsgx_pve.signed.so in prebuilt package is built by [pve](https://github.com/intel/linux-sgx/tree/master/psw/ae/pve) with branch [sgx_2.22_reproducible](https://github.com/intel/linux-sgx/tree/sgx_2.22_reproducible) and signed by Intel. +The PVE is part of Intel(R) Software Guard Extensions for Linux\* OS which is published in [linux-sgx](https://github.com/intel/linux-sgx/) Github repository. The libsgx_pve.signed.so in prebuilt package is built by [pve](https://github.com/intel/linux-sgx/tree/master/psw/ae/pve) with branch [sgx_2.25_reproducible](https://github.com/intel/linux-sgx/tree/sgx_2.25_reproducible) and signed by Intel. # PCE source code -The PCE is part of Intel(R) Software Guard Extensions for Linux\* OS which is published in [linux-sgx](https://github.com/intel/linux-sgx/) Github repository. The libsgx_pce.signed.so in prebuilt package is built by [pce](https://github.com/intel/linux-sgx/tree/master/psw/ae/pce) with branch [sgx_2.22_reproducible](https://github.com/intel/linux-sgx/tree/sgx_2.22_reproducible) and signed by Intel. +The PCE is part of Intel(R) Software Guard Extensions for Linux\* OS which is published in [linux-sgx](https://github.com/intel/linux-sgx/) Github repository. The libsgx_pce.signed.so in prebuilt package is built by [pce](https://github.com/intel/linux-sgx/tree/master/psw/ae/pce) with branch [sgx_2.25_reproducible](https://github.com/intel/linux-sgx/tree/sgx_2.25_reproducible) and signed by Intel. # QE source code -The QE is part of Intel(R) Software Guard Extensions for Linux\* OS which is published in [linux-sgx](https://github.com/intel/linux-sgx/) Github repository. The libsgx_qe.signed.so in prebuilt package is built by [qe](https://github.com/intel/linux-sgx/tree/master/psw/ae/qe) with branch [sgx_2.22_reproducible](https://github.com/intel/linux-sgx/tree/sgx_2.22_reproducible) and signed by Intel. +The QE is part of Intel(R) Software Guard Extensions for Linux\* OS which is published in [linux-sgx](https://github.com/intel/linux-sgx/) Github repository. The libsgx_qe.signed.so in prebuilt package is built by [qe](https://github.com/intel/linux-sgx/tree/master/psw/ae/qe) with branch [sgx_2.25_reproducible](https://github.com/intel/linux-sgx/tree/sgx_2.25_reproducible) and signed by Intel. diff --git a/psw/ae/data/prebuilt/le_prod_css.bin b/psw/ae/data/prebuilt/le_prod_css.bin index c7f2596ca..6b694c052 100644 Binary files a/psw/ae/data/prebuilt/le_prod_css.bin and b/psw/ae/data/prebuilt/le_prod_css.bin differ diff --git a/psw/ae/le/Makefile b/psw/ae/le/Makefile index 650b580c9..bc63b59b3 100644 --- a/psw/ae/le/Makefile +++ b/psw/ae/le/Makefile @@ -33,7 +33,6 @@ TOP_DIR := ../../.. include ../buildenv.mk AENAME = launch_enclave -LE_VER:= $(shell awk '$$2 ~ /LE_VERSION/ { print substr($$3, 2, length($$3) - 2); }' $(COMMON_DIR)/inc/internal/se_version.h) CFLAGS += -Werror CXXFLAGS += -Werror @@ -51,7 +50,7 @@ AENAME_OUT := $(SONAME) #generate $(SONAME) only but do not sign it all: $(AENAME_OUT) $(SONAME): $(OBJS) - $(CXX) $(CXXFLAGS) -o $@ $(OBJS) -nostdlib -nodefaultlibs -nostartfiles -Wl,-soname=libsgx_$(AENAME).signed.so.$(call SPLIT_VERSION,$(LE_VER),1) $(LDTFLAGS) + $(CXX) $(CXXFLAGS) -o $@ $(OBJS) -nostdlib -nodefaultlibs -nostartfiles -Wl,-soname=libsgx_$(AENAME).signed.so.$(call get_major_version,LE_VERSION) $(LDTFLAGS) $(STRIP) --strip-unneeded --remove-section=.comment --remove-section=.note $(SONAME) $(OBJ):$(AENAME)_t.c diff --git a/psw/ae/le/config.xml b/psw/ae/le/config.xml index 4646cbe83..9666c8128 100644 --- a/psw/ae/le/config.xml +++ b/psw/ae/le/config.xml @@ -3,7 +3,7 @@ 0 1 0x20 - 6 + 7 1 0 1 @@ -14,4 +14,5 @@ 0x02 1 1 + 1 diff --git a/psw/ae/le/config_prod.xml b/psw/ae/le/config_prod.xml index 3633ba39a..21885124a 100644 --- a/psw/ae/le/config_prod.xml +++ b/psw/ae/le/config_prod.xml @@ -3,7 +3,7 @@ 0 1 0x20 - 6 + 7 1 0 1 @@ -13,4 +13,5 @@ 0x20000 0x10 1 + 1 diff --git a/psw/ae/pce/Makefile b/psw/ae/pce/Makefile index 88ba9bffe..13aff73ff 100644 --- a/psw/ae/pce/Makefile +++ b/psw/ae/pce/Makefile @@ -38,8 +38,6 @@ CFLAGS += -Werror AENAME = pce -PCE_VER:= $(shell awk '$$2 ~ /PCE/ { print substr($$3, 2, length($$3) - 2); }' $(COMMON_DIR)/inc/internal/se_version.h) - INCLUDE += -I$(LINUX_PSW_DIR)/ae/data/constants/linux INCLUDE += -I$(SGX_HEADER_DIR)/libcxx \ @@ -61,7 +59,7 @@ all: pce_sim_private_key.pem endif $(SONAME): $(OBJS) - $(CXX) $(CXXFLAGS) -o $@ $(OBJS) -nostdlib -nodefaultlibs -nostartfiles -Wl,-soname=libsgx_$(AENAME).signed.so.$(call SPLIT_VERSION,$(PCE_VER),1) $(LDTFLAGS) + $(CXX) $(CXXFLAGS) -o $@ $(OBJS) -nostdlib -nodefaultlibs -nostartfiles -Wl,-soname=libsgx_$(AENAME).signed.so.$(call get_major_version,PCE_VERSION) $(LDTFLAGS) $(STRIP) --strip-unneeded --remove-section=.comment --remove-section=.note $(SONAME) pce.o: $(AENAME)_t.c diff --git a/psw/ae/pce/config.xml b/psw/ae/pce/config.xml index 272d12b07..1275f752e 100644 --- a/psw/ae/pce/config.xml +++ b/psw/ae/pce/config.xml @@ -3,7 +3,7 @@ 1 0 0x1 - 0xF + 0x10 1 0 1 @@ -12,4 +12,5 @@ 0x8000 0x8000 1 + 1 diff --git a/psw/ae/pve/Makefile b/psw/ae/pve/Makefile index 171b6974b..3da3a43b2 100644 --- a/psw/ae/pve/Makefile +++ b/psw/ae/pve/Makefile @@ -36,7 +36,6 @@ include ../buildenv.mk CXXFLAGS += -Werror CFLAGS += -Werror AENAME = provision_enclave -PVE_VER:= $(shell awk '$$2 ~ /PVE_VERSION/ { print substr($$3, 2, length($$3) - 2); }' $(COMMON_DIR)/inc/internal/se_version.h) INCLUDE += -I$(LINUX_PSW_DIR)/ae/data/constants/linux @@ -71,7 +70,7 @@ EPID: $(MAKE) -C $(EPID_SDK_DIR) 2> /dev/null $(SONAME): $(OBJS) EPID - $(CXX) $(CXXFLAGS) -o $@ $(OBJS) -nostdlib -nodefaultlibs -nostartfiles -Wl,-soname=libsgx_$(AENAME).signed.so.$(call SPLIT_VERSION,$(PVE_VER),1) $(LDTFLAGS) + $(CXX) $(CXXFLAGS) -o $@ $(OBJS) -nostdlib -nodefaultlibs -nostartfiles -Wl,-soname=libsgx_$(AENAME).signed.so.$(call get_major_version,PVE_VERSION) $(LDTFLAGS) $(STRIP) --strip-unneeded --remove-section=.comment --remove-section=.note $(SONAME) provision_enclave.o: $(AENAME)_t.c diff --git a/psw/ae/pve/config.xml b/psw/ae/pve/config.xml index 1ba94fbb4..eb1082f27 100644 --- a/psw/ae/pve/config.xml +++ b/psw/ae/pve/config.xml @@ -3,7 +3,7 @@ 1 0 0x1 - 0xF + 0x10 1 0 1 @@ -12,4 +12,5 @@ 0x50000 0x50000 1 + 1 diff --git a/psw/ae/qe/Makefile b/psw/ae/qe/Makefile index 946399acd..e77219e9d 100644 --- a/psw/ae/qe/Makefile +++ b/psw/ae/qe/Makefile @@ -36,8 +36,6 @@ include ../buildenv.mk CXXFLAGS += -Werror CFLAGS += -Werror -QE_VER:= $(shell awk '$$2 ~ /QE_VERSION/ { print substr($$3, 2, length($$3) - 2); }' $(COMMON_DIR)/inc/internal/se_version.h) - EXTERNAL_LIB += -L$(EPID_SDK_DIR)/epid/member -lmember \ -L$(EPID_SDK_DIR)/epid/common -lcommon @@ -68,7 +66,7 @@ EPID: $(MAKE) -C $(EPID_SDK_DIR) 2> /dev/null $(SONAME): $(OBJS) EPID - $(CC) $(CFLAGS) -o $@ $(OBJS) -nostdlib -nodefaultlibs -nostartfiles -Wl,-soname=libsgx_$(AENAME).signed.so.$(call SPLIT_VERSION,$(QE_VER),1) $(LDTFLAGS) + $(CC) $(CFLAGS) -o $@ $(OBJS) -nostdlib -nodefaultlibs -nostartfiles -Wl,-soname=libsgx_$(AENAME).signed.so.$(call get_major_version,QE_VERSION) $(LDTFLAGS) $(STRIP) --strip-unneeded --remove-section=.comment --remove-section=.note $(SONAME) $(OBJ): $(AENAME)_t.c diff --git a/psw/ae/qe/config.xml b/psw/ae/qe/config.xml index 97e9ee501..f6921e804 100644 --- a/psw/ae/qe/config.xml +++ b/psw/ae/qe/config.xml @@ -3,7 +3,7 @@ 0 0 0x1 - 0xF + 0x10 1 0 1 @@ -13,4 +13,5 @@ 0x50000 0x50000 1 + 1 diff --git a/psw/enclave_common/Makefile b/psw/enclave_common/Makefile index 3e3151d8f..915f3bc61 100644 --- a/psw/enclave_common/Makefile +++ b/psw/enclave_common/Makefile @@ -66,32 +66,24 @@ vpath %.cpp $(DIR1):$(DIR2) LIBWRAPPER := libwrapper.a LIBSGX_ENCLAVE_COMMON := libsgx_enclave_common.so -LIBSGX_ENCLAVE_COMMON_DEBUG := libsgx_enclave_common.so.debug +LIBSGX_ENCLAVE_COMMON_FULL := $(LIBSGX_ENCLAVE_COMMON).$(call get_full_version,ENCLAVE_COMMON_VERSION) +LIBSGX_ENCLAVE_COMMON_MAJOR := $(LIBSGX_ENCLAVE_COMMON).$(call get_major_version,ENCLAVE_COMMON_VERSION) LIBSGX_ENCLAVE_COMMON_STATIC := libsgx_enclave_common.a .PHONY: all -all: $(LIBENCLAVE_COMMON) $(LIBSGX_ENCLAVE_COMMON_DEBUG) $(LIBSGX_ENCLAVE_COMMON_STATIC) | $(BUILD_DIR) - @$(CP) $(LIBSGX_ENCLAVE_COMMON) $| - @$(CP) $(LIBSGX_ENCLAVE_COMMON_STATIC) $| -ifndef DEBUG - @$(CP) $(LIBSGX_ENCLAVE_COMMON_DEBUG) $| -endif +all: $(LIBSGX_ENCLAVE_COMMON) $(LIBSGX_ENCLAVE_COMMON_STATIC) | $(BUILD_DIR) + @$(CP) $(LIBSGX_ENCLAVE_COMMON) $|/$(LIBSGX_ENCLAVE_COMMON_FULL) + @$(LN) $(LIBSGX_ENCLAVE_COMMON_FULL) $|/$(LIBSGX_ENCLAVE_COMMON_MAJOR) + @$(LN) $(LIBSGX_ENCLAVE_COMMON_MAJOR) $|/$(LIBSGX_ENCLAVE_COMMON) + @$(CP) $(LIBSGX_ENCLAVE_COMMON_STATIC) $| $(LIBSGX_ENCLAVE_COMMON): $(OBJ) $(LIBWRAPPER) - $(CXX) $(CXXFLAGS) -shared -Wl,-soname=$@.$(call SPLIT_VERSION,$(ECL_VER),1) $(LIB) -o $@ $(OBJ) $(LDFLAGS) + $(CXX) $(CXXFLAGS) -shared -Wl,-soname=$(LIBSGX_ENCLAVE_COMMON_MAJOR) $(LIB) -o $@ $(OBJ) $(LDFLAGS) $(LIBSGX_ENCLAVE_COMMON_STATIC): $(OBJ) $(LIBWRAPPER) $(CP) $(COMMON_DIR)/se_wrapper_psw/libwrapper.a $@ $(AR) rcs $@ $(OBJ) -$(LIBSGX_ENCLAVE_COMMON_DEBUG): $(LIBSGX_ENCLAVE_COMMON) -ifndef DEBUG - $(CP) $(LIBSGX_ENCLAVE_COMMON) $(LIBSGX_ENCLAVE_COMMON).orig - $(OBJCOPY) --only-keep-debug $(LIBSGX_ENCLAVE_COMMON) $(LIBSGX_ENCLAVE_COMMON_DEBUG) - $(STRIP) -g $(LIBSGX_ENCLAVE_COMMON) - $(OBJCOPY) --add-gnu-debuglink=$(LIBSGX_ENCLAVE_COMMON_DEBUG) $(LIBSGX_ENCLAVE_COMMON) -endif - $(OBJ): %.o: %.cpp $(CXX) -c $(CXXFLAGS) $(INC) $< -o $@ @@ -103,7 +95,9 @@ $(BUILD_DIR): .PHONY: clean clean:: - @$(RM) *.o $(LIBSGX_ENCLAVE_COMMON) $(LIBSGX_ENCLAVE_COMMON_DEBUG) $(LIBSGX_ENCLAVE_COMMON_STATIC) - @$(RM) $(BUILD_DIR)/$(LIBSGX_ENCLAVE_COMMON) $(BUILD_DIR)/$(LIBSGX_ENCLAVE_COMMON_DEBUG) $(BUILD_DIR)/$(LIBSGX_ENCLAVE_COMMON_STATIC) - @$(RM) $(LIBSGX_ENCLAVE_COMMON).orig $(BUILD_DIR)/$(LIBSGX_ENCLAVE_COMMON_DEBUG) + @$(RM) *.o $(LIBSGX_ENCLAVE_COMMON) $(LIBSGX_ENCLAVE_COMMON_STATIC) \ + $(BUILD_DIR)/$(LIBSGX_ENCLAVE_COMMON_FULL) \ + $(BUILD_DIR)/$(LIBSGX_ENCLAVE_COMMON_MAJOR) \ + $(BUILD_DIR)/$(LIBSGX_ENCLAVE_COMMON) \ + $(BUILD_DIR)/$(LIBSGX_ENCLAVE_COMMON_STATIC) $(MAKE) -C $(COMMON_DIR)/se_wrapper_psw/ clean diff --git a/psw/enclave_common/sgx_enclave_common.cpp b/psw/enclave_common/sgx_enclave_common.cpp index b13d912e0..9867ecc86 100644 --- a/psw/enclave_common/sgx_enclave_common.cpp +++ b/psw/enclave_common/sgx_enclave_common.cpp @@ -1007,18 +1007,24 @@ extern "C" size_t COMM_API enclave_load_data( if (!(data_properties & ENCLAVE_PAGE_UNVALIDATED)) addp.flags = SGX_PAGE_MEASURE; addp.count = 0; - int ret = ioctl(hfile, SGX_IOC_ENCLAVE_ADD_PAGES_IN_KERNEL, &addp); - if (ret) { - SE_TRACE(SE_TRACE_WARNING, "\nAdd Page - %p to %p... FAIL\n", source, target_address); - if (enclave_error != NULL) - *enclave_error = error_driver2api(ret, errno); - if(source_buffer == NULL) - { - free(source); - source = NULL; - } - return 0; - } + do { + int ret = ioctl(hfile, SGX_IOC_ENCLAVE_ADD_PAGES_IN_KERNEL, &addp); + if(ret && addp.count == 0 && errno != EBUSY && errno != EAGAIN ) + { //total failure + SE_TRACE(SE_TRACE_WARNING, "\nAdd Page - %p to %p... FAIL\n", source, target_address); + if (enclave_error != NULL) + *enclave_error = error_driver2api(ret, errno); + if(source_buffer == NULL) + { + free(source); + source = NULL; + } + return 0; + } + addp.length -= addp.count; + addp.offset += addp.count; + addp.count = 0; + } while (addp.length != 0); if(source_buffer == NULL) { free(source); diff --git a/psw/uae_service/linux/Makefile b/psw/uae_service/linux/Makefile index c797b00a9..bffbdc5b4 100644 --- a/psw/uae_service/linux/Makefile +++ b/psw/uae_service/linux/Makefile @@ -32,9 +32,7 @@ TOP_DIR = ../../.. include $(TOP_DIR)/buildenv.mk -LAUNCH_VERSION:= $(shell awk '$$2 ~ /LAUNCH_VERSION/ { print substr($$3, 2, length($$3) - 2); }' $(COMMON_DIR)/inc/internal/se_version.h) -EPID_VERSION:= $(shell awk '$$2 ~ /EPID_VERSION/ { print substr($$3, 2, length($$3) - 2); }' $(COMMON_DIR)/inc/internal/se_version.h) -QUOTE_EX_VERSION:= $(shell awk '$$2 ~ /QUOTE_EX_VERSION/ { print substr($$3, 2, length($$3) - 2); }' $(COMMON_DIR)/inc/internal/se_version.h) +get_version_name = $(addsuffix _VERSION,$(shell echo $(subst libsgx_,,$(basename $1)) | tr a-z A-Z)) IPC_COMMON_DIR := $(TOP_DIR)/psw/ae/aesm_service/source/core/ipc IPC_COMMON_SRC_DIR := $(IPC_COMMON_DIR) @@ -43,7 +41,7 @@ IPC_COMMON_PROTO_DIR := $(IPC_COMMON_DIR) UAE_WRAPPER_DIR := ../uae_wrapper UAE_SRC_DIR := $(UAE_WRAPPER_DIR)/src UAE_INC_DIR := $(UAE_WRAPPER_DIR)/inc -AE_COMMON_DIR := $(LINUX_PSW_DIR)/ae/common +AE_COMMON_DIR := $(LINUX_PSW_DIR)/ae/common INCLUDE += -I. INCLUDE += -I$(COMMON_DIR) \ @@ -55,16 +53,16 @@ INCLUDE += -I$(LINUX_PSW_DIR)/ae/common \ -I$(LINUX_PSW_DIR)/ae/inc/internal \ -I$(SGX_HEADER_DIR) -INCLUDE += -I$(LINUX_EXTERNAL_DIR)/epid-sdk \ - -I$(IPC_COMMON_INC_DIR) \ - -I$(UAE_INC_DIR) \ - -I$(IPC_COMMON_PROTO_DIR) \ +INCLUDE += -I$(LINUX_EXTERNAL_DIR)/epid-sdk \ + -I$(IPC_COMMON_INC_DIR) \ + -I$(UAE_INC_DIR) \ + -I$(IPC_COMMON_PROTO_DIR) \ -I$(LINUX_PSW_DIR)/ae/aesm_service/source \ -I$(LINUX_PSW_DIR)/ae/aesm_service/source/common CXXFLAGS += -fPIC -Werror -Wno-unused-parameter -g -DPROTOBUF_INLINE_NOT_IN_HEADERS=0 -EXTERNAL_LIB += -lprotobuf +EXTERNAL_LIB += -lprotobuf vpath %.cpp .. $(COMMON_DIR)/src $(IPC_COMMON_SRC_DIR) $(IPC_COMMON_PROTO_DIR) $(UAE_SRC_DIR) $(AE_COMMON_DIR) vpath %.c $(COMMON_DIR)/src @@ -110,68 +108,42 @@ IPC_SRC := AEGetQuoteResponse.cpp \ AEGetSupportedAttKeyIDsRequest.cpp \ AEGetSupportedAttKeyIDsResponse.cpp -PROTOBUF_SRC := messages.pb.cc +PROTOBUF_SRC := messages.pb.cc SRC := AEServicesImpl.cpp \ AEServicesProvider.cpp \ uae_api.cpp \ se_sig_rl.cpp \ sgx_uae_service.cpp \ - uae_service_assert.cpp + uae_service_assert.cpp LEGACY_SRC := legacy_uae_service.cpp \ uae_service_version.cpp -OBJ := $(C_SRC:.c=.o) $(SRC:.cpp=.o) $(IPC_SRC:.cpp=.o) $(PROTOBUF_SRC:.cc=.o) +OBJ := $(C_SRC:.c=.o) $(SRC:.cpp=.o) $(IPC_SRC:.cpp=.o) $(PROTOBUF_SRC:.cc=.o) LEGACY_OBJ := $(LEGACY_SRC:.cpp=.o) LDUFLAGS:= -pthread $(COMMON_LDFLAGS) -LIBNAME := libsgx_epid.so libsgx_launch.so libsgx_quote_ex.so -ifndef DEBUG -LIBNAME_DEBUG = $(LIBNAME:.so=.so.debug) -endif - -LEGACY_LIBNAME = libsgx_uae_service.so -LEGACY_LIBNAME_DEBUG = libsgx_uae_service.so.debug +LIBNAME := libsgx_epid.so libsgx_launch.so libsgx_quote_ex.so +LEGACY_LIBNAME := libsgx_uae_service.so .PHONY: all all: install_lib .PHONY: install_lib -install_lib: $(LIBNAME) $(LIBNAME_DEBUG) $(LEGACY_LIBNAME) $(LEGACY_LIBNAME_DEBUG) | $(BUILD_DIR) - @$(foreach lib,$(LIBNAME),$(CP) $(lib) $|;) +install_lib: $(LIBNAME) $(LEGACY_LIBNAME) | $(BUILD_DIR) + @$(foreach lib,$(LIBNAME),$(CP) $(lib) $|/$(lib).$(call get_full_version,$(call get_version_name,$(lib)));) + @$(foreach lib,$(LIBNAME),$(LN) $(lib).$(call get_full_version,$(call get_version_name,$(lib))) $|/$(lib).$(call get_major_version,$(call get_version_name,$(lib)));) + @$(foreach lib,$(LIBNAME),$(LN) $(lib).$(call get_major_version,$(call get_version_name,$(lib))) $|/$(lib);) @$(CP) $(LEGACY_LIBNAME) $| -ifndef DEBUG - @$(foreach lib,$(LIBNAME_DEBUG),$(CP) $(lib) $|;) - @$(CP) $(LEGACY_LIBNAME_DEBUG) $| -endif libsgx_%.so: $(OBJ) %_version.o - $(CXX) $(CXXFLAGS) $^ -shared $(LDUFLAGS) -Wl,--version-script=$(@:.so=.lds) -Wl,--gc-sections $(EXTERNAL_LIB) -Wl,-soname=$@.$(call SPLIT_VERSION,$($(shell echo $(@:libsgx_%.so=%_version)|tr a-z A-Z)),1) -o $@ -%.so.debug: %.so -ifndef DEBUG - ((test -f $@) ||( \ - $(CP) $< $<.orig &&\ - $(OBJCOPY) --only-keep-debug $< $@ &&\ - $(STRIP) -g $< &&\ - $(OBJCOPY) --add-gnu-debuglink=$@ $< )) -endif + $(CXX) $(CXXFLAGS) $^ -shared $(LDUFLAGS) -Wl,--version-script=$(@:.so=.lds) -Wl,--gc-sections $(EXTERNAL_LIB) -Wl,-soname=$@.$(call get_major_version,$(call get_version_name,$@)) -o $@ $(LEGACY_LIBNAME): $(LEGACY_OBJ) $(CXX) $(CXXFLAGS) $^ -shared $(LDUFLAGS) -ldl -Wl,--version-script=uae_service.lds -Wl,--gc-sections -Wl,-soname=$@ -o $@ -$(LEGACY_LIBNAME_DEBUG): $(LEGACY_LIBNAME) - ((test -f $(LEGACY_LIBNAME_DEBUG)) || $(MAKE) separate_debug_info) - -.PHONY: separate_debug_info -separate_debug_info: -ifndef DEBUG - $(CP) $(LEGACY_LIBNAME) $(LEGACY_LIBNAME).orig - $(OBJCOPY) --only-keep-debug $(LEGACY_LIBNAME) $(LEGACY_LIBNAME_DEBUG) - $(STRIP) -g $(LEGACY_LIBNAME) - $(OBJCOPY) --add-gnu-debuglink=$(LEGACY_LIBNAME_DEBUG) $(LEGACY_LIBNAME) -endif $(IPC_SRC:.cpp=.o) : $(IPC_COMMON_PROTO_DIR)/messages.pb.cc AEServicesImpl.o : $(IPC_COMMON_PROTO_DIR)/messages.pb.cc @@ -192,11 +164,9 @@ $(IPC_COMMON_PROTO_DIR)/messages.pb.cc: $(IPC_COMMON_PROTO_DIR)/messages.proto .PHONY: clean clean: $(MAKE) -C $(IPC_COMMON_PROTO_DIR) clean - @$(RM) $(OBJ) $(LEGACY_OBJ) *.orig - @$(RM) $(LIBNAME) $(addprefix $(BUILD_DIR)/,$(LIBNAME)) - @$(RM) $(LIBNAME_DEBUG) $(addprefix $(BUILD_DIR)/,$(LIBNAME_DEBUG)) + @$(RM) $(OBJ) $(LEGACY_OBJ) + @$(RM) $(LIBNAME) $(addsuffix *,$(addprefix $(BUILD_DIR)/,$(LIBNAME))) @$(RM) $(LEGACY_LIBNAME) $(BUILD_DIR)/$(LEGACY_LIBNAME) - @$(RM) $(LEGACY_LIBNAME_DEBUG) $(BUILD_DIR)/$(LEGACY_LIBNAME_DEBUG) .PHONY: rebuild rebuild: diff --git a/psw/urts/linux/Makefile b/psw/urts/linux/Makefile index 4a2644af1..41797648b 100644 --- a/psw/urts/linux/Makefile +++ b/psw/urts/linux/Makefile @@ -31,8 +31,6 @@ include ../../../buildenv.mk -URTS_VER:= $(shell awk '$$2 ~ /URTS_VERSION/ { print substr($$3, 2, length($$3) - 2); }' $(COMMON_DIR)/inc/internal/se_version.h) - ifndef DEBUG CXXFLAGS += -DDISABLE_TRACE CFLAGS += -DDISABLE_TRACE @@ -124,38 +122,27 @@ vpath %.S $(DIR1):$(DIR5) LIBWRAPPER := libwrapper.a LIBSGX_ENCLAVE_COMMON := libsgx_enclave_common.a -LIBURTS := libsgx_urts.so LIBURTS_INTERNAL := liburts_internal.so -LIBURTS_DEBUG := libsgx_urts.so.debug - +LIBURTS := libsgx_urts.so +LIBURTS_FULL := $(LIBURTS).$(call get_full_version,URTS_VERSION) +LIBURTS_MAJOR := $(LIBURTS).$(call get_major_version,URTS_VERSION) .PHONY: all -all: $(LIBURTS) $(LIBURTS_INTERNAL) $(LIBURTS_DEBUG) | $(BUILD_DIR) - @$(CP) $(LIBURTS) $| +all: $(LIBURTS) $(LIBURTS_INTERNAL) | $(BUILD_DIR) + @$(CP) $(LIBURTS) $|/$(LIBURTS_FULL) + @$(LN) $(LIBURTS_FULL) $|/$(LIBURTS_MAJOR) + @$(LN) $(LIBURTS_MAJOR) $|/$(LIBURTS) @$(CP) $(LIBURTS_INTERNAL) $| -ifndef DEBUG - @$(CP) $(LIBURTS_DEBUG) $| -endif $(LIBURTS_INTERNAL): $(INTERNAL_OBJ) $(LIBWRAPPER) $(LIBSGX_ENCLAVE_COMMON) ittnotify @$(MKDIR) $(BUILD_DIR)/.sgx_enclave_common - @$(RM) -f $(BUILD_DIR)/.sgx_enclave_common/* - cd $(BUILD_DIR)/.sgx_enclave_common && \ - $(AR) x $(BUILD_DIR)/$(LIBSGX_ENCLAVE_COMMON) && \ - $(RM) -f edmm_utility.o - $(CXX) $(CXXFLAGS) -shared -Wl,-soname=$@ $(LIB) -o $@ $(INTERNAL_OBJ) $(BUILD_DIR)/.sgx_enclave_common/*.o $(INTERNAL_LDFLAGS) - @$(RM) -rf $(BUILD_DIR)/.sgx_enclave_common + $(AR) x $(BUILD_DIR)/$(LIBSGX_ENCLAVE_COMMON) --output $(BUILD_DIR)/.sgx_enclave_common && \ + $(RM) $(BUILD_DIR)/.sgx_enclave_common/edmm_utility.o + $(CXX) $(CXXFLAGS) -shared -Wl,-soname=$@ $(LIB) -o $@ $(INTERNAL_OBJ) $(BUILD_DIR)/.sgx_enclave_common/*.o $(INTERNAL_LDFLAGS) + @$(RM) -r $(BUILD_DIR)/.sgx_enclave_common $(LIBURTS): $(URTS_OBJ) $(LIBWRAPPER) $(LIBSGX_ENCLAVE_COMMON) ittnotify - $(CXX) $(CXXFLAGS) -shared -Wl,-soname=$@.$(call SPLIT_VERSION,$(URTS_VER),1) $(LIB) -o $@ $(URTS_OBJ) $(LDFLAGS) - -$(LIBURTS_DEBUG): $(LIBURTS) -ifndef DEBUG - $(CP) $(LIBURTS) $(LIBURTS).orig - $(OBJCOPY) --only-keep-debug $(LIBURTS) $(LIBURTS_DEBUG) - $(STRIP) -g $(LIBURTS) - $(OBJCOPY) --add-gnu-debuglink=$(LIBURTS_DEBUG) $(LIBURTS) -endif + $(CXX) $(CXXFLAGS) -shared -Wl,-soname=$(LIBURTS_MAJOR) $(LIB) -o $@ $(URTS_OBJ) $(LDFLAGS) $(CPP_OBJ): %.o: %.cpp $(CXX) -c $(CXXFLAGS) $(INC) $< -o $@ @@ -178,9 +165,11 @@ $(BUILD_DIR): .PHONY: clean clean:: - @$(RM) *.o $(LIBURTS) $(LIBURTS_INTERNAL) $(LIBURTS_DEBUG) - @$(RM) $(BUILD_DIR)/$(LIBURTS) $(BUILD_DIR)/$(LIBURTS_INTERNAL) - @$(RM) $(LIBURTS).orig $(BUILD_DIR)/$(LIBURTS_DEBUG) - $(MAKE) -C $(COMMON_DIR)/se_wrapper_psw/ clean - $(MAKE) -C $(LINUX_PSW_DIR)/enclave_common/ clean - $(MAKE) -C $(VTUNE_DIR)/sdk/src/ittnotify clean + @$(RM) *.o $(LIBURTS) $(LIBURTS_INTERNAL) \ + $(BUILD_DIR)/$(LIBURTS) \ + $(BUILD_DIR)/$(LIBURTS_FULL) \ + $(BUILD_DIR)/$(LIBURTS_MAJOR) \ + $(BUILD_DIR)/$(LIBURTS_INTERNAL) + $(MAKE) -C $(COMMON_DIR)/se_wrapper_psw/ clean + $(MAKE) -C $(LINUX_PSW_DIR)/enclave_common/ clean + $(MAKE) -C $(VTUNE_DIR)/sdk/src/ittnotify clean diff --git a/psw/urts/linux/enter_enclave.S b/psw/urts/linux/enter_enclave.S index ba0c2c5a8..69c7c67a1 100644 --- a/psw/urts/linux/enter_enclave.S +++ b/psw/urts/linux/enter_enclave.S @@ -52,7 +52,7 @@ DECLARE_GLOBAL_FUNC set_xsave_info lea_symbol g_clean_ymm, %xax movl %edx, (%xax) ret - .cfi_endproc +END_FUNC DECLARE_GLOBAL_FUNC vdso_sgx_enter_enclave_wrapper EENTER_PROLOG @@ -78,6 +78,7 @@ EENTER_PROLOG call *(%r10) mov %xax, %xsi EENTER_EPILOG +END_FUNC DECLARE_GLOBAL_FUNC __morestack @@ -158,6 +159,7 @@ EENTER_PROLOG .Loret: EENTER_EPILOG +END_FUNC .Lasync_exit_pointer: ENCLU @@ -170,17 +172,17 @@ EENTER_PROLOG DECLARE_GLOBAL_FUNC get_aep lea_pic .Lasync_exit_pointer, %xax ret - .cfi_endproc +END_FUNC DECLARE_GLOBAL_FUNC get_eenterp lea_pic .Leenter_inst, %xax ret - .cfi_endproc +END_FUNC DECLARE_GLOBAL_FUNC get_eretp lea_pic .Leret, %xax ret - .cfi_endproc +END_FUNC /* * function stack_sticker is the wrapper of ocall, @@ -305,7 +307,7 @@ DECLARE_GLOBAL_FUNC stack_sticker leave ret - .cfi_endproc +END_FUNC /* * void sgx_debug_load_state_add_element(debug_enclave_info_t* new_enclave_info, debug_enclave_info_t** g_debug_enclave_info_list) @@ -320,7 +322,7 @@ DECLARE_GLOBAL_FUNC sgx_debug_load_state_add_element movq %rdi, (%rsi) #endif ret - .cfi_endproc +END_FUNC /* * void sgx_debug_unload_state_remove_element(debug_enclave_info_t* enclave_info, debug_enclave_info_t** pre_enclave_info, debug_enclave_info_t* next_enclave_info) @@ -336,7 +338,7 @@ DECLARE_GLOBAL_FUNC sgx_debug_unload_state_remove_element movq %rdx, (%rsi) #endif ret - .cfi_endproc +END_FUNC /* We do not need executable stack.*/ .section .note.GNU-stack,"",@progbits diff --git a/psw/urts/linux/enter_enclave.h b/psw/urts/linux/enter_enclave.h index 13a746692..0c76d1aaf 100644 --- a/psw/urts/linux/enter_enclave.h +++ b/psw/urts/linux/enter_enclave.h @@ -130,7 +130,6 @@ mov -SE_WORDSIZE*2(%rbp), %r15 mov %xbp, %xsp pop %xbp ret -.cfi_endproc .endm #if defined(__i386__) diff --git a/psw/urts/parser/update_global_data.hxx b/psw/urts/parser/update_global_data.hxx index d13089aa5..4181239a4 100644 --- a/psw/urts/parser/update_global_data.hxx +++ b/psw/urts/parser/update_global_data.hxx @@ -168,9 +168,10 @@ namespace { { global_data->enclave_image_address = 0; global_data->elrange_start_address= 0; - global_data->elrange_size = global_data->enclave_size; + global_data->elrange_size = 0; } global_data->edmm_bk_overhead = (sys_word_t)create_param->edmm_bk_overhead; + global_data->fips_on = create_param->fips_on; return true; } } diff --git a/sdk/Makefile b/sdk/Makefile index 2f8e8c851..0f85c1cc1 100644 --- a/sdk/Makefile +++ b/sdk/Makefile @@ -33,7 +33,7 @@ include ../buildenv.mk include Makefile.source -# SDK requires prebuilt IPP libraries. +# IPP libraries must be ready for SDK build CHECK_OPT := ifeq ("$(wildcard $(LINUX_EXTERNAL_DIR)/ippcp_internal/lib/linux/intel64)", "") CHECK_OPT := opt_check_failed @@ -41,7 +41,7 @@ endif .PHONY: opt_check_failed opt_check_failed: - @echo "ERROR: Please run 'download_prebuilt.sh' to download the prebuilt optimized libraries before compiling." + @echo "ERROR: Please go to top directory and run 'make preparation' to prepare the optimized libraries before compiling." @echo "Exiting......" @exit 3 diff --git a/sdk/debugger_interface/linux/Makefile b/sdk/debugger_interface/linux/Makefile index d5d6a14e0..8f2847dae 100644 --- a/sdk/debugger_interface/linux/Makefile +++ b/sdk/debugger_interface/linux/Makefile @@ -39,16 +39,16 @@ CPPFLAGS += -I$(COMMON_DIR)/inc/ \ CFLAGS += -W -Wall -Werror -D_GNU_SOURCE -fpic ifeq ($(CC_BELOW_4_9), 1) - CFLAGS += -fstack-protector + CFLAGS += -fstack-protector else - CFLAGS += -fstack-protector-strong + CFLAGS += -fstack-protector-strong endif LDLIBS += -ldl ifdef DEBUG CFLAGS += -g -DSE_DEBUG=1 -ffunction-sections -fdata-sections else - CFLAGS += -O2 -D_FORTIFY_SOURCE=2 -ffunction-sections -fdata-sections + CFLAGS += -O2 -D_FORTIFY_SOURCE=$(FORTIFY_SOURCE_VAL) -ffunction-sections -fdata-sections endif OBJ1 := se_memory.o se_trace.o diff --git a/sdk/gperftools/gperftools-2.7/autogen.sh b/sdk/gperftools/gperftools-2.7/autogen.sh index c9b5bebb0..b9f879aad 100755 --- a/sdk/gperftools/gperftools-2.7/autogen.sh +++ b/sdk/gperftools/gperftools-2.7/autogen.sh @@ -11,8 +11,6 @@ autoreconf -i if [ "$1" = "DEBUG" ] then COMMON_FLAGS="-DTCMALLOC_SGX_DEBUG" -else - COMMON_FLAGS="-D_FORTIFY_SOURCE=2" fi COMMON_FLAGS="$COMMON_FLAGS -DNO_HEAP_CHECK -DTCMALLOC_SGX -DTCMALLOC_NO_ALIASES" diff --git a/sdk/protected_code_loader/Makefile b/sdk/protected_code_loader/Makefile index 352602f35..921a5c11e 100644 --- a/sdk/protected_code_loader/Makefile +++ b/sdk/protected_code_loader/Makefile @@ -39,8 +39,8 @@ else PCLVERBOSE := endif -# optimize bug on GCC 13.3.2, we need to disable optimize when build with GCC 13.3.2 -CC_NO_LESS_THAN_13 := $(shell expr $(CC_VERSION) \>\= "13") +# optimize bug on GCC 13.3.2(ubuntu23.10) and gcc 12.2 debian12, we need to disable optimize when build with GCC 12 +CC_NO_LESS_THAN_12 := $(shell expr $(CC_VERSION) \>\= "12") ifeq ($(ARCH), x86) $(error x86 build is not supported, only x64!!) @@ -101,11 +101,11 @@ PCL_LIB_CPP_FLAGS := $(TCXXFLAGS) $(ENCLAVE_CXXFLAGS) $(PCL_INCLUDE_PATH) PCL_SIM_LIB_C_FLAGS := $(TCFLAGS) $(ENCLAVE_CFLAGS) -DSE_SIM=1 $(PCL_INCLUDE_PATH) -I$(LINUX_SDK_DIR)/simulation/tinst PCL_SIM_LIB_CPP_FLAGS := $(TCXXFLAGS) $(ENCLAVE_CXXFLAGS) -DSE_SIM=1 $(PCL_INCLUDE_PATH) -I$(LINUX_SDK_DIR)/simulation/tinst -ifeq ($(CC_NO_LESS_THAN_13), 1) -PCL_LIB_C_FLAGS += -DTURN_OFF_O2_GCC13 -PCL_LIB_CPP_FLAGS += -DTURN_OFF_O2_GCC13 -PCL_SIM_LIB_C_FLAGS += -DTURN_OFF_O2_GCC13 -PCL_SIM_LIB_CPP_FLAGS += -DTURN_OFF_O2_GCC13 +ifeq ($(CC_NO_LESS_THAN_12), 1) +PCL_LIB_C_FLAGS += -DTURN_OFF_O2 +PCL_LIB_CPP_FLAGS += -DTURN_OFF_O2 +PCL_SIM_LIB_C_FLAGS += -DTURN_OFF_O2 +PCL_SIM_LIB_CPP_FLAGS += -DTURN_OFF_O2 endif # targets diff --git a/sdk/protected_code_loader/crypto/pcl_gcm128.c b/sdk/protected_code_loader/crypto/pcl_gcm128.c index d78b4ffe5..4ad2eb9f3 100644 --- a/sdk/protected_code_loader/crypto/pcl_gcm128.c +++ b/sdk/protected_code_loader/crypto/pcl_gcm128.c @@ -806,7 +806,7 @@ void pcl_gcm_gmult_clmul(u64 Xi[2], const u128 Htable[16]); void pcl_gcm_ghash_clmul(u64 Xi[2], const u128 Htable[16], const u8 *inp, size_t len); -#ifdef TURN_OFF_O2_GCC13 +#ifdef TURN_OFF_O2 #pragma GCC push_options #pragma GCC optimize("O0") #endif @@ -943,7 +943,7 @@ void pcl_CRYPTO_gcm128_init(GCM128_CONTEXT *ctx, void *key, block128_f block) PCL UNUSED END */ } -#ifdef TURN_OFF_O2_GCC13 +#ifdef TURN_OFF_O2 #pragma GCC pop_options #endif void pcl_CRYPTO_gcm128_setiv(GCM128_CONTEXT *ctx, const unsigned char *iv, diff --git a/sdk/protected_code_loader/crypto/pcl_sha256.c b/sdk/protected_code_loader/crypto/pcl_sha256.c index 64dbb2b4e..8a0001735 100644 --- a/sdk/protected_code_loader/crypto/pcl_sha256.c +++ b/sdk/protected_code_loader/crypto/pcl_sha256.c @@ -134,7 +134,7 @@ static const SHA_LONG pcl_K256[64] = { 0x748f82eeUL, 0x78a5636fUL, 0x84c87814UL, 0x8cc70208UL, 0x90befffaUL, 0xa4506cebUL, 0xbef9a3f7UL, 0xc67178f2UL }; -#ifdef TURN_OFF_O2_GCC13 +#ifdef TURN_OFF_O2 #pragma GCC push_option #pragma GCC optimize("O0") #endif @@ -215,6 +215,6 @@ static void pcl_sha256_block_data_order(SHA256_CTX *ctx, const void *in, } } -#ifdef TURN_OFF_O2_GCC13 +#ifdef TURN_OFF_O2 #pragma GCC pop_option #endif diff --git a/sdk/sample_libcrypto/Makefile b/sdk/sample_libcrypto/Makefile index f330488df..8e15e5b84 100644 --- a/sdk/sample_libcrypto/Makefile +++ b/sdk/sample_libcrypto/Makefile @@ -38,7 +38,7 @@ CXXFLAGS += -fno-rtti -fno-exceptions -fPIC -Werror CPPFLAGS := -isystem $(SGX_IPP_INC) \ -I$(COMMON_DIR)/inc/internal/ -CFLAGS += -fPIC -fno-exceptions -I$(SGX_IPP_INC) -DIPPCP_PREVIEW_XMSS #-Werror +CFLAGS += -fPIC -fno-exceptions -I$(SGX_IPP_INC) -DIPPCP_PREVIEW_ALL #-Werror IPPLIB_DIR = $(SGX_IPP_DIR)/lib/linux/intel64/no_mitigation diff --git a/sdk/sign_tool/SignTool/manage_metadata.cpp b/sdk/sign_tool/SignTool/manage_metadata.cpp index 60e48eb09..eea61c496 100644 --- a/sdk/sign_tool/SignTool/manage_metadata.cpp +++ b/sdk/sign_tool/SignTool/manage_metadata.cpp @@ -185,13 +185,12 @@ bool parse_metadata_file(const char *xmlpath, xml_parameter_t *parameter, int pa return true; } -CMetadata::CMetadata(metadata_t *metadata, BinParser *parser, bool fips_on) +CMetadata::CMetadata(metadata_t *metadata, BinParser *parser) : m_meta_verions(0), m_metadata(metadata), m_parser(parser) , m_rva(0), m_gd_size(0), m_gd_template(NULL) { memset(m_metadata, 0, sizeof(metadata_t)); memset(&m_create_param, 0, sizeof(m_create_param)); - m_create_param.fips_on = fips_on ? 1 : 0; memset(&m_elrange_config_entry, 0, sizeof(m_elrange_config_entry)); } CMetadata::~CMetadata() @@ -605,6 +604,7 @@ bool CMetadata::check_xml_parameter(const xml_parameter_t *parameter) m_create_param.tcs_max_num = (uint32_t)(parameter[TCSMAXNUM].flag ? parameter[TCSMAXNUM].value : parameter[TCSNUM].value); m_create_param.tcs_min_pool = (uint32_t)parameter[TCSMINPOOL].value; m_create_param.tcs_policy = (uint32_t)parameter[TCSPOLICY].value; + m_create_param.fips_on = (uint32_t)parameter[ENABLEIPPFIPS].value; se_trace(SE_TRACE_ERROR, "tcs_num %d, tcs_max_num %d, tcs_min_pool %d\n", m_create_param.tcs_num, m_create_param.tcs_max_num, m_create_param.tcs_min_pool); SE_TRACE_DEBUG("RSRV_MIN_SIZE = 0x%016llX\n", m_create_param.rsrv_min_size); diff --git a/sdk/sign_tool/SignTool/manage_metadata.h b/sdk/sign_tool/SignTool/manage_metadata.h index 65e27cfaf..24505a052 100644 --- a/sdk/sign_tool/SignTool/manage_metadata.h +++ b/sdk/sign_tool/SignTool/manage_metadata.h @@ -86,7 +86,8 @@ typedef enum _para_type_t PKRU, AMX, USERREGIONSIZE, - ENABLEAEXNOTIFY + ENABLEAEXNOTIFY, + ENABLEIPPFIPS } para_type_t; typedef struct _xml_parameter_t @@ -108,7 +109,7 @@ void *get_extend_entry_by_ID(const metadata_t *metadata, uint32_t entry_id); class CMetadata: private Uncopyable { public: - CMetadata(metadata_t *metadata, BinParser *parser, bool fips_on); + CMetadata(metadata_t *metadata, BinParser *parser); ~CMetadata(); bool build_metadata(const xml_parameter_t *parameter); bool rts_dynamic(); diff --git a/sdk/sign_tool/SignTool/sign_tool.cpp b/sdk/sign_tool/SignTool/sign_tool.cpp index 17827c97c..63e24ec9b 100644 --- a/sdk/sign_tool/SignTool/sign_tool.cpp +++ b/sdk/sign_tool/SignTool/sign_tool.cpp @@ -69,12 +69,10 @@ #define REL_ERROR_BIT 0x1 #define INIT_SEC_ERROR_BIT 0x2 #define RESIGN_BIT 0x4 -#define FIPS_BIT 0x8 #define IGNORE_REL_ERROR(x) (((x) & REL_ERROR_BIT) != 0) #define IGNORE_INIT_SEC_ERROR(x) (((x) & INIT_SEC_ERROR_BIT) != 0) #define ENABLE_RESIGN(x) (((x) & RESIGN_BIT) != 0) -#define ENABLE_FIPS(x) (((x) & FIPS_BIT) != 0) typedef enum _file_path_t { @@ -172,7 +170,7 @@ static bool measure_enclave(uint8_t *hash, const char *dllpath, const xml_parame } // generate metadata - CMetadata meta(metadata, parser.get(), ENABLE_FIPS(option_flag_bits)); + CMetadata meta(metadata, parser.get()); if(meta.build_metadata(parameter) == false) { close_handle(fh); @@ -670,7 +668,6 @@ static bool cmdline_parse(unsigned int argc, char *argv[], int *mode, const char {"-ignore-rel-error", REL_ERROR_BIT}, {"-ignore-init-sec-error", INIT_SEC_ERROR_BIT}, {"-resign", RESIGN_BIT}, - {"-enable-fips", FIPS_BIT} }; unsigned int params_count = (unsigned)(sizeof(params_sign)/sizeof(params_sign[0])); @@ -1359,7 +1356,8 @@ int main(int argc, char* argv[]) {"PKRU", FEATURE_LOADER_SELECTS, FEATURE_MUST_BE_DISABLED, FEATURE_MUST_BE_DISABLED, 0}, {"AMX", FEATURE_LOADER_SELECTS, FEATURE_MUST_BE_DISABLED, FEATURE_MUST_BE_DISABLED, 0}, {"UserRegionSize", ENCLAVE_MAX_SIZE_64/2, 0, USER_REGION_SIZE, 0}, - {"EnableAEXNotify", 1, 0, 0, 0}}; + {"EnableAEXNotify", 1, 0, 0, 0}, + {"EnableIPPFIPS", 1, 0, 0, 0}}; const char *path[8] = {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL}; uint8_t enclave_hash[SGX_HASH_SIZE] = {0}; uint8_t metadata_raw[METADATA_SIZE]; diff --git a/sdk/simulation/assembly/linux/lowlib.S b/sdk/simulation/assembly/linux/lowlib.S index 421a447f5..d2ecfa690 100644 --- a/sdk/simulation/assembly/linux/lowlib.S +++ b/sdk/simulation/assembly/linux/lowlib.S @@ -39,7 +39,7 @@ DECLARE_LOCAL_FUNC get_bp mov %xbp, %xax ret - .cfi_endproc +END_FUNC #define reg_xax (0 * SE_WORDSIZE) #define reg_xbx (1 * SE_WORDSIZE) @@ -63,4 +63,4 @@ DECLARE_LOCAL_FUNC load_regs push reg_xip(%xdx) mov reg_xdx(%xdx), %xdx ret - .cfi_endproc +END_FUNC diff --git a/sdk/simulation/assembly/linux/sw_emu.h b/sdk/simulation/assembly/linux/sw_emu.h index 2fb9340d1..fde8c99a6 100644 --- a/sdk/simulation/assembly/linux/sw_emu.h +++ b/sdk/simulation/assembly/linux/sw_emu.h @@ -116,6 +116,7 @@ DECLARE_LOCAL_FUNC Do\()\inst\()_SW SE_PROLOG \inst\()_SW SE_EPILOG +END_FUNC .endm #endif diff --git a/sdk/simulation/uae_service_sim/linux/Makefile b/sdk/simulation/uae_service_sim/linux/Makefile index cb673f147..c66beed2a 100644 --- a/sdk/simulation/uae_service_sim/linux/Makefile +++ b/sdk/simulation/uae_service_sim/linux/Makefile @@ -29,13 +29,10 @@ # # -TOP_DIR = ../../../.. +TOP_DIR = ../../../.. include $(TOP_DIR)/buildenv.mk -LAUNCH_VERSION:= $(shell awk '$$2 ~ /LAUNCH_VERSION/ { print substr($$3, 2, length($$3) - 2); }' $(COMMON_DIR)/inc/internal/se_version.h) -PLATFORM_VERSION:= $(shell awk '$$2 ~ /PLATFORM_VERSION/ { print substr($$3, 2, length($$3) - 2); }' $(COMMON_DIR)/inc/internal/se_version.h) -EPID_VERSION:= $(shell awk '$$2 ~ /EPID_VERSION/ { print substr($$3, 2, length($$3) - 2); }' $(COMMON_DIR)/inc/internal/se_version.h) -QUOTE_EX_VERSION:= $(shell awk '$$2 ~ /QUOTE_EX_VERSION/ { print substr($$3, 2, length($$3) - 2); }' $(COMMON_DIR)/inc/internal/se_version.h) +get_version_name = $(addsuffix _VERSION,$(shell echo $(subst _deploy,,$(subst libsgx_,,$(basename $1))) | tr a-z A-Z)) PREBUILT_OPENSSL_DIR := $(LINUX_EXTERNAL_DIR)/dcap_source/prebuilt/openssl CRYPTO_LIB := -L$(PREBUILT_OPENSSL_DIR)/lib/linux64 -lcrypto @@ -54,7 +51,7 @@ INCLUDES := -I.. \ -I$(PREBUILT_OPENSSL_DIR)/inc -CXXFLAGS += -Wall -fPIC $(INCLUDES) -Werror -g $(CET_FLAGS) +CXXFLAGS += -Wall -fPIC $(INCLUDES) -Werror -g $(CET_FLAGS) CFLAGS := $(filter-out -fPIC -Werror, $(CFLAGS)) -Wall $(INCLUDES) $(CET_FLAGS) @@ -71,37 +68,23 @@ vpath %.cpp $(LINUX_PSW_DIR)/ae/common \ vpath %.c $(COMMON_DIR)/src -CPP_SRC := $(wildcard *.cpp ../*.cpp) se_sig_rl.cpp cpusvn_util.cpp sgx_read_rand.cpp +CPP_SRC := $(wildcard *.cpp ../*.cpp) se_sig_rl.cpp cpusvn_util.cpp sgx_read_rand.cpp CPP_SRC += crypto_evp_digest.cpp crypto_cmac_128.cpp C_SRC := se_trace.c se_thread.c OBJ := $(sort $(CPP_SRC:.cpp=.o)) \ $(C_SRC:.c=.o) -LIBNAME = libsgx_epid_sim.so libsgx_launch_sim.so libsgx_quote_ex_sim.so libsgx_uae_service_sim.so -ifndef DEBUG -LIBNAME_DEBUG = $(LIBNAME:.so=.so.debug) -endif +LIBNAME = libsgx_epid_sim.so libsgx_launch_sim.so libsgx_quote_ex_sim.so libsgx_uae_service_sim.so LIBUAE_SERVICE_DEPLOY := $(LIBNAME:_sim.so=_deploy.so) .PHONY: all -all: $(LIBNAME) $(LIBNAME_DEBUG) $(LIBUAE_SERVICE_DEPLOY) $(LEGACY_LIBNAME) $(LEGACY_LIBNAME_DEBUG) $(LEGACY_LIBUAE_SERVICE_DEPLOY) | $(BUILD_DIR) +all: $(LIBNAME) $(LIBUAE_SERVICE_DEPLOY) $(LEGACY_LIBUAE_SERVICE_DEPLOY) | $(BUILD_DIR) @$(foreach lib,$(LIBNAME),$(CP) $(lib) $|;) @$(foreach lib,$(LIBUAE_SERVICE_DEPLOY),$(CP) $(lib) $|;) -ifndef DEBUG - @$(foreach lib,$(LIBNAME_DEBUG),$(CP) $(lib) $|;) -endif libsgx_%_sim.so: $(OBJ) -lrdrand $(CXX) $(CXXFLAGS) $^ -shared $(LDUFLAGS) -Wl,--version-script=$(@:_sim.so=.lds) -Wl,--gc-sections $(EXTERNAL_LIB) -o $@ -%.so.debug: %.so -ifndef DEBUG - ((test -f $@) ||( \ - $(CP) $< $<.orig &&\ - $(OBJCOPY) --only-keep-debug $< $@ &&\ - $(STRIP) -g $< &&\ - $(OBJCOPY) --add-gnu-debuglink=$@ $< )) -endif %.o: %.c $(CC) $(CFLAGS) -Werror -fPIC -c $< -o $@ @@ -121,7 +104,7 @@ else endif libsgx_%_deploy.so: ../libsgx_%_deploy.c - $(CC) -I$(COMMON_DIR)/inc $(CET_FLAGS) -fPIC -shared -Wl,-soname=$(@:_deploy.so=.so.$(call SPLIT_VERSION,$($(shell echo $(@:libsgx_%_deploy.so=%_version)|tr a-z A-Z)),1)) $< -o $@ + $(CC) -I$(COMMON_DIR)/inc $(CET_FLAGS) -fPIC -shared -Wl,-soname=$(@:_deploy.so=.so.$(call get_major_version,$(call get_version_name,$@))) $< -o $@ libsgx_uae_service_deploy.so: $(wildcard ../*_deploy.c) $(CC) -I$(COMMON_DIR)/inc $(CET_FLAGS) -fPIC -shared -Wl,-soname=$(@:_deploy.so=.so) $^ -o $@ @@ -134,8 +117,7 @@ clean: @$(RM) *.o @$(RM) ../*.o *.orig @$(RM) $(LIBNAME) $(addprefix $(BUILD_DIR)/,$(LIBNAME)) - @$(RM) $(LIBNAME_DEBUG) $(addprefix $(BUILD_DIR)/,$(LIBNAME_DEBUG)) - @$(RM) $(LIBUAE_SERVICE_DEPLOY) $(addprefix $(BUILD_DIR)/,$(LIBUAE_SERVICE_DEPLOY)) + @$(RM) $(LIBUAE_SERVICE_DEPLOY) $(addprefix $(BUILD_DIR)/,$(LIBUAE_SERVICE_DEPLOY)) ifeq ($(RDRAND_MAKEFILE), $(wildcard $(RDRAND_MAKEFILE))) @$(MAKE) distclean -C $(RDRAND_LIBDIR) endif diff --git a/sdk/simulation/urtssim/linux/Makefile b/sdk/simulation/urtssim/linux/Makefile index 96ce2b606..dde577ca8 100644 --- a/sdk/simulation/urtssim/linux/Makefile +++ b/sdk/simulation/urtssim/linux/Makefile @@ -31,8 +31,6 @@ include ../../../../buildenv.mk -URTS_VER:= $(shell awk '$$2 ~ /URTS_VERSION/ { print substr($$3, 2, length($$3) - 2); }' $(COMMON_DIR)/inc/internal/se_version.h) - SIM_DIR := $(LINUX_SDK_DIR)/simulation VTUNE_DIR = $(LINUX_EXTERNAL_DIR)/vtune/linux @@ -127,31 +125,19 @@ vpath %.c .:$(DIR6) LDFLAGS += $(COMMON_LDFLAGS) -Wl,--version-script=$(LINUX_PSW_DIR)/urts/linux/urts.lds LIBURTSSIM_SHARED := libsgx_urts_sim.so -LIBURTSSIM_DEBUG := libsgx_urts_sim.so.debug LIBURTS_DEPLOY := libsgx_urts_deploy.so -LDLIBS += -lwrapper $(CRYPTO_LIB) -Wl,-Bdynamic -Wl,-Bsymbolic -lsgx_uae_service_sim +LDLIBS += -lwrapper $(CRYPTO_LIB) -Wl,-Bdynamic -Wl,-Bsymbolic -lsgx_uae_service_sim SONAME = $(LIBURTSSIM_SHARED) .PHONY: all -all: $(LIBURTSSIM_SHARED) $(LIBURTSSIM_DEBUG) $(LIBURTS_DEPLOY)| $(BUILD_DIR) +all: $(LIBURTSSIM_SHARED) $(LIBURTS_DEPLOY)| $(BUILD_DIR) $(CP) $(LIBURTSSIM_SHARED) $| $(CP) $(LIBURTS_DEPLOY) $| -ifndef DEBUG - $(CP) $(LIBURTSSIM_DEBUG) $| -endif $(LIBURTSSIM_SHARED): simasm uinst driver_api wrapper uae_service_sim $(OBJ) $(OBJ6) ittnotify $(CXX) $(CXXFLAGS) -shared -Wl,-soname=$(SONAME) $(OBJ) $(OBJ6) $(LDFLAGS) $(LDLIBS) -o $@ -$(LIBURTSSIM_DEBUG): $(LIBURTSSIM_SHARED) -ifndef DEBUG - $(CP) $(LIBURTSSIM_SHARED) $(LIBURTSSIM_SHARED).orig - $(OBJCOPY) --only-keep-debug $(LIBURTSSIM_SHARED) $(LIBURTSSIM_DEBUG) - $(STRIP) -g $(LIBURTSSIM_SHARED) - $(OBJCOPY) --add-gnu-debuglink=$(LIBURTSSIM_DEBUG) $(LIBURTSSIM_SHARED) -endif - $(BUILD_DIR): @$(MKDIR) $@ @@ -188,12 +174,12 @@ ittnotify: CFLAGS= CXXFLAGS= $(MAKE) -C $(VTUNE_DIR)/sdk/src/ittnotify/ $(LIBURTS_DEPLOY):../urts_deploy.c - $(CC) -I$(COMMON_DIR)/inc $(CET_FLAGS) -shared -fPIC -Wl,-soname=libsgx_urts.so.$(call SPLIT_VERSION,$(URTS_VER),1) $< -o $@ + $(CC) -I$(COMMON_DIR)/inc $(CET_FLAGS) -shared -fPIC -Wl,-soname=libsgx_urts.so.$(call get_major_version,URTS_VERSION) $< -o $@ .PHONY: clean clean:: - @$(RM) *.o $(LIBURTSSIM_SHARED) $(LIBURTS_DEPLOY) $(LIBURTSSIM_DEBUG) $(LIBURTSSIM_SHARED).orig - @$(RM) $(BUILD_DIR)/$(LIBURTSSIM_SHARED) $(BUILD_DIR)/$(LIBURTS_DEPLOY) $(BUILD_DIR)/$(LIBURTSSIM_DEBUG) + @$(RM) *.o $(LIBURTSSIM_SHARED) $(LIBURTS_DEPLOY) + @$(RM) $(BUILD_DIR)/$(LIBURTSSIM_SHARED) $(BUILD_DIR)/$(LIBURTS_DEPLOY) $(MAKE) -C $(COMMON_DIR)/se_wrapper clean $(MAKE) -C $(SIM_DIR)/driver_api/ clean $(MAKE) -C $(SIM_DIR)/assembly/ clean diff --git a/sdk/tlibc/time/_def_time.c b/sdk/tlibc/time/_def_time.c new file mode 100644 index 000000000..ad2a56650 --- /dev/null +++ b/sdk/tlibc/time/_def_time.c @@ -0,0 +1,38 @@ +/* $OpenBSD: _def_time.c,v 1.6 2016/05/23 00:05:15 guenther Exp $ */ +/* + * Written by J.T. Conklin . + * Public domain. + */ + +#ifdef USE_LOCALE +#include +#endif +#include "localedef.h" + +const _TimeLocale _DefaultTimeLocale = +{ + { + "Sun","Mon","Tue","Wed","Thu","Fri","Sat", + }, + { + "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", + "Friday", "Saturday" + }, + { + "Jan", "Feb", "Mar", "Apr", "May", "Jun", + "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" + }, + { + "January", "February", "March", "April", "May", "June", "July", + "August", "September", "October", "November", "December" + }, + { + "AM", "PM" + }, + "%a %b %e %H:%M:%S %Y", + "%m/%d/%y", + "%H:%M:%S", + "%I:%M:%S %p" +}; + +const _TimeLocale *_CurrentTimeLocale = &_DefaultTimeLocale; diff --git a/sdk/tlibc/time/localedef.h b/sdk/tlibc/time/localedef.h new file mode 100644 index 000000000..ce16287eb --- /dev/null +++ b/sdk/tlibc/time/localedef.h @@ -0,0 +1,54 @@ +/* $OpenBSD: localedef.h,v 1.1 2016/05/23 00:05:15 guenther Exp $ */ +/* $NetBSD: localedef.h,v 1.4 1996/04/09 20:55:31 cgd Exp $ */ + +/* + * Copyright (c) 1994 Winning Strategies, Inc. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by Winning Strategies, Inc. + * 4. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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 _LOCALEDEF_H_ +#define _LOCALEDEF_H_ + +#include + +typedef struct { + const char *abday[7]; + const char *day[7]; + const char *abmon[12]; + const char *mon[12]; + const char *am_pm[2]; + const char *d_t_fmt; + const char *d_fmt; + const char *t_fmt; + const char *t_fmt_ampm; +} _TimeLocale; + +extern const _TimeLocale *_CurrentTimeLocale; +extern const _TimeLocale _DefaultTimeLocale; + +#endif /* !_LOCALEDEF_H_ */ diff --git a/sdk/tlibc/time/localtime.c b/sdk/tlibc/time/localtime.c new file mode 100644 index 000000000..bb0503ae3 --- /dev/null +++ b/sdk/tlibc/time/localtime.c @@ -0,0 +1,847 @@ +/* $OpenBSD: localtime.c,v 1.65 2022/10/03 15:34:39 millert Exp $ */ +/* +** This file is in the public domain, so clarified as of +** 1996-06-05 by Arthur David Olson. +*/ + +/* +** Leap second handling from Bradley White. +** POSIX-style TZ environment variable handling from Guy Harris. +*/ + +#include +#include +#include "sgx_spinlock.h" +#include +#include +#include + +#include "private.h" +#include "tzfile.h" + + +#ifndef TZ_ABBR_MAX_LEN +#define TZ_ABBR_MAX_LEN 16 +#endif /* !defined TZ_ABBR_MAX_LEN */ + +#ifndef TZ_ABBR_CHAR_SET +#define TZ_ABBR_CHAR_SET \ + "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 :+-._" +#endif /* !defined TZ_ABBR_CHAR_SET */ + +#ifndef TZ_ABBR_ERR_CHAR +#define TZ_ABBR_ERR_CHAR '_' +#endif /* !defined TZ_ABBR_ERR_CHAR */ + +#ifndef WILDABBR +/* +** Someone might make incorrect use of a time zone abbreviation: +** 1. They might reference tzname[0] before calling tzset (explicitly +** or implicitly). +** 2. They might reference tzname[1] before calling tzset (explicitly +** or implicitly). +** 3. They might reference tzname[1] after setting to a time zone +** in which Daylight Saving Time is never observed. +** 4. They might reference tzname[0] after setting to a time zone +** in which Standard Time is never observed. +** 5. They might reference tm.tm_zone after calling offtime. +** What's best to do in the above cases is open to debate; +** for now, we just set things up so that in any of the five cases +** WILDABBR is used. Another possibility: initialize tzname[0] to the +** string "tzname[0] used before set", and similarly for the other cases. +** And another: initialize tzname[0] to "ERA", with an explanation in the +** manual page of what this "time zone abbreviation" means (doing this so +** that tzname[0] has the "normal" length of three characters). +*/ +#define WILDABBR " " +#endif /* !defined WILDABBR */ + +static char wildabbr[] = WILDABBR; + +static const char gmt[] = "GMT"; + +/* +** The DST rules to use if TZ has no rules and we can't load TZDEFRULES. +** We default to US rules as of 1999-08-17. +** POSIX 1003.1 section 8.1.1 says that the default DST rules are +** implementation dependent; for historical reasons, US rules are a +** common default. +*/ +#ifndef TZDEFRULESTRING +#define TZDEFRULESTRING ",M4.1.0,M10.5.0" +#endif /* !defined TZDEFDST */ + +struct ttinfo { /* time type information */ + long tt_gmtoff; /* UTC offset in seconds */ + int tt_isdst; /* used to set tm_isdst */ + int tt_abbrind; /* abbreviation list index */ + int tt_ttisstd; /* TRUE if transition is std time */ + int tt_ttisgmt; /* TRUE if transition is UTC */ +}; + +struct lsinfo { /* leap second information */ + time_t ls_trans; /* transition time */ + long ls_corr; /* correction to apply */ +}; + +#define BIGGEST(a, b) (((a) > (b)) ? (a) : (b)) + +#ifdef TZNAME_MAX +#define MY_TZNAME_MAX TZNAME_MAX +#endif /* defined TZNAME_MAX */ +#ifndef TZNAME_MAX +#define MY_TZNAME_MAX 255 +#endif /* !defined TZNAME_MAX */ + +struct state { + int leapcnt; + int timecnt; + int typecnt; + int charcnt; + int goback; + int goahead; + time_t ats[TZ_MAX_TIMES]; + unsigned char types[TZ_MAX_TIMES]; + struct ttinfo ttis[TZ_MAX_TYPES]; + char chars[BIGGEST(BIGGEST(TZ_MAX_CHARS + 1, sizeof gmt), + (2 * (MY_TZNAME_MAX + 1)))]; + struct lsinfo lsis[TZ_MAX_LEAPS]; +}; + +struct rule { + int r_type; /* type of rule--see below */ + int r_day; /* day number of rule */ + int r_week; /* week number of rule */ + int r_mon; /* month number of rule */ + long r_time; /* transition time of rule */ +}; + +#define JULIAN_DAY 0 /* Jn - Julian day */ +#define DAY_OF_YEAR 1 /* n - day of year */ +#define MONTH_NTH_DAY_OF_WEEK 2 /* Mm.n.d - month, week, day of week */ + +/* +** Prototypes for static functions. +*/ +static struct tm * localsub(const time_t * timep, long offset, + struct tm * tmp); +static int increment_overflow(int * number, int delta); +static int leaps_thru_end_of(int y); +static int long_increment_overflow(long * number, int delta); +static int long_normalize_overflow(long * tensptr, + int * unitsptr, int base); +static int normalize_overflow(int * tensptr, int * unitsptr, + int base); +static void settzname(void); +static time_t time1(struct tm * tmp, + struct tm * (*funcp)(const time_t *, + long, struct tm *), + long offset); +static time_t time2(struct tm *tmp, + struct tm * (*funcp)(const time_t *, + long, struct tm*), + long offset, int * okayp); +static time_t time2sub(struct tm *tmp, + struct tm * (*funcp)(const time_t *, + long, struct tm*), + long offset, int * okayp, int do_norm_secs); +static struct tm * timesub(const time_t * timep, long offset, + const struct state * sp, struct tm * tmp); +static int tmcomp(const struct tm * atmp, + const struct tm * btmp); + +static struct state * lclptr; +static struct state * gmtptr; + + +#ifndef TZ_STRLEN_MAX +#define TZ_STRLEN_MAX 255 +#endif /* !defined TZ_STRLEN_MAX */ + +static sgx_spinlock_t lcl = SGX_SPINLOCK_INITIALIZER; + + +char * tzname[2] = { + wildabbr, + wildabbr +}; +#if 0 +DEF_WEAK(tzname); +#endif + +/* +** Section 4.12.3 of X3.159-1989 requires that +** Except for the strftime function, these functions [asctime, +** ctime, gmtime, localtime] return values in one of two static +** objects: a broken-down time structure and an array of char. +** Thanks to Paul Eggert for noting this. +*/ + +long timezone = 0; +int daylight = 0; + +static void +settzname(void) +{ + struct state * const sp = lclptr; + int i; + + tzname[0] = wildabbr; + tzname[1] = wildabbr; + daylight = 0; + timezone = 0; + if (sp == NULL) { + tzname[0] = tzname[1] = (char *)gmt; + return; + } + /* + ** And to get the latest zone names into tzname. . . + */ + for (i = 0; i < sp->timecnt; ++i) { + const struct ttinfo *ttisp = &sp->ttis[sp->types[i]]; + + tzname[ttisp->tt_isdst] = &sp->chars[ttisp->tt_abbrind]; + if (ttisp->tt_isdst) + daylight = 1; + if (!ttisp->tt_isdst) + timezone = -(ttisp->tt_gmtoff); + } + /* + ** Finally, scrub the abbreviations. + ** First, replace bogus characters. + */ + for (i = 0; i < sp->charcnt; ++i) { + if (strchr(TZ_ABBR_CHAR_SET, sp->chars[i]) == NULL) + sp->chars[i] = TZ_ABBR_ERR_CHAR; + } + /* + ** Second, truncate long abbreviations. + */ + for (i = 0; i < sp->typecnt; ++i) { + const struct ttinfo *ttisp = &sp->ttis[i]; + char *cp = &sp->chars[ttisp->tt_abbrind]; + + if (strlen(cp) > TZ_ABBR_MAX_LEN && + strcmp(cp, GRANDPARENTED) != 0) + *(cp + TZ_ABBR_MAX_LEN) = '\0'; + } +} + +static const int mon_lengths[2][MONSPERYEAR] = { + { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }, + { 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 } +}; + +static const int year_lengths[2] = { + DAYSPERNYEAR, DAYSPERLYEAR +}; + +static void +tzset_basic(void) +{ + + // Orig implementation is to read TimeZone from env. + // Inside enclave, disable TimeZone + const char *name = "\0"; + if (lclptr == NULL) { + lclptr = calloc(1, sizeof *lclptr); + if (lclptr == NULL) { + settzname(); /* all we can do */ + return; + } + } + if (*name == '\0') { + /* + ** User wants it fast rather than right. + */ + lclptr->leapcnt = 0; /* so, we're off a little */ + lclptr->timecnt = 0; + lclptr->typecnt = 0; + lclptr->ttis[0].tt_isdst = 0; + lclptr->ttis[0].tt_gmtoff = 0; + lclptr->ttis[0].tt_abbrind = 0; + strlcpy(lclptr->chars, gmt, sizeof lclptr->chars); + } + settzname(); +} + +/* +** The easy way to behave "as if no library function calls" localtime +** is to not call it--so we drop its guts into "localsub", which can be +** freely called. (And no, the PANS doesn't require the above behavior-- +** but it *is* desirable.) +** +** The unused offset argument is for the benefit of mktime variants. +*/ + +static struct tm * +localsub(const time_t *timep, long offset, struct tm *tmp) +{ + struct state * sp; + const struct ttinfo * ttisp; + int i; + struct tm * result; + const time_t t = *timep; + + sp = lclptr; + + if (sp == NULL) + //return gmtsub(timep, offset, tmp); + return NULL; + + if ((sp->goback && t < sp->ats[0]) || + (sp->goahead && t > sp->ats[sp->timecnt - 1])) { + time_t newt = t; + time_t seconds; + time_t tcycles; + int_fast64_t icycles; + + if (t < sp->ats[0]) + seconds = sp->ats[0] - t; + else + seconds = t - sp->ats[sp->timecnt - 1]; + --seconds; + tcycles = seconds / YEARSPERREPEAT / AVGSECSPERYEAR; + ++tcycles; + icycles = tcycles; + if (tcycles - icycles >= 1 || icycles - tcycles >= 1) + return NULL; + seconds = icycles; + seconds *= YEARSPERREPEAT; + seconds *= AVGSECSPERYEAR; + if (t < sp->ats[0]) + newt += seconds; + else + newt -= seconds; + if (newt < sp->ats[0] || + newt > sp->ats[sp->timecnt - 1]) + return NULL; /* "cannot happen" */ + result = localsub(&newt, offset, tmp); + if (result == tmp) { + time_t newy; + + newy = tmp->tm_year; + if (t < sp->ats[0]) + newy -= icycles * YEARSPERREPEAT; + else + newy += icycles * YEARSPERREPEAT; + tmp->tm_year = newy; + if (tmp->tm_year != newy) + return NULL; + } + return result; + } + if (sp->timecnt == 0 || t < sp->ats[0]) { + i = 0; + while (sp->ttis[i].tt_isdst) { + if (++i >= sp->typecnt) { + i = 0; + break; + } + } + } else { + int lo = 1; + int hi = sp->timecnt; + + while (lo < hi) { + int mid = (lo + hi) >> 1; + + if (t < sp->ats[mid]) + hi = mid; + else + lo = mid + 1; + } + i = (int) sp->types[lo - 1]; + } + ttisp = &sp->ttis[i]; + /* + ** To get (wrong) behavior that's compatible with System V Release 2.0 + ** you'd replace the statement below with + ** t += ttisp->tt_gmtoff; + ** timesub(&t, 0L, sp, tmp); + */ + result = timesub(&t, ttisp->tt_gmtoff, sp, tmp); + tmp->tm_isdst = ttisp->tt_isdst; + tzname[tmp->tm_isdst] = &sp->chars[ttisp->tt_abbrind]; + tmp->tm_zone = &sp->chars[ttisp->tt_abbrind]; + return result; +} + +/* +** Return the number of leap years through the end of the given year +** where, to make the math easy, the answer for year zero is defined as zero. +*/ + +static int +leaps_thru_end_of(int y) +{ + return (y >= 0) ? (y / 4 - y / 100 + y / 400) : + -(leaps_thru_end_of(-(y + 1)) + 1); +} + +static struct tm * +timesub(const time_t *timep, long offset, const struct state *sp, struct tm *tmp) +{ + const struct lsinfo * lp; + time_t tdays; + int idays; /* unsigned would be so 2003 */ + long rem; + int y; + const int * ip; + long corr; + int hit; + int i; + long seconds; + + corr = 0; + hit = 0; + i = (sp == NULL) ? 0 : sp->leapcnt; + while (--i >= 0) { + lp = &sp->lsis[i]; + if (*timep >= lp->ls_trans) { + if (*timep == lp->ls_trans) { + hit = ((i == 0 && lp->ls_corr > 0) || + lp->ls_corr > sp->lsis[i - 1].ls_corr); + if (hit) { + while (i > 0 && + sp->lsis[i].ls_trans == + sp->lsis[i - 1].ls_trans + 1 && + sp->lsis[i].ls_corr == + sp->lsis[i - 1].ls_corr + 1) { + ++hit; + --i; + } + } + } + corr = lp->ls_corr; + break; + } + } + y = EPOCH_YEAR; + tdays = *timep / SECSPERDAY; + rem = *timep - tdays * SECSPERDAY; + while (tdays < 0 || tdays >= year_lengths[isleap(y)]) { + int newy; + time_t tdelta; + int idelta; + int leapdays; + + tdelta = tdays / DAYSPERLYEAR; + idelta = tdelta; + if (tdelta - idelta >= 1 || idelta - tdelta >= 1) + return NULL; + if (idelta == 0) + idelta = (tdays < 0) ? -1 : 1; + newy = y; + if (increment_overflow(&newy, idelta)) + return NULL; + leapdays = leaps_thru_end_of(newy - 1) - + leaps_thru_end_of(y - 1); + tdays -= ((time_t) newy - y) * DAYSPERNYEAR; + tdays -= leapdays; + y = newy; + } + + seconds = tdays * SECSPERDAY + 0.5; + tdays = seconds / SECSPERDAY; + rem += seconds - tdays * SECSPERDAY; + + /* + ** Given the range, we can now fearlessly cast... + */ + idays = tdays; + rem += offset - corr; + while (rem < 0) { + rem += SECSPERDAY; + --idays; + } + while (rem >= SECSPERDAY) { + rem -= SECSPERDAY; + ++idays; + } + while (idays < 0) { + if (increment_overflow(&y, -1)) + return NULL; + idays += year_lengths[isleap(y)]; + } + while (idays >= year_lengths[isleap(y)]) { + idays -= year_lengths[isleap(y)]; + if (increment_overflow(&y, 1)) + return NULL; + } + tmp->tm_year = y; + if (increment_overflow(&tmp->tm_year, -TM_YEAR_BASE)) + return NULL; + tmp->tm_yday = idays; + /* + ** The "extra" mods below avoid overflow problems. + */ + tmp->tm_wday = EPOCH_WDAY + + ((y - EPOCH_YEAR) % DAYSPERWEEK) * + (DAYSPERNYEAR % DAYSPERWEEK) + + leaps_thru_end_of(y - 1) - + leaps_thru_end_of(EPOCH_YEAR - 1) + + idays; + tmp->tm_wday %= DAYSPERWEEK; + if (tmp->tm_wday < 0) + tmp->tm_wday += DAYSPERWEEK; + tmp->tm_hour = (int) (rem / SECSPERHOUR); + rem %= SECSPERHOUR; + tmp->tm_min = (int) (rem / SECSPERMIN); + /* + ** A positive leap second requires a special + ** representation. This uses "... ??:59:60" et seq. + */ + tmp->tm_sec = (int) (rem % SECSPERMIN) + hit; + ip = mon_lengths[isleap(y)]; + for (tmp->tm_mon = 0; idays >= ip[tmp->tm_mon]; ++(tmp->tm_mon)) + idays -= ip[tmp->tm_mon]; + tmp->tm_mday = (int) (idays + 1); + tmp->tm_isdst = 0; + tmp->tm_gmtoff = offset; + return tmp; +} + +/* +** Adapted from code provided by Robert Elz, who writes: +** The "best" way to do mktime I think is based on an idea of Bob +** Kridle's (so its said...) from a long time ago. +** It does a binary search of the time_t space. Since time_t's are +** just 32 bits, its a max of 32 iterations (even at 64 bits it +** would still be very reasonable). +*/ + +#ifndef WRONG +#define WRONG (-1) +#endif /* !defined WRONG */ + +/* +** Normalize logic courtesy Paul Eggert. +*/ + +static int +increment_overflow(int *ip, int j) +{ + int const i = *ip; + + /* + ** If i >= 0 there can only be overflow if i + j > INT_MAX + ** or if j > INT_MAX - i; given i >= 0, INT_MAX - i cannot overflow. + ** If i < 0 there can only be overflow if i + j < INT_MIN + ** or if j < INT_MIN - i; given i < 0, INT_MIN - i cannot overflow. + */ + if ((i >= 0) ? (j > INT_MAX - i) : (j < INT_MIN - i)) + return TRUE; + *ip += j; + return FALSE; +} + +static int +long_increment_overflow(long *lp, int m) +{ + long const l = *lp; + + if ((l >= 0) ? (m > LONG_MAX - l) : (m < LONG_MIN - l)) + return TRUE; + *lp += m; + return FALSE; +} + +static int +normalize_overflow(int *tensptr, int *unitsptr, int base) +{ + int tensdelta; + + tensdelta = (*unitsptr >= 0) ? + (*unitsptr / base) : + (-1 - (-1 - *unitsptr) / base); + *unitsptr -= tensdelta * base; + return increment_overflow(tensptr, tensdelta); +} + +static int +long_normalize_overflow(long *tensptr, int *unitsptr, int base) +{ + int tensdelta; + + tensdelta = (*unitsptr >= 0) ? + (*unitsptr / base) : + (-1 - (-1 - *unitsptr) / base); + *unitsptr -= tensdelta * base; + return long_increment_overflow(tensptr, tensdelta); +} + +static int +tmcomp(const struct tm *atmp, const struct tm *btmp) +{ + int result; + + if ((result = (atmp->tm_year - btmp->tm_year)) == 0 && + (result = (atmp->tm_mon - btmp->tm_mon)) == 0 && + (result = (atmp->tm_mday - btmp->tm_mday)) == 0 && + (result = (atmp->tm_hour - btmp->tm_hour)) == 0 && + (result = (atmp->tm_min - btmp->tm_min)) == 0) + result = atmp->tm_sec - btmp->tm_sec; + return result; +} + +static time_t +time2sub(struct tm *tmp, struct tm *(*funcp)(const time_t *, long, struct tm *), + long offset, int *okayp, int do_norm_secs) +{ + const struct state * sp; + int dir; + int i, j; + int saved_seconds; + long li; + time_t lo; + time_t hi; + long y; + time_t newt; + time_t t; + struct tm yourtm, mytm; + + *okayp = FALSE; + yourtm = *tmp; + if (do_norm_secs) { + if (normalize_overflow(&yourtm.tm_min, &yourtm.tm_sec, + SECSPERMIN)) + return WRONG; + } + if (normalize_overflow(&yourtm.tm_hour, &yourtm.tm_min, MINSPERHOUR)) + return WRONG; + if (normalize_overflow(&yourtm.tm_mday, &yourtm.tm_hour, HOURSPERDAY)) + return WRONG; + y = yourtm.tm_year; + if (long_normalize_overflow(&y, &yourtm.tm_mon, MONSPERYEAR)) + return WRONG; + /* + ** Turn y into an actual year number for now. + ** It is converted back to an offset from TM_YEAR_BASE later. + */ + if (long_increment_overflow(&y, TM_YEAR_BASE)) + return WRONG; + while (yourtm.tm_mday <= 0) { + if (long_increment_overflow(&y, -1)) + return WRONG; + li = y + (1 < yourtm.tm_mon); + yourtm.tm_mday += year_lengths[isleap(li)]; + } + while (yourtm.tm_mday > DAYSPERLYEAR) { + li = y + (1 < yourtm.tm_mon); + yourtm.tm_mday -= year_lengths[isleap(li)]; + if (long_increment_overflow(&y, 1)) + return WRONG; + } + for ( ; ; ) { + i = mon_lengths[isleap(y)][yourtm.tm_mon]; + if (yourtm.tm_mday <= i) + break; + yourtm.tm_mday -= i; + if (++yourtm.tm_mon >= MONSPERYEAR) { + yourtm.tm_mon = 0; + if (long_increment_overflow(&y, 1)) + return WRONG; + } + } + if (long_increment_overflow(&y, -TM_YEAR_BASE)) + return WRONG; + yourtm.tm_year = y; + if (yourtm.tm_year != y) + return WRONG; + if (yourtm.tm_sec >= 0 && yourtm.tm_sec < SECSPERMIN) + saved_seconds = 0; + else if (y + TM_YEAR_BASE < EPOCH_YEAR) { + /* + ** We can't set tm_sec to 0, because that might push the + ** time below the minimum representable time. + ** Set tm_sec to 59 instead. + ** This assumes that the minimum representable time is + ** not in the same minute that a leap second was deleted from, + ** which is a safer assumption than using 58 would be. + */ + if (increment_overflow(&yourtm.tm_sec, 1 - SECSPERMIN)) + return WRONG; + saved_seconds = yourtm.tm_sec; + yourtm.tm_sec = SECSPERMIN - 1; + } else { + saved_seconds = yourtm.tm_sec; + yourtm.tm_sec = 0; + } + /* + ** Do a binary search (this works whatever time_t's type is). + */ + lo = 1; + for (i = 0; i < (int) TYPE_BIT(time_t) - 1; ++i) + lo *= 2; + hi = -(lo + 1); + for ( ; ; ) { + t = lo / 2 + hi / 2; + if (t < lo) + t = lo; + else if (t > hi) + t = hi; + if ((*funcp)(&t, offset, &mytm) == NULL) { + /* + ** Assume that t is too extreme to be represented in + ** a struct tm; arrange things so that it is less + ** extreme on the next pass. + */ + dir = (t > 0) ? 1 : -1; + } else + dir = tmcomp(&mytm, &yourtm); + if (dir != 0) { + if (t == lo) { + ++t; + if (t <= lo) + return WRONG; + ++lo; + } else if (t == hi) { + --t; + if (t >= hi) + return WRONG; + --hi; + } + if (lo > hi) + return WRONG; + if (dir > 0) + hi = t; + else + lo = t; + continue; + } + if (yourtm.tm_isdst < 0 || mytm.tm_isdst == yourtm.tm_isdst) + break; + /* + ** Right time, wrong type. + ** Hunt for right time, right type. + ** It's okay to guess wrong since the guess + ** gets checked. + */ + sp = (const struct state *) + ((funcp == localsub) ? lclptr : gmtptr); + if (sp == NULL) + return WRONG; + for (i = sp->typecnt - 1; i >= 0; --i) { + if (sp->ttis[i].tt_isdst != yourtm.tm_isdst) + continue; + for (j = sp->typecnt - 1; j >= 0; --j) { + if (sp->ttis[j].tt_isdst == yourtm.tm_isdst) + continue; + newt = t + sp->ttis[j].tt_gmtoff - + sp->ttis[i].tt_gmtoff; + if ((*funcp)(&newt, offset, &mytm) == NULL) + continue; + if (tmcomp(&mytm, &yourtm) != 0) + continue; + if (mytm.tm_isdst != yourtm.tm_isdst) + continue; + /* + ** We have a match. + */ + t = newt; + goto label; + } + } + return WRONG; + } +label: + newt = t + saved_seconds; + if ((newt < t) != (saved_seconds < 0)) + return WRONG; + t = newt; + if ((*funcp)(&t, offset, tmp)) + *okayp = TRUE; + return t; +} + +static time_t +time2(struct tm *tmp, struct tm * (*funcp)(const time_t *, long, struct tm *), + long offset, int *okayp) +{ + time_t t; + + /* + ** First try without normalization of seconds + ** (in case tm_sec contains a value associated with a leap second). + ** If that fails, try with normalization of seconds. + */ + t = time2sub(tmp, funcp, offset, okayp, FALSE); + return *okayp ? t : time2sub(tmp, funcp, offset, okayp, TRUE); +} + +static time_t +time1(struct tm *tmp, struct tm * (*funcp)(const time_t *, long, struct tm *), + long offset) +{ + time_t t; + const struct state * sp; + int samei, otheri; + int sameind, otherind; + int i; + int nseen; + int seen[TZ_MAX_TYPES]; + int types[TZ_MAX_TYPES]; + int okay; + + if (tmp == NULL) { + errno = EINVAL; + return WRONG; + } + if (tmp->tm_isdst > 1) + tmp->tm_isdst = 1; + t = time2(tmp, funcp, offset, &okay); + + if (okay || tmp->tm_isdst < 0) + return t; + + /* + ** We're supposed to assume that somebody took a time of one type + ** and did some math on it that yielded a "struct tm" that's bad. + ** We try to divine the type they started from and adjust to the + ** type they need. + */ + sp = (const struct state *) ((funcp == localsub) ? lclptr : gmtptr); + if (sp == NULL) + return WRONG; + for (i = 0; i < sp->typecnt; ++i) + seen[i] = FALSE; + nseen = 0; + for (i = sp->timecnt - 1; i >= 0; --i) { + if (!seen[sp->types[i]]) { + seen[sp->types[i]] = TRUE; + types[nseen++] = sp->types[i]; + } + } + for (sameind = 0; sameind < nseen; ++sameind) { + samei = types[sameind]; + if (sp->ttis[samei].tt_isdst != tmp->tm_isdst) + continue; + for (otherind = 0; otherind < nseen; ++otherind) { + otheri = types[otherind]; + if (sp->ttis[otheri].tt_isdst == tmp->tm_isdst) + continue; + tmp->tm_sec += sp->ttis[otheri].tt_gmtoff - + sp->ttis[samei].tt_gmtoff; + tmp->tm_isdst = !tmp->tm_isdst; + t = time2(tmp, funcp, offset, &okay); + if (okay) + return t; + tmp->tm_sec -= sp->ttis[otheri].tt_gmtoff - + sp->ttis[samei].tt_gmtoff; + tmp->tm_isdst = !tmp->tm_isdst; + } + } + return WRONG; +} + +time_t +mktime(struct tm *tmp) +{ + time_t ret; + sgx_spin_lock(&lcl); + tzset_basic(); + ret = time1(tmp, localsub, 0L); + sgx_spin_unlock(&lcl); + return ret; +} diff --git a/sdk/tlibc/time/private.h b/sdk/tlibc/time/private.h index 846063e5b..7a088f9fa 100644 --- a/sdk/tlibc/time/private.h +++ b/sdk/tlibc/time/private.h @@ -8,6 +8,8 @@ ** 1996-06-05 by Arthur David Olson. */ +#define GRANDPARENTED "Local time zone must be set--see zic manual page" + /* ** Nested includes */ @@ -60,6 +62,27 @@ 1 + TYPE_SIGNED(type)) #endif /* !defined INT_STRLEN_MAXIMUM */ +#ifndef YEARSPERREPEAT +#define YEARSPERREPEAT 400 /* years before a Gregorian repeat */ +#endif /* !defined YEARSPERREPEAT */ + +/* +** The Gregorian year averages 365.2425 days, which is 31556952 seconds. +*/ + +#ifndef AVGSECSPERYEAR +#define AVGSECSPERYEAR 31556952L +#endif /* !defined AVGSECSPERYEAR */ + +#ifndef SECSPERREPEAT +#define SECSPERREPEAT ((int_fast64_t) YEARSPERREPEAT * (int_fast64_t) AVGSECSPERYEAR) +#endif /* !defined SECSPERREPEAT */ + +#ifndef SECSPERREPEAT_BITS +#define SECSPERREPEAT_BITS 34 /* ceil(log2(SECSPERREPEAT)) */ +#endif /* !defined SECSPERREPEAT_BITS */ + + /* Disable warnings */ #endif /* !defined PRIVATE_H */ diff --git a/sdk/tlibc/time/strptime.c b/sdk/tlibc/time/strptime.c new file mode 100644 index 000000000..08023a7cc --- /dev/null +++ b/sdk/tlibc/time/strptime.c @@ -0,0 +1,680 @@ +/* $OpenBSD: strptime.c,v 1.31 2023/03/02 16:21:51 millert Exp $ */ +/* $NetBSD: strptime.c,v 1.12 1998/01/20 21:39:40 mycroft Exp $ */ +/*- + * Copyright (c) 1997, 1998, 2005, 2008 The NetBSD Foundation, Inc. + * All rights reserved. + * + * This code was contributed to The NetBSD Foundation by Klaus Klein. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. 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 FOUNDATION 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 +#include +#include +#ifdef USE_LOCALE +#include +#endif +#include +#include +#include + +#include "localedef.h" +#include "private.h" +#include "tzfile.h" + +#define _ctloc(x) (_CurrentTimeLocale->x) + +/* + * We do not implement alternate representations. However, we always + * check whether a given modifier is allowed for a certain conversion. + */ +#define _ALT_E 0x01 +#define _ALT_O 0x02 +#define _LEGAL_ALT(x) { if (alt_format & ~(x)) return (0); } + +/* + * We keep track of some of the fields we set in order to compute missing ones. + */ +#define FIELD_TM_MON (1 << 0) +#define FIELD_TM_MDAY (1 << 1) +#define FIELD_TM_WDAY (1 << 2) +#define FIELD_TM_YDAY (1 << 3) +#define FIELD_TM_YEAR (1 << 4) + +static char gmt[] = { "GMT" }; +static char utc[] = { "UTC" }; +/* RFC-822/RFC-2822 */ +static const char * const nast[5] = { + "EST", "CST", "MST", "PST", "\0\0\0" +}; +static const char * const nadt[5] = { + "EDT", "CDT", "MDT", "PDT", "\0\0\0" +}; + +static const int mon_lengths[2][MONSPERYEAR] = { + { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }, + { 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 } +}; + +static int _conv_num(const unsigned char **, int *, int, int); +static int epoch_to_tm(const unsigned char **, struct tm *); +static int leaps_thru_end_of(const int y); +static char *_strptime(const char *, const char *, struct tm *, int); +static const u_char *_find_string(const u_char *, int *, const char * const *, + const char * const *, int); + + +char * +strptime(const char *buf, const char *fmt, struct tm *tm) +{ + return(_strptime(buf, fmt, tm, 1)); +} +DEF_WEAK(strptime); + +static char * +_strptime(const char *buf, const char *fmt, struct tm *tm, int initialize) +{ + unsigned char c; + const unsigned char *bp, *ep; + size_t len; + int alt_format, i, offs; + int neg = 0; + static int century, relyear, fields; + + if (initialize) { + century = TM_YEAR_BASE; + relyear = -1; + fields = 0; + } + + bp = (const unsigned char *)buf; + while ((c = *fmt) != '\0') { + /* Clear `alternate' modifier prior to new conversion. */ + alt_format = 0; + + /* Eat up white-space. */ + if (isspace(c)) { + while (isspace(*bp)) + bp++; + + fmt++; + continue; + } + + if ((c = *fmt++) != '%') + goto literal; + + +again: switch (c = *fmt++) { + case '%': /* "%%" is converted to "%". */ +literal: + if (c != *bp++) + return (NULL); + + break; + + /* + * "Alternative" modifiers. Just set the appropriate flag + * and start over again. + */ + case 'E': /* "%E?" alternative conversion modifier. */ + _LEGAL_ALT(0); + alt_format |= _ALT_E; + goto again; + + case 'O': /* "%O?" alternative conversion modifier. */ + _LEGAL_ALT(0); + alt_format |= _ALT_O; + goto again; + + /* + * "Complex" conversion rules, implemented through recursion. + */ + case 'c': /* Date and time, using the locale's format. */ + _LEGAL_ALT(_ALT_E); + if (!(bp = _strptime(bp, _ctloc(d_t_fmt), tm, 0))) + return (NULL); + break; + + case 'D': /* The date as "%m/%d/%y". */ + _LEGAL_ALT(0); + if (!(bp = _strptime(bp, "%m/%d/%y", tm, 0))) + return (NULL); + break; + + case 'F': /* The date as "%Y-%m-%d". */ + _LEGAL_ALT(0); + if (!(bp = _strptime(bp, "%Y-%m-%d", tm, 0))) + return (NULL); + continue; + + case 'R': /* The time as "%H:%M". */ + _LEGAL_ALT(0); + if (!(bp = _strptime(bp, "%H:%M", tm, 0))) + return (NULL); + break; + + case 'r': /* The time as "%I:%M:%S %p". */ + _LEGAL_ALT(0); + if (!(bp = _strptime(bp, "%I:%M:%S %p", tm, 0))) + return (NULL); + break; + + case 'T': /* The time as "%H:%M:%S". */ + _LEGAL_ALT(0); + if (!(bp = _strptime(bp, "%H:%M:%S", tm, 0))) + return (NULL); + break; + + case 'X': /* The time, using the locale's format. */ + _LEGAL_ALT(_ALT_E); + if (!(bp = _strptime(bp, _ctloc(t_fmt), tm, 0))) + return (NULL); + break; + + case 'x': /* The date, using the locale's format. */ + _LEGAL_ALT(_ALT_E); + if (!(bp = _strptime(bp, _ctloc(d_fmt), tm, 0))) + return (NULL); + break; + + /* + * "Elementary" conversion rules. + */ + case 'A': /* The day of week, using the locale's form. */ + case 'a': + _LEGAL_ALT(0); + for (i = 0; i < 7; i++) { + /* Full name. */ + len = strlen(_ctloc(day[i])); + if (strncasecmp(_ctloc(day[i]), bp, len) == 0) + break; + + /* Abbreviated name. */ + len = strlen(_ctloc(abday[i])); + if (strncasecmp(_ctloc(abday[i]), bp, len) == 0) + break; + } + + /* Nothing matched. */ + if (i == 7) + return (NULL); + + tm->tm_wday = i; + bp += len; + fields |= FIELD_TM_WDAY; + break; + + case 'B': /* The month, using the locale's form. */ + case 'b': + case 'h': + _LEGAL_ALT(0); + for (i = 0; i < 12; i++) { + /* Full name. */ + len = strlen(_ctloc(mon[i])); + if (strncasecmp(_ctloc(mon[i]), bp, len) == 0) + break; + + /* Abbreviated name. */ + len = strlen(_ctloc(abmon[i])); + if (strncasecmp(_ctloc(abmon[i]), bp, len) == 0) + break; + } + + /* Nothing matched. */ + if (i == 12) + return (NULL); + + tm->tm_mon = i; + bp += len; + fields |= FIELD_TM_MON; + break; + + case 'C': /* The century number. */ + _LEGAL_ALT(_ALT_E); + if (!(_conv_num(&bp, &i, 0, 99))) + return (NULL); + + century = i * 100; + break; + + case 'e': /* The day of month. */ + if (isspace(*bp)) + bp++; + /* FALLTHROUGH */ + case 'd': + _LEGAL_ALT(_ALT_O); + if (!(_conv_num(&bp, &tm->tm_mday, 1, 31))) + return (NULL); + fields |= FIELD_TM_MDAY; + break; + + case 'k': /* The hour (24-hour clock representation). */ + _LEGAL_ALT(0); + /* FALLTHROUGH */ + case 'H': + _LEGAL_ALT(_ALT_O); + if (!(_conv_num(&bp, &tm->tm_hour, 0, 23))) + return (NULL); + break; + + case 'l': /* The hour (12-hour clock representation). */ + _LEGAL_ALT(0); + /* FALLTHROUGH */ + case 'I': + _LEGAL_ALT(_ALT_O); + if (!(_conv_num(&bp, &tm->tm_hour, 1, 12))) + return (NULL); + break; + + case 'j': /* The day of year. */ + _LEGAL_ALT(0); + if (!(_conv_num(&bp, &tm->tm_yday, 1, 366))) + return (NULL); + tm->tm_yday--; + fields |= FIELD_TM_YDAY; + break; + + case 'M': /* The minute. */ + _LEGAL_ALT(_ALT_O); + if (!(_conv_num(&bp, &tm->tm_min, 0, 59))) + return (NULL); + break; + + case 'm': /* The month. */ + _LEGAL_ALT(_ALT_O); + if (!(_conv_num(&bp, &tm->tm_mon, 1, 12))) + return (NULL); + tm->tm_mon--; + fields |= FIELD_TM_MON; + break; + + case 'p': /* The locale's equivalent of AM/PM. */ + _LEGAL_ALT(0); + /* AM? */ + len = strlen(_ctloc(am_pm[0])); + if (strncasecmp(_ctloc(am_pm[0]), bp, len) == 0) { + if (tm->tm_hour > 12) /* i.e., 13:00 AM ?! */ + return (NULL); + else if (tm->tm_hour == 12) + tm->tm_hour = 0; + + bp += len; + break; + } + /* PM? */ + len = strlen(_ctloc(am_pm[1])); + if (strncasecmp(_ctloc(am_pm[1]), bp, len) == 0) { + if (tm->tm_hour > 12) /* i.e., 13:00 PM ?! */ + return (NULL); + else if (tm->tm_hour < 12) + tm->tm_hour += 12; + + bp += len; + break; + } + + /* Nothing matched. */ + return (NULL); + + case 'S': /* The seconds. */ + _LEGAL_ALT(_ALT_O); + if (!(_conv_num(&bp, &tm->tm_sec, 0, 60))) + return (NULL); + break; + case 's': /* Seconds since epoch. */ + #if 0 + if (!(epoch_to_tm(&bp, tm))) + return (NULL); + fields = 0xffff; /* everything */ + break; + #else + // No local time support in tlibc + return (NULL); + #endif + case 'U': /* The week of year, beginning on sunday. */ + case 'W': /* The week of year, beginning on monday. */ + _LEGAL_ALT(_ALT_O); + /* + * XXX This is bogus, as we can not assume any valid + * information present in the tm structure at this + * point to calculate a real value, so just check the + * range for now. + */ + if (!(_conv_num(&bp, &i, 0, 53))) + return (NULL); + break; + + case 'w': /* The day of week, beginning on sunday. */ + _LEGAL_ALT(_ALT_O); + if (!(_conv_num(&bp, &tm->tm_wday, 0, 6))) + return (NULL); + fields |= FIELD_TM_WDAY; + break; + + case 'u': /* The day of week, monday = 1. */ + _LEGAL_ALT(_ALT_O); + if (!(_conv_num(&bp, &i, 1, 7))) + return (NULL); + tm->tm_wday = i % 7; + fields |= FIELD_TM_WDAY; + continue; + + case 'g': /* The year corresponding to the ISO week + * number but without the century. + */ + if (!(_conv_num(&bp, &i, 0, 99))) + return (NULL); + continue; + + case 'G': /* The year corresponding to the ISO week + * number with century. + */ + do + bp++; + while (isdigit(*bp)); + continue; + + case 'V': /* The ISO 8601:1988 week number as decimal */ + if (!(_conv_num(&bp, &i, 0, 53))) + return (NULL); + continue; + + case 'Y': /* The year. */ + _LEGAL_ALT(_ALT_E); + if (!(_conv_num(&bp, &i, 0, 9999))) + return (NULL); + + relyear = -1; + tm->tm_year = i - TM_YEAR_BASE; + fields |= FIELD_TM_YEAR; + break; + + case 'y': /* The year within the century (2 digits). */ + _LEGAL_ALT(_ALT_E | _ALT_O); + if (!(_conv_num(&bp, &relyear, 0, 99))) + return (NULL); + break; + + case 'Z': + #if 0 + tzset(); + if (strncmp((const char *)bp, gmt, 3) == 0) { + tm->tm_isdst = 0; + tm->tm_gmtoff = 0; + tm->tm_zone = gmt; + bp += 3; + } else if (strncmp((const char *)bp, utc, 3) == 0) { + tm->tm_isdst = 0; + tm->tm_gmtoff = 0; + tm->tm_zone = utc; + bp += 3; + } else { + ep = _find_string(bp, &i, + (const char * const *)tzname, + NULL, 2); + if (ep == NULL) + return (NULL); + + tm->tm_isdst = i; + tm->tm_gmtoff = -(timezone); + tm->tm_zone = tzname[i]; + bp = ep; + } + continue; + #else + // Don't support TimeZone in tlibc + return (NULL); + #endif + + case 'z': + #if 0 + + /* + * We recognize all ISO 8601 formats: + * Z = Zulu time/UTC + * [+-]hhmm + * [+-]hh:mm + * [+-]hh + * We recognize all RFC-822/RFC-2822 formats: + * UT|GMT + * North American : UTC offsets + * E[DS]T = Eastern : -4 | -5 + * C[DS]T = Central : -5 | -6 + * M[DS]T = Mountain: -6 | -7 + * P[DS]T = Pacific : -7 | -8 + */ + while (isspace(*bp)) + bp++; + + switch (*bp++) { + case 'G': + if (*bp++ != 'M') + return NULL; + /*FALLTHROUGH*/ + case 'U': + if (*bp++ != 'T') + return NULL; + /*FALLTHROUGH*/ + case 'Z': + tm->tm_isdst = 0; + tm->tm_gmtoff = 0; + tm->tm_zone = utc; + continue; + case '+': + neg = 0; + break; + case '-': + neg = 1; + break; + default: + --bp; + ep = _find_string(bp, &i, nast, NULL, 4); + if (ep != NULL) { + tm->tm_gmtoff = (-5 - i) * SECSPERHOUR; + tm->tm_zone = (char *)nast[i]; + bp = ep; + continue; + } + ep = _find_string(bp, &i, nadt, NULL, 4); + if (ep != NULL) { + tm->tm_isdst = 1; + tm->tm_gmtoff = (-4 - i) * SECSPERHOUR; + tm->tm_zone = (char *)nadt[i]; + bp = ep; + continue; + } + return NULL; + } + if (!isdigit(bp[0]) || !isdigit(bp[1])) + return NULL; + offs = ((bp[0]-'0') * 10 + (bp[1]-'0')) * SECSPERHOUR; + bp += 2; + if (*bp == ':') + bp++; + if (isdigit(*bp)) { + offs += (*bp++ - '0') * 10 * SECSPERMIN; + if (!isdigit(*bp)) + return NULL; + offs += (*bp++ - '0') * SECSPERMIN; + } + if (neg) + offs = -offs; + tm->tm_isdst = 0; /* XXX */ + tm->tm_gmtoff = offs; + tm->tm_zone = NULL; /* XXX */ + continue; + #else + // Don't support TimeZone in tlibc + return (NULL); + #endif + + /* + * Miscellaneous conversions. + */ + case 'n': /* Any kind of white-space. */ + case 't': + _LEGAL_ALT(0); + while (isspace(*bp)) + bp++; + break; + + + default: /* Unknown/unsupported conversion. */ + return (NULL); + } + + + } + + /* + * We need to evaluate the two digit year spec (%y) + * last as we can get a century spec (%C) at any time. + */ + if (relyear != -1) { + if (century == TM_YEAR_BASE) { + if (relyear <= 68) + tm->tm_year = relyear + 2000 - TM_YEAR_BASE; + else + tm->tm_year = relyear + 1900 - TM_YEAR_BASE; + } else { + tm->tm_year = relyear + century - TM_YEAR_BASE; + } + fields |= FIELD_TM_YEAR; + } + + /* Compute some missing values when possible. */ + if (fields & FIELD_TM_YEAR) { + const int year = tm->tm_year + TM_YEAR_BASE; + const int *mon_lens = mon_lengths[isleap(year)]; + if (!(fields & FIELD_TM_YDAY) && + (fields & FIELD_TM_MON) && (fields & FIELD_TM_MDAY)) { + tm->tm_yday = tm->tm_mday - 1; + for (i = 0; i < tm->tm_mon; i++) + tm->tm_yday += mon_lens[i]; + fields |= FIELD_TM_YDAY; + } + if (fields & FIELD_TM_YDAY) { + int days = tm->tm_yday; + if (!(fields & FIELD_TM_WDAY)) { + tm->tm_wday = EPOCH_WDAY + + ((year - EPOCH_YEAR) % DAYSPERWEEK) * + (DAYSPERNYEAR % DAYSPERWEEK) + + leaps_thru_end_of(year - 1) - + leaps_thru_end_of(EPOCH_YEAR - 1) + + tm->tm_yday; + tm->tm_wday %= DAYSPERWEEK; + if (tm->tm_wday < 0) + tm->tm_wday += DAYSPERWEEK; + } + if (!(fields & FIELD_TM_MON)) { + tm->tm_mon = 0; + while (tm->tm_mon < MONSPERYEAR && days >= mon_lens[tm->tm_mon]) + days -= mon_lens[tm->tm_mon++]; + } + if (!(fields & FIELD_TM_MDAY)) + tm->tm_mday = days + 1; + } + } + + return ((char *)bp); +} + + +static int +_conv_num(const unsigned char **buf, int *dest, int llim, int ulim) +{ + int result = 0; + int rulim = ulim; + + if (**buf < '0' || **buf > '9') + return (0); + + /* we use rulim to break out of the loop when we run out of digits */ + do { + result *= 10; + result += *(*buf)++ - '0'; + rulim /= 10; + } while ((result * 10 <= ulim) && rulim && **buf >= '0' && **buf <= '9'); + + if (result < llim || result > ulim) + return (0); + + *dest = result; + return (1); +} + +#if 0 /* No local time support in tlibc */ +static int +epoch_to_tm(const unsigned char **buf, struct tm *tm) +{ + int saved_errno = errno; + int ret = 0; + time_t secs; + char *ep; + + errno = 0; + secs = strtoll(*buf, &ep, 10); + if (*buf == (unsigned char *)ep) + goto done; + if (secs < 0 || + secs == LLONG_MAX && errno == ERANGE) + goto done; + if (localtime_r(&secs, tm) == NULL) + goto done; + ret = 1; +done: + *buf = ep; + errno = saved_errno; + return (ret); +} +#endif + +static const u_char * +_find_string(const u_char *bp, int *tgt, const char * const *n1, + const char * const *n2, int c) +{ + int i; + unsigned int len; + + /* check full name - then abbreviated ones */ + for (; n1 != NULL; n1 = n2, n2 = NULL) { + for (i = 0; i < c; i++, n1++) { + len = strlen(*n1); + if (strncasecmp(*n1, (const char *)bp, len) == 0) { + *tgt = i; + return bp + len; + } + } + } + + /* Nothing matched */ + return NULL; +} + +static int +leaps_thru_end_of(const int y) +{ + return (y >= 0) ? (y / 4 - y / 100 + y / 400) : + -(leaps_thru_end_of(-(y + 1)) + 1); +} diff --git a/sdk/tlibc/time/tzfile.h b/sdk/tlibc/time/tzfile.h index f2316855c..bae77fec8 100644 --- a/sdk/tlibc/time/tzfile.h +++ b/sdk/tlibc/time/tzfile.h @@ -17,6 +17,38 @@ ** Thank you! */ +/* +** In the current implementation, "tzset()" refuses to deal with files that +** exceed any of the limits below. +*/ + +#ifndef TZ_MAX_TIMES +#define TZ_MAX_TIMES 1200 +#endif /* !defined TZ_MAX_TIMES */ + +#ifndef TZ_MAX_TYPES +#ifndef NOSOLAR +#define TZ_MAX_TYPES 256 /* Limited by what (unsigned char)'s can hold */ +#endif /* !defined NOSOLAR */ +#ifdef NOSOLAR +/* +** Must be at least 14 for Europe/Riga as of Jan 12 1995, +** as noted by Earl Chew. +*/ +#define TZ_MAX_TYPES 20 /* Maximum number of local time types */ +#endif /* !defined NOSOLAR */ +#endif /* !defined TZ_MAX_TYPES */ + +#ifndef TZ_MAX_CHARS +#define TZ_MAX_CHARS 50 /* Maximum number of abbreviation characters */ + /* (limited by what unsigned chars can hold) */ +#endif /* !defined TZ_MAX_CHARS */ + +#ifndef TZ_MAX_LEAPS +#define TZ_MAX_LEAPS 50 /* Maximum number of leap second corrections */ +#endif /* !defined TZ_MAX_LEAPS */ + + #define SECSPERMIN 60 #define MINSPERHOUR 60 #define HOURSPERDAY 24 diff --git a/sdk/tlibcrypto/Makefile b/sdk/tlibcrypto/Makefile index 06b49b0f6..76f6e2198 100644 --- a/sdk/tlibcrypto/Makefile +++ b/sdk/tlibcrypto/Makefile @@ -38,7 +38,7 @@ CPPFLAGS := -I$(COMMON_DIR)/inc/internal \ CXXFLAGS += $(ENCLAVE_CXXFLAGS) -fno-exceptions -fno-rtti -Werror -SGX_COMMON_CFLAGS += -DIPPCP_PREVIEW_XMSS +SGX_COMMON_CFLAGS += -DIPPCP_PREVIEW_ALL SHARED_OBJ = tcrypto_version.o sgx_common_init_ipp.o @@ -51,11 +51,11 @@ else endif #($(ARCH), x86_64) ifeq ($(MITIGATION-CVE-2020-0551), LOAD) -OPENSSL_LIBRARY_PATH := $(OPENSSL_PACKAGE)/lib64/cve_2020_0551_load + OPENSSL_LIBRARY_PATH := $(OPENSSL_PACKAGE)/lib64/cve_2020_0551_load else ifeq ($(MITIGATION-CVE-2020-0551), CF) -OPENSSL_LIBRARY_PATH := $(OPENSSL_PACKAGE)/lib64/cve_2020_0551_cf + OPENSSL_LIBRARY_PATH := $(OPENSSL_PACKAGE)/lib64/cve_2020_0551_cf else -OPENSSL_LIBRARY_PATH := $(OPENSSL_PACKAGE)/lib64 + OPENSSL_LIBRARY_PATH := $(OPENSSL_PACKAGE)/lib64 endif ifdef DEBUG diff --git a/sdk/tlibcrypto/ipp/ipp_disp/intel64/ippsLMSBufferGetSize.c b/sdk/tlibcrypto/ipp/ipp_disp/intel64/ippsLMSBufferGetSize.c new file mode 100644 index 000000000..8c84249bb --- /dev/null +++ b/sdk/tlibcrypto/ipp/ipp_disp/intel64/ippsLMSBufferGetSize.c @@ -0,0 +1,82 @@ +/* + * Copyright (C) 2011-2021 Intel Corporation. All rights reserved. + * + * 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. + * * Neither the name of Intel Corporation nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER 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 "ippcp.h" + +#ifndef IPP_CALL +#define IPP_CALL IPP_STDCALL +#endif +#define IPPFUN(type,name,arg) extern type IPP_CALL name arg + +#ifndef NULL +#ifdef __cplusplus +#define NULL 0 +#else +#define NULL ((void *)0) +#endif +#endif + +#if defined (_M_AMD64) || defined (__x86_64__) + +#define AVX3I_FEATURES ( ippCPUID_SHA|ippCPUID_AVX512VBMI|ippCPUID_AVX512VBMI2|ippCPUID_AVX512IFMA|ippCPUID_AVX512GFNI|ippCPUID_AVX512VAES|ippCPUID_AVX512VCLMUL ) +#define AVX3X_FEATURES ( ippCPUID_AVX512F|ippCPUID_AVX512CD|ippCPUID_AVX512VL|ippCPUID_AVX512BW|ippCPUID_AVX512DQ ) +#define AVX3M_FEATURES ( ippCPUID_AVX512F|ippCPUID_AVX512CD|ippCPUID_AVX512PF|ippCPUID_AVX512ER ) + +#ifdef __cplusplus +extern "C" { +#endif + +IPPAPI(IppStatus, k1_ippsLMSBufferGetSize, (Ipp32s* pSize, Ipp32s maxMessageLength, const IppsLMSAlgoType lmsType)) +IPPAPI(IppStatus, l9_ippsLMSBufferGetSize, (Ipp32s* pSize, Ipp32s maxMessageLength, const IppsLMSAlgoType lmsType)) +IPPAPI(IppStatus, y8_ippsLMSBufferGetSize, (Ipp32s* pSize, Ipp32s maxMessageLength, const IppsLMSAlgoType lmsType)) + +IPPFUN(IppStatus, sgx_disp_ippsLMSBufferGetSize, (Ipp32s* pSize, Ipp32s maxMessageLength, const IppsLMSAlgoType lmsType)) +{ + Ipp64u _features; + _features = ippcpGetEnabledCpuFeatures(); + + if( AVX3I_FEATURES == ( _features & AVX3I_FEATURES )) { + return k1_ippsLMSBufferGetSize( pSize, maxMessageLength, lmsType ); + } else + if( ippCPUID_AVX2 == ( _features & ippCPUID_AVX2 )) { + return l9_ippsLMSBufferGetSize( pSize, maxMessageLength, lmsType ); + } else + if( ippCPUID_SSE42 == ( _features & ippCPUID_SSE42 )) { + return y8_ippsLMSBufferGetSize( pSize, maxMessageLength, lmsType ); + } else + return ippStsCpuNotSupportedErr; +} + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/sdk/tlibcrypto/ipp/ipp_disp/intel64/ippsLMSPublicKeyStateGetSize.c b/sdk/tlibcrypto/ipp/ipp_disp/intel64/ippsLMSPublicKeyStateGetSize.c new file mode 100644 index 000000000..2a9ec4210 --- /dev/null +++ b/sdk/tlibcrypto/ipp/ipp_disp/intel64/ippsLMSPublicKeyStateGetSize.c @@ -0,0 +1,82 @@ +/* + * Copyright (C) 2011-2021 Intel Corporation. All rights reserved. + * + * 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. + * * Neither the name of Intel Corporation nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER 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 "ippcp.h" + +#ifndef IPP_CALL +#define IPP_CALL IPP_STDCALL +#endif +#define IPPFUN(type,name,arg) extern type IPP_CALL name arg + +#ifndef NULL +#ifdef __cplusplus +#define NULL 0 +#else +#define NULL ((void *)0) +#endif +#endif + +#if defined (_M_AMD64) || defined (__x86_64__) + +#define AVX3I_FEATURES ( ippCPUID_SHA|ippCPUID_AVX512VBMI|ippCPUID_AVX512VBMI2|ippCPUID_AVX512IFMA|ippCPUID_AVX512GFNI|ippCPUID_AVX512VAES|ippCPUID_AVX512VCLMUL ) +#define AVX3X_FEATURES ( ippCPUID_AVX512F|ippCPUID_AVX512CD|ippCPUID_AVX512VL|ippCPUID_AVX512BW|ippCPUID_AVX512DQ ) +#define AVX3M_FEATURES ( ippCPUID_AVX512F|ippCPUID_AVX512CD|ippCPUID_AVX512PF|ippCPUID_AVX512ER ) + +#ifdef __cplusplus +extern "C" { +#endif + +IPPAPI(IppStatus, k1_ippsLMSPublicKeyStateGetSize, (Ipp32s* pSize, const IppsLMSAlgoType lmsType)) +IPPAPI(IppStatus, l9_ippsLMSPublicKeyStateGetSize, (Ipp32s* pSize, const IppsLMSAlgoType lmsType)) +IPPAPI(IppStatus, y8_ippsLMSPublicKeyStateGetSize, (Ipp32s* pSize, const IppsLMSAlgoType lmsType)) + +IPPFUN(IppStatus, sgx_disp_ippsLMSPublicKeyStateGetSize, (Ipp32s* pSize, const IppsLMSAlgoType lmsType)) +{ + Ipp64u _features; + _features = ippcpGetEnabledCpuFeatures(); + + if( AVX3I_FEATURES == ( _features & AVX3I_FEATURES )) { + return k1_ippsLMSPublicKeyStateGetSize( pSize, lmsType ); + } else + if( ippCPUID_AVX2 == ( _features & ippCPUID_AVX2 )) { + return l9_ippsLMSPublicKeyStateGetSize( pSize, lmsType ); + } else + if( ippCPUID_SSE42 == ( _features & ippCPUID_SSE42 )) { + return y8_ippsLMSPublicKeyStateGetSize( pSize, lmsType ); + } else + return ippStsCpuNotSupportedErr; +} + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/sdk/tlibcrypto/ipp/ipp_disp/intel64/ippsLMSSetPublicKeyState.c b/sdk/tlibcrypto/ipp/ipp_disp/intel64/ippsLMSSetPublicKeyState.c new file mode 100644 index 000000000..6faabb258 --- /dev/null +++ b/sdk/tlibcrypto/ipp/ipp_disp/intel64/ippsLMSSetPublicKeyState.c @@ -0,0 +1,82 @@ +/* + * Copyright (C) 2011-2021 Intel Corporation. All rights reserved. + * + * 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. + * * Neither the name of Intel Corporation nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER 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 "ippcp.h" + +#ifndef IPP_CALL +#define IPP_CALL IPP_STDCALL +#endif +#define IPPFUN(type,name,arg) extern type IPP_CALL name arg + +#ifndef NULL +#ifdef __cplusplus +#define NULL 0 +#else +#define NULL ((void *)0) +#endif +#endif + +#if defined (_M_AMD64) || defined (__x86_64__) + +#define AVX3I_FEATURES ( ippCPUID_SHA|ippCPUID_AVX512VBMI|ippCPUID_AVX512VBMI2|ippCPUID_AVX512IFMA|ippCPUID_AVX512GFNI|ippCPUID_AVX512VAES|ippCPUID_AVX512VCLMUL ) +#define AVX3X_FEATURES ( ippCPUID_AVX512F|ippCPUID_AVX512CD|ippCPUID_AVX512VL|ippCPUID_AVX512BW|ippCPUID_AVX512DQ ) +#define AVX3M_FEATURES ( ippCPUID_AVX512F|ippCPUID_AVX512CD|ippCPUID_AVX512PF|ippCPUID_AVX512ER ) + +#ifdef __cplusplus +extern "C" { +#endif + +IPPAPI(IppStatus, k1_ippsLMSSetPublicKeyState, (const IppsLMSAlgoType lmsType, const Ipp8u* pI, const Ipp8u* pK, IppsLMSPublicKeyState* pState)) +IPPAPI(IppStatus, l9_ippsLMSSetPublicKeyState, (const IppsLMSAlgoType lmsType, const Ipp8u* pI, const Ipp8u* pK, IppsLMSPublicKeyState* pState)) +IPPAPI(IppStatus, y8_ippsLMSSetPublicKeyState, (const IppsLMSAlgoType lmsType, const Ipp8u* pI, const Ipp8u* pK, IppsLMSPublicKeyState* pState)) + +IPPFUN(IppStatus, sgx_disp_ippsLMSSetPublicKeyState, (const IppsLMSAlgoType lmsType, const Ipp8u* pI, const Ipp8u* pK, IppsLMSPublicKeyState* pState)) +{ + Ipp64u _features; + _features = ippcpGetEnabledCpuFeatures(); + + if( AVX3I_FEATURES == ( _features & AVX3I_FEATURES )) { + return k1_ippsLMSSetPublicKeyState( lmsType, pI, pK, pState ); + } else + if( ippCPUID_AVX2 == ( _features & ippCPUID_AVX2 )) { + return l9_ippsLMSSetPublicKeyState( lmsType, pI, pK, pState ); + } else + if( ippCPUID_SSE42 == ( _features & ippCPUID_SSE42 )) { + return y8_ippsLMSSetPublicKeyState( lmsType, pI, pK, pState ); + } else + return ippStsCpuNotSupportedErr; +} + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/sdk/tlibcrypto/ipp/ipp_disp/intel64/ippsLMSSetSignatureState.c b/sdk/tlibcrypto/ipp/ipp_disp/intel64/ippsLMSSetSignatureState.c new file mode 100644 index 000000000..f2cdca76f --- /dev/null +++ b/sdk/tlibcrypto/ipp/ipp_disp/intel64/ippsLMSSetSignatureState.c @@ -0,0 +1,82 @@ +/* + * Copyright (C) 2011-2021 Intel Corporation. All rights reserved. + * + * 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. + * * Neither the name of Intel Corporation nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER 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 "ippcp.h" + +#ifndef IPP_CALL +#define IPP_CALL IPP_STDCALL +#endif +#define IPPFUN(type,name,arg) extern type IPP_CALL name arg + +#ifndef NULL +#ifdef __cplusplus +#define NULL 0 +#else +#define NULL ((void *)0) +#endif +#endif + +#if defined (_M_AMD64) || defined (__x86_64__) + +#define AVX3I_FEATURES ( ippCPUID_SHA|ippCPUID_AVX512VBMI|ippCPUID_AVX512VBMI2|ippCPUID_AVX512IFMA|ippCPUID_AVX512GFNI|ippCPUID_AVX512VAES|ippCPUID_AVX512VCLMUL ) +#define AVX3X_FEATURES ( ippCPUID_AVX512F|ippCPUID_AVX512CD|ippCPUID_AVX512VL|ippCPUID_AVX512BW|ippCPUID_AVX512DQ ) +#define AVX3M_FEATURES ( ippCPUID_AVX512F|ippCPUID_AVX512CD|ippCPUID_AVX512PF|ippCPUID_AVX512ER ) + +#ifdef __cplusplus +extern "C" { +#endif + +IPPAPI(IppStatus, k1_ippsLMSSetSignatureState, (const IppsLMSAlgoType lmsType, Ipp32u q, const Ipp8u* pC, const Ipp8u* pY, const Ipp8u* pAuthPath, IppsLMSSignatureState* pState)) +IPPAPI(IppStatus, l9_ippsLMSSetSignatureState, (const IppsLMSAlgoType lmsType, Ipp32u q, const Ipp8u* pC, const Ipp8u* pY, const Ipp8u* pAuthPath, IppsLMSSignatureState* pState)) +IPPAPI(IppStatus, y8_ippsLMSSetSignatureState, (const IppsLMSAlgoType lmsType, Ipp32u q, const Ipp8u* pC, const Ipp8u* pY, const Ipp8u* pAuthPath, IppsLMSSignatureState* pState)) + +IPPFUN(IppStatus, sgx_disp_ippsLMSSetSignatureState, (const IppsLMSAlgoType lmsType, Ipp32u q, const Ipp8u* pC, const Ipp8u* pY, const Ipp8u* pAuthPath, IppsLMSSignatureState* pState)) +{ + Ipp64u _features; + _features = ippcpGetEnabledCpuFeatures(); + + if( AVX3I_FEATURES == ( _features & AVX3I_FEATURES )) { + return k1_ippsLMSSetSignatureState( lmsType, q, pC, pY, pAuthPath, pState ); + } else + if( ippCPUID_AVX2 == ( _features & ippCPUID_AVX2 )) { + return l9_ippsLMSSetSignatureState( lmsType, q, pC, pY, pAuthPath, pState ); + } else + if( ippCPUID_SSE42 == ( _features & ippCPUID_SSE42 )) { + return y8_ippsLMSSetSignatureState( lmsType, q, pC, pY, pAuthPath, pState ); + } else + return ippStsCpuNotSupportedErr; +} + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/sdk/tlibcrypto/ipp/ipp_disp/intel64/ippsLMSSignatureStateGetSize.c b/sdk/tlibcrypto/ipp/ipp_disp/intel64/ippsLMSSignatureStateGetSize.c new file mode 100644 index 000000000..780753d6c --- /dev/null +++ b/sdk/tlibcrypto/ipp/ipp_disp/intel64/ippsLMSSignatureStateGetSize.c @@ -0,0 +1,82 @@ +/* + * Copyright (C) 2011-2021 Intel Corporation. All rights reserved. + * + * 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. + * * Neither the name of Intel Corporation nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER 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 "ippcp.h" + +#ifndef IPP_CALL +#define IPP_CALL IPP_STDCALL +#endif +#define IPPFUN(type,name,arg) extern type IPP_CALL name arg + +#ifndef NULL +#ifdef __cplusplus +#define NULL 0 +#else +#define NULL ((void *)0) +#endif +#endif + +#if defined (_M_AMD64) || defined (__x86_64__) + +#define AVX3I_FEATURES ( ippCPUID_SHA|ippCPUID_AVX512VBMI|ippCPUID_AVX512VBMI2|ippCPUID_AVX512IFMA|ippCPUID_AVX512GFNI|ippCPUID_AVX512VAES|ippCPUID_AVX512VCLMUL ) +#define AVX3X_FEATURES ( ippCPUID_AVX512F|ippCPUID_AVX512CD|ippCPUID_AVX512VL|ippCPUID_AVX512BW|ippCPUID_AVX512DQ ) +#define AVX3M_FEATURES ( ippCPUID_AVX512F|ippCPUID_AVX512CD|ippCPUID_AVX512PF|ippCPUID_AVX512ER ) + +#ifdef __cplusplus +extern "C" { +#endif + +IPPAPI(IppStatus, k1_ippsLMSSignatureStateGetSize, (Ipp32s* pSize, const IppsLMSAlgoType lmsType)) +IPPAPI(IppStatus, l9_ippsLMSSignatureStateGetSize, (Ipp32s* pSize, const IppsLMSAlgoType lmsType)) +IPPAPI(IppStatus, y8_ippsLMSSignatureStateGetSize, (Ipp32s* pSize, const IppsLMSAlgoType lmsType)) + +IPPFUN(IppStatus, sgx_disp_ippsLMSSignatureStateGetSize, (Ipp32s* pSize, const IppsLMSAlgoType lmsType)) +{ + Ipp64u _features; + _features = ippcpGetEnabledCpuFeatures(); + + if( AVX3I_FEATURES == ( _features & AVX3I_FEATURES )) { + return k1_ippsLMSSignatureStateGetSize( pSize, lmsType ); + } else + if( ippCPUID_AVX2 == ( _features & ippCPUID_AVX2 )) { + return l9_ippsLMSSignatureStateGetSize( pSize, lmsType ); + } else + if( ippCPUID_SSE42 == ( _features & ippCPUID_SSE42 )) { + return y8_ippsLMSSignatureStateGetSize( pSize, lmsType ); + } else + return ippStsCpuNotSupportedErr; +} + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/sdk/tlibcrypto/ipp/ipp_disp/intel64/ippsLMSVerify.c b/sdk/tlibcrypto/ipp/ipp_disp/intel64/ippsLMSVerify.c new file mode 100644 index 000000000..56c1bfa3f --- /dev/null +++ b/sdk/tlibcrypto/ipp/ipp_disp/intel64/ippsLMSVerify.c @@ -0,0 +1,82 @@ +/* + * Copyright (C) 2011-2021 Intel Corporation. All rights reserved. + * + * 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. + * * Neither the name of Intel Corporation nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER 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 "ippcp.h" + +#ifndef IPP_CALL +#define IPP_CALL IPP_STDCALL +#endif +#define IPPFUN(type,name,arg) extern type IPP_CALL name arg + +#ifndef NULL +#ifdef __cplusplus +#define NULL 0 +#else +#define NULL ((void *)0) +#endif +#endif + +#if defined (_M_AMD64) || defined (__x86_64__) + +#define AVX3I_FEATURES ( ippCPUID_SHA|ippCPUID_AVX512VBMI|ippCPUID_AVX512VBMI2|ippCPUID_AVX512IFMA|ippCPUID_AVX512GFNI|ippCPUID_AVX512VAES|ippCPUID_AVX512VCLMUL ) +#define AVX3X_FEATURES ( ippCPUID_AVX512F|ippCPUID_AVX512CD|ippCPUID_AVX512VL|ippCPUID_AVX512BW|ippCPUID_AVX512DQ ) +#define AVX3M_FEATURES ( ippCPUID_AVX512F|ippCPUID_AVX512CD|ippCPUID_AVX512PF|ippCPUID_AVX512ER ) + +#ifdef __cplusplus +extern "C" { +#endif + +IPPAPI(IppStatus, k1_ippsLMSVerify, (const Ipp8u* pMsg, const Ipp32s msgLen, const IppsLMSSignatureState* pSign, int* pIsSignValid, const IppsLMSPublicKeyState* pKey, Ipp8u* pBuffer)) +IPPAPI(IppStatus, l9_ippsLMSVerify, (const Ipp8u* pMsg, const Ipp32s msgLen, const IppsLMSSignatureState* pSign, int* pIsSignValid, const IppsLMSPublicKeyState* pKey, Ipp8u* pBuffer)) +IPPAPI(IppStatus, y8_ippsLMSVerify, (const Ipp8u* pMsg, const Ipp32s msgLen, const IppsLMSSignatureState* pSign, int* pIsSignValid, const IppsLMSPublicKeyState* pKey, Ipp8u* pBuffer)) + +IPPFUN(IppStatus, sgx_disp_ippsLMSVerify, (const Ipp8u* pMsg, const Ipp32s msgLen, const IppsLMSSignatureState* pSign, int* pIsSignValid, const IppsLMSPublicKeyState* pKey, Ipp8u* pBuffer)) +{ + Ipp64u _features; + _features = ippcpGetEnabledCpuFeatures(); + + if( AVX3I_FEATURES == ( _features & AVX3I_FEATURES )) { + return k1_ippsLMSVerify( pMsg, msgLen, pSign, pIsSignValid, pKey, pBuffer ); + } else + if( ippCPUID_AVX2 == ( _features & ippCPUID_AVX2 )) { + return l9_ippsLMSVerify( pMsg, msgLen, pSign, pIsSignValid, pKey, pBuffer ); + } else + if( ippCPUID_SSE42 == ( _features & ippCPUID_SSE42 )) { + return y8_ippsLMSVerify( pMsg, msgLen, pSign, pIsSignValid, pKey, pBuffer ); + } else + return ippStsCpuNotSupportedErr; +} + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/sdk/tlibcrypto/ipp/sgx_aes_ctr.cpp b/sdk/tlibcrypto/ipp/sgx_aes_ctr.cpp index a6c0ddab5..f2a12aebf 100644 --- a/sdk/tlibcrypto/ipp/sgx_aes_ctr.cpp +++ b/sdk/tlibcrypto/ipp/sgx_aes_ctr.cpp @@ -29,10 +29,38 @@ * */ -#include "sgx_tcrypto.h" -#include "ippcp.h" +#include "ipp_wrapper.h" #include "stdlib.h" #include "string.h" +#include "sgx_fips_internal.h" + +static void fips_self_test_aes_ctr() +{ + static bool fips_selftest_aes_ctr_flag = false; + + if (g_global_data.fips_on != 0 && fips_selftest_aes_ctr_flag == false) + { + sgx_status_t ret = SGX_ERROR_UNEXPECTED; + fips_test_status test_result = IPPCP_ALGO_SELFTEST_OK; + int buf_size = 0; + uint8_t *p_buf = NULL; + do + { + FIPS_SELFTEST_FUNC_1(test_result, fips_selftest_ippsAESEncryptDecrypt_get_size, &buf_size); + p_buf = (uint8_t *)malloc(buf_size); + ALLOC_ERROR_BREAK(p_buf, ret); + + FIPS_SELFTEST_FUNC_1(test_result, fips_selftest_ippsAESEncryptCTR, p_buf); + FIPS_SELFTEST_FUNC_1(test_result, fips_selftest_ippsAESDecryptCTR, p_buf); + ret = SGX_SUCCESS; + fips_selftest_aes_ctr_flag = true; + } while (0); + SAFE_FREE(p_buf); + + ERROR_ABORT(ret); + } + return; +} /* AES-CTR 128-bit * Parameters: @@ -48,11 +76,11 @@ * uint8_t *p_dst - Pointer to the cipher text. Size of buffer should be >= src_len. */ sgx_status_t sgx_aes_ctr_encrypt(const sgx_aes_ctr_128bit_key_t *p_key, const uint8_t *p_src, - const uint32_t src_len, uint8_t *p_ctr, const uint32_t ctr_inc_bits, - uint8_t *p_dst) + const uint32_t src_len, uint8_t *p_ctr, const uint32_t ctr_inc_bits, + uint8_t *p_dst) { IppStatus error_code = ippStsNoErr; - IppsAESSpec* ptr_ctx = NULL; + IppsAESSpec *ptr_ctx = NULL; int ctx_size = 0; if ((p_key == NULL) || (p_src == NULL) || (p_ctr == NULL) || (p_dst == NULL)) @@ -60,20 +88,22 @@ sgx_status_t sgx_aes_ctr_encrypt(const sgx_aes_ctr_128bit_key_t *p_key, const ui return SGX_ERROR_INVALID_PARAMETER; } + fips_self_test_aes_ctr(); + // AES-CTR-128 encryption error_code = ippsAESGetSize(&ctx_size); if (error_code != ippStsNoErr) { return SGX_ERROR_UNEXPECTED; } - ptr_ctx = (IppsAESSpec*)malloc(ctx_size); + ptr_ctx = (IppsAESSpec *)malloc(ctx_size); if (ptr_ctx == NULL) { return SGX_ERROR_OUT_OF_MEMORY; } // Init - error_code = ippsAESInit((const Ipp8u*)p_key, SGX_AESCTR_KEY_SIZE, ptr_ctx, ctx_size); + error_code = ippsAESInit((const Ipp8u *)p_key, SGX_AESCTR_KEY_SIZE, ptr_ctx, ctx_size); if (error_code != ippStsNoErr) { // Clear temp State before free. @@ -81,10 +111,13 @@ sgx_status_t sgx_aes_ctr_encrypt(const sgx_aes_ctr_128bit_key_t *p_key, const ui free(ptr_ctx); switch (error_code) { - case ippStsMemAllocErr: return SGX_ERROR_OUT_OF_MEMORY; + case ippStsMemAllocErr: + return SGX_ERROR_OUT_OF_MEMORY; case ippStsNullPtrErr: - case ippStsLengthErr: return SGX_ERROR_INVALID_PARAMETER; - default: return SGX_ERROR_UNEXPECTED; + case ippStsLengthErr: + return SGX_ERROR_INVALID_PARAMETER; + default: + return SGX_ERROR_UNEXPECTED; } } error_code = ippsAESEncryptCTR(p_src, p_dst, src_len, ptr_ctx, p_ctr, ctr_inc_bits); @@ -97,8 +130,10 @@ sgx_status_t sgx_aes_ctr_encrypt(const sgx_aes_ctr_128bit_key_t *p_key, const ui { case ippStsCTRSizeErr: case ippStsNullPtrErr: - case ippStsLengthErr: return SGX_ERROR_INVALID_PARAMETER; - default: return SGX_ERROR_UNEXPECTED; + case ippStsLengthErr: + return SGX_ERROR_INVALID_PARAMETER; + default: + return SGX_ERROR_UNEXPECTED; } } // Clear temp State before free. @@ -108,11 +143,11 @@ sgx_status_t sgx_aes_ctr_encrypt(const sgx_aes_ctr_128bit_key_t *p_key, const ui } sgx_status_t sgx_aes_ctr_decrypt(const sgx_aes_ctr_128bit_key_t *p_key, const uint8_t *p_src, - const uint32_t src_len, uint8_t *p_ctr, const uint32_t ctr_inc_bits, - uint8_t *p_dst) + const uint32_t src_len, uint8_t *p_ctr, const uint32_t ctr_inc_bits, + uint8_t *p_dst) { IppStatus error_code = ippStsNoErr; - IppsAESSpec* ptr_ctx = NULL; + IppsAESSpec *ptr_ctx = NULL; int ctx_size = 0; if ((p_key == NULL) || (p_src == NULL) || (p_ctr == NULL) || (p_dst == NULL)) @@ -120,20 +155,22 @@ sgx_status_t sgx_aes_ctr_decrypt(const sgx_aes_ctr_128bit_key_t *p_key, const ui return SGX_ERROR_INVALID_PARAMETER; } + fips_self_test_aes_ctr(); + // AES-CTR-128 encryption error_code = ippsAESGetSize(&ctx_size); if (error_code != ippStsNoErr) { return SGX_ERROR_UNEXPECTED; } - ptr_ctx = (IppsAESSpec*)malloc(ctx_size); + ptr_ctx = (IppsAESSpec *)malloc(ctx_size); if (ptr_ctx == NULL) { return SGX_ERROR_OUT_OF_MEMORY; } // Init - error_code = ippsAESInit((const Ipp8u*)p_key, SGX_AESCTR_KEY_SIZE, ptr_ctx, ctx_size); + error_code = ippsAESInit((const Ipp8u *)p_key, SGX_AESCTR_KEY_SIZE, ptr_ctx, ctx_size); if (error_code != ippStsNoErr) { // Clear temp State before free. @@ -141,10 +178,13 @@ sgx_status_t sgx_aes_ctr_decrypt(const sgx_aes_ctr_128bit_key_t *p_key, const ui free(ptr_ctx); switch (error_code) { - case ippStsMemAllocErr: return SGX_ERROR_OUT_OF_MEMORY; + case ippStsMemAllocErr: + return SGX_ERROR_OUT_OF_MEMORY; case ippStsNullPtrErr: - case ippStsLengthErr: return SGX_ERROR_INVALID_PARAMETER; - default: return SGX_ERROR_UNEXPECTED; + case ippStsLengthErr: + return SGX_ERROR_INVALID_PARAMETER; + default: + return SGX_ERROR_UNEXPECTED; } } error_code = ippsAESDecryptCTR(p_src, p_dst, src_len, ptr_ctx, p_ctr, ctr_inc_bits); @@ -157,8 +197,10 @@ sgx_status_t sgx_aes_ctr_decrypt(const sgx_aes_ctr_128bit_key_t *p_key, const ui { case ippStsCTRSizeErr: case ippStsNullPtrErr: - case ippStsLengthErr: return SGX_ERROR_INVALID_PARAMETER; - default: return SGX_ERROR_UNEXPECTED; + case ippStsLengthErr: + return SGX_ERROR_INVALID_PARAMETER; + default: + return SGX_ERROR_UNEXPECTED; } } // Clear temp State before free. diff --git a/sdk/tlibcrypto/ipp/sgx_aes_gcm.cpp b/sdk/tlibcrypto/ipp/sgx_aes_gcm.cpp index b67c2cb55..caeb66db7 100644 --- a/sdk/tlibcrypto/ipp/sgx_aes_gcm.cpp +++ b/sdk/tlibcrypto/ipp/sgx_aes_gcm.cpp @@ -29,40 +29,68 @@ * */ - #include "sgx_tcrypto.h" #include "ippcp.h" #include "ipp_wrapper.h" #include "stdlib.h" #include "string.h" #include +#include "sgx_fips_internal.h" + +static void fips_self_test_aes_gcm() +{ + static bool fips_selftest_aes_gcm_flag = false; + if (g_global_data.fips_on != 0 && fips_selftest_aes_gcm_flag == false) + { + sgx_status_t ret = SGX_ERROR_UNEXPECTED; + fips_test_status test_result = IPPCP_ALGO_SELFTEST_OK; + int buf_size = 0; + uint8_t *p_buf = NULL; + do + { + FIPS_SELFTEST_FUNC_1(test_result, fips_selftest_ippsAES_GCM_get_size, &buf_size); + p_buf = (uint8_t *)malloc(buf_size); + ALLOC_ERROR_BREAK(p_buf, ret); + FIPS_SELFTEST_FUNC_1(test_result, fips_selftest_ippsAES_GCMEncrypt, p_buf); + FIPS_SELFTEST_FUNC_1(test_result, fips_selftest_ippsAES_GCMDecrypt, p_buf); + + ret = SGX_SUCCESS; + fips_selftest_aes_gcm_flag = true; + } while (0); + SAFE_FREE(p_buf); + ERROR_ABORT(ret); + } + return; +} static sgx_status_t aes_gcm_encrypt_internal(const uint8_t *p_key, uint32_t key_len, const uint8_t *p_src, uint32_t src_len, - uint8_t *p_dst, const uint8_t *p_iv, uint32_t iv_len, const uint8_t *p_aad, uint32_t aad_len, sgx_aes_gcm_128bit_tag_t *p_out_mac) + uint8_t *p_dst, const uint8_t *p_iv, uint32_t iv_len, const uint8_t *p_aad, + uint32_t aad_len, sgx_aes_gcm_128bit_tag_t *p_out_mac) { IppStatus error_code = ippStsNoErr; - IppsAES_GCMState* pState = NULL; + IppsAES_GCMState *pState = NULL; int ippStateSize = 0; const int noise_level = 1; - if ((p_key == NULL) || ((src_len > 0) && (p_dst == NULL)) || ((src_len > 0) && (p_src == NULL)) - || (p_out_mac == NULL) || (iv_len != SGX_AESGCM_IV_SIZE) || ((aad_len > 0) && (p_aad == NULL)) - || (p_iv == NULL) || ((p_src == NULL) && (p_aad == NULL))) + if ((p_key == NULL) || ((src_len > 0) && (p_dst == NULL)) || ((src_len > 0) && (p_src == NULL)) || (p_out_mac == NULL) + || (iv_len != SGX_AESGCM_IV_SIZE) || ((aad_len > 0) && (p_aad == NULL)) || (p_iv == NULL) || ((p_src == NULL) && (p_aad == NULL))) { return SGX_ERROR_INVALID_PARAMETER; } - if(key_len != SGX_AESGCM_KEY_SIZE && key_len != SGX_AESGCM_KEY256_SIZE) + if (key_len != SGX_AESGCM_KEY_SIZE && key_len != SGX_AESGCM_KEY256_SIZE) { return SGX_ERROR_INVALID_PARAMETER; } + fips_self_test_aes_gcm(); + error_code = ippsAES_GCMGetSize(&ippStateSize); if (error_code != ippStsNoErr) { return SGX_ERROR_UNEXPECTED; } - pState = (IppsAES_GCMState*)malloc(ippStateSize); + pState = (IppsAES_GCMState *)malloc(ippStateSize); if (pState == NULL) { return SGX_ERROR_OUT_OF_MEMORY; @@ -75,14 +103,17 @@ static sgx_status_t aes_gcm_encrypt_internal(const uint8_t *p_key, uint32_t key_ free(pState); switch (error_code) { - case ippStsMemAllocErr: return SGX_ERROR_OUT_OF_MEMORY; + case ippStsMemAllocErr: + return SGX_ERROR_OUT_OF_MEMORY; case ippStsNullPtrErr: - case ippStsLengthErr: return SGX_ERROR_INVALID_PARAMETER; - default: return SGX_ERROR_UNEXPECTED; + case ippStsLengthErr: + return SGX_ERROR_INVALID_PARAMETER; + default: + return SGX_ERROR_UNEXPECTED; } } error_code = ippsAES_GCMSetupNoise(noise_level, pState); - if(error_code != ippStsNoErr) + if (error_code != ippStsNoErr) { memset_s(pState, ippStateSize, 0, ippStateSize); free(pState); @@ -97,11 +128,14 @@ static sgx_status_t aes_gcm_encrypt_internal(const uint8_t *p_key, uint32_t key_ switch (error_code) { case ippStsNullPtrErr: - case ippStsLengthErr: return SGX_ERROR_INVALID_PARAMETER; - default: return SGX_ERROR_UNEXPECTED; + case ippStsLengthErr: + return SGX_ERROR_INVALID_PARAMETER; + default: + return SGX_ERROR_UNEXPECTED; } } - if (src_len > 0) { + if (src_len > 0) + { error_code = ippsAES_GCMEncrypt(p_src, p_dst, src_len, pState); if (error_code != ippStsNoErr) { @@ -110,8 +144,10 @@ static sgx_status_t aes_gcm_encrypt_internal(const uint8_t *p_key, uint32_t key_ free(pState); switch (error_code) { - case ippStsNullPtrErr: return SGX_ERROR_INVALID_PARAMETER; - default: return SGX_ERROR_UNEXPECTED; + case ippStsNullPtrErr: + return SGX_ERROR_INVALID_PARAMETER; + default: + return SGX_ERROR_UNEXPECTED; } } } @@ -125,8 +161,10 @@ static sgx_status_t aes_gcm_encrypt_internal(const uint8_t *p_key, uint32_t key_ switch (error_code) { case ippStsNullPtrErr: - case ippStsLengthErr: return SGX_ERROR_INVALID_PARAMETER; - default: return SGX_ERROR_UNEXPECTED; + case ippStsLengthErr: + return SGX_ERROR_INVALID_PARAMETER; + default: + return SGX_ERROR_UNEXPECTED; } } // Clear temp State before free. @@ -136,26 +174,28 @@ static sgx_status_t aes_gcm_encrypt_internal(const uint8_t *p_key, uint32_t key_ } static sgx_status_t aes_gcm_decrypt_internal(const uint8_t *p_key, uint32_t key_len, const uint8_t *p_src, uint32_t src_len, - uint8_t *p_dst, const uint8_t *p_iv, uint32_t iv_len, const uint8_t *p_aad, uint32_t aad_len, const sgx_aes_gcm_128bit_tag_t *p_in_mac) + uint8_t *p_dst, const uint8_t *p_iv, uint32_t iv_len, const uint8_t *p_aad, uint32_t aad_len, + const sgx_aes_gcm_128bit_tag_t *p_in_mac) { IppStatus error_code = ippStsNoErr; uint8_t l_tag[SGX_AESGCM_MAC_SIZE]; - IppsAES_GCMState* pState = NULL; + IppsAES_GCMState *pState = NULL; int ippStateSize = 0; const int noise_level = 1; - if ((p_key == NULL) || ((src_len > 0) && (p_dst == NULL)) || ((src_len > 0) && (p_src == NULL)) - || (p_in_mac == NULL) || (iv_len != SGX_AESGCM_IV_SIZE) || ((aad_len > 0) && (p_aad == NULL)) - || (p_iv == NULL) || ((p_src == NULL) && (p_aad == NULL))) + if ((p_key == NULL) || ((src_len > 0) && (p_dst == NULL)) || ((src_len > 0) && (p_src == NULL)) || (p_in_mac == NULL) + || (iv_len != SGX_AESGCM_IV_SIZE) || ((aad_len > 0) && (p_aad == NULL)) || (p_iv == NULL) || ((p_src == NULL) && (p_aad == NULL))) { return SGX_ERROR_INVALID_PARAMETER; } // Currently only accept 128-bits key and 256-bits key - if(key_len != SGX_AESGCM_KEY_SIZE && key_len != SGX_AESGCM_KEY256_SIZE) + if (key_len != SGX_AESGCM_KEY_SIZE && key_len != SGX_AESGCM_KEY256_SIZE) { return SGX_ERROR_INVALID_PARAMETER; } + fips_self_test_aes_gcm(); + // Autenthication Tag returned by Decrypt to be compared with Tag created during seal memset(&l_tag, 0, SGX_AESGCM_MAC_SIZE); error_code = ippsAES_GCMGetSize(&ippStateSize); @@ -163,7 +203,7 @@ static sgx_status_t aes_gcm_decrypt_internal(const uint8_t *p_key, uint32_t key_ { return SGX_ERROR_UNEXPECTED; } - pState = (IppsAES_GCMState*)malloc(ippStateSize); + pState = (IppsAES_GCMState *)malloc(ippStateSize); if (pState == NULL) { return SGX_ERROR_OUT_OF_MEMORY; @@ -176,14 +216,17 @@ static sgx_status_t aes_gcm_decrypt_internal(const uint8_t *p_key, uint32_t key_ free(pState); switch (error_code) { - case ippStsMemAllocErr: return SGX_ERROR_OUT_OF_MEMORY; + case ippStsMemAllocErr: + return SGX_ERROR_OUT_OF_MEMORY; case ippStsNullPtrErr: - case ippStsLengthErr: return SGX_ERROR_INVALID_PARAMETER; - default: return SGX_ERROR_UNEXPECTED; + case ippStsLengthErr: + return SGX_ERROR_INVALID_PARAMETER; + default: + return SGX_ERROR_UNEXPECTED; } } error_code = ippsAES_GCMSetupNoise(noise_level, pState); - if(error_code != ippStsNoErr) + if (error_code != ippStsNoErr) { memset_s(pState, ippStateSize, 0, ippStateSize); free(pState); @@ -198,11 +241,14 @@ static sgx_status_t aes_gcm_decrypt_internal(const uint8_t *p_key, uint32_t key_ switch (error_code) { case ippStsNullPtrErr: - case ippStsLengthErr: return SGX_ERROR_INVALID_PARAMETER; - default: return SGX_ERROR_UNEXPECTED; + case ippStsLengthErr: + return SGX_ERROR_INVALID_PARAMETER; + default: + return SGX_ERROR_UNEXPECTED; } } - if (src_len > 0) { + if (src_len > 0) + { error_code = ippsAES_GCMDecrypt(p_src, p_dst, src_len, pState); if (error_code != ippStsNoErr) { @@ -211,8 +257,10 @@ static sgx_status_t aes_gcm_decrypt_internal(const uint8_t *p_key, uint32_t key_ free(pState); switch (error_code) { - case ippStsNullPtrErr: return SGX_ERROR_INVALID_PARAMETER; - default: return SGX_ERROR_UNEXPECTED; + case ippStsNullPtrErr: + return SGX_ERROR_INVALID_PARAMETER; + default: + return SGX_ERROR_UNEXPECTED; } } } @@ -226,8 +274,10 @@ static sgx_status_t aes_gcm_decrypt_internal(const uint8_t *p_key, uint32_t key_ switch (error_code) { case ippStsNullPtrErr: - case ippStsLengthErr: return SGX_ERROR_INVALID_PARAMETER; - default: return SGX_ERROR_UNEXPECTED; + case ippStsLengthErr: + return SGX_ERROR_INVALID_PARAMETER; + default: + return SGX_ERROR_UNEXPECTED; } } // Clear temp State before free. @@ -247,25 +297,24 @@ static sgx_status_t aes_gcm_decrypt_internal(const uint8_t *p_key, uint32_t key_ } /* Rijndael AES-GCM -* Parameters: -* Return: sgx_status_t - SGX_SUCCESS or failure as defined sgx_error.h -* Inputs: sgx_aes_gcm_128bit_key_t *p_key - Pointer to key used in encryption/decryption operation -* uint8_t *p_src - Pointer to input stream to be encrypted/decrypted -* uint32_t src_len - Length of input stream to be encrypted/decrypted -* uint8_t *p_iv - Pointer to initialization vector to use -* uint32_t iv_len - Length of initialization vector -* uint8_t *p_aad - Pointer to input stream of additional authentication data -* uint32_t aad_len - Length of additional authentication data stream -* sgx_aes_gcm_128bit_tag_t *p_in_mac - Pointer to expected MAC in decryption process -* Output: uint8_t *p_dst - Pointer to cipher text. Size of buffer should be >= src_len. -* sgx_aes_gcm_128bit_tag_t *p_out_mac - Pointer to MAC generated from encryption process -* NOTE: Wrapper is responsible for confirming decryption tag matches encryption tag */ + * Parameters: + * Return: sgx_status_t - SGX_SUCCESS or failure as defined sgx_error.h + * Inputs: sgx_aes_gcm_128bit_key_t *p_key - Pointer to key used in encryption/decryption operation + * uint8_t *p_src - Pointer to input stream to be encrypted/decrypted + * uint32_t src_len - Length of input stream to be encrypted/decrypted + * uint8_t *p_iv - Pointer to initialization vector to use + * uint32_t iv_len - Length of initialization vector + * uint8_t *p_aad - Pointer to input stream of additional authentication data + * uint32_t aad_len - Length of additional authentication data stream + * sgx_aes_gcm_128bit_tag_t *p_in_mac - Pointer to expected MAC in decryption process + * Output: uint8_t *p_dst - Pointer to cipher text. Size of buffer should be >= src_len. + * sgx_aes_gcm_128bit_tag_t *p_out_mac - Pointer to MAC generated from encryption process + * NOTE: Wrapper is responsible for confirming decryption tag matches encryption tag */ sgx_status_t sgx_rijndael128GCM_encrypt(const sgx_aes_gcm_128bit_key_t *p_key, const uint8_t *p_src, uint32_t src_len, uint8_t *p_dst, const uint8_t *p_iv, uint32_t iv_len, const uint8_t *p_aad, uint32_t aad_len, sgx_aes_gcm_128bit_tag_t *p_out_mac) { return aes_gcm_encrypt_internal((const uint8_t *)p_key, sizeof(sgx_aes_ctr_128bit_key_t), p_src, src_len, p_dst, p_iv, iv_len, p_aad, aad_len, p_out_mac); - } sgx_status_t sgx_rijndael128GCM_decrypt(const sgx_aes_gcm_128bit_key_t *p_key, const uint8_t *p_src, @@ -276,17 +325,18 @@ sgx_status_t sgx_rijndael128GCM_decrypt(const sgx_aes_gcm_128bit_key_t *p_key, c } sgx_status_t sgx_aes_gcm_encrypt(const uint8_t *p_key, uint32_t key_len, const uint8_t *p_src, uint32_t src_len, - uint8_t *p_dst, uint8_t *p_iv, uint32_t iv_len, const uint8_t *p_aad, uint32_t aad_len, sgx_aes_gcm_128bit_tag_t *p_out_mac) + uint8_t *p_dst, uint8_t *p_iv, uint32_t iv_len, const uint8_t *p_aad, uint32_t aad_len, + sgx_aes_gcm_128bit_tag_t *p_out_mac) { - if(p_iv == NULL || iv_len != SGX_AESGCM_IV_SIZE) + if (p_iv == NULL || iv_len != SGX_AESGCM_IV_SIZE) return SGX_ERROR_INVALID_PARAMETER; uint8_t iv[SGX_AESGCM_IV_SIZE]; sgx_status_t ret = sgx_read_rand(iv, SGX_AESGCM_IV_SIZE); - if(ret != SGX_SUCCESS) + if (ret != SGX_SUCCESS) return ret; ret = aes_gcm_encrypt_internal(p_key, key_len, p_src, src_len, p_dst, iv, SGX_AESGCM_IV_SIZE, p_aad, aad_len, p_out_mac); - if(ret == SGX_SUCCESS) + if (ret == SGX_SUCCESS) memcpy(p_iv, iv, SGX_AESGCM_IV_SIZE); memset_s(iv, SGX_AESGCM_IV_SIZE, 0, SGX_AESGCM_IV_SIZE); @@ -294,31 +344,37 @@ sgx_status_t sgx_aes_gcm_encrypt(const uint8_t *p_key, uint32_t key_len, const u } sgx_status_t sgx_aes_gcm_decrypt(const uint8_t *p_key, uint32_t key_len, const uint8_t *p_src, uint32_t src_len, - uint8_t *p_dst, const uint8_t *p_iv, uint32_t iv_len, const uint8_t *p_aad, uint32_t aad_len, const sgx_aes_gcm_128bit_tag_t *p_in_mac) + uint8_t *p_dst, const uint8_t *p_iv, uint32_t iv_len, const uint8_t *p_aad, + uint32_t aad_len, const sgx_aes_gcm_128bit_tag_t *p_in_mac) { return aes_gcm_decrypt_internal(p_key, key_len, p_src, src_len, p_dst, p_iv, iv_len, p_aad, aad_len, p_in_mac); } sgx_status_t sgx_aes_gcm128_enc_init(const uint8_t *key, const uint8_t *iv, uint32_t iv_len, const uint8_t *aad, - uint32_t aad_len, sgx_aes_state_handle_t* aes_gcm_state) + uint32_t aad_len, sgx_aes_state_handle_t *aes_gcm_state) { if ((aad_len >= INT_MAX) || (key == NULL) || (iv_len != SGX_AESGCM_IV_SIZE) || ((aad_len > 0) && (aad == NULL)) || (iv == NULL) || (aes_gcm_state == NULL)) { return SGX_ERROR_INVALID_PARAMETER; } + + fips_self_test_aes_gcm(); + int state_size = 0; sgx_status_t ret = SGX_ERROR_UNEXPECTED; IppStatus status = ippStsNoErr; IppsAES_GCMState *p_state = NULL; const int noise_level = 1; - do { + do + { status = ippsAES_GCMGetSize(&state_size); ERROR_BREAK(status); p_state = reinterpret_cast(malloc(state_size)); - if (p_state == NULL) { + if (p_state == NULL) + { ret = SGX_ERROR_OUT_OF_MEMORY; break; } @@ -335,27 +391,31 @@ sgx_status_t sgx_aes_gcm128_enc_init(const uint8_t *key, const uint8_t *iv, uint ret = SGX_SUCCESS; } while (0); - if (ret != SGX_SUCCESS) { + if (ret != SGX_SUCCESS) + { CLEAR_FREE_MEM(p_state, state_size); } return ret; } - sgx_status_t sgx_aes_gcm128_enc_get_mac(uint8_t *mac, sgx_aes_state_handle_t aes_gcm_state) { if ((mac == NULL) || (aes_gcm_state == NULL)) { return SGX_ERROR_INVALID_PARAMETER; } + + fips_self_test_aes_gcm(); + sgx_status_t ret = SGX_ERROR_UNEXPECTED; - IppStatus status = ippsAES_GCMGetTag(mac, SGX_AESGCM_MAC_SIZE, (IppsAES_GCMState*)aes_gcm_state); - if (status == ippStsNoErr) { + IppStatus status = ippsAES_GCMGetTag(mac, SGX_AESGCM_MAC_SIZE, (IppsAES_GCMState *)aes_gcm_state); + if (status == ippStsNoErr) + { ret = SGX_SUCCESS; } - //In case of error, clear output MAC buffer. + // In case of error, clear output MAC buffer. // if (ret != SGX_SUCCESS) memset_s(mac, SGX_AESGCM_MAC_SIZE, 0, SGX_AESGCM_MAC_SIZE); @@ -363,15 +423,15 @@ sgx_status_t sgx_aes_gcm128_enc_get_mac(uint8_t *mac, sgx_aes_state_handle_t aes return ret; } - -//aes_gcm encryption fini function +// aes_gcm encryption fini function sgx_status_t sgx_aes_gcm_close(sgx_aes_state_handle_t aes_gcm_state) { if (aes_gcm_state == NULL) return SGX_ERROR_INVALID_PARAMETER; - + int state_size = 0; - if (ippsAES_GCMGetSize(&state_size) != ippStsNoErr) { + if (ippsAES_GCMGetSize(&state_size) != ippStsNoErr) + { free(aes_gcm_state); return SGX_SUCCESS; } @@ -379,15 +439,18 @@ sgx_status_t sgx_aes_gcm_close(sgx_aes_state_handle_t aes_gcm_state) return SGX_SUCCESS; } - sgx_status_t sgx_aes_gcm128_enc_update(uint8_t *p_src, uint32_t src_len, - uint8_t *p_dst, sgx_aes_state_handle_t aes_gcm_state) + uint8_t *p_dst, sgx_aes_state_handle_t aes_gcm_state) { if ((aes_gcm_state == NULL) || (p_src == NULL) || (p_dst == NULL) || (src_len >= INT_MAX) || (src_len == 0)) { return SGX_ERROR_INVALID_PARAMETER; } - if (ippsAES_GCMEncrypt(p_src, p_dst, src_len, (IppsAES_GCMState*)aes_gcm_state) != ippStsNoErr) { + + fips_self_test_aes_gcm(); + + if (ippsAES_GCMEncrypt(p_src, p_dst, src_len, (IppsAES_GCMState *)aes_gcm_state) != ippStsNoErr) + { return SGX_ERROR_UNEXPECTED; } return SGX_SUCCESS; diff --git a/sdk/tlibcrypto/ipp/sgx_cmac128.cpp b/sdk/tlibcrypto/ipp/sgx_cmac128.cpp index fb4886a2f..d28ed9f54 100644 --- a/sdk/tlibcrypto/ipp/sgx_cmac128.cpp +++ b/sdk/tlibcrypto/ipp/sgx_cmac128.cpp @@ -29,24 +29,47 @@ * */ - -#include "sgx_tcrypto.h" -#include "ippcp.h" +#include "ipp_wrapper.h" #include "stdlib.h" #include "string.h" +#include "sgx_fips_internal.h" +static void fips_self_test_cmac128() +{ + static bool fips_selftest_cmac128_flag = false; + + if (g_global_data.fips_on != 0 && fips_selftest_cmac128_flag == false) + { + sgx_status_t ret = SGX_ERROR_UNEXPECTED; + fips_test_status test_result = IPPCP_ALGO_SELFTEST_OK; + int buf_size = 0; + uint8_t *p_buf = NULL; + do + { + FIPS_SELFTEST_FUNC_1(test_result, fips_selftest_ippsAES_CMAC_get_size, &buf_size); + p_buf = (uint8_t *)malloc(buf_size); + ALLOC_ERROR_BREAK(p_buf, ret); + FIPS_SELFTEST_FUNC_1(test_result, fips_selftest_ippsAES_CMACUpdate, p_buf); + ret = SGX_SUCCESS; + fips_selftest_cmac128_flag = true; + } while (0); + SAFE_FREE(p_buf); + ERROR_ABORT(ret); + } + return; +} /* Message Authentication - Rijndael 128 CMAC -* Parameters: -* Return: sgx_status_t - SGX_SUCCESS or failure as defined sgx_error.h -* Inputs: sgx_cmac_128bit_key_t *p_key - Pointer to key used in encryption/decryption operation -* uint8_t *p_src - Pointer to input stream to be MACed -* uint32_t src_len - Length of input stream to be MACed -* Output: sgx_cmac_gcm_128bit_tag_t *p_mac - Pointer to resultant MAC */ + * Parameters: + * Return: sgx_status_t - SGX_SUCCESS or failure as defined sgx_error.h + * Inputs: sgx_cmac_128bit_key_t *p_key - Pointer to key used in encryption/decryption operation + * uint8_t *p_src - Pointer to input stream to be MACed + * uint32_t src_len - Length of input stream to be MACed + * Output: sgx_cmac_gcm_128bit_tag_t *p_mac - Pointer to resultant MAC */ sgx_status_t sgx_rijndael128_cmac_msg(const sgx_cmac_128bit_key_t *p_key, const uint8_t *p_src, uint32_t src_len, sgx_cmac_128bit_tag_t *p_mac) { - IppsAES_CMACState* pState = NULL; + IppsAES_CMACState *pState = NULL; int ippStateSize = 0; IppStatus error_code = ippStsNoErr; const int noise_level = 1; @@ -55,12 +78,15 @@ sgx_status_t sgx_rijndael128_cmac_msg(const sgx_cmac_128bit_key_t *p_key, const { return SGX_ERROR_INVALID_PARAMETER; } + + fips_self_test_cmac128(); + error_code = ippsAES_CMACGetSize(&ippStateSize); if (error_code != ippStsNoErr) { return SGX_ERROR_UNEXPECTED; } - pState = (IppsAES_CMACState*)malloc(ippStateSize); + pState = (IppsAES_CMACState *)malloc(ippStateSize); if (pState == NULL) { return SGX_ERROR_OUT_OF_MEMORY; @@ -73,14 +99,17 @@ sgx_status_t sgx_rijndael128_cmac_msg(const sgx_cmac_128bit_key_t *p_key, const free(pState); switch (error_code) { - case ippStsMemAllocErr: return SGX_ERROR_OUT_OF_MEMORY; + case ippStsMemAllocErr: + return SGX_ERROR_OUT_OF_MEMORY; case ippStsNullPtrErr: - case ippStsLengthErr: return SGX_ERROR_INVALID_PARAMETER; - default: return SGX_ERROR_UNEXPECTED; + case ippStsLengthErr: + return SGX_ERROR_INVALID_PARAMETER; + default: + return SGX_ERROR_UNEXPECTED; } } error_code = ippsAES_CMACSetupNoise(noise_level, pState); - if(error_code != ippStsNoErr) + if (error_code != ippStsNoErr) { memset_s(pState, ippStateSize, 0, ippStateSize); free(pState); @@ -95,8 +124,10 @@ sgx_status_t sgx_rijndael128_cmac_msg(const sgx_cmac_128bit_key_t *p_key, const switch (error_code) { case ippStsNullPtrErr: - case ippStsLengthErr: return SGX_ERROR_INVALID_PARAMETER; - default: return SGX_ERROR_UNEXPECTED; + case ippStsLengthErr: + return SGX_ERROR_INVALID_PARAMETER; + default: + return SGX_ERROR_UNEXPECTED; } } error_code = ippsAES_CMACFinal((Ipp8u *)p_mac, SGX_CMAC_MAC_SIZE, pState); @@ -108,8 +139,10 @@ sgx_status_t sgx_rijndael128_cmac_msg(const sgx_cmac_128bit_key_t *p_key, const switch (error_code) { case ippStsNullPtrErr: - case ippStsLengthErr: return SGX_ERROR_INVALID_PARAMETER; - default: return SGX_ERROR_UNEXPECTED; + case ippStsLengthErr: + return SGX_ERROR_INVALID_PARAMETER; + default: + return SGX_ERROR_UNEXPECTED; } } // Clear temp State before free. @@ -136,18 +169,20 @@ static void sgx_secure_free_cmac128_state(IppsAES_CMACState *pState) } /* Allocates and initializes CMAC state -* Parameters: -* Return: sgx_status_t - SGX_SUCCESS or failure as defined in sgx_error.h -* Inputs: sgx_cmac_128bit_key_t *p_key - Pointer to the key used in encryption/decryption operation -* Output: sgx_cmac_state_handle_t *p_cmac_handle - Pointer to the handle of the CMAC state */ -sgx_status_t sgx_cmac128_init(const sgx_cmac_128bit_key_t *p_key, sgx_cmac_state_handle_t* p_cmac_handle) + * Parameters: + * Return: sgx_status_t - SGX_SUCCESS or failure as defined in sgx_error.h + * Inputs: sgx_cmac_128bit_key_t *p_key - Pointer to the key used in encryption/decryption operation + * Output: sgx_cmac_state_handle_t *p_cmac_handle - Pointer to the handle of the CMAC state */ +sgx_status_t sgx_cmac128_init(const sgx_cmac_128bit_key_t *p_key, sgx_cmac_state_handle_t *p_cmac_handle) { if ((p_key == NULL) || (p_cmac_handle == NULL)) { return SGX_ERROR_INVALID_PARAMETER; } - IppsAES_CMACState* pState = NULL; + fips_self_test_cmac128(); + + IppsAES_CMACState *pState = NULL; int ippStateSize = 0; IppStatus error_code = ippStsNoErr; const int noise_level = 1; @@ -156,7 +191,7 @@ sgx_status_t sgx_cmac128_init(const sgx_cmac_128bit_key_t *p_key, sgx_cmac_state { return SGX_ERROR_UNEXPECTED; } - pState = (IppsAES_CMACState*)malloc(ippStateSize); + pState = (IppsAES_CMACState *)malloc(ippStateSize); if (pState == NULL) { return SGX_ERROR_OUT_OF_MEMORY; @@ -169,14 +204,17 @@ sgx_status_t sgx_cmac128_init(const sgx_cmac_128bit_key_t *p_key, sgx_cmac_state free(pState); switch (error_code) { - case ippStsMemAllocErr: return SGX_ERROR_OUT_OF_MEMORY; + case ippStsMemAllocErr: + return SGX_ERROR_OUT_OF_MEMORY; case ippStsNullPtrErr: - case ippStsLengthErr: return SGX_ERROR_INVALID_PARAMETER; - default: return SGX_ERROR_UNEXPECTED; + case ippStsLengthErr: + return SGX_ERROR_INVALID_PARAMETER; + default: + return SGX_ERROR_UNEXPECTED; } } error_code = ippsAES_CMACSetupNoise(noise_level, pState); - if(error_code != ippStsNoErr) + if (error_code != ippStsNoErr) { memset_s(pState, ippStateSize, 0, ippStateSize); free(pState); @@ -187,59 +225,70 @@ sgx_status_t sgx_cmac128_init(const sgx_cmac_128bit_key_t *p_key, sgx_cmac_state } /* Updates CMAC hash calculation based on the input message -* Parameters: -* Return: sgx_status_t - SGX_SUCCESS or failure as defined in sgx_error. -* Input: sgx_cmac_state_handle_t cmac_handle - Handle to the CMAC state -* uint8_t *p_src - Pointer to the input stream to be hashed -* uint32_t src_len - Length of the input stream to be hashed */ + * Parameters: + * Return: sgx_status_t - SGX_SUCCESS or failure as defined in sgx_error. + * Input: sgx_cmac_state_handle_t cmac_handle - Handle to the CMAC state + * uint8_t *p_src - Pointer to the input stream to be hashed + * uint32_t src_len - Length of the input stream to be hashed */ sgx_status_t sgx_cmac128_update(const uint8_t *p_src, uint32_t src_len, sgx_cmac_state_handle_t cmac_handle) { if ((p_src == NULL) || (cmac_handle == NULL)) { return SGX_ERROR_INVALID_PARAMETER; } + + fips_self_test_cmac128(); + IppStatus error_code = ippStsNoErr; - error_code = ippsAES_CMACUpdate(p_src, src_len, (IppsAES_CMACState*)cmac_handle); + error_code = ippsAES_CMACUpdate(p_src, src_len, (IppsAES_CMACState *)cmac_handle); switch (error_code) { - case ippStsNoErr: return SGX_SUCCESS; + case ippStsNoErr: + return SGX_SUCCESS; case ippStsNullPtrErr: - case ippStsLengthErr: return SGX_ERROR_INVALID_PARAMETER; - default: return SGX_ERROR_UNEXPECTED; + case ippStsLengthErr: + return SGX_ERROR_INVALID_PARAMETER; + default: + return SGX_ERROR_UNEXPECTED; } } /* Returns Hash calculation -* Parameters: -* Return: sgx_status_t - SGX_SUCCESS or failure as defined in sgx_error.h -* Input: sgx_cmac_state_handle_t cmac_handle - Handle to the CMAC state -* Output: sgx_cmac_128bit_tag_t *p_hash - Resultant hash from operation */ + * Parameters: + * Return: sgx_status_t - SGX_SUCCESS or failure as defined in sgx_error.h + * Input: sgx_cmac_state_handle_t cmac_handle - Handle to the CMAC state + * Output: sgx_cmac_128bit_tag_t *p_hash - Resultant hash from operation */ sgx_status_t sgx_cmac128_final(sgx_cmac_state_handle_t cmac_handle, sgx_cmac_128bit_tag_t *p_hash) { if ((cmac_handle == NULL) || (p_hash == NULL)) { return SGX_ERROR_INVALID_PARAMETER; } + + fips_self_test_cmac128(); + IppStatus error_code = ippStsNoErr; - error_code = ippsAES_CMACFinal((Ipp8u *)p_hash, SGX_CMAC_MAC_SIZE, (IppsAES_CMACState*)cmac_handle); + error_code = ippsAES_CMACFinal((Ipp8u *)p_hash, SGX_CMAC_MAC_SIZE, (IppsAES_CMACState *)cmac_handle); switch (error_code) { - case ippStsNoErr: return SGX_SUCCESS; + case ippStsNoErr: + return SGX_SUCCESS; case ippStsNullPtrErr: - case ippStsLengthErr: return SGX_ERROR_INVALID_PARAMETER; - default: return SGX_ERROR_UNEXPECTED; + case ippStsLengthErr: + return SGX_ERROR_INVALID_PARAMETER; + default: + return SGX_ERROR_UNEXPECTED; } } - /* Clean up the CMAC state -* Parameters: -* Return: sgx_status_t - SGX_SUCCESS or failure as defined in sgx_error.h -* Input: sgx_cmac_state_handle_t cmac_handle - Handle to the CMAC state */ + * Parameters: + * Return: sgx_status_t - SGX_SUCCESS or failure as defined in sgx_error.h + * Input: sgx_cmac_state_handle_t cmac_handle - Handle to the CMAC state */ sgx_status_t sgx_cmac128_close(sgx_cmac_state_handle_t cmac_handle) { if (cmac_handle == NULL) return SGX_ERROR_INVALID_PARAMETER; - sgx_secure_free_cmac128_state((IppsAES_CMACState*)cmac_handle); + sgx_secure_free_cmac128_state((IppsAES_CMACState *)cmac_handle); return SGX_SUCCESS; } diff --git a/sdk/tlibcrypto/ipp/sgx_ecc256.cpp b/sdk/tlibcrypto/ipp/sgx_ecc256.cpp index e72ef9436..b4f8203c1 100644 --- a/sdk/tlibcrypto/ipp/sgx_ecc256.cpp +++ b/sdk/tlibcrypto/ipp/sgx_ecc256.cpp @@ -30,9 +30,50 @@ */ #include "ipp_wrapper.h" +#include "sgx_fips_internal.h" #define ECC_FIELD_SIZE 256 +void fips_self_test_ecc() +{ + static bool fips_selftest_ecc_flag = false; + if (g_global_data.fips_on != 0 && fips_selftest_ecc_flag == false) + { + sgx_status_t ret = SGX_ERROR_UNEXPECTED; + fips_test_status test_result = IPPCP_ALGO_SELFTEST_OK; + int gfp_buf_size = 0; + uint8_t *p_gfp_buf = NULL; + int ec_buf_size = 0; + uint8_t *p_ec_buf = NULL; + int data_buf_size = 0; + uint8_t *p_data_buf = NULL; + do + { + FIPS_SELFTEST_FUNC_1(test_result, fips_selftest_ippsGFpECSignVerifyDSA_get_size_GFp_buff, &gfp_buf_size); + p_gfp_buf = (uint8_t *)malloc(gfp_buf_size); + ALLOC_ERROR_BREAK(p_gfp_buf, ret); + FIPS_SELFTEST_FUNC_2(test_result, fips_selftest_ippsGFpECSignVerifyDSA_get_size_GFpEC_buff, &ec_buf_size, p_gfp_buf); + p_ec_buf = (uint8_t *)malloc(ec_buf_size); + ALLOC_ERROR_BREAK(p_ec_buf, ret); + FIPS_SELFTEST_FUNC_3(test_result, fips_selftest_ippsGFpECSignVerifyDSA_get_size_data_buff, &data_buf_size, p_gfp_buf, p_ec_buf); + p_data_buf = (uint8_t *)malloc(data_buf_size); + ALLOC_ERROR_BREAK(p_data_buf, ret); + FIPS_SELFTEST_FUNC_3(test_result, fips_selftest_ippsGFpECSignDSA, p_gfp_buf, p_ec_buf, p_data_buf); + FIPS_SELFTEST_FUNC_3(test_result, fips_selftest_ippsGFpECVerifyDSA, p_gfp_buf, p_ec_buf, p_data_buf); + FIPS_SELFTEST_FUNC_3(test_result, fips_selftest_ippsGFpECPrivateKey, p_gfp_buf, p_ec_buf, p_data_buf); + FIPS_SELFTEST_FUNC_3(test_result, fips_selftest_ippsGFpECPublicKey, p_gfp_buf, p_ec_buf, p_data_buf); + FIPS_SELFTEST_FUNC_3(test_result, fips_selftest_ippsGFpECSharedSecretDH, p_gfp_buf, p_ec_buf, p_data_buf); + ret = SGX_SUCCESS; + fips_selftest_ecc_flag = true; + } while (0); + SAFE_FREE(p_gfp_buf); + SAFE_FREE(p_ec_buf); + SAFE_FREE(p_data_buf); + ERROR_ABORT(ret); + } + return; +} + /* * Elliptic Curve Crytpography - Based on GF(p), 256 bits */ @@ -44,6 +85,9 @@ sgx_status_t sgx_ecc256_open_context(sgx_ecc_state_handle_t *p_ecc_handle) { if (p_ecc_handle == NULL) return SGX_ERROR_INVALID_PARAMETER; + + fips_self_test_ecc(); + IppStatus ipp_ret = ippStsErr; ipp_ec_state_handles_t *ipp_state_handle = NULL; IppsGFpState *gfp_ctx = NULL; @@ -159,6 +203,9 @@ sgx_status_t sgx_ecc256_create_key_pair(sgx_ec256_private_t *p_private, { return SGX_ERROR_INVALID_PARAMETER; } + + fips_self_test_ecc(); + IppsBigNumState *dh_priv_bn = NULL; IppStatus ipp_ret = ippStsErr; IppsBigNumState *pub_gx = NULL; @@ -273,6 +320,9 @@ sgx_status_t sgx_ecc256_check_point(const sgx_ec256_public_t *p_point, { return SGX_ERROR_INVALID_PARAMETER; } + + fips_self_test_ecc(); + ipp_ec_state_handles_t *p_ec_handle = (ipp_ec_state_handles_t *)ecc_handle; IppsGFpECPoint *point2check = NULL; IppStatus ipp_ret = ippStsErr; @@ -348,6 +398,9 @@ sgx_status_t sgx_ecc256_compute_shared_dhkey(const sgx_ec256_private_t *p_privat { return SGX_ERROR_INVALID_PARAMETER; } + + fips_self_test_ecc(); + IppsBigNumState *bn_dh_priv_b = NULL; IppsBigNumState *bn_dh_share = NULL; IppsBigNumState *pub_a_gx = NULL; @@ -454,6 +507,9 @@ sgx_status_t sgx_ecc256_calculate_pub_from_priv(const sgx_ec256_private_t *p_att { return SGX_ERROR_INVALID_PARAMETER; } + + fips_self_test_ecc(); + IppStatus ipp_ret = ippStsErr; IppsGFpState *gfp_ctx = NULL; IppsGFpECState *ec_state = NULL; @@ -501,7 +557,7 @@ sgx_status_t sgx_ecc256_calculate_pub_from_priv(const sgx_ec256_private_t *p_att { ipp_ret = ippStsNoMemErr; break; - } + } ipp_ret = ippsGFpECPointInit(NULL, NULL, public_key, ec_state); ERROR_BREAK(ipp_ret); diff --git a/sdk/tlibcrypto/ipp/sgx_ecc256_ecdsa.cpp b/sdk/tlibcrypto/ipp/sgx_ecc256_ecdsa.cpp index 968cca9d8..d082b43f0 100644 --- a/sdk/tlibcrypto/ipp/sgx_ecc256_ecdsa.cpp +++ b/sdk/tlibcrypto/ipp/sgx_ecc256_ecdsa.cpp @@ -30,6 +30,7 @@ */ #include "ipp_wrapper.h" +#include "sgx_fips_internal.h" const uint32_t sgx_nistp256_r[] = { 0xFC632551, 0xF3B9CAC2, 0xA7179E84, 0xBCE6FAAD, 0xFFFFFFFF, 0xFFFFFFFF, @@ -53,6 +54,8 @@ sgx_status_t sgx_ecdsa_sign(const uint8_t *p_data, { return SGX_ERROR_INVALID_PARAMETER; } + fips_self_test_hash256(); + fips_self_test_ecc(); IppStatus ipp_ret = ippStsErr; ipp_ec_state_handles_t *p_ec_handle = (ipp_ec_state_handles_t *)ecc_handle; @@ -205,6 +208,8 @@ sgx_status_t sgx_ecdsa_verify(const uint8_t *p_data, { return SGX_ERROR_INVALID_PARAMETER; } + fips_self_test_hash256(); + uint8_t hash[SGX_SHA256_HASH_SIZE] = {0}; // Prepare the message used to sign. @@ -227,6 +232,8 @@ sgx_status_t sgx_ecdsa_verify_hash(const uint8_t *hash, return SGX_ERROR_INVALID_PARAMETER; } + fips_self_test_ecc(); + IppStatus ipp_ret = ippStsErr; ipp_ec_state_handles_t *p_ec_handle = (ipp_ec_state_handles_t *)ecc_handle; IppECResult result = ippECInvalidSignature; @@ -337,12 +344,14 @@ sgx_status_t sgx_ecdsa_verify_hash(const uint8_t *hash, } } -sgx_status_t sgx_calculate_ecdsa_priv_key(const unsigned char* hash_drg, int hash_drg_len, - const unsigned char* sgx_nistp256_r_m1, int sgx_nistp256_r_m1_len, - unsigned char* out_key, int out_key_len) { +sgx_status_t sgx_calculate_ecdsa_priv_key(const unsigned char *hash_drg, int hash_drg_len, + const unsigned char *sgx_nistp256_r_m1, int sgx_nistp256_r_m1_len, + unsigned char *out_key, int out_key_len) +{ if (out_key == NULL || hash_drg_len <= 0 || sgx_nistp256_r_m1_len <= 0 || - out_key_len <= 0 || hash_drg == NULL || sgx_nistp256_r_m1 == NULL) { + out_key_len <= 0 || hash_drg == NULL || sgx_nistp256_r_m1 == NULL) + { return SGX_ERROR_INVALID_PARAMETER; } @@ -354,44 +363,46 @@ sgx_status_t sgx_calculate_ecdsa_priv_key(const unsigned char* hash_drg, int has IppsBigNumState *bn_one = NULL; Ipp32u i = 1; - do { + do + { - //allocate and initialize BNs + // allocate and initialize BNs // ipp_status = sgx_ipp_newBN(reinterpret_cast(hash_drg), hash_drg_len, &bn_d); ERROR_BREAK(ipp_status); - //generate mod to be n-1 where n is order of ECC Group + // generate mod to be n-1 where n is order of ECC Group // ipp_status = sgx_ipp_newBN(reinterpret_cast(sgx_nistp256_r_m1), sgx_nistp256_r_m1_len, &bn_m); ERROR_BREAK(ipp_status); - //allocate memory for output BN + // allocate memory for output BN // ipp_status = sgx_ipp_newBN(NULL, sgx_nistp256_r_m1_len, &bn_o); ERROR_BREAK(ipp_status); - //create big number with value of 1 + // create big number with value of 1 // ipp_status = sgx_ipp_newBN(&i, sizeof(Ipp32u), &bn_one); ERROR_BREAK(ipp_status); - //calculate output's BN value + // calculate output's BN value ipp_status = ippsMod_BN(bn_d, bn_m, bn_o); ERROR_BREAK(ipp_status) - //increase by 1 + // increase by 1 // ipp_status = ippsAdd_BN(bn_o, bn_one, bn_o); ERROR_BREAK(ipp_status); /*Unmatched size*/ - if (sgx_nistp256_r_m1_len != sizeof(sgx_ec256_private_t)) { + if (sgx_nistp256_r_m1_len != sizeof(sgx_ec256_private_t)) + { break; } - //convert BN_o into octet string - ipp_status = ippsGetOctString_BN(reinterpret_cast(out_key), sgx_nistp256_r_m1_len, bn_o);//output data in bigendian order + // convert BN_o into octet string + ipp_status = ippsGetOctString_BN(reinterpret_cast(out_key), sgx_nistp256_r_m1_len, bn_o); // output data in bigendian order ERROR_BREAK(ipp_status); ret_code = SGX_SUCCESS; @@ -405,7 +416,8 @@ sgx_status_t sgx_calculate_ecdsa_priv_key(const unsigned char* hash_drg, int has if (ipp_status == ippStsMemAllocErr) ret_code = SGX_ERROR_OUT_OF_MEMORY; - if (ret_code != SGX_SUCCESS) { + if (ret_code != SGX_SUCCESS) + { (void)memset_s(out_key, out_key_len, 0, out_key_len); } diff --git a/sdk/tlibcrypto/ipp/sgx_ecc256_internal.cpp b/sdk/tlibcrypto/ipp/sgx_ecc256_internal.cpp index 9d9a8d17f..904e9c1c3 100644 --- a/sdk/tlibcrypto/ipp/sgx_ecc256_internal.cpp +++ b/sdk/tlibcrypto/ipp/sgx_ecc256_internal.cpp @@ -29,13 +29,9 @@ * */ - - - #include "ipp_wrapper.h" #include "sgx_ecc256_internal.h" - - +#include "sgx_fips_internal.h" /* Computes a point with scalar multiplication based on private B key (local) and remote public Ga Key * Parameters: @@ -46,41 +42,42 @@ * Output: sgx_ec256_shared_point_t *p_shared_key - Pointer to the target shared point - LITTLE ENDIAN x-coordinate of (privKeyB - pubKeyA) */ sgx_status_t sgx_ecc256_compute_shared_point(sgx_ec256_private_t *p_private_b, - sgx_ec256_public_t *p_public_ga, - sgx_ec256_shared_point_t *p_shared_key, - sgx_ecc_state_handle_t ecc_handle) + sgx_ec256_public_t *p_public_ga, + sgx_ec256_shared_point_t *p_shared_key, + sgx_ecc_state_handle_t ecc_handle) { if ((ecc_handle == NULL) || (p_private_b == NULL) || (p_public_ga == NULL) || (p_shared_key == NULL)) { return SGX_ERROR_INVALID_PARAMETER; } - - IppsBigNumState* bn_dh_privb = NULL; - IppsBigNumState* bn_dh_shared_x = NULL; - IppsBigNumState* bn_dh_shared_y = NULL; - IppsBigNumState* puba_gx = NULL; - IppsBigNumState* puba_gy = NULL; - IppsGFpECPoint* point_pub_a = NULL; - IppsGFpECPoint* point_r = NULL; - IppStatus ipp_ret = ippStsErr; - int ec_point_size = 0; - IppECResult ipp_result = ippECValid; + fips_self_test_ecc(); + + IppsBigNumState *bn_dh_privb = NULL; + IppsBigNumState *bn_dh_shared_x = NULL; + IppsBigNumState *bn_dh_shared_y = NULL; + IppsBigNumState *puba_gx = NULL; + IppsBigNumState *puba_gy = NULL; + IppsGFpECPoint *point_pub_a = NULL; + IppsGFpECPoint *point_r = NULL; + IppStatus ipp_ret = ippStsErr; + int ec_point_size = 0; + IppECResult ipp_result = ippECValid; int scratch_size = 0; - Ipp8u* scratch_buf = NULL; + Ipp8u *scratch_buf = NULL; ipp_ec_state_handles_t *p_ec_handle = (ipp_ec_state_handles_t *)ecc_handle; do { - ipp_ret = sgx_ipp_newBN((Ipp32u*)p_private_b->r, sizeof(sgx_ec256_private_t), &bn_dh_privb); + ipp_ret = sgx_ipp_newBN((Ipp32u *)p_private_b->r, sizeof(sgx_ec256_private_t), &bn_dh_privb); ERROR_BREAK(ipp_ret); - ipp_ret = sgx_ipp_newBN((uint32_t*)p_public_ga->gx, sizeof(p_public_ga->gx), &puba_gx); + ipp_ret = sgx_ipp_newBN((uint32_t *)p_public_ga->gx, sizeof(p_public_ga->gx), &puba_gx); ERROR_BREAK(ipp_ret); - ipp_ret = sgx_ipp_newBN((uint32_t*)p_public_ga->gy, sizeof(p_public_ga->gy), &puba_gy); + ipp_ret = sgx_ipp_newBN((uint32_t *)p_public_ga->gy, sizeof(p_public_ga->gy), &puba_gy); ERROR_BREAK(ipp_ret); ipp_ret = ippsGFpECPointGetSize(p_ec_handle->p_ec_state, &ec_point_size); ERROR_BREAK(ipp_ret); point_pub_a = (IppsGFpECPoint *)malloc(ec_point_size); - if(!point_pub_a) + if (!point_pub_a) { ipp_ret = ippStsNoMemErr; break; @@ -90,14 +87,14 @@ sgx_status_t sgx_ecc256_compute_shared_point(sgx_ec256_private_t *p_private_b, ipp_ret = ippsGFpECSetPointRegular(puba_gx, puba_gy, point_pub_a, p_ec_handle->p_ec_state); ERROR_BREAK(ipp_ret); ipp_ret = ippsGFpECTstPoint(point_pub_a, &ipp_result, p_ec_handle->p_ec_state); - ERROR_BREAK(ipp_ret); + ERROR_BREAK(ipp_ret); if (ipp_result != ippECValid) { break; } point_r = (IppsGFpECPoint *)malloc(ec_point_size); - if(!point_r) + if (!point_r) { ipp_ret = ippStsNoMemErr; break; @@ -108,7 +105,7 @@ sgx_status_t sgx_ecc256_compute_shared_point(sgx_ec256_private_t *p_private_b, ipp_ret = ippsGFpECScratchBufferSize(1, p_ec_handle->p_ec_state, &scratch_size); ERROR_BREAK(ipp_ret); scratch_buf = (Ipp8u *)malloc(scratch_size); - if(!scratch_buf) + if (!scratch_buf) { ipp_ret = ippStsNoMemErr; break; @@ -116,11 +113,11 @@ sgx_status_t sgx_ecc256_compute_shared_point(sgx_ec256_private_t *p_private_b, ipp_ret = ippsGFpECMulPoint(point_pub_a, bn_dh_privb, point_r, p_ec_handle->p_ec_state, scratch_buf); ERROR_BREAK(ipp_ret); - //defense in depth to verify that point_r in ECC group - //a return value of ippECValid indicates the point is on the elliptic curve - //and is not the point at infinity + // defense in depth to verify that point_r in ECC group + // a return value of ippECValid indicates the point is on the elliptic curve + // and is not the point at infinity ipp_ret = ippsGFpECTstPoint(point_r, &ipp_result, p_ec_handle->p_ec_state); - ERROR_BREAK(ipp_ret); + ERROR_BREAK(ipp_ret); if (ipp_result != ippECValid) { break; @@ -139,17 +136,17 @@ sgx_status_t sgx_ecc256_compute_shared_point(sgx_ec256_private_t *p_private_b, ipp_ret = ippsRef_BN(&sgn, &length, &pdata, bn_dh_shared_x); ERROR_BREAK(ipp_ret); memset(p_shared_key->x, 0, sizeof(p_shared_key->x)); - memcpy(p_shared_key->x, pdata, ROUND_TO(length, 8)/8); + memcpy(p_shared_key->x, pdata, ROUND_TO(length, 8) / 8); // Clear memory securely - memset_s(pdata, sizeof(p_shared_key->x), 0, ROUND_TO(length, 8)/8); + memset_s(pdata, sizeof(p_shared_key->x), 0, ROUND_TO(length, 8) / 8); ipp_ret = ippsRef_BN(&sgn, &length, &pdata, bn_dh_shared_y); ERROR_BREAK(ipp_ret); memset(p_shared_key->y, 0, sizeof(p_shared_key->y)); - memcpy(p_shared_key->y, pdata, ROUND_TO(length, 8)/8); + memcpy(p_shared_key->y, pdata, ROUND_TO(length, 8) / 8); // Clear memory securely - memset_s(pdata, sizeof(p_shared_key->x), 0, ROUND_TO(length, 8)/8); - }while(0); + memset_s(pdata, sizeof(p_shared_key->x), 0, ROUND_TO(length, 8) / 8); + } while (0); CLEAR_FREE_MEM(point_pub_a, ec_point_size); CLEAR_FREE_MEM(point_r, ec_point_size); sgx_ipp_secure_free_BN(puba_gx, sizeof(p_public_ga->gx)); @@ -168,4 +165,3 @@ sgx_status_t sgx_ecc256_compute_shared_point(sgx_ec256_private_t *p_private_b, } return SGX_SUCCESS; } - diff --git a/sdk/tlibcrypto/ipp/sgx_fips.cpp b/sdk/tlibcrypto/ipp/sgx_fips.cpp index 4f3851954..b17fa522c 100644 --- a/sdk/tlibcrypto/ipp/sgx_fips.cpp +++ b/sdk/tlibcrypto/ipp/sgx_fips.cpp @@ -38,244 +38,13 @@ #include "ipp_wrapper.h" #include "global_data.h" -#define ERROR_SELFTEST_BREAK(test_result) \ - if (test_result != IPPCP_ALGO_SELFTEST_OK) \ - { \ - break; \ - } -#define ALLOC_ERROR_BREAK(pointer, ret) \ - if (pointer == NULL) \ - { \ - ret = SGX_ERROR_OUT_OF_MEMORY; \ - break; \ - } - -#define FIPS_SELFTEST_FUNC(result, func) \ - result = func(); \ - ERROR_SELFTEST_BREAK(result) - -#define FIPS_SELFTEST_FUNC_1(result, func, para) \ - result = func(para); \ - ERROR_SELFTEST_BREAK(result) - -#define FIPS_SELFTEST_FUNC_2(result, func, para1, para2) \ - result = func(para1, para2);\ - ERROR_SELFTEST_BREAK(result) - -#define FIPS_SELFTEST_FUNC_3(result, func, para1, para2, para3) \ - result = func(para1, para2, para3);\ - ERROR_SELFTEST_BREAK(result) - - -/* Encrypt/Decrypt */ -static sgx_status_t encrypt_decrypt_self_test() -{ - sgx_status_t ret = SGX_ERROR_UNEXPECTED; - fips_test_status test_result = IPPCP_ALGO_SELFTEST_OK; - int buf_size = 0; - uint8_t *p_buf = NULL; - int key_buf_size = 0; - uint8_t *p_key_buf = NULL; - do - { - FIPS_SELFTEST_FUNC_1(test_result, fips_selftest_ippsAESEncryptDecrypt_get_size, &buf_size); - p_buf = (uint8_t *)malloc(buf_size); - ALLOC_ERROR_BREAK(p_buf, ret); - FIPS_SELFTEST_FUNC_1(test_result, fips_selftest_ippsAESEncryptCBC, p_buf); - FIPS_SELFTEST_FUNC_1(test_result, fips_selftest_ippsAESDecryptCBC, p_buf); - - FIPS_SELFTEST_FUNC_1(test_result, fips_selftest_ippsAESEncryptCBC_CS1, p_buf); - FIPS_SELFTEST_FUNC_1(test_result, fips_selftest_ippsAESEncryptCBC_CS2, p_buf); - FIPS_SELFTEST_FUNC_1(test_result, fips_selftest_ippsAESEncryptCBC_CS3, p_buf); - FIPS_SELFTEST_FUNC_1(test_result, fips_selftest_ippsAESDecryptCBC_CS1, p_buf); - FIPS_SELFTEST_FUNC_1(test_result, fips_selftest_ippsAESDecryptCBC_CS2, p_buf); - FIPS_SELFTEST_FUNC_1(test_result, fips_selftest_ippsAESDecryptCBC_CS3, p_buf); - - FIPS_SELFTEST_FUNC_1(test_result, fips_selftest_ippsAESEncryptCFB, p_buf); - FIPS_SELFTEST_FUNC_1(test_result, fips_selftest_ippsAESDecryptCFB, p_buf); - FIPS_SELFTEST_FUNC_1(test_result, fips_selftest_ippsAESEncryptOFB, p_buf); - FIPS_SELFTEST_FUNC_1(test_result, fips_selftest_ippsAESDecryptOFB, p_buf); - - FIPS_SELFTEST_FUNC_1(test_result, fips_selftest_ippsAESEncryptCTR, p_buf); - FIPS_SELFTEST_FUNC_1(test_result, fips_selftest_ippsAESDecryptCTR, p_buf); - - FIPS_SELFTEST_FUNC_1(test_result, fips_selftest_ippsAESEncryptDecryptCCM_get_size, &buf_size); - p_buf = (uint8_t *)realloc(p_buf, buf_size); - ALLOC_ERROR_BREAK(p_buf, ret); - FIPS_SELFTEST_FUNC_1(test_result, fips_selftest_ippsAES_CCMEncrypt, p_buf); - FIPS_SELFTEST_FUNC_1(test_result, fips_selftest_ippsAES_CCMDecrypt, p_buf); - - FIPS_SELFTEST_FUNC_1(test_result, fips_selftest_ippsAES_GCM_get_size, &buf_size); - p_buf = (uint8_t *)realloc(p_buf, buf_size); - ALLOC_ERROR_BREAK(p_buf, ret); - FIPS_SELFTEST_FUNC_1(test_result, fips_selftest_ippsAES_GCMEncrypt, p_buf); - FIPS_SELFTEST_FUNC_1(test_result, fips_selftest_ippsAES_GCMDecrypt, p_buf); - - FIPS_SELFTEST_FUNC_1(test_result, fips_selftest_ippsAES_CMAC_get_size, &buf_size); - p_buf = (uint8_t *)realloc(p_buf, buf_size); - ALLOC_ERROR_BREAK(p_buf, ret); - FIPS_SELFTEST_FUNC_1(test_result, fips_selftest_ippsAES_CMACUpdate, p_buf); - - FIPS_SELFTEST_FUNC_1(test_result, fips_selftest_ippsRSAEncryptDecrypt_OAEP_rmf_get_size_keys, &key_buf_size); - p_key_buf = (uint8_t *)malloc(key_buf_size); - ALLOC_ERROR_BREAK(p_key_buf, ret); - FIPS_SELFTEST_FUNC_2(test_result, fips_selftest_ippsRSAEncryptDecrypt_OAEP_rmf_get_size, &buf_size, p_key_buf); - p_buf = (uint8_t *)realloc(p_buf, buf_size); - ALLOC_ERROR_BREAK(p_buf, ret); - FIPS_SELFTEST_FUNC_2(test_result, fips_selftest_ippsRSAEncrypt_OAEP_rmf, p_buf, p_key_buf); - FIPS_SELFTEST_FUNC_2(test_result, fips_selftest_ippsRSADecrypt_OAEP_rmf, p_buf, p_key_buf); - ret = SGX_SUCCESS; - } while (0); - SAFE_FREE(p_buf); - SAFE_FREE(p_key_buf); - return ret; -} - -/* Hash */ -static sgx_status_t hash_self_test() -{ - sgx_status_t ret = SGX_ERROR_UNEXPECTED; - fips_test_status test_result = IPPCP_ALGO_SELFTEST_OK; - int buf_size = 0; - uint8_t *p_buf = NULL; - do - { - // Hashes - FIPS_SELFTEST_FUNC_1(test_result, fips_selftest_ippsHash_rmf_get_size, &buf_size); - p_buf = (uint8_t *)malloc(buf_size); - ALLOC_ERROR_BREAK(p_buf, ret); - - // We only check below HASH algorithms - IppHashAlgId ids[] = {ippHashAlg_SHA224, ippHashAlg_SHA256, ippHashAlg_SHA384, ippHashAlg_SHA512}; - for (uint32_t i = 0; i < sizeof(ids)/sizeof(ids[0]); i++) - { - FIPS_SELFTEST_FUNC_2(test_result, fips_selftest_ippsHashUpdate_rmf, (IppHashAlgId)ids[i], p_buf); - FIPS_SELFTEST_FUNC_1(test_result, fips_selftest_ippsHashMessage_rmf, (IppHashAlgId)ids[i]); - } - ret = SGX_SUCCESS; - } while (0); - SAFE_FREE(p_buf); - return ret; -} - -/* HMAC */ -static sgx_status_t hmac_self_test() -{ - sgx_status_t ret = SGX_ERROR_UNEXPECTED; - fips_test_status test_result = IPPCP_ALGO_SELFTEST_OK; - int buf_size = 0; - uint8_t *p_buf = NULL; - do - { - FIPS_SELFTEST_FUNC_1(test_result, fips_selftest_ippsHMAC_rmf_get_size, &buf_size); - p_buf = (uint8_t *)malloc(buf_size); - ALLOC_ERROR_BREAK(p_buf, ret); - FIPS_SELFTEST_FUNC_1(test_result, fips_selftest_ippsHMACUpdate_rmf, p_buf); - FIPS_SELFTEST_FUNC(test_result, fips_selftest_ippsHMACMessage_rmf); - ret = SGX_SUCCESS; - } while (0); - SAFE_FREE(p_buf); - return ret; -} - -/* RSA sign/verify */ -static sgx_status_t rsa_sign_verfy_self_test() -{ - sgx_status_t ret = SGX_ERROR_UNEXPECTED; - fips_test_status test_result = IPPCP_ALGO_SELFTEST_OK; - int buf_size = 0; - uint8_t *p_buf = NULL; - int key_buf_size = 0; - uint8_t *p_key_buf = NULL; - do - { - FIPS_SELFTEST_FUNC_1(test_result, fips_selftest_ippsRSASignVerify_PKCS1v15_rmf_get_size_keys, &key_buf_size); - p_key_buf = (uint8_t *)malloc(key_buf_size); - ALLOC_ERROR_BREAK(p_key_buf, ret); - FIPS_SELFTEST_FUNC_2(test_result, fips_selftest_ippsRSASignVerify_PKCS1v15_rmf_get_size, &buf_size, p_key_buf); - p_buf = (uint8_t *)malloc(buf_size); - ALLOC_ERROR_BREAK(p_buf, ret); - FIPS_SELFTEST_FUNC_2(test_result, fips_selftest_ippsRSASign_PKCS1v15_rmf, p_buf, p_key_buf); - FIPS_SELFTEST_FUNC_2(test_result, fips_selftest_ippsRSAVerify_PKCS1v15_rmf, p_buf, p_key_buf); - - FIPS_SELFTEST_FUNC_1(test_result, fips_selftest_ippsRSASignVerify_PSS_rmf_get_size_keys, &key_buf_size); - p_key_buf = (uint8_t *)realloc(p_key_buf, key_buf_size); - ALLOC_ERROR_BREAK(p_key_buf, ret); - FIPS_SELFTEST_FUNC_2(test_result, fips_selftest_ippsRSASignVerify_PSS_rmf_get_size, &buf_size, p_key_buf); - p_buf = (uint8_t *)realloc(p_buf, buf_size); - ALLOC_ERROR_BREAK(p_buf, ret); - FIPS_SELFTEST_FUNC_2(test_result, fips_selftest_ippsRSASign_PSS_rmf, p_buf, p_key_buf); - FIPS_SELFTEST_FUNC_2(test_result, fips_selftest_ippsRSAVerify_PSS_rmf, p_buf, p_key_buf); - FIPS_SELFTEST_FUNC_2(test_result, fips_selftest_ippsRSA_GenerateKeys, p_buf, p_key_buf); - ret = SGX_SUCCESS; - } while (0); - SAFE_FREE(p_buf); - SAFE_FREE(p_key_buf); - return ret; -} - -/* ECDSA sign/verify */ -static sgx_status_t ecdsa_sign_verify_self_test() -{ - sgx_status_t ret = SGX_ERROR_UNEXPECTED; - fips_test_status test_result = IPPCP_ALGO_SELFTEST_OK; - int gfp_buf_size = 0; - uint8_t *p_gfp_buf = NULL; - int ec_buf_size = 0; - uint8_t *p_ec_buf = NULL; - int data_buf_size = 0; - uint8_t *p_data_buf = NULL; - do - { - FIPS_SELFTEST_FUNC_1(test_result, fips_selftest_ippsGFpECSignVerifyDSA_get_size_GFp_buff, &gfp_buf_size); - p_gfp_buf = (uint8_t *)malloc(gfp_buf_size); - ALLOC_ERROR_BREAK(p_gfp_buf, ret); - FIPS_SELFTEST_FUNC_2(test_result, fips_selftest_ippsGFpECSignVerifyDSA_get_size_GFpEC_buff, &ec_buf_size, p_gfp_buf); - p_ec_buf = (uint8_t *)malloc(ec_buf_size); - ALLOC_ERROR_BREAK(p_ec_buf, ret); - FIPS_SELFTEST_FUNC_3(test_result, fips_selftest_ippsGFpECSignVerifyDSA_get_size_data_buff, &data_buf_size, p_gfp_buf, p_ec_buf); - p_data_buf = (uint8_t *)malloc(data_buf_size); - ALLOC_ERROR_BREAK(p_data_buf, ret); - FIPS_SELFTEST_FUNC_3(test_result, fips_selftest_ippsGFpECSignDSA, p_gfp_buf, p_ec_buf, p_data_buf); - FIPS_SELFTEST_FUNC_3(test_result, fips_selftest_ippsGFpECVerifyDSA, p_gfp_buf, p_ec_buf, p_data_buf); - FIPS_SELFTEST_FUNC_3(test_result, fips_selftest_ippsGFpECPublicKey, p_gfp_buf, p_ec_buf, p_data_buf); - FIPS_SELFTEST_FUNC_3(test_result, fips_selftest_ippsGFpECSharedSecretDH, p_gfp_buf, p_ec_buf, p_data_buf); - - ret = SGX_SUCCESS; - } while (0); - SAFE_FREE(p_gfp_buf); - SAFE_FREE(p_ec_buf); - SAFE_FREE(p_data_buf); - return ret; -} - -/* FIPS selftest - * Should only be called if require to run in FIPS mode */ -extern "C" sgx_status_t sgx_crypto_fips_selftest() -{ - sgx_status_t ret = encrypt_decrypt_self_test(); - if (ret != SGX_SUCCESS) - return ret; - ret = hash_self_test(); - if (ret != SGX_SUCCESS) - return ret; - ret = hmac_self_test(); - if (ret != SGX_SUCCESS) - return ret; - ret = rsa_sign_verfy_self_test(); - if (ret != SGX_SUCCESS) - return ret; - ret = ecdsa_sign_verify_self_test(); - return ret; -} - sgx_status_t sgx_is_fips_approved_func(sgx_fips_func_t func, func_fips_approved_t *is_approved) { if (is_approved == NULL) return SGX_ERROR_INVALID_PARAMETER; bool ret = func > 0 ? true : false; - if (ret == true) + if (ret == true && g_global_data.fips_on != 0) { *is_approved = 1; } diff --git a/sdk/tlibcrypto/ipp/sgx_fips_internal.h b/sdk/tlibcrypto/ipp/sgx_fips_internal.h new file mode 100644 index 000000000..a77616cf3 --- /dev/null +++ b/sdk/tlibcrypto/ipp/sgx_fips_internal.h @@ -0,0 +1,78 @@ +/* + * Copyright (C) 2011-2021 Intel Corporation. All rights reserved. + * + * 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. + * * Neither the name of Intel Corporation nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER 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. + * + */ + +#pragma once + +#include "sgx_tcrypto.h" +#include "ippcp.h" +#include "ippcp/fips_cert.h" +#include "global_data.h" + +#define ERROR_SELFTEST_BREAK(test_result) \ + if (test_result != IPPCP_ALGO_SELFTEST_OK) \ + { \ + break; \ + } +#define ALLOC_ERROR_BREAK(pointer, ret) \ + if (pointer == NULL) \ + { \ + ret = SGX_ERROR_OUT_OF_MEMORY; \ + break; \ + } + +#define FIPS_SELFTEST_FUNC(result, func) \ + result = func(); \ + ERROR_SELFTEST_BREAK(result) + +#define FIPS_SELFTEST_FUNC_1(result, func, para) \ + result = func(para); \ + ERROR_SELFTEST_BREAK(result) + +#define FIPS_SELFTEST_FUNC_2(result, func, para1, para2) \ + result = func(para1, para2);\ + ERROR_SELFTEST_BREAK(result) + +#define FIPS_SELFTEST_FUNC_3(result, func, para1, para2, para3) \ + result = func(para1, para2, para3);\ + ERROR_SELFTEST_BREAK(result) + +#define ERROR_ABORT(ret) \ + { \ + if (ret != SGX_SUCCESS) \ + { \ + g_global_data.fips_on = 0; \ + abort(); \ + } \ + } + +void fips_self_test_ecc(); +void fips_self_test_hash256(); +void fips_self_test_hash384(); diff --git a/sdk/tlibcrypto/ipp/sgx_hmac.cpp b/sdk/tlibcrypto/ipp/sgx_hmac.cpp index 1175f9e3f..1bc32d443 100644 --- a/sdk/tlibcrypto/ipp/sgx_hmac.cpp +++ b/sdk/tlibcrypto/ipp/sgx_hmac.cpp @@ -34,8 +34,35 @@ #include "ipp_wrapper.h" #include "stdlib.h" #include "string.h" +#include "sgx_fips_internal.h" - /* Message Authentication - HMAC 256 +static void fips_self_test_hmac() +{ + static bool fips_selftest_hmac_flag = false; + + if (g_global_data.fips_on != 0 && fips_selftest_hmac_flag == false) + { + sgx_status_t ret = SGX_ERROR_UNEXPECTED; + fips_test_status test_result = IPPCP_ALGO_SELFTEST_OK; + int buf_size = 0; + uint8_t *p_buf = NULL; + do + { + FIPS_SELFTEST_FUNC_1(test_result, fips_selftest_ippsHMAC_rmf_get_size, &buf_size); + p_buf = (uint8_t *)malloc(buf_size); + ALLOC_ERROR_BREAK(p_buf, ret); + FIPS_SELFTEST_FUNC_1(test_result, fips_selftest_ippsHMACUpdate_rmf, p_buf); + FIPS_SELFTEST_FUNC(test_result, fips_selftest_ippsHMACMessage_rmf); + fips_selftest_hmac_flag = true; + ret = SGX_SUCCESS; + } while (0); + SAFE_FREE(p_buf); + ERROR_ABORT(ret); + } + return; +} + +/* Message Authentication - HMAC 256 * Parameters: * Return: sgx_status_t - SGX_SUCCESS or failure as defined sgx_error.h * Inputs: const unsigned char *p_src - Pointer to input stream to be MACed @@ -46,126 +73,151 @@ * Output: unsigned char *p_mac - Pointer to resultant MAC */ sgx_status_t sgx_hmac_sha256_msg(const unsigned char *p_src, int src_len, const unsigned char *p_key, int key_len, - unsigned char *p_mac, int mac_len) + unsigned char *p_mac, int mac_len) { - if ((p_src == NULL) || (p_key == NULL) || (p_mac == NULL) || (src_len <= 0) || (key_len <= 0) || (mac_len <= 0)) { - return SGX_ERROR_INVALID_PARAMETER; - } - - sgx_status_t ret = SGX_ERROR_UNEXPECTED; - IppStatus ipp_ret = ippStsNoErr; - - do { - ipp_ret = ippsHMACMessage_rmf(p_src, src_len, (const Ipp8u*)p_key, key_len, p_mac, mac_len, ippsHashMethod_SHA256_TT()); - ERROR_BREAK(ipp_ret); - - ret = SGX_SUCCESS; - } while (0); - - if (ret != SGX_SUCCESS) { - memset_s(p_mac, mac_len, 0, mac_len); - } - - return ret; + if ((p_src == NULL) || (p_key == NULL) || (p_mac == NULL) || (src_len <= 0) || (key_len <= 0) || (mac_len <= 0)) + { + return SGX_ERROR_INVALID_PARAMETER; + } + + fips_self_test_hmac(); + fips_self_test_hash256(); + + sgx_status_t ret = SGX_ERROR_UNEXPECTED; + IppStatus ipp_ret = ippStsNoErr; + + do + { + ipp_ret = ippsHMACMessage_rmf(p_src, src_len, (const Ipp8u *)p_key, key_len, p_mac, mac_len, ippsHashMethod_SHA256_TT()); + ERROR_BREAK(ipp_ret); + + ret = SGX_SUCCESS; + } while (0); + + if (ret != SGX_SUCCESS) + { + memset_s(p_mac, mac_len, 0, mac_len); + } + + return ret; } /* Allocates and initializes HMAC state -* Parameters: -* Return: sgx_status_t - SGX_SUCCESS or failure as defined in sgx_error.h -* Inputs: const unsigned char *p_key - Pointer to the key used in message authentication operation -* int key_len - Key length -* Output: sgx_hmac_state_handle_t *p_hmac_handle - Pointer to the initialized HMAC state handle -*/ + * Parameters: + * Return: sgx_status_t - SGX_SUCCESS or failure as defined in sgx_error.h + * Inputs: const unsigned char *p_key - Pointer to the key used in message authentication operation + * int key_len - Key length + * Output: sgx_hmac_state_handle_t *p_hmac_handle - Pointer to the initialized HMAC state handle + */ sgx_status_t sgx_hmac256_init(const unsigned char *p_key, int key_len, sgx_hmac_state_handle_t *p_hmac_handle) { - if ((p_key == NULL) || (key_len <= 0) || (p_hmac_handle == NULL)) { + if ((p_key == NULL) || (key_len <= 0) || (p_hmac_handle == NULL)) + { return SGX_ERROR_INVALID_PARAMETER; } - IppStatus ipp_ret = ippStsNoErr; - sgx_status_t ret = SGX_ERROR_UNEXPECTED; - IppsHMACState_rmf* pState = NULL; - - int size = 0; - - do { - ipp_ret = ippsHMACGetSize_rmf(&size); - ERROR_BREAK(ipp_ret); - pState = (IppsHMACState_rmf*) malloc(size); - if (NULL == pState) - { - ret = SGX_ERROR_OUT_OF_MEMORY; - break; - } - ipp_ret = ippsHMACInit_rmf(p_key, key_len, pState, ippsHashMethod_SHA256_TT()); - ERROR_BREAK(ipp_ret); - - *p_hmac_handle = pState; - ret = SGX_SUCCESS; - } while (0); - - if (ret != SGX_SUCCESS) { - sgx_hmac256_close((sgx_hmac_state_handle_t)pState); - } - - return ret; + fips_self_test_hmac(); + fips_self_test_hash256(); + + IppStatus ipp_ret = ippStsNoErr; + sgx_status_t ret = SGX_ERROR_UNEXPECTED; + IppsHMACState_rmf *pState = NULL; + + int size = 0; + + do + { + ipp_ret = ippsHMACGetSize_rmf(&size); + ERROR_BREAK(ipp_ret); + pState = (IppsHMACState_rmf *)malloc(size); + if (NULL == pState) + { + ret = SGX_ERROR_OUT_OF_MEMORY; + break; + } + ipp_ret = ippsHMACInit_rmf(p_key, key_len, pState, ippsHashMethod_SHA256_TT()); + ERROR_BREAK(ipp_ret); + + *p_hmac_handle = pState; + ret = SGX_SUCCESS; + } while (0); + + if (ret != SGX_SUCCESS) + { + sgx_hmac256_close((sgx_hmac_state_handle_t)pState); + } + + return ret; } /* Updates HMAC hash calculation based on the input message -* Parameters: -* Return: sgx_status_t - SGX_SUCCESS or failure as defined in sgx_error. -* Input: uint8_t *p_src - Pointer to the input stream to be hashed -* int src_len - Length of input stream to be hashed -* sgx_hmac_state_handle_t hmac_handle - Handle to the HMAC state -*/ + * Parameters: + * Return: sgx_status_t - SGX_SUCCESS or failure as defined in sgx_error. + * Input: uint8_t *p_src - Pointer to the input stream to be hashed + * int src_len - Length of input stream to be hashed + * sgx_hmac_state_handle_t hmac_handle - Handle to the HMAC state + */ sgx_status_t sgx_hmac256_update(const uint8_t *p_src, int src_len, sgx_hmac_state_handle_t hmac_handle) { - if ((p_src == NULL) || (src_len <= 0) || (hmac_handle == NULL)) { - return SGX_ERROR_INVALID_PARAMETER; - } - IppStatus ipp_ret = ippStsNoErr; - - ipp_ret = ippsHMACUpdate_rmf(p_src, (int)src_len, (IppsHMACState_rmf*)hmac_handle); - if (ipp_ret != ippStsNoErr) { - return SGX_ERROR_UNEXPECTED; - } - return SGX_SUCCESS; + if ((p_src == NULL) || (src_len <= 0) || (hmac_handle == NULL)) + { + return SGX_ERROR_INVALID_PARAMETER; + } + + fips_self_test_hmac(); + fips_self_test_hash256(); + + IppStatus ipp_ret = ippStsNoErr; + + ipp_ret = ippsHMACUpdate_rmf(p_src, (int)src_len, (IppsHMACState_rmf *)hmac_handle); + if (ipp_ret != ippStsNoErr) + { + return SGX_ERROR_UNEXPECTED; + } + return SGX_SUCCESS; } /* Returns calculated hash -* Parameters: -* Return: sgx_status_t - SGX_SUCCESS or failure as defined in sgx_error.h -* Input: sgx_hmac_state_handle_t hmac_handle - Handle to the HMAC state -* int hash_len - Expected MAC length -* Output: unsigned char *p_hash - Resultant hash from HMAC operation -*/ + * Parameters: + * Return: sgx_status_t - SGX_SUCCESS or failure as defined in sgx_error.h + * Input: sgx_hmac_state_handle_t hmac_handle - Handle to the HMAC state + * int hash_len - Expected MAC length + * Output: unsigned char *p_hash - Resultant hash from HMAC operation + */ sgx_status_t sgx_hmac256_final(unsigned char *p_hash, int hash_len, sgx_hmac_state_handle_t hmac_handle) { - if ((p_hash == NULL) || (hash_len <= 0) || (hmac_handle == NULL)) { + if ((p_hash == NULL) || (hash_len <= 0) || (hmac_handle == NULL)) + { return SGX_ERROR_INVALID_PARAMETER; } - IppStatus ipp_ret = ippStsNoErr; - ipp_ret = ippsHMACFinal_rmf(p_hash, hash_len, (IppsHMACState_rmf*)hmac_handle); - if (ipp_ret != ippStsNoErr) { - memset_s(p_hash, hash_len, 0, hash_len); - return SGX_ERROR_UNEXPECTED; - } + fips_self_test_hmac(); + fips_self_test_hash256(); - return SGX_SUCCESS; + IppStatus ipp_ret = ippStsNoErr; + + ipp_ret = ippsHMACFinal_rmf(p_hash, hash_len, (IppsHMACState_rmf *)hmac_handle); + if (ipp_ret != ippStsNoErr) + { + memset_s(p_hash, hash_len, 0, hash_len); + return SGX_ERROR_UNEXPECTED; + } + + return SGX_SUCCESS; } /* Clean up and free the HMAC state -* Parameters: -* Return: sgx_status_t - SGX_SUCCESS or failure as defined in sgx_error.h -* Input: sgx_hmac_state_handle_t hmac_handle - Handle to the HMAC state -* */ + * Parameters: + * Return: sgx_status_t - SGX_SUCCESS or failure as defined in sgx_error.h + * Input: sgx_hmac_state_handle_t hmac_handle - Handle to the HMAC state + * */ sgx_status_t sgx_hmac256_close(sgx_hmac_state_handle_t hmac_handle) { - if (hmac_handle == NULL) { + if (hmac_handle == NULL) + { return SGX_ERROR_INVALID_PARAMETER; } - + int size = 0; IppStatus ipp_ret = ippsHMACGetSize_rmf(&size); if (ipp_ret != ippStsNoErr) diff --git a/sdk/tlibcrypto/ipp/sgx_rsa3072.cpp b/sdk/tlibcrypto/ipp/sgx_rsa3072.cpp index 45e44d6a9..6639644a8 100644 --- a/sdk/tlibcrypto/ipp/sgx_rsa3072.cpp +++ b/sdk/tlibcrypto/ipp/sgx_rsa3072.cpp @@ -29,35 +29,79 @@ * */ - #include "ipp_wrapper.h" +#include "sgx_fips_internal.h" +static void fips_self_test_rsa_sign_verify() +{ + static bool fips_selftest_rsa_sign_verify_flag = false; -sgx_status_t sgx_rsa3072_sign_ex(const uint8_t * p_data, - uint32_t data_size, - const sgx_rsa3072_key_t * p_key, - const sgx_rsa3072_public_key_t *p_public, - sgx_rsa3072_signature_t * p_signature) + if (g_global_data.fips_on != 0 && fips_selftest_rsa_sign_verify_flag == false) + { + sgx_status_t ret = SGX_ERROR_UNEXPECTED; + fips_test_status test_result = IPPCP_ALGO_SELFTEST_OK; + int buf_size = 0; + uint8_t *p_buf = NULL; + int key_buf_size = 0; + uint8_t *p_key_buf = NULL; + do + { + FIPS_SELFTEST_FUNC_1(test_result, fips_selftest_ippsRSASignVerify_PKCS1v15_rmf_get_size_keys, &key_buf_size); + p_key_buf = (uint8_t *)malloc(key_buf_size); + ALLOC_ERROR_BREAK(p_key_buf, ret); + FIPS_SELFTEST_FUNC_2(test_result, fips_selftest_ippsRSASignVerify_PKCS1v15_rmf_get_size, &buf_size, p_key_buf); + p_buf = (uint8_t *)malloc(buf_size); + ALLOC_ERROR_BREAK(p_buf, ret); + FIPS_SELFTEST_FUNC_2(test_result, fips_selftest_ippsRSASign_PKCS1v15_rmf, p_buf, p_key_buf); + FIPS_SELFTEST_FUNC_2(test_result, fips_selftest_ippsRSAVerify_PKCS1v15_rmf, p_buf, p_key_buf); + + FIPS_SELFTEST_FUNC_1(test_result, fips_selftest_ippsRSASignVerify_PSS_rmf_get_size_keys, &key_buf_size); + p_key_buf = (uint8_t *)realloc(p_key_buf, key_buf_size); + ALLOC_ERROR_BREAK(p_key_buf, ret); + FIPS_SELFTEST_FUNC_2(test_result, fips_selftest_ippsRSASignVerify_PSS_rmf_get_size, &buf_size, p_key_buf); + p_buf = (uint8_t *)realloc(p_buf, buf_size); + ALLOC_ERROR_BREAK(p_buf, ret); + FIPS_SELFTEST_FUNC_2(test_result, fips_selftest_ippsRSA_GenerateKeys, p_buf, p_key_buf); + ret = SGX_SUCCESS; + fips_selftest_rsa_sign_verify_flag = true; + + } while (0); + SAFE_FREE(p_buf); + SAFE_FREE(p_key_buf); + ERROR_ABORT(ret); + } + return; +} + +sgx_status_t sgx_rsa3072_sign_ex(const uint8_t *p_data, + uint32_t data_size, + const sgx_rsa3072_key_t *p_key, + const sgx_rsa3072_public_key_t *p_public, + sgx_rsa3072_signature_t *p_signature) { if ((p_data == NULL) || (data_size < 1) || (p_key == NULL) || - (p_signature == NULL) ) + (p_signature == NULL)) { return SGX_ERROR_INVALID_PARAMETER; } + + fips_self_test_rsa_sign_verify(); + fips_self_test_hash256(); + IppStatus ipp_ret = ippStsNoErr; - IppsRSAPrivateKeyState* p_rsa_privatekey_ctx = NULL; + IppsRSAPrivateKeyState *p_rsa_privatekey_ctx = NULL; int private_key_ctx_size = 0; int temp_buff_size = 0; Ipp8u *temp_buff = NULL; - IppsBigNumState* p_prikey_mod_bn = NULL; - IppsBigNumState* p_prikey_d_bn = NULL; + IppsBigNumState *p_prikey_mod_bn = NULL; + IppsBigNumState *p_prikey_d_bn = NULL; - IppsRSAPublicKeyState* p_rsa_publickey_ctx = NULL; + IppsRSAPublicKeyState *p_rsa_publickey_ctx = NULL; - IppsBigNumState* p_pubkey_mod_bn = NULL; - IppsBigNumState* p_pubkey_exp_bn = NULL; + IppsBigNumState *p_pubkey_mod_bn = NULL; + IppsBigNumState *p_pubkey_exp_bn = NULL; do { @@ -70,18 +114,19 @@ sgx_status_t sgx_rsa3072_sign_ex(const uint8_t * p_data, // allocate private key context ipp_ret = ippsRSA_GetSizePrivateKeyType1(SGX_RSA3072_KEY_SIZE * 8, SGX_RSA3072_PRI_EXP_SIZE * 8, - &private_key_ctx_size); + &private_key_ctx_size); ERROR_BREAK(ipp_ret); - p_rsa_privatekey_ctx = (IppsRSAPrivateKeyState*)malloc(private_key_ctx_size); - if (!p_rsa_privatekey_ctx) { + p_rsa_privatekey_ctx = (IppsRSAPrivateKeyState *)malloc(private_key_ctx_size); + if (!p_rsa_privatekey_ctx) + { ipp_ret = ippStsMemAllocErr; break; } // initialize the private key context ipp_ret = ippsRSA_InitPrivateKeyType1(SGX_RSA3072_KEY_SIZE * 8, SGX_RSA3072_PRI_EXP_SIZE * 8, - p_rsa_privatekey_ctx, private_key_ctx_size); + p_rsa_privatekey_ctx, private_key_ctx_size); ERROR_BREAK(ipp_ret); ipp_ret = ippsRSA_SetPrivateKeyType1(p_prikey_mod_bn, p_prikey_d_bn, p_rsa_privatekey_ctx); @@ -94,7 +139,8 @@ sgx_status_t sgx_rsa3072_sign_ex(const uint8_t * p_data, temp_buff_size = private_key_buffer_size; - if(p_public != NULL) { + if (p_public != NULL) + { // Initializa IPP BN from the public key ipp_ret = sgx_ipp_newBN((const Ipp32u *)p_public->mod, sizeof(p_public->mod), &p_pubkey_mod_bn); ERROR_BREAK(ipp_ret); @@ -106,18 +152,19 @@ sgx_status_t sgx_rsa3072_sign_ex(const uint8_t * p_data, int public_key_ctx_size = 0; ipp_ret = ippsRSA_GetSizePublicKey(SGX_RSA3072_KEY_SIZE * 8, SGX_RSA3072_PUB_EXP_SIZE * 8, - &public_key_ctx_size); + &public_key_ctx_size); ERROR_BREAK(ipp_ret); - p_rsa_publickey_ctx = (IppsRSAPublicKeyState*)malloc(public_key_ctx_size); - if (!p_rsa_publickey_ctx) { + p_rsa_publickey_ctx = (IppsRSAPublicKeyState *)malloc(public_key_ctx_size); + if (!p_rsa_publickey_ctx) + { ipp_ret = ippStsMemAllocErr; break; } // initialize the public key context ipp_ret = ippsRSA_InitPublicKey(SGX_RSA3072_KEY_SIZE * 8, SGX_RSA3072_PUB_EXP_SIZE * 8, - p_rsa_publickey_ctx, public_key_ctx_size); + p_rsa_publickey_ctx, public_key_ctx_size); ERROR_BREAK(ipp_ret); ipp_ret = ippsRSA_SetPublicKey(p_pubkey_mod_bn, p_pubkey_exp_bn, p_rsa_publickey_ctx); @@ -129,12 +176,13 @@ sgx_status_t sgx_rsa3072_sign_ex(const uint8_t * p_data, ipp_ret = ippsRSA_GetBufferSizePublicKey(&public_key_buffer_size, p_rsa_publickey_ctx); ERROR_BREAK(ipp_ret); - if(public_key_buffer_size > temp_buff_size) - temp_buff_size = public_key_buffer_size; + if (public_key_buffer_size > temp_buff_size) + temp_buff_size = public_key_buffer_size; } - temp_buff = (Ipp8u*)malloc(temp_buff_size); - if (!temp_buff) { + temp_buff = (Ipp8u *)malloc(temp_buff_size); + if (!temp_buff) + { ipp_ret = ippStsMemAllocErr; break; } @@ -147,7 +195,7 @@ sgx_status_t sgx_rsa3072_sign_ex(const uint8_t * p_data, sgx_ipp_secure_free_BN(p_prikey_mod_bn, sizeof(p_key->mod)); sgx_ipp_secure_free_BN(p_prikey_d_bn, sizeof(p_key->d)); CLEAR_FREE_MEM(p_rsa_privatekey_ctx, private_key_ctx_size); - + sgx_ipp_secure_free_BN(p_pubkey_mod_bn, sizeof(p_public->mod)); sgx_ipp_secure_free_BN(p_pubkey_exp_bn, sizeof(p_public->exp)); SAFE_FREE(p_rsa_publickey_ctx); @@ -156,47 +204,54 @@ sgx_status_t sgx_rsa3072_sign_ex(const uint8_t * p_data, switch (ipp_ret) { - case ippStsNoErr: return SGX_SUCCESS; + case ippStsNoErr: + return SGX_SUCCESS; case ippStsNoMemErr: - case ippStsMemAllocErr: return SGX_ERROR_OUT_OF_MEMORY; + case ippStsMemAllocErr: + return SGX_ERROR_OUT_OF_MEMORY; case ippStsNullPtrErr: case ippStsLengthErr: case ippStsOutOfRangeErr: case ippStsSizeErr: - case ippStsBadArgErr: return SGX_ERROR_INVALID_PARAMETER; - default: return SGX_ERROR_UNEXPECTED; + case ippStsBadArgErr: + return SGX_ERROR_INVALID_PARAMETER; + default: + return SGX_ERROR_UNEXPECTED; } } - -sgx_status_t sgx_rsa3072_sign(const uint8_t * p_data, - uint32_t data_size, - const sgx_rsa3072_key_t * p_key, - sgx_rsa3072_signature_t * p_signature) +sgx_status_t sgx_rsa3072_sign(const uint8_t *p_data, + uint32_t data_size, + const sgx_rsa3072_key_t *p_key, + sgx_rsa3072_signature_t *p_signature) { - return sgx_rsa3072_sign_ex(p_data, data_size, p_key, NULL, p_signature); + return sgx_rsa3072_sign_ex(p_data, data_size, p_key, NULL, p_signature); } sgx_status_t sgx_rsa3072_verify(const uint8_t *p_data, - uint32_t data_size, - const sgx_rsa3072_public_key_t *p_public, - const sgx_rsa3072_signature_t *p_signature, - sgx_rsa_result_t *p_result) + uint32_t data_size, + const sgx_rsa3072_public_key_t *p_public, + const sgx_rsa3072_signature_t *p_signature, + sgx_rsa_result_t *p_result) { if ((p_data == NULL) || (data_size < 1) || (p_public == NULL) || (p_signature == NULL) || (p_result == NULL)) { return SGX_ERROR_INVALID_PARAMETER; } + + fips_self_test_rsa_sign_verify(); + fips_self_test_hash256(); + *p_result = SGX_RSA_INVALID_SIGNATURE; IppStatus ipp_ret = ippStsNoErr; - IppsRSAPublicKeyState* p_rsa_publickey_ctx = NULL; + IppsRSAPublicKeyState *p_rsa_publickey_ctx = NULL; Ipp8u *temp_buff = NULL; - IppsBigNumState* p_pubkey_mod_bn = NULL; - IppsBigNumState* p_pubkey_exp_bn = NULL; + IppsBigNumState *p_pubkey_mod_bn = NULL; + IppsBigNumState *p_pubkey_exp_bn = NULL; int result = 0; @@ -213,18 +268,19 @@ sgx_status_t sgx_rsa3072_verify(const uint8_t *p_data, int public_key_ctx_size = 0; ipp_ret = ippsRSA_GetSizePublicKey(SGX_RSA3072_KEY_SIZE * 8, SGX_RSA3072_PUB_EXP_SIZE * 8, - &public_key_ctx_size); + &public_key_ctx_size); ERROR_BREAK(ipp_ret); - p_rsa_publickey_ctx = (IppsRSAPublicKeyState*)malloc(public_key_ctx_size); - if (!p_rsa_publickey_ctx) { + p_rsa_publickey_ctx = (IppsRSAPublicKeyState *)malloc(public_key_ctx_size); + if (!p_rsa_publickey_ctx) + { ipp_ret = ippStsMemAllocErr; break; } // initialize the public key context ipp_ret = ippsRSA_InitPublicKey(SGX_RSA3072_KEY_SIZE * 8, SGX_RSA3072_PUB_EXP_SIZE * 8, - p_rsa_publickey_ctx, public_key_ctx_size); + p_rsa_publickey_ctx, public_key_ctx_size); ERROR_BREAK(ipp_ret); ipp_ret = ippsRSA_SetPublicKey(p_pubkey_mod_bn, p_pubkey_exp_bn, p_rsa_publickey_ctx); @@ -236,8 +292,9 @@ sgx_status_t sgx_rsa3072_verify(const uint8_t *p_data, ipp_ret = ippsRSA_GetBufferSizePublicKey(&public_key_buffer_size, p_rsa_publickey_ctx); ERROR_BREAK(ipp_ret); - temp_buff = (Ipp8u*)malloc(public_key_buffer_size); - if (!temp_buff) { + temp_buff = (Ipp8u *)malloc(public_key_buffer_size); + if (!temp_buff) + { ipp_ret = ippStsMemAllocErr; break; } @@ -259,14 +316,18 @@ sgx_status_t sgx_rsa3072_verify(const uint8_t *p_data, switch (ipp_ret) { - case ippStsNoErr: return SGX_SUCCESS; + case ippStsNoErr: + return SGX_SUCCESS; case ippStsNoMemErr: - case ippStsMemAllocErr: return SGX_ERROR_OUT_OF_MEMORY; + case ippStsMemAllocErr: + return SGX_ERROR_OUT_OF_MEMORY; case ippStsNullPtrErr: case ippStsLengthErr: case ippStsOutOfRangeErr: case ippStsSizeErr: - case ippStsBadArgErr: return SGX_ERROR_INVALID_PARAMETER; - default: return SGX_ERROR_UNEXPECTED; + case ippStsBadArgErr: + return SGX_ERROR_INVALID_PARAMETER; + default: + return SGX_ERROR_UNEXPECTED; } } diff --git a/sdk/tlibcrypto/ipp/sgx_rsa_encryption.cpp b/sdk/tlibcrypto/ipp/sgx_rsa_encryption.cpp index 3cc46597e..d80a4bc77 100644 --- a/sdk/tlibcrypto/ipp/sgx_rsa_encryption.cpp +++ b/sdk/tlibcrypto/ipp/sgx_rsa_encryption.cpp @@ -30,47 +30,91 @@ */ /** -* File: -* sgx_rsa_encryption.cpp -* Description: -* Wrapper for rsa operation functions -* -*/ + * File: + * sgx_rsa_encryption.cpp + * Description: + * Wrapper for rsa operation functions + * + */ #include #include #include #include "sgx_error.h" #include "sgx_trts.h" #include "ipp_wrapper.h" +#include "sgx_fips_internal.h" +void fips_self_test_rsa_encrypt_decrypt() +{ + static bool fips_selftest_rsa_encrypt_decrypt = false; + + if (g_global_data.fips_on != 0 && fips_selftest_rsa_encrypt_decrypt == false) + { + sgx_status_t ret = SGX_ERROR_UNEXPECTED; + fips_test_status test_result = IPPCP_ALGO_SELFTEST_OK; + int buf_size = 0; + uint8_t *p_buf = NULL; + int key_buf_size = 0; + uint8_t *p_key_buf = NULL; + do + { + FIPS_SELFTEST_FUNC_1(test_result, fips_selftest_ippsRSAEncryptDecrypt_OAEP_rmf_get_size_keys, &key_buf_size); + p_key_buf = (uint8_t *)malloc(key_buf_size); + ALLOC_ERROR_BREAK(p_key_buf, ret); + FIPS_SELFTEST_FUNC_2(test_result, fips_selftest_ippsRSAEncryptDecrypt_OAEP_rmf_get_size, &buf_size, p_key_buf); + p_buf = (uint8_t *)malloc(buf_size); + ALLOC_ERROR_BREAK(p_buf, ret); + FIPS_SELFTEST_FUNC_2(test_result, fips_selftest_ippsRSAEncrypt_OAEP_rmf, p_buf, p_key_buf); + FIPS_SELFTEST_FUNC_2(test_result, fips_selftest_ippsRSADecrypt_OAEP_rmf, p_buf, p_key_buf); + + FIPS_SELFTEST_FUNC_1(test_result, fips_selftest_ippsRSASignVerify_PSS_rmf_get_size_keys, &key_buf_size); + p_key_buf = (uint8_t *)realloc(p_key_buf, key_buf_size); + ALLOC_ERROR_BREAK(p_key_buf, ret); + FIPS_SELFTEST_FUNC_2(test_result, fips_selftest_ippsRSASignVerify_PSS_rmf_get_size, &buf_size, p_key_buf); + p_buf = (uint8_t *)realloc(p_buf, buf_size); + ALLOC_ERROR_BREAK(p_buf, ret); + FIPS_SELFTEST_FUNC_2(test_result, fips_selftest_ippsRSA_GenerateKeys, p_buf, p_key_buf); + ret = SGX_SUCCESS; + fips_selftest_rsa_encrypt_decrypt = true; + } while (0); + SAFE_FREE(p_buf); + SAFE_FREE(p_key_buf); + ERROR_ABORT(ret); + } + return; +} sgx_status_t sgx_create_rsa_key_pair(int n_byte_size, int e_byte_size, unsigned char *p_n, unsigned char *p_d, unsigned char *p_e, - unsigned char *p_p, unsigned char *p_q, unsigned char *p_dmp1, - unsigned char *p_dmq1, unsigned char *p_iqmp) + unsigned char *p_p, unsigned char *p_q, unsigned char *p_dmp1, + unsigned char *p_dmq1, unsigned char *p_iqmp) { if (n_byte_size <= 0 || e_byte_size <= 0 || p_n == NULL || p_d == NULL || p_e == NULL || - p_p == NULL || p_q == NULL || p_dmp1 == NULL || p_dmq1 == NULL || p_iqmp == NULL) { + p_p == NULL || p_q == NULL || p_dmp1 == NULL || p_dmq1 == NULL || p_iqmp == NULL) + { return SGX_ERROR_INVALID_PARAMETER; } + fips_self_test_rsa_encrypt_decrypt(); + IppsRSAPrivateKeyState *p_pri_key = NULL; IppStatus error_code = ippStsNoErr; sgx_status_t ret_code = SGX_ERROR_UNEXPECTED; IppsPrimeState *p_prime = NULL; - Ipp8u * scratch_buffer = NULL; + Ipp8u *scratch_buffer = NULL; int pri_size = 0, scratch_buffer_size = 0; IppsBigNumState *bn_n = NULL, *bn_e = NULL, *bn_d = NULL, *bn_e_s = NULL, *bn_p = NULL, *bn_q = NULL, *bn_dmp1 = NULL, *bn_dmq1 = NULL, *bn_iqmp = NULL; int size = 0; IppsBigNumSGN sgn = IppsBigNumPOS; - do { + do + { - //create a new prime number generator + // create a new prime number generator // error_code = sgx_ipp_newPrimeGen(n_byte_size * 8 / 2, &p_prime); ERROR_BREAK(error_code); - //allocate and init private key of type 2 + // allocate and init private key of type 2 // error_code = ippsRSA_GetSizePrivateKeyType2(n_byte_size / 2 * 8, n_byte_size / 2 * 8, &pri_size); ERROR_BREAK(error_code); @@ -83,7 +127,7 @@ sgx_status_t sgx_create_rsa_key_pair(int n_byte_size, int e_byte_size, unsigned error_code = ippsRSA_InitPrivateKeyType2(n_byte_size / 2 * 8, n_byte_size / 2 * 8, p_pri_key, pri_size); ERROR_BREAK(error_code); - //allocate scratch buffer, to be used as temp buffer + // allocate scratch buffer, to be used as temp buffer // error_code = ippsRSA_GetBufferSizePrivateKey(&scratch_buffer_size, p_pri_key); ERROR_BREAK(error_code); @@ -95,9 +139,9 @@ sgx_status_t sgx_create_rsa_key_pair(int n_byte_size, int e_byte_size, unsigned } memset(scratch_buffer, 0, scratch_buffer_size); - //allocate and initialize RSA BNs + // allocate and initialize RSA BNs // - error_code = sgx_ipp_newBN((const Ipp32u*)p_e, e_byte_size, &bn_e_s); + error_code = sgx_ipp_newBN((const Ipp32u *)p_e, e_byte_size, &bn_e_s); ERROR_BREAK(error_code); error_code = sgx_ipp_newBN(NULL, n_byte_size, &bn_n); ERROR_BREAK(error_code); @@ -116,68 +160,69 @@ sgx_status_t sgx_create_rsa_key_pair(int n_byte_size, int e_byte_size, unsigned error_code = sgx_ipp_newBN(NULL, n_byte_size / 2, &bn_iqmp); ERROR_BREAK(error_code); - //generate RSA key components with n_byte_size modulus and p_e public exponent + // generate RSA key components with n_byte_size modulus and p_e public exponent // - do { + do + { // generate keys // ippsRSA_GenerateKeys() may return ippStsInsufficientEntropy. // In that case, we need to retry the API error_code = ippsRSA_GenerateKeys(bn_e_s, - bn_n, - bn_e, - bn_d, - p_pri_key, - scratch_buffer, - 1, - p_prime, - sgx_ipp_DRNGen, - NULL); + bn_n, + bn_e, + bn_d, + p_pri_key, + scratch_buffer, + 1, + p_prime, + sgx_ipp_DRNGen, + NULL); } while (error_code == ippStsInsufficientEntropy); ERROR_BREAK(error_code); - //extract private key components into BNs + // extract private key components into BNs // error_code = ippsRSA_GetPrivateKeyType2(bn_p, - bn_q, - bn_dmp1, - bn_dmq1, - bn_iqmp, - p_pri_key); + bn_q, + bn_dmp1, + bn_dmq1, + bn_iqmp, + p_pri_key); ERROR_BREAK(error_code); - //extract RSA components from BNs into output buffers + // extract RSA components from BNs into output buffers // error_code = ippsGetSize_BN(bn_n, &size); ERROR_BREAK(error_code); - error_code = ippsGet_BN(&sgn, &size, (Ipp32u*)p_n, bn_n); + error_code = ippsGet_BN(&sgn, &size, (Ipp32u *)p_n, bn_n); ERROR_BREAK(error_code); error_code = ippsGetSize_BN(bn_e, &size); ERROR_BREAK(error_code); - error_code = ippsGet_BN(&sgn, &size, (Ipp32u*)p_e, bn_e); + error_code = ippsGet_BN(&sgn, &size, (Ipp32u *)p_e, bn_e); ERROR_BREAK(error_code); error_code = ippsGetSize_BN(bn_d, &size); ERROR_BREAK(error_code); - error_code = ippsGet_BN(&sgn, &size, (Ipp32u*)p_d, bn_d); + error_code = ippsGet_BN(&sgn, &size, (Ipp32u *)p_d, bn_d); ERROR_BREAK(error_code); error_code = ippsGetSize_BN(bn_p, &size); ERROR_BREAK(error_code); - error_code = ippsGet_BN(&sgn, &size, (Ipp32u*)p_p, bn_p); + error_code = ippsGet_BN(&sgn, &size, (Ipp32u *)p_p, bn_p); ERROR_BREAK(error_code); error_code = ippsGetSize_BN(bn_q, &size); ERROR_BREAK(error_code); - error_code = ippsGet_BN(&sgn, &size, (Ipp32u*)p_q, bn_q); + error_code = ippsGet_BN(&sgn, &size, (Ipp32u *)p_q, bn_q); ERROR_BREAK(error_code); error_code = ippsGetSize_BN(bn_dmp1, &size); ERROR_BREAK(error_code); - error_code = ippsGet_BN(&sgn, &size, (Ipp32u*)p_dmp1, bn_dmp1); + error_code = ippsGet_BN(&sgn, &size, (Ipp32u *)p_dmp1, bn_dmp1); ERROR_BREAK(error_code); error_code = ippsGetSize_BN(bn_dmq1, &size); ERROR_BREAK(error_code); - error_code = ippsGet_BN(&sgn, &size, (Ipp32u*)p_dmq1, bn_dmq1); + error_code = ippsGet_BN(&sgn, &size, (Ipp32u *)p_dmq1, bn_dmq1); ERROR_BREAK(error_code); error_code = ippsGetSize_BN(bn_iqmp, &size); ERROR_BREAK(error_code); - error_code = ippsGet_BN(&sgn, &size, (Ipp32u*)p_iqmp, bn_iqmp); + error_code = ippsGet_BN(&sgn, &size, (Ipp32u *)p_iqmp, bn_iqmp); ERROR_BREAK(error_code); ret_code = SGX_SUCCESS; @@ -203,9 +248,9 @@ sgx_status_t sgx_create_rsa_key_pair(int n_byte_size, int e_byte_size, unsigned return ret_code; } -sgx_status_t sgx_create_rsa_priv2_key(int mod_size, int exp_size, const unsigned char *p_rsa_key_e, const unsigned char *p_rsa_key_p, const unsigned char *p_rsa_key_q, - const unsigned char *p_rsa_key_dmp1, const unsigned char *p_rsa_key_dmq1, const unsigned char *p_rsa_key_iqmp, - void **new_pri_key2) +sgx_status_t sgx_create_rsa_priv2_key(int mod_size, int exp_size, const unsigned char *p_rsa_key_e, const unsigned char *p_rsa_key_p, + const unsigned char *p_rsa_key_q, const unsigned char *p_rsa_key_dmp1, const unsigned char *p_rsa_key_dmq1, + const unsigned char *p_rsa_key_iqmp, void **new_pri_key2) { (void)(exp_size); (void)(p_rsa_key_e); @@ -213,27 +258,32 @@ sgx_status_t sgx_create_rsa_priv2_key(int mod_size, int exp_size, const unsigned IppsBigNumState *p_p = NULL, *p_q = NULL, *p_dmp1 = NULL, *p_dmq1 = NULL, *p_iqmp = NULL; int rsa2_size = 0; sgx_status_t ret_code = SGX_ERROR_UNEXPECTED; - if (mod_size <= 0 || p_rsa_key_p == NULL || p_rsa_key_q == NULL || p_rsa_key_dmp1 == NULL || p_rsa_key_dmq1 == NULL || p_rsa_key_iqmp == NULL || new_pri_key2 == NULL) { + if (mod_size <= 0 || p_rsa_key_p == NULL || p_rsa_key_q == NULL || p_rsa_key_dmp1 == NULL || p_rsa_key_dmq1 == NULL + || p_rsa_key_iqmp == NULL || new_pri_key2 == NULL) + { return SGX_ERROR_INVALID_PARAMETER; } + fips_self_test_rsa_encrypt_decrypt(); + IppStatus error_code = ippStsNoErr; - do { + do + { - //generate and assign RSA components BNs + // generate and assign RSA components BNs // - error_code = sgx_ipp_newBN((const Ipp32u*)p_rsa_key_p, mod_size / 2, &p_p); + error_code = sgx_ipp_newBN((const Ipp32u *)p_rsa_key_p, mod_size / 2, &p_p); ERROR_BREAK(error_code); - error_code = sgx_ipp_newBN((const Ipp32u*)p_rsa_key_q, mod_size / 2, &p_q); + error_code = sgx_ipp_newBN((const Ipp32u *)p_rsa_key_q, mod_size / 2, &p_q); ERROR_BREAK(error_code); - error_code = sgx_ipp_newBN((const Ipp32u*)p_rsa_key_dmp1, mod_size / 2, &p_dmp1); + error_code = sgx_ipp_newBN((const Ipp32u *)p_rsa_key_dmp1, mod_size / 2, &p_dmp1); ERROR_BREAK(error_code); - error_code = sgx_ipp_newBN((const Ipp32u*)p_rsa_key_dmq1, mod_size / 2, &p_dmq1); + error_code = sgx_ipp_newBN((const Ipp32u *)p_rsa_key_dmq1, mod_size / 2, &p_dmq1); ERROR_BREAK(error_code); - error_code = sgx_ipp_newBN((const Ipp32u*)p_rsa_key_iqmp, mod_size / 2, &p_iqmp); + error_code = sgx_ipp_newBN((const Ipp32u *)p_rsa_key_iqmp, mod_size / 2, &p_iqmp); ERROR_BREAK(error_code); - //allocate and initialize private key of type 2 + // allocate and initialize private key of type 2 // error_code = ippsRSA_GetSizePrivateKeyType2(mod_size / 2 * 8, mod_size / 2 * 8, &rsa2_size); ERROR_BREAK(error_code); @@ -246,11 +296,11 @@ sgx_status_t sgx_create_rsa_priv2_key(int mod_size, int exp_size, const unsigned error_code = ippsRSA_InitPrivateKeyType2(mod_size / 2 * 8, mod_size / 2 * 8, p_rsa2, rsa2_size); ERROR_BREAK(error_code); - //setup private key with values of input components + // setup private key with values of input components // error_code = ippsRSA_SetPrivateKeyType2(p_p, p_q, p_dmp1, p_dmq1, p_iqmp, p_rsa2); ERROR_BREAK(error_code); - *new_pri_key2 = (void*)p_rsa2; + *new_pri_key2 = (void *)p_rsa2; ret_code = SGX_SUCCESS; } while (0); @@ -261,37 +311,44 @@ sgx_status_t sgx_create_rsa_priv2_key(int mod_size, int exp_size, const unsigned sgx_ipp_secure_free_BN(p_dmq1, mod_size / 2); sgx_ipp_secure_free_BN(p_iqmp, mod_size / 2); - if (error_code == ippStsMemAllocErr) { + if (error_code == ippStsMemAllocErr) + { ret_code = SGX_ERROR_OUT_OF_MEMORY; } - if (ret_code != SGX_SUCCESS) { + if (ret_code != SGX_SUCCESS) + { secure_free_rsa_pri_key(p_rsa2); } return ret_code; } -sgx_status_t sgx_create_rsa_pub1_key(int mod_size, int exp_size, const unsigned char *le_n, const unsigned char *le_e, void **new_pub_key1) +sgx_status_t sgx_create_rsa_pub1_key(int mod_size, int exp_size, const unsigned char *le_n, + const unsigned char *le_e, void **new_pub_key1) { - if (new_pub_key1 == NULL || mod_size <= 0 || exp_size <= 0 || le_n == NULL || le_e == NULL) { + if (new_pub_key1 == NULL || mod_size <= 0 || exp_size <= 0 || le_n == NULL || le_e == NULL) + { return SGX_ERROR_INVALID_PARAMETER; } + fips_self_test_rsa_encrypt_decrypt(); + IppsRSAPublicKeyState *p_pub_key = NULL; IppsBigNumState *p_n = NULL, *p_e = NULL; int rsa_size = 0; sgx_status_t ret_code = SGX_ERROR_UNEXPECTED; IppStatus error_code = ippStsNoErr; - do { + do + { - //generate and assign RSA components BNs + // generate and assign RSA components BNs // - error_code = sgx_ipp_newBN((const Ipp32u*)le_n, mod_size, &p_n); + error_code = sgx_ipp_newBN((const Ipp32u *)le_n, mod_size, &p_n); ERROR_BREAK(error_code); - error_code = sgx_ipp_newBN((const Ipp32u*)le_e, exp_size, &p_e); + error_code = sgx_ipp_newBN((const Ipp32u *)le_e, exp_size, &p_e); ERROR_BREAK(error_code); - //allocate and initialize public key + // allocate and initialize public key // error_code = ippsRSA_GetSizePublicKey(mod_size * 8, exp_size * 8, &rsa_size); ERROR_BREAK(error_code); @@ -304,12 +361,12 @@ sgx_status_t sgx_create_rsa_pub1_key(int mod_size, int exp_size, const unsigned error_code = ippsRSA_InitPublicKey(mod_size * 8, exp_size * 8, p_pub_key, rsa_size); ERROR_BREAK(error_code); - //setup public key with values of input components + // setup public key with values of input components // error_code = ippsRSA_SetPublicKey(p_n, p_e, p_pub_key); ERROR_BREAK(error_code); - *new_pub_key1 = (void*)p_pub_key; + *new_pub_key1 = (void *)p_pub_key; ret_code = SGX_SUCCESS; } while (0); @@ -319,57 +376,70 @@ sgx_status_t sgx_create_rsa_pub1_key(int mod_size, int exp_size, const unsigned if (error_code == ippStsMemAllocErr) ret_code = SGX_ERROR_OUT_OF_MEMORY; - if (ret_code != SGX_SUCCESS) { + if (ret_code != SGX_SUCCESS) + { secure_free_rsa_pub_key(mod_size, exp_size, p_pub_key); } return ret_code; } -sgx_status_t sgx_rsa_pub_encrypt_sha256(const void* rsa_key, unsigned char* pout_data, size_t* pout_len, const unsigned char* pin_data, - const size_t pin_len) { - if (rsa_key == NULL || pout_len == NULL || pin_data == NULL || pin_len < 1 || pin_len >= INT_MAX) { +sgx_status_t sgx_rsa_pub_encrypt_sha256(const void *rsa_key, unsigned char *pout_data, size_t *pout_len, + const unsigned char *pin_data, const size_t pin_len) +{ + if (rsa_key == NULL || pout_len == NULL || pin_data == NULL || pin_len < 1 || pin_len >= INT_MAX) + { return SGX_ERROR_INVALID_PARAMETER; } - IppsBigNumState* p_modulus = NULL; + fips_self_test_rsa_encrypt_decrypt(); + fips_self_test_hash256(); + + IppsBigNumState *p_modulus = NULL; int mod_len = 0; uint8_t *p_scratch_buffer = NULL; - Ipp8u seeds[RSA_SEED_SIZE_SHA256] = { 0 }; + Ipp8u seeds[RSA_SEED_SIZE_SHA256] = {0}; int scratch_buff_size = 0; sgx_status_t ret_code = SGX_ERROR_UNEXPECTED; - do { + do + { // - //create a new BN + // create a new BN // - if (sgx_ipp_newBN(NULL, MAX_IPP_BN_LENGTH, &p_modulus) != ippStsNoErr) { + if (sgx_ipp_newBN(NULL, MAX_IPP_BN_LENGTH, &p_modulus) != ippStsNoErr) + { break; } - //get public key modulus + // get public key modulus // - if (ippsRSA_GetPublicKey(p_modulus, NULL, (IppsRSAPublicKeyState*)rsa_key) != ippStsNoErr) { + if (ippsRSA_GetPublicKey(p_modulus, NULL, (IppsRSAPublicKeyState *)rsa_key) != ippStsNoErr) + { break; } - //get modulus length in bits + // get modulus length in bits // - if (ippsExtGet_BN(0, &mod_len, 0, p_modulus) != ippStsNoErr) { + if (ippsExtGet_BN(0, &mod_len, 0, p_modulus) != ippStsNoErr) + { break; } - if (pout_data == NULL) { + if (pout_data == NULL) + { // return required pout_data buffer size *pout_len = mod_len / 8; ret_code = SGX_SUCCESS; break; } - else if (*pout_len < (size_t)(mod_len / 8)) { + else if (*pout_len < (size_t)(mod_len / 8)) + { ret_code = SGX_ERROR_INVALID_PARAMETER; break; } - //get scratch buffer size, to be used as temp buffer, and allocate it + // get scratch buffer size, to be used as temp buffer, and allocate it // - if (ippsRSA_GetBufferSizePublicKey(&scratch_buff_size, (IppsRSAPublicKeyState*)rsa_key) != ippStsNoErr) { + if (ippsRSA_GetBufferSizePublicKey(&scratch_buff_size, (IppsRSAPublicKeyState *)rsa_key) != ippStsNoErr) + { break; } p_scratch_buffer = (uint8_t *)malloc(scratch_buff_size); @@ -380,19 +450,21 @@ sgx_status_t sgx_rsa_pub_encrypt_sha256(const void* rsa_key, unsigned char* pout } memset(p_scratch_buffer, 0, scratch_buff_size); - //get random seed + // get random seed // - if (sgx_read_rand(seeds, RSA_SEED_SIZE_SHA256) != SGX_SUCCESS) { + if (sgx_read_rand(seeds, RSA_SEED_SIZE_SHA256) != SGX_SUCCESS) + { break; } - //encrypt input data with public rsa_key and SHA256 padding + // encrypt input data with public rsa_key and SHA256 padding // if (ippsRSAEncrypt_OAEP_rmf(pin_data, (int)pin_len, NULL, 0, seeds, - pout_data, (IppsRSAPublicKeyState*)rsa_key, ippsHashMethod_SHA256_TT(), p_scratch_buffer) != ippStsNoErr) { + pout_data, (IppsRSAPublicKeyState *)rsa_key, ippsHashMethod_SHA256_TT(), p_scratch_buffer) != ippStsNoErr) + { break; } - *pout_len = mod_len / 8; + *pout_len = mod_len / 8; ret_code = SGX_SUCCESS; } while (0); @@ -402,68 +474,76 @@ sgx_status_t sgx_rsa_pub_encrypt_sha256(const void* rsa_key, unsigned char* pout sgx_ipp_secure_free_BN(p_modulus, MAX_IPP_BN_LENGTH); return ret_code; } -sgx_status_t sgx_rsa_priv_decrypt_sha256(const void* rsa_key, unsigned char* pout_data, size_t* pout_len, const unsigned char* pin_data, - const size_t pin_len) { +sgx_status_t sgx_rsa_priv_decrypt_sha256(const void *rsa_key, unsigned char *pout_data, size_t *pout_len, + const unsigned char *pin_data, const size_t pin_len) +{ (void)(pin_len); - if (rsa_key == NULL || pout_len == NULL || pin_data == NULL) { + if (rsa_key == NULL || pout_len == NULL || pin_data == NULL) + { return SGX_ERROR_INVALID_PARAMETER; } - IppsBigNumState* p_bn = NULL; + fips_self_test_rsa_encrypt_decrypt(); + fips_self_test_hash256(); + + IppsBigNumState *p_bn = NULL; int dataLen = 0; int factor = 1; sgx_status_t ret_code = SGX_ERROR_UNEXPECTED; uint8_t *p_scratch_buffer = NULL; int scratch_buff_size = 0; - do { - //create a new BN + do + { + // create a new BN // if (sgx_ipp_newBN(NULL, MAX_IPP_BN_LENGTH, &p_bn) != ippStsNoErr) { break; } - //get private key modulus or prime factor P + // get private key modulus or prime factor P // - if (ippsRSA_GetPrivateKeyType1(p_bn, NULL, (IppsRSAPrivateKeyState*)rsa_key) != ippStsNoErr) + if (ippsRSA_GetPrivateKeyType1(p_bn, NULL, (IppsRSAPrivateKeyState *)rsa_key) != ippStsNoErr) { - if (ippsRSA_GetPrivateKeyType2(p_bn, NULL, NULL, NULL, NULL, (IppsRSAPrivateKeyState*)rsa_key) != ippStsNoErr) + if (ippsRSA_GetPrivateKeyType2(p_bn, NULL, NULL, NULL, NULL, (IppsRSAPrivateKeyState *)rsa_key) != ippStsNoErr) { break; } else { - //we're working with prime number and not modulus, need to multiply length by 2 + // we're working with prime number and not modulus, need to multiply length by 2 // factor = 2; } } - //get modulus or prime factor P bits length + // get modulus or prime factor P bits length // if (ippsExtGet_BN(0, &dataLen, 0, p_bn) != ippStsNoErr) { break; } - + // output buffer is NULL, return required pout_data buffer size // - if (pout_data == NULL) { - //calculate pout_len based on RSA factors size and return. - // convert bits to bytes, in case of working with P, multiply by factor=2. + if (pout_data == NULL) + { + // calculate pout_len based on RSA factors size and return. + // convert bits to bytes, in case of working with P, multiply by factor=2. // *pout_len = dataLen / 8 * factor; ret_code = SGX_SUCCESS; break; } - else if(*pout_len < (size_t)(dataLen / 8 * factor)) + else if (*pout_len < (size_t)(dataLen / 8 * factor)) { ret_code = SGX_ERROR_INVALID_PARAMETER; break; } - //get scratch buffer size, to be used as temp buffer, and allocate it + // get scratch buffer size, to be used as temp buffer, and allocate it // - if (ippsRSA_GetBufferSizePrivateKey(&scratch_buff_size, (IppsRSAPrivateKeyState*)rsa_key) != ippStsNoErr) { + if (ippsRSA_GetBufferSizePrivateKey(&scratch_buff_size, (IppsRSAPrivateKeyState *)rsa_key) != ippStsNoErr) + { break; } p_scratch_buffer = (uint8_t *)malloc(scratch_buff_size); @@ -473,9 +553,10 @@ sgx_status_t sgx_rsa_priv_decrypt_sha256(const void* rsa_key, unsigned char* pou break; } - //decrypt input ciphertext using private key rsa_key - if (ippsRSADecrypt_OAEP_rmf(pin_data, NULL, 0, pout_data, (int*)pout_len, (IppsRSAPrivateKeyState*)rsa_key, - ippsHashMethod_SHA256_TT(), p_scratch_buffer) != ippStsNoErr) { + // decrypt input ciphertext using private key rsa_key + if (ippsRSADecrypt_OAEP_rmf(pin_data, NULL, 0, pout_data, (int *)pout_len, (IppsRSAPrivateKeyState *)rsa_key, + ippsHashMethod_SHA256_TT(), p_scratch_buffer) != ippStsNoErr) + { break; } ret_code = SGX_SUCCESS; @@ -487,13 +568,15 @@ sgx_status_t sgx_rsa_priv_decrypt_sha256(const void* rsa_key, unsigned char* pou return ret_code; } -sgx_status_t sgx_create_rsa_priv1_key(int n_byte_size, int e_byte_size, int d_byte_size, const unsigned char *le_n, const unsigned char *le_e, - const unsigned char *le_d, void **new_pri_key1) +sgx_status_t sgx_create_rsa_priv1_key(int n_byte_size, int e_byte_size, int d_byte_size, const unsigned char *le_n, + const unsigned char *le_e, const unsigned char *le_d, void **new_pri_key1) { if (n_byte_size <= 0 || e_byte_size <= 0 || d_byte_size <= 0 || new_pri_key1 == NULL || - le_n == NULL || le_e == NULL || le_d == NULL) { + le_n == NULL || le_e == NULL || le_d == NULL) + { return SGX_ERROR_INVALID_PARAMETER; } + fips_self_test_rsa_encrypt_decrypt(); IppsRSAPrivateKeyState *p_rsa1 = NULL; IppsBigNumState *p_n = NULL, *p_d = NULL; @@ -501,19 +584,21 @@ sgx_status_t sgx_create_rsa_priv1_key(int n_byte_size, int e_byte_size, int d_by sgx_status_t ret_code = SGX_ERROR_UNEXPECTED; IppStatus error_code = ippStsErr; - do { + do + { - //generate and assign RSA components BNs + // generate and assign RSA components BNs // - error_code = sgx_ipp_newBN((const Ipp32u*)le_n, n_byte_size, &p_n); + error_code = sgx_ipp_newBN((const Ipp32u *)le_n, n_byte_size, &p_n); ERROR_BREAK(error_code); - error_code = sgx_ipp_newBN((const Ipp32u*)le_d, d_byte_size, &p_d); + error_code = sgx_ipp_newBN((const Ipp32u *)le_d, d_byte_size, &p_d); ERROR_BREAK(error_code); - //allocate and init private key of type 1 + // allocate and init private key of type 1 // error_code = ippsRSA_GetSizePrivateKeyType1(n_byte_size * 8, d_byte_size * 8, &rsa1_size); - if (error_code != ippStsNoErr || rsa1_size <= 0) { + if (error_code != ippStsNoErr || rsa1_size <= 0) + { break; } p_rsa1 = (IppsRSAPrivateKeyState *)malloc(rsa1_size); @@ -525,7 +610,7 @@ sgx_status_t sgx_create_rsa_priv1_key(int n_byte_size, int e_byte_size, int d_by error_code = ippsRSA_InitPrivateKeyType1(n_byte_size * 8, d_byte_size * 8, p_rsa1, rsa1_size); ERROR_BREAK(error_code); - //setup private key with values of input components + // setup private key with values of input components // error_code = ippsRSA_SetPrivateKeyType1(p_n, p_d, p_rsa1); ERROR_BREAK(error_code); @@ -537,9 +622,11 @@ sgx_status_t sgx_create_rsa_priv1_key(int n_byte_size, int e_byte_size, int d_by sgx_ipp_secure_free_BN(p_n, n_byte_size); sgx_ipp_secure_free_BN(p_d, d_byte_size); - if (ret_code != SGX_SUCCESS) { + if (ret_code != SGX_SUCCESS) + { secure_free_rsa_pri_key(p_rsa1); - if (error_code == ippStsMemAllocErr) { + if (error_code == ippStsMemAllocErr) + { ret_code = SGX_ERROR_OUT_OF_MEMORY; } } @@ -547,14 +634,20 @@ sgx_status_t sgx_create_rsa_priv1_key(int n_byte_size, int e_byte_size, int d_by return ret_code; } +sgx_status_t sgx_free_rsa_key(void *p_rsa_key, sgx_rsa_key_type_t key_type, int mod_size, int exp_size) +{ + + fips_self_test_rsa_encrypt_decrypt(); -sgx_status_t sgx_free_rsa_key(void *p_rsa_key, sgx_rsa_key_type_t key_type, int mod_size, int exp_size) { - if (key_type == SGX_RSA_PRIVATE_KEY) { - (void)(exp_size); - secure_free_rsa_pri_key((IppsRSAPrivateKeyState*)p_rsa_key); - } else if (key_type == SGX_RSA_PUBLIC_KEY) { - secure_free_rsa_pub_key(mod_size, exp_size, (IppsRSAPublicKeyState*)p_rsa_key); - } + if (key_type == SGX_RSA_PRIVATE_KEY) + { + (void)(exp_size); + secure_free_rsa_pri_key((IppsRSAPrivateKeyState *)p_rsa_key); + } + else if (key_type == SGX_RSA_PUBLIC_KEY) + { + secure_free_rsa_pub_key(mod_size, exp_size, (IppsRSAPublicKeyState *)p_rsa_key); + } - return SGX_SUCCESS; + return SGX_SUCCESS; } diff --git a/sdk/tlibcrypto/ipp/sgx_rsa_internal.cpp b/sdk/tlibcrypto/ipp/sgx_rsa_internal.cpp index fc7148487..354e4629b 100644 --- a/sdk/tlibcrypto/ipp/sgx_rsa_internal.cpp +++ b/sdk/tlibcrypto/ipp/sgx_rsa_internal.cpp @@ -34,13 +34,11 @@ #include "ippcp.h" #include "ipp_wrapper.h" - extern "C" void secure_free_rsa_pri_key(IppsRSAPrivateKeyState *pri_key) { if (pri_key == NULL) { return; } - IppsBigNumState* p_bn_mod = NULL; IppsBigNumState* p_bn_p = NULL; IppsBigNumState* p_bn_exp = NULL; diff --git a/sdk/tlibcrypto/ipp/sgx_sha256.cpp b/sdk/tlibcrypto/ipp/sgx_sha256.cpp index 59f338003..14169c3b9 100644 --- a/sdk/tlibcrypto/ipp/sgx_sha256.cpp +++ b/sdk/tlibcrypto/ipp/sgx_sha256.cpp @@ -32,29 +32,66 @@ #include "ippcp.h" #include "sgx_tcrypto.h" #include "stdlib.h" +#include "sgx_fips_internal.h" #ifndef SAFE_FREE -#define SAFE_FREE(ptr) {if (NULL != (ptr)) {free(ptr); (ptr)=NULL;}} +#define SAFE_FREE(ptr) \ + { \ + if (NULL != (ptr)) \ + { \ + free(ptr); \ + (ptr) = NULL; \ + } \ + } #endif +void fips_self_test_hash256() +{ + static bool fips_selftest_hash256_flag = false; + + if (g_global_data.fips_on != 0 && fips_selftest_hash256_flag == false) + { + sgx_status_t ret = SGX_ERROR_UNEXPECTED; + fips_test_status test_result = IPPCP_ALGO_SELFTEST_OK; + int buf_size = 0; + uint8_t *p_buf = NULL; + + do + { + FIPS_SELFTEST_FUNC_1(test_result, fips_selftest_ippsHash_rmf_get_size, &buf_size); + p_buf = (uint8_t *)malloc(buf_size); + FIPS_SELFTEST_FUNC_2(test_result, fips_selftest_ippsHashUpdate_rmf, (IppHashAlgId)ippHashAlg_SHA256, p_buf); + FIPS_SELFTEST_FUNC_1(test_result, fips_selftest_ippsHashMessage_rmf, (IppHashAlgId)ippHashAlg_SHA256); + + ret = SGX_SUCCESS; + fips_selftest_hash256_flag = true; + + } while (0); + SAFE_FREE(p_buf); + ERROR_ABORT(ret); + } + return; +} /* Allocates and initializes sha256 state -* Parameters: -* Return: sgx_status_t - SGX_SUCCESS or failure as defined in sgx_error.h -* Output: sgx_sha_state_handle_t *p_sha_handle - Pointer to the handle of the SHA256 state */ -sgx_status_t sgx_sha256_init(sgx_sha_state_handle_t* p_sha_handle) + * Parameters: + * Return: sgx_status_t - SGX_SUCCESS or failure as defined in sgx_error.h + * Output: sgx_sha_state_handle_t *p_sha_handle - Pointer to the handle of the SHA256 state */ +sgx_status_t sgx_sha256_init(sgx_sha_state_handle_t *p_sha_handle) { IppStatus ipp_ret = ippStsNoErr; - IppsHashState_rmf* p_temp_state = NULL; + IppsHashState_rmf *p_temp_state = NULL; if (p_sha_handle == NULL) return SGX_ERROR_INVALID_PARAMETER; + fips_self_test_hash256(); + int ctx_size = 0; ipp_ret = ippsHashGetSize_rmf(&ctx_size); if (ipp_ret != ippStsNoErr) return SGX_ERROR_UNEXPECTED; - p_temp_state = (IppsHashState_rmf*)(malloc(ctx_size)); + p_temp_state = (IppsHashState_rmf *)(malloc(ctx_size)); if (p_temp_state == NULL) return SGX_ERROR_OUT_OF_MEMORY; ipp_ret = ippsHashInit_rmf(p_temp_state, ippsHashMethod_SHA256_TT()); @@ -65,8 +102,10 @@ sgx_status_t sgx_sha256_init(sgx_sha_state_handle_t* p_sha_handle) switch (ipp_ret) { case ippStsNullPtrErr: - case ippStsLengthErr: return SGX_ERROR_INVALID_PARAMETER; - default: return SGX_ERROR_UNEXPECTED; + case ippStsLengthErr: + return SGX_ERROR_INVALID_PARAMETER; + default: + return SGX_ERROR_UNEXPECTED; } } @@ -75,54 +114,66 @@ sgx_status_t sgx_sha256_init(sgx_sha_state_handle_t* p_sha_handle) } /* Updates sha256 has calculation based on the input message -* Parameters: -* Return: sgx_status_t - SGX_SUCCESS or failure as defined in sgx_error. -* Input: sgx_sha_state_handle_t sha_handle - Handle to the SHA256 state -* uint8_t *p_src - Pointer to the input stream to be hashed -* uint32_t src_len - Length of the input stream to be hashed */ + * Parameters: + * Return: sgx_status_t - SGX_SUCCESS or failure as defined in sgx_error. + * Input: sgx_sha_state_handle_t sha_handle - Handle to the SHA256 state + * uint8_t *p_src - Pointer to the input stream to be hashed + * uint32_t src_len - Length of the input stream to be hashed */ sgx_status_t sgx_sha256_update(const uint8_t *p_src, uint32_t src_len, sgx_sha_state_handle_t sha_handle) { if ((p_src == NULL) || (sha_handle == NULL)) { return SGX_ERROR_INVALID_PARAMETER; } + + fips_self_test_hash256(); + IppStatus ipp_ret = ippStsNoErr; - ipp_ret = ippsHashUpdate_rmf(p_src, src_len, (IppsHashState_rmf*)sha_handle); + ipp_ret = ippsHashUpdate_rmf(p_src, src_len, (IppsHashState_rmf *)sha_handle); switch (ipp_ret) { - case ippStsNoErr: return SGX_SUCCESS; + case ippStsNoErr: + return SGX_SUCCESS; case ippStsNullPtrErr: - case ippStsLengthErr: return SGX_ERROR_INVALID_PARAMETER; - default: return SGX_ERROR_UNEXPECTED; + case ippStsLengthErr: + return SGX_ERROR_INVALID_PARAMETER; + default: + return SGX_ERROR_UNEXPECTED; } } /* Returns Hash calculation -* Parameters: -* Return: sgx_status_t - SGX_SUCCESS or failure as defined in sgx_error.h -* Input: sgx_sha_state_handle_t sha_handle - Handle to the SHA256 state -* Output: sgx_sha256_hash_t *p_hash - Resultant hash from operation */ + * Parameters: + * Return: sgx_status_t - SGX_SUCCESS or failure as defined in sgx_error.h + * Input: sgx_sha_state_handle_t sha_handle - Handle to the SHA256 state + * Output: sgx_sha256_hash_t *p_hash - Resultant hash from operation */ sgx_status_t sgx_sha256_get_hash(sgx_sha_state_handle_t sha_handle, sgx_sha256_hash_t *p_hash) { if ((sha_handle == NULL) || (p_hash == NULL)) { return SGX_ERROR_INVALID_PARAMETER; } + + fips_self_test_hash256(); + IppStatus ipp_ret = ippStsNoErr; - ipp_ret = ippsHashGetTag_rmf((Ipp8u*)p_hash, SGX_SHA256_HASH_SIZE, (IppsHashState_rmf*)sha_handle); + ipp_ret = ippsHashGetTag_rmf((Ipp8u *)p_hash, SGX_SHA256_HASH_SIZE, (IppsHashState_rmf *)sha_handle); switch (ipp_ret) { - case ippStsNoErr: return SGX_SUCCESS; + case ippStsNoErr: + return SGX_SUCCESS; case ippStsNullPtrErr: - case ippStsLengthErr: return SGX_ERROR_INVALID_PARAMETER; - default: return SGX_ERROR_UNEXPECTED; + case ippStsLengthErr: + return SGX_ERROR_INVALID_PARAMETER; + default: + return SGX_ERROR_UNEXPECTED; } } /* Cleans up sha state -* Parameters: -* Return: sgx_status_t - SGX_SUCCESS or failure as defined in sgx_error.h -* Input: sgx_sha_state_handle_t sha_handle - Handle to the SHA256 state */ + * Parameters: + * Return: sgx_status_t - SGX_SUCCESS or failure as defined in sgx_error.h + * Input: sgx_sha_state_handle_t sha_handle - Handle to the SHA256 state */ sgx_status_t sgx_sha256_close(sgx_sha_state_handle_t sha_handle) { if (sha_handle == NULL) diff --git a/sdk/tlibcrypto/ipp/sgx_sha256_msg.cpp b/sdk/tlibcrypto/ipp/sgx_sha256_msg.cpp index 81af4a727..e08d1b936 100644 --- a/sdk/tlibcrypto/ipp/sgx_sha256_msg.cpp +++ b/sdk/tlibcrypto/ipp/sgx_sha256_msg.cpp @@ -33,6 +33,7 @@ #include "sgx_tcrypto.h" #include "ippcp.h" #include "stdlib.h" +#include "sgx_fips_internal.h" #ifndef SAFE_FREE #define SAFE_FREE(ptr) {if (NULL != (ptr)) {free(ptr); (ptr)=NULL;}} @@ -52,6 +53,8 @@ sgx_status_t sgx_sha256_msg(const uint8_t *p_src, uint32_t src_len, sgx_sha256_h return SGX_ERROR_INVALID_PARAMETER; } + fips_self_test_hash256(); + IppStatus ipp_ret = ippStsNoErr; ipp_ret = ippsHashMessage_rmf((const Ipp8u *) p_src, src_len, (Ipp8u *)p_hash, ippsHashMethod_SHA256_TT()); switch (ipp_ret) diff --git a/sdk/tlibcrypto/ipp/sgx_sha384.cpp b/sdk/tlibcrypto/ipp/sgx_sha384.cpp index f2fda9fb2..1dc12b814 100644 --- a/sdk/tlibcrypto/ipp/sgx_sha384.cpp +++ b/sdk/tlibcrypto/ipp/sgx_sha384.cpp @@ -32,29 +32,59 @@ #include "ippcp.h" #include "sgx_tcrypto.h" #include "stdlib.h" +#include "sgx_fips_internal.h" #ifndef SAFE_FREE #define SAFE_FREE(ptr) {if (NULL != (ptr)) {free(ptr); (ptr)=NULL;}} #endif +void fips_self_test_hash384() +{ + static bool fips_selftest_hash384_flag = false; + + if (g_global_data.fips_on != 0 && fips_selftest_hash384_flag == false) + { + sgx_status_t ret = SGX_ERROR_UNEXPECTED; + fips_test_status test_result = IPPCP_ALGO_SELFTEST_OK; + int buf_size = 0; + uint8_t *p_buf = NULL; + + do + { + FIPS_SELFTEST_FUNC_1(test_result, fips_selftest_ippsHash_rmf_get_size, &buf_size); + p_buf = (uint8_t *)malloc(buf_size); + FIPS_SELFTEST_FUNC_2(test_result, fips_selftest_ippsHashUpdate_rmf, (IppHashAlgId)ippHashAlg_SHA384, p_buf); + FIPS_SELFTEST_FUNC_1(test_result, fips_selftest_ippsHashMessage_rmf, (IppHashAlgId)ippHashAlg_SHA384); + + ret = SGX_SUCCESS; + fips_selftest_hash384_flag = true; + + } while (0); + SAFE_FREE(p_buf); + ERROR_ABORT(ret); + } + return; +} /* Allocates and initializes sha384 state -* Parameters: -* Return: sgx_status_t - SGX_SUCCESS or failure as defined in sgx_error.h -* Output: sgx_sha_state_handle_t *p_sha_handle - Pointer to the handle of the SHA384 state */ -sgx_status_t sgx_sha384_init(sgx_sha_state_handle_t* p_sha_handle) + * Parameters: + * Return: sgx_status_t - SGX_SUCCESS or failure as defined in sgx_error.h + * Output: sgx_sha_state_handle_t *p_sha_handle - Pointer to the handle of the SHA384 state */ +sgx_status_t sgx_sha384_init(sgx_sha_state_handle_t *p_sha_handle) { IppStatus ipp_ret = ippStsNoErr; - IppsHashState_rmf* p_temp_state = NULL; + IppsHashState_rmf *p_temp_state = NULL; if (p_sha_handle == NULL) return SGX_ERROR_INVALID_PARAMETER; + fips_self_test_hash384(); + int ctx_size = 0; ipp_ret = ippsHashGetSize_rmf(&ctx_size); if (ipp_ret != ippStsNoErr) return SGX_ERROR_UNEXPECTED; - p_temp_state = (IppsHashState_rmf*)(malloc(ctx_size)); + p_temp_state = (IppsHashState_rmf *)(malloc(ctx_size)); if (p_temp_state == NULL) return SGX_ERROR_OUT_OF_MEMORY; ipp_ret = ippsHashInit_rmf(p_temp_state, ippsHashMethod_SHA384()); @@ -65,8 +95,10 @@ sgx_status_t sgx_sha384_init(sgx_sha_state_handle_t* p_sha_handle) switch (ipp_ret) { case ippStsNullPtrErr: - case ippStsLengthErr: return SGX_ERROR_INVALID_PARAMETER; - default: return SGX_ERROR_UNEXPECTED; + case ippStsLengthErr: + return SGX_ERROR_INVALID_PARAMETER; + default: + return SGX_ERROR_UNEXPECTED; } } @@ -75,54 +107,66 @@ sgx_status_t sgx_sha384_init(sgx_sha_state_handle_t* p_sha_handle) } /* Updates sha384 has calculation based on the input message -* Parameters: -* Return: sgx_status_t - SGX_SUCCESS or failure as defined in sgx_error. -* Input: sgx_sha_state_handle_t sha_handle - Handle to the SHA384 state -* uint8_t *p_src - Pointer to the input stream to be hashed -* uint32_t src_len - Length of the input stream to be hashed */ + * Parameters: + * Return: sgx_status_t - SGX_SUCCESS or failure as defined in sgx_error. + * Input: sgx_sha_state_handle_t sha_handle - Handle to the SHA384 state + * uint8_t *p_src - Pointer to the input stream to be hashed + * uint32_t src_len - Length of the input stream to be hashed */ sgx_status_t sgx_sha384_update(const uint8_t *p_src, uint32_t src_len, sgx_sha_state_handle_t sha_handle) { if ((p_src == NULL) || (sha_handle == NULL)) { return SGX_ERROR_INVALID_PARAMETER; } + + fips_self_test_hash384(); + IppStatus ipp_ret = ippStsNoErr; - ipp_ret = ippsHashUpdate_rmf(p_src, src_len, (IppsHashState_rmf*)sha_handle); + ipp_ret = ippsHashUpdate_rmf(p_src, src_len, (IppsHashState_rmf *)sha_handle); switch (ipp_ret) { - case ippStsNoErr: return SGX_SUCCESS; + case ippStsNoErr: + return SGX_SUCCESS; case ippStsNullPtrErr: - case ippStsLengthErr: return SGX_ERROR_INVALID_PARAMETER; - default: return SGX_ERROR_UNEXPECTED; + case ippStsLengthErr: + return SGX_ERROR_INVALID_PARAMETER; + default: + return SGX_ERROR_UNEXPECTED; } } /* Returns Hash calculation -* Parameters: -* Return: sgx_status_t - SGX_SUCCESS or failure as defined in sgx_error.h -* Input: sgx_sha_state_handle_t sha_handle - Handle to the SHA384 state -* Output: sgx_sha384_hash_t *p_hash - Resultant hash from operation */ + * Parameters: + * Return: sgx_status_t - SGX_SUCCESS or failure as defined in sgx_error.h + * Input: sgx_sha_state_handle_t sha_handle - Handle to the SHA384 state + * Output: sgx_sha384_hash_t *p_hash - Resultant hash from operation */ sgx_status_t sgx_sha384_get_hash(sgx_sha_state_handle_t sha_handle, sgx_sha384_hash_t *p_hash) { if ((sha_handle == NULL) || (p_hash == NULL)) { return SGX_ERROR_INVALID_PARAMETER; } + + fips_self_test_hash384(); + IppStatus ipp_ret = ippStsNoErr; - ipp_ret = ippsHashGetTag_rmf((Ipp8u*)p_hash, SGX_SHA384_HASH_SIZE, (IppsHashState_rmf*)sha_handle); + ipp_ret = ippsHashGetTag_rmf((Ipp8u *)p_hash, SGX_SHA384_HASH_SIZE, (IppsHashState_rmf *)sha_handle); switch (ipp_ret) { - case ippStsNoErr: return SGX_SUCCESS; + case ippStsNoErr: + return SGX_SUCCESS; case ippStsNullPtrErr: - case ippStsLengthErr: return SGX_ERROR_INVALID_PARAMETER; - default: return SGX_ERROR_UNEXPECTED; + case ippStsLengthErr: + return SGX_ERROR_INVALID_PARAMETER; + default: + return SGX_ERROR_UNEXPECTED; } } /* Cleans up sha state -* Parameters: -* Return: sgx_status_t - SGX_SUCCESS or failure as defined in sgx_error.h -* Input: sgx_sha_state_handle_t sha_handle - Handle to the SHA384 state */ + * Parameters: + * Return: sgx_status_t - SGX_SUCCESS or failure as defined in sgx_error.h + * Input: sgx_sha_state_handle_t sha_handle - Handle to the SHA384 state */ sgx_status_t sgx_sha384_close(sgx_sha_state_handle_t sha_handle) { if (sha_handle == NULL) diff --git a/sdk/tlibcrypto/ipp/sgx_sha384_msg.cpp b/sdk/tlibcrypto/ipp/sgx_sha384_msg.cpp index 6d0db5f7d..039b1a2cc 100644 --- a/sdk/tlibcrypto/ipp/sgx_sha384_msg.cpp +++ b/sdk/tlibcrypto/ipp/sgx_sha384_msg.cpp @@ -33,6 +33,7 @@ #include "sgx_tcrypto.h" #include "ippcp.h" #include "stdlib.h" +#include "sgx_fips_internal.h" #ifndef SAFE_FREE #define SAFE_FREE(ptr) {if (NULL != (ptr)) {free(ptr); (ptr)=NULL;}} @@ -52,6 +53,8 @@ sgx_status_t sgx_sha384_msg(const uint8_t *p_src, uint32_t src_len, sgx_sha384_h return SGX_ERROR_INVALID_PARAMETER; } + fips_self_test_hash384(); + IppStatus ipp_ret = ippStsNoErr; ipp_ret = ippsHashMessage_rmf((const Ipp8u *) p_src, src_len, (Ipp8u *)p_hash, ippsHashMethod_SHA384()); switch (ipp_ret) diff --git a/sdk/tlibcrypto/sgxssl/sgx_fips.cpp b/sdk/tlibcrypto/sgxssl/sgx_fips.cpp index 98b1ff757..728e1870f 100644 --- a/sdk/tlibcrypto/sgxssl/sgx_fips.cpp +++ b/sdk/tlibcrypto/sgxssl/sgx_fips.cpp @@ -34,11 +34,6 @@ #include "global_data.h" #include "util.h" -extern "C" sgx_status_t sgx_crypto_fips_selftest() -{ - return SGX_ERROR_UNSUPPORTED_FUNCTION; -} - sgx_status_t sgx_is_fips_approved_func(sgx_fips_func_t func, func_fips_approved_t *is_approved) { UNUSED(func); diff --git a/sdk/tlibcxx/include/iostream b/sdk/tlibcxx/include/iostream index 16b5477c1..e01d67984 100644 --- a/sdk/tlibcxx/include/iostream +++ b/sdk/tlibcxx/include/iostream @@ -33,14 +33,14 @@ extern wostream wclog; */ -// Not supported in SGX. #include <__config> -#if !defined(_LIBCPP_SGX_CONFIG) #include #include #include #include +// Not supported in SGX. +#if !defined(_LIBCPP_SGX_CONFIG) #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER) #pragma GCC system_header #endif diff --git a/sdk/trts/init_enclave.cpp b/sdk/trts/init_enclave.cpp index 03b54c1c3..53c376a2f 100644 --- a/sdk/trts/init_enclave.cpp +++ b/sdk/trts/init_enclave.cpp @@ -61,9 +61,9 @@ uint64_t g_enclave_size __attribute__((section(RELRO_SECTION_NAME))) = 0; int g_aexnotify_supported __attribute__((section(RELRO_SECTION_NAME))) = 0; -const volatile global_data_t g_global_data __attribute__((section(".niprod"))) = {VERSION_UINT, 1, 2, 3, 4, 5, 6, 0, 0, 0, +volatile global_data_t g_global_data __attribute__((section(".nipd"))) = {VERSION_UINT, 1, 2, 3, 4, 5, 6, 0, 0, 0, {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, {0, 0, 0, 0, 0, 0}, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, 0, 0, - {{{0, 0, 0, 0, 0, 0, 0}}}, 0, 0, 0, 0}; + {{{0, 0, 0, 0, 0, 0, 0}}}, 0, 0, 0, 0, 0, 0}; // Make sure to access this with atomics or the {get,set}_enclave_state assembly wrappers. uint32_t g_enclave_state __attribute__((section(".nipd"))) = ENCLAVE_INIT_NOT_STARTED; @@ -120,18 +120,19 @@ extern "C" int init_enclave(void *enclave_base, void *ms) } g_enclave_base = (uint64_t)get_enclave_base(); - g_enclave_size = g_global_data.elrange_size; - //we are not allowed to set enclave_image_address to 0 if elrange is set - //so if enclave_image_address is 0, it means elrange is not set - if(g_global_data.enclave_image_address != 0) + g_enclave_size = g_global_data.enclave_size; + + // If elrange_size is not 0, it means elrange is set + if(g_global_data.elrange_size != 0) { - //__ImageBase should be the same as enclave_start_address + //__ImageBase should be the same as enclave_image_address if(g_global_data.enclave_image_address != g_enclave_base) { abort(); } - //if elrange is set, we should set enclave_base to correct value + //if elrange is set, we should set enclave_base and enclave_size to correct value g_enclave_base = g_global_data.elrange_start_address; + g_enclave_size = g_global_data.elrange_size; } // Check if the ms is outside the enclave. diff --git a/sdk/trts/linux/trts_mitigation.S b/sdk/trts/linux/trts_mitigation.S index 4474a55de..c3b79db1d 100644 --- a/sdk/trts/linux/trts_mitigation.S +++ b/sdk/trts/linux/trts_mitigation.S @@ -109,13 +109,7 @@ aex_notify_c3_cache: * ct_restore_state) | | | rsvd main-flow RBP |-6 | * | | | rsvd main-flow RSI |-7 | * | | | rsvd main-flow RDI |-8 | - * | | | rsvd main-flow FLAGS |-9 | - * +-|-| rsvd main-flow -8(rsp) |-10| - * +-|-| &SSA[0].AEXNOTIFY (rsi) |-11| - * (copy of parameters | | | ptr stack tickle (rdx) |-12| - * passed @entry) | | | ptr code tickle (rcx) |-13| - * | | | ptr data tickle (r8) |-14| - * +-|-| ptr c3 byte (r9) |-15| + * +-|-| rsvd main-flow -8(rsp) |-9 | * (this whole rsvd area | --------------------------- | * is persistent and will | | ... | | * not be touched by | | padding for alignment | | @@ -160,14 +154,8 @@ aex_notify_c3_cache: #define RSVD_RBP_OFFSET (-RED_ZONE_SIZE-6*SE_WORDSIZE) #define RSVD_RSI_OFFSET (-RED_ZONE_SIZE-7*SE_WORDSIZE) #define RSVD_RDI_OFFSET (-RED_ZONE_SIZE-8*SE_WORDSIZE) -#define RSVD_FLAGS_OFFSET (-RED_ZONE_SIZE-9*SE_WORDSIZE) -#define RSVD_REDZONE_WORD_OFFSET (-RED_ZONE_SIZE-10*SE_WORDSIZE) -#define RSVD_AEXNOTIFY_ADDRESS_OFFSET (-RED_ZONE_SIZE-11*SE_WORDSIZE) -#define RSVD_STACK_TICKLE_OFFSET (-RED_ZONE_SIZE-12*SE_WORDSIZE) -#define RSVD_CODE_TICKLE_OFFSET (-RED_ZONE_SIZE-13*SE_WORDSIZE) -#define RSVD_DATA_TICKLE_OFFSET (-RED_ZONE_SIZE-14*SE_WORDSIZE) -#define RSVD_C3_ADDRESS_OFFSET (-RED_ZONE_SIZE-15*SE_WORDSIZE) -#define RSVD_TOP (-RED_ZONE_SIZE-15*SE_WORDSIZE) +#define RSVD_REDZONE_WORD_OFFSET (-RED_ZONE_SIZE-9*SE_WORDSIZE) +#define RSVD_TOP (-RED_ZONE_SIZE-9*SE_WORDSIZE) #if RSVD_SIZE_OF_MITIGATION_STACK_AREA != (RSVD_BOTTOM-RSVD_TOP) #error "Malformed reserved mitigation stack area" @@ -192,60 +180,129 @@ aex_notify_c3_cache: #define INFO_FLAGS_OFFSET (16*SE_WORDSIZE) #define INFO_RIP_OFFSET (17*SE_WORDSIZE) +# Returns the enclave application resumption point if the AEX occurred within +# the mitigation or at __ct_mitigation_ret. If the AEX occurred during the +# mitigation at a RET instruction within the enclave application called by +# .ct_check_execute, then cselect_mitigation_rip() will return the address of +# that RET. Thus, the returned RIP will always point within the originally +# interrupted enclave application page. +DECLARE_LOCAL_FUNC cselect_mitigation_rip +# rdi: info + mov INFO_RIP_OFFSET(%rdi), %rax # rax: pre-irq rip + mov INFO_RSP_OFFSET(%rdi), %rcx # rcx: pre-irq rsp + lea_pic __ct_mitigation_ret, %rsi + cmp %rsi, %rax + lea 8(%rcx), %rsi + + # set rcx = IRQ in __ct_mitigation_ret ? original main-flow rsp : pre-irq rsp + cmove %rsi, %rcx + + lea_pic __ct_mitigation_ret, %rdx + sub %rax, %rdx + + # set CF=1 (B) if IRQ in mitigation (including __ct_mitigation_ret) + cmp $(.ct_aexnotify_end - .ct_mitigation_begin), %rdx + + # set rax = irq in mitigation ? original main-flow rip : pre-irq rip + cmovb RSVD_RIP_OFFSET(%rcx), %rax + + ret +END_FUNC + +# If interrupt happened during execution of the atomic mitigation stub +# (including any C3 calls from ct_check_execute), restore clobbered +# enclave application registers from the persistent reserved area on the +# stack into the info struct parameter. +DECLARE_LOCAL_FUNC cselect_mitigation_regs +# rdi: info +# rsi: saved_rip +# rdx: c3_byte_address + mov INFO_RIP_OFFSET(%rdi), %rax + mov INFO_RSP_OFFSET(%rdi), %rcx + + # Set r8b=1 if saved_rip=c3_byte_address + cmp %rsi, %rdx + sete %r8b + + # Set r9b=1 if info->rip=__ct_mitigation_ret + lea_pic __ct_mitigation_ret, %rdx + cmp %rax, %rdx + sete %r9b + + # Set r10b=1 if *info->rsp=.ct_check_execute_post + lea_pic .ct_check_execute_post, %rdx + cmp (%rcx), %rdx + sete %r10b + + # Set r8b=1 if (*info->rsp=.ct_check_execute_post) + # and ((saved_rip=c3_byte_address) or (info->rip=__ct_mitigation_ret)) + or %r9b, %r8b + and %r10b, %r8b + + # Pop the return address if r8b=1 + lea 8(%rcx), %rdx + cmovnz %rdx, %rcx + mov %rcx, INFO_RSP_OFFSET(%rdi) + + # Set r9b=1 if the mitigation was interrupted, but not at a RET + lea_pic .ct_mitigation_end, %rdx + sub %rax, %rdx + cmp $(.ct_mitigation_end - .ct_mitigation_begin + 1), %rdx + setb %r9b + + # If the mitigation was interrupted, restore clobbered registers from the + # reserved area on the stack. + or %r9b, %r8b + mov INFO_RIP_OFFSET(%rdi), %rax + cmovnz RSVD_RIP_OFFSET(%rcx), %rax + mov %rax, RSVD_RIP_OFFSET(%rcx) + mov %rax, INFO_RIP_OFFSET(%rdi) + mov INFO_RAX_OFFSET(%rdi), %rax + cmovnz RSVD_RAX_OFFSET(%rcx), %rax + mov %rax, RSVD_RAX_OFFSET(%rcx) + mov %rax, INFO_RAX_OFFSET(%rdi) + mov INFO_RCX_OFFSET(%rdi), %rax + cmovnz RSVD_RCX_OFFSET(%rcx), %rax + mov %rax, RSVD_RCX_OFFSET(%rcx) + mov %rax, INFO_RCX_OFFSET(%rdi) + mov INFO_RDX_OFFSET(%rdi), %rax + cmovnz RSVD_RDX_OFFSET(%rcx), %rax + mov %rax, RSVD_RDX_OFFSET(%rcx) + mov %rax, INFO_RDX_OFFSET(%rdi) + mov INFO_RBX_OFFSET(%rdi), %rax + cmovnz RSVD_RBX_OFFSET(%rcx), %rax + mov %rax, RSVD_RBX_OFFSET(%rcx) + mov %rax, INFO_RBX_OFFSET(%rdi) + mov INFO_RBP_OFFSET(%rdi), %rax + cmovnz RSVD_RBP_OFFSET(%rcx), %rax + mov %rax, RSVD_RBP_OFFSET(%rcx) + mov %rax, INFO_RBP_OFFSET(%rdi) + mov INFO_RSI_OFFSET(%rdi), %rax + cmovnz RSVD_RSI_OFFSET(%rcx), %rax + mov %rax, RSVD_RSI_OFFSET(%rcx) + mov %rax, INFO_RSI_OFFSET(%rdi) + mov INFO_RDI_OFFSET(%rdi), %rax + cmovnz RSVD_RDI_OFFSET(%rcx), %rax + mov %rax, RSVD_RDI_OFFSET(%rcx) + mov %rax, INFO_RDI_OFFSET(%rdi) + + # If the mitigation was interrupted, restore the first q/dword of the red + # zone from the reserved area; otherwise save it to the reserved area + mov -SE_WORDSIZE(%rcx), %rax + cmovnz RSVD_REDZONE_WORD_OFFSET(%rcx), %rax + mov %rax, RSVD_REDZONE_WORD_OFFSET(%rcx) + ret +END_FUNC + DECLARE_LOCAL_FUNC constant_time_apply_sgxstep_mitigation_and_continue_execution -/* Note: moving rsp upwards as a scratchpad register discards any data at lower - * addresses (i.e., these may be overwritten by nested exception handlers, but - * the stage-1 handler will always safeguard a red zone + rsvd area under the - * interrupted stack pointer). */ - mov INFO_RSP_OFFSET(%rdi), %rsp /* rsp: pre-irq rsp */ - mov INFO_RIP_OFFSET(%rdi), %rax /* rax: pre-irq rip */ - mov %rax, %r10 - -/* Check whether the last AEX occurred during the mitigation */ - cmpb $0xc3, (%rax) # ZF=1 if interrupted c3 (ret) - cmovz (%rsp), %rax # rax: irq c3? caller rip : pre-irq rip - mov %rsp, %rbp - lea SE_WORDSIZE(%rsp), %rbx - cmovz %rbx, %rbp # rbp: irq c3? post-ret rsp : pre-irq rsp - - lea_pic __ct_mitigation_end, %rbx - sub %rax, %rbx - cmp $(__ct_mitigation_end - __ct_mitigation_begin + 1), %rbx -// CMP will set CF=1 (B) if the mitigation was interrupted, CF=0 (NB) otherwise - cmovb %rbp, %rsp # rsp: original main flow rsp - mov %rsp, INFO_RSP_OFFSET(%rdi) - -// If the mitigation was interrupted, restore the interrupted IP from the -// reserved area - cmovb RSVD_RIP_OFFSET(%rsp), %r10 - mov %r10, RSVD_RIP_OFFSET(%rsp) - -// Copy RFLAGS onto the reserved stack area - mov INFO_FLAGS_OFFSET(%rdi), %rax - mov %rax, RSVD_FLAGS_OFFSET(%rsp) - -// If the mitigation was interrupted, restore the first q/dword of the red -// zone from the reserved area; otherwise save it to the reserved area - mov -SE_WORDSIZE(%rsp), %rax - cmovb RSVD_REDZONE_WORD_OFFSET(%rsp), %rax - mov %rax, RSVD_REDZONE_WORD_OFFSET(%rsp) - -// Save &SSA[0].GPRSGX.AEXNOTIFY to the reserved area - mov %rsi, RSVD_AEXNOTIFY_ADDRESS_OFFSET(%rsp) - -// If the mitigation was interrupted, restore tickle parameters from the -// reserved area. - cmovb RSVD_STACK_TICKLE_OFFSET(%rsp), %rdx - cmovb RSVD_CODE_TICKLE_OFFSET(%rsp), %rcx - cmovb RSVD_DATA_TICKLE_OFFSET(%rsp), %r8 - cmovb RSVD_C3_ADDRESS_OFFSET(%rsp), %r9 - mov %rdx, RSVD_STACK_TICKLE_OFFSET(%rsp) - mov %rcx, RSVD_CODE_TICKLE_OFFSET(%rsp) - mov %r8, RSVD_DATA_TICKLE_OFFSET(%rsp) - mov %r9, RSVD_C3_ADDRESS_OFFSET(%rsp) - -// If the mitigation was not interrupted (the interrupt occured in the main flow) -// then restore the registers from *info +# rdi: info +# rsi: address of the AEX-Notify-enabling byte +# rdx: stack_tickle_pages +# rcx: code_tickle_page +# r8: data_tickle_address +# r9: c3_byte_address + mov %r8, %rbx + mov %r9, %rbp mov INFO_R8_OFFSET(%rdi), %r8 mov INFO_R9_OFFSET(%rdi), %r9 mov INFO_R10_OFFSET(%rdi), %r10 @@ -254,49 +311,18 @@ DECLARE_LOCAL_FUNC constant_time_apply_sgxstep_mitigation_and_continue_execution mov INFO_R13_OFFSET(%rdi), %r13 mov INFO_R14_OFFSET(%rdi), %r14 mov INFO_R15_OFFSET(%rdi), %r15 - mov INFO_RAX_OFFSET(%rdi), %rax - mov INFO_RCX_OFFSET(%rdi), %rcx - mov INFO_RDX_OFFSET(%rdi), %rdx - mov INFO_RBX_OFFSET(%rdi), %rbx - mov INFO_RBP_OFFSET(%rdi), %rbp - mov INFO_RSI_OFFSET(%rdi), %rsi - mov INFO_RDI_OFFSET(%rdi), %rdi - -// If the mitigation was interrupted, restore registers from the reserved area -// on the stack. - cmovb RSVD_RAX_OFFSET(%rsp), %rax - cmovb RSVD_RCX_OFFSET(%rsp), %rcx - cmovb RSVD_RDX_OFFSET(%rsp), %rdx - cmovb RSVD_RBX_OFFSET(%rsp), %rbx - cmovb RSVD_RBP_OFFSET(%rsp), %rbp - cmovb RSVD_RSI_OFFSET(%rsp), %rsi - cmovb RSVD_RDI_OFFSET(%rsp), %rdi - - mov %rax, RSVD_RAX_OFFSET(%rsp) - mov %rcx, RSVD_RCX_OFFSET(%rsp) - mov %rdx, RSVD_RDX_OFFSET(%rsp) - mov %rbx, RSVD_RBX_OFFSET(%rsp) - mov %rbp, RSVD_RBP_OFFSET(%rsp) - mov %rsi, RSVD_RSI_OFFSET(%rsp) - mov %rdi, RSVD_RDI_OFFSET(%rsp) - -# Restore tickle addresses - mov RSVD_STACK_TICKLE_OFFSET(%rsp), %rbp - mov RSVD_CODE_TICKLE_OFFSET(%rsp), %rsi - mov RSVD_DATA_TICKLE_OFFSET(%rsp), %rdx - mov RSVD_C3_ADDRESS_OFFSET(%rsp), %rdi -# Set up the stack tickles - shrb $1, %bpl # Bit 0 in %rbp indicates whether a second stack page can be tickled - mov %rbp, %rbx - jnc .restore_flags - sub $0x1000, %rbx - -.restore_flags: - lea RSVD_FLAGS_OFFSET(%rsp), %rax - xchg %rax, %rsp + +/* NOTE: moving rsp upwards as a scratchpad register discards any data at lower + * addresses (i.e., these may be overwritten by nested exception handlers), but + * the stage-1 handler will always safeguard a 128-byte red zone under the + * interrupted stack pointer. Thus, the code below is safe: + * INFO_FLAGS_OFFSET-INFO_RSP_OFFSET = 12*8 = 96 < 128-byte ABI red zone. + */ + lea INFO_FLAGS_OFFSET(%rdi), %rsp popf - xchg %rax, %rsp + mov INFO_RSP_OFFSET(%rdi), %rsp /* rsp: pre-irq rsp */ + mov %rdx, %rdi # NOTHING AFTER THIS POINT CAN MODIFY EFLAGS/RFLAGS @@ -304,53 +330,69 @@ DECLARE_LOCAL_FUNC constant_time_apply_sgxstep_mitigation_and_continue_execution # BEGIN MITIGATION CODE ################################################################################ +# rdi: stack_tickle_pages +# rsi: address of the AEX-Notify-enabling byte +# rdx: unused (will be clobbered) +# rcx: code_tickle_page +# rax: unused (will be clobbered) +# rbx: data_tickle_address +# rbp: c3_byte_address + #define MITIGATION_CODE_ALIGNMENT 0x200 .align MITIGATION_CODE_ALIGNMENT # Enable AEX Notify .ct_enable_aexnotify: - mov RSVD_AEXNOTIFY_ADDRESS_OFFSET(%rsp), %rax - movb $1, (%rax) + movb $1, (%rsi) - .global __ct_mitigation_begin -__ct_mitigation_begin: +.ct_mitigation_begin: + mov RSVD_REDZONE_WORD_OFFSET(%rsp), %rsi lfence +# Set up the stack tickles + movzx %dil, %edx # Bit 0 in %rdi indicates whether a second stack page can be tickled + mov $0, %dil + mov $12, %eax + shlx %rax, %rdx, %rdx + lea (%rdi,%rdx), %rdx + .ct_check_write: - movl $63, %ecx - shlx %rcx, %rsi, %rcx # Bit 0 in %rsi indicates whether data_tickle_address can be written - jrcxz .ct_clear_low_bits_of_rdx - lea -1(%rsi), %rsi # Clear bit 0 in %rsi - movb (%rdx), %al - movb %al, (%rdx) # Will fault if the data page is not writable - -.ct_clear_low_bits_of_rdx: + mov %rcx, %rax + mov $63, %ecx + shlx %rcx, %rax, %rcx # Bit 0 in %rax indicates whether data_tickle_address can be written + jrcxz .ct_clear_low_bits_of_rbx + lea -1(%rax), %rax # Clear bit 0 in %rax + movb (%rbx), %cl + movb %cl, (%rbx) # Will fault if the data page is not writable + +.ct_clear_low_bits_of_rbx: movl $12, %ecx - shrx %rcx, %rdx, %rdx - shlx %rcx, %rdx, %rdx + shrx %rcx, %rbx, %rbx + shlx %rcx, %rbx, %rbx .ct_check_execute: - call *%rdi + call *%rbp + +.ct_check_execute_post: + mov RSVD_RBP_OFFSET(%rsp), %rbp + mov %rsi, -SE_WORDSIZE(%rsp) # restore the first q/dword of the red zone # Load all working set cache lines and warm the TLB entries mov $0x1000, %ecx .align 0x10 .ct_warm_caches_and_tlbs: lea -0x40(%ecx), %ecx - mov (%rsi, %rcx), %eax - mov (%rbp, %rcx), %eax - mov (%rbx, %rcx), %eax - mov (%rdx, %rcx), %eax + mov (%rax, %rcx), %esi # code page tickle + mov (%rdi, %rcx), %esi # stack page 1 tickle + mov (%rdx, %rcx), %esi # stack page 2 tickle + mov (%rbx, %rcx), %esi # data tickle jrcxz .ct_restore_state jmp .ct_warm_caches_and_tlbs # loops 64 times .ct_restore_state: - movzx %sil, %ecx # Bit 4 of %sil indicates whether cycles should be added - mov RSVD_REDZONE_WORD_OFFSET(%rsp), %rdi - mov %rdi, -SE_WORDSIZE(%rsp) # restore the first q/dword of the red zone + movzx %al, %ecx # Bit 4 of %al indicates whether cycles should be added mov RSVD_RDI_OFFSET(%rsp), %rdi mov RSVD_RSI_OFFSET(%rsp), %rsi - mov RSVD_RBP_OFFSET(%rsp), %rbp mov RSVD_RBX_OFFSET(%rsp), %rbx mov RSVD_RDX_OFFSET(%rsp), %rdx mov RSVD_RAX_OFFSET(%rsp), %rax @@ -361,13 +403,13 @@ __ct_mitigation_begin: .ct_restore_rcx: mov RSVD_RCX_OFFSET(%rsp), %rcx -__ct_mitigation_end: +.ct_mitigation_end: jmp *RSVD_RIP_OFFSET(%rsp) .global __ct_mitigation_ret __ct_mitigation_ret: ret - .cfi_endproc +END_FUNC .ct_aexnotify_end: diff --git a/sdk/trts/linux/trts_pic.S b/sdk/trts/linux/trts_pic.S index 2bea7ed40..e1a290a0e 100644 --- a/sdk/trts/linux/trts_pic.S +++ b/sdk/trts/linux/trts_pic.S @@ -45,14 +45,14 @@ DECLARE_LOCAL_FUNC get_enclave_base lea_pic __ImageBase, %xax ret - .cfi_endproc +END_FUNC DECLARE_LOCAL_FUNC get_enclave_state lea_pic g_enclave_state, %xcx xor %xax, %xax movl (%xcx), %eax ret - .cfi_endproc +END_FUNC DECLARE_LOCAL_FUNC set_enclave_state lea_pic g_enclave_state, %xax @@ -61,7 +61,7 @@ DECLARE_LOCAL_FUNC set_enclave_state #endif movl %edi, (%xax) ret - .cfi_endproc +END_FUNC DECLARE_LOCAL_FUNC lock_enclave lea_pic g_enclave_state, %xdx @@ -71,7 +71,7 @@ DECLARE_LOCAL_FUNC lock_enclave mov $ENCLAVE_INIT_IN_PROGRESS, %ecx /* if (g_global_data.enclave_state == ENCLAVE_INIT_NOT_STARTED) */ lock cmpxchgl %ecx, (%xdx) /* g_global_data.enclave_state == ENCLAVE_INIT_IN_PROGRESS */ ret /* xax: the initial value of enclave state */ - .cfi_endproc +END_FUNC /* * --------------------------------------------------------------------- @@ -83,7 +83,7 @@ DECLARE_LOCAL_FUNC lock_enclave DECLARE_LOCAL_FUNC get_thread_data READ_TD_DATA self_addr ret - .cfi_endproc +END_FUNC /* * --------------------------------------------------------------------- @@ -95,7 +95,7 @@ DECLARE_LOCAL_FUNC get_thread_data DECLARE_LOCAL_FUNC get_stack_guard READ_TD_DATA stack_guard ret - .cfi_endproc +END_FUNC /* * --------------------------------------------------------------------- @@ -263,7 +263,7 @@ DECLARE_GLOBAL_FUNC enclave_entry /* Should not come here */ ud2 - .cfi_endproc +END_FUNC /* * ------------------------------------------------------------------------- @@ -453,7 +453,7 @@ DECLARE_LOCAL_FUNC do_ocall cld /* DF = 0 */ ENCLU - .cfi_endproc +END_FUNC /* * ------------------------------------------------------------------ @@ -478,7 +478,7 @@ DECLARE_LOCAL_FUNC __morestack call do_ocall leave ret - .cfi_endproc +END_FUNC DECLARE_GLOBAL_FUNC asm_oret mov %xsp, %xbx @@ -525,7 +525,7 @@ DECLARE_GLOBAL_FUNC asm_oret ret /* should not come here */ ud2 - .cfi_endproc +END_FUNC /* * ------------------------------------------------------------------------ @@ -550,6 +550,7 @@ DECLARE_LOCAL_FUNC do_egetkey xor %xax, %xax .Legetkey_done: SE_EPILOG +END_FUNC /* @@ -572,6 +573,7 @@ Lereport_inst: ENCLU setc %al SE_EPILOG +END_FUNC .global Leverifyreport2_inst DECLARE_LOCAL_FUNC do_everifyreport2 @@ -583,6 +585,7 @@ Leverifyreport2_inst: xor %xax, %xax .Leverifyreport2_done: SE_EPILOG +END_FUNC DECLARE_GLOBAL_FUNC do_eaccept SE_PROLOG @@ -591,6 +594,7 @@ DECLARE_GLOBAL_FUNC do_eaccept cmp $SGX_SUCCESS, %eax jnz abort SE_EPILOG +END_FUNC DECLARE_GLOBAL_FUNC do_eacceptcopy SE_PROLOG @@ -599,12 +603,14 @@ DECLARE_GLOBAL_FUNC do_eacceptcopy cmp $SGX_SUCCESS, %eax jnz abort SE_EPILOG +END_FUNC DECLARE_GLOBAL_FUNC do_emodpe SE_PROLOG mov $SE_EMODPE, %eax ENCLU SE_EPILOG +END_FUNC #define _RDRAND_RETRY_TIMES 10 /* @@ -633,7 +639,7 @@ DECLARE_LOCAL_FUNC do_rdrand movl %eax, (%xcx) mov $1, %xax ret - .cfi_endproc +END_FUNC /* * ------------------------------------------------------------------------- @@ -644,7 +650,7 @@ DECLARE_LOCAL_FUNC abort lea_pic g_enclave_state, %xax movl $ENCLAVE_CRASHED, (%xax) ud2 - .cfi_endproc +END_FUNC /* * ------------------------------------------------------------------------- @@ -702,7 +708,7 @@ DECLARE_LOCAL_FUNC continue_execution xchg %xax, %xsp ret $(RED_ZONE_SIZE) /* pop xip and red zone (if any) */ - .cfi_endproc +END_FUNC /* * ------------------------------------------------------------------------- @@ -715,5 +721,5 @@ DECLARE_LOCAL_FUNC second_phase mov $SE_EDECCSSA, %xax enclu /* DECCSSA */ jmp *%xdx - .cfi_endproc +END_FUNC diff --git a/sdk/trts/trts_mitigation.h b/sdk/trts/trts_mitigation.h index d6ef85d52..554b3b91a 100644 --- a/sdk/trts/trts_mitigation.h +++ b/sdk/trts/trts_mitigation.h @@ -32,6 +32,6 @@ #ifndef TRTS_MIITGATION_H__ #define TRTS_MIITGATION_H__ -#define RSVD_SIZE_OF_MITIGATION_STACK_AREA (15 * 8) +#define RSVD_SIZE_OF_MITIGATION_STACK_AREA (9 * 8) #endif diff --git a/sdk/trts/trts_veh.cpp b/sdk/trts/trts_veh.cpp index d7b15400b..8333eadbd 100644 --- a/sdk/trts/trts_veh.cpp +++ b/sdk/trts/trts_veh.cpp @@ -73,6 +73,10 @@ sgx_mm_pfhandler_t g_mm_pfhandler = NULL; #define DEC_VEH_POINTER(x) (sgx_exception_handler_t)((x) ^ g_veh_cookie) extern int g_aexnotify_supported; extern "C" sgx_status_t sgx_apply_mitigations(const sgx_exception_info_t *); +extern "C" uintptr_t cselect_mitigation_rip(const sgx_exception_info_t *); +extern "C" uintptr_t cselect_mitigation_regs(const sgx_exception_info_t *, + uintptr_t saved_rip, + uintptr_t c3_byte_address); extern uint16_t aex_notify_c3_cache[2048]; extern uint8_t *__ct_mitigation_ret; @@ -219,6 +223,7 @@ static void apply_constant_time_sgxstep_mitigation_and_continue_execution(sgx_ex thread_data_t *thread_data = get_thread_data(); int ct_result; uint64_t data_address; + uintptr_t saved_rip; uintptr_t code_tickle_page, c3_byte_address, stack_tickle_pages, data_tickle_address, stack_base_page = ((thread_data->stack_base_addr & ~0xFFF) == 0) ? (thread_data->stack_base_addr) - 0x1000 : @@ -226,6 +231,11 @@ static void apply_constant_time_sgxstep_mitigation_and_continue_execution(sgx_ex stack_limit_page = thread_data->stack_limit_addr & ~0xFFF; int data_tickle_address_is_within_enclave; + // NOTE: use cselect_mitigation_rip to ensure we only ever dereference + // the interrupted application code page, even if previous interrupt + // was in the atomic mitigation stub (i.e., zero-step) + saved_rip = cselect_mitigation_rip(info); + // Determine which stack pages can be tickled if (((uintptr_t)info & ~0xFFF) == stack_base_page) { if (stack_base_page == stack_limit_page) { @@ -234,7 +244,7 @@ static void apply_constant_time_sgxstep_mitigation_and_continue_execution(sgx_ex } else { // The current stack page is the base page, but there are more // pages so we tickle the next one as well. - stack_tickle_pages = stack_base_page | 1; + stack_tickle_pages = (stack_base_page - 0x1000) | 1; } } else { // If the current stack page is not the base page, then it's generally @@ -242,11 +252,11 @@ static void apply_constant_time_sgxstep_mitigation_and_continue_execution(sgx_ex // code and the interrupted code may have separate but adjacent stack // pages (in this case, the interrupted code's stack frame must be on // the page with a higher address). - stack_tickle_pages = (((uintptr_t)info & ~0xFFF) + 0x1000) | 1; + stack_tickle_pages = ((uintptr_t)info & ~0xFFF) | 1; } // Look up the code page in the c3 cache - code_tickle_page = info->cpu_context.REG(ip) & ~0xFFF; + code_tickle_page = saved_rip & ~0xFFF; c3_byte_address = code_tickle_page + *(aex_notify_c3_cache + ((code_tickle_page >> 12) & 0x07FF)); if (*(uint8_t *)c3_byte_address != 0xc3) { uint8_t *i = (uint8_t *)code_tickle_page, *e = i + 4096; @@ -260,6 +270,11 @@ static void apply_constant_time_sgxstep_mitigation_and_continue_execution(sgx_ex } } + // NOTE: in case the previous interrupt was in the atomic mitigation + // stub, first restore clobbered application registers in the info + // struct before determining tickle addresses + cselect_mitigation_regs(info, saved_rip, c3_byte_address); + ct_result = ct_decode(&info->cpu_context, &data_address); data_tickle_address = stack_tickle_pages & ~0x1; @@ -527,9 +542,8 @@ extern "C" sgx_status_t trts_handle_exception(void *tcs) size += RED_ZONE_SIZE; // Add space for reserved slot for GPRs that will be used by mitigation - // assembly code RIP, RAX, RBX, RCX, RDX, RBP, RSI, RDI Saved flags, 1st - // D/QWORD of red zone, &SSA[0].GPRSGX.AEXNOTIFY, stack_tickle_pages, - // code_tickle_page, data_tickle_page, c3_byte_address + // assembly code RIP, RAX, RBX, RCX, RDX, RBP, RSI, RDI, 1st + // QWORD of red zone size += RSVD_SIZE_OF_MITIGATION_STACK_AREA; // decrease the stack to give space for info diff --git a/sdk/tsetjmp/_setjmp.S b/sdk/tsetjmp/_setjmp.S index 770d12c95..2dc89a740 100644 --- a/sdk/tsetjmp/_setjmp.S +++ b/sdk/tsetjmp/_setjmp.S @@ -172,7 +172,7 @@ DECLARE_GLOBAL_FUNC setjmp ret .crash: ud2 - .cfi_endproc +END_FUNC DECLARE_GLOBAL_FUNC longjmp #ifdef LINUX32 @@ -273,7 +273,7 @@ DECLARE_GLOBAL_FUNC longjmp jnz 1f incl %eax 1: ret - .cfi_endproc +END_FUNC .weak _setjmp diff --git a/sdk/ttls/Makefile b/sdk/ttls/Makefile index 943d920d8..3fc0c6f4a 100644 --- a/sdk/ttls/Makefile +++ b/sdk/ttls/Makefile @@ -53,6 +53,7 @@ INCLUDE += -I$(COMMON_DIR)/inc/tlibc \ -I$(COMMON_DIR)/inc \ -I$(LINUX_SDK_DIR)/tlibcxx/include \ -I$(SGX_QV_PATH)/QvE/Include \ + -I$(SGX_QV_PATH)/appraisal/qal \ -I$(SGX_QV_PATH)/../QuoteGeneration/quote_wrapper/common/inc \ -I$(SGX_QV_PATH)/../QuoteGeneration/quote_wrapper/tdx_attest \ -I$(SGX_QV_PATH)/../QuoteGeneration/pce_wrapper/inc \