From 321a6580fb133a4f9d80245f18556e5bd51521d3 Mon Sep 17 00:00:00 2001 From: "Li, Xun" Date: Wed, 6 Apr 2022 13:12:24 +0800 Subject: [PATCH] Linux 2.16 Open Source Gold Release Upgraded to OpenSSL 1.1.1m. Provided RA-TLS (Remote Attestation based Transport Layer Security) APIs and Samples. Supported PKRU (Protection Key rights Register) in Enclave. Added APIs of SHA384 and VerifyReport2 to support TDX. Enhanced QPL (Quote Provider Library) to support caching Intel PCK (Provisioning Certificate Key) certificate chain in local memory, or retrieving Intel PCK cert chain from local HTTP/S address. Upgraded Intel ECDSA Quote Verification Enclave to integrate SgxSSL/OpenSSL version 1.1.1m. Introduced Intel ID enclave for QE identity generation. Fixed bugs. Signed-off-by: Li, Xun --- License.txt | 52 ++ Makefile | 32 +- Makefile.psw_dcap | 71 ++ README.md | 39 +- .../Enclave/TrustedLibrary/Libcxx.cpp | 4 +- .../SampleAttestedTLS/AttestedTLSREADME.md | 145 +++++ SampleCode/SampleAttestedTLS/Makefile | 71 ++ SampleCode/SampleAttestedTLS/README.md | 129 ++++ SampleCode/SampleAttestedTLS/client/Makefile | 65 ++ .../SampleAttestedTLS/client/enc/Makefile | 96 +++ .../client/enc/client_enc.config.xml | 12 + .../SampleAttestedTLS/client/enc/enclave.lds | 10 + .../client/enc/openssl_client.cpp | 290 +++++++++ .../client/enc/private_test_key.pem | 39 ++ .../SampleAttestedTLS/client/host/Makefile | 56 ++ .../SampleAttestedTLS/client/host/host.cpp | 238 +++++++ .../SampleAttestedTLS/client/tls_client.edl | 47 ++ SampleCode/SampleAttestedTLS/common/common.h | 57 ++ .../SampleAttestedTLS/common/enclave.edl | 44 ++ .../SampleAttestedTLS/common/err_msg.cpp | 131 ++++ .../common/openssl_utility.cpp | 314 +++++++++ .../common/openssl_utility.h | 46 ++ .../SampleAttestedTLS/common/tcommon.cpp | 57 ++ .../SampleAttestedTLS/common/ucommon.cpp | 60 ++ .../SampleAttestedTLS/common/utility.cpp | 262 ++++++++ SampleCode/SampleAttestedTLS/common/utility.h | 64 ++ .../common/verify_callback.cpp | 155 +++++ .../SampleAttestedTLS/non_enc_client/Makefile | 63 ++ .../non_enc_client/client.cpp | 331 ++++++++++ .../SampleAttestedTLS/prepare_sgxssl.sh | 100 +++ SampleCode/SampleAttestedTLS/server/Makefile | 65 ++ .../SampleAttestedTLS/server/enc/Makefile | 66 ++ .../SampleAttestedTLS/server/enc/enclave.lds | 10 + .../server/enc/openssl_server.cpp | 242 +++++++ .../server/enc/private_test_key.pem | 39 ++ .../server/enc/server_enc.config.xml | 12 + .../SampleAttestedTLS/server/host/Makefile | 52 ++ .../SampleAttestedTLS/server/host/host.cpp | 234 +++++++ .../SampleAttestedTLS/server/tls_server.edl | 44 ++ .../SampleAttestedTLS/sgx_socket/htonl.c | 8 + .../SampleAttestedTLS/sgx_socket/htons.c | 8 + .../sgx_socket/include/bits/alltypes.h | 402 ++++++++++++ .../sgx_socket/include/byteswap.h | 20 + .../sgx_socket/include/features.h | 24 + .../sgx_socket/include/netdb.h | 156 +++++ .../sgx_socket/include/netinet/in.h | 416 ++++++++++++ .../sgx_socket/include/poll.h | 49 ++ .../sgx_socket/include/sgx_socket.edl | 51 ++ .../sgx_socket/include/sys/select.h | 43 ++ .../sgx_socket/include/sys/socket.h | 396 ++++++++++++ .../sgx_socket/trusted_sgx_socket.cpp | 162 +++++ .../sgx_socket/untrusted_sgx_socket.cpp | 104 +++ SampleCode/SampleAttestedTLS/sgxenv.mk | 149 +++++ .../SampleEnclaveGMIPP/Enclave/Enclave.cpp | 607 +++++++++++++++--- SampleCode/SampleEnclavePCL/Makefile | 21 + SampleCode/SampleEnclavePCL/README.md | 26 +- buildenv.mk | 14 +- common/inc/internal/arch.h | 2 + common/inc/internal/inst.h | 1 + common/inc/internal/linux/linux-regs.h | 1 + common/inc/internal/se_version.h | 25 +- common/inc/internal/trts_inst.h | 12 +- common/inc/sgx_attributes.h | 3 +- common/inc/sgx_report2.h | 110 ++++ common/inc/sgx_tcrypto.h | 7 + common/inc/sgx_trts.h | 19 + common/inc/sgx_ttls.edl | 62 ++ common/inc/sgx_ttls.h | 143 +++++ common/inc/sgx_utils.h | 14 +- common/inc/sgx_utls.h | 91 +++ download_prebuilt.sh | 8 +- external/CppMicroServices/CMakeLists.txt | 2 +- .../CppMicroServices/third_party/jsoncpp.cpp | 9 + external/dcap_source | 2 +- external/epid-sdk/ext/ipp/include/sgx_ippcp.h | 25 +- external/ippcp_internal/README.md | 22 +- external/protobuf/Makefile | 9 +- external/protobuf/sgx_protobuf.patch | 78 ++- external/rdrand/src/Makefile.in | 5 + external/sgxssl/prepare_sgxssl.sh | 8 +- .../vtune/linux/sdk/src/ittnotify/Makefile | 6 + .../common/gen_source/copy_source.py | 116 ++++ .../common/psw-dcap/91-sgx-enclave.rules | 4 + .../common/psw-dcap/92-sgx-provision.rules | 3 + .../psw-dcap/BOM_install/libsgx-ae-epid.txt | 3 + .../BOM_install/libsgx-ae-id-enclave.txt | 2 + .../psw-dcap/BOM_install/libsgx-ae-le.txt | 3 + .../psw-dcap/BOM_install/libsgx-ae-pce.txt | 3 + .../psw-dcap/BOM_install/libsgx-ae-qe3.txt | 2 + .../psw-dcap/BOM_install/libsgx-ae-qve.txt | 2 + .../BOM_install/libsgx-aesm-ecdsa-plugin.txt | 2 + .../BOM_install/libsgx-aesm-epid-plugin.txt | 2 + .../BOM_install/libsgx-aesm-launch-plugin.txt | 3 + .../BOM_install/libsgx-aesm-pce-plugin.txt | 2 + .../libsgx-aesm-quote-ex-plugin.txt | 2 + .../libsgx-dcap-default-qpl-devel.txt | 1 + .../BOM_install/libsgx-dcap-default-qpl.txt | 4 + .../BOM_install/libsgx-dcap-ql-devel.txt | 2 + .../psw-dcap/BOM_install/libsgx-dcap-ql.txt | 2 + .../libsgx-dcap-quote-verify-devel.txt | 3 + .../BOM_install/libsgx-dcap-quote-verify.txt | 2 + .../libsgx-enclave-common-devel.txt | 2 + .../BOM_install/libsgx-enclave-common.txt | 4 + .../BOM_install/libsgx-epid-devel.txt | 2 + .../psw-dcap/BOM_install/libsgx-epid.txt | 2 + .../psw-dcap/BOM_install/libsgx-headers.txt | 13 + .../BOM_install/libsgx-launch-devel.txt | 2 + .../psw-dcap/BOM_install/libsgx-launch.txt | 2 + .../psw-dcap/BOM_install/libsgx-pce-logic.txt | 2 + .../psw-dcap/BOM_install/libsgx-qe3-logic.txt | 3 + .../BOM_install/libsgx-quote-ex-devel.txt | 2 + .../psw-dcap/BOM_install/libsgx-quote-ex.txt | 2 + .../BOM_install/libsgx-ra-network-devel.txt | 4 + .../BOM_install/libsgx-ra-network.txt | 2 + .../BOM_install/libsgx-ra-uefi-devel.txt | 4 + .../psw-dcap/BOM_install/libsgx-ra-uefi.txt | 2 + .../BOM_install/libsgx-uae-service.txt | 2 + .../psw-dcap/BOM_install/libsgx-urts.txt | 2 + .../psw-dcap/BOM_install/sgx-aesm-service.txt | 14 + .../psw-dcap/BOM_install/sgx-dcap-pccs.txt | 75 +++ .../BOM_install/sgx-pck-id-retrieval-tool.txt | 5 + .../psw-dcap/BOM_install/sgx-ra-service.txt | 8 + .../psw-dcap/BOM_source/psw-dcap-tarball.txt | 19 + linux/installer/common/psw-dcap/Makefile | 361 +++++++++++ linux/installer/common/psw-dcap/cleanup.sh | 60 ++ linux/installer/common/psw-dcap/installConfig | 46 ++ linux/installer/common/psw-dcap/linksgx.sh | 55 ++ .../common/psw-dcap/remount-dev-exec.service | 11 + linux/installer/common/psw-dcap/startup.sh | 55 ++ linux/installer/common/psw/BOMs/psw_base.txt | 11 +- linux/installer/common/psw/install.sh | 2 +- linux/installer/common/sdk/BOMs/sdk_base.txt | 55 ++ .../common/sdk/BOMs/sdk_cve_2020_0551_cf.txt | 2 + .../sdk/BOMs/sdk_cve_2020_0551_load.txt | 2 + linux/installer/common/sdk/BOMs/sdk_x64.txt | 2 + .../common/sgx-aesm-service/Makefile | 28 +- .../common/sgx-aesm-service/cleanup.sh | 10 +- .../common/sgx-aesm-service/createTarball.sh | 10 + .../common/sgx-aesm-service/startup.sh | 6 +- .../sgx-aesm-service-1.0/debian/control | 4 +- .../debian/libsgx-ae-pce.postinst | 2 +- linux/installer/rpm/psw-dcap/build.sh | 103 +++ linux/installer/rpm/psw-dcap/clean.sh | 36 ++ .../installer/rpm/psw-dcap/psw-dcap.spec.tmpl | 521 +++++++++++++++ linux/installer/rpm/psw-dcap/sanitize.sh | 54 ++ .../rpm/sgx-aesm-service/libsgx-ae-pce.spec | 4 +- .../libsgx-aesm-ecdsa-plugin.spec | 2 +- .../libsgx-aesm-pce-plugin.spec | 2 +- .../build_and_launch_docker.sh | 6 +- linux/reproducibility/start_build.sh.tmp | 2 + .../config/aesmd_service/aesmd.service | 2 + psw/ae/aesm_service/source/CMakeLists.txt | 2 + psw/ae/aesm_service/source/core/main.cpp | 21 +- .../source/oal/linux/aesm_util.cpp | 27 +- .../oal/linux/persistent_storage_table.cpp | 18 +- .../aesm_service/source/qcnl/CMakeLists.txt | 1 + psw/ae/le/Makefile | 3 +- psw/ae/pce/Makefile | 4 +- psw/ae/pve/Makefile | 3 +- psw/ae/qe/Makefile | 4 +- psw/ae/qe/quoting_enclave.cpp | 12 +- psw/ae/ref_le/Makefile | 2 +- psw/enclave_common/sgx_enclave_common.cpp | 5 + psw/urts/linux/edmm_utility.cpp | 10 + psw/urts/linux/enclave_creator_hw.cpp | 4 +- psw/urts/linux/enter_enclave.S | 27 + psw/urts/linux/isgx_user.h | 94 +++ psw/urts/linux/sig_handler.cpp | 195 +++++- psw/urts/se_detect.cpp | 29 + psw/urts/se_detect.h | 8 + sdk/Makefile.source | 21 +- sdk/cpprt/Makefile | 2 +- .../linux/libunwind/src/se-iterate-phdr.c | 3 +- sdk/gperftools/gperftools-2.7/configure.ac | 2 +- sdk/libcapable/linux/Makefile | 4 +- sdk/protected_code_loader/pcl_entry.cpp | 18 +- sdk/protected_fs/sgx_uprotected_fs/Makefile | 2 +- sdk/selib/sgx_verify_report2.cpp | 158 +++++ sdk/sign_tool/SignTool/Makefile | 4 +- sdk/sign_tool/SignTool/manage_metadata.cpp | 21 +- sdk/sign_tool/SignTool/manage_metadata.h | 7 +- sdk/sign_tool/SignTool/sign_tool.cpp | 3 +- .../SEConfigureCPUSVN/linux/Makefile | 2 +- sdk/simulation/driver_api/Makefile | 2 +- sdk/simulation/uae_service_sim/linux/Makefile | 10 +- sdk/simulation/uinst/Makefile | 2 +- sdk/simulation/urtssim/linux/Makefile | 6 +- sdk/switchless/sgx_uswitchless/Makefile | 4 +- sdk/tlibcrypto/Makefile | 4 +- sdk/tlibcrypto/ipp/sgx_sha384.cpp | 134 ++++ sdk/tlibcrypto/ipp/sgx_sha384_msg.cpp | 65 ++ sdk/tlibcrypto/sgxssl/sgx_aes_ctr.cpp | 4 +- sdk/tlibcrypto/sgxssl/sgx_sha384.cpp | 157 +++++ sdk/tlibcrypto/sgxssl/sgx_sha384_msg.cpp | 63 ++ sdk/trts/init_enclave.cpp | 9 +- sdk/trts/linux/global_init.c | 5 +- sdk/trts/linux/trts_pic.S | 59 +- sdk/trts/trts.cpp | 34 + sdk/trts/trts_ecall.cpp | 10 +- sdk/trts/trts_util.cpp | 16 +- sdk/trts/trts_util.h | 1 + sdk/trts/trts_veh.cpp | 9 + .../src/safecrt/{memomve_s.c => memmove_s.c} | 0 sdk/ttls/Makefile | 99 +++ sdk/ttls/cert_generator.cpp | 430 +++++++++++++ sdk/ttls/cert_header.h | 142 ++++ sdk/ttls/cert_verifier.cpp | 544 ++++++++++++++++ sdk/ttls/tsgxsslio.h | 37 ++ sdk/ttls/ttls.cpp | 378 +++++++++++ sdk/ukey_exchange/Makefile | 4 +- sdk/utls/Makefile | 89 +++ sdk/utls/utls.cpp | 313 +++++++++ 212 files changed, 11971 insertions(+), 329 deletions(-) create mode 100644 Makefile.psw_dcap create mode 100644 SampleCode/SampleAttestedTLS/AttestedTLSREADME.md create mode 100644 SampleCode/SampleAttestedTLS/Makefile create mode 100644 SampleCode/SampleAttestedTLS/README.md create mode 100644 SampleCode/SampleAttestedTLS/client/Makefile create mode 100644 SampleCode/SampleAttestedTLS/client/enc/Makefile create mode 100644 SampleCode/SampleAttestedTLS/client/enc/client_enc.config.xml create mode 100644 SampleCode/SampleAttestedTLS/client/enc/enclave.lds create mode 100644 SampleCode/SampleAttestedTLS/client/enc/openssl_client.cpp create mode 100644 SampleCode/SampleAttestedTLS/client/enc/private_test_key.pem create mode 100644 SampleCode/SampleAttestedTLS/client/host/Makefile create mode 100644 SampleCode/SampleAttestedTLS/client/host/host.cpp create mode 100644 SampleCode/SampleAttestedTLS/client/tls_client.edl create mode 100644 SampleCode/SampleAttestedTLS/common/common.h create mode 100644 SampleCode/SampleAttestedTLS/common/enclave.edl create mode 100644 SampleCode/SampleAttestedTLS/common/err_msg.cpp create mode 100644 SampleCode/SampleAttestedTLS/common/openssl_utility.cpp create mode 100644 SampleCode/SampleAttestedTLS/common/openssl_utility.h create mode 100644 SampleCode/SampleAttestedTLS/common/tcommon.cpp create mode 100644 SampleCode/SampleAttestedTLS/common/ucommon.cpp create mode 100644 SampleCode/SampleAttestedTLS/common/utility.cpp create mode 100644 SampleCode/SampleAttestedTLS/common/utility.h create mode 100644 SampleCode/SampleAttestedTLS/common/verify_callback.cpp create mode 100644 SampleCode/SampleAttestedTLS/non_enc_client/Makefile create mode 100644 SampleCode/SampleAttestedTLS/non_enc_client/client.cpp create mode 100755 SampleCode/SampleAttestedTLS/prepare_sgxssl.sh create mode 100644 SampleCode/SampleAttestedTLS/server/Makefile create mode 100644 SampleCode/SampleAttestedTLS/server/enc/Makefile create mode 100644 SampleCode/SampleAttestedTLS/server/enc/enclave.lds create mode 100644 SampleCode/SampleAttestedTLS/server/enc/openssl_server.cpp create mode 100644 SampleCode/SampleAttestedTLS/server/enc/private_test_key.pem create mode 100644 SampleCode/SampleAttestedTLS/server/enc/server_enc.config.xml create mode 100644 SampleCode/SampleAttestedTLS/server/host/Makefile create mode 100644 SampleCode/SampleAttestedTLS/server/host/host.cpp create mode 100644 SampleCode/SampleAttestedTLS/server/tls_server.edl create mode 100644 SampleCode/SampleAttestedTLS/sgx_socket/htonl.c create mode 100644 SampleCode/SampleAttestedTLS/sgx_socket/htons.c create mode 100644 SampleCode/SampleAttestedTLS/sgx_socket/include/bits/alltypes.h create mode 100644 SampleCode/SampleAttestedTLS/sgx_socket/include/byteswap.h create mode 100644 SampleCode/SampleAttestedTLS/sgx_socket/include/features.h create mode 100644 SampleCode/SampleAttestedTLS/sgx_socket/include/netdb.h create mode 100644 SampleCode/SampleAttestedTLS/sgx_socket/include/netinet/in.h create mode 100644 SampleCode/SampleAttestedTLS/sgx_socket/include/poll.h create mode 100644 SampleCode/SampleAttestedTLS/sgx_socket/include/sgx_socket.edl create mode 100644 SampleCode/SampleAttestedTLS/sgx_socket/include/sys/select.h create mode 100644 SampleCode/SampleAttestedTLS/sgx_socket/include/sys/socket.h create mode 100644 SampleCode/SampleAttestedTLS/sgx_socket/trusted_sgx_socket.cpp create mode 100644 SampleCode/SampleAttestedTLS/sgx_socket/untrusted_sgx_socket.cpp create mode 100644 SampleCode/SampleAttestedTLS/sgxenv.mk create mode 100644 common/inc/sgx_report2.h create mode 100644 common/inc/sgx_ttls.edl create mode 100644 common/inc/sgx_ttls.h create mode 100644 common/inc/sgx_utls.h create mode 100755 linux/installer/common/gen_source/copy_source.py create mode 100644 linux/installer/common/psw-dcap/91-sgx-enclave.rules create mode 100644 linux/installer/common/psw-dcap/92-sgx-provision.rules create mode 100644 linux/installer/common/psw-dcap/BOM_install/libsgx-ae-epid.txt create mode 100644 linux/installer/common/psw-dcap/BOM_install/libsgx-ae-id-enclave.txt create mode 100644 linux/installer/common/psw-dcap/BOM_install/libsgx-ae-le.txt create mode 100644 linux/installer/common/psw-dcap/BOM_install/libsgx-ae-pce.txt create mode 100644 linux/installer/common/psw-dcap/BOM_install/libsgx-ae-qe3.txt create mode 100644 linux/installer/common/psw-dcap/BOM_install/libsgx-ae-qve.txt create mode 100644 linux/installer/common/psw-dcap/BOM_install/libsgx-aesm-ecdsa-plugin.txt create mode 100644 linux/installer/common/psw-dcap/BOM_install/libsgx-aesm-epid-plugin.txt create mode 100644 linux/installer/common/psw-dcap/BOM_install/libsgx-aesm-launch-plugin.txt create mode 100644 linux/installer/common/psw-dcap/BOM_install/libsgx-aesm-pce-plugin.txt create mode 100644 linux/installer/common/psw-dcap/BOM_install/libsgx-aesm-quote-ex-plugin.txt create mode 100644 linux/installer/common/psw-dcap/BOM_install/libsgx-dcap-default-qpl-devel.txt create mode 100644 linux/installer/common/psw-dcap/BOM_install/libsgx-dcap-default-qpl.txt create mode 100644 linux/installer/common/psw-dcap/BOM_install/libsgx-dcap-ql-devel.txt create mode 100644 linux/installer/common/psw-dcap/BOM_install/libsgx-dcap-ql.txt create mode 100644 linux/installer/common/psw-dcap/BOM_install/libsgx-dcap-quote-verify-devel.txt create mode 100644 linux/installer/common/psw-dcap/BOM_install/libsgx-dcap-quote-verify.txt create mode 100644 linux/installer/common/psw-dcap/BOM_install/libsgx-enclave-common-devel.txt create mode 100644 linux/installer/common/psw-dcap/BOM_install/libsgx-enclave-common.txt create mode 100644 linux/installer/common/psw-dcap/BOM_install/libsgx-epid-devel.txt create mode 100644 linux/installer/common/psw-dcap/BOM_install/libsgx-epid.txt create mode 100644 linux/installer/common/psw-dcap/BOM_install/libsgx-headers.txt create mode 100644 linux/installer/common/psw-dcap/BOM_install/libsgx-launch-devel.txt create mode 100644 linux/installer/common/psw-dcap/BOM_install/libsgx-launch.txt create mode 100644 linux/installer/common/psw-dcap/BOM_install/libsgx-pce-logic.txt create mode 100644 linux/installer/common/psw-dcap/BOM_install/libsgx-qe3-logic.txt create mode 100644 linux/installer/common/psw-dcap/BOM_install/libsgx-quote-ex-devel.txt create mode 100644 linux/installer/common/psw-dcap/BOM_install/libsgx-quote-ex.txt create mode 100644 linux/installer/common/psw-dcap/BOM_install/libsgx-ra-network-devel.txt create mode 100644 linux/installer/common/psw-dcap/BOM_install/libsgx-ra-network.txt create mode 100644 linux/installer/common/psw-dcap/BOM_install/libsgx-ra-uefi-devel.txt create mode 100644 linux/installer/common/psw-dcap/BOM_install/libsgx-ra-uefi.txt create mode 100644 linux/installer/common/psw-dcap/BOM_install/libsgx-uae-service.txt create mode 100644 linux/installer/common/psw-dcap/BOM_install/libsgx-urts.txt create mode 100644 linux/installer/common/psw-dcap/BOM_install/sgx-aesm-service.txt create mode 100644 linux/installer/common/psw-dcap/BOM_install/sgx-dcap-pccs.txt create mode 100644 linux/installer/common/psw-dcap/BOM_install/sgx-pck-id-retrieval-tool.txt create mode 100644 linux/installer/common/psw-dcap/BOM_install/sgx-ra-service.txt create mode 100644 linux/installer/common/psw-dcap/BOM_source/psw-dcap-tarball.txt create mode 100644 linux/installer/common/psw-dcap/Makefile create mode 100755 linux/installer/common/psw-dcap/cleanup.sh create mode 100644 linux/installer/common/psw-dcap/installConfig create mode 100755 linux/installer/common/psw-dcap/linksgx.sh create mode 100644 linux/installer/common/psw-dcap/remount-dev-exec.service create mode 100755 linux/installer/common/psw-dcap/startup.sh create mode 100755 linux/installer/rpm/psw-dcap/build.sh create mode 100755 linux/installer/rpm/psw-dcap/clean.sh create mode 100644 linux/installer/rpm/psw-dcap/psw-dcap.spec.tmpl create mode 100755 linux/installer/rpm/psw-dcap/sanitize.sh create mode 100644 sdk/selib/sgx_verify_report2.cpp create mode 100644 sdk/tlibcrypto/ipp/sgx_sha384.cpp create mode 100644 sdk/tlibcrypto/ipp/sgx_sha384_msg.cpp create mode 100644 sdk/tlibcrypto/sgxssl/sgx_sha384.cpp create mode 100644 sdk/tlibcrypto/sgxssl/sgx_sha384_msg.cpp rename sdk/tsafecrt/pal/src/safecrt/{memomve_s.c => memmove_s.c} (100%) create mode 100644 sdk/ttls/Makefile create mode 100644 sdk/ttls/cert_generator.cpp create mode 100644 sdk/ttls/cert_header.h create mode 100644 sdk/ttls/cert_verifier.cpp create mode 100644 sdk/ttls/tsgxsslio.h create mode 100644 sdk/ttls/ttls.cpp create mode 100644 sdk/utls/Makefile create mode 100644 sdk/utls/utls.cpp diff --git a/License.txt b/License.txt index 5d348506d..b97d27f55 100644 --- a/License.txt +++ b/License.txt @@ -1577,3 +1577,55 @@ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + + +21. Remote Attestation based TLS and Sample + +MIT License + +Copyright (c) Open Enclave SDK contributors. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE + +22. musl C + +musl as a whole is licensed under the following standard MIT license: + +---------------------------------------------------------------------- +Copyright © 2005-2020 Rich Felker, et al. + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/Makefile b/Makefile index 34d43badc..c9905ffc2 100644 --- a/Makefile +++ b/Makefile @@ -90,8 +90,12 @@ sdk_install_pkg: sdk 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 +endif +ifeq ("$(wildcard ./external/dcap_source/QuoteGeneration/psw/ae/data/prebuilt/libsgx_id_enclave.signed.so)", "") + ./external/dcap_source/QuoteGeneration/download_prebuilt.sh endif $(CP) external/dcap_source/QuoteGeneration/psw/ae/data/prebuilt/libsgx_qe3.signed.so $(BUILD_DIR) + $(CP) external/dcap_source/QuoteGeneration/psw/ae/data/prebuilt/libsgx_id_enclave.signed.so $(BUILD_DIR) ./linux/installer/bin/build-installpkg.sh psw .PHONY: deb_libsgx_ae_qe3 @@ -101,6 +105,13 @@ ifeq ("$(wildcard ./external/dcap_source/QuoteGeneration/psw/ae/data/prebuilt/li endif $(MAKE) -C external/dcap_source/QuoteGeneration deb_sgx_ae_qe3_pkg $(CP) external/dcap_source/QuoteGeneration/installer/linux/deb/libsgx-ae-qe3/libsgx-ae-qe3*.deb ./linux/installer/deb/sgx-aesm-service/ +.PHONY: deb_libsgx_ae_id_enclave +deb_libsgx_ae_id_enclave: +ifeq ("$(wildcard ./external/dcap_source/QuoteGeneration/psw/ae/data/prebuilt/libsgx_id_enclave.signed.so)", "") + ./external/dcap_source/QuoteGeneration/download_prebuilt.sh +endif + $(MAKE) -C external/dcap_source/QuoteGeneration deb_sgx_ae_id_enclave_pkg + $(CP) external/dcap_source/QuoteGeneration/installer/linux/deb/libsgx-ae-id-enclave/libsgx-ae-id-enclave*.deb ./linux/installer/deb/sgx-aesm-service/ .PHONY: deb_libsgx_qe3_logic deb_libsgx_qe3_logic: psw $(MAKE) -C external/dcap_source/QuoteGeneration deb_sgx_qe3_logic_pkg @@ -139,12 +150,12 @@ deb_libsgx_urts: psw ./linux/installer/deb/libsgx-urts/build.sh .PHONY: deb_libsgx_headers_pkg -deb_libsgx_headers_pkg: +deb_libsgx_headers_pkg: ./linux/installer/deb/libsgx-headers/build.sh ifeq ($(CC_BELOW_5_2), 1) .PHONY: deb_psw_pkg -deb_psw_pkg: deb_libsgx_headers_pkg deb_libsgx_qe3_logic deb_libsgx_pce_logic deb_sgx_aesm_service deb_libsgx_epid deb_libsgx_launch deb_libsgx_quote_ex deb_libsgx_uae_service deb_libsgx_enclave_common deb_libsgx_urts deb_libsgx_ae_qe3 +deb_psw_pkg: deb_libsgx_headers_pkg deb_libsgx_qe3_logic deb_libsgx_pce_logic deb_sgx_aesm_service deb_libsgx_epid deb_libsgx_launch deb_libsgx_quote_ex deb_libsgx_uae_service deb_libsgx_enclave_common deb_libsgx_urts deb_libsgx_ae_qe3 deb_libsgx_ae_id_enclave else .PHONY: deb_libsgx_dcap_default_qpl deb_libsgx_dcap_default_qpl: @@ -188,7 +199,7 @@ deb_sgx_ra_service_pkg: .PHONY: deb_psw_pkg -deb_psw_pkg: deb_libsgx_headers_pkg deb_libsgx_qe3_logic deb_libsgx_pce_logic deb_sgx_aesm_service deb_libsgx_epid deb_libsgx_launch deb_libsgx_quote_ex deb_libsgx_uae_service deb_libsgx_enclave_common deb_libsgx_urts deb_libsgx_ae_qe3 deb_libsgx_dcap_default_qpl deb_libsgx_dcap_pccs deb_libsgx_dcap_ql deb_libsgx_ae_qve deb_sgx_dcap_quote_verify deb_sgx_pck_id_retrieval_tool_pkg deb_sgx_ra_service_pkg +deb_psw_pkg: deb_libsgx_headers_pkg deb_libsgx_qe3_logic deb_libsgx_pce_logic deb_sgx_aesm_service deb_libsgx_epid deb_libsgx_launch deb_libsgx_quote_ex deb_libsgx_uae_service deb_libsgx_enclave_common deb_libsgx_urts 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 deb_sgx_pck_id_retrieval_tool_pkg deb_sgx_ra_service_pkg endif .PHONY: deb_local_repo @@ -202,6 +213,13 @@ ifeq ("$(wildcard ./external/dcap_source/QuoteGeneration/psw/ae/data/prebuilt/li endif $(MAKE) -C external/dcap_source/QuoteGeneration rpm_sgx_ae_qe3_pkg $(CP) external/dcap_source/QuoteGeneration/installer/linux/rpm/libsgx-ae-qe3/libsgx-ae-qe3*.rpm ./linux/installer/rpm/sgx-aesm-service/ +.PHONY: rpm_libsgx_ae_id_enclave +rpm_libsgx_ae_id_enclave: +ifeq ("$(wildcard ./external/dcap_source/QuoteGeneration/psw/ae/data/prebuilt/libsgx_id_enclave.signed.so)", "") + ./external/dcap_source/QuoteGeneration/download_prebuilt.sh +endif + $(MAKE) -C external/dcap_source/QuoteGeneration rpm_sgx_ae_id_enclave_pkg + $(CP) external/dcap_source/QuoteGeneration/installer/linux/rpm/libsgx-ae-id-enclave/libsgx-ae-id-enclave*.rpm ./linux/installer/rpm/sgx-aesm-service/ .PHONY: rpm_libsgx_pce_logic rpm_libsgx_pce_logic: psw $(MAKE) -C external/dcap_source/QuoteGeneration rpm_sgx_pce_logic_pkg @@ -244,12 +262,12 @@ rpm_sdk_pkg: sdk ./linux/installer/rpm/sdk/build.sh .PHONY: rpm_libsgx_headers_pkg -rpm_libsgx_headers_pkg: +rpm_libsgx_headers_pkg: ./linux/installer/rpm/libsgx-headers/build.sh ifeq ($(CC_BELOW_5_2), 1) .PHONY: rpm_psw_pkg -rpm_psw_pkg: rpm_libsgx_headers_pkg rpm_libsgx_pce_logic rpm_libsgx_qe3_logic rpm_sgx_aesm_service rpm_libsgx_epid rpm_libsgx_launch rpm_libsgx_quote_ex rpm_libsgx_uae_service rpm_libsgx_enclave_common rpm_libsgx_urts rpm_libsgx_ae_qe3 +rpm_psw_pkg: rpm_libsgx_headers_pkg rpm_libsgx_pce_logic rpm_libsgx_qe3_logic rpm_sgx_aesm_service rpm_libsgx_epid rpm_libsgx_launch rpm_libsgx_quote_ex rpm_libsgx_uae_service rpm_libsgx_enclave_common rpm_libsgx_urts rpm_libsgx_ae_qe3 rpm_libsgx_ae_id_enclave else .PHONY: rpm_libsgx_dcap_default_qpl rpm_libsgx_dcap_default_qpl: @@ -291,7 +309,7 @@ rpm_sgx_ra_service_pkg: $(CP) external/dcap_source/tools/SGXPlatformRegistration/build/installer/libsgx-ra-*rpm ./linux/installer/rpm/sgx-aesm-service/ .PHONY: rpm_psw_pkg -rpm_psw_pkg: rpm_libsgx_headers_pkg rpm_libsgx_pce_logic rpm_libsgx_qe3_logic rpm_sgx_aesm_service rpm_libsgx_epid rpm_libsgx_launch rpm_libsgx_quote_ex rpm_libsgx_uae_service rpm_libsgx_enclave_common rpm_libsgx_urts rpm_libsgx_ae_qe3 rpm_libsgx_dcap_default_qpl rpm_libsgx_dcap_pccs rpm_libsgx_dcap_ql rpm_libsgx_ae_qve rpm_sgx_dcap_quote_verify rpm_sgx_pck_id_retrieval_tool_pkg rpm_sgx_ra_service_pkg +rpm_psw_pkg: rpm_libsgx_headers_pkg rpm_libsgx_pce_logic rpm_libsgx_qe3_logic rpm_sgx_aesm_service rpm_libsgx_epid rpm_libsgx_launch rpm_libsgx_quote_ex rpm_libsgx_uae_service rpm_libsgx_enclave_common rpm_libsgx_urts 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 rpm_sgx_pck_id_retrieval_tool_pkg rpm_sgx_ra_service_pkg endif .PHONY: rpm_local_repo @@ -335,6 +353,7 @@ ifeq ("$(shell test -f external/dcap_source/QuoteVerification/Makefile && echo M @$(MAKE) -C external/dcap_source/QuoteGeneration clean ./external/dcap_source/QuoteGeneration/installer/linux/deb/libsgx-ae-qve/clean.sh ./external/dcap_source/QuoteGeneration/installer/linux/deb/libsgx-ae-qe3/clean.sh + ./external/dcap_source/QuoteGeneration/installer/linux/deb/libsgx-ae-id-enclave/clean.sh ./external/dcap_source/QuoteGeneration/installer/linux/deb/libsgx-dcap-default-qpl/clean.sh ./external/dcap_source/QuoteGeneration/installer/linux/deb/libsgx-dcap-ql/clean.sh ./external/dcap_source/QuoteGeneration/installer/linux/deb/libsgx-pce-logic/clean.sh @@ -343,6 +362,7 @@ ifeq ("$(shell test -f external/dcap_source/QuoteVerification/Makefile && echo M ./external/dcap_source/QuoteGeneration/installer/linux/deb/sgx-dcap-pccs/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 + ./external/dcap_source/QuoteGeneration/installer/linux/rpm/libsgx-ae-id-enclave/clean.sh ./external/dcap_source/QuoteGeneration/installer/linux/rpm/libsgx-dcap-default-qpl/clean.sh ./external/dcap_source/QuoteGeneration/installer/linux/rpm/libsgx-dcap-ql/clean.sh ./external/dcap_source/QuoteGeneration/installer/linux/rpm/libsgx-pce-logic/clean.sh diff --git a/Makefile.psw_dcap b/Makefile.psw_dcap new file mode 100644 index 000000000..3d18f6791 --- /dev/null +++ b/Makefile.psw_dcap @@ -0,0 +1,71 @@ +# +# 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 buildenv.mk + +define DIR_EXISTS +$(shell test -d $(1) && echo "$(1)") +endef + +SGX_SDK := /tmp/intel/sgxsdk +export SGX_SDK + +.PHONY: build psw dcap install clean sdk install_sdk + +build: psw dcap + +psw: install_sdk + @$(MAKE) -C psw/ USE_OPT_LIBS=$(USE_OPT_LIBS) + +dcap: install_sdk + @$(MAKE) -C external/dcap_source/ + +install: + @$(MAKE) -I linux/installer/common/psw-dcap -f linux/installer/common/psw-dcap/Makefile SRCDIR=. DESTDIR=$(DESTDIR) install + +clean: + @$(MAKE) -C psw/ clean + @$(MAKE) -C external/dcap_source/ clean + @$(MAKE) -C sdk/ clean +ifneq ($(call DIR_EXISTS,$(SGX_SDK)),) + $(SGX_SDK)/uninstall.sh +endif + +sdk: + $(MAKE) -C sdk/ USE_OPT_LIBS=$(USE_OPT_LIBS) + $(MAKE) -C external/dcap_source/QuoteVerification/dcap_tvl clean + $(MAKE) -C external/dcap_source/QuoteVerification/dcap_tvl + +install_sdk: sdk + ./linux/installer/bin/build-installpkg.sh sdk +ifeq ($(call DIR_EXISTS,$(SGX_SDK)),) + ./linux/installer/bin/sgx_linux_x64_sdk_*.bin --prefix=$(dir $(SGX_SDK)) +endif diff --git a/README.md b/README.md index 56fa4df0f..02e115e55 100644 --- a/README.md +++ b/README.md @@ -91,8 +91,8 @@ Build the Intel(R) SGX SDK and Intel(R) SGX PSW Package * Ubuntu\* 18.04 LTS Server 64bits * Ubuntu\* 20.04 LTS Desktop 64bits * Ubuntu\* 20.04 LTS Server 64bits - * Red Hat Enterprise Linux Server release 8.2 64bits - * CentOS 8.2 64bits + * Red Hat Enterprise Linux Server release 8.4 64bits + * CentOS Stream 8 64bits - Use the following command(s) to install the required tools to build the Intel(R) SGX SDK: * On Ubuntu 18.04: @@ -103,13 +103,13 @@ Build the Intel(R) SGX SDK and Intel(R) SGX PSW Package ``` $ sudo apt-get install build-essential ocaml ocamlbuild automake autoconf libtool wget python-is-python3 libssl-dev git cmake perl ``` - * On Red Hat Enterprise Linux 8.2: + * On Red Hat Enterprise Linux 8.4: ``` $ sudo yum groupinstall 'Development Tools' $ sudo yum install ocaml ocaml-ocamlbuild wget python2 openssl-devel git cmake perl $ sudo alternatives --set python /usr/bin/python2 ``` - * On CentOS 8.2: + * On CentOS Stream 8: ``` $ sudo dnf group install 'Development Tools' $ sudo dnf --enablerepo=PowerTools install ocaml ocaml-ocamlbuild redhat-rpm-config openssl-devel wget rpm-build git cmake perl python2 @@ -122,11 +122,11 @@ Build the Intel(R) SGX SDK and Intel(R) SGX PSW Package ``` $ sudo apt-get install libssl-dev libcurl4-openssl-dev protobuf-compiler libprotobuf-dev debhelper cmake reprepro unzip ``` - * On Red Hat Enterprise Linux 8.2: + * On Red Hat Enterprise Linux 8.4: ``` $ sudo yum install openssl-devel libcurl-devel protobuf-devel cmake rpm-build createrepo yum-utils ``` - * On CentOS 8.2: + * On CentOS Stream 8: ``` $ sudo dnf --enablerepo=PowerTools install openssl-devel libcurl-devel protobuf-devel cmake rpm-build createrepo yum-utils ``` @@ -231,7 +231,7 @@ You can find the tools and libraries generated in the `build/linux` directory. ``` $ make deb_psw_pkg DEBUG=1 ``` - * On Red Hat Enterprise Linux 8.2 and CentOS 8.2: + * On Red Hat Enterprise Linux 8.4 and CentOS Stream 8: ``` $ make rpm_psw_pkg ``` @@ -275,12 +275,12 @@ You can find the tools and libraries generated in the `build/linux` directory. **Note**: The above command builds the local package repository. If you want to use it, you need to add it to the system repository configuration. Since the local package repository is not signed with GPG, you should ignore the gpgcheck when installing the packages. - To add the local RPM package repository to the system repository configuration, you can use the following command. You need to replace PATH_TO_LOCAL_REPO with the proper path on your system: - * On Red Hat Enterprise Linux 8.2 and CentOS 8.2: + * On Red Hat Enterprise Linux 8.4 and CentOS Stream 8: ``` $ sudo yum-config-manager --add-repo file://PATH_TO_LOCAL_REPO ``` - To ignore the gpgcheck when you install the package, enter the following command: - * On Red Hat Enterprise Linux 8.2 and CentOS 8.2: + * On Red Hat Enterprise Linux 8.4 and CentOS Stream 8: ``` $ sudo yum --nogpgcheck install ``` @@ -293,14 +293,14 @@ Install the Intel(R) SGX SDK * Ubuntu\* 18.04 LTS Server 64bits * Ubuntu\* 20.04 LTS Desktop 64bits * Ubuntu\* 20.04 LTS Server 64bits - * Red Hat Enterprise Linux Server release 8.2 64bits - * CentOS 8.2 64bits + * Red Hat Enterprise Linux Server release 8.4 64bits + * CentOS Stream 8 64bits - Use the following command to install the required tool to use Intel(R) SGX SDK: * On Ubuntu 18.04 and Ubuntu 20.04: ``` $ sudo apt-get install build-essential python ``` - * On Red Hat Enterprise Linux 8.2 and CentOS 8.2: + * On Red Hat Enterprise Linux 8.4 and CentOS Stream 8: ``` $ sudo yum groupinstall 'Development Tools' $ sudo yum install python2 @@ -357,8 +357,8 @@ Install the Intel(R) SGX PSW * Ubuntu\* 18.04 LTS Server 64bits * Ubuntu\* 20.04 LTS Desktop 64bits * Ubuntu\* 20.04 LTS Server 64bits - * Red Hat Enterprise Linux Server release 8.2 64bits - * CentOS 8.2 64bits + * Red Hat Enterprise Linux Server release 8.4 64bits + * CentOS Stream 8 64bits - Ensure that you have a system with the following required hardware: * 6th Generation Intel(R) Core(TM) Processor or newer - Configure the system with the **Intel SGX hardware enabled** option and install Intel(R) SGX driver in advance. @@ -368,11 +368,11 @@ Install the Intel(R) SGX PSW ``` $ sudo apt-get install libssl-dev libcurl4-openssl-dev libprotobuf-dev ``` - * On Red Hat Enterprise Linux 8.2: + * On Red Hat Enterprise Linux 8.4: ``` $ sudo yum install openssl-devel libcurl-devel protobuf-devel ``` - * On CentOS 8.2: + * On CentOS Stream 8: ``` $ sudo dnf --enablerepo=PowerTools install libcurl-devel protobuf-devel ``` @@ -382,7 +382,7 @@ The SGX PSW provides 3 services: launch, EPID-based attestation, and algorithm a #### Using the local repo(recommended) -| |Ubuntu 18.04 and Ubuntu 20.04|Red Hat Enterprise Linux 8.2, CentOS 8.2| +| |Ubuntu 18.04 and Ubuntu 20.04|Red Hat Enterprise Linux 8.4, CentOS Stream 8| | ------------ | ------------ | ------------ | |launch service |apt-get install libsgx-launch libsgx-urts|yum install libsgx-launch libsgx-urts| |EPID-based attestation service|apt-get install libsgx-epid libsgx-urts|yum install libsgx-epid libsgx-urts| @@ -407,7 +407,10 @@ Some packages are configured with recommended dependency on other packages that ``` --no-install-recommends ``` -**NOTE** On rpm based system, rpmbuild>=4.12 is required to enable similar features. +* On Red Hat Enterprise Linux 8.4 and CentOS Stream 8: +``` + --setopt=install_weak_deps=False +``` ### ECDSA attestation To enable ECDSA attestation diff --git a/SampleCode/Cxx14SGXDemo/Enclave/TrustedLibrary/Libcxx.cpp b/SampleCode/Cxx14SGXDemo/Enclave/TrustedLibrary/Libcxx.cpp index 9bb337ce9..9939feefc 100644 --- a/SampleCode/Cxx14SGXDemo/Enclave/TrustedLibrary/Libcxx.cpp +++ b/SampleCode/Cxx14SGXDemo/Enclave/TrustedLibrary/Libcxx.cpp @@ -294,8 +294,8 @@ void ecall_cxx14_equal_mismatch_permutation_new_overloads() printf("first pair of different values: (%d, %d)\n", *diff_pair.first, *diff_pair.second); - constexpr auto v_permu1 = {1, 2, 3, 4, 5}; - constexpr auto v_permu2 = {3, 5, 4, 1, 9}; + auto v_permu1 = {1, 2, 3, 4, 5}; + auto v_permu2 = {3, 5, 4, 1, 9}; printf("v_permu1 and v_permu2 is_permutation: %s\n", std::is_permutation(v_permu1.begin(), v_permu1.end(), v_permu2.begin()) ? "True" : "False"); diff --git a/SampleCode/SampleAttestedTLS/AttestedTLSREADME.md b/SampleCode/SampleAttestedTLS/AttestedTLSREADME.md new file mode 100644 index 000000000..658ead938 --- /dev/null +++ b/SampleCode/SampleAttestedTLS/AttestedTLSREADME.md @@ -0,0 +1,145 @@ +# Secure Channel in Intel SGX SDK + + As Intel SGX SDK is getting adopted into more realistic scenarios, we are receiving requests from Intel SGX SDK developers for adding secure channel support. + + We do have the attestation sample that shows how to conduct remote attestation between two enclaves and establish a `proprietary` channel based on asymmetric keys exchanged during the attestation process. It demonstrates how to conduct mutual attestation but it does not go all the way to show how to establish a fully secure channel. + + Most of the real world software uses TLS-like standard protocol through popular TLS APIs (currently OpenSSL) for establishing secure channels. Thus, instead of inventing a new communication protocol, we implemented `Attested TLS` feature to address above customer need by adding a set of new Intel SGX SDK APIs to help seamlessly integrate remote attestation into the popular TLS protocol for establishing an TLS channel with attested connecting party without modifying existing TLS APIs (currently supported OpenSSL inside SGX enclave). + +# What is an Attested TLS channel + +The remote attestation feature that comes with Intel SGX could significantly improve a TLS endpoint's (client or server) trustworthiness for a TLS connection starting or terminating inside an enclave. An Attested TLS channel is a TLS channel that integrates remote attestation validation as part of the TLS channel establishing process. Once established, it guarantees that an attested connecting party is running inside a TEE with expected identity. + +There are two types of Attested TLS connections: +1. Both ends of an Attested TLS channel terminate inside SGX enclaves + - Guarantee that both parties of a TLS channel are running inside SGX enclaves + - Intel SGX SDK sample: SampleAttestedTLS\client +2. Only one end of an Attested TLS channel terminate inside SGX enclaves + - In this case, the assumption is that the end not terminated inside an SGX encalve is a trust party. The most common use case is, this non-enclave party might have secrets to securely share with the other party through an Attested TLS channel. + - Intel SGX SDK sample: SampleAttestedTLS\non_enc_client + +## Prerequisites + + The audience is assumed to be familiar with: + + - [Transport Layer Security (TLS)](https://en.wikipedia.org/wiki/Transport_Layer_Security) a cryptographic protocol designed to provide communications security over a computer network. + + - [SGX Enclave Attestation](https://software.intel.com/content/www/us/en/develop/topics/software-guard-extensions/attestation-services.html?wapkw=Intel%20SGX%20attestation): Attestation is the concept of a HW entity or of a combination of HW and SW gaining the trust of a remote provider or producer. + +### How it works + + By taking advantage of the fact that TLS involving parties use public-key cryptography for identity authentication during the [TLS handshaking process](https://en.wikipedia.org/wiki/Transport_Layer_Security#TLS_handshake), the Attested TLS feature uses a self-signed X509.V3 certificate to represent a TLS endpoint's identity. We make this certificate cryptographically bound to this specific enclave instance by adding a custom certificate extension (called quote extension) with this enclave's attestation quote that has the certificate's public key information embedded. + + A new API tee_get_attestation_certificate_with_evidence was added for generating such a self-signed certificate for use in the TLS handshaking process + +#### Generate TLS certificate + + A connecting party needs to provide a key pair for the tee_get_certificate_with_evidence api to produce a self-signed certificate. These keys could be transient keys and unique for each new TLS connection. + - a private key (pkey): used for generating a certificate and represent the identity of the TLS connecting party + - a public key (pubkey): used in the TLS handshake process to create a digital signature in every TLS connection, + +``` +/** + * tee_get_certificate_with_evidence + * + * This function generates a self-signed x.509 certificate with embedded + * evidence generated for the enclave. + * This function only runs inside enclave + * + * + * @param[in] subject_name a string containing an X.509 distinguished + * name (DN) for customizing the generated certificate. This name is also used + * as the issuer name because this is a self-signed certificate + * See RFC5280 (https://tools.ietf.org/html/rfc5280) for details + * Example value "CN=Intel SGX Enclave,O=Intel Corporation,C=US" + * + * @param[in] p_prv_key A private key used to sign this certificate + * @param[in] private_key_size The size of the private_key in bytes + * @param[in] p_pub_key A public key used as the certificate's subject key + * @param[in] public_key_size The size of the public key in bytes + * @param[out] pp_output_cert A pointer to output certificate pointer + * @param[out] p_output_cert_size A pointer to the size of the output certificate above + * + * @return SGX_QL_SUCCESS on success + */ +quote3_error_t SGXAPI tee_get_certificate_with_evidence( + const unsigned char *p_subject_name, + const uint8_t *p_prv_key, + size_t private_key_size, + const uint8_t *p_pub_key, + size_t public_key_size, + uint8_t **pp_output_cert, + size_t *p_output_cert_size); + +``` +#### Authenticate peer certificate + +Upon receiving a certificate from the peer endpoint, a connecting party needs to perform peer certificate validation. + +In this feature, instead of using the TLS API's default authentication routine, which validates the certificate against a pre-determined CAs for authentication, an application needs to conduct "Extended custom certificate validation" inside the peer custom certificate verification callback (cert_verify_callback), which is supported by all the popular TLS APIs. + +``` +For example: + OpenSSL: + void SSL_CTX_set_verify( + SSL_CTX *ctx, int mode, + int (*verify_callback)(int, X509_STORE_CTX *)) +``` +##### Custom extended certificate validation + +The following four validation steps are performed inside the cert_verify_callback + 1. Validate certificate + - Verify the signature of the self-signed certificate to ascertain that the attestation evidence is genuine and unmodified. + 2. Validate the evidence + - Extract this evidence extension from the certificate + - Perform evidence validation + 3. Validate peer enclave's identity + - Validate the enclave’s identity (e.g., MRENCLAVE in SGX) against the expected list. This check ensures only the intended party is allowed to connect to. + + A new SGX API, tee_verify_certificate_with_evidence_host() or tee_verify_ceritificate_with_evidence() for inside enclave calls, was added to perform step 1-2 and leaving step 3 to application for business logic. + + A caller wants to fail cert_verify_callback with non-zero code if either certificate signature validation failed or unexpected TEE identity was found. This failure return will cause the TLS handshaking process to terminate immediately, thus preventing establishing connection with an unqualified connecting party. + +``` +/** + * tee_verify_certificate_with_evidence_host for outside enclave calls + * tee_verify_certificate_with_evidence for inside enclave calls + * + * This function performs SGX quote and X.509 certificate verification. The + * validation includes extracting SGX quote extension from the + * certificate before validating the quote + * + * @param[in] p_cert_in_der A pointer to buffer holding certificate contents + *  in DER format + * @param[in] cert_in_der_len The size of certificate buffer above + * @param[in] expiration_check_date The date that verifier will use to determine if any of the inputted collateral have expired + * @param[out] p_qv_result SGX quote verification result + * @param[out] pp_supplemental_data A pointer to SGX quote verification + * supplemental data pointer + * @param[out] p_supplemental_data_size The size of supplemental data above + * + * @retval SGX_SUCCESS on a successful validation + * @retval SGX_QUOTE_VERIFY_FAILURE on quote verification failure + * @retval SGX_QUOTE_VERIFY_WARNING on quote verification failed with non-critical + * error, pls refer to output parameters 'p_qv_result' and + * 'p_supplemental_data' to customize your own verification policy + * @retval SGX_ERROR_INVALID_PARAMETER At least one parameter is invalid + * @retval SGX_ERROR_UNEXPECTED general failure + */ +#if INSIDE_ENCLAVE + quote3_error_t SGXAPI tee_verify_certificate_with_evidence( +#else OUTSIDE_ENCLAVE_CALL + quote3_error_t SGXAPI tee_verify_certificate_with_evidence_host( +#endif + const uint8_t *p_cert_in_der, + size_t cert_in_der_len, + const time_t expiration_check_date, + sgx_ql_qv_result_t *p_qv_result, + uint8_t **pp_supplemental_data, + uint32_t *p_supplemental_data_size); +``` + Once the received certificate passed above validation, the TLS handshaking process can continue until an connection is established. Once connected, a connecting party can be confident that the other connecting party is indeed a specific enclave image running inside the enclave. + +In the case of establishing a Attested TLS channel between two enclaves, the same authentication process could be applied to both directions in the TLS handshaking process to establish an mutually attested TLS channel between two enclaves. + + Please see OE SDK samples for how to use those new APIs along with your favorite TLS library. diff --git a/SampleCode/SampleAttestedTLS/Makefile b/SampleCode/SampleAttestedTLS/Makefile new file mode 100644 index 000000000..26b2b49e8 --- /dev/null +++ b/SampleCode/SampleAttestedTLS/Makefile @@ -0,0 +1,71 @@ +# +# 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 ./sgxenv.mk + +.PHONY: all PREPARE_SGX_SSL build clean run + +all: build + +# make sgxssl lib beforehand +PREPARE_SGXSSL := ./prepare_sgxssl.sh +SGXSSL_HEADER_CHECK := $(SGXSSL_PKG_PATH)/include/openssl/opensslconf.h +PREPARE_SGX_SSL: + @chmod 755 $(PREPARE_SGXSSL) + @test -f $(SGXSSL_PKG_PATH)/lib64/lib$(OpenSSL_Crypto_Library_Name).a && test -f $(SGXSSL_PKG_PATH)/lib64/lib$(OpenSSL_SSL_Library_Name).a && test -f $(SGXSSL_PKG_PATH)/lib64/lib$(SGXSSL_Library_Name).a && test -f $(SGXSSL_HEADER_CHECK) || $(PREPARE_SGXSSL) + @$(info "NOTE: sgxssl prepared") + +$(SGXSSL_HEADER_CHECK) : PREPARE_SGX_SSL + +build: $(SGXSSL_HEADER_CHECK) + $(MAKE) -C server + $(MAKE) -C client + $(MAKE) -C non_enc_client + +clean: + $(MAKE) -C server clean + $(MAKE) -C client clean + $(MAKE) -C non_enc_client clean + +run: + echo "Launch processes to establish an Attested TLS between two enclaves" + ./server/host/tls_server_host ./server/enc/tls_server_enclave.signed.so -port:12341 & + sleep 2 + ./client/host/tls_client_host ./client/enc/tls_client_enclave.signed.so -server:localhost -port:12341 + echo "Launch processes to establish an Attested TLS between an non-encalve TLS client and an TLS server running inside an enclave" + ./server/host/tls_server_host ./server/enc/tls_server_enclave.signed.so -port:12345 & + sleep 2 + ./non_enc_client/tls_non_enc_client -server:localhost -port:12345 + +run-server-in-loop: + echo "Launch long-running Attested TLS server" + ./server/host/tls_server_host ./server/enc/tls_server_enclave.signed.so -port:12341 -server-in-loop diff --git a/SampleCode/SampleAttestedTLS/README.md b/SampleCode/SampleAttestedTLS/README.md new file mode 100644 index 000000000..1e0b0b952 --- /dev/null +++ b/SampleCode/SampleAttestedTLS/README.md @@ -0,0 +1,129 @@ +## Prerequisites + The audience is assumed to be familiar: + [What is an Attested TLS channel](AttestedTLSREADME.md#what-is-an-attested-tls-channel) + +# The Attested TLS sample + +It has the following properties: + +- Demonstrates attested TLS feature + - between two enclaves + - between an enclave application and a non enclave application +- Use of SgxSSL libraries inside enclaves for TLS +- Use of following Enclave APIs + - tee_get_certificate_with_evidence + - tee_free_certificate + - tee_verify_certificate_with_evidence + - tee_verify_certificate_with_evidence_host + +**Note: Currently this sample only works on SGX-FLC systems.** The underlying SGX library support for end-to-end remote attestation is required but available only on SGX-FLC system. There is no plan to back port those libraries to either SGX1 system or software emulator. + +**Additional Notes to this Sample: +- Only ECDSA attestation is supported. +- To make sure you can run this sample successfully, please refer to the samples in Intel(R) SGX DCAP repo: + https://github.com/intel/SGXDataCenterAttestationPrimitives + Steps in Readme in the 2 samples - QuoteGenerationSample and QuoteVerificationSample also apply to this sample. + Please make sure the above 2 samples work good before you make and run this project. + +## Overall Sample Configuration + +This sample demonstrates 2 types of TLS channels +- Attested TLS channel between two enclaves + - Both TLS client and server are hosted in enclave +- Attested TLS channel between a non enclave application and an enclave + - TLS server is hosted in enclave, TLS client is hosted in non-enclave environment + +Note: Both of them can run on the same machine or separate machines. + +### Server application + - Host part (tls_server_host) + - Instantiate an enclave before transitioning the control into the enclave via an ecall. + - Enclave (tls_server_enclave.signed.so) + - Call tee_get_certificate_with_evidence to generate an certificate + - Use SgxSSL API to configure a TLS server using the generated certificate + - Launch a TLS server and wait for client connection request + - Read client payload and reply with server payload + - How to launch a server instance +``` +./server/host/tls_server_host ./server/enc/tls_server_enclave.signed.so -port:12341 +``` +### Enclave Client application + - Host part (tls_client_host) + - Instantiate an enclave before transitioning the control into the enclave via an ecall. + - Enclave (tls_client_enclave.signed.so) + - Connect to server port via socket + - Use SgxSSL API to configure a TLS client + - Call tee_verify_certificate_with_evidence to verify the certificate and SGX ECDSA quote + - Call tee_get_certificate_with_evidence to generate an certificate as client's certificate + - Send client payload and wait for server's payload + - How to launch a client instance +``` +./client/host/tls_client_host ./client/enc/tls_client_enclave.signed.so -server:localhost -port:12341 +``` + +### Non-enclave Client application + - When used in this scenario, this non-enclave client is assumed to be a trusted party holding secrets and only shares it with the server after the server is validated + - Connect to server port via socket + - Use OpenSSL API to configure a TLS client + - Call tee_verify_certificate_with_evidence_host to verify the certificate and SGX ECDSA quote + - Send client payload and wait for server's payload + +``` +./non_enc_client/tls_non_enc_client -server:localhost -port:12341 +``` + +## Build and run + ```bash + make + make run + ``` + +Note: + - Intel(R) ECDSA quote generation will load Intel(R) signed PCE, QE, which need to be run with an uid in `sgx_prv` group. Use below command to add the user running the process to `sgx_prv` group, then try to launch application again: + $ sudo usermod -a -G sgx_prv + - This sample has a dependency on the socket support, included in this project directory sgx_socket. + - Option SGX_DEBUG is provided here to disable or enable debug symbols in the object file. + Use it with make command: + "make SGX_DEBUG=0" to turn off debug symbols, and "make SGX_DEBUG=1" to turn on debug symbols. + - TLS support is provided by intel-sgx-ssl project on the branch support_tls. + Repo URL: https://github.com/intel/intel-sgx-ssl/tree/support_tls + Currently the branch only provides basic functions for TLS session between server and client inside enclave + running in this sample. + The project has a pre-preparation script - prepare_sgxssl.sh to prepare the SgxSSL libraries and link to them in + the Makefile. + - Limitation: No Simulation mode is supported. + +### Running attested TLS server in loop +By default the server exits after completing a TLS session with a client. `-server-in-loop` run-time option changes this behavior to allow the TLS server to handle multiple client requests. + +```bash +./server/host/tls_server_host ./server/enc/tls_server_enclave.signed.so -port:12341 -server-in-loop +or +make run-server-in-loop +``` + +### Recommended TLS configurations when using OpenSSL + + It is strongly recommended that developers configure OpenSSL to restrict the TLS versions, cipher suites and elliptic curves to be used for TLS connections to enclave: + + - TLS protocol versions + - TLS 1.2 + - TLS 1.3 + - TLS 1.3 cipher suites (in the exact order) + - TLS13-AES-256-GCM-SHA384 + - TLS13-AES-128-GCM-SHA256 + - TLS 1.2 cipher suites (in the exact order) + - ECDHE-ECDSA-AES128-GCM-SHA256 + - ECDHE-ECDSA-AES256-GCM-SHA384 + - ECDHE-RSA-"AES128-GCM-SHA256 + - ECDHE-RSA-AES256-GCM-SHA384 + - ECDHE-ECDSA-AES128-SHA256 + - ECDHE-ECDSA-AES256-SHA384 + - ECDHE-RSA-AES128-SHA256 + - ECDHE-RSA-AES256-SHA384 + - Elliptic curves + - P-521 + - P-384 + - P-256 + + This sample illustrates how to use [`initalize_ssl_context()`](common/openssl_utility.cpp#L118) to configure the `SSL_CTX` as suggested in both the [server](server/enc/openssl_server.cpp#L147) and the [client](client/enc/openssl_client.cpp#L200) modules. diff --git a/SampleCode/SampleAttestedTLS/client/Makefile b/SampleCode/SampleAttestedTLS/client/Makefile new file mode 100644 index 000000000..42fa8142f --- /dev/null +++ b/SampleCode/SampleAttestedTLS/client/Makefile @@ -0,0 +1,65 @@ +# +# 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. +# +# + +# MIT License +# +# Copyright (c) Open Enclave SDK contributors. +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in all +# copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +# SOFTWARE + +all: build + +build: + $(MAKE) -C enc + $(MAKE) -C host + +clean: + $(MAKE) -C enc clean + $(MAKE) -C host clean + +run: + host/tls_client_host ./enc/tls_client_enclave.signed.so -server:localhost -port:12341 diff --git a/SampleCode/SampleAttestedTLS/client/enc/Makefile b/SampleCode/SampleAttestedTLS/client/enc/Makefile new file mode 100644 index 000000000..ed6a666e8 --- /dev/null +++ b/SampleCode/SampleAttestedTLS/client/enc/Makefile @@ -0,0 +1,96 @@ +# +# 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. +# +# + +# +# Copyright (C) 2011-2022 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 ../../sgxenv.mk + +INCDIR := $(SGX_SDK)/include # EDL search path +SOCKETINCDIR = $(SOCKET_DIR)/include #socket EDL search path +SSLINCDIR = $(SGXSSL_PKG_PATH)/include +ENC_TLS_CLIENT_Name := tls_client_enclave.so +Signed_ENC_TLS_CLIENT_Name := tls_client_enclave.signed.so + +.PHONY: all build clean run + +SRC_FILES := openssl_client.cpp ../../sgx_socket/trusted_sgx_socket.cpp ../../sgx_socket/htons.c ../../sgx_socket/htonl.c ../../common/verify_callback.cpp ../../common/utility.cpp ../../common/openssl_utility.cpp ../../common/tcommon.cpp ../../common/err_msg.cpp +OBJ_FILES := tls_client_t.o trusted_sgx_socket.o htons.o htonl.o openssl_client.o verify_callback.o utility.o openssl_utility.o tcommon.o err_msg.o + +all: + $(MAKE) build + $(MAKE) sign + +build: + @ echo "Compilers used: $(CC), $(CXX)" + $(SGX_EDGER8R) --trusted ../tls_client.edl --search-path . \ + --search-path ../../common \ + --search-path $(INCDIR) \ + --search-path $(SOCKETINCDIR) \ + --search-path $(SSLINCDIR) \ + + $(CXX) -c -DM_TLS_CLIENT $(Enclave_Cpp_Flags) -I. -include "tsgxsslio.h" -std=c++11 $(SRC_FILES) + $(CC) -c $(Enclave_C_Flags) -I. ./tls_client_t.c + $(CXX) -o $(ENC_TLS_CLIENT_Name) $(OBJ_FILES) $(Enclave_Link_Flags) + +sign: + $(SGX_ENCLAVE_SIGNER) sign -key private_test_key.pem -enclave $(ENC_TLS_CLIENT_Name) \ + -out $(Signed_ENC_TLS_CLIENT_Name) -config client_enc.config.xml + +clean: + rm -f ./*.o $(ENC_TLS_CLIENT_Name) $(Signed_ENC_TLS_CLIENT_Name) tls_client_t.* tls_client_args.h diff --git a/SampleCode/SampleAttestedTLS/client/enc/client_enc.config.xml b/SampleCode/SampleAttestedTLS/client/enc/client_enc.config.xml new file mode 100644 index 000000000..99434e818 --- /dev/null +++ b/SampleCode/SampleAttestedTLS/client/enc/client_enc.config.xml @@ -0,0 +1,12 @@ + + 0 + 0 + 0x40000 + 0x100000 + 2 + 1 + + 0 + 0 + 0xFFFFFFFF + diff --git a/SampleCode/SampleAttestedTLS/client/enc/enclave.lds b/SampleCode/SampleAttestedTLS/client/enc/enclave.lds new file mode 100644 index 000000000..127093a88 --- /dev/null +++ b/SampleCode/SampleAttestedTLS/client/enc/enclave.lds @@ -0,0 +1,10 @@ +client_enclave.so +{ + global: + g_global_data_sim; + g_global_data; + enclave_entry; + g_peak_heap_used; + local: + *; +}; diff --git a/SampleCode/SampleAttestedTLS/client/enc/openssl_client.cpp b/SampleCode/SampleAttestedTLS/client/enc/openssl_client.cpp new file mode 100644 index 000000000..36b57bc99 --- /dev/null +++ b/SampleCode/SampleAttestedTLS/client/enc/openssl_client.cpp @@ -0,0 +1,290 @@ +/** +* +* MIT License +* +* Copyright (c) Open Enclave SDK contributors. +* +* Permission is hereby granted, free of charge, to any person obtaining a copy +* of this software and associated documentation files (the "Software"), to deal +* in the Software without restriction, including without limitation the rights +* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +* copies of the Software, and to permit persons to whom the Software is +* furnished to do so, subject to the following conditions: +* +* The above copyright notice and this permission notice shall be included in all +* copies or substantial portions of the Software. +* +* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +* SOFTWARE +* +*/ + +#include +#include +#include +#include +#include +#include +#include +#include +#include "../../common/openssl_utility.h" +#include "tls_client_t.h" +#include +#include +#include +#include +#include + + +int verify_callback(int preverify_ok, X509_STORE_CTX* ctx); + +extern "C" +{ + int launch_tls_client(char* server_name, char* server_port); +}; + + +unsigned long inet_addr2(const char *str) +{ + unsigned long lHost = 0; + char *pLong = (char *)&lHost; + char *p = (char *)str; + while (p) + { + *pLong++ = atoi(p); + p = strchr(p, '.'); + if (p) + ++p; + } + return lHost; +} +// This routine conducts a simple HTTP request/response communication with +// server +int communicate_with_server(SSL* ssl) +{ + unsigned char buf[200]; + int ret = 1; + int error = 0; + int len = 0; + int bytes_written = 0; + int bytes_read = 0; + + // Write an GET request to the server + t_print(TLS_CLIENT "-----> Write to server:\n"); + len = snprintf((char*)buf, sizeof(buf) - 1, CLIENT_PAYLOAD); + while ((bytes_written = SSL_write(ssl, buf, (size_t)len)) <= 0) + { + error = SSL_get_error(ssl, bytes_written); + if (error == SSL_ERROR_WANT_WRITE) + continue; + t_print(TLS_CLIENT "Failed! SSL_write returned %d\n", error); + ret = bytes_written; + goto done; + } + + t_print(TLS_CLIENT "%d bytes written\n", bytes_written); + + // Read the HTTP response from server + t_print(TLS_CLIENT "<---- Read from server:\n"); + do + { + len = sizeof(buf) - 1; + memset(buf, 0, sizeof(buf)); + bytes_read = SSL_read(ssl, buf, (size_t)len); + if (bytes_read <= 0) + { + int error = SSL_get_error(ssl, bytes_read); + if (error == SSL_ERROR_WANT_READ) + continue; + + t_print(TLS_CLIENT "Failed! SSL_read returned error=%d\n", error); + ret = bytes_read; + break; + } + + t_print(TLS_CLIENT " %d bytes read\n", bytes_read); + // check to to see if received payload is expected + if ((bytes_read != SERVER_PAYLOAD_SIZE) || + (memcmp(SERVER_PAYLOAD, buf, bytes_read) != 0)) + { + t_print( + TLS_CLIENT "ERROR: expected reading %lu bytes but only " + "received %d bytes\n", + SERVER_PAYLOAD_SIZE, + bytes_read); + ret = bytes_read; + break; + } + else + { + t_print(TLS_CLIENT + " received all the expected data from server\n\n"); + ret = 0; + break; + } + } while (1); +done: + return ret; +} + +// create a socket and connect to the server_name:server_port +int create_socket(char* server_name, char* server_port) +{ + int sockfd = -1; + struct sockaddr_in dest_sock; + int res = -1; + + sockfd = socket(AF_INET, SOCK_STREAM, 0); + if (sockfd == -1) + { + t_print(TLS_CLIENT "Error: Cannot create socket %d.\n", errno); + goto done; + } + + dest_sock.sin_family = AF_INET; + dest_sock.sin_port = htons(atoi(server_port)); + dest_sock.sin_addr.s_addr = inet_addr2(server_name); + bzero(&(dest_sock.sin_zero), sizeof(dest_sock.sin_zero)); + + if (connect( + sockfd, (sockaddr*) &dest_sock, + sizeof(struct sockaddr)) == -1) + { + t_print( + TLS_CLIENT "failed to connect to %s:%s (errno=%d)\n", + server_port, + server_port, + errno); + ocall_close(&res, sockfd); + if (res != 0) + t_print(TLS_CLIENT "OCALL: error closing socket\n"); + sockfd = -1; + goto done; + } + t_print(TLS_CLIENT "connected to %s:%s\n", server_name, server_port); + +done: + return sockfd; +} + +int launch_tls_client(char* server_name, char* server_port) +{ + t_print(TLS_CLIENT " called launch tls client\n"); + + int ret = 0; + + SSL_CTX* ssl_client_ctx = nullptr; + SSL* ssl_session = nullptr; + + X509* cert = nullptr; + EVP_PKEY* pkey = nullptr; + SSL_CONF_CTX* ssl_confctx = SSL_CONF_CTX_new(); + + int client_socket = -1; + int error = 0; + + t_print("\nStarting" TLS_CLIENT "\n\n\n"); + + if ((ssl_client_ctx = SSL_CTX_new(TLS_client_method())) == nullptr) + { + t_print(TLS_CLIENT "unable to create a new SSL context\n"); + goto done; + } + + if (initalize_ssl_context(ssl_confctx, ssl_client_ctx) != SGX_SUCCESS) + { + t_print(TLS_CLIENT "unable to create a initialize SSL context\n "); + goto done; + } + + // specify the verify_callback for custom verification + SSL_CTX_set_verify(ssl_client_ctx, SSL_VERIFY_PEER, &verify_callback); + t_print(TLS_CLIENT "load cert and key\n"); + if (load_tls_certificates_and_keys(ssl_client_ctx, cert, pkey) != 0) + { + t_print(TLS_CLIENT + " unable to load certificate and private key on the client\n"); + goto done; + } + + if ((ssl_session = SSL_new(ssl_client_ctx)) == nullptr) + { + t_print(TLS_CLIENT + "Unable to create a new SSL connection state object\n"); + goto done; + } + + t_print(TLS_CLIENT "new ssl connection getting created\n"); + client_socket = create_socket(server_name, server_port); + if (client_socket == -1) + { + t_print( + TLS_CLIENT + "create a socket and initiate a TCP connect to server: %s:%s " + "(errno=%d)\n", + server_name, + server_port, + errno); + goto done; + } + + // set up ssl socket and initiate TLS connection with TLS server + SSL_set_fd(ssl_session, client_socket); + + if ((error = SSL_connect(ssl_session)) != 1) + { + t_print( + TLS_CLIENT "Error: Could not establish a TLS session ret2=%d " + "SSL_get_error()=%d\n", + error, + SSL_get_error(ssl_session, error)); + goto done; + } + t_print( + TLS_CLIENT "successfully established TLS channel:%s\n", + SSL_get_version(ssl_session)); + + // start the client server communication + if ((error = communicate_with_server(ssl_session)) != 0) + { + t_print(TLS_CLIENT "Failed: communicate_with_server (ret=%d)\n", error); + goto done; + } + + // Free the structures we don't need anymore + ret = 0; +done: + + if (client_socket != -1) + { + ocall_close(&ret, client_socket); + if (ret != 0) + t_print(TLS_CLIENT "OCALL: error close socket\n"); + } + + if (ssl_session) + { + SSL_shutdown(ssl_session); + SSL_free(ssl_session); + } + + if (cert) + X509_free(cert); + + if (pkey) + EVP_PKEY_free(pkey); + + if (ssl_client_ctx) + SSL_CTX_free(ssl_client_ctx); + + if (ssl_confctx) + SSL_CONF_CTX_free(ssl_confctx); + + t_print(TLS_CLIENT " %s\n", (ret == 0) ? "success" : "failed"); + return (ret); +} diff --git a/SampleCode/SampleAttestedTLS/client/enc/private_test_key.pem b/SampleCode/SampleAttestedTLS/client/enc/private_test_key.pem new file mode 100644 index 000000000..59d0c1675 --- /dev/null +++ b/SampleCode/SampleAttestedTLS/client/enc/private_test_key.pem @@ -0,0 +1,39 @@ +-----BEGIN RSA PRIVATE KEY----- +MIIG4gIBAAKCAYEAqhEGbnOzUfNffyL98nRjFOXYb+4d1Q/CluY3GlbDFv9OphD9 +zwY8TnSUz/cIBMdphAadGlnjIi8SS9Yey1IfRcIW1pMnRaAS8J1Kwh9WgBqBZlA/ +bFB4a45ZC16l+oeG5/u3MeQsKDsNIT1kfHJDSb18UHlvEPNcrzIDy+TAcAhd7q/a +av1lDp28TgT7kUdVb5HitBzBQ67s4/L6XzloyAMqSybT56nnTeADcNa/tvom8vqz +0lZ5nXAQ7ZAhGKJKCWk+9aT5oxLNBCrUYQ+UtnJ8429uzBYvG/fyaMcAGjkcfnW2 +irYSpwfFbpN6Ew2252V6O6KYTcFGKBGQaXKezflTOOQ6yRUr5a4GqwTsVc6TH+Nv +pIyL1SgY2zzSkwciqTRyHBh7UpfCC3E3ZNJKT4CUPXu5eINL6v2Wmz8CRbc2hoPo +D+oIvLoqcgClihZs3XlGp3D6ULEgKBP5ortCgpUbitgtA0zGLrQlJhKHVkGgwxax +1U9wLHPNLxzzsGaJAgEDAoIBgHFgrvRNIjaiP6oXU/b4Qg3ukEqevo4Kgbnuz2bk +gg9U3xlgqTSu0t74YzVPWq3aRlgEaLw77MF0tt05adzhai6BZI8MxNkVYfW+Mda/ +jwARq5mK1PLgUEe0O1zpw/xaWe/9JMvtcsV8s2t+Qv2hgjEo/Yr7n2CiPcohV91D +KvVa6UnKkZyo7gm+fYlYp7YvjkphQc1ogNfJ80Kh/D97mzACHDIZ4ppxRN6VV6CP +Knn8GfdRzTbkUROgC0kKwLsW2u/rBFTw0ktBgfVchQmNuI+LBn95/Z6IBbNKOEWI +bLWY/blDkQ6C4uTCfHNWBmYkHJJ427V1XsIFcbuLaxrRL6hKqHSx5F1utlDjgNzk +2C+6Fo0aH1yf0wSc6slHEUef9pMbfvEvjDpm8y1xR+3VLhQgasleW1MHsAwDbzc6 +1Vos3LrMk49gpKPR/RrCPQ+aRpFnAaJl66iBMykqIEpuYOj3a0iHMs2MtSst7Kh/ +TDAlZRseCULoDPyNH1A6rJ08CwKBwQDXmNX87JG7CBQ6JemaBG+xhccjQT2VFSCj +mQw/g8bKZ+MiHYyhyfr6muAExuYw5HsSysX7//p1s+7cVnsBgHsO1MOwSoa8ajxj +iY07GrKHxOtS7UQavzomdudyNjXSVfCH8bEaESV4bm8JuZOFsnGshE7V7F/BoUU3 +3cVu4JDE+vCfT6qaGhLTFwZzsxuGj293Nwu37a6RfncCmHN3Fqdzp0lghdx0On9d +8Z4XOwVAvD/H7+7eQj5pslyDH7QPKl0CgcEAye/ieU8sdyh12fojOLaQLZwsAPc0 +yTUF62+RwPaWP2u8xnLQUyfDVUkqvMuKSPMQ+OVqr3KPtQUssmn0v7hcQrSS2Y7d +gITeCM84JJL1hnKF+U78ft2VJ8XROxwC1UFARJmCmEADgo7mPY23+mAThMulOYHQ +ulZ+oRqqWYYxeXj6zwFgHr7+8+goVioubB+TjCe4e+pqQnDcZ7xVu/8JsXqxPYeE +Wr83D/2kEhiPzU1JUnm1ErEeR+3Bs6U8tWIdAoHBAI+7OVNIYSdauCbD8RFYSnZZ +L2zWKQ4OFcJmCCpX2dxFQha+XcExUfxnQAMvRCCYUgyHLqf//E539JLkUgEAUgnj +LSAxryhG0u0GXidnIa/YnOHzgrx/fBmkmkwkI+GOoFqhILwLblBJn1vRDQPMS8hY +NI6dlSvA2M/pLknrCy38oGo1HGa8DIy6BE0iElm09PoksnqedGD++gG696S5xPfE +25Wukvgm/5P2aWTSA4B9f9qf9JQsKZvMPay/zV9xkwKBwQCGn+xQ33L6Gvk7/Bd7 +JGAeaB1V+iMwzgPySmErTw7U8n3ZoeA3b9eOMMcoh7GF92Cl7kcfobUjWMh28U3V +JZLXIwyRCekAWJQF33rDDKOu9wP7if2p6Q4ag+DSEqyOK4Atu6xlgAJXCe7Ts8/8 +QA0DMm4mVosm5FRrZxw7rsumUKc0q5Vp1Kn38BrkHB7yv7eyxSWn8ZwsSz2afY59 +VLEg/HYpBQLnKiS1U8K2uwqI3jDhpni3IL7anoEibih47BMCgcBniK1vaIEB03SJ +C407iKJX2uDAGUOakYGe4A6cjJz0ShGgfk5X3+qg3/ii/4igLAWi6mbuCHZEiCjN +Wsr83gBzdK8DpoNdI23IHRasH8Vw6/B6ya8sIP6PzJFCEEMUTNpJwO+swWFvEsEO +IY/o4Ue6+DX87v5mDa7IkJiGbCv567UA9665c/MNx70QJwivHtMbaC5ajiBUF1jZ +qe8PhaHRkBjgIUt+vnmxcbhU2e+S91ZBdITyV/l+H3+wHBIhdP0= +-----END RSA PRIVATE KEY----- diff --git a/SampleCode/SampleAttestedTLS/client/host/Makefile b/SampleCode/SampleAttestedTLS/client/host/Makefile new file mode 100644 index 000000000..807d266df --- /dev/null +++ b/SampleCode/SampleAttestedTLS/client/host/Makefile @@ -0,0 +1,56 @@ +# +# 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 ../../sgxenv.mk + +INCDIR=$(SGX_SDK)/include +SOCKETINCDIR = $(SOCKET_DIR)/include +SSLINCDIR = $(SGXSSL_PKG_PATH)/include +TLSINCDIR = $(SGXTLS_DIR)/include + +all: build + +build: + @ echo "Compilers used: $(CC), $(CXX)" + $(SGX_EDGER8R) --untrusted ../tls_client.edl \ + --search-path $(INCDIR) \ + --search-path . \ + --search-path $(SOCKETINCDIR) \ + --search-path $(SSLINCDIR) \ + --search-path $(TLSINCDIR) \ + --search-path ../../common + + $(CC) -c $(App_C_Flags) tls_client_u.c + $(CXX) -c -DM_TLS_CLIENT $(App_Cpp_Flags) host.cpp ../../sgx_socket/untrusted_sgx_socket.cpp ../../common/ucommon.cpp + $(CXX) -o tls_client_host host.o untrusted_sgx_socket.o tls_client_u.o ucommon.o $(App_Link_Flags) + +clean: + rm -f tls_client_host *.o tls_client_u.* tls_client_args.h diff --git a/SampleCode/SampleAttestedTLS/client/host/host.cpp b/SampleCode/SampleAttestedTLS/client/host/host.cpp new file mode 100644 index 000000000..b8efbb76a --- /dev/null +++ b/SampleCode/SampleAttestedTLS/client/host/host.cpp @@ -0,0 +1,238 @@ +/** +* +* MIT License +* +* Copyright (c) Open Enclave SDK contributors. +* +* Permission is hereby granted, free of charge, to any person obtaining a copy +* of this software and associated documentation files (the "Software"), to deal +* in the Software without restriction, including without limitation the rights +* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +* copies of the Software, and to permit persons to whom the Software is +* furnished to do so, subject to the following conditions: +* +* The above copyright notice and this permission notice shall be included in all +* copies or substantial portions of the Software. +* +* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +* SOFTWARE +* +*/ + +#include "sgx_urts.h" +#include +#include +#include "tls_client_u.h" +#include +#include + +#define TLS_SERVER_NAME "localhost" +#define TLS_SERVER_PORT "12340" + +/* Global EID shared by multiple threads */ +sgx_enclave_id_t client_global_eid = 0; + + +typedef struct _sgx_errlist_t { + sgx_status_t err; + const char *msg; + const char *sug; /* Suggestion */ +} sgx_errlist_t; + +/* Error code returned by sgx_create_enclave */ +static sgx_errlist_t sgx_errlist[] = { + { + SGX_ERROR_UNEXPECTED, + "Unexpected error occurred.", + NULL + }, + { + SGX_ERROR_INVALID_PARAMETER, + "Invalid parameter.", + NULL + }, + { + SGX_ERROR_OUT_OF_MEMORY, + "Out of memory.", + NULL + }, + { + SGX_ERROR_ENCLAVE_LOST, + "Power transition occurred.", + "Please refer to the sample \"PowerTransition\" for details." + }, + { + SGX_ERROR_INVALID_ENCLAVE, + "Invalid enclave image.", + NULL + }, + { + SGX_ERROR_INVALID_ENCLAVE_ID, + "Invalid enclave identification.", + NULL + }, + { + SGX_ERROR_INVALID_SIGNATURE, + "Invalid enclave signature.", + NULL + }, + { + SGX_ERROR_OUT_OF_EPC, + "Out of EPC memory.", + NULL + }, + { + SGX_ERROR_NO_DEVICE, + "Invalid SGX device.", + "Please make sure SGX module is enabled in the BIOS, and install SGX driver afterwards." + }, + { + SGX_ERROR_MEMORY_MAP_CONFLICT, + "Memory map conflicted.", + NULL + }, + { + SGX_ERROR_INVALID_METADATA, + "Invalid enclave metadata.", + NULL + }, + { + SGX_ERROR_DEVICE_BUSY, + "SGX device was busy.", + NULL + }, + { + SGX_ERROR_INVALID_VERSION, + "Enclave version was invalid.", + NULL + }, + { + SGX_ERROR_INVALID_ATTRIBUTE, + "Enclave was not authorized.", + NULL + }, + { + SGX_ERROR_ENCLAVE_FILE_ACCESS, + "Can't open enclave file.", + NULL + }, +}; + +/* Check error conditions for loading enclave */ +void print_error_message(sgx_status_t ret) +{ + size_t idx = 0; + size_t ttl = sizeof sgx_errlist/sizeof sgx_errlist[0]; + + for (idx = 0; idx < ttl; idx++) { + if(ret == sgx_errlist[idx].err) { + if(NULL != sgx_errlist[idx].sug) + printf("Info: %s\n", sgx_errlist[idx].sug); + printf("Error: %s\n", sgx_errlist[idx].msg); + break; + } + } + + if (idx == ttl) + printf("Error code is 0x%X. Please refer to the \"Intel SGX SDK Developer Reference\" for more details.\n", ret); +} + +sgx_status_t initialize_enclave(const char *enclave_path) +{ + sgx_status_t ret = SGX_ERROR_UNEXPECTED; + + // the 1st parameter should be CLIENT_ENCLAVE_FILENAME + ret = sgx_create_enclave(enclave_path, SGX_DEBUG_FLAG, NULL, NULL, &client_global_eid, NULL); + printf("Client Enc: Enclave library %s\n", enclave_path); + + if (ret != SGX_SUCCESS) + { + print_error_message(ret); + return ret; + } + return ret; +} + +void terminate_enclave() +{ + sgx_destroy_enclave(client_global_eid); + printf("Host: Enclave successfully terminated.\n"); +} + +int main(int argc, const char* argv[]) +{ + sgx_status_t result = SGX_SUCCESS; + int ret = 1; + char* server_name = NULL; + char* server_port = NULL; + + /* Check argument count */ + if (argc != 4) + { + print_usage: + printf( + "Usage: %s TLS_SERVER_ENCLAVE_PATH -server: -port:\n", + argv[0]); + return 1; + } + // read server name parameter + { + const char* option = "-server:"; + int param_len = 0; + param_len = strlen(option); + if (strncmp(argv[2], option, param_len) == 0) + { + server_name = (char*)(argv[2] + param_len); + } + else + { + fprintf(stderr, "Unknown option %s\n", argv[2]); + goto print_usage; + } + } + printf("server name = [%s]\n", server_name); + + // read port parameter + { + const char* option = "-port:"; + int param_len = 0; + param_len = strlen(option); + if (strncmp(argv[3], option, param_len) == 0) + { + server_port = (char*)(argv[3] + param_len); + } + else + { + fprintf(stderr, "Unknown option %s\n", argv[2]); + goto print_usage; + } + } + printf("server port = [%s]\n", server_port); + + printf("Host: Creating client enclave\n"); + result = initialize_enclave(argv[1]); + if (result != SGX_SUCCESS) + { + goto exit; + } + + printf("Host: launch TLS client to initiate TLS connection\n"); + result = launch_tls_client(client_global_eid, &ret, server_name, server_port); + if (result != SGX_SUCCESS || ret != 0) + { + printf("Host: launch_tls_client failed\n"); + goto exit; + } + ret = 0; +exit: + + terminate_enclave(); + + printf("Host: %s \n", (ret == 0) ? "succeeded" : "failed"); + return ret; +} diff --git a/SampleCode/SampleAttestedTLS/client/tls_client.edl b/SampleCode/SampleAttestedTLS/client/tls_client.edl new file mode 100644 index 000000000..74d71c63e --- /dev/null +++ b/SampleCode/SampleAttestedTLS/client/tls_client.edl @@ -0,0 +1,47 @@ +/* + * 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. + * + */ + + +enclave { + from "sgx_tstdc.edl" import *; + from "enclave.edl" import *; + from "sgx_socket.edl" import *; + from "sgx_tsgxssl.edl" import *; + from "sgx_ttls.edl" import *; + from "sgx_pthread.edl" import *; + + include "sgx_ttls.h" + trusted { + public int launch_tls_client( + [in, string] char* server_name, + [in, string] char* server_port); + }; +}; diff --git a/SampleCode/SampleAttestedTLS/common/common.h b/SampleCode/SampleAttestedTLS/common/common.h new file mode 100644 index 000000000..b630eb554 --- /dev/null +++ b/SampleCode/SampleAttestedTLS/common/common.h @@ -0,0 +1,57 @@ +/** +* +* MIT License +* +* Copyright (c) Open Enclave SDK contributors. +* +* Permission is hereby granted, free of charge, to any person obtaining a copy +* of this software and associated documentation files (the "Software"), to deal +* in the Software without restriction, including without limitation the rights +* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +* copies of the Software, and to permit persons to whom the Software is +* furnished to do so, subject to the following conditions: +* +* The above copyright notice and this permission notice shall be included in all +* copies or substantial portions of the Software. +* +* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +* SOFTWARE +* +*/ + +#define TLS_CLIENT "TLS client: " +#define TLS_SERVER "TLS server: " + +#define CLIENT_PAYLOAD "GET / HTTP/1.0\r\n\r\n" +#define SERVER_PAYLOAD \ + "HTTP/1.0 200 OK\r\nContent-Type: text/html\r\n\r\n" \ + "

mbed TLS Test Server

\r\n" \ + "

Successful connection :

\r\n" \ + "A message from TLS server inside enclave\r\n" + +#define CLIENT_PAYLOAD_SIZE strlen(CLIENT_PAYLOAD) +#define SERVER_PAYLOAD_SIZE strlen(SERVER_PAYLOAD) + + + +// put common files here in a definition of Macro to reduce +// redundancy code +#ifdef CLIENT_UNTRUSTED +#include "sgx_utls.h" +#define PRINT printf +#define GETCURRTIME time +#define VERIFY_CALLBACK tee_verify_certificate_with_evidence_host +#define FREE_SUPDATA tee_free_supplemental_data_host +#else +#include "sgx_ttls.h" +extern void t_print(const char* fmt, ...); +#define PRINT t_print +#define GETCURRTIME t_time +#define VERIFY_CALLBACK tee_verify_certificate_with_evidence +#define FREE_SUPDATA tee_free_supplemental_data +#endif diff --git a/SampleCode/SampleAttestedTLS/common/enclave.edl b/SampleCode/SampleAttestedTLS/common/enclave.edl new file mode 100644 index 000000000..6e2854070 --- /dev/null +++ b/SampleCode/SampleAttestedTLS/common/enclave.edl @@ -0,0 +1,44 @@ +/* + * 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. + * + */ + +// ocall for untrusted functions +enclave { + /* + * ocall_print_string - invokes OCALL to display string buffer inside the enclave. + * [in]: copy the string buffer to App outside. + * [string]: specifies 'str' is a NULL terminated buffer. + */ + untrusted { + void ocall_print_string([in, string] const char *str); + int ocall_close(int fd); + void ocall_get_current_time([out] uint64_t *p_current_time); + }; +}; diff --git a/SampleCode/SampleAttestedTLS/common/err_msg.cpp b/SampleCode/SampleAttestedTLS/common/err_msg.cpp new file mode 100644 index 000000000..6465ecebc --- /dev/null +++ b/SampleCode/SampleAttestedTLS/common/err_msg.cpp @@ -0,0 +1,131 @@ +/* + * 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 "common.h" +#include "sgx_ql_lib_common.h" +#include "sgx_qve_header.h" +#include +#include + +/* translate error code here + * qv result code and quote3 error code + */ + + +std::map ql_error_map = +{ + { SGX_QL_SUCCESS, "quoting service success" }, + { SGX_QL_ERROR_UNEXPECTED, "unexpected error in quoting service"}, + { SGX_QL_OUT_OF_EPC, "not enough EPC to load the quoting enclave"}, + { SGX_QL_ERROR_INVALID_PARAMETER, "invalid parameter"} +}; + +typedef enum _log_level { + L_OK = 0, + L_WARNING, // log level warning, not fatal + L_FATAL // log level fatal +} qv_log_level; + +typedef std::pair qv_result_info; + +std::string strOK = "SUCCESS:Verification Completed"; +std::string strCfgNeeded = + "quote verification passed, TCB is the latest, still need additional config"; +std::string strOutofDate = + "quote verification passed, TCB level not latest, pls upgrade platform patch"; +std::string strOutofDateCfgNeeded = + "quote verification passed, TCB level out of date, additional config needed at patch level"; +std::string strSWHdNeeded = + "software hardening required"; +std::string strInvalidSig = + "invalid signature over app report"; +std::string strRevoked = + "platform/attestation key is revoked"; +std::string strUnspecified = + "invalid input"; + + +std::map qve_error_map = +{ + { SGX_QL_QV_RESULT_OK, std::make_pair(L_OK, strOK)}, + { SGX_QL_QV_RESULT_CONFIG_NEEDED, + std::make_pair(L_WARNING, strCfgNeeded) }, + { SGX_QL_QV_RESULT_OUT_OF_DATE, + std::make_pair(L_WARNING, strOutofDate) }, + { SGX_QL_QV_RESULT_OUT_OF_DATE_CONFIG_NEEDED, + std::make_pair(L_WARNING, strOutofDateCfgNeeded) }, + { SGX_QL_QV_RESULT_SW_HARDENING_NEEDED, + std::make_pair(L_WARNING, strSWHdNeeded) }, + { SGX_QL_QV_RESULT_INVALID_SIGNATURE, + std::make_pair(L_FATAL, strInvalidSig) }, + { SGX_QL_QV_RESULT_REVOKED, std::make_pair(L_FATAL, strRevoked) }, + { SGX_QL_QV_RESULT_UNSPECIFIED, std::make_pair(L_FATAL, strUnspecified) } +}; + + +void p_sgx_tls_qv_err_msg(sgx_ql_qv_result_t error_code) +{ + if (qve_error_map.find(error_code) != qve_error_map.end()) + { + switch (qve_error_map[error_code].first) + { + case L_WARNING: + PRINT("WARNING: 0x%x - %s\n", error_code, + qve_error_map[error_code].second.c_str()); + break; + case L_FATAL: + PRINT("FATAL: 0x%x - %s\n", error_code, + qve_error_map[error_code].second.c_str()); + break; + default: // default is ok + // but you need to check the collateral_expiration_status + // refer to dcap sample qvl(quote_verification_result) + PRINT("unknown error level\n"); + break; + } + } + else + { + PRINT("UNKNOWN error type(0x%x) and info, please check! \n", error_code); + } +} + +void p_sgx_tls_qe_err_msg(quote3_error_t error_code) +{ + if (ql_error_map.find(error_code) != ql_error_map.end()) + { + PRINT("%s", ql_error_map[error_code].c_str()); + } + else + { + PRINT("please check the error 0x%x\n", error_code); + } +} diff --git a/SampleCode/SampleAttestedTLS/common/openssl_utility.cpp b/SampleCode/SampleAttestedTLS/common/openssl_utility.cpp new file mode 100644 index 000000000..e2db8bc2a --- /dev/null +++ b/SampleCode/SampleAttestedTLS/common/openssl_utility.cpp @@ -0,0 +1,314 @@ +/** +* +* MIT License +* +* Copyright (c) Open Enclave SDK contributors. +* +* Permission is hereby granted, free of charge, to any person obtaining a copy +* of this software and associated documentation files (the "Software"), to deal +* in the Software without restriction, including without limitation the rights +* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +* copies of the Software, and to permit persons to whom the Software is +* furnished to do so, subject to the following conditions: +* +* The above copyright notice and this permission notice shall be included in all +* copies or substantial portions of the Software. +* +* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +* SOFTWARE +* +*/ + +#include "openssl_utility.h" + +sgx_status_t generate_certificate_and_pkey(X509*& certificate, EVP_PKEY*& pkey) +{ + quote3_error_t qresult = SGX_QL_SUCCESS; + sgx_status_t result = SGX_ERROR_UNEXPECTED; + uint8_t* output_certificate = NULL; + size_t output_certificate_size = 0; + uint8_t* private_key_buffer = nullptr; + size_t private_key_buffer_size = 0; + uint8_t* public_key_buffer = nullptr; + size_t public_key_buffer_size = 0; + const unsigned char* certificate_buffer_ptr = nullptr; + BIO* mem = nullptr; + int key_type = RSA_TYPE; + + if (key_type) { + t_print(" generating keys by EC P-384\n"); + } + else + { + t_print(" generating keys by RSA 3072\n"); + } + result = generate_key_pair( + key_type, &public_key_buffer, + &public_key_buffer_size, + &private_key_buffer, + &private_key_buffer_size); + if (result != SGX_SUCCESS) + { + t_print(" failed to generate RSA key pair\n"); + goto done; + } + + t_print("public_key_buf_size:[%ld]\n", public_key_buffer_size); + t_print("%s\n", public_key_buffer); + t_print("private_key_buf_size:[%ld]\n", private_key_buffer_size); + t_print("%s\n", private_key_buffer); + qresult = tee_get_certificate_with_evidence( + certificate_subject_name, + private_key_buffer, + private_key_buffer_size, + public_key_buffer, + public_key_buffer_size, + &output_certificate, + &output_certificate_size); + + if (qresult != SGX_QL_SUCCESS || output_certificate == nullptr) + { + if (output_certificate == nullptr) + t_print(" null certificate\n"); + p_sgx_tls_qe_err_msg(qresult); + goto done; + } + + // temporary buffer required as if d2i_x509 call is successful + // certificate_buffer_ptr is incremented to the byte following the parsed + // data. sending certificate_buffer_ptr as argument will keep + // output_certificate pointer undisturbed. + + certificate_buffer_ptr = output_certificate; + + if ((certificate = d2i_X509( + nullptr, + &certificate_buffer_ptr, + (long)output_certificate_size)) == nullptr) + { + t_print("Failed to convert DER format certificate to X509 structure\n"); + goto done; + } + mem = BIO_new_mem_buf((void*)private_key_buffer, -1); + if (!mem) + { + t_print("Failed to convert private key buf into BIO_mem\n"); + goto done; + } + if ((pkey = PEM_read_bio_PrivateKey(mem, nullptr, 0, nullptr)) == nullptr) + { + t_print("Failed to convert private key buffer into EVP_KEY format\n"); + goto done; + } + + result = SGX_SUCCESS; +done: + if (private_key_buffer) + free(private_key_buffer); + if (public_key_buffer) + free(public_key_buffer); + certificate_buffer_ptr = nullptr; + + if (mem) + BIO_free(mem); + if (output_certificate) + tee_free_certificate(output_certificate); + return result; +} + +sgx_status_t load_tls_certificates_and_keys( + SSL_CTX* ctx, + X509*& certificate, + EVP_PKEY*& pkey) +{ + sgx_status_t result = SGX_ERROR_UNEXPECTED; + + if (generate_certificate_and_pkey(certificate, pkey) != SGX_SUCCESS) + { + t_print("Cannot generate certificate and pkey\n"); + goto exit; + } + + if (certificate == nullptr) + { + t_print("null cert\n"); + goto exit; + } + + if (!SSL_CTX_use_certificate(ctx, certificate)) + { + t_print("Cannot load certificate on the server\n"); + goto exit; + } + + if (!SSL_CTX_use_PrivateKey(ctx, pkey)) + { + t_print("Cannot load private key on the server\n"); + goto exit; + } + + /* verify private key */ + if (!SSL_CTX_check_private_key(ctx)) + { + t_print("Private key does not match the public certificate\n"); + goto exit; + } + result = SGX_SUCCESS; +exit: + return result; +} + +sgx_status_t initalize_ssl_context(SSL_CONF_CTX*& ssl_conf_ctx, SSL_CTX*& ctx) +{ + sgx_status_t ret = SGX_ERROR_UNEXPECTED; + // Configure the SSL context based on Open Enclave's security guidance. + const char* cipher_list_tlsv12_below = + "ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-" + "AES128-GCM-SHA256:" + "ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES128-SHA256:ECDHE-ECDSA-" + "AES256-SHA384:" + "ECDHE-RSA-AES128-SHA256:ECDHE-RSA-AES256-SHA384"; + const char* cipher_list_tlsv13 = + "TLS13-AES-256-GCM-SHA384:TLS13-AES-128-GCM-SHA256"; + const char* supported_curves = "P-521:P-384:P-256"; + + SSL_CONF_CTX_set_ssl_ctx(ssl_conf_ctx, ctx); + SSL_CONF_CTX_set_flags( + ssl_conf_ctx, + SSL_CONF_FLAG_FILE | SSL_CONF_FLAG_SERVER | SSL_CONF_FLAG_CLIENT); + int ssl_conf_return_value = -1; + if ((ssl_conf_return_value = + SSL_CONF_cmd(ssl_conf_ctx, "MinProtocol", "TLSv1.2")) < 0) + { + t_print( + "Setting MinProtocol for ssl context configuration failed with " + "error %d \n", + ssl_conf_return_value); + goto exit; + } + if ((ssl_conf_return_value = + SSL_CONF_cmd(ssl_conf_ctx, "MaxProtocol", "TLSv1.3")) < 0) + { + t_print( + "Setting MaxProtocol for ssl context configuration failed with " + "error %d \n", + ssl_conf_return_value); + goto exit; + } + if ((ssl_conf_return_value = SSL_CONF_cmd( + ssl_conf_ctx, "CipherString", cipher_list_tlsv12_below)) < 0) + { + t_print( + "Setting CipherString for ssl context configuration failed with " + "error %d \n", + ssl_conf_return_value); + goto exit; + } + if ((ssl_conf_return_value = SSL_CONF_cmd( + ssl_conf_ctx, "Ciphersuites", cipher_list_tlsv13)) < 0) + { + t_print( + "Setting Ciphersuites for ssl context configuration failed with " + "error %d \n", + ssl_conf_return_value); + goto exit; + } + if ((ssl_conf_return_value = + SSL_CONF_cmd(ssl_conf_ctx, "Curves", supported_curves)) < 0) + { + t_print( + "Setting Curves for ssl context configuration failed with error %d " + "\n", + ssl_conf_return_value); + goto exit; + } + if (!SSL_CONF_CTX_finish(ssl_conf_ctx)) + { + t_print("Error finishing ssl context configuration \n"); + goto exit; + } + ret = SGX_SUCCESS; +exit: + return ret; +} + +int read_from_session_peer( + SSL*& ssl_session, + const char* payload, + size_t payload_length) +{ + int ret = -1; + unsigned char buffer[200]; // the expected payload to be read from peer is + // at maximum of size 200 + int bytes_read = 0; + do + { + unsigned int len = sizeof(buffer) - 1; + memset(buffer, 0, sizeof(buffer)); + bytes_read = SSL_read(ssl_session, buffer, (size_t)len); + + if (bytes_read <= 0) + { + int error = SSL_get_error(ssl_session, bytes_read); + if (error == SSL_ERROR_WANT_READ) + continue; + + t_print("Failed! SSL_read returned error=%d\n", error); + ret = bytes_read; + break; + } + + t_print(" %d bytes read from session peer\n", bytes_read); + + // check to see if received payload is expected + if ((bytes_read != payload_length) || + (memcmp(payload, buffer, bytes_read) != 0)) + { + t_print( + "ERROR: expected reading %lu bytes but only " + "received %d bytes\n", + payload_length, + bytes_read); + ret = bytes_read; + goto exit; + } + else + { + t_print(" received all the expected data from the session peer\n\n"); + ret = 0; + break; + } + } while (1); + +exit: + return ret; +} + +int write_to_session_peer( + SSL*& ssl_session, + const char* payload, + size_t payload_length) +{ + int bytes_written = 0; + int ret = 0; + + while ((bytes_written = SSL_write(ssl_session, payload, payload_length)) <= + 0) + { + int error = SSL_get_error(ssl_session, bytes_written); + if (error == SSL_ERROR_WANT_WRITE) + continue; + t_print("Failed! SSL_write returned %d\n", error); + ret = bytes_written; + goto exit; + } + + t_print("%lu bytes written to session peer\n\n", payload_length); +exit: + return ret; +} diff --git a/SampleCode/SampleAttestedTLS/common/openssl_utility.h b/SampleCode/SampleAttestedTLS/common/openssl_utility.h new file mode 100644 index 000000000..4cb8ebc58 --- /dev/null +++ b/SampleCode/SampleAttestedTLS/common/openssl_utility.h @@ -0,0 +1,46 @@ +/** +* +* MIT License +* +* Copyright (c) Open Enclave SDK contributors. +* +* Permission is hereby granted, free of charge, to any person obtaining a copy +* of this software and associated documentation files (the "Software"), to deal +* in the Software without restriction, including without limitation the rights +* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +* copies of the Software, and to permit persons to whom the Software is +* furnished to do so, subject to the following conditions: +* +* The above copyright notice and this permission notice shall be included in all +* copies or substantial portions of the Software. +* +* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +* SOFTWARE +* +*/ + +#include "sgx_ttls.h" +#include +#include +#include "utility.h" + +int read_from_session_peer( + SSL*& ssl_session, + const char* payload, + size_t payload_length); +int write_to_session_peer( + SSL*& ssl_session, + const char* payload, + size_t payload_length); + +sgx_status_t load_tls_certificates_and_keys( + SSL_CTX* ctx, + X509*& certificate, + EVP_PKEY*& pkey); + +sgx_status_t initalize_ssl_context(SSL_CONF_CTX*& ssl_conf_ctx, SSL_CTX*& ctx); diff --git a/SampleCode/SampleAttestedTLS/common/tcommon.cpp b/SampleCode/SampleAttestedTLS/common/tcommon.cpp new file mode 100644 index 000000000..5e13210c5 --- /dev/null +++ b/SampleCode/SampleAttestedTLS/common/tcommon.cpp @@ -0,0 +1,57 @@ +/* + * 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 +#include +#include "utility.h" +#ifdef M_TLS_SERVER +#include "tls_server_t.h" +#else +#include "tls_client_t.h" +#endif +/* + * printf: + * Invokes OCALL to display the enclave buffer to the terminal. + */ +void t_print(const char *fmt, ...) +{ + char buf[BUFSIZ] = {'\0'}; + va_list ap; + va_start(ap, fmt); + vsnprintf(buf, BUFSIZ, fmt, ap); + va_end(ap); + ocall_print_string(buf); +} + +void t_time(time_t *current_t) +{ + ocall_get_current_time((uint64_t*)current_t); +} diff --git a/SampleCode/SampleAttestedTLS/common/ucommon.cpp b/SampleCode/SampleAttestedTLS/common/ucommon.cpp new file mode 100644 index 000000000..52a4591a2 --- /dev/null +++ b/SampleCode/SampleAttestedTLS/common/ucommon.cpp @@ -0,0 +1,60 @@ +/* + * 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 +#include +#include +#ifdef M_TLS_SERVER +#include "../server/host/tls_server_u.h" +#else +#include "../client/host/tls_client_u.h" +#endif + +int ocall_close(int fd) +{ + return close(fd); +} + +void ocall_get_current_time(uint64_t *p_current_time) +{ + time_t rawtime; + time (&rawtime); + + if (!p_current_time) + return; + *p_current_time = (uint64_t) rawtime; +} + + +void ocall_print_string(const char *str) +{ + printf("%s", str); +} diff --git a/SampleCode/SampleAttestedTLS/common/utility.cpp b/SampleCode/SampleAttestedTLS/common/utility.cpp new file mode 100644 index 000000000..c3850b06e --- /dev/null +++ b/SampleCode/SampleAttestedTLS/common/utility.cpp @@ -0,0 +1,262 @@ +/** +* +* MIT License +* +* Copyright (c) Open Enclave SDK contributors. +* +* Permission is hereby granted, free of charge, to any person obtaining a copy +* of this software and associated documentation files (the "Software"), to deal +* in the Software without restriction, including without limitation the rights +* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +* copies of the Software, and to permit persons to whom the Software is +* furnished to do so, subject to the following conditions: +* +* The above copyright notice and this permission notice shall be included in all +* copies or substantial portions of the Software. +* +* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +* SOFTWARE +* +*/ + +#include "utility.h" + +// +// Generate_Key_Pair function: +// type1: RSA +// type2: EC-P384 +// currently all hardware independant +// +#include +#include +#include +#include +#include +#include +#include +#include +#include "sgx_trts.h" + + +int get_pkey_by_rsa(EVP_PKEY *pk) +{ + int res = -1; + RSA* rsa = nullptr; + BIGNUM* e = nullptr; + + + e = BN_new(); + if (!e) { + t_print("BN_new failed\n"); + return res; + } + + res = BN_set_word(e, (BN_ULONG)RSA_F4); + if (!res) { + t_print("BN_set_word failed (%d)\n", res); + return res; + } + + rsa = RSA_new(); + if (!rsa) { + t_print("RSA_new failed\n"); + res = -1; + return res; + } + + res = RSA_generate_key_ex( + rsa, + RSA_3072_PRIVATE_KEY_SIZE, /* number of bits for the key value */ + e, /* exponent - RSA_F4 is defined as 0x10001L */ + nullptr /* callback argument - not needed in this case */ + ); + + if (!res) + { + t_print("RSA_generate_key failed (%d)\n", res); + return res; + } + + // Assign RSA key to EVP_PKEY structure + EVP_PKEY_assign_RSA(pk, rsa); + + return res; +} + +int get_pkey_by_ec(EVP_PKEY *pk) +{ + int res = -1; + EVP_PKEY_CTX *ctx; + + ctx = EVP_PKEY_CTX_new_id(EVP_PKEY_EC, NULL); + if (ctx == NULL) + return res; + res = EVP_PKEY_keygen_init(ctx); + if (res <= 0) + { + t_print("EC_generate_key failed (%d)\n", res); + return res; + } + + res = EVP_PKEY_CTX_set_ec_paramgen_curve_nid(ctx, NID_secp384r1); + if (res <= 0) + { + t_print("EC_generate_key failed (%d)\n", res); + return res; + } + + /* Generate key */ + res = EVP_PKEY_keygen(ctx, &pk); + if (res <= 0) + { + t_print("EC_generate_key failed (%d)\n", res); + return res; + } + + return res; +} + + +// actually is generating RSA pair +// hardare independant +sgx_status_t generate_key_pair( + int type, + uint8_t** public_key, + size_t* public_key_size, + uint8_t** private_key, + size_t* private_key_size) +{ + sgx_status_t result = SGX_ERROR_UNEXPECTED; + uint8_t* local_public_key = nullptr; + uint8_t* local_private_key = nullptr; + int res = -1; + EVP_PKEY* pkey = nullptr; + BIO* bio = nullptr; + + pkey = EVP_PKEY_new(); + if (!pkey) + { + t_print("EVP_PKEY_new failed\n"); + result = SGX_ERROR_UNEXPECTED; + goto done; + } + + if (type != RSA_TYPE && type != EC_TYPE) + { + type = RSA_TYPE; // by default, we use RSA_TYPE + } + + switch(type) + { + case RSA_TYPE: + res = get_pkey_by_rsa(pkey); + break; + case EC_TYPE: + res = get_pkey_by_ec(pkey); + break; + } + + if (res <= 0) + { + t_print("get_pkey failed (%d)\n", res); + result = SGX_ERROR_UNEXPECTED; + goto done; + } + + // Allocate memory + local_public_key = (uint8_t*)malloc(RSA_3072_PUBLIC_KEY_SIZE); + if (!local_public_key) + { + t_print("out-of-memory:calloc(local_public_key failed\n"); + result = SGX_ERROR_OUT_OF_EPC; + goto done; + } + memset(local_public_key, 0x00, RSA_3072_PUBLIC_KEY_SIZE); + + local_private_key = (uint8_t*)malloc(RSA_3072_PRIVATE_KEY_SIZE); + if (!local_private_key) + { + t_print("out-of-memory: calloc(local_private_key) failed\n"); + result = SGX_ERROR_OUT_OF_EPC; + goto done; + } + memset(local_private_key, 0x00, RSA_3072_PRIVATE_KEY_SIZE); + + // Write out the public/private key in PEM format for exchange with + // other enclaves. + bio = BIO_new(BIO_s_mem()); + if (!bio) + { + t_print("BIO_new for local_public_key failed\n"); + goto done; + } + + res = PEM_write_bio_PUBKEY(bio, pkey); + if (!res) + { + t_print("PEM_write_bio_PUBKEY failed (%d)\n", res); + goto done; + } + + res = BIO_read(bio, local_public_key, RSA_3072_PUBLIC_KEY_SIZE); + if (!res) + { + t_print("BIO_read public key failed (%d)\n", res); + goto done; + } + BIO_free(bio); + bio = nullptr; + + bio = BIO_new(BIO_s_mem()); + if (!bio) + { + t_print("BIO_new for local_public_key failed\n"); + goto done; + } + + res = PEM_write_bio_PrivateKey( + bio, pkey, nullptr, nullptr, 0, nullptr, nullptr); + if (!res) + { + t_print("PEM_write_bio_PrivateKey failed (%d)\n", res); + goto done; + } + + res = BIO_read(bio, local_private_key, RSA_3072_PRIVATE_KEY_SIZE); + if (!res) + { + t_print("BIO_read private key failed (%d)\n", res); + goto done; + } + + BIO_free(bio); + bio = nullptr; + + *public_key = local_public_key; + *private_key = local_private_key; + + *public_key_size = strlen(reinterpret_cast(local_public_key)) + 1; + *private_key_size = strlen(reinterpret_cast(local_private_key)) + 1; + + t_print("public_key_size %d, private_key_size %d\n", *public_key_size, *private_key_size); + result = SGX_SUCCESS; + +done: + if (bio) + BIO_free(bio); + if (pkey) + EVP_PKEY_free(pkey); // When this is called, rsa is also freed + if (result != SGX_SUCCESS) + { + if (local_public_key) + free(local_public_key); + if (local_private_key) + free(local_private_key); + } + return result; +} diff --git a/SampleCode/SampleAttestedTLS/common/utility.h b/SampleCode/SampleAttestedTLS/common/utility.h new file mode 100644 index 000000000..d2feb2449 --- /dev/null +++ b/SampleCode/SampleAttestedTLS/common/utility.h @@ -0,0 +1,64 @@ +/** +* +* MIT License +* +* Copyright (c) Open Enclave SDK contributors. +* +* Permission is hereby granted, free of charge, to any person obtaining a copy +* of this software and associated documentation files (the "Software"), to deal +* in the Software without restriction, including without limitation the rights +* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +* copies of the Software, and to permit persons to whom the Software is +* furnished to do so, subject to the following conditions: +* +* The above copyright notice and this permission notice shall be included in all +* copies or substantial portions of the Software. +* +* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +* SOFTWARE +* +*/ + +/* definitions of common functions in trusted environment + * for both server and client + */ + +#include +#include + +#include "common.h" + +#include "sgx_trts.h" + +#define RSA_PUBLIC_KEY_SIZE 512 +#define RSA_PRIVATE_KEY_SIZE 2048 + +#define RSA_3072_PUBLIC_KEY_SIZE 650 +#define RSA_3072_PRIVATE_KEY_SIZE 3072 + +#define RSA_TYPE 0 +#define EC_TYPE 1 // EC-P384 + +const unsigned char certificate_subject_name[] = + "CN=Intel SGX Enclave, O=Intel Corporation,C=US"; + +void t_time(time_t *c_time); + +void t_print(const char* fmt, ...); + +sgx_status_t generate_key_pair( + int type, + uint8_t** public_key, + size_t* public_key_size, + uint8_t** private_key, + size_t* private_key_size); + +void p_sgx_tls_qv_err_msg(sgx_ql_qv_result_t error_code); + +void p_sgx_tls_qe_err_msg(quote3_error_t error_code); + diff --git a/SampleCode/SampleAttestedTLS/common/verify_callback.cpp b/SampleCode/SampleAttestedTLS/common/verify_callback.cpp new file mode 100644 index 000000000..90e636ae1 --- /dev/null +++ b/SampleCode/SampleAttestedTLS/common/verify_callback.cpp @@ -0,0 +1,155 @@ +/** +* +* MIT License +* +* Copyright (c) Open Enclave SDK contributors. +* +* Permission is hereby granted, free of charge, to any person obtaining a copy +* of this software and associated documentation files (the "Software"), to deal +* in the Software without restriction, including without limitation the rights +* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +* copies of the Software, and to permit persons to whom the Software is +* furnished to do so, subject to the following conditions: +* +* The above copyright notice and this permission notice shall be included in all +* copies or substantial portions of the Software. +* +* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +* SOFTWARE +* +*/ + +#include +#include +#include + +#include +#include +#include +#include +#include "utility.h" +#include "common.h" + + +// The return value of verify_callback controls the strategy of the further +// verification process. If verify_callback returns 0, the verification process +// is immediately stopped with "verification failed" state and A verification +// failure alert is sent to the peer and the TLS/SSL handshake is terminated. If +// verify_callback returns 1, the verification process is continued. +int verify_callback(int preverify_ok, X509_STORE_CTX* ctx) +{ + int ret = 0; + int der_len = 0; + unsigned char* der = nullptr; + int sup_data_len = 0; + time_t current_time; + unsigned char* sup_data = nullptr; + unsigned char* buff = nullptr; + sgx_ql_qv_result_t qv_result; + quote3_error_t result = SGX_QL_SUCCESS; + X509* crt = nullptr; + int err = X509_V_ERR_UNSPECIFIED; + + PRINT( + TLS_CLIENT "verify_callback called with preverify_ok=%d\n", + preverify_ok); + crt = X509_STORE_CTX_get_current_cert(ctx); + if (crt == nullptr) + { + PRINT(TLS_CLIENT "failed to retrieve certificate\n"); + goto done; + } + + if (preverify_ok == 0) + { + err = X509_STORE_CTX_get_error(ctx); + if (err == X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT) + { + // A self-signed certificate is expected, return 1 to continue the + // verification process + PRINT(TLS_CLIENT "self-signed certificated detected\n"); + ret = 1; + goto done; + } + } + + // convert a cert into a buffer in DER format + der_len = i2d_X509(crt, nullptr); + if (der_len <= 0) { + PRINT(TLS_CLIENT "i2d_X509 failed(der_len=%d)\n", der_len); + goto done; + } + + buff = (unsigned char*)malloc(der_len); + if (buff == nullptr) + { + PRINT(TLS_CLIENT "malloc failed (der_len=%d)\n", der_len); + goto done; + } + der = buff; + der_len = i2d_X509(crt, &buff); + if (der_len < 0) + { + PRINT(TLS_CLIENT "i2d_X509 failed(der_len=%d)\n", der_len); + goto done; + } + + // note: i2d_X509() updates the pointer to the buffer so that following the + // call to i2d_X509(), buff is pointing to the "end" of the data buffer + // pointed by buff That is, buff = buff + der_len; + PRINT( + TLS_CLIENT "der=%p buff=%p buff moved by %d offset der_len=%d\n", + der, + buff, + (int)(buff - der), + der_len); + + PRINT(" verifying certificate start \n"); + //inside enclave, the current_time is acquired by ocall, this is just an example + // current_time by ocall is untrusted, user please be aware of it. + GETCURRTIME(¤t_time); + + // verify tls certificate + result = VERIFY_CALLBACK( + der, der_len, current_time, &qv_result, &sup_data, (uint32_t *)&sup_data_len); + + // result != SGX_QL_SUCCESS means critical error + if (result != SGX_QL_SUCCESS) + { + PRINT(TLS_CLIENT "Quote Verification Failed with result(%x) - \n", result); + p_sgx_tls_qe_err_msg(result); + goto done; + } + else + { + // We only print the warning info in this sample + // In your product, we suggest you to check qv_result and supplemental data, define your own verification policy + if (qv_result != SGX_QL_QV_RESULT_OK) + { + PRINT(TLS_CLIENT "Warning: Quote verification has non-critical error. You can define your own verification policy based on below info:\n"); + p_sgx_tls_qv_err_msg(qv_result); + } + } + + FREE_SUPDATA(sup_data); + + PRINT(" verifying certificate end\n"); + ret = 1; +done: + + if (der) + free(der); + + if (err != X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT) + { + PRINT( + TLS_CLIENT "verifying SGX certificate extensions ... %s\n", + ret ? "succeeded" : "failed"); + } + return ret; +} diff --git a/SampleCode/SampleAttestedTLS/non_enc_client/Makefile b/SampleCode/SampleAttestedTLS/non_enc_client/Makefile new file mode 100644 index 000000000..b0ba4cb1a --- /dev/null +++ b/SampleCode/SampleAttestedTLS/non_enc_client/Makefile @@ -0,0 +1,63 @@ +# +# 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 ../sgxenv.mk + +Client_Include_Path := -I. -I$(SGX_SDK)/include -I/usr/include/openssl +Client_Cpp_Flags := -DCLIENT_UNTRUSTED $(SGX_COMMON_CFLAGS) -fPIC -Wno-attributes $(Client_Include_Path) + +ifeq ($(SGX_DEBUG), 1) + Client_Cpp_Flags += -DDEBUG -UNDEBUG -UEDEBUG +else ifeq ($(SGX_PRERELEASE), 1) + Client_Cpp_Flags += -DNDEBUG -DEDEBUG -UDEBUG +else + Client_Cpp_Flags += -DNDEBUG -UEDEBUG -UDEBUG +endif + +Client_Cpp_Flags += -std=c++11 + +Client_Link_Flags := $(SGX_COMMON_CFLAGS) -L. -lssl \ + -L$(SGX_LIBRARY_PATH) -l$(Urts_Library_Name) -lsgx_utls \ + -lsgx_dcap_ql -lsgx_dcap_quoteverify -lcrypto + +.PHONY: all build clean #run + +all: build + +build: + $(CXX) -c $(Client_Cpp_Flags) client.cpp ../common/err_msg.cpp ../common/verify_callback.cpp + $(CXX) -o tls_non_enc_client client.o err_msg.o verify_callback.o $(Client_Link_Flags) + +clean: + rm -f tls_non_enc_client *.o + +run: + ./tls_non_enc_client -server:localhost -port:12341 diff --git a/SampleCode/SampleAttestedTLS/non_enc_client/client.cpp b/SampleCode/SampleAttestedTLS/non_enc_client/client.cpp new file mode 100644 index 000000000..c74436465 --- /dev/null +++ b/SampleCode/SampleAttestedTLS/non_enc_client/client.cpp @@ -0,0 +1,331 @@ +/** +* +* MIT License +* +* Copyright (c) Open Enclave SDK contributors. +* +* Permission is hereby granted, free of charge, to any person obtaining a copy +* of this software and associated documentation files (the "Software"), to deal +* in the Software without restriction, including without limitation the rights +* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +* copies of the Software, and to permit persons to whom the Software is +* furnished to do so, subject to the following conditions: +* +* The above copyright notice and this permission notice shall be included in all +* copies or substantial portions of the Software. +* +* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +* SOFTWARE +* +*/ + +#include +#include +#include +#include +#include +#include + +#include "sgx_utls.h" +#include + +#include +#include +#include +#include +#include +#include + +#include "../common/common.h" + +int verify_callback(int preverify_ok, X509_STORE_CTX* ctx); +int create_socket(char* server_name, char* server_port); + +int parse_arguments( + int argc, + char** argv, + char** server_name, + char** server_port) +{ + int ret = 1; + const char* option = nullptr; + unsigned int param_len = 0; + + if (argc != 3) + goto print_usage; + + option = "-server:"; + param_len = strlen(option); + if (strncmp(argv[1], option, param_len) != 0) + goto print_usage; + *server_name = (char*)(argv[1] + param_len); + + option = "-port:"; + param_len = strlen(option); + if (strncmp(argv[2], option, param_len) != 0) + goto print_usage; + + *server_port = (char*)(argv[2] + param_len); + ret = 0; + goto done; + +print_usage: + printf(TLS_CLIENT "Usage: %s -server: -port:\n", argv[0]); +done: + return ret; +} + +// This routine conducts a simple HTTP request/response communication with +// server +int communicate_with_server(SSL* ssl) +{ + unsigned char buf[200]; + int ret = 1; + int error = 0; + unsigned int len = 0; + int bytes_written = 0; + int bytes_read = 0; + + // Write an GET request to the server + printf(TLS_CLIENT "-----> Write to server:\n"); + len = snprintf((char*)buf, sizeof(buf) - 1, CLIENT_PAYLOAD); + while ((bytes_written = SSL_write(ssl, buf, (size_t)len)) <= 0) + { + error = SSL_get_error(ssl, bytes_written); + if (error == SSL_ERROR_WANT_WRITE) + continue; + printf(TLS_CLIENT "Failed! SSL_write returned %d\n", error); + ret = bytes_written; + goto done; + } + + printf(TLS_CLIENT "%d bytes written\n", bytes_written); + + // Read the HTTP response from server + printf(TLS_CLIENT "<---- Read from server:\n"); + do + { + len = sizeof(buf) - 1; + memset(buf, 0, sizeof(buf)); + bytes_read = SSL_read(ssl, buf, (size_t)len); + if (bytes_read <= 0) + { + int error = SSL_get_error(ssl, bytes_read); + if (error == SSL_ERROR_WANT_READ) + continue; + + printf(TLS_CLIENT "Failed! SSL_read returned error=%d\n", error); + ret = bytes_read; + goto done; + } + + printf(TLS_CLIENT " %d bytes read\n", bytes_read); + + // check to to see if received payload is expected + if ((bytes_read != SERVER_PAYLOAD_SIZE) || + (memcmp(SERVER_PAYLOAD, buf, bytes_read) != 0)) + { + printf( + TLS_CLIENT "ERROR: expected reading %lu bytes but only " + "received %d bytes\n", + SERVER_PAYLOAD_SIZE, + bytes_read); + ret = bytes_read; + goto done; + } + else + { + printf(TLS_CLIENT + " received all the expected data from server\n\n"); + ret = 0; + printf("Verified: the contents of server payload were expected\n\n"); + break; + } + } while (1); + ret = 0; +done: + return ret; +} + +// create a socket and connect to the server_name:server_port +int create_socket(char* server_name, char* server_port) +{ + int sockfd = -1; + struct addrinfo hints, *dest_info, *curr_di; + int res; + + hints = {0}; + hints.ai_family = AF_INET; + hints.ai_socktype = SOCK_STREAM; + + if ((res = getaddrinfo(server_name, server_port, &hints, &dest_info)) != 0) + { + printf( + TLS_CLIENT "Error: Cannot resolve hostname %s. %s\n", + server_name, + gai_strerror(res)); + goto done; + } + + curr_di = dest_info; + while (curr_di) + { + if (curr_di->ai_family == AF_INET) + { + break; + } + + curr_di = curr_di->ai_next; + } + + if (!curr_di) + { + printf( + TLS_CLIENT "Error: Cannot get address for hostname %s.\n", + server_name); + goto done; + } + + sockfd = socket(AF_INET, SOCK_STREAM, 0); + if (sockfd == -1) + { + printf(TLS_CLIENT "Error: Cannot create socket %d.\n", errno); + goto done; + } + + if (connect( + sockfd, + (struct sockaddr*)curr_di->ai_addr, + sizeof(struct sockaddr)) == -1) + { + printf( + TLS_CLIENT "failed to connect to %s:%s (errno=%d)\n", + server_name, + server_port, + errno); + close(sockfd); + sockfd = -1; + goto done; + } + printf(TLS_CLIENT "connected to %s:%s\n", server_name, server_port); + +done: + if (dest_info) + freeaddrinfo(dest_info); + + return sockfd; +} + +int main(int argc, char** argv) +{ + int ret = 1; + SSL_CTX* ctx = nullptr; + SSL* ssl = nullptr; + int serversocket = 0; + char* server_name = nullptr; + char* server_port = nullptr; + int error = 0; + + printf("\nStarting" TLS_CLIENT "\n\n\n"); + if ((error = parse_arguments(argc, argv, &server_name, &server_port)) != 0) + { + printf( + TLS_CLIENT "TLS client:parse input parmeter failed (%d)!\n", error); + goto done; + } + + // initialize openssl library and register algorithms + OpenSSL_add_all_algorithms(); + ERR_load_BIO_strings(); + ERR_load_crypto_strings(); + SSL_load_error_strings(); + + if (SSL_library_init() < 0) + { + printf(TLS_CLIENT + "TLS client: could not initialize the OpenSSL library !\n"); + goto done; + } + + if ((ctx = SSL_CTX_new(SSLv23_client_method())) == nullptr) + { + printf(TLS_CLIENT "TLS client: unable to create a new SSL context\n"); + goto done; + } + + // choose TLSv1.2 by excluding SSLv2, SSLv3 ,TLS 1.0 and TLS 1.1 + SSL_CTX_set_options(ctx, SSL_OP_NO_SSLv2); + SSL_CTX_set_options(ctx, SSL_OP_NO_SSLv3); + SSL_CTX_set_options(ctx, SSL_OP_NO_TLSv1); + SSL_CTX_set_options(ctx, SSL_OP_NO_TLSv1_1); + // specify the verify_callback for custom verification + SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, &verify_callback); + + if ((ssl = SSL_new(ctx)) == nullptr) + { + printf(TLS_CLIENT + "Unable to create a new SSL connection state object\n"); + goto done; + } + + serversocket = create_socket(server_name, server_port); + if (serversocket == -1) + { + printf( + TLS_CLIENT + "create a socket and initate a TCP connect to server: %s:%s " + "(errno=%d)\n", + server_name, + server_port, + errno); + goto done; + } + + printf( + TLS_CLIENT + "create a socket and initate a TCP connect to server: %s:%s " + "\n", + server_name, + server_port); + // setup ssl socket and initiate TLS connection with TLS server + SSL_set_fd(ssl, serversocket); + if ((error = SSL_connect(ssl)) != 1) + { + printf( + TLS_CLIENT "Error: Could not establish an SSL session ret2=%d " + "SSL_get_error()=%d\n", + error, + SSL_get_error(ssl, error)); + goto done; + } + printf( + TLS_CLIENT "successfully established TLS channel:%s\n", + SSL_get_version(ssl)); + + // start the client server communication + if ((error = communicate_with_server(ssl)) != 0) + { + printf(TLS_CLIENT "Failed: communicate_with_server (ret=%d)\n", error); + goto done; + } + + // Free the structures we don't need anymore + ret = 0; +done: + if (serversocket != -1) + close(serversocket); + + if (ssl) + SSL_free(ssl); + + if (ctx) + SSL_CTX_free(ctx); + + printf(TLS_CLIENT " %s\n", (ret == 0) ? "success" : "failed"); + return (ret); +} diff --git a/SampleCode/SampleAttestedTLS/prepare_sgxssl.sh b/SampleCode/SampleAttestedTLS/prepare_sgxssl.sh new file mode 100755 index 000000000..6cb56053f --- /dev/null +++ b/SampleCode/SampleAttestedTLS/prepare_sgxssl.sh @@ -0,0 +1,100 @@ +#!/usr/bin/env bash +# +# 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. +# +# + +ARG1=${1:-build} +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-1.1.1m +sgxssl_github_archive=https://github.com/01org/intel-sgx-ssl/archive +sgxssl_file_name=support_tls_lin_1.1.1m +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/1.1.1/$openssl_ver_name.tar.gz + +FileExists() { + pushd $sgxssl_dir/Linux/ + make clean sgxssl_no_mitigation + echo "build sgxssl completed" + popd +} + +debug=false + +if [ $debug == true ] ; then + read -n 1 -p "download souce code only, because we need to build ourselves" +fi + +openssl_chksum=f89199be8b23ca45fc7cb9f1d8d3ee67312318286ad030f5316aca6462db6c96 +sgxssl_chksum=e645b5e9b0d81da4470d454b7f7d838cc310dd72427bd343bfe744c82493b39e +rm -f check_sum_openssl.txt check_sum_sgxssl.txt +if [ ! -f $build_script ]; then + wget $sgxssl_github_archive/$sgxssl_file_name.zip -P $sgxssl_dir/ || exit 1 + sha256sum $sgxssl_dir/$sgxssl_file_name.zip > $sgxssl_dir/check_sum_sgxssl.txt + grep $sgxssl_chksum $sgxssl_dir/check_sum_sgxssl.txt + if [ $? -ne 0 ]; then + echo "File $sgxssl_dir/$sgxssl_file_name.zip checksum failure" + rm -f $sgxssl_dir/$sgxssl_file_name.zip + exit -1 + fi + unzip -qq $sgxssl_dir/$sgxssl_file_name.zip -d $sgxssl_dir/ || exit 1 + mv $sgxssl_dir/intel-sgx-ssl-$sgxssl_file_name/* $sgxssl_dir/ || exit 1 + rm $sgxssl_dir/$sgxssl_file_name.zip || exit 1 + rm -rf $sgxssl_dir/intel-sgx-ssl-$sgxssl_file_name || exit 1 +fi + +if [ ! -f $openssl_out_dir/$openssl_ver_name.tar.gz ]; then + wget $full_openssl_url_old -P $openssl_out_dir || wget $full_openssl_url -P $openssl_out_dir || exit 1 + sha256sum $openssl_out_dir/$openssl_ver_name.tar.gz > $sgxssl_dir/check_sum_openssl.txt + echo "downloading OPENSSL source code now..." + grep $openssl_chksum $sgxssl_dir/check_sum_openssl.txt + if [ $? -ne 0 ]; then + echo "File $openssl_out_dir/$openssl_ver_name.tar.gz checksum failure" + rm -f $openssl_out_dir/$openssl_ver_name.tar.gz + exit -1 + fi +fi + + +if [ "$1" = "nobuild" ]; then + exit 0 +fi + +if [ $debug == false ] ; then + echo "only when debug is turned off, can script go here" + FileExists + echo "endof of build sgxssl" && exit 0 +fi + +echo "end of script" diff --git a/SampleCode/SampleAttestedTLS/server/Makefile b/SampleCode/SampleAttestedTLS/server/Makefile new file mode 100644 index 000000000..871ebe386 --- /dev/null +++ b/SampleCode/SampleAttestedTLS/server/Makefile @@ -0,0 +1,65 @@ +# +# 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. +# +# + +# MIT License +# +# Copyright (c) Open Enclave SDK contributors. +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in all +# copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +# SOFTWARE + +all: build + +build: + $(MAKE) -C enc + $(MAKE) -C host + +clean: + $(MAKE) -C enc clean + $(MAKE) -C host clean + +run: + host/tls_server_host ./enc/tls_server_enclave.signed.so -port:12341 -server-in-loop diff --git a/SampleCode/SampleAttestedTLS/server/enc/Makefile b/SampleCode/SampleAttestedTLS/server/enc/Makefile new file mode 100644 index 000000000..b0d740cf9 --- /dev/null +++ b/SampleCode/SampleAttestedTLS/server/enc/Makefile @@ -0,0 +1,66 @@ +# +# 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 ../../sgxenv.mk + +INCDIR := $(SGX_SDK)/include +ENC_TLS_SERVER_Name := tls_server_enclave.so +Signed_ENC_TLS_SERVER_Name := tls_server_enclave.signed.so + +.PHONY: all build clean run + +SRC_FILES = openssl_server.cpp ../../sgx_socket/htons.c ../../sgx_socket/htonl.c ../../sgx_socket/trusted_sgx_socket.cpp ../../common/verify_callback.cpp ../../common/utility.cpp ../../common/openssl_utility.cpp ../../common/tcommon.cpp ../../common/err_msg.cpp + +OBJ_FILES = tls_server_t.o trusted_sgx_socket.o htonl.o htons.o openssl_server.o verify_callback.o utility.o openssl_utility.o tcommon.o err_msg.o + +all: + $(MAKE) build + $(MAKE) sign + +build: + @ echo "Compilers used: $(CC), $(CXX)" + $(SGX_EDGER8R) ../tls_server.edl --trusted \ + --search-path . \ + --search-path $(INCDIR) \ + --search-path $(SOCKET_DIR)/include \ + --search-path ../../common \ + --search-path $(SGXSSL_PKG_PATH)/include + + $(CXX) -c -DM_TLS_SERVER $(Enclave_Cpp_Flags) -I. -std=c++11 -include "tsgxsslio.h" ${SRC_FILES} + $(CC) -c $(Enclave_C_Flags) -I. tls_server_t.c + $(CXX) -o $(ENC_TLS_SERVER_Name) $(OBJ_FILES) $(Enclave_Link_Flags) + +sign: + $(SGX_ENCLAVE_SIGNER) sign -key private_test_key.pem -enclave $(ENC_TLS_SERVER_Name) \ + -out $(Signed_ENC_TLS_SERVER_Name) -config server_enc.config.xml + +clean: + rm -f *.o $(ENC_TLS_SERVER_Name) $(Signed_ENC_TLS_SERVER_Name) tls_server_t.* diff --git a/SampleCode/SampleAttestedTLS/server/enc/enclave.lds b/SampleCode/SampleAttestedTLS/server/enc/enclave.lds new file mode 100644 index 000000000..127093a88 --- /dev/null +++ b/SampleCode/SampleAttestedTLS/server/enc/enclave.lds @@ -0,0 +1,10 @@ +client_enclave.so +{ + global: + g_global_data_sim; + g_global_data; + enclave_entry; + g_peak_heap_used; + local: + *; +}; diff --git a/SampleCode/SampleAttestedTLS/server/enc/openssl_server.cpp b/SampleCode/SampleAttestedTLS/server/enc/openssl_server.cpp new file mode 100644 index 000000000..a81130dc9 --- /dev/null +++ b/SampleCode/SampleAttestedTLS/server/enc/openssl_server.cpp @@ -0,0 +1,242 @@ +/** +* +* MIT License +* +* Copyright (c) Open Enclave SDK contributors. +* +* Permission is hereby granted, free of charge, to any person obtaining a copy +* of this software and associated documentation files (the "Software"), to deal +* in the Software without restriction, including without limitation the rights +* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +* copies of the Software, and to permit persons to whom the Software is +* furnished to do so, subject to the following conditions: +* +* The above copyright notice and this permission notice shall be included in all +* copies or substantial portions of the Software. +* +* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +* SOFTWARE +* +*/ + +#include +#include +#include +#include +#include +#include +#include +#include "../../common/openssl_utility.h" + +extern "C" +{ + int set_up_tls_server(char* server_port, bool keep_server_up); + sgx_status_t ocall_close(int *ret, int fd); +}; + +int verify_callback(int preverify_ok, X509_STORE_CTX* ctx); + +int create_listener_socket(int port, int& server_socket) +{ + int ret = -1; + const int reuse = 1; + struct sockaddr_in addr; + addr.sin_family = AF_INET; + addr.sin_port = htons(port); + addr.sin_addr.s_addr = htonl(INADDR_ANY); + + server_socket = socket(AF_INET, SOCK_STREAM, 0); + if (server_socket < 0) + { + t_print(TLS_SERVER "socket creation failed\n"); + goto exit; + } + + if (setsockopt( + server_socket, + SOL_SOCKET, + SO_REUSEADDR, + (const void*)&reuse, + sizeof(reuse)) < 0) + { + t_print(TLS_SERVER "setsocket failed \n"); + goto exit; + } + + if (bind(server_socket, (struct sockaddr*)&addr, sizeof(addr)) < 0) + { + t_print(TLS_SERVER "Unable to bind socket to the port\n"); + goto exit; + } + + if (listen(server_socket, 20) < 0) + { + t_print(TLS_SERVER "Unable to open socket for listening\n"); + goto exit; + } + ret = 0; +exit: + return ret; +} + +int handle_communication_until_done( + int& server_socket_fd, + int& client_socket_fd, + SSL_CTX*& ssl_server_ctx, + SSL*& ssl_session, + bool keep_server_up) +{ + int ret = -1; + int test_error = 1; +waiting_for_connection_request: + + struct sockaddr_in addr; + uint len = sizeof(addr); + + // reset ssl_session and client_socket_fd to prepare for the new TLS + // connection + if (client_socket_fd > 0) + { + ocall_close(&ret, client_socket_fd); + if (ret != 0) { + t_print(TLS_SERVER "OCALL: error closing client socket before starting a new TLS session.\n"); + goto exit; + } + } + SSL_free(ssl_session); + t_print(TLS_SERVER " waiting for client connection\n"); + + client_socket_fd = accept(server_socket_fd, (struct sockaddr*)&addr, &len); + + if (client_socket_fd < 0) + { + t_print(TLS_SERVER "Unable to accept the client request\n"); + goto exit; + } + + // create a new SSL structure for a connection + if ((ssl_session = SSL_new(ssl_server_ctx)) == nullptr) + { + t_print(TLS_SERVER + "Unable to create a new SSL connection state object\n"); + goto exit; + } + + SSL_set_fd(ssl_session, client_socket_fd); + + // wait for a TLS/SSL client to initiate a TLS/SSL handshake + + t_print(TLS_SERVER "initiating a passive connect SSL_accept\n"); + test_error = SSL_accept(ssl_session); + if (test_error <= 0) + { + t_print(TLS_SERVER " SSL handshake failed, error(%d)(%d)\n", + test_error, SSL_get_error(ssl_session, test_error)); + goto exit; + } + + t_print(TLS_SERVER "<---- Read from client:\n"); + if (read_from_session_peer( + ssl_session, CLIENT_PAYLOAD, CLIENT_PAYLOAD_SIZE) != 0) + { + t_print(TLS_SERVER " Read from client failed\n"); + goto exit; + } + + t_print(TLS_SERVER "<---- Write to client:\n"); + if (write_to_session_peer( + ssl_session, SERVER_PAYLOAD, strlen(SERVER_PAYLOAD)) != 0) + { + t_print(TLS_SERVER " Write to client failed\n"); + goto exit; + } + + if (keep_server_up) + goto waiting_for_connection_request; + + ret = 0; +exit: + return ret; +} + +int set_up_tls_server(char* server_port, bool keep_server_up) +{ + int ret = 0; + int server_socket_fd; + int client_socket_fd = -1; + unsigned int server_port_number; + + X509* certificate = nullptr; + EVP_PKEY* pkey = nullptr; + SSL_CONF_CTX* ssl_confctx = SSL_CONF_CTX_new(); + + SSL_CTX* ssl_server_ctx = nullptr; + SSL* ssl_session = nullptr; + if ((ssl_server_ctx = SSL_CTX_new(TLS_server_method())) == nullptr) + { + t_print(TLS_SERVER "unable to create a new SSL context\n"); + goto exit; + } + + if (initalize_ssl_context(ssl_confctx, ssl_server_ctx) != SGX_SUCCESS) + { + t_print(TLS_SERVER "unable to create a initialize SSL context\n "); + goto exit; + } + SSL_CTX_set_verify(ssl_server_ctx, SSL_VERIFY_PEER, &verify_callback); + + if (load_tls_certificates_and_keys(ssl_server_ctx, certificate, pkey) != 0) + { + t_print(TLS_SERVER + " unable to load certificate and private key on the server\n "); + goto exit; + } + + server_port_number = (unsigned int)atoi(server_port); // convert to char* to int + if (create_listener_socket(server_port_number, server_socket_fd) != 0) + { + t_print(TLS_SERVER " unable to create listener socket on the server\n "); + goto exit; + } + + // handle communication + ret = handle_communication_until_done( + server_socket_fd, + client_socket_fd, + ssl_server_ctx, + ssl_session, + keep_server_up); + if (ret != 0) + { + t_print(TLS_SERVER "server communication error %d\n", ret); + goto exit; + } + +exit: + ocall_close(&ret, client_socket_fd); // close the socket connections + if (ret != 0) + t_print(TLS_SERVER "OCALL: error closing client socket\n"); + ocall_close(&ret, server_socket_fd); + if (ret != 0) + t_print(TLS_SERVER "OCALL: error closing server socket\n"); + + if (ssl_session) + { + SSL_shutdown(ssl_session); + SSL_free(ssl_session); + } + if (ssl_server_ctx) + SSL_CTX_free(ssl_server_ctx); + if (ssl_confctx) + SSL_CONF_CTX_free(ssl_confctx); + if (certificate) + X509_free(certificate); + if (pkey) + EVP_PKEY_free(pkey); + return (ret); +} diff --git a/SampleCode/SampleAttestedTLS/server/enc/private_test_key.pem b/SampleCode/SampleAttestedTLS/server/enc/private_test_key.pem new file mode 100644 index 000000000..38c002ab6 --- /dev/null +++ b/SampleCode/SampleAttestedTLS/server/enc/private_test_key.pem @@ -0,0 +1,39 @@ +-----BEGIN RSA PRIVATE KEY----- +MIIG5AIBAAKCAYEA3G5Wa4v6OPqaboH5qO/g8Hg0NCkAIRAN3dCepNPjtjY/Uanr +mMu99GZn/L/+SzMjawYhudUmtHkh3m3nHKJqp0HMVgXV0k1BK00fnlUHYP2bNr5R +tV0LvpGH6Iy4b7t0/WRCZrxVdbJfaCnR8f7n9AJZ9xsnuuIiRL1dppH1lfijHuaj +aH2VBbOrrzkhS3LQQloG278KO3Yy0VeVCbm7ljO06QXv+V2I4jExVRtiiWAPnb0x +54b6AKkD+K4r+9LvYofZPVig+aQ9y54H3wJw3PWOlTOgkJPONIDhxkP+sTbaAlOD +NSE3XtPdMkGIH3RxMSkg8NWEa9tYhNOIfNUAN/ECT1Qe6UhMS5MVH2bCru/TijbA +IIWUwypWpt8UBs420RF8aJ69mivLsiEeJm3ODwa70h+1e2Da6Kgp6kpG9ZOm3wQ7 +WK9ywxiG1HR9Yd+wu8bBMfW1HBCjdpH2wQFOTsC5qy1FqIAU9a5r3tXn6CbMJnev +Sg2NAwd5UTADBOVhAgEDAoIBgQCS9DmdB/wl/Gb0VqZwn+tK+s14G1VrYAk+ixRt +4pfOztThG/Jl3SlNmZqof/7czMJHWWvROMR4UME+8+9obEcaK92Oro6MM4DHiL++ +41pAqRIkfuEjk10ptlqbCHr1J6NTmCxEfY5OdupFcTahVJqirDv6Ehp8lsGDKOkZ +tqO5UGy/RGzwU7iud8fKJhYyTIrW5q89KgbSTsyLj7ixJn0OzSNGA/VQ6QXsIMuO +EkGw6rUT03aaWfwAcK1QdB1SjJ5aOTLATtFPs3WKA40dBv4yNs7seywMqFq2rE1c +TxgbittaId28nCqNWH0dgJrq75qnYc8BucrvOd36tQwAYjs0Sr03/8TkyiWkC8mf +C0LT+aqD90bcF+S5hYr+grhBO9SzWYNWwvlWy2j3N6W/gCgmJbgEB+oke7NAR5Sd +Vy8wHiJshGKQ8xDBBAzFikZ2+rqHcHsuNjxNcp0qDbMaNrC4AxEKkL1mw6znD61F +IFQkKUdeAM5L+FnnyLU2qAw82qsCgcEA8lN0PU+sb5e2t1A92iswTyHcPktMmINM +OtnvJcAV4FWf3pM9kUKFyeT3HeWZ/+jEyI+tDvoyNcg8mjzE8JmIfzaM/7NhsJ6k +hACK7G6YW1yEt7kvbLY9h8B2MaH8BObVwJu0luSAaTnZU323t2yakiGmlLdgYPSl +0zxWdUzNu0Tn/rBVPTkNzK0T8Lq935KXvHU/OECvQPrDZCVAPFBgng7qH40SIyp1 +hMKVbWTKb6GDmn0O2mgSsT0jTRl0mj0hAoHBAOjemN+SupJ/VsVIdllMw0KBe/Qv +keUT+eekfpYNRKeQ8RyNeQj0ccDqKmgbBb8kRG2GvV9Eoc88TvKHMYuoHupKWXuh +FeF6b1GA28RnRhWczwyKpmmrgCUhj/d5A6ANogNvgs+Vxy7A1OvP7c/A90OsgTdc +deOyqDUAdIj6snIhiz2NUkIJy9TlX7tqVc/VATQoyTRjq2bp9FNYKd1e5JytNfvH +F2swHBZUUonAn0JHXX75av2w83YdRjIafA9gQQKBwQChjPgo38hKZSR6NX6RciA0 +wT1+3N27AjLR5p9ugA6VjmqUYikLga6GmKS+mRFVRdiFtR4J/CF5MChm0y31u7BU +zwiqd5Z1vxhYAFydnxA86Fh6e3TzJCkFKvl2a/1YmePVvSMPQwBGJpDiU8/Pnbxh +a8RjJOrrTcPiKDmjiIkng0VUdY4o0LPdyLf10dPqYbp9o3961corUdeYGNV9iusU +CfFqXgwXcaOt1w5I7dxKa60RqLSRmrcg02zeEPhm02sCgcEAmz8QlQx8Yao52Nr5 +kN3Xgaun+B+2mLf778L/DrODGmCgvbOmBfhL1fFxmryuf22C868o6i3BNNLfTFoh +B8Vp8YbmUmtj66b04QCSgu+EDmiKCFxu8R0AGMEKpPtXwAkWrPUB37kvdICN8oqe +ioCk18hWJOhOl8xwI1WjBfx29sEHfl421rEyje4/0kbj3+NWIsXbeEJyRJv4N5Ab +6OntvcjOp9oPnMq9ZDg3BoBqLC+TqfucqSCiTr4uzBGoCkArAoHBANdEojnkFjyw +cdoU54SQ0/JXLP38C2tibMg/kLEuAKIw6fWasEdf/SQ08Z0+mXomQDMhjBj98Tc8 +aEbkEqhwWLW2py3djDLPifSxMx+taog930SMubKquefyztX+jzajElCahwmt4XmK +l8tZTFVQPWqdRmtUvFCrHRGi+Rw5FApSDQqHgFANXuSx8mSNQKiMWQIO65cYT/Vi +490OqpNhUA5lXTxywdQmyg7RdCiV2xAYy+NE1EAIBYUdlNPG1WbAHA== +-----END RSA PRIVATE KEY----- diff --git a/SampleCode/SampleAttestedTLS/server/enc/server_enc.config.xml b/SampleCode/SampleAttestedTLS/server/enc/server_enc.config.xml new file mode 100644 index 000000000..99434e818 --- /dev/null +++ b/SampleCode/SampleAttestedTLS/server/enc/server_enc.config.xml @@ -0,0 +1,12 @@ + + 0 + 0 + 0x40000 + 0x100000 + 2 + 1 + + 0 + 0 + 0xFFFFFFFF + diff --git a/SampleCode/SampleAttestedTLS/server/host/Makefile b/SampleCode/SampleAttestedTLS/server/host/Makefile new file mode 100644 index 000000000..d687063f7 --- /dev/null +++ b/SampleCode/SampleAttestedTLS/server/host/Makefile @@ -0,0 +1,52 @@ +# +# 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 ../../sgxenv.mk + +INCDIR := $(SGX_SDK)/include +SOCKET_INCDIR := $(SOCKET_DIR)/include + +all: build + +build: + @ echo "Compilers used: $(CC), $(CXX)" + $(SGX_EDGER8R) ../tls_server.edl --untrusted \ + --search-path $(INCDIR) \ + --search-path ../../common \ + --search-path $(SOCKET_INCDIR) \ + --search-path $(SGXSSL_PKG_PATH)/include + + $(CC) -c $(App_C_Flags) tls_server_u.c + $(CXX) -c -DM_TLS_SERVER $(App_Cpp_Flags) host.cpp ../../sgx_socket/untrusted_sgx_socket.cpp ../../common/ucommon.cpp + $(CXX) -o tls_server_host untrusted_sgx_socket.o tls_server_u.o host.o ucommon.o $(App_Link_Flags) + +clean: + rm -f tls_server_host* *.o tls_server_u.* tls_server_args.h diff --git a/SampleCode/SampleAttestedTLS/server/host/host.cpp b/SampleCode/SampleAttestedTLS/server/host/host.cpp new file mode 100644 index 000000000..5e21af2b6 --- /dev/null +++ b/SampleCode/SampleAttestedTLS/server/host/host.cpp @@ -0,0 +1,234 @@ +/** +* +* MIT License +* +* Copyright (c) Open Enclave SDK contributors. +* +* Permission is hereby granted, free of charge, to any person obtaining a copy +* of this software and associated documentation files (the "Software"), to deal +* in the Software without restriction, including without limitation the rights +* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +* copies of the Software, and to permit persons to whom the Software is +* furnished to do so, subject to the following conditions: +* +* The above copyright notice and this permission notice shall be included in all +* copies or substantial portions of the Software. +* +* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +* SOFTWARE +* +*/ + +#include "sgx_urts.h" +#include +#include "tls_server_u.h" + +#define LOOP_OPTION "-server-in-loop" +/* Global EID shared by multiple threads */ +sgx_enclave_id_t server_global_eid = 0; + + +typedef struct _sgx_errlist_t { + sgx_status_t err; + const char *msg; + const char *sug; /* Suggestion */ +} sgx_errlist_t; + +/* Error code returned by sgx_create_enclave */ +static sgx_errlist_t sgx_errlist[] = { + { + SGX_ERROR_UNEXPECTED, + "Unexpected error occurred.", + NULL + }, + { + SGX_ERROR_INVALID_PARAMETER, + "Invalid parameter.", + NULL + }, + { + SGX_ERROR_OUT_OF_MEMORY, + "Out of memory.", + NULL + }, + { + SGX_ERROR_ENCLAVE_LOST, + "Power transition occurred.", + "Please refer to the sample \"PowerTransition\" for details." + }, + { + SGX_ERROR_INVALID_ENCLAVE, + "Invalid enclave image.", + NULL + }, + { + SGX_ERROR_INVALID_ENCLAVE_ID, + "Invalid enclave identification.", + NULL + }, + { + SGX_ERROR_INVALID_SIGNATURE, + "Invalid enclave signature.", + NULL + }, + { + SGX_ERROR_OUT_OF_EPC, + "Out of EPC memory.", + NULL + }, + { + SGX_ERROR_NO_DEVICE, + "Invalid SGX device.", + "Please make sure SGX module is enabled in the BIOS, and install SGX driver afterwards." + }, + { + SGX_ERROR_MEMORY_MAP_CONFLICT, + "Memory map conflicted.", + NULL + }, + { + SGX_ERROR_INVALID_METADATA, + "Invalid enclave metadata.", + NULL + }, + { + SGX_ERROR_DEVICE_BUSY, + "SGX device was busy.", + NULL + }, + { + SGX_ERROR_INVALID_VERSION, + "Enclave version was invalid.", + NULL + }, + { + SGX_ERROR_INVALID_ATTRIBUTE, + "Enclave was not authorized.", + NULL + }, + { + SGX_ERROR_ENCLAVE_FILE_ACCESS, + "Can't open enclave file.", + NULL + }, +}; + +/* Check error conditions for loading enclave */ +void print_error_message(sgx_status_t ret) +{ + size_t idx = 0; + size_t ttl = sizeof sgx_errlist/sizeof sgx_errlist[0]; + + for (idx = 0; idx < ttl; idx++) { + if(ret == sgx_errlist[idx].err) { + if(NULL != sgx_errlist[idx].sug) + printf("Info: %s\n", sgx_errlist[idx].sug); + printf("Error: %s\n", sgx_errlist[idx].msg); + break; + } + } + + if (idx == ttl) + printf("Error code is 0x%X. Please refer to the \"Intel SGX SDK Developer Reference\" for more details.\n", ret); +} + +sgx_status_t initialize_enclave(const char *enclave_path) +{ + sgx_status_t ret = SGX_ERROR_UNEXPECTED; + + // the 1st parameter should be SERVER_ENCLAVE_FILENAME + ret = sgx_create_enclave(enclave_path, SGX_DEBUG_FLAG, NULL, NULL, + &server_global_eid, NULL); + + printf("Server Enc: Enclave library %s\n", enclave_path); + + if (ret != SGX_SUCCESS) + { + print_error_message(ret); + return ret; + } + return ret; +} + +void terminate_enclave() +{ + sgx_destroy_enclave(server_global_eid); + printf("Host: Enclave successfully terminated.\n"); +} + +int main(int argc, const char* argv[]) +{ + sgx_status_t result = SGX_SUCCESS; + int ret = 1; + char* server_port = NULL; + int keep_server_up = 0; // should be bool type, 0 false, 1 true + + /* Check argument count */ + if (argc != 3) + { + if (argc == 4) + { + if (strcmp(argv[3], LOOP_OPTION) != 0) + { + goto print_usage; + } + else + { + keep_server_up = 1; + goto read_port; + } + } + print_usage: + printf( + "Usage: %s TLS_SERVER_ENCLAVE_PATH -port: [%s]\n", + argv[0], + LOOP_OPTION); + return 1; + } + +read_port: + // read port parameter + { + char* option = (char*)"-port:"; + size_t param_len = 0; + param_len = strlen(option); + if (strncmp(argv[2], option, param_len) == 0) + { + server_port = (char*)(argv[2] + param_len); + } + else + { + fprintf(stderr, "Unknown option %s\n", argv[2]); + goto print_usage; + } + } + printf("server port = %s\n", server_port); + + printf("Host: Creating an tls server enclave\n"); + result = initialize_enclave(argv[1]); + if (result != SGX_SUCCESS) + { + goto exit; + } + + printf("Host: calling setup_tls_server\n"); + result = set_up_tls_server(server_global_eid, &ret, server_port, keep_server_up); + if (result != SGX_SUCCESS || ret != 0) + { + printf("Host: setup_tls_server failed\n"); + goto exit; + } + +exit: + + printf("Host: Terminating enclaves\n"); + terminate_enclave(); + + printf("Host: %s \n", (ret == 0) ? "succeeded" : "failed"); + return ret; +} diff --git a/SampleCode/SampleAttestedTLS/server/tls_server.edl b/SampleCode/SampleAttestedTLS/server/tls_server.edl new file mode 100644 index 000000000..38e25be4a --- /dev/null +++ b/SampleCode/SampleAttestedTLS/server/tls_server.edl @@ -0,0 +1,44 @@ +/* + * 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. + * + */ + +enclave { + from "sgx_tstdc.edl" import *; + from "sgx_socket.edl" import *; + from "enclave.edl" import *; + from "sgx_tsgxssl.edl" import *; + from "sgx_ttls.edl" import *; + from "sgx_pthread.edl" import *; + + include "sgx_ttls.h" + trusted { + public int set_up_tls_server([in, string] char* port, int keep_server_up); + }; +}; diff --git a/SampleCode/SampleAttestedTLS/sgx_socket/htonl.c b/SampleCode/SampleAttestedTLS/sgx_socket/htonl.c new file mode 100644 index 000000000..6622d16cc --- /dev/null +++ b/SampleCode/SampleAttestedTLS/sgx_socket/htonl.c @@ -0,0 +1,8 @@ +#include +#include + +uint32_t htonl(uint32_t n) +{ + union { int i; char c; } u = { 1 }; + return u.c ? bswap_32(n) : n; +} diff --git a/SampleCode/SampleAttestedTLS/sgx_socket/htons.c b/SampleCode/SampleAttestedTLS/sgx_socket/htons.c new file mode 100644 index 000000000..03a3a1d59 --- /dev/null +++ b/SampleCode/SampleAttestedTLS/sgx_socket/htons.c @@ -0,0 +1,8 @@ +#include +#include + +uint16_t htons(uint16_t n) +{ + union { int i; char c; } u = { 1 }; + return u.c ? bswap_16(n) : n; +} diff --git a/SampleCode/SampleAttestedTLS/sgx_socket/include/bits/alltypes.h b/SampleCode/SampleAttestedTLS/sgx_socket/include/bits/alltypes.h new file mode 100644 index 000000000..b274239f5 --- /dev/null +++ b/SampleCode/SampleAttestedTLS/sgx_socket/include/bits/alltypes.h @@ -0,0 +1,402 @@ +#define _Addr long +#define _Int64 long +#define _Reg long + +#define __LONG_MAX 0x7fffffffffffffffL +#define __USE_TIME_BITS64 1 + +#if defined(__NEED_va_list) && !defined(__DEFINED_va_list) +typedef __builtin_va_list va_list; +#define __DEFINED_va_list +#endif + +#if defined(__NEED___isoc_va_list) && !defined(__DEFINED___isoc_va_list) +typedef __builtin_va_list __isoc_va_list; +#define __DEFINED___isoc_va_list +#endif + + +#ifndef __cplusplus +#if defined(__NEED_wchar_t) && !defined(__DEFINED_wchar_t) +typedef int wchar_t; +#define __DEFINED_wchar_t +#endif + +#endif + +#if defined(__FLT_EVAL_METHOD__) && __FLT_EVAL_METHOD__ == 2 +#if defined(__NEED_float_t) && !defined(__DEFINED_float_t) +typedef long double float_t; +#define __DEFINED_float_t +#endif + +#if defined(__NEED_double_t) && !defined(__DEFINED_double_t) +typedef long double double_t; +#define __DEFINED_double_t +#endif + +#else +#if defined(__NEED_float_t) && !defined(__DEFINED_float_t) +typedef float float_t; +#define __DEFINED_float_t +#endif + +#if defined(__NEED_double_t) && !defined(__DEFINED_double_t) +typedef double double_t; +#define __DEFINED_double_t +#endif + +#endif + +#if defined(__NEED_max_align_t) && !defined(__DEFINED_max_align_t) +typedef struct { long long __ll; long double __ld; } max_align_t; +#define __DEFINED_max_align_t +#endif + + +#if defined(__NEED_time_t) && !defined(__DEFINED_time_t) +typedef long time_t; +#define __DEFINED_time_t +#endif + +#if defined(__NEED_suseconds_t) && !defined(__DEFINED_suseconds_t) +typedef long suseconds_t; +#define __DEFINED_suseconds_t +#endif + + +#if defined(__NEED_pthread_attr_t) && !defined(__DEFINED_pthread_attr_t) +typedef struct { union { int __i[14]; volatile int __vi[14]; unsigned long __s[7]; } __u; } pthread_attr_t; +#define __DEFINED_pthread_attr_t +#endif + +#if defined(__NEED_pthread_mutex_t) && !defined(__DEFINED_pthread_mutex_t) +typedef struct { union { int __i[10]; volatile int __vi[10]; volatile void *volatile __p[5]; } __u; } pthread_mutex_t; +#define __DEFINED_pthread_mutex_t +#endif + +#if defined(__NEED_mtx_t) && !defined(__DEFINED_mtx_t) +typedef struct { union { int __i[10]; volatile int __vi[10]; volatile void *volatile __p[5]; } __u; } mtx_t; +#define __DEFINED_mtx_t +#endif + +#if defined(__NEED_pthread_cond_t) && !defined(__DEFINED_pthread_cond_t) +typedef struct { union { int __i[12]; volatile int __vi[12]; void *__p[6]; } __u; } pthread_cond_t; +#define __DEFINED_pthread_cond_t +#endif + +#if defined(__NEED_cnd_t) && !defined(__DEFINED_cnd_t) +typedef struct { union { int __i[12]; volatile int __vi[12]; void *__p[6]; } __u; } cnd_t; +#define __DEFINED_cnd_t +#endif + +#if defined(__NEED_pthread_rwlock_t) && !defined(__DEFINED_pthread_rwlock_t) +typedef struct { union { int __i[14]; volatile int __vi[14]; void *__p[7]; } __u; } pthread_rwlock_t; +#define __DEFINED_pthread_rwlock_t +#endif + +#if defined(__NEED_pthread_barrier_t) && !defined(__DEFINED_pthread_barrier_t) +typedef struct { union { int __i[8]; volatile int __vi[8]; void *__p[4]; } __u; } pthread_barrier_t; +#define __DEFINED_pthread_barrier_t +#endif + +#if defined(__NEED_size_t) && !defined(__DEFINED_size_t) +typedef unsigned _Addr size_t; +#define __DEFINED_size_t +#endif + +#if defined(__NEED_uintptr_t) && !defined(__DEFINED_uintptr_t) +typedef unsigned _Addr uintptr_t; +#define __DEFINED_uintptr_t +#endif + +#if defined(__NEED_ptrdiff_t) && !defined(__DEFINED_ptrdiff_t) +typedef _Addr ptrdiff_t; +#define __DEFINED_ptrdiff_t +#endif + +#if defined(__NEED_ssize_t) && !defined(__DEFINED_ssize_t) +typedef _Addr ssize_t; +#define __DEFINED_ssize_t +#endif + +#if defined(__NEED_intptr_t) && !defined(__DEFINED_intptr_t) +typedef _Addr intptr_t; +#define __DEFINED_intptr_t +#endif + +#if defined(__NEED_regoff_t) && !defined(__DEFINED_regoff_t) +typedef _Addr regoff_t; +#define __DEFINED_regoff_t +#endif + +#if defined(__NEED_register_t) && !defined(__DEFINED_register_t) +typedef _Reg register_t; +#define __DEFINED_register_t +#endif + + +#if defined(__NEED_int8_t) && !defined(__DEFINED_int8_t) +typedef signed char int8_t; +#define __DEFINED_int8_t +#endif + +#if defined(__NEED_int16_t) && !defined(__DEFINED_int16_t) +typedef signed short int16_t; +#define __DEFINED_int16_t +#endif + +#if defined(__NEED_int32_t) && !defined(__DEFINED_int32_t) +typedef signed int int32_t; +#define __DEFINED_int32_t +#endif + +#if defined(__NEED_int64_t) && !defined(__DEFINED_int64_t) +typedef signed _Int64 int64_t; +#define __DEFINED_int64_t +#endif + +#if defined(__NEED_intmax_t) && !defined(__DEFINED_intmax_t) +typedef signed _Int64 intmax_t; +#define __DEFINED_intmax_t +#endif + +#if defined(__NEED_uint8_t) && !defined(__DEFINED_uint8_t) +typedef unsigned char uint8_t; +#define __DEFINED_uint8_t +#endif + +#if defined(__NEED_uint16_t) && !defined(__DEFINED_uint16_t) +typedef unsigned short uint16_t; +#define __DEFINED_uint16_t +#endif + +#if defined(__NEED_uint32_t) && !defined(__DEFINED_uint32_t) +typedef unsigned int uint32_t; +#define __DEFINED_uint32_t +#endif + +#if defined(__NEED_uint64_t) && !defined(__DEFINED_uint64_t) +typedef unsigned _Int64 uint64_t; +#define __DEFINED_uint64_t +#endif + +#if defined(__NEED_u_int64_t) && !defined(__DEFINED_u_int64_t) +typedef unsigned _Int64 u_int64_t; +#define __DEFINED_u_int64_t +#endif + +#if defined(__NEED_uintmax_t) && !defined(__DEFINED_uintmax_t) +typedef unsigned _Int64 uintmax_t; +#define __DEFINED_uintmax_t +#endif + + +#if defined(__NEED_mode_t) && !defined(__DEFINED_mode_t) +typedef unsigned mode_t; +#define __DEFINED_mode_t +#endif + +#if defined(__NEED_nlink_t) && !defined(__DEFINED_nlink_t) +typedef unsigned _Reg nlink_t; +#define __DEFINED_nlink_t +#endif + +#if defined(__NEED_off_t) && !defined(__DEFINED_off_t) +typedef _Int64 off_t; +#define __DEFINED_off_t +#endif + +#if defined(__NEED_ino_t) && !defined(__DEFINED_ino_t) +typedef unsigned _Int64 ino_t; +#define __DEFINED_ino_t +#endif + +#if defined(__NEED_dev_t) && !defined(__DEFINED_dev_t) +typedef unsigned _Int64 dev_t; +#define __DEFINED_dev_t +#endif + +#if defined(__NEED_blksize_t) && !defined(__DEFINED_blksize_t) +typedef long blksize_t; +#define __DEFINED_blksize_t +#endif + +#if defined(__NEED_blkcnt_t) && !defined(__DEFINED_blkcnt_t) +typedef _Int64 blkcnt_t; +#define __DEFINED_blkcnt_t +#endif + +#if defined(__NEED_fsblkcnt_t) && !defined(__DEFINED_fsblkcnt_t) +typedef unsigned _Int64 fsblkcnt_t; +#define __DEFINED_fsblkcnt_t +#endif + +#if defined(__NEED_fsfilcnt_t) && !defined(__DEFINED_fsfilcnt_t) +typedef unsigned _Int64 fsfilcnt_t; +#define __DEFINED_fsfilcnt_t +#endif + + +#if defined(__NEED_wint_t) && !defined(__DEFINED_wint_t) +typedef unsigned wint_t; +#define __DEFINED_wint_t +#endif + +#if defined(__NEED_wctype_t) && !defined(__DEFINED_wctype_t) +typedef unsigned long wctype_t; +#define __DEFINED_wctype_t +#endif + + +#if defined(__NEED_timer_t) && !defined(__DEFINED_timer_t) +typedef void * timer_t; +#define __DEFINED_timer_t +#endif + +#if defined(__NEED_clockid_t) && !defined(__DEFINED_clockid_t) +typedef int clockid_t; +#define __DEFINED_clockid_t +#endif + +#if defined(__NEED_clock_t) && !defined(__DEFINED_clock_t) +typedef long clock_t; +#define __DEFINED_clock_t +#endif + +#if defined(__NEED_struct_timeval) && !defined(__DEFINED_struct_timeval) +struct timeval { time_t tv_sec; suseconds_t tv_usec; }; +#define __DEFINED_struct_timeval +#endif + +#if 0 +#if defined(__NEED_struct_timespec) && !defined(__DEFINED_struct_timespec) +struct timespec { time_t tv_sec; long tv_nsec; }; +#define __DEFINED_struct_timespec +#endif +#endif + +#if defined(__NEED_pid_t) && !defined(__DEFINED_pid_t) +typedef int pid_t; +#define __DEFINED_pid_t +#endif + +#if defined(__NEED_id_t) && !defined(__DEFINED_id_t) +typedef unsigned id_t; +#define __DEFINED_id_t +#endif + +#if defined(__NEED_uid_t) && !defined(__DEFINED_uid_t) +typedef unsigned uid_t; +#define __DEFINED_uid_t +#endif + +#if defined(__NEED_gid_t) && !defined(__DEFINED_gid_t) +typedef unsigned gid_t; +#define __DEFINED_gid_t +#endif + +#if defined(__NEED_key_t) && !defined(__DEFINED_key_t) +typedef int key_t; +#define __DEFINED_key_t +#endif + +#if defined(__NEED_useconds_t) && !defined(__DEFINED_useconds_t) +typedef unsigned useconds_t; +#define __DEFINED_useconds_t +#endif + + +#ifdef __cplusplus +#if defined(__NEED_pthread_t) && !defined(__DEFINED_pthread_t) +typedef unsigned long pthread_t; +#define __DEFINED_pthread_t +#endif + +#else +#if defined(__NEED_pthread_t) && !defined(__DEFINED_pthread_t) +typedef struct __pthread * pthread_t; +#define __DEFINED_pthread_t +#endif + +#endif +#if defined(__NEED_pthread_once_t) && !defined(__DEFINED_pthread_once_t) +typedef int pthread_once_t; +#define __DEFINED_pthread_once_t +#endif + +#if defined(__NEED_pthread_key_t) && !defined(__DEFINED_pthread_key_t) +typedef unsigned pthread_key_t; +#define __DEFINED_pthread_key_t +#endif + +#if defined(__NEED_pthread_spinlock_t) && !defined(__DEFINED_pthread_spinlock_t) +typedef int pthread_spinlock_t; +#define __DEFINED_pthread_spinlock_t +#endif + +#if defined(__NEED_pthread_mutexattr_t) && !defined(__DEFINED_pthread_mutexattr_t) +typedef struct { unsigned __attr; } pthread_mutexattr_t; +#define __DEFINED_pthread_mutexattr_t +#endif + +#if defined(__NEED_pthread_condattr_t) && !defined(__DEFINED_pthread_condattr_t) +typedef struct { unsigned __attr; } pthread_condattr_t; +#define __DEFINED_pthread_condattr_t +#endif + +#if defined(__NEED_pthread_barrierattr_t) && !defined(__DEFINED_pthread_barrierattr_t) +typedef struct { unsigned __attr; } pthread_barrierattr_t; +#define __DEFINED_pthread_barrierattr_t +#endif + +#if defined(__NEED_pthread_rwlockattr_t) && !defined(__DEFINED_pthread_rwlockattr_t) +typedef struct { unsigned __attr[2]; } pthread_rwlockattr_t; +#define __DEFINED_pthread_rwlockattr_t +#endif + + +#if defined(__NEED_FILE) && !defined(__DEFINED_FILE) +typedef struct _IO_FILE FILE; +#define __DEFINED_FILE +#endif + + +#if defined(__NEED_mbstate_t) && !defined(__DEFINED_mbstate_t) +typedef struct __mbstate_t { unsigned __opaque1, __opaque2; } mbstate_t; +#define __DEFINED_mbstate_t +#endif + + +#if defined(__NEED_locale_t) && !defined(__DEFINED_locale_t) +typedef struct __locale_struct * locale_t; +#define __DEFINED_locale_t +#endif + + +#if defined(__NEED_sigset_t) && !defined(__DEFINED_sigset_t) +typedef struct __sigset_t { unsigned long __bits[128/sizeof(long)]; } sigset_t; +#define __DEFINED_sigset_t +#endif + + +#if defined(__NEED_struct_iovec) && !defined(__DEFINED_struct_iovec) +struct iovec { void *iov_base; size_t iov_len; }; +#define __DEFINED_struct_iovec +#endif + + +#if defined(__NEED_socklen_t) && !defined(__DEFINED_socklen_t) +typedef unsigned socklen_t; +#define __DEFINED_socklen_t +#endif + +#if defined(__NEED_sa_family_t) && !defined(__DEFINED_sa_family_t) +typedef unsigned short sa_family_t; +#define __DEFINED_sa_family_t +#endif + + +#undef _Addr +#undef _Int64 +#undef _Reg diff --git a/SampleCode/SampleAttestedTLS/sgx_socket/include/byteswap.h b/SampleCode/SampleAttestedTLS/sgx_socket/include/byteswap.h new file mode 100644 index 000000000..696c40973 --- /dev/null +++ b/SampleCode/SampleAttestedTLS/sgx_socket/include/byteswap.h @@ -0,0 +1,20 @@ +#ifndef _BYTESWAP_H +#define _BYTESWAP_H + +#include +#include + +static __inline uint16_t __bswap_16(uint16_t __x) +{ + return (uint16_t)((__x<<8) | (__x>>8)); +} + +static __inline uint32_t __bswap_32(uint32_t __x) +{ + return (__x>>24) | (__x>>8&0xff00) | (__x<<8&0xff0000) | (__x<<24); +} + +#define bswap_16(x) __bswap_16(x) +#define bswap_32(x) __bswap_32(x) + +#endif diff --git a/SampleCode/SampleAttestedTLS/sgx_socket/include/features.h b/SampleCode/SampleAttestedTLS/sgx_socket/include/features.h new file mode 100644 index 000000000..fa9b97407 --- /dev/null +++ b/SampleCode/SampleAttestedTLS/sgx_socket/include/features.h @@ -0,0 +1,24 @@ +#ifndef _FEATURES_H +#define _FEATURES_H + +#if defined(_ALL_SOURCE) && !defined(_GNU_SOURCE) +#define _GNU_SOURCE 1 +#endif + +#if defined(_DEFAULT_SOURCE) && !defined(_BSD_SOURCE) +#define _BSD_SOURCE 1 +#endif + +#if !defined(_POSIX_SOURCE) && !defined(_POSIX_C_SOURCE) \ + && !defined(_XOPEN_SOURCE) && !defined(_GNU_SOURCE) \ + && !defined(_BSD_SOURCE) && !defined(__STRICT_ANSI__) +#define _BSD_SOURCE 1 +#define _XOPEN_SOURCE 700 +#endif + +#define __restrict +#define __inline inline + +#define __REDIR(x,y) __typeof__(x) x __asm__(#y) + +#endif diff --git a/SampleCode/SampleAttestedTLS/sgx_socket/include/netdb.h b/SampleCode/SampleAttestedTLS/sgx_socket/include/netdb.h new file mode 100644 index 000000000..d096c7818 --- /dev/null +++ b/SampleCode/SampleAttestedTLS/sgx_socket/include/netdb.h @@ -0,0 +1,156 @@ +#ifndef _NETDB_H +#define _NETDB_H + +#ifdef __cplusplus +extern "C" { +#endif + +#include +#include + +#if defined(_GNU_SOURCE) || defined(_BSD_SOURCE) +#define __NEED_size_t +#include +#endif + +struct addrinfo { + int ai_flags; + int ai_family; + int ai_socktype; + int ai_protocol; + socklen_t ai_addrlen; + struct sockaddr *ai_addr; + char *ai_canonname; + struct addrinfo *ai_next; +}; + +#define AI_PASSIVE 0x01 +#define AI_CANONNAME 0x02 +#define AI_NUMERICHOST 0x04 +#define AI_V4MAPPED 0x08 +#define AI_ALL 0x10 +#define AI_ADDRCONFIG 0x20 +#define AI_NUMERICSERV 0x400 + + +#define NI_NUMERICHOST 0x01 +#define NI_NUMERICSERV 0x02 +#define NI_NOFQDN 0x04 +#define NI_NAMEREQD 0x08 +#define NI_DGRAM 0x10 +#define NI_NUMERICSCOPE 0x100 + +#define EAI_BADFLAGS -1 +#define EAI_NONAME -2 +#define EAI_AGAIN -3 +#define EAI_FAIL -4 +#define EAI_FAMILY -6 +#define EAI_SOCKTYPE -7 +#define EAI_SERVICE -8 +#define EAI_MEMORY -10 +#define EAI_SYSTEM -11 +#define EAI_OVERFLOW -12 + +int getaddrinfo (const char *__restrict, const char *__restrict, const struct addrinfo *__restrict, struct addrinfo **__restrict); +void freeaddrinfo (struct addrinfo *); +int getnameinfo (const struct sockaddr *__restrict, socklen_t, char *__restrict, socklen_t, char *__restrict, socklen_t, int); +const char *gai_strerror(int); + + +/* Legacy functions follow (marked OBsolete in SUS) */ + +struct netent { + char *n_name; + char **n_aliases; + int n_addrtype; + uint32_t n_net; +}; + +struct hostent { + char *h_name; + char **h_aliases; + int h_addrtype; + int h_length; + char **h_addr_list; +}; +#define h_addr h_addr_list[0] + +struct servent { + char *s_name; + char **s_aliases; + int s_port; + char *s_proto; +}; + +struct protoent { + char *p_name; + char **p_aliases; + int p_proto; +}; + +void sethostent (int); +void endhostent (void); +struct hostent *gethostent (void); + +void setnetent (int); +void endnetent (void); +struct netent *getnetent (void); +struct netent *getnetbyaddr (uint32_t, int); +struct netent *getnetbyname (const char *); + +void setservent (int); +void endservent (void); +struct servent *getservent (void); +struct servent *getservbyname (const char *, const char *); +struct servent *getservbyport (int, const char *); + +void setprotoent (int); +void endprotoent (void); +struct protoent *getprotoent (void); +struct protoent *getprotobyname (const char *); +struct protoent *getprotobynumber (int); + +#if defined(_GNU_SOURCE) || defined(_BSD_SOURCE) || defined(_POSIX_SOURCE) \ + || (defined(_POSIX_C_SOURCE) && _POSIX_C_SOURCE+0 < 200809L) \ + || (defined(_XOPEN_SOURCE) && _XOPEN_SOURCE+0 < 700) +struct hostent *gethostbyname (const char *); +struct hostent *gethostbyaddr (const void *, socklen_t, int); +#ifdef __GNUC__ +__attribute__((const)) +#endif +int *__h_errno_location(void); +#define h_errno (*__h_errno_location()) +#define HOST_NOT_FOUND 1 +#define TRY_AGAIN 2 +#define NO_RECOVERY 3 +#define NO_DATA 4 +#define NO_ADDRESS NO_DATA +#endif + +#if defined(_GNU_SOURCE) || defined(_BSD_SOURCE) +void herror(const char *); +const char *hstrerror(int); +int gethostbyname_r(const char *, struct hostent *, char *, size_t, struct hostent **, int *); +int gethostbyname2_r(const char *, int, struct hostent *, char *, size_t, struct hostent **, int *); +struct hostent *gethostbyname2(const char *, int); +int gethostbyaddr_r(const void *, socklen_t, int, struct hostent *, char *, size_t, struct hostent **, int *); +int getservbyport_r(int, const char *, struct servent *, char *, size_t, struct servent **); +int getservbyname_r(const char *, const char *, struct servent *, char *, size_t, struct servent **); +#define EAI_NODATA -5 +#define EAI_ADDRFAMILY -9 +#define EAI_INPROGRESS -100 +#define EAI_CANCELED -101 +#define EAI_NOTCANCELED -102 +#define EAI_ALLDONE -103 +#define EAI_INTR -104 +#define EAI_IDN_ENCODE -105 +#define NI_MAXHOST 255 +#define NI_MAXSERV 32 +#endif + + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/SampleCode/SampleAttestedTLS/sgx_socket/include/netinet/in.h b/SampleCode/SampleAttestedTLS/sgx_socket/include/netinet/in.h new file mode 100644 index 000000000..f9594339f --- /dev/null +++ b/SampleCode/SampleAttestedTLS/sgx_socket/include/netinet/in.h @@ -0,0 +1,416 @@ +#ifndef _NETINET_IN_H +#define _NETINET_IN_H + +#ifdef __cplusplus +extern "C" { +#endif + +#include +#include +#include + +typedef uint16_t in_port_t; +typedef uint32_t in_addr_t; +struct in_addr { in_addr_t s_addr; }; + +struct sockaddr_in { + sa_family_t sin_family; + in_port_t sin_port; + struct in_addr sin_addr; + uint8_t sin_zero[8]; +}; + +struct in6_addr { + union { + uint8_t __s6_addr[16]; + uint16_t __s6_addr16[8]; + uint32_t __s6_addr32[4]; + } __in6_union; +}; +#define s6_addr __in6_union.__s6_addr +#define s6_addr16 __in6_union.__s6_addr16 +#define s6_addr32 __in6_union.__s6_addr32 + +struct sockaddr_in6 { + sa_family_t sin6_family; + in_port_t sin6_port; + uint32_t sin6_flowinfo; + struct in6_addr sin6_addr; + uint32_t sin6_scope_id; +}; + +struct ipv6_mreq { + struct in6_addr ipv6mr_multiaddr; + unsigned ipv6mr_interface; +}; + +#define INADDR_ANY ((in_addr_t) 0x00000000) +#define INADDR_BROADCAST ((in_addr_t) 0xffffffff) +#define INADDR_NONE ((in_addr_t) 0xffffffff) +#define INADDR_LOOPBACK ((in_addr_t) 0x7f000001) + +#define INADDR_UNSPEC_GROUP ((in_addr_t) 0xe0000000) +#define INADDR_ALLHOSTS_GROUP ((in_addr_t) 0xe0000001) +#define INADDR_ALLRTRS_GROUP ((in_addr_t) 0xe0000002) +#define INADDR_ALLSNOOPERS_GROUP ((in_addr_t) 0xe000006a) +#define INADDR_MAX_LOCAL_GROUP ((in_addr_t) 0xe00000ff) + +#define IN6ADDR_ANY_INIT { { { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 } } } +#define IN6ADDR_LOOPBACK_INIT { { { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1 } } } + +extern const struct in6_addr in6addr_any, in6addr_loopback; + +#define INET_ADDRSTRLEN 16 +#define INET6_ADDRSTRLEN 46 + +uint32_t htonl(uint32_t); +uint16_t htons(uint16_t); +uint32_t ntohl(uint32_t); +uint16_t ntohs(uint16_t); + +#define IPPORT_RESERVED 1024 + +#define IPPROTO_IP 0 +#define IPPROTO_HOPOPTS 0 +#define IPPROTO_ICMP 1 +#define IPPROTO_IGMP 2 +#define IPPROTO_IPIP 4 +#define IPPROTO_TCP 6 +#define IPPROTO_EGP 8 +#define IPPROTO_PUP 12 +#define IPPROTO_UDP 17 +#define IPPROTO_IDP 22 +#define IPPROTO_TP 29 +#define IPPROTO_DCCP 33 +#define IPPROTO_IPV6 41 +#define IPPROTO_ROUTING 43 +#define IPPROTO_FRAGMENT 44 +#define IPPROTO_RSVP 46 +#define IPPROTO_GRE 47 +#define IPPROTO_ESP 50 +#define IPPROTO_AH 51 +#define IPPROTO_ICMPV6 58 +#define IPPROTO_NONE 59 +#define IPPROTO_DSTOPTS 60 +#define IPPROTO_MTP 92 +#define IPPROTO_BEETPH 94 +#define IPPROTO_ENCAP 98 +#define IPPROTO_PIM 103 +#define IPPROTO_COMP 108 +#define IPPROTO_SCTP 132 +#define IPPROTO_MH 135 +#define IPPROTO_UDPLITE 136 +#define IPPROTO_MPLS 137 +#define IPPROTO_ETHERNET 143 +#define IPPROTO_RAW 255 +#define IPPROTO_MPTCP 262 +#define IPPROTO_MAX 263 + +#define IN6_IS_ADDR_UNSPECIFIED(a) \ + (((uint32_t *) (a))[0] == 0 && ((uint32_t *) (a))[1] == 0 && \ + ((uint32_t *) (a))[2] == 0 && ((uint32_t *) (a))[3] == 0) + +#define IN6_IS_ADDR_LOOPBACK(a) \ + (((uint32_t *) (a))[0] == 0 && ((uint32_t *) (a))[1] == 0 && \ + ((uint32_t *) (a))[2] == 0 && \ + ((uint8_t *) (a))[12] == 0 && ((uint8_t *) (a))[13] == 0 && \ + ((uint8_t *) (a))[14] == 0 && ((uint8_t *) (a))[15] == 1 ) + +#define IN6_IS_ADDR_MULTICAST(a) (((uint8_t *) (a))[0] == 0xff) + +#define IN6_IS_ADDR_LINKLOCAL(a) \ + ((((uint8_t *) (a))[0]) == 0xfe && (((uint8_t *) (a))[1] & 0xc0) == 0x80) + +#define IN6_IS_ADDR_SITELOCAL(a) \ + ((((uint8_t *) (a))[0]) == 0xfe && (((uint8_t *) (a))[1] & 0xc0) == 0xc0) + +#define IN6_IS_ADDR_V4MAPPED(a) \ + (((uint32_t *) (a))[0] == 0 && ((uint32_t *) (a))[1] == 0 && \ + ((uint8_t *) (a))[8] == 0 && ((uint8_t *) (a))[9] == 0 && \ + ((uint8_t *) (a))[10] == 0xff && ((uint8_t *) (a))[11] == 0xff) + +#define IN6_IS_ADDR_V4COMPAT(a) \ + (((uint32_t *) (a))[0] == 0 && ((uint32_t *) (a))[1] == 0 && \ + ((uint32_t *) (a))[2] == 0 && ((uint8_t *) (a))[15] > 1) + +#define IN6_IS_ADDR_MC_NODELOCAL(a) \ + (IN6_IS_ADDR_MULTICAST(a) && ((((uint8_t *) (a))[1] & 0xf) == 0x1)) + +#define IN6_IS_ADDR_MC_LINKLOCAL(a) \ + (IN6_IS_ADDR_MULTICAST(a) && ((((uint8_t *) (a))[1] & 0xf) == 0x2)) + +#define IN6_IS_ADDR_MC_SITELOCAL(a) \ + (IN6_IS_ADDR_MULTICAST(a) && ((((uint8_t *) (a))[1] & 0xf) == 0x5)) + +#define IN6_IS_ADDR_MC_ORGLOCAL(a) \ + (IN6_IS_ADDR_MULTICAST(a) && ((((uint8_t *) (a))[1] & 0xf) == 0x8)) + +#define IN6_IS_ADDR_MC_GLOBAL(a) \ + (IN6_IS_ADDR_MULTICAST(a) && ((((uint8_t *) (a))[1] & 0xf) == 0xe)) + +#define __ARE_4_EQUAL(a,b) \ + (!( (0[a]-0[b]) | (1[a]-1[b]) | (2[a]-2[b]) | (3[a]-3[b]) )) +#define IN6_ARE_ADDR_EQUAL(a,b) \ + __ARE_4_EQUAL((const uint32_t *)(a), (const uint32_t *)(b)) + +#define IN_CLASSA(a) ((((in_addr_t)(a)) & 0x80000000) == 0) +#define IN_CLASSA_NET 0xff000000 +#define IN_CLASSA_NSHIFT 24 +#define IN_CLASSA_HOST (0xffffffff & ~IN_CLASSA_NET) +#define IN_CLASSA_MAX 128 +#define IN_CLASSB(a) ((((in_addr_t)(a)) & 0xc0000000) == 0x80000000) +#define IN_CLASSB_NET 0xffff0000 +#define IN_CLASSB_NSHIFT 16 +#define IN_CLASSB_HOST (0xffffffff & ~IN_CLASSB_NET) +#define IN_CLASSB_MAX 65536 +#define IN_CLASSC(a) ((((in_addr_t)(a)) & 0xe0000000) == 0xc0000000) +#define IN_CLASSC_NET 0xffffff00 +#define IN_CLASSC_NSHIFT 8 +#define IN_CLASSC_HOST (0xffffffff & ~IN_CLASSC_NET) +#define IN_CLASSD(a) ((((in_addr_t)(a)) & 0xf0000000) == 0xe0000000) +#define IN_MULTICAST(a) IN_CLASSD(a) +#define IN_EXPERIMENTAL(a) ((((in_addr_t)(a)) & 0xe0000000) == 0xe0000000) +#define IN_BADCLASS(a) ((((in_addr_t)(a)) & 0xf0000000) == 0xf0000000) + +#define IN_LOOPBACKNET 127 + + +#define IP_TOS 1 +#define IP_TTL 2 +#define IP_HDRINCL 3 +#define IP_OPTIONS 4 +#define IP_ROUTER_ALERT 5 +#define IP_RECVOPTS 6 +#define IP_RETOPTS 7 +#define IP_PKTINFO 8 +#define IP_PKTOPTIONS 9 +#define IP_PMTUDISC 10 +#define IP_MTU_DISCOVER 10 +#define IP_RECVERR 11 +#define IP_RECVTTL 12 +#define IP_RECVTOS 13 +#define IP_MTU 14 +#define IP_FREEBIND 15 +#define IP_IPSEC_POLICY 16 +#define IP_XFRM_POLICY 17 +#define IP_PASSSEC 18 +#define IP_TRANSPARENT 19 +#define IP_ORIGDSTADDR 20 +#define IP_RECVORIGDSTADDR IP_ORIGDSTADDR +#define IP_MINTTL 21 +#define IP_NODEFRAG 22 +#define IP_CHECKSUM 23 +#define IP_BIND_ADDRESS_NO_PORT 24 +#define IP_RECVFRAGSIZE 25 +#define IP_RECVERR_RFC4884 26 +#define IP_MULTICAST_IF 32 +#define IP_MULTICAST_TTL 33 +#define IP_MULTICAST_LOOP 34 +#define IP_ADD_MEMBERSHIP 35 +#define IP_DROP_MEMBERSHIP 36 +#define IP_UNBLOCK_SOURCE 37 +#define IP_BLOCK_SOURCE 38 +#define IP_ADD_SOURCE_MEMBERSHIP 39 +#define IP_DROP_SOURCE_MEMBERSHIP 40 +#define IP_MSFILTER 41 +#define IP_MULTICAST_ALL 49 +#define IP_UNICAST_IF 50 + +#define IP_RECVRETOPTS IP_RETOPTS + +#define IP_PMTUDISC_DONT 0 +#define IP_PMTUDISC_WANT 1 +#define IP_PMTUDISC_DO 2 +#define IP_PMTUDISC_PROBE 3 +#define IP_PMTUDISC_INTERFACE 4 +#define IP_PMTUDISC_OMIT 5 + +#define IP_DEFAULT_MULTICAST_TTL 1 +#define IP_DEFAULT_MULTICAST_LOOP 1 +#define IP_MAX_MEMBERSHIPS 20 + +struct ip_opts { + struct in_addr ip_dst; + char ip_opts[40]; +}; + +#if defined(_GNU_SOURCE) || defined(_BSD_SOURCE) + +#define MCAST_JOIN_GROUP 42 +#define MCAST_BLOCK_SOURCE 43 +#define MCAST_UNBLOCK_SOURCE 44 +#define MCAST_LEAVE_GROUP 45 +#define MCAST_JOIN_SOURCE_GROUP 46 +#define MCAST_LEAVE_SOURCE_GROUP 47 +#define MCAST_MSFILTER 48 + +#define MCAST_EXCLUDE 0 +#define MCAST_INCLUDE 1 + +struct ip_mreq { + struct in_addr imr_multiaddr; + struct in_addr imr_interface; +}; + +struct ip_mreqn { + struct in_addr imr_multiaddr; + struct in_addr imr_address; + int imr_ifindex; +}; + +struct ip_mreq_source { + struct in_addr imr_multiaddr; + struct in_addr imr_interface; + struct in_addr imr_sourceaddr; +}; + +struct ip_msfilter { + struct in_addr imsf_multiaddr; + struct in_addr imsf_interface; + uint32_t imsf_fmode; + uint32_t imsf_numsrc; + struct in_addr imsf_slist[1]; +}; +#define IP_MSFILTER_SIZE(numsrc) \ + (sizeof(struct ip_msfilter) - sizeof(struct in_addr) \ + + (numsrc) * sizeof(struct in_addr)) + +struct group_req { + uint32_t gr_interface; + struct sockaddr_storage gr_group; +}; + +struct group_source_req { + uint32_t gsr_interface; + struct sockaddr_storage gsr_group; + struct sockaddr_storage gsr_source; +}; + +struct group_filter { + uint32_t gf_interface; + struct sockaddr_storage gf_group; + uint32_t gf_fmode; + uint32_t gf_numsrc; + struct sockaddr_storage gf_slist[1]; +}; +#define GROUP_FILTER_SIZE(numsrc) \ + (sizeof(struct group_filter) - sizeof(struct sockaddr_storage) \ + + (numsrc) * sizeof(struct sockaddr_storage)) + +struct in_pktinfo { + int ipi_ifindex; + struct in_addr ipi_spec_dst; + struct in_addr ipi_addr; +}; + +struct in6_pktinfo { + struct in6_addr ipi6_addr; + unsigned ipi6_ifindex; +}; + +struct ip6_mtuinfo { + struct sockaddr_in6 ip6m_addr; + uint32_t ip6m_mtu; +}; +#endif + +#define IPV6_ADDRFORM 1 +#define IPV6_2292PKTINFO 2 +#define IPV6_2292HOPOPTS 3 +#define IPV6_2292DSTOPTS 4 +#define IPV6_2292RTHDR 5 +#define IPV6_2292PKTOPTIONS 6 +#define IPV6_CHECKSUM 7 +#define IPV6_2292HOPLIMIT 8 +#define IPV6_NEXTHOP 9 +#define IPV6_AUTHHDR 10 +#define IPV6_UNICAST_HOPS 16 +#define IPV6_MULTICAST_IF 17 +#define IPV6_MULTICAST_HOPS 18 +#define IPV6_MULTICAST_LOOP 19 +#define IPV6_JOIN_GROUP 20 +#define IPV6_LEAVE_GROUP 21 +#define IPV6_ROUTER_ALERT 22 +#define IPV6_MTU_DISCOVER 23 +#define IPV6_MTU 24 +#define IPV6_RECVERR 25 +#define IPV6_V6ONLY 26 +#define IPV6_JOIN_ANYCAST 27 +#define IPV6_LEAVE_ANYCAST 28 +#define IPV6_MULTICAST_ALL 29 +#define IPV6_ROUTER_ALERT_ISOLATE 30 +#define IPV6_IPSEC_POLICY 34 +#define IPV6_XFRM_POLICY 35 +#define IPV6_HDRINCL 36 + +#define IPV6_RECVPKTINFO 49 +#define IPV6_PKTINFO 50 +#define IPV6_RECVHOPLIMIT 51 +#define IPV6_HOPLIMIT 52 +#define IPV6_RECVHOPOPTS 53 +#define IPV6_HOPOPTS 54 +#define IPV6_RTHDRDSTOPTS 55 +#define IPV6_RECVRTHDR 56 +#define IPV6_RTHDR 57 +#define IPV6_RECVDSTOPTS 58 +#define IPV6_DSTOPTS 59 +#define IPV6_RECVPATHMTU 60 +#define IPV6_PATHMTU 61 +#define IPV6_DONTFRAG 62 +#define IPV6_RECVTCLASS 66 +#define IPV6_TCLASS 67 +#define IPV6_AUTOFLOWLABEL 70 +#define IPV6_ADDR_PREFERENCES 72 +#define IPV6_MINHOPCOUNT 73 +#define IPV6_ORIGDSTADDR 74 +#define IPV6_RECVORIGDSTADDR IPV6_ORIGDSTADDR +#define IPV6_TRANSPARENT 75 +#define IPV6_UNICAST_IF 76 +#define IPV6_RECVFRAGSIZE 77 +#define IPV6_FREEBIND 78 + +#define IPV6_ADD_MEMBERSHIP IPV6_JOIN_GROUP +#define IPV6_DROP_MEMBERSHIP IPV6_LEAVE_GROUP +#define IPV6_RXHOPOPTS IPV6_HOPOPTS +#define IPV6_RXDSTOPTS IPV6_DSTOPTS + +#define IPV6_PMTUDISC_DONT 0 +#define IPV6_PMTUDISC_WANT 1 +#define IPV6_PMTUDISC_DO 2 +#define IPV6_PMTUDISC_PROBE 3 +#define IPV6_PMTUDISC_INTERFACE 4 +#define IPV6_PMTUDISC_OMIT 5 + +#define IPV6_PREFER_SRC_TMP 0x0001 +#define IPV6_PREFER_SRC_PUBLIC 0x0002 +#define IPV6_PREFER_SRC_PUBTMP_DEFAULT 0x0100 +#define IPV6_PREFER_SRC_COA 0x0004 +#define IPV6_PREFER_SRC_HOME 0x0400 +#define IPV6_PREFER_SRC_CGA 0x0008 +#define IPV6_PREFER_SRC_NONCGA 0x0800 + +#define IPV6_RTHDR_LOOSE 0 +#define IPV6_RTHDR_STRICT 1 + +#define IPV6_RTHDR_TYPE_0 0 + +#define __UAPI_DEF_IN_ADDR 0 +#define __UAPI_DEF_IN_IPPROTO 0 +#define __UAPI_DEF_IN_PKTINFO 0 +#define __UAPI_DEF_IP_MREQ 0 +#define __UAPI_DEF_SOCKADDR_IN 0 +#define __UAPI_DEF_IN_CLASS 0 +#define __UAPI_DEF_IN6_ADDR 0 +#define __UAPI_DEF_IN6_ADDR_ALT 0 +#define __UAPI_DEF_SOCKADDR_IN6 0 +#define __UAPI_DEF_IPV6_MREQ 0 +#define __UAPI_DEF_IPPROTO_V6 0 +#define __UAPI_DEF_IPV6_OPTIONS 0 +#define __UAPI_DEF_IN6_PKTINFO 0 +#define __UAPI_DEF_IP6_MTUINFO 0 + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/SampleCode/SampleAttestedTLS/sgx_socket/include/poll.h b/SampleCode/SampleAttestedTLS/sgx_socket/include/poll.h new file mode 100644 index 000000000..a78131a30 --- /dev/null +++ b/SampleCode/SampleAttestedTLS/sgx_socket/include/poll.h @@ -0,0 +1,49 @@ +#ifndef _POLL_H +#define _POLL_H + +#ifdef __cplusplus +extern "C" { +#endif + +#include + +#define POLLIN 0x001 +#define POLLPRI 0x002 +#define POLLOUT 0x004 +#define POLLERR 0x008 +#define POLLHUP 0x010 +#define POLLNVAL 0x020 +#define POLLRDNORM 0x040 +#define POLLRDBAND 0x080 +#ifndef POLLWRNORM +#define POLLWRNORM 0x100 +#define POLLWRBAND 0x200 +#endif +#ifndef POLLMSG +#define POLLMSG 0x400 +#define POLLRDHUP 0x2000 +#endif + +typedef unsigned long nfds_t; + +struct pollfd { + int fd; + short events; + short revents; +}; + +int poll (struct pollfd *, nfds_t, int); + +#ifdef _GNU_SOURCE +#define __NEED_time_t +#define __NEED_struct_timespec +#define __NEED_sigset_t +#include +int ppoll(struct pollfd *, nfds_t, const struct timespec *, const sigset_t *); +#endif + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/SampleCode/SampleAttestedTLS/sgx_socket/include/sgx_socket.edl b/SampleCode/SampleAttestedTLS/sgx_socket/include/sgx_socket.edl new file mode 100644 index 000000000..2525a1942 --- /dev/null +++ b/SampleCode/SampleAttestedTLS/sgx_socket/include/sgx_socket.edl @@ -0,0 +1,51 @@ +/* + * 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. + * + */ + +enclave { + + include "sys/socket.h" + include "sys/select.h" + include "netdb.h" + include "poll.h" + + untrusted { + int u_socket (int domain, int type, int protocol) propagate_errno; + int u_bind (int fd, [in, size=len] const struct sockaddr *addr, socklen_t len) propagate_errno; + int u_listen (int fd, int n) propagate_errno; + int u_accept (int fd, [out, size=addrlen_in] struct sockaddr *addr, socklen_t addrlen_in, [out] socklen_t *addrlen_out) propagate_errno; + int u_connect (int fd, [in, size=len] const struct sockaddr *addr, socklen_t len) propagate_errno; + ssize_t u_send (int fd, [in, size=n] const void *buf, size_t n, int flags) propagate_errno; + + ssize_t u_recv (int fd, [out, size=n] void *buf, size_t n, int flags) propagate_errno; + int u_setsockopt (int fd, int level, int optname, [in, size=optlen] const void *optval, socklen_t optlen) propagate_errno; + int u_close(int fd); + }; +}; diff --git a/SampleCode/SampleAttestedTLS/sgx_socket/include/sys/select.h b/SampleCode/SampleAttestedTLS/sgx_socket/include/sys/select.h new file mode 100644 index 000000000..e7f8ec104 --- /dev/null +++ b/SampleCode/SampleAttestedTLS/sgx_socket/include/sys/select.h @@ -0,0 +1,43 @@ +#ifndef _SYS_SELECT_H +#define _SYS_SELECT_H +#ifdef __cplusplus +extern "C" { +#endif + +#include +#include +#include + +#define __NEED_size_t +#define __NEED_time_t +#define __NEED_suseconds_t +#define __NEED_struct_timeval +#define __NEED_struct_timespec +#define __NEED_sigset_t + +#include + +#define FD_SETSIZE 1024 + +typedef unsigned long fd_mask; + +typedef struct { + unsigned long fds_bits[FD_SETSIZE / 8 / sizeof(long)]; +} fd_set; + +#define FD_ZERO(s) do { int __i; unsigned long *__b=(s)->fds_bits; for(__i=sizeof (fd_set)/sizeof (long); __i; __i--) *__b++=0; } while(0) +#define FD_SET(d, s) ((s)->fds_bits[(d)/(8*sizeof(long))] |= (1UL<<((d)%(8*sizeof(long))))) +#define FD_CLR(d, s) ((s)->fds_bits[(d)/(8*sizeof(long))] &= ~(1UL<<((d)%(8*sizeof(long))))) +#define FD_ISSET(d, s) !!((s)->fds_bits[(d)/(8*sizeof(long))] & (1UL<<((d)%(8*sizeof(long))))) + +int select (int, fd_set *__restrict, fd_set *__restrict, fd_set *__restrict, struct timeval *__restrict); +int pselect (int, fd_set *__restrict, fd_set *__restrict, fd_set *__restrict, const struct timespec *__restrict, const sigset_t *__restrict); + +#if defined(_GNU_SOURCE) || defined(_BSD_SOURCE) +#define NFDBITS (8*(int)sizeof(long)) +#endif + +#ifdef __cplusplus +} +#endif +#endif diff --git a/SampleCode/SampleAttestedTLS/sgx_socket/include/sys/socket.h b/SampleCode/SampleAttestedTLS/sgx_socket/include/sys/socket.h new file mode 100644 index 000000000..62e037c4b --- /dev/null +++ b/SampleCode/SampleAttestedTLS/sgx_socket/include/sys/socket.h @@ -0,0 +1,396 @@ +#ifndef _SYS_SOCKET_H +#define _SYS_SOCKET_H +#ifdef __cplusplus +extern "C" { +#endif + +#include + +#define __NEED_socklen_t +#define __NEED_sa_family_t +#define __NEED_size_t +#define __NEED_ssize_t +#define __NEED_uid_t +#define __NEED_pid_t +#define __NEED_gid_t +#define __NEED_struct_iovec + +#include + +struct msghdr { + void *msg_name; + socklen_t msg_namelen; + struct iovec *msg_iov; + int msg_iovlen; +#if __LONG_MAX > 0x7fffffff + int __pad1; +#endif + void *msg_control; + socklen_t msg_controllen; +#if __LONG_MAX > 0x7fffffff + int __pad2; +#endif + int msg_flags; +}; + +struct cmsghdr { + socklen_t cmsg_len; +#if __LONG_MAX > 0x7fffffff + int __pad1; +#endif + int cmsg_level; + int cmsg_type; +}; + +#ifdef _GNU_SOURCE +struct ucred { + pid_t pid; + uid_t uid; + gid_t gid; +}; + +struct mmsghdr { + struct msghdr msg_hdr; + unsigned int msg_len; +}; + +struct timespec; + +int sendmmsg (int, struct mmsghdr *, unsigned int, unsigned int); +int recvmmsg (int, struct mmsghdr *, unsigned int, unsigned int, struct timespec *); +#endif + +struct linger { + int l_onoff; + int l_linger; +}; + +#define SHUT_RD 0 +#define SHUT_WR 1 +#define SHUT_RDWR 2 + +#ifndef SOCK_STREAM +#define SOCK_STREAM 1 +#define SOCK_DGRAM 2 +#endif + +#define SOCK_RAW 3 +#define SOCK_RDM 4 +#define SOCK_SEQPACKET 5 +#define SOCK_DCCP 6 +#define SOCK_PACKET 10 + +#ifndef SOCK_CLOEXEC +#define SOCK_CLOEXEC 02000000 +#define SOCK_NONBLOCK 04000 +#endif + +#define PF_UNSPEC 0 +#define PF_LOCAL 1 +#define PF_UNIX PF_LOCAL +#define PF_FILE PF_LOCAL +#define PF_INET 2 +#define PF_AX25 3 +#define PF_IPX 4 +#define PF_APPLETALK 5 +#define PF_NETROM 6 +#define PF_BRIDGE 7 +#define PF_ATMPVC 8 +#define PF_X25 9 +#define PF_INET6 10 +#define PF_ROSE 11 +#define PF_DECnet 12 +#define PF_NETBEUI 13 +#define PF_SECURITY 14 +#define PF_KEY 15 +#define PF_NETLINK 16 +#define PF_ROUTE PF_NETLINK +#define PF_PACKET 17 +#define PF_ASH 18 +#define PF_ECONET 19 +#define PF_ATMSVC 20 +#define PF_RDS 21 +#define PF_SNA 22 +#define PF_IRDA 23 +#define PF_PPPOX 24 +#define PF_WANPIPE 25 +#define PF_LLC 26 +#define PF_IB 27 +#define PF_MPLS 28 +#define PF_CAN 29 +#define PF_TIPC 30 +#define PF_BLUETOOTH 31 +#define PF_IUCV 32 +#define PF_RXRPC 33 +#define PF_ISDN 34 +#define PF_PHONET 35 +#define PF_IEEE802154 36 +#define PF_CAIF 37 +#define PF_ALG 38 +#define PF_NFC 39 +#define PF_VSOCK 40 +#define PF_KCM 41 +#define PF_QIPCRTR 42 +#define PF_SMC 43 +#define PF_XDP 44 +#define PF_MAX 45 + +#define AF_UNSPEC PF_UNSPEC +#define AF_LOCAL PF_LOCAL +#define AF_UNIX AF_LOCAL +#define AF_FILE AF_LOCAL +#define AF_INET PF_INET +#define AF_AX25 PF_AX25 +#define AF_IPX PF_IPX +#define AF_APPLETALK PF_APPLETALK +#define AF_NETROM PF_NETROM +#define AF_BRIDGE PF_BRIDGE +#define AF_ATMPVC PF_ATMPVC +#define AF_X25 PF_X25 +#define AF_INET6 PF_INET6 +#define AF_ROSE PF_ROSE +#define AF_DECnet PF_DECnet +#define AF_NETBEUI PF_NETBEUI +#define AF_SECURITY PF_SECURITY +#define AF_KEY PF_KEY +#define AF_NETLINK PF_NETLINK +#define AF_ROUTE PF_ROUTE +#define AF_PACKET PF_PACKET +#define AF_ASH PF_ASH +#define AF_ECONET PF_ECONET +#define AF_ATMSVC PF_ATMSVC +#define AF_RDS PF_RDS +#define AF_SNA PF_SNA +#define AF_IRDA PF_IRDA +#define AF_PPPOX PF_PPPOX +#define AF_WANPIPE PF_WANPIPE +#define AF_LLC PF_LLC +#define AF_IB PF_IB +#define AF_MPLS PF_MPLS +#define AF_CAN PF_CAN +#define AF_TIPC PF_TIPC +#define AF_BLUETOOTH PF_BLUETOOTH +#define AF_IUCV PF_IUCV +#define AF_RXRPC PF_RXRPC +#define AF_ISDN PF_ISDN +#define AF_PHONET PF_PHONET +#define AF_IEEE802154 PF_IEEE802154 +#define AF_CAIF PF_CAIF +#define AF_ALG PF_ALG +#define AF_NFC PF_NFC +#define AF_VSOCK PF_VSOCK +#define AF_KCM PF_KCM +#define AF_QIPCRTR PF_QIPCRTR +#define AF_SMC PF_SMC +#define AF_XDP PF_XDP +#define AF_MAX PF_MAX + +#ifndef SO_DEBUG +#define SO_DEBUG 1 +#define SO_REUSEADDR 2 +#define SO_TYPE 3 +#define SO_ERROR 4 +#define SO_DONTROUTE 5 +#define SO_BROADCAST 6 +#define SO_SNDBUF 7 +#define SO_RCVBUF 8 +#define SO_KEEPALIVE 9 +#define SO_OOBINLINE 10 +#define SO_NO_CHECK 11 +#define SO_PRIORITY 12 +#define SO_LINGER 13 +#define SO_BSDCOMPAT 14 +#define SO_REUSEPORT 15 +#define SO_PASSCRED 16 +#define SO_PEERCRED 17 +#define SO_RCVLOWAT 18 +#define SO_SNDLOWAT 19 +#define SO_ACCEPTCONN 30 +#define SO_PEERSEC 31 +#define SO_SNDBUFFORCE 32 +#define SO_RCVBUFFORCE 33 +#define SO_PROTOCOL 38 +#define SO_DOMAIN 39 +#endif + +#ifndef SO_RCVTIMEO +#if __LONG_MAX == 0x7fffffff +#define SO_RCVTIMEO 66 +#define SO_SNDTIMEO 67 +#else +#define SO_RCVTIMEO 20 +#define SO_SNDTIMEO 21 +#endif +#endif + +#ifndef SO_TIMESTAMP +#if __LONG_MAX == 0x7fffffff +#define SO_TIMESTAMP 63 +#define SO_TIMESTAMPNS 64 +#define SO_TIMESTAMPING 65 +#else +#define SO_TIMESTAMP 29 +#define SO_TIMESTAMPNS 35 +#define SO_TIMESTAMPING 37 +#endif +#endif + +#define SO_SECURITY_AUTHENTICATION 22 +#define SO_SECURITY_ENCRYPTION_TRANSPORT 23 +#define SO_SECURITY_ENCRYPTION_NETWORK 24 + +#define SO_BINDTODEVICE 25 + +#define SO_ATTACH_FILTER 26 +#define SO_DETACH_FILTER 27 +#define SO_GET_FILTER SO_ATTACH_FILTER + +#define SO_PEERNAME 28 +#define SCM_TIMESTAMP SO_TIMESTAMP +#define SO_PASSSEC 34 +#define SCM_TIMESTAMPNS SO_TIMESTAMPNS +#define SO_MARK 36 +#define SCM_TIMESTAMPING SO_TIMESTAMPING +#define SO_RXQ_OVFL 40 +#define SO_WIFI_STATUS 41 +#define SCM_WIFI_STATUS SO_WIFI_STATUS +#define SO_PEEK_OFF 42 +#define SO_NOFCS 43 +#define SO_LOCK_FILTER 44 +#define SO_SELECT_ERR_QUEUE 45 +#define SO_BUSY_POLL 46 +#define SO_MAX_PACING_RATE 47 +#define SO_BPF_EXTENSIONS 48 +#define SO_INCOMING_CPU 49 +#define SO_ATTACH_BPF 50 +#define SO_DETACH_BPF SO_DETACH_FILTER +#define SO_ATTACH_REUSEPORT_CBPF 51 +#define SO_ATTACH_REUSEPORT_EBPF 52 +#define SO_CNX_ADVICE 53 +#define SCM_TIMESTAMPING_OPT_STATS 54 +#define SO_MEMINFO 55 +#define SO_INCOMING_NAPI_ID 56 +#define SO_COOKIE 57 +#define SCM_TIMESTAMPING_PKTINFO 58 +#define SO_PEERGROUPS 59 +#define SO_ZEROCOPY 60 +#define SO_TXTIME 61 +#define SCM_TXTIME SO_TXTIME +#define SO_BINDTOIFINDEX 62 +#define SO_DETACH_REUSEPORT_BPF 68 + +#ifndef SOL_SOCKET +#define SOL_SOCKET 1 +#endif + +#define SOL_IP 0 +#define SOL_IPV6 41 +#define SOL_ICMPV6 58 + +#define SOL_RAW 255 +#define SOL_DECNET 261 +#define SOL_X25 262 +#define SOL_PACKET 263 +#define SOL_ATM 264 +#define SOL_AAL 265 +#define SOL_IRDA 266 +#define SOL_NETBEUI 267 +#define SOL_LLC 268 +#define SOL_DCCP 269 +#define SOL_NETLINK 270 +#define SOL_TIPC 271 +#define SOL_RXRPC 272 +#define SOL_PPPOL2TP 273 +#define SOL_BLUETOOTH 274 +#define SOL_PNPIPE 275 +#define SOL_RDS 276 +#define SOL_IUCV 277 +#define SOL_CAIF 278 +#define SOL_ALG 279 +#define SOL_NFC 280 +#define SOL_KCM 281 +#define SOL_TLS 282 +#define SOL_XDP 283 + +#define SOMAXCONN 128 + +#define MSG_OOB 0x0001 +#define MSG_PEEK 0x0002 +#define MSG_DONTROUTE 0x0004 +#define MSG_CTRUNC 0x0008 +#define MSG_PROXY 0x0010 +#define MSG_TRUNC 0x0020 +#define MSG_DONTWAIT 0x0040 +#define MSG_EOR 0x0080 +#define MSG_WAITALL 0x0100 +#define MSG_FIN 0x0200 +#define MSG_SYN 0x0400 +#define MSG_CONFIRM 0x0800 +#define MSG_RST 0x1000 +#define MSG_ERRQUEUE 0x2000 +#define MSG_NOSIGNAL 0x4000 +#define MSG_MORE 0x8000 +#define MSG_WAITFORONE 0x10000 +#define MSG_BATCH 0x40000 +#define MSG_ZEROCOPY 0x4000000 +#define MSG_FASTOPEN 0x20000000 +#define MSG_CMSG_CLOEXEC 0x40000000 + +#define __CMSG_LEN(cmsg) (((cmsg)->cmsg_len + sizeof(long) - 1) & ~(long)(sizeof(long) - 1)) +#define __CMSG_NEXT(cmsg) ((unsigned char *)(cmsg) + __CMSG_LEN(cmsg)) +#define __MHDR_END(mhdr) ((unsigned char *)(mhdr)->msg_control + (mhdr)->msg_controllen) + +#define CMSG_DATA(cmsg) ((unsigned char *) (((struct cmsghdr *)(cmsg)) + 1)) +#define CMSG_NXTHDR(mhdr, cmsg) ((cmsg)->cmsg_len < sizeof (struct cmsghdr) || \ + __CMSG_LEN(cmsg) + sizeof(struct cmsghdr) >= __MHDR_END(mhdr) - (unsigned char *)(cmsg) \ + ? 0 : (struct cmsghdr *)__CMSG_NEXT(cmsg)) +#define CMSG_FIRSTHDR(mhdr) ((size_t) (mhdr)->msg_controllen >= sizeof (struct cmsghdr) ? (struct cmsghdr *) (mhdr)->msg_control : (struct cmsghdr *) 0) + +#define CMSG_ALIGN(len) (((len) + sizeof (size_t) - 1) & (size_t) ~(sizeof (size_t) - 1)) +#define CMSG_SPACE(len) (CMSG_ALIGN (len) + CMSG_ALIGN (sizeof (struct cmsghdr))) +#define CMSG_LEN(len) (CMSG_ALIGN (sizeof (struct cmsghdr)) + (len)) + +#define SCM_RIGHTS 0x01 +#define SCM_CREDENTIALS 0x02 + +struct sockaddr { + sa_family_t sa_family; + char sa_data[14]; +}; + +struct sockaddr_storage { + sa_family_t ss_family; + char __ss_padding[128-sizeof(long)-sizeof(sa_family_t)]; + unsigned long __ss_align; +}; + +int socket (int, int, int); +int socketpair (int, int, int, int [2]); + +int shutdown (int, int); + +int bind (int, const struct sockaddr *, socklen_t); +int connect (int, const struct sockaddr *, socklen_t); +int listen (int, int); +int accept (int, struct sockaddr *__restrict, socklen_t *__restrict); +int accept4(int, struct sockaddr *__restrict, socklen_t *__restrict, int); + +int getsockname (int, struct sockaddr *__restrict, socklen_t *__restrict); +int getpeername (int, struct sockaddr *__restrict, socklen_t *__restrict); + +ssize_t send (int, const void *, size_t, int); +ssize_t recv (int, void *, size_t, int); +ssize_t sendto (int, const void *, size_t, int, const struct sockaddr *, socklen_t); +ssize_t recvfrom (int, void *__restrict, size_t, int, struct sockaddr *__restrict, socklen_t *__restrict); +ssize_t sendmsg (int, const struct msghdr *, int); +ssize_t recvmsg (int, struct msghdr *, int); + +int getsockopt (int, int, int, void *__restrict, socklen_t *__restrict); +int setsockopt (int, int, int, const void *, socklen_t); + +int sockatmark (int); + +#ifdef __cplusplus +} +#endif +#endif diff --git a/SampleCode/SampleAttestedTLS/sgx_socket/trusted_sgx_socket.cpp b/SampleCode/SampleAttestedTLS/sgx_socket/trusted_sgx_socket.cpp new file mode 100644 index 000000000..71178c05c --- /dev/null +++ b/SampleCode/SampleAttestedTLS/sgx_socket/trusted_sgx_socket.cpp @@ -0,0 +1,162 @@ +/* + * 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. + * + */ + + +#ifdef M_TLS_SERVER +#include "tls_server_t.h" +#else +#include "tls_client_t.h" +#endif + + + +#include "sgx_trts.h" + +/* support socket APIs inside enclave */ + +/* for socket APIs, refer to https://en.wikipedia.org/wiki/Berkeley_sockets */ + +int socket(int domain, int type, int protocol) +{ + int ret = -1; + + if (u_socket(&ret, domain, type, protocol) == SGX_SUCCESS) + return ret; + + return -1; +} + +int connect (int sockfd, const struct sockaddr *servaddr, socklen_t addrlen) +{ + int ret = -1; + + if (u_connect(&ret, sockfd, servaddr, addrlen) == SGX_SUCCESS) + return ret; + + return -1; +} + +int bind(int sockfd, const struct sockaddr* servaddr, socklen_t addrlen) +{ + int ret = -1; + + if (u_bind(&ret, sockfd, servaddr, addrlen) == SGX_SUCCESS) + return ret; + + return -1; +} + +int listen(int sockfd, int backlog) +{ + int ret = -1; + + if (u_listen(&ret, sockfd, backlog) == SGX_SUCCESS) + return ret; + + return -1; +} + + +int accept(int sockfd, struct sockaddr* addr, socklen_t *addrlen) +{ + int ret = -1; + socklen_t addrlen_in = 0; + + if ((addr && !addrlen) || (addrlen && !addr)) + { + return -1; + } + + if (addr && addrlen) + { + addrlen_in = *addrlen; + } + + if (u_accept(&ret, sockfd, addr, addrlen_in, addrlen) == SGX_SUCCESS) + return ret; + + return -1; +} + +ssize_t send(int sockfd, const void *buf, size_t nbytes, int flags) +{ + ssize_t ret = 0; + + if (u_send(&ret, sockfd, buf, nbytes, flags) == SGX_SUCCESS) + return ret; + + return -1; +} + +ssize_t recv(int fd, void *buf, size_t len, int flags) +{ + ssize_t ret = 0; + + if (u_recv(&ret, fd, buf, len, flags) == SGX_SUCCESS) + return ret; + + return -1; +} + +int setsockopt( + int fd, + int level, + int optname, + const void *optval, + socklen_t optlen + ) +{ + int ret = -1; + + //errno = 0; + + if (!optval || !optlen) + { + // errno = EINVAL; + return -1; + } + + if (u_setsockopt(&ret, fd, level, optname, optval, optlen) != SGX_SUCCESS) { + // errno = EINVAL; + return -1; + } + + return ret; +} + +int close(int sockfd) +{ + int ret = -1; + if (u_close(&ret, sockfd) == SGX_SUCCESS) + return ret; + + return -1; +} diff --git a/SampleCode/SampleAttestedTLS/sgx_socket/untrusted_sgx_socket.cpp b/SampleCode/SampleAttestedTLS/sgx_socket/untrusted_sgx_socket.cpp new file mode 100644 index 000000000..ecbdf715f --- /dev/null +++ b/SampleCode/SampleAttestedTLS/sgx_socket/untrusted_sgx_socket.cpp @@ -0,0 +1,104 @@ +/* + * 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 +#ifdef M_TLS_SERVER +#include "../server/host/tls_server_u.h" +#else +#include "../client/host/tls_client_u.h" +#endif + +/* ocalls to use socket APIs , call socket syscalls */ + +int u_socket(int domain, int type, int protocol) +{ + return socket(domain, type, protocol); +} + +int u_connect(int sockfd, const struct sockaddr *servaddr, socklen_t addrlen) +{ + return connect(sockfd, servaddr, addrlen); +} + +int u_bind(int fd, const struct sockaddr *addr, socklen_t len) +{ + return bind(fd, addr, len); +} + +int u_listen(int fd, int n) +{ + return listen(fd, n); +} + +int u_accept( + int fd, + struct sockaddr *addr, + socklen_t addrlen_in, + socklen_t *addrlen_out + ) +{ + int ret = -1; + + if ((ret = accept(fd, addr, &addrlen_in)) != -1) + { + if (addrlen_out) + *addrlen_out = addrlen_in; + } + return ret; +} + +ssize_t u_send(int sockfd, const void *buf, size_t nbytes, int flags) +{ + return send(sockfd, buf, nbytes, flags); +} + +ssize_t u_recv(int sockfd, void *buf, size_t nbytes, int flags) +{ + return recv(sockfd, buf, nbytes, flags); +} + +int u_setsockopt( + int sockfd, + int level, + int optname, + const void *optval, + socklen_t optlen + ) +{ + return setsockopt(sockfd, level, optname, optval, optlen); +} + +int u_close(int fd) +{ + return close(fd); +} diff --git a/SampleCode/SampleAttestedTLS/sgxenv.mk b/SampleCode/SampleAttestedTLS/sgxenv.mk new file mode 100644 index 000000000..82ffe6788 --- /dev/null +++ b/SampleCode/SampleAttestedTLS/sgxenv.mk @@ -0,0 +1,149 @@ +# +# 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. +# +# + +######## SGX SDK Settings ######## + +SGX_SDK ?= /opt/intel/sgxsdk +SGX_MODE := HW +SGX_ARCH ?= x64 +SGX_DEBUG ?= 1 + + +mkfile_path := $(abspath $(lastword $(MAKEFILE_LIST))) +PROJ_DIR := $(dir $(mkfile_path)) +SGXSSL_DIR ?= $(PROJ_DIR)sgxssl +SGXSSL_PKG_PATH := $(SGXSSL_DIR)/Linux/package +SOCKET_DIR ?= $(PROJ_DIR)sgx_socket + +#$(info "*******DEBUG MESSAGE: SGXSSL PATH SET TO***********") +#$(info "SGXSSL_DIR set to:$(SGXSSL_DIR)") + +ifeq ($(shell getconf LONG_BIT), 32) + SGX_ARCH := x86 +else ifeq ($(findstring -m32, $(CXXFLAGS)), -m32) + SGX_ARCH := x86 +endif + +SGX_COMMON_CFLAGS := -m64 +SGX_LIBRARY_PATH := $(SGX_SDK)/lib64 +SGX_ENCLAVE_SIGNER := $(SGX_SDK)/bin/x64/sgx_sign +SGX_EDGER8R := $(SGX_SDK)/bin/x64/sgx_edger8r + +ifeq ($(SGX_DEBUG), 1) + SGX_COMMON_CFLAGS += -O0 -g +else + SGX_COMMON_CFLAGS += -O2 +endif + +######## App Settings ######## + +Urts_Library_Name := sgx_urts +U_TLS_Library_Name := sgx_utls + +App_Include_Paths := -IInclude -I$(SGX_SDK)/include +App_C_Flags := $(SGX_COMMON_CFLAGS) -fPIC -Wno-attributes $(App_Include_Paths) + +# Three configuration modes - Debug, prerelease, release +# Debug - Macro DEBUG enabled. +# Prerelease - Macro NDEBUG and EDEBUG enabled. +# Release - Macro NDEBUG enabled. +ifeq ($(SGX_DEBUG), 1) + App_C_Flags += -DDEBUG -UNDEBUG -UEDEBUG +else + App_C_Flags += -DNDEBUG -DEDEBUG -UDEBUG +endif + +SGXSSL_U_Library_Name := sgx_usgxssl + +SGXSSL_U_Link_Libraries := -L$(SGXSSL_PKG_PATH)/lib64 -Wl,--whole-archive -l$(SGXSSL_U_Library_Name) -Wl,--no-whole-archive +SGXTLS_U_Link_Libraries := -lsgx_utls + +App_Cpp_Flags := $(App_C_Flags) -std=c++11 +App_Link_Flags := $(SGX_COMMON_CFLAGS) $(SGXSSL_U_Link_Libraries) -L$(SGX_LIBRARY_PATH) -l$(Urts_Library_Name) $(SGXTLS_U_Link_Libraries) -lsgx_dcap_ql -lsgx_dcap_quoteverify -lcrypto -lpthread + +######## Enclave Settings ######## + +Trts_Library_Name := sgx_trts +Service_Library_Name := sgx_tservice + +SGXSSL_Library_Name := sgx_tsgxssl +OpenSSL_SSL_Library_Name := sgx_tsgxssl_ssl +OpenSSL_Crypto_Library_Name := sgx_tsgxssl_crypto + +SGX_TLS_Library_Name := sgx_ttls +SGX_TVL_Library_Name := sgx_dcap_tvl + +Common_Enclave_Cpp_Files := $(wildcard common/*.cpp) +Enclave_Include_Paths := -IInclude -IEnclave -I$(SGX_SDK)/include -I$(SGX_SDK)/include/tlibc -I$(SGX_SDK)/include/libcxx +Enclave_Include_Paths += -I$(SGXSSL_PKG_PATH)/include +Enclave_Include_Paths += -I$(SOCKET_DIR)/include + +CC_BELOW_4_9 := $(shell expr "`$(CC) -dumpversion`" \< "4.9") +ifeq ($(CC_BELOW_4_9), 1) + Enclave_C_Flags := $(SGX_COMMON_CFLAGS) -nostdinc -fvisibility=hidden -fpie -ffunction-sections -fdata-sections -fstack-protector +else + Enclave_C_Flags := $(SGX_COMMON_CFLAGS) -nostdinc -fvisibility=hidden -fpie -ffunction-sections -fdata-sections -fstack-protector-strong +endif + +Enclave_C_Flags += $(Enclave_Include_Paths) +Enclave_Cpp_Flags := $(Enclave_C_Flags) -std=c++11 -nostdinc++ + +SgxSSL_Link_Libraries := -L$(SGXSSL_PKG_PATH)/lib64 -Wl,--whole-archive -l$(SGXSSL_Library_Name) -Wl,--no-whole-archive \ + -l$(OpenSSL_SSL_Library_Name) -l$(OpenSSL_Crypto_Library_Name) + +Security_Link_Flags := -Wl,-z,noexecstack -Wl,-z,relro -Wl,-z,now -pie + + +# To generate a proper enclave, it is recommended to follow below guideline to link the trusted libraries: +# 1. Link sgx_trts with the `--whole-archive' and `--no-whole-archive' options, +# so that the whole content of trts is included in the enclave. +# 2. For other libraries, you just need to pull the required symbols. +# Use `--start-group' and `--end-group' to link these libraries. +# Do NOT move the libraries linked with `--start-group' and `--end-group' within `--whole-archive' and `--no-whole-archive' options. +# Otherwise, you may get some undesirable errors. +Enclave_Link_Flags := $(SGX_COMMON_CFLAGS) -Wl,--no-undefined -nostdlib -nodefaultlibs -nostartfiles \ + $(Security_Link_Flags) \ + $(SgxSSL_Link_Libraries) \ + -L$(SGX_LIBRARY_PATH) \ + -Wl,--whole-archive -l$(Trts_Library_Name) -Wl,--no-whole-archive \ + -L$(SGX_LIBRARY_PATH) \ + -Wl,--start-group -lsgx_tstdc -lsgx_pthread -lsgx_tcxx -lsgx_tcrypto -l$(Service_Library_Name) \ + -l$(SGX_TVL_Library_Name) -lsgx_ttls -Wl,--end-group \ + -Wl,-Bstatic -Wl,-Bsymbolic -Wl,--no-undefined \ + -Wl,-pie,-eenclave_entry -Wl,--export-dynamic \ + -Wl,--defsym,__ImageBase=0 -Wl,--gc-sections \ + -Wl,--version-script=$(shell pwd)/enclave.lds + +ifeq ($(SGX_DEBUG), 1) + Build_Mode = HW_DEBUG +else + Build_Mode = HW_PRERELEASE +endif diff --git a/SampleCode/SampleEnclaveGMIPP/Enclave/Enclave.cpp b/SampleCode/SampleEnclaveGMIPP/Enclave/Enclave.cpp index bba603d7b..52fd16b40 100644 --- a/SampleCode/SampleEnclaveGMIPP/Enclave/Enclave.cpp +++ b/SampleCode/SampleEnclaveGMIPP/Enclave/Enclave.cpp @@ -34,6 +34,7 @@ #include #include /* vsnprintf */ #include +#include "sgx_trts.h" #include /* ipp library */ @@ -41,6 +42,9 @@ #define SAFE_FREE(ptr, size) do {if (NULL != (ptr)) {memset_s(ptr, size, 0, size); free(ptr); (ptr)=NULL;}} 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. @@ -157,196 +161,607 @@ static IppsBigNumState* new_BN(int len, const unsigned int* pData) return pBN; } +/* Convert bit size into 32-bit word size */ +static int Bitsize2Wordsize(int nBits) +{ + return (nBits+31)>>5; +} + +/* Set up an array of 32-bit items with random number */ +static int rand(void) +{ + int num = 0; + sgx_read_rand((unsigned char*)&num, sizeof(int)); + return num; +} +static unsigned int* rand32(unsigned int* pX, int size) +{ + for(int n = 0; n < size; n++) + pX[n] = rand(); + return pX; +} + /* Define Pseudo-random generation context */ static IppsPRNGState* new_PRNG(void) { - int ctxSize = 0; + int size = 0; IppsPRNGState* pPRNG = NULL; - IppStatus status = ippStsNoErr; - - status = ippsPRNGGetSize(&ctxSize); - if (status != ippStsNoErr) { + 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(ctxSize)); + pPRNG = (IppsPRNGState*)malloc(size); if (pPRNG == NULL) { printf("Error: fail to allocate memory for PRNG\n"); return NULL; } - status = ippsPRNGInit(256, pPRNG); - if (status != ippStsNoErr) { + ipp_ret = ippsPRNGInit(seedBitsize, pPRNG); + if (ipp_ret != ippStsNoErr) { printf("Error: fail to initialize PRNG\n"); - SAFE_FREE(pPRNG, ctxSize); + SAFE_FREE(pPRNG, size); + return NULL; + } + + seed = (unsigned int*)malloc(seedSize); + augm = (unsigned int*)malloc(seedSize); + ipp_ret = ippsPRNGSetSeed(pBN=new_BN(seedSize, rand32(seed, seedSize)), pPRNG); + if (ipp_ret != ippStsNoErr) { + printf("Error: fail to set the seed value of PRNG\n"); + SAFE_FREE(pPRNG, size); + SAFE_FREE(pBN, sizeof(pBN)); + SAFE_FREE(pBN, sizeof(augm)); + SAFE_FREE(pBN, sizeof(seed)); + return NULL; + } + SAFE_FREE(pBN, sizeof(pBN)); + ipp_ret = ippsPRNGSetAugment(pBN=new_BN(seedSize, rand32(augm, seedSize)), pPRNG); + if (ipp_ret != ippStsNoErr) { + printf("Error: fail to set the entropy augmentation of PRNG\n"); + SAFE_FREE(pPRNG, size); + SAFE_FREE(pBN, sizeof(pBN)); + SAFE_FREE(pBN, sizeof(augm)); + SAFE_FREE(pBN, sizeof(seed)); return NULL; } return pPRNG; } -/* Signing and verification using ECC context for SM2 */ -int ecall_sm2(void) +/* 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) { - IppsECCPState *pECCPS = NULL; - IppsBigNumState *pBNS = NULL; - IppsPRNGState *pPRNGS = NULL; - IppsBigNumState *pRandMsg = NULL; - IppsBigNumState *pMsg = NULL; - IppsBigNumState *regPrivateKey = NULL, *ephPrivateKey = NULL; - IppsECCPPointState *regPublicKey = NULL, *ephPublicKey = NULL; - IppsBigNumState *signX = NULL, *signY = NULL; - - IppStatus status = ippStsNoErr; - IppECResult eccResult = ippECValid; + int ctx_size = 0; + IppsHashState_rmf* hash_handle = NULL; + IppStatus ipp_ret = ippStsNoErr; int ret = 0; - const unsigned int order[] = {0x39D54123, 0x53BBF409, 0x21C6052B, 0x7203DF6B, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFE}; - const int ordSize = sizeof(order) / sizeof(unsigned int); - unsigned int tmpData[ordSize]; + 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 { - // 1. Create ECC context for SM2 - pECCPS = new_ECC_sm2(); - if (pECCPS == NULL) { - printf("Error: fail to create ecc context for sm2\n"); + ipp_ret = ippsGetOctString_BN(xA, 32, pubX); + if (ipp_ret != ippStsNoErr) { + printf("Error: fail to Convert BN value pubX into octet string xA\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(hash_handle, sizeof(hash_handle)); + + 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; + } - // 2. Get order of ECC context for SM2 - pBNS = new_BN(ordSize, order); - if (pBNS == NULL) { - printf("Error: fail to get order of ecc context for sm2\n"); + ipp_ret = ippsHashGetSize_rmf(&ctx_size); + if (ipp_ret != ippStsNoErr) + { + printf("Error: fail to get size of IppsHashState_rmf\n"); ret = -2; break; } - // 3. Create a random message to be signed - pPRNGS = new_PRNG(); - if (pPRNGS == NULL) { - printf("Error: fail to create pseudo-random generation context\n"); + hash_handle = (IppsHashState_rmf*)(malloc(ctx_size)); + if (!hash_handle) + { + printf("Error: fail to allocate memory for IppsHashState_rmf\n"); ret = -3; break; } - status = ippsPRNGen(tmpData, 256, pPRNGS); - if (status != ippStsNoErr) { - printf("Error: fail to generate a pseudorandom bit sequence\n"); + + // 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"); ret = -4; break; } - pRandMsg = new_BN(ordSize, tmpData); - if (pRandMsg == NULL) { - printf("Error: fail to create a random message\n"); + + // 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; } - pMsg = new_BN(ordSize, 0); - if (pMsg == NULL) { - printf("Error: fail to create a message to be signed\n"); + 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; } - status = ippsMod_BN(pRandMsg, pBNS, pMsg); - if (status != ippStsNoErr) { - printf("Error: fail to compute modular reduction for input big number\n"); + 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); - // 4. Create regular and ephemeral private key and public key - regPrivateKey = new_BN(ordSize, 0); - if (regPrivateKey == NULL) { - printf("Error: fail to create regular private key\n"); - ret = -8; + SAFE_FREE(hash_handle, sizeof(hash_handle)); + + 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) +{ + IppsECCPState *pECCPS = NULL; + IppsPRNGState *pPRNGS = NULL; + IppsBigNumState *ephPrivateKey = NULL; + IppsECCPPointState *regPublicKey = NULL, *ephPublicKey = NULL; + IppsBigNumState *pMsg = NULL; + IppsBigNumState *pX = NULL, *pY = 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"); + 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 = -9; + 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 = -10; + ret = -4; break; - } - ephPublicKey = new_ECC_Point(); - if (ephPublicKey == NULL) { - printf("Error: fail to create ephemeral public key\n"); - ret = -11; + } + ipp_ret = ippsECCPPublicKey(regPrivateKey, regPublicKey, pECCPS); + if (ipp_ret != ippStsNoErr) { + printf("Error: fail to calculate regular public key\n"); + ret = -5; break; } - // 5. Generate regular and ephemeral key pairs - status = ippsECCPGenKeyPair(regPrivateKey, regPublicKey, pECCPS, ippsPRNGen, pPRNGS); - if (status != ippStsNoErr) { - printf("Error: fail to generate regular key pairs\n"); - ret = -12; + // 3. Generate ephemeral key pairs + pPRNGS = new_PRNG(); + if (pPRNGS == NULL) { + printf("Error: fail to create pPRNGS\n"); + ret = -6; break; } - status = ippsECCPGenKeyPair(ephPrivateKey, ephPublicKey, pECCPS, ippsPRNGen, pPRNGS); - if (status != ippStsNoErr) { + + 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); + 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; break; } // 6. Sign using ECC context for SM2 - status = ippsECCPSetKeyPair(ephPrivateKey, ephPublicKey, ippFalse, pECCPS); - if (status != ippStsNoErr) { + 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); + if (ipp_ret != ippStsNoErr) { + printf("Error: fail to compute signature\n"); + ret = -15; + break; + } + } while(0); + + // 7. Final, remove secret and release resources + SAFE_FREE(pY, sizeof(pY)); + SAFE_FREE(pX, sizeof(pX)); + SAFE_FREE(pMsg, sizeof(pMsg)); + SAFE_FREE(regPublicKey, sizeof(regPublicKey)); + SAFE_FREE(ephPublicKey, sizeof(ephPublicKey)); + SAFE_FREE(ephPrivateKey, sizeof(ephPrivateKey)); + SAFE_FREE(pPRNGS, sizeof(pPRNGS)); + SAFE_FREE(pECCPS, sizeof(pECCPS)); + + 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) +{ + IppsECCPState *pECCPS = NULL; + IppsBigNumState* pMsg = NULL; + IppsBigNumState *pX = NULL, *pY = 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"); + ret = -1; + break; + } + + // 2. Create pX and pY + pX = new_BN(ordSize, 0); + if (pX == NULL){ + printf("Error: fail to create pX\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 resources + SAFE_FREE(pY, sizeof(pY)); + SAFE_FREE(pX, sizeof(pX)); + SAFE_FREE(pMsg, sizeof(pMsg)); + SAFE_FREE(pECCPS, sizeof(pECCPS)); + + return ret; +} + +/* Signing and verification using ECC context for SM2 */ +int ecall_sm2(void) +{ + IppsECCPState *pECCPS = NULL; + IppsBigNumState *regPrivateKey = NULL; + IppsECCPPointState *regPublicKey = NULL; + IppsBigNumState *signX = NULL, *signY = NULL; + IppStatus ipp_ret = ippStsNoErr; + int ret = 0; + + char *message = "context need to be signed"; + char *user_id = "1234567812345678"; + unsigned char priKey[] = "\xd0\x91\x56\x73\x30\x17\xbd\xad\x80\x9f\xd9\xbb\xd8\xc6\x93\xf6\x02\x30\x59\x31\x69\xb6\xf9\x4a\xaf\x1c\x8e\xe1\x38\xcc\x99\xb5"; + + 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. Create regular private key and public key + regPrivateKey = new_BN(ordSize, 0); + if (regPrivateKey == NULL) { + printf("Error: fail to create regular private key\n"); + ret = -2; + break; + } + regPublicKey = new_ECC_Point(); + if (regPublicKey == NULL) { + printf("Error: fail to create regular public key\n"); + ret = -3; + break; + } + + // 3. Create 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"); + 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; + } + + // 4. Create signX and signY signX = new_BN(ordSize, 0); if (signX == NULL) { printf("Error: fail to create signX\n"); - ret = -15; + ret = -6; break; } signY = new_BN(ordSize, 0); if (signY == NULL) { printf("Error: fail to create signY\n"); - ret = -16; - break; - } - status = ippsECCPSignSM2(pMsg, regPrivateKey, ephPrivateKey, signX, signY, pECCPS); - if (status != ippStsNoErr) { - printf("Error: fail to compute signature\n"); - ret = -17; + ret = -7; break; - } + } - // 7. Verify using ECC context for SM2 - status = ippsECCPSetKeyPair(NULL, regPublicKey, ippTrue, pECCPS); - if (status != ippStsNoErr) { - printf("Error: fail to set regular public key\n"); - ret = -18; + // 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) + { + printf("Error: fail to sign\n"); + ret = -8; break; } - status = ippsECCPVerifySM2(pMsg, regPublicKey, signX, signY, &eccResult, pECCPS); - if((status != ippStsNoErr) || (eccResult != ippECValid)) { - printf("Error: fail to verify signature\n"); - ret = -19; + + // 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) + { + printf("Error: fail to verify\n"); + ret = -9; break; } } while(0); - // 8. Final, remove secret and release resources - SAFE_FREE(signX, sizeof(signX)); + // 7. Final, remove secret and release resources SAFE_FREE(signY, sizeof(signY)); - SAFE_FREE(ephPublicKey, sizeof(ephPublicKey)); - SAFE_FREE(ephPrivateKey, sizeof(ephPrivateKey)); + SAFE_FREE(signX, sizeof(signX)); SAFE_FREE(regPublicKey, sizeof(regPublicKey)); SAFE_FREE(regPrivateKey, sizeof(regPrivateKey)); - SAFE_FREE(pRandMsg, sizeof(pRandMsg)); - SAFE_FREE(pMsg, sizeof(pMsg)); - SAFE_FREE(pPRNGS, sizeof(pPRNGS)); - SAFE_FREE(pBNS, sizeof(pBNS)); SAFE_FREE(pECCPS, sizeof(pECCPS)); return ret; diff --git a/SampleCode/SampleEnclavePCL/Makefile b/SampleCode/SampleEnclavePCL/Makefile index 46a10160b..e2aadbe18 100644 --- a/SampleCode/SampleEnclavePCL/Makefile +++ b/SampleCode/SampleEnclavePCL/Makefile @@ -217,13 +217,34 @@ all: .config_$(Build_Mode)_$(SGX_ARCH)$(SGX_PCL) @$(MAKE) target ifeq ($(Build_Mode), HW_RELEASE) +ifeq ($(SGX_PCL), 1) target: $(App_Name) $(Enclave_Name) $(Seal_Enclave_Name) + @echo "The project has been built in release hardware mode." + @echo "Note that there are 2 enclaves in this project" + @echo "$(Enclave_Name) and $(Seal_Enclave_Name)" + @echo "Therefore, there are 2 steps involved for this project in release hardware mode" + @echo "Step 1: encrypt the enclave - $(Enclave_Name)" + @echo "First encrypt the $(Enclave_Name) with the encryption key before signing the enclave" + @echo "To encrypt the $(Enclave_Name) use this command:" + @echo " $(Pcl_Encryption_Tool) -i $(Enclave_Name) -o $(Encrypted_Enclave_Name) -k " + @echo "Step 2: sign $(Encrypted_Enclave_Name) and $(Seal_Enclave_Name)" + @echo "Please sign the $(Encrypted_Enclave_Name) with enclave signing key" + @echo "and also sign the $(Seal_Enclave_Name) with seal enclave signing key before you run the $(App_Name) to launch and access the enclaves." + @echo "To sign the seal enclave (i.e. $(Seal_Enclave_Name)) use the command" + @echo " $(SGX_ENCLAVE_SIGNER) sign -key -enclave $(Seal_Enclave_Name) -out $(Signed_Seal_Enclave_Name) -config $(Seal_Enclave_Config_File)" + @echo "To sign the encrypted enclave (i.e. $(Encrypted_Enclave_Name)) from step 1, use the command:" + @echo " $(SGX_ENCLAVE_SIGNER) sign -key -enclave $(Encrypted_Enclave_Name) -out $(Signed_Enclave_Name) -config $(Enclave_Config_File)" + @echo "You can also sign the enclave using an external signing tool." + @echo "To build the project in simulation mode set SGX_MODE=SIM. To build the project in prerelease mode set SGX_PRERELEASE=1 and SGX_MODE=HW." +else +target: $(App_Name) $(Enclave_Name) @echo "The project has been built in release hardware mode." @echo "Please sign the $(Enclave_Name) first with your signing key before you run the $(App_Name) to launch and access the enclave." @echo "To sign the enclave use the command:" @echo " $(SGX_ENCLAVE_SIGNER) sign -key -enclave $(Enclave_Name) -out <$(Signed_Enclave_Name)> -config $(Enclave_Config_File)" @echo "You can also sign the enclave using an external signing tool." @echo "To build the project in simulation mode set SGX_MODE=SIM. To build the project in prerelease mode set SGX_PRERELEASE=1 and SGX_MODE=HW." +endif else target: $(Signed_Seal_Enclave_Name) $(App_Name) $(Signed_Enclave_Name) ifeq ($(Build_Mode), HW_DEBUG) diff --git a/SampleCode/SampleEnclavePCL/README.md b/SampleCode/SampleEnclavePCL/README.md index cbb8fe1ba..ae07e155a 100644 --- a/SampleCode/SampleEnclavePCL/README.md +++ b/SampleCode/SampleEnclavePCL/README.md @@ -25,13 +25,25 @@ Enclave writers should compare SampleEnclave and SampleEnclavePCL. This demonstr Build and test the Intel(R) SGX PCL with the sample code -------------------------------------------------------- - -- To compile and run the sample -``` - $ cd SampleEnclavePCL - $ make - $ ./app -``` +1. Install Intel(R) Software Guard Extensions (Intel(R) SGX) SDK for Linux* OS +2. Make sure your environment is set: + $ source ${sgx-sdk-install-path}/environment +3. Build the project with the prepared Makefile: + a. Hardware Mode, Debug build: + $ make + b. Hardware Mode, Pre-release build: + $ make SGX_PRERELEASE=1 SGX_DEBUG=0 + c. Hardware Mode, Release build: + $ make SGX_DEBUG=0 + d. Simulation Mode, Debug build: + $ make SGX_MODE=SIM + e. Simulation Mode, Pre-release build: + $ make SGX_MODE=SIM SGX_PRERELEASE=1 SGX_DEBUG=0 + f. Simulation Mode, Release build: + $ make SGX_MODE=SIM SGX_DEBUG=0 +4. Execute the binary directly: + $ ./app +5. Remember to "make clean" before switching build mode ------------------------------------------------- Launch token initialization diff --git a/buildenv.mk b/buildenv.mk index ce3034195..51009c755 100644 --- a/buildenv.mk +++ b/buildenv.mk @@ -92,6 +92,7 @@ CC_VERSION_MAJOR := $(shell echo $(CC_VERSION) | cut -f1 -d.) CC_VERSION_MINOR := $(shell echo $(CC_VERSION) | cut -f2 -d.) CC_BELOW_4_9 := $(shell [ $(CC_VERSION_MAJOR) -lt 4 -o \( $(CC_VERSION_MAJOR) -eq 4 -a $(CC_VERSION_MINOR) -le 9 \) ] && echo 1) CC_BELOW_5_2 := $(shell [ $(CC_VERSION_MAJOR) -lt 5 -o \( $(CC_VERSION_MAJOR) -eq 5 -a $(CC_VERSION_MINOR) -le 2 \) ] && echo 1) +CC_NO_LESS_THAN_8 := $(shell expr $(CC_VERSION) \>\= "8") # turn on stack protector for SDK ifeq ($(CC_BELOW_4_9), 1) @@ -178,6 +179,12 @@ else COMMON_FLAGS += -DITT_ARCH_IA64 endif + +CET_FLAGS := +ifeq ($(CC_NO_LESS_THAN_8), 1) + CET_FLAGS += -fcf-protection +endif + CFLAGS += $(COMMON_FLAGS) CXXFLAGS += $(COMMON_FLAGS) @@ -224,7 +231,6 @@ ifeq ($(MITIGATION_INDIRECT), 1) MITIGATION_CFLAGS += -mindirect-branch-register endif ifeq ($(MITIGATION_RET), 1) -CC_NO_LESS_THAN_8 := $(shell expr $(CC_VERSION) \>\= "8") ifeq ($(CC_NO_LESS_THAN_8), 1) MITIGATION_CFLAGS += -fcf-protection=none endif @@ -246,6 +252,12 @@ endif MITIGATION_CFLAGS += $(MITIGATION_ASFLAGS) +#fcf-protection is not compatible with MITIGATION +ifneq ($(MITIGATION_RET), 1) + CFLAGS += $(CET_FLAGS) + CXXFLAGS += $(CET_FLAGS) +endif + # Compiler and linker options for an Enclave # # We are using '--export-dynamic' so that `g_global_data_sim' etc. diff --git a/common/inc/internal/arch.h b/common/inc/internal/arch.h index 375f12bf8..54f31ded6 100644 --- a/common/inc/internal/arch.h +++ b/common/inc/internal/arch.h @@ -37,8 +37,10 @@ #include "sgx_attributes.h" #include "sgx_key.h" #include "sgx_report.h" +#include "sgx_report2.h" #include "sgx_tcrypto.h" + #define SE_PAGE_SIZE 0x1000 #define TCS_SIZE SE_PAGE_SIZE diff --git a/common/inc/internal/inst.h b/common/inc/internal/inst.h index c95a3b00f..4f2b35756 100644 --- a/common/inc/internal/inst.h +++ b/common/inc/internal/inst.h @@ -46,6 +46,7 @@ typedef enum { SE_ERESUME, SE_EEXIT, SE_EACCEPT, + SE_EVERIFYREPORT2 = 0x8, SE_LAST_RING3, SE_ECREATE = 0x0, diff --git a/common/inc/internal/linux/linux-regs.h b/common/inc/internal/linux/linux-regs.h index b34f173fa..48a206d3b 100644 --- a/common/inc/internal/linux/linux-regs.h +++ b/common/inc/internal/linux/linux-regs.h @@ -88,6 +88,7 @@ #define SE_EEXIT 4 #define SE_EACCEPT 5 #define SE_EMODPE 6 +#define SE_EVERIFYREPORT2 8 #define SE_ECREATE 0 diff --git a/common/inc/internal/se_version.h b/common/inc/internal/se_version.h index b21726877..88f6a7c40 100644 --- a/common/inc/internal/se_version.h +++ b/common/inc/internal/se_version.h @@ -31,20 +31,25 @@ #ifndef _SE_VERSION_H_ #define _SE_VERSION_H_ -#define STRFILEVER "2.15.101.1" +#define STRFILEVER "2.16.100.4" #define SGX_MAJOR_VERSION 2 -#define SGX_MINOR_VERSION 15 -#define SGX_REVISION_VERSION 101 +#define SGX_MINOR_VERSION 16 +#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) 2021 Intel Corporation" +#define COPYRIGHT "Copyright (C) 2022 Intel Corporation" -#define UAE_SERVICE_VERSION "2.3.213.1" -#define URTS_VERSION "1.1.117.1" -#define ENCLAVE_COMMON_VERSION "1.1.120.1" -#define LAUNCH_VERSION "1.0.115.1" -#define EPID_VERSION "1.0.115.1" -#define QUOTE_EX_VERSION "1.1.115.1" +#define UAE_SERVICE_VERSION "2.3.214.4" +#define URTS_VERSION "1.1.118.4" +#define ENCLAVE_COMMON_VERSION "1.1.121.4" +#define LAUNCH_VERSION "1.0.116.4" +#define EPID_VERSION "1.0.116.4" +#define QUOTE_EX_VERSION "1.1.116.4" + +#define PCE_VERSION "1.16.100.0" +#define LE_VERSION "1.16.100.0" +#define QE_VERSION "1.16.100.0" +#define PVE_VERSION "1.16.100.0" #endif diff --git a/common/inc/internal/trts_inst.h b/common/inc/internal/trts_inst.h index 9e8046190..354148dcc 100644 --- a/common/inc/internal/trts_inst.h +++ b/common/inc/internal/trts_inst.h @@ -35,7 +35,7 @@ #include "sgx.h" #include "arch.h" -/* Attention: +/* Attention: * if the following alignment requirement changes, go to selib to * review the memory allocation of sgx_create_report and sgx_get_key. */ @@ -43,6 +43,7 @@ #define REPORT_DATA_ALIGN_SIZE 128 #define REPORT_ALIGN_SIZE 512 #define KEY_REQUEST_ALIGN_SIZE 512 +#define REPORT2_MAC_STRUCT_ALIGN_SIZE 256 #define KEY_ALIGN_SIZE 16 #define BIT_ERROR(x) (1 << (x)) @@ -56,6 +57,14 @@ typedef enum _egetkey_status_t EGETKEY_INVALID_KEYNAME = BIT_ERROR(8), } egetkey_status_t; +typedef enum _everifyreport2_status_t +{ + EVERIFYREPORT2_SUCCESS = 0, + EVERIFYREPORT2_INVALID_LEAF = 1, + EVERIFYREPORT2_INVALID_REPORTMACSTRUCT = BIT_ERROR(4)|BIT_ERROR(3)|BIT_ERROR(2), + EVERIFYREPORT2_INVALID_CPUSVN = BIT_ERROR(5), +} everifyreport2_status_t; + struct ms_tcs { void * ptcs; @@ -67,6 +76,7 @@ extern "C" { int sgx_accept_forward(si_flags_t sfl, size_t lo, size_t hi); int do_ereport(const sgx_target_info_t *target_info, const sgx_report_data_t *report_data, sgx_report_t *report); +int do_everifyreport2(const sgx_report2_mac_struct_t *report2_mac_struct); int do_egetkey(const sgx_key_request_t *key_request, sgx_key_128bit_t *key); uint32_t do_rdrand(uint32_t *rand); int do_eaccept(const sec_info_t *, size_t); diff --git a/common/inc/sgx_attributes.h b/common/inc/sgx_attributes.h index 0cc162615..4f5e18008 100644 --- a/common/inc/sgx_attributes.h +++ b/common/inc/sgx_attributes.h @@ -47,8 +47,9 @@ #define SGX_XFRM_AVX 0x0000000000000006ULL /* AVX XFRM which includes AVX state(0x04) and SSE state(0x02) required by AVX */ #define SGX_XFRM_AVX512 0x00000000000000E6ULL /* AVX-512 XFRM - not supported */ #define SGX_XFRM_MPX 0x0000000000000018ULL /* MPX XFRM - not supported */ +#define SGX_XFRM_PKRU 0x0000000000000200ULL /* PKRU state */ -#define SGX_XFRM_RESERVED (~(SGX_XFRM_LEGACY | SGX_XFRM_AVX | SGX_XFRM_AVX512)) +#define SGX_XFRM_RESERVED (~(SGX_XFRM_LEGACY | SGX_XFRM_AVX | SGX_XFRM_AVX512 | SGX_XFRM_PKRU)) typedef struct _attributes_t { diff --git a/common/inc/sgx_report2.h b/common/inc/sgx_report2.h new file mode 100644 index 000000000..14f764232 --- /dev/null +++ b/common/inc/sgx_report2.h @@ -0,0 +1,110 @@ +/* + * 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. + * + */ + +/* + * This file is to define Report Type2 + */ + +#ifndef _SGX_REPORT2_H_ +#define _SGX_REPORT2_H_ + +#define TEE_HASH_384_SIZE 48 /* SHA384 */ +#define TEE_MAC_SIZE 32 /* Message SHA 256 HASH Code - 32 bytes */ + +#define SGX_REPORT2_DATA_SIZE 64 +#define TEE_CPU_SVN_SIZE 16 + +#pragma pack(push, 1) + +typedef uint8_t tee_mac_t[TEE_MAC_SIZE]; + +typedef struct _tee_cpu_svn_t { + uint8_t svn[TEE_CPU_SVN_SIZE]; +} tee_cpu_svn_t; + +typedef struct _tee_measurement_t { + uint8_t m[TEE_HASH_384_SIZE]; +} tee_measurement_t; + +typedef struct _tee_report_data_t { + uint8_t d[SGX_REPORT2_DATA_SIZE]; +} tee_report_data_t; + +typedef struct _tee_attributes_t +{ + uint32_t a[2]; +} tee_attributes_t; + +#define SGX_LEGACY_REPORT_TYPE 0x0 /* SGX Legacy Report Type */ +#define TEE_REPORT2_TYPE 0x81 /* TEE Report Type2 */ +#define TEE_REPORT2_SUBTYPE 0x0 /* SUBTYPE for Report Type2 is 0 */ +#define TEE_REPORT2_VERSION 0x0 /* VERSION for Report Type2 is 0 */ + +typedef struct _tee_report_type_t { + uint8_t type; /* Trusted Execution Environment(TEE) type: + 0x00: SGX Legacy REPORT TYPE + 0x7F-0x01: Reserved + 0x80: Reserved + 0x81: TEE Report type 2 + 0xFF-0x82: Reserved + */ + uint8_t subtype; /* TYPE-specific subtype, Stage1: value is 0 */ + uint8_t version; /* TYPE-specific version, Stage1: value is 0 */ + uint8_t reserved; /* Reserved, must be zero */ +} tee_report_type_t; + +#define SGX_REPORT2_MAC_STRUCT_RESERVED1_BYTES 12 +#define SGX_REPORT2_MAC_STRUCT_RESERVED2_BYTES 32 +typedef struct _sgx_report2_mac_struct_t /* 256 bytes */ +{ + tee_report_type_t report_type; /* ( 0) TEE Report type.*/ + uint8_t reserved1[SGX_REPORT2_MAC_STRUCT_RESERVED1_BYTES]; /* ( 4) Reserved, must be zero */ + tee_cpu_svn_t cpu_svn; /* ( 16) Security Version of the CPU */ + tee_measurement_t tee_tcb_info_hash; /* ( 32) SHA384 of TEE_TCB_INFO for TEEs */ + tee_measurement_t tee_info_hash; /* ( 80) SHA384 of TEE_INFO */ + tee_report_data_t report_data; /* (128) Data provided by the user */ + uint8_t reserved2[SGX_REPORT2_MAC_STRUCT_RESERVED2_BYTES]; /* (192) Reserved, must be zero */ + tee_mac_t mac; /* (224) The Message Authentication Code over this structure */ +} sgx_report2_mac_struct_t; + +#define TEE_TCB_INFO_SIZE 239 +#define SGX_REPORT2_RESERVED_BYTES 17 +#define TEE_INFO_SIZE 512 +typedef struct _sgx_report2_t /* 1024 bytes */ +{ + sgx_report2_mac_struct_t report_mac_struct; /* ( 0) Report mac struct for SGX report type 2 */ + uint8_t tee_tcb_info[TEE_TCB_INFO_SIZE]; /* (256) Struct contains details about extra TCB elements not found in CPUSVN */ + uint8_t reserved[SGX_REPORT2_RESERVED_BYTES]; /* (495) Reserved, must be zero */ + uint8_t tee_info[TEE_INFO_SIZE]; /* (512) Struct contains the TEE Info */ +} sgx_report2_t; +#pragma pack(pop) + +#endif diff --git a/common/inc/sgx_tcrypto.h b/common/inc/sgx_tcrypto.h index 302a9c622..982daba7b 100644 --- a/common/inc/sgx_tcrypto.h +++ b/common/inc/sgx_tcrypto.h @@ -46,6 +46,7 @@ #define SGX_SHA1_HASH_SIZE 20 #define SGX_SHA256_HASH_SIZE 32 +#define SGX_SHA384_HASH_SIZE 48 #define SGX_ECP256_KEY_SIZE 32 #define SGX_NISTP_ECP256_KEY_SIZE (SGX_ECP256_KEY_SIZE/sizeof(uint32_t)) #define SGX_AESGCM_IV_SIZE 12 @@ -105,6 +106,7 @@ typedef void* sgx_aes_state_handle_t; typedef uint8_t sgx_sha1_hash_t[SGX_SHA1_HASH_SIZE]; typedef uint8_t sgx_sha256_hash_t[SGX_SHA256_HASH_SIZE]; +typedef uint8_t sgx_sha384_hash_t[SGX_SHA384_HASH_SIZE]; typedef uint8_t sgx_aes_gcm_128bit_key_t[SGX_AESGCM_KEY_SIZE]; typedef uint8_t sgx_aes_gcm_128bit_tag_t[SGX_AESGCM_MAC_SIZE]; @@ -217,6 +219,7 @@ extern "C" { * uint32_t src_len - Length of the input stream to be hashed * Output: sgx_sha#_hash_t *p_hash - Resultant hash from operation */ + sgx_status_t SGXAPI sgx_sha384_msg(const uint8_t *p_src, uint32_t src_len, sgx_sha384_hash_t *p_hash); sgx_status_t SGXAPI sgx_sha256_msg(const uint8_t *p_src, uint32_t src_len, sgx_sha256_hash_t *p_hash); sgx_status_t SGXAPI sgx_sha1_msg(const uint8_t *p_src, uint32_t src_len, sgx_sha1_hash_t *p_hash); @@ -226,6 +229,7 @@ extern "C" { * 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 SHA state */ + sgx_status_t SGXAPI sgx_sha384_init(sgx_sha_state_handle_t* p_sha_handle); sgx_status_t SGXAPI sgx_sha256_init(sgx_sha_state_handle_t* p_sha_handle); sgx_status_t SGXAPI sgx_sha1_init(sgx_sha_state_handle_t* p_sha_handle); @@ -237,6 +241,7 @@ extern "C" { * 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 SGXAPI sgx_sha384_update(const uint8_t *p_src, uint32_t src_len, sgx_sha_state_handle_t sha_handle); sgx_status_t SGXAPI sgx_sha256_update(const uint8_t *p_src, uint32_t src_len, sgx_sha_state_handle_t sha_handle); sgx_status_t SGXAPI sgx_sha1_update(const uint8_t *p_src, size_t src_len, sgx_sha_state_handle_t sha_handle); @@ -247,6 +252,7 @@ extern "C" { * Input: sgx_sha_state_handle_t sha_handle - Handle to the SHA state * Output: sgx_sha#_hash_t *p_hash - Resultant hash from operation */ + sgx_status_t SGXAPI sgx_sha384_get_hash(sgx_sha_state_handle_t sha_handle, sgx_sha384_hash_t *p_hash); sgx_status_t SGXAPI sgx_sha256_get_hash(sgx_sha_state_handle_t sha_handle, sgx_sha256_hash_t *p_hash); sgx_status_t SGXAPI sgx_sha1_get_hash(sgx_sha_state_handle_t sha_handle, sgx_sha1_hash_t *p_hash); @@ -256,6 +262,7 @@ extern "C" { * 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 SHA state */ + sgx_status_t SGXAPI sgx_sha384_close(sgx_sha_state_handle_t sha_handle); sgx_status_t SGXAPI sgx_sha256_close(sgx_sha_state_handle_t sha_handle); sgx_status_t SGXAPI sgx_sha1_close(sgx_sha_state_handle_t sha_handle); diff --git a/common/inc/sgx_trts.h b/common/inc/sgx_trts.h index 24a65e261..139ac4fe6 100644 --- a/common/inc/sgx_trts.h +++ b/common/inc/sgx_trts.h @@ -35,6 +35,7 @@ #include "sgx_error.h" #include "stddef.h" #include "sgx_defs.h" +#include "stdint.h" #ifdef __cplusplus extern "C" { @@ -82,6 +83,24 @@ int SGXAPI sgx_is_enclave_crashed(void) __attribute__((section(".nipx"))); */ sgx_status_t SGXAPI sgx_read_rand(unsigned char *rand, size_t length_in_bytes); +/* sgx_rdpkru() + * Parameters: + * val - the output PRKU + * Return Value: + * 1 - read successfully + * 0 - failed to read + */ +int SGXAPI sgx_rdpkru(uint32_t *val); + +/* sgx_wrpkru() + * Parameters: + * val - the target value to be written into PKRU + * Return Value: + * 1 - write successfully + * 0 - failed to write + */ +int SGXAPI sgx_wrpkru(uint32_t val); + #ifdef __cplusplus } #endif diff --git a/common/inc/sgx_ttls.edl b/common/inc/sgx_ttls.edl new file mode 100644 index 000000000..ca0906f57 --- /dev/null +++ b/common/inc/sgx_ttls.edl @@ -0,0 +1,62 @@ +/* + * 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. + * + */ + +enclave{ + include "sgx_report.h" + include "sgx_qve_header.h" + include "sgx_ql_lib_common.h" + include "sgx_ql_quote.h" + + untrusted { + quote3_error_t sgx_tls_get_qe_target_info_ocall([size = target_info_size, out] sgx_target_info_t *p_target_info, + size_t target_info_size); + + quote3_error_t sgx_tls_get_quote_size_ocall([out] uint32_t *p_quote_size); + + quote3_error_t sgx_tls_get_quote_ocall([size = report_size, in] sgx_report_t* p_report, + size_t report_size, + [size = quote_size, out] uint8_t *p_quote, + uint32_t quote_size); + + quote3_error_t sgx_tls_get_supplemental_data_size_ocall([out] uint32_t *p_supplemental_data_size); + + quote3_error_t sgx_tls_verify_quote_ocall( + [size = quote_size, in] const uint8_t *p_quote, + uint32_t quote_size, + time_t expiration_check_date, + [out] sgx_ql_qv_result_t *p_quote_verification_result, + [size = qve_report_info_size, in, out] sgx_ql_qe_report_info_t *p_qve_report_info, + size_t qve_report_info_size, + [size = supplemental_data_size, out] uint8_t *p_supplemental_data, + uint32_t supplemental_data_size); + + }; +}; diff --git a/common/inc/sgx_ttls.h b/common/inc/sgx_ttls.h new file mode 100644 index 000000000..cc8e7f9d0 --- /dev/null +++ b/common/inc/sgx_ttls.h @@ -0,0 +1,143 @@ +/* + * 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. + * + */ + +#ifndef _SGX_TTLS_H_ +#define _SGX_TTLS_H_ + +#include +#include +#include "sgx_error.h" +#include "sgx_defs.h" +#include "sgx_qve_header.h" +#include "sgx_ql_quote.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/* + * 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. + * + */ +quote3_error_t SGXAPI tee_get_certificate_with_evidence( + const unsigned char *p_subject_name, + const uint8_t *p_prv_key, + size_t private_key_size, + const uint8_t *p_pub_key, + size_t public_key_size, + uint8_t **pp_output_cert, + size_t *p_output_cert_size); + +/** + * tee_free_certificate + * + * Frees the output certificate buffer. + * This function is only available in the enclave. + * + * @param[in] p_certificate A pointer to output certificate buffer after called API `tee_get_certificate_with_evidence`. + * @retval SGX_QL_SUCCESS The function succeeded. + * @retval other appropriate error code. + */ +quote3_error_t SGXAPI tee_free_certificate(uint8_t* p_certificate); + + +/** + * tee_verify_certificate_with_evidence + * + * This function performs Intel(R) TEE quote and X.509 certificate verification. + * The validation includes extracting quote extension from the certificate before  + * validating the quote + * + * @param[in] p_cert_in_der A pointer to buffer holding certificate contents in DER format + * @param[in] cert_in_der_len The size of certificate buffer above + * @param[in] expiration_check_date The date that verifier will use to determine if any of the verification collateral have expired + * @param[out] p_qv_result SGX quote verification result + * @param[out] pp_supplemental_data A pointer to SGX quote verification supplemental data pointer + * @param[out] p_supplemental_data_size The size of supplemental data above + * @retval SGX_SUCCESS on a successful validation + * Please also refer to output parameters 'p_qv_result' for some warnings, + * You can refer to 'p_qv_result' and supplemental data to define your own quote verification policy + * @retval SGX_ERROR_INVALID_PARAMETER At least one parameter is invalid + * @retval SGX_ERROR_UNEXPECTED general failure + */ +quote3_error_t SGXAPI tee_verify_certificate_with_evidence( + const uint8_t *p_cert_in_der, + size_t cert_in_der_len, + const time_t expiration_check_date, + sgx_ql_qv_result_t *p_qv_result, + uint8_t **pp_supplemental_data, + uint32_t *p_supplemental_data_size); + +/** + * tee_free_supplemental_data_in_enclave + * + * Frees the quote verification supplemental data buffer. + * This function is only available in the enclave. + * + * @param[in] p_supplemental_data A pointer to the quote verification supplemental data, which is + * output of API `tee_verify_certificate_with_evidence` + * @retval SGX_QL_SUCCESS The function succeeded. + * @retval other appropriate error code. + */ +quote3_error_t SGXAPI tee_free_supplemental_data(uint8_t* p_supplemental_data); + + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/common/inc/sgx_utils.h b/common/inc/sgx_utils.h index 9b9bed855..d9a546c81 100644 --- a/common/inc/sgx_utils.h +++ b/common/inc/sgx_utils.h @@ -42,6 +42,7 @@ #include "sgx.h" #include "sgx_defs.h" +#include "sgx_report2.h" #ifdef __cplusplus extern "C" { @@ -84,13 +85,24 @@ sgx_status_t SGXAPI sgx_self_target(sgx_target_info_t *target_info); * Purpose: Software verification for the input report * * Paramters: - * report - [IN] ponter to the cryptographic report to be verified. + * report - [IN] pointer to the cryptographic report to be verified. * * Return value: * sgx_status_t - SGX_SUCCESS or failure as defined in sgx_error.h. */ sgx_status_t SGXAPI sgx_verify_report(const sgx_report_t *report); +/* sgx_verify_report2 + * Purpose: Software verification for the mac structure of the cryptographic report + * + * Parameters: + * report_mac_struct - [IN] pointer to the mac structure of the cryptographic report to be verified. + * + * Return value: + * sgx_status_t - SGX_SUCCESS or failure as defined in sgx_error.h. +*/ +sgx_status_t SGXAPI sgx_verify_report2(const sgx_report2_mac_struct_t *report_mac_struct); + /*sgx_get_key * Purpose: Generate a 128-bit secret key with the input information. * diff --git a/common/inc/sgx_utls.h b/common/inc/sgx_utls.h new file mode 100644 index 000000000..b68ee6685 --- /dev/null +++ b/common/inc/sgx_utls.h @@ -0,0 +1,91 @@ +/* + * 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. + * + */ + +#ifndef _SGX_UTLS_H_ +#define _SGX_UTLS_H_ + +#include +#include +#include "sgx_error.h" +#include "sgx_defs.h" +#include "sgx_qve_header.h" +#include "sgx_ql_quote.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/* + * tee_verify_certificate_with_evidence_host + * + * This function performs Intel(R) TEE quote and X.509 certificate verification in host. + * The validation includes extracting TEE quote extension from the + * certificate before validating the quote + * + * @param[in] p_cert_in_der A pointer to buffer holding certificate contents in DER format + * @param[in] cert_in_der_len The size of certificate buffer above + * @param[in] expiration_check_date The date that verifier will use to determine if any of the inputted collateral have expired + * @param[out] p_qv_result SGX quote verification result + * @param[out] pp_supplemental_data A pointer to SGX quote verification supplemental data pointer + * @param[out] p_supplemental_data_size The size of supplemental data above + * @retval SGX_QL_SUCCESS on a successful validation + * But you can still refer to output parameters 'p_qv_result' for some non-critical errors, + * You can refer to 'p_qv_result' and supplemental data to define your own quote verification policy + * @retval SGX_QL_ERROR_INVALID_PARAMETER At least one parameter is invalid + * @retval SGX_QL_ERROR_UNEXPECTED general failure + */ +quote3_error_t SGXAPI tee_verify_certificate_with_evidence_host( + const uint8_t *p_cert_in_der, + size_t cert_in_der_len, + const time_t expiration_check_date, + sgx_ql_qv_result_t *p_qv_result, + uint8_t **pp_supplemental_data, + uint32_t *p_supplemental_data_size); + +/** + * tee_free_supplemental_data + * + * Frees the quote verification supplemental data buffer. + * This function is only available out the enclave. + * + * @param[in] p_supplemental_data A pointer to the quote verification supplemental data, which is + * output of API `tee_verify_certificate_with_evidence` + * @retval SGX_QL_SUCCESS The function succeeded. + * @retval other appropriate error code. + */ +quote3_error_t SGXAPI tee_free_supplemental_data_host(uint8_t* p_supplemental_data); + + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/download_prebuilt.sh b/download_prebuilt.sh index 1927170a8..fa992a4ec 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.15.1.tar.gz -ae_file_name=prebuilt_ae_2.15.1.tar.gz +optlib_name=optimized_libs_2.16.tar.gz +ae_file_name=prebuilt_ae_2.16.tar.gz binutils_file_name=as.ld.objdump.r4.tar.gz -checksum_file=SHA256SUM_prebuilt_2.15.1.cfg -server_url_path=https://download.01.org/intel-sgx/sgx-linux/2.15.1 +checksum_file=SHA256SUM_prebuilt_2.16.cfg +server_url_path=https://download.01.org/intel-sgx/sgx-linux/2.16 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 ccc66d52f..1c3876f0a 100644 --- a/external/CppMicroServices/CMakeLists.txt +++ b/external/CppMicroServices/CMakeLists.txt @@ -380,7 +380,7 @@ else() foreach(_cxxflag -Werror -Wall -Wextra -Wpointer-arith -Winvalid-pch -Wcast-align -Wwrite-strings -Woverloaded-virtual -Wnon-virtual-dtor -Wold-style-cast - -Wstrict-null-sentinel -Wsign-promo -fdiagnostics-show-option -Wno-deprecated-copy) + -Wstrict-null-sentinel -Wsign-promo -fdiagnostics-show-option -Wno-deprecated-copy -Wno-deprecated-declarations) usFunctionCheckCompilerFlags(${_cxxflag} US_CXX_FLAGS) endforeach() diff --git a/external/CppMicroServices/third_party/jsoncpp.cpp b/external/CppMicroServices/third_party/jsoncpp.cpp index d827863d6..80a45450a 100644 --- a/external/CppMicroServices/third_party/jsoncpp.cpp +++ b/external/CppMicroServices/third_party/jsoncpp.cpp @@ -381,8 +381,11 @@ bool Reader::readValue() { break; case tokenNull: { +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wmaybe-uninitialized" Value v; currentValue().swapPayload(v); +#pragma GCC diagnostic pop } break; // Else, fall through... @@ -1224,8 +1227,11 @@ bool OurReader::readValue() { break; case tokenNull: { +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wmaybe-uninitialized" Value v; currentValue().swapPayload(v); +#pragma GCC diagnostic pop } break; case tokenNaN: @@ -1253,8 +1259,11 @@ bool OurReader::readValue() { // "Un-read" the current token and mark the current value as a null // token. current_--; +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wmaybe-uninitialized" Value v; currentValue().swapPayload(v); +#pragma GCC diagnostic pop break; } // else, fall through ... default: diff --git a/external/dcap_source b/external/dcap_source index 4b2b8fcef..fe200aa16 160000 --- a/external/dcap_source +++ b/external/dcap_source @@ -1 +1 @@ -Subproject commit 4b2b8fcef71caa4da294e2171b3816e2baa3ceaf +Subproject commit fe200aa160bc159f92149f02e703f0b02e4348d2 diff --git a/external/epid-sdk/ext/ipp/include/sgx_ippcp.h b/external/epid-sdk/ext/ipp/include/sgx_ippcp.h index 7f576b23a..18d452794 100644 --- a/external/epid-sdk/ext/ipp/include/sgx_ippcp.h +++ b/external/epid-sdk/ext/ipp/include/sgx_ippcp.h @@ -30,6 +30,7 @@ */ + #ifndef _SGX_IPPCP_H_ #define _SGX_IPPCP_H_ @@ -235,6 +236,22 @@ extern "C" { #define ippsHashMethod_SHA384 sgx_disp_ippsHashMethod_SHA384 #define ippsHashMethod_SHA512_256 sgx_disp_ippsHashMethod_SHA512_256 #define ippsHashMethod_SHA512_224 sgx_disp_ippsHashMethod_SHA512_224 + #define ippsHashMethodGetSize sgx_disp_ippsHashMethodGetSize + #define ippsHashMethodSet_MD5 sgx_disp_ippsHashMethodSet_MD5 + #define ippsHashMethodSet_SM3 sgx_disp_ippsHashMethodSet_SM3 + #define ippsHashMethodSet_SHA1 sgx_disp_ippsHashMethodSet_SHA1 + #define ippsHashMethodSet_SHA1_NI sgx_disp_ippsHashMethodSet_SHA1_NI + #define ippsHashMethodSet_SHA1_TT sgx_disp_ippsHashMethodSet_SHA1_TT + #define ippsHashMethodSet_SHA256 sgx_disp_ippsHashMethodSet_SHA256 + #define ippsHashMethodSet_SHA256_NI sgx_disp_ippsHashMethodSet_SHA256_NI + #define ippsHashMethodSet_SHA256_TT sgx_disp_ippsHashMethodSet_SHA256_TT + #define ippsHashMethodSet_SHA224 sgx_disp_ippsHashMethodSet_SHA224 + #define ippsHashMethodSet_SHA224_NI sgx_disp_ippsHashMethodSet_SHA224_NI + #define ippsHashMethodSet_SHA224_TT sgx_disp_ippsHashMethodSet_SHA224_TT + #define ippsHashMethodSet_SHA512 sgx_disp_ippsHashMethodSet_SHA512 + #define ippsHashMethodSet_SHA384 sgx_disp_ippsHashMethodSet_SHA384 + #define ippsHashMethodSet_SHA512_256 sgx_disp_ippsHashMethodSet_SHA512_256 + #define ippsHashMethodSet_SHA512_224 sgx_disp_ippsHashMethodSet_SHA512_224 #define ippsHashGetSize_rmf sgx_disp_ippsHashGetSize_rmf #define ippsHashInit_rmf sgx_disp_ippsHashInit_rmf #define ippsHashPack_rmf sgx_disp_ippsHashPack_rmf @@ -348,14 +365,6 @@ extern "C" { #define ippsRSAVerify_PKCS1v15 sgx_disp_ippsRSAVerify_PKCS1v15 #define ippsRSASign_PKCS1v15_rmf sgx_disp_ippsRSASign_PKCS1v15_rmf #define ippsRSAVerify_PKCS1v15_rmf sgx_disp_ippsRSAVerify_PKCS1v15_rmf - #define ippsRSA_MB_GetBufferSizePublicKey sgx_disp_ippsRSA_MB_GetBufferSizePublicKey - #define ippsRSA_MB_GetBufferSizePrivateKey sgx_disp_ippsRSA_MB_GetBufferSizePrivateKey - #define ippsRSA_MB_Encrypt sgx_disp_ippsRSA_MB_Encrypt - #define ippsRSA_MB_Decrypt sgx_disp_ippsRSA_MB_Decrypt - #define ippsRSA_MB_Sign_PSS_rmf sgx_disp_ippsRSA_MB_Sign_PSS_rmf - #define ippsRSA_MB_Verify_PSS_rmf sgx_disp_ippsRSA_MB_Verify_PSS_rmf - #define ippsRSA_MB_Sign_PKCS1v15_rmf sgx_disp_ippsRSA_MB_Sign_PKCS1v15_rmf - #define ippsRSA_MB_Verify_PKCS1v15_rmf sgx_disp_ippsRSA_MB_Verify_PKCS1v15_rmf #define ippsDLGetResultString sgx_disp_ippsDLGetResultString #define ippsDLPGetSize sgx_disp_ippsDLPGetSize #define ippsDLPInit sgx_disp_ippsDLPInit diff --git a/external/ippcp_internal/README.md b/external/ippcp_internal/README.md index a9b0cecad..3c2ccb271 100644 --- a/external/ippcp_internal/README.md +++ b/external/ippcp_internal/README.md @@ -3,17 +3,17 @@ The ippcp library is built based on the Open Source project ipp-crypto: * tag: [ippcp_2021.3](https://github.com/intel/ipp-crypto/tree/ippcp_2021.3) In order to build your own IPP crypto, please follow below steps: -1. Download the prebuilt mitigation tools package `as.ld.objdump.gold.{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`. -2. Read the ipp-crypto README to prepare your build environment. -3. Make sure ipp-crypto source code are prepared. -4. Build the target ippcp library with the prepared Makefile: - a. Build the target ippcp library with All-Loads-Mitigation: - $ make MITIGATION-CVE-2020-0551=LOAD - b. Build the target ippcp library with Branch-Mitigation: - $ make MITIGATION-CVE-2020-0551=CF - c. Build the target ippcp library with No-Mitigation: - $ make -The built-out static library `libippcp.a` and header files will be copied into the right place. +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`. +2. Read the ipp-crypto README to prepare your build environment. +3. Make sure ipp-crypto source code are prepared. +4. Build the target ippcp library with the prepared Makefile: + a. Build the target ippcp library with All-Loads-Mitigation: + $ make MITIGATION-CVE-2020-0551=LOAD + b. Build the target ippcp library with Branch-Mitigation: + $ make MITIGATION-CVE-2020-0551=C + c. Build the target ippcp library with No-Mitigation: + $ make +The built-out static library `libippcp.a` and header files will be copied into the right place. Remember to "make clean" before switching the build. For IPP crypto reproducible build, please follow the instructions in [reproducibility README.md](../../linux/reproducibility/README.md) to reproduce the prebuilt IPP crypto. diff --git a/external/protobuf/Makefile b/external/protobuf/Makefile index 54b8b7439..88eedc720 100644 --- a/external/protobuf/Makefile +++ b/external/protobuf/Makefile @@ -51,9 +51,14 @@ CHECK_SOURCE := protobuf_code endif .PHONY: all +ifeq ($(BUILD_PROTOC), 1) all: $(LIBPB) $(PROTOCPB) $(BUILD_DIR) $(CP) $(LIBPB) $(BUILD_DIR)/libsgx_protobuf.a $(CP) $(PROTOCPB) $(BUILD_DIR)/sgx_protoc +else +all: $(LIBPB) $(BUILD_DIR) + $(CP) $(LIBPB) $(BUILD_DIR)/libsgx_protobuf.a +endif $(BUILD_DIR): @$(MKDIR) $@ @@ -73,10 +78,12 @@ $(LIBPB): $(CHECK_SOURCE) ifeq ("$(wildcard $(PB_DIR)/cmake/libsgx_protobuf.cmake)", "") cd $(PB_DIR) && git apply ../sgx_protobuf.patch&& cd .. endif - $(MKDIR) protobuf_code/final_tlibPB/build && cd protobuf_code/final_tlibPB/build && cmake $(PB_CONFIG) -Dprotobuf_BUILD_PROTOC_BINARIES=FALSE -Dprotobuf_BUILD_TESTS=FALSE -DSGX=TRUE ../../cmake && make + $(MKDIR) protobuf_code/final_tlibPB/build && cd protobuf_code/final_tlibPB/build && cmake $(PB_CONFIG) -Dprotobuf_BUILD_PROTOC_BINARIES=FALSE -Dprotobuf_BUILD_TESTS=FALSE -DProtobuf_LITE_LIBRARIES=FALSE -DSGX=TRUE ../../cmake && make +ifeq ($(BUILD_PROTOC), 1) $(PROTOCPB): $(CHECK_SOURCE) $(MKDIR) protobuf_code/final_protocPB/build && cd protobuf_code/final_protocPB/build && cmake -Dprotobuf_BUILD_PROTOC_BINARIES=TRUE -Dprotobuf_BUILD_TESTS=FALSE -DSGX=FALSE ../../cmake && make +endif .PHONY: clean clean: diff --git a/external/protobuf/sgx_protobuf.patch b/external/protobuf/sgx_protobuf.patch index 86f94e788..5a3cf5978 100644 --- a/external/protobuf/sgx_protobuf.patch +++ b/external/protobuf/sgx_protobuf.patch @@ -1,11 +1,13 @@ -From fe8fb72edd288b34f56d29655b31628418ece297 Mon Sep 17 00:00:00 2001 +From 1fd736c2c796b7ff475a0e26c28acb6a48eb9b5e Mon Sep 17 00:00:00 2001 From: yanxue -Date: Wed, 18 Aug 2021 16:38:10 +0800 +Date: Wed, 16 Feb 2022 16:44:18 +0800 Subject: [PATCH] Enable Protobuf in SGX --- cmake/CMakeLists.txt | 31 +++- cmake/libsgx_protobuf.cmake | 137 ++++++++++++++++++ + configure.ac | 2 +- + src/google/protobuf/compiler/cpp/cpp_file.cc | 2 + src/google/protobuf/generated_message_util.cc | 10 ++ src/google/protobuf/io/coded_stream.h | 4 + .../protobuf/io/zero_copy_stream_impl.cc | 8 +- @@ -26,11 +28,11 @@ Subject: [PATCH] Enable Protobuf in SGX .../protobuf/util/delimited_message_util.cc | 2 + .../protobuf/util/delimited_message_util.h | 7 +- src/google/protobuf/util/time_util.h | 4 + - 22 files changed, 293 insertions(+), 13 deletions(-) + 24 files changed, 296 insertions(+), 14 deletions(-) create mode 100644 cmake/libsgx_protobuf.cmake diff --git a/cmake/CMakeLists.txt b/cmake/CMakeLists.txt -index 52661f5..1d8a2d7 100644 +index 52661f522..1d8a2d71a 100644 --- a/cmake/CMakeLists.txt +++ b/cmake/CMakeLists.txt @@ -19,6 +19,13 @@ endif() @@ -87,7 +89,7 @@ index 52661f5..1d8a2d7 100644 endif (protobuf_BUILD_LIBPROTOC) diff --git a/cmake/libsgx_protobuf.cmake b/cmake/libsgx_protobuf.cmake new file mode 100644 -index 0000000..262129e +index 000000000..262129e49 --- /dev/null +++ b/cmake/libsgx_protobuf.cmake @@ -0,0 +1,137 @@ @@ -228,8 +230,34 @@ index 0000000..262129e + OUTPUT_NAME ${LIB_PREFIX}protobuf + DEBUG_POSTFIX "${protobuf_DEBUG_POSTFIX}") +add_library(protobuf::libprotobuf ALIAS libprotobuf) +diff --git a/configure.ac b/configure.ac +index eb70a76e1..3402990f8 100644 +--- a/configure.ac ++++ b/configure.ac +@@ -106,7 +106,7 @@ ACX_CHECK_SUNCC + + # Have to do libtool after SUNCC, other wise it "helpfully" adds Crun Cstd + # to the link +-AC_PROG_LIBTOOL ++LT_INIT + + # Check whether the linker supports version scripts + AC_MSG_CHECKING([whether the linker supports version scripts]) +diff --git a/src/google/protobuf/compiler/cpp/cpp_file.cc b/src/google/protobuf/compiler/cpp/cpp_file.cc +index 875beec9f..732b0e915 100644 +--- a/src/google/protobuf/compiler/cpp/cpp_file.cc ++++ b/src/google/protobuf/compiler/cpp/cpp_file.cc +@@ -75,6 +75,8 @@ std::string GetSortKey(const FileDescriptor& val) { + + template <> + std::string GetSortKey(const SCC& val) { ++ if (val.GetRepresentative() == nullptr) ++ return std::string(""); + return val.GetRepresentative()->full_name(); + } + diff --git a/src/google/protobuf/generated_message_util.cc b/src/google/protobuf/generated_message_util.cc -index f1f6f88..b02f91d 100644 +index f1f6f8833..b02f91d0d 100644 --- a/src/google/protobuf/generated_message_util.cc +++ b/src/google/protobuf/generated_message_util.cc @@ -39,7 +39,11 @@ @@ -277,7 +305,7 @@ index f1f6f88..b02f91d 100644 } // namespace internal diff --git a/src/google/protobuf/io/coded_stream.h b/src/google/protobuf/io/coded_stream.h -index 0fff178..431a1c9 100644 +index 0fff1782c..431a1c994 100644 --- a/src/google/protobuf/io/coded_stream.h +++ b/src/google/protobuf/io/coded_stream.h @@ -131,7 +131,11 @@ @@ -293,7 +321,7 @@ index 0fff178..431a1c9 100644 (defined(__BYTE_ORDER) && __BYTE_ORDER == __LITTLE_ENDIAN)) && \ !defined(PROTOBUF_DISABLE_LITTLE_ENDIAN_OPT_FOR_TEST) diff --git a/src/google/protobuf/io/zero_copy_stream_impl.cc b/src/google/protobuf/io/zero_copy_stream_impl.cc -index 52617e9..08de285 100644 +index 52617e9ef..08de285a3 100644 --- a/src/google/protobuf/io/zero_copy_stream_impl.cc +++ b/src/google/protobuf/io/zero_copy_stream_impl.cc @@ -33,15 +33,20 @@ @@ -335,7 +363,7 @@ index 52617e9..08de285 100644 ConcatenatingInputStream::ConcatenatingInputStream( diff --git a/src/google/protobuf/io/zero_copy_stream_impl.h b/src/google/protobuf/io/zero_copy_stream_impl.h -index 0206e38..1f0b19c 100644 +index 0206e3887..1f0b19ce3 100644 --- a/src/google/protobuf/io/zero_copy_stream_impl.h +++ b/src/google/protobuf/io/zero_copy_stream_impl.h @@ -53,7 +53,7 @@ @@ -357,7 +385,7 @@ index 0206e38..1f0b19c 100644 // A ZeroCopyInputStream which reads from several other streams in sequence. diff --git a/src/google/protobuf/message_lite.cc b/src/google/protobuf/message_lite.cc -index 0e85991..c533c9f 100644 +index 0e8599147..c533c9f3e 100644 --- a/src/google/protobuf/message_lite.cc +++ b/src/google/protobuf/message_lite.cc @@ -272,7 +272,7 @@ bool MessageLite::ParsePartialFromZeroCopyStream( @@ -396,7 +424,7 @@ index 0e85991..c533c9f 100644 GOOGLE_DCHECK(IsInitialized()) << InitializationErrorMessage("serialize", *this); return AppendPartialToString(output); diff --git a/src/google/protobuf/message_lite.h b/src/google/protobuf/message_lite.h -index a76c16e..cc62911 100644 +index a76c16e5a..cc6291162 100644 --- a/src/google/protobuf/message_lite.h +++ b/src/google/protobuf/message_lite.h @@ -310,11 +310,15 @@ class PROTOBUF_EXPORT MessageLite { @@ -431,7 +459,7 @@ index a76c16e..cc62911 100644 // existing contents. All required fields must be set. bool AppendToString(std::string* output) const; diff --git a/src/google/protobuf/stubs/common.cc b/src/google/protobuf/stubs/common.cc -index bc150f5..c7be73d 100644 +index bc150f56a..c7be73d57 100644 --- a/src/google/protobuf/stubs/common.cc +++ b/src/google/protobuf/stubs/common.cc @@ -35,7 +35,11 @@ @@ -487,7 +515,7 @@ index bc150f5..c7be73d 100644 } diff --git a/src/google/protobuf/stubs/int128.cc b/src/google/protobuf/stubs/int128.cc -index 2119e65..6896876 100644 +index 2119e6550..68968760e 100644 --- a/src/google/protobuf/stubs/int128.cc +++ b/src/google/protobuf/stubs/int128.cc @@ -31,7 +31,9 @@ @@ -517,7 +545,7 @@ index 2119e65..6896876 100644 } // namespace protobuf } // namespace google diff --git a/src/google/protobuf/stubs/int128.h b/src/google/protobuf/stubs/int128.h -index dc70d96..bfca3bf 100644 +index dc70d96eb..bfca3bfc6 100644 --- a/src/google/protobuf/stubs/int128.h +++ b/src/google/protobuf/stubs/int128.h @@ -85,9 +85,11 @@ class PROTOBUF_EXPORT uint128 { @@ -545,7 +573,7 @@ index dc70d96..bfca3bf 100644 // Methods to access low and high pieces of 128-bit value. // Defined externally from uint128 to facilitate conversion diff --git a/src/google/protobuf/stubs/port.h b/src/google/protobuf/stubs/port.h -index 0fcee68..8e017b7 100644 +index 0fcee6891..8e017b735 100644 --- a/src/google/protobuf/stubs/port.h +++ b/src/google/protobuf/stubs/port.h @@ -57,9 +57,13 @@ @@ -563,7 +591,7 @@ index 0fcee68..8e017b7 100644 #if ((defined(__LITTLE_ENDIAN__) && !defined(__BIG_ENDIAN__)) || \ (defined(__BYTE_ORDER) && __BYTE_ORDER == __LITTLE_ENDIAN) || \ diff --git a/src/google/protobuf/stubs/status.cc b/src/google/protobuf/stubs/status.cc -index 03b37c3..f53c178 100644 +index 03b37c365..f53c1781e 100644 --- a/src/google/protobuf/stubs/status.cc +++ b/src/google/protobuf/stubs/status.cc @@ -29,7 +29,9 @@ @@ -590,7 +618,7 @@ index 03b37c3..f53c178 100644 } // namespace util } // namespace protobuf diff --git a/src/google/protobuf/stubs/status.h b/src/google/protobuf/stubs/status.h -index bededad..2d82c8c 100644 +index bededad54..2d82c8c76 100644 --- a/src/google/protobuf/stubs/status.h +++ b/src/google/protobuf/stubs/status.h @@ -113,8 +113,10 @@ class PROTOBUF_EXPORT Status { @@ -605,7 +633,7 @@ index bededad..2d82c8c 100644 } // namespace util } // namespace protobuf diff --git a/src/google/protobuf/stubs/stringpiece.cc b/src/google/protobuf/stubs/stringpiece.cc -index 353c78c..1ed4546 100644 +index 353c78cad..1ed4546ba 100644 --- a/src/google/protobuf/stubs/stringpiece.cc +++ b/src/google/protobuf/stubs/stringpiece.cc @@ -33,16 +33,20 @@ @@ -630,7 +658,7 @@ index 353c78c..1ed4546 100644 // Out-of-line error path. void StringPiece::LogFatalSizeTooBig(size_t size, const char* details) { diff --git a/src/google/protobuf/stubs/stringpiece.h b/src/google/protobuf/stubs/stringpiece.h -index fbcb20a..afd567e 100644 +index fbcb20afc..afd567eed 100644 --- a/src/google/protobuf/stubs/stringpiece.h +++ b/src/google/protobuf/stubs/stringpiece.h @@ -423,8 +423,10 @@ inline bool operator>=(StringPiece x, StringPiece y) { @@ -645,7 +673,7 @@ index fbcb20a..afd567e 100644 namespace internal { // StringPiece is not a POD and can not be used in an union (pre C++11). We diff --git a/src/google/protobuf/stubs/strutil.cc b/src/google/protobuf/stubs/strutil.cc -index 2ecdb2b..4944f63 100644 +index 2ecdb2bf7..4944f6380 100644 --- a/src/google/protobuf/stubs/strutil.cc +++ b/src/google/protobuf/stubs/strutil.cc @@ -39,6 +39,9 @@ @@ -728,7 +756,7 @@ index 2ecdb2b..4944f63 100644 int snprintf_result = snprintf(buffer, kFloatToBufferSize, "%.*g", FLT_DIG, value); diff --git a/src/google/protobuf/stubs/time.cc b/src/google/protobuf/stubs/time.cc -index 922be76..4efb2e8 100644 +index 922be76d1..4efb2e85e 100644 --- a/src/google/protobuf/stubs/time.cc +++ b/src/google/protobuf/stubs/time.cc @@ -264,7 +264,11 @@ bool DateTimeToSeconds(const DateTime& time, int64* seconds) { @@ -744,7 +772,7 @@ index 922be76..4efb2e8 100644 } diff --git a/src/google/protobuf/text_format.cc b/src/google/protobuf/text_format.cc -index f47d4e8..afd178c 100644 +index f47d4e8d0..afd178c6f 100644 --- a/src/google/protobuf/text_format.cc +++ b/src/google/protobuf/text_format.cc @@ -63,6 +63,9 @@ @@ -758,7 +786,7 @@ index f47d4e8..afd178c 100644 namespace google { namespace protobuf { diff --git a/src/google/protobuf/util/delimited_message_util.cc b/src/google/protobuf/util/delimited_message_util.cc -index 425dc2c..d07637d 100644 +index 425dc2cfd..d07637d3b 100644 --- a/src/google/protobuf/util/delimited_message_util.cc +++ b/src/google/protobuf/util/delimited_message_util.cc @@ -38,6 +38,7 @@ namespace google { @@ -778,7 +806,7 @@ index 425dc2c..d07637d 100644 bool ParseDelimitedFromCodedStream(MessageLite* message, io::CodedInputStream* input, diff --git a/src/google/protobuf/util/delimited_message_util.h b/src/google/protobuf/util/delimited_message_util.h -index d3f7dbe..4fe6fd1 100644 +index d3f7dbe8a..4fe6fd190 100644 --- a/src/google/protobuf/util/delimited_message_util.h +++ b/src/google/protobuf/util/delimited_message_util.h @@ -34,8 +34,9 @@ @@ -818,7 +846,7 @@ index d3f7dbe..4fe6fd1 100644 bool PROTOBUF_EXPORT ParseDelimitedFromCodedStream(MessageLite* message, io::CodedInputStream* input, diff --git a/src/google/protobuf/util/time_util.h b/src/google/protobuf/util/time_util.h -index 95063fc..084c996 100644 +index 95063fc49..084c996a1 100644 --- a/src/google/protobuf/util/time_util.h +++ b/src/google/protobuf/util/time_util.h @@ -43,10 +43,14 @@ struct timeval { diff --git a/external/rdrand/src/Makefile.in b/external/rdrand/src/Makefile.in index 5a4ec8c42..dc042de95 100644 --- a/external/rdrand/src/Makefile.in +++ b/external/rdrand/src/Makefile.in @@ -2,6 +2,11 @@ PACKAGE_NAME=@PACKAGE_NAME@ PACKAGE_VERSION=@PACKAGE_VERSION@ CC=@CC@ CFLAGS=@CFLAGS@ -O2 +CC_VERSION := $(shell $(CC) -dumpversion) +CC_NO_LESS_THAN_8 := $(shell expr $(CC_VERSION) \>\= "8") +ifeq ($(CC_NO_LESS_THAN_8), 1) + CFLAGS += -fcf-protection +endif AR=ar TEST_OBJ=main.o diff --git a/external/sgxssl/prepare_sgxssl.sh b/external/sgxssl/prepare_sgxssl.sh index 31ce3ce78..5d0be1443 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=1.1.1l +openssl_ver=1.1.1m openssl_ver_name=openssl-$openssl_ver sgxssl_github_archive=https://github.com/intel/intel-sgx-ssl/archive -sgxssl_file_name=lin_2.14_1.1.1k +sgxssl_file_name=lin_2.16_1.1.1m_update build_script=$top_dir/Linux/build_openssl.sh server_url_path=https://www.openssl.org/source full_openssl_url=$server_url_path/old/1.1.1/$openssl_ver_name.tar.gz -sgxssl_chksum=825e58823f2ec39bcfb69c2c62cc4e769bdac057ade10b362cdeac1f5a563954 -openssl_chksum=0b7a3e5e59c34827fe0c3a74b7ec8baef302b98fa80088d7f9153aa16fa76bd1 +sgxssl_chksum=46d3e6113da446f0fb250d9ca3b73f06b4fbc4e8f552c98f5de0865ee38caffc +openssl_chksum=f89199be8b23ca45fc7cb9f1d8d3ee67312318286ad030f5316aca6462db6c96 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/external/vtune/linux/sdk/src/ittnotify/Makefile b/external/vtune/linux/sdk/src/ittnotify/Makefile index 6e4f565e6..ce1432d0a 100644 --- a/external/vtune/linux/sdk/src/ittnotify/Makefile +++ b/external/vtune/linux/sdk/src/ittnotify/Makefile @@ -5,6 +5,12 @@ LIBNAME := libittnotify.a INCLUDE += -I ../../../include CFLAGS += $(INCLUDE) -fPIC -Wno-strict-prototypes +CC ?= gcc +CC_VERSION := $(shell $(CC) -dumpversion) +CC_NO_LESS_THAN_8 := $(shell expr $(CC_VERSION) \>\= "8") +ifeq ($(CC_NO_LESS_THAN_8), 1) + CFLAGS += -fcf-protection +endif .PHONY: all all: $(LIBNAME) diff --git a/linux/installer/common/gen_source/copy_source.py b/linux/installer/common/gen_source/copy_source.py new file mode 100755 index 000000000..b5f76a267 --- /dev/null +++ b/linux/installer/common/gen_source/copy_source.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python +# +# 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. +# +# + +import os +import shutil +import argparse + +def copy_directory(src, dst): + if os.path.isdir(src) == True: + if os.path.exists(dst) == False: + os.makedirs(dst) + + for item in os.listdir(src): + copy_directory((os.path.join(src, item)).replace("\\", "/"), (os.path.join(dst, item)).replace("\\", "/")) + else: + shutil.copy(src, dst) + return + +def copy_files(): + with open(bom_file, 'r') as f: + next(f) + for line in f: + if line == "\n": + continue + src = line.split('\t')[0].replace("\\", "/").replace("/", src_path + "/") + dst = line.split('\t')[1].replace("\\", "/").replace("/", dst_path + "/") + + if os.path.realpath(dst).startswith(os.path.realpath(src) + "/") == True: + print("Error: destination {} is a sub-directory of source {}!".format(dst, src)) + exit(1) + + if os.path.exists(src) == True: + if os.path.isdir(src) == False : + if os.path.exists(os.path.dirname(dst)) == False: + os.makedirs(os.path.dirname(dst)) + shutil.copy(src, dst) + else: + copy_directory(src, dst) + else: + print("Error: src directory/file {} does not exist!".format(src)) + exit(1) + return + +def parse_args(): + global bom_file + global src_path + global dst_path + global cleanup + + parser = argparse.ArgumentParser() + parser.add_argument("--bom-file", metavar="[BOM file]", type=argparse.FileType('r'), dest="bom_file", required=True, + help="The BOM file used to generate the source tree.") + parser.add_argument("--src-path", metavar="[source path]", dest="src_path", required=True, + help="The path for the original source code.") + parser.add_argument("--dst-path", metavar="[destination path]", dest="dst_path", required=True, + help="The detestation path of the generated source tree.") + parser.add_argument("--cleanup", action="store_true", default=False, dest="cleanup", + help="Whether to cleanup the source tree.") + args = parser.parse_args() + + if os.path.isfile(os.path.abspath(args.bom_file.name)) == False: + parser.error("Invalid argument for option '--bom-file %s'." %(args.bom_file.name)) + exit(1) + if os.path.isdir(os.path.abspath(args.src_path)) == False: + parser.error("Invalid argument for option '--src-path %s'." %(args.src_path)) + exit(1) + if os.path.exists(args.dst_path) == True and os.path.isdir(os.path.abspath(args.dst_path)) == False: + parser.error("Invalid argument for option '--dst-path %s'." %(args.dst_path)) + exit(1) + + bom_file = args.bom_file.name + src_path = args.src_path + dst_path = args.dst_path + cleanup = args.cleanup + + if cleanup == True and os.path.exists(dst_path) == True: + shutil.rmtree(os.path.abspath(dst_path)) + + if os.path.exists(dst_path) == False: + os.makedirs(dst_path) + return + +if __name__ == "__main__": + parse_args() + copy_files() + + exit(0) diff --git a/linux/installer/common/psw-dcap/91-sgx-enclave.rules b/linux/installer/common/psw-dcap/91-sgx-enclave.rules new file mode 100644 index 000000000..223dd06b4 --- /dev/null +++ b/linux/installer/common/psw-dcap/91-sgx-enclave.rules @@ -0,0 +1,4 @@ +SUBSYSTEM=="misc",KERNEL=="sgx_enclave",MODE="0666",SYMLINK+="sgx/enclave" +SUBSYSTEM=="misc",KERNEL=="enclave",MODE="0666" +SUBSYSTEM=="sgx",KERNEL=="sgx/enclave",MODE="0666" + diff --git a/linux/installer/common/psw-dcap/92-sgx-provision.rules b/linux/installer/common/psw-dcap/92-sgx-provision.rules new file mode 100644 index 000000000..78ab76f38 --- /dev/null +++ b/linux/installer/common/psw-dcap/92-sgx-provision.rules @@ -0,0 +1,3 @@ +SUBSYSTEM=="misc",KERNEL=="sgx_provision",SYMLINK+="sgx/provision",GROUP="sgx_prv",MODE="0660" +SUBSYSTEM=="misc",KERNEL=="provision",GROUP="sgx_prv",MODE="0660" +SUBSYSTEM=="sgx",KERNEL=="sgx/provision",GROUP="sgx_prv",MODE="0660" diff --git a/linux/installer/common/psw-dcap/BOM_install/libsgx-ae-epid.txt b/linux/installer/common/psw-dcap/BOM_install/libsgx-ae-epid.txt new file mode 100644 index 000000000..0a20fe39b --- /dev/null +++ b/linux/installer/common/psw-dcap/BOM_install/libsgx-ae-epid.txt @@ -0,0 +1,3 @@ +DeliveryName InstallName FileCheckSum FileFeature FileOwner +/build/linux/libsgx_qe.signed.so /aesm/libsgx_qe.signed.so 0 main STP +/build/linux/libsgx_pve.signed.so /aesm/libsgx_pve.signed.so 0 main STP diff --git a/linux/installer/common/psw-dcap/BOM_install/libsgx-ae-id-enclave.txt b/linux/installer/common/psw-dcap/BOM_install/libsgx-ae-id-enclave.txt new file mode 100644 index 000000000..b450db4be --- /dev/null +++ b/linux/installer/common/psw-dcap/BOM_install/libsgx-ae-id-enclave.txt @@ -0,0 +1,2 @@ +DeliveryName InstallName FileCheckSum FileFeature FileOwner +/external/dcap_source/QuoteGeneration/psw/ae/data/prebuilt/libsgx_id_enclave.signed.so /lib/libsgx_id_enclave.signed.so 0 main STP diff --git a/linux/installer/common/psw-dcap/BOM_install/libsgx-ae-le.txt b/linux/installer/common/psw-dcap/BOM_install/libsgx-ae-le.txt new file mode 100644 index 000000000..b286d66b6 --- /dev/null +++ b/linux/installer/common/psw-dcap/BOM_install/libsgx-ae-le.txt @@ -0,0 +1,3 @@ +DeliveryName InstallName FileCheckSum FileFeature FileOwner +/build/linux/libsgx_le.signed.so /aesm/libsgx_le.signed.so 0 main STP +/build/linux/le_prod_css.bin /aesm/le_prod_css.bin 0 main STP \ No newline at end of file diff --git a/linux/installer/common/psw-dcap/BOM_install/libsgx-ae-pce.txt b/linux/installer/common/psw-dcap/BOM_install/libsgx-ae-pce.txt new file mode 100644 index 000000000..3c0c7d537 --- /dev/null +++ b/linux/installer/common/psw-dcap/BOM_install/libsgx-ae-pce.txt @@ -0,0 +1,3 @@ +DeliveryName InstallName FileCheckSum FileFeature FileOwner +/build/linux/libsgx_pce.signed.so /lib/libsgx_pce.signed.so 0 main STP +/linux/installer/common/psw-dcap/92-sgx-provision.rules /etc/udev/rules.d/93-sgx-provision.rules 0 main STP diff --git a/linux/installer/common/psw-dcap/BOM_install/libsgx-ae-qe3.txt b/linux/installer/common/psw-dcap/BOM_install/libsgx-ae-qe3.txt new file mode 100644 index 000000000..a3b7631ed --- /dev/null +++ b/linux/installer/common/psw-dcap/BOM_install/libsgx-ae-qe3.txt @@ -0,0 +1,2 @@ +DeliveryName InstallName FileCheckSum FileFeature FileOwner +/external/dcap_source/QuoteGeneration/psw/ae/data/prebuilt/libsgx_qe3.signed.so /lib/libsgx_qe3.signed.so 0 main STP diff --git a/linux/installer/common/psw-dcap/BOM_install/libsgx-ae-qve.txt b/linux/installer/common/psw-dcap/BOM_install/libsgx-ae-qve.txt new file mode 100644 index 000000000..188d6b86b --- /dev/null +++ b/linux/installer/common/psw-dcap/BOM_install/libsgx-ae-qve.txt @@ -0,0 +1,2 @@ +DeliveryName InstallName FileCheckSum FileFeature FileOwner +/external/dcap_source/QuoteGeneration/psw/ae/data/prebuilt/libsgx_qve.signed.so /lib/libsgx_qve.signed.so 0 main STP diff --git a/linux/installer/common/psw-dcap/BOM_install/libsgx-aesm-ecdsa-plugin.txt b/linux/installer/common/psw-dcap/BOM_install/libsgx-aesm-ecdsa-plugin.txt new file mode 100644 index 000000000..1a819fcd2 --- /dev/null +++ b/linux/installer/common/psw-dcap/BOM_install/libsgx-aesm-ecdsa-plugin.txt @@ -0,0 +1,2 @@ +DeliveryName InstallName FileCheckSum FileFeature FileOwner +/build/linux/bundles/libecdsa_quote_service_bundle.so /aesm/bundles/libecdsa_quote_service_bundle.so 0 main STP \ No newline at end of file diff --git a/linux/installer/common/psw-dcap/BOM_install/libsgx-aesm-epid-plugin.txt b/linux/installer/common/psw-dcap/BOM_install/libsgx-aesm-epid-plugin.txt new file mode 100644 index 000000000..dd14a29bc --- /dev/null +++ b/linux/installer/common/psw-dcap/BOM_install/libsgx-aesm-epid-plugin.txt @@ -0,0 +1,2 @@ +DeliveryName InstallName FileCheckSum FileFeature FileOwner +/build/linux/bundles/libepid_quote_service_bundle.so /aesm/bundles/libepid_quote_service_bundle.so 0 main STP \ No newline at end of file diff --git a/linux/installer/common/psw-dcap/BOM_install/libsgx-aesm-launch-plugin.txt b/linux/installer/common/psw-dcap/BOM_install/libsgx-aesm-launch-plugin.txt new file mode 100644 index 000000000..a425f58fa --- /dev/null +++ b/linux/installer/common/psw-dcap/BOM_install/libsgx-aesm-launch-plugin.txt @@ -0,0 +1,3 @@ +DeliveryName InstallName FileCheckSum FileFeature FileOwner +/build/linux/bundles/lible_launch_service_bundle.so /aesm/bundles/lible_launch_service_bundle.so 0 main STP +/psw/ae/aesm_service/data/white_list_cert_to_be_verify.bin /aesm/data/white_list_cert_to_be_verify.bin 0 main STP \ No newline at end of file diff --git a/linux/installer/common/psw-dcap/BOM_install/libsgx-aesm-pce-plugin.txt b/linux/installer/common/psw-dcap/BOM_install/libsgx-aesm-pce-plugin.txt new file mode 100644 index 000000000..4278189be --- /dev/null +++ b/linux/installer/common/psw-dcap/BOM_install/libsgx-aesm-pce-plugin.txt @@ -0,0 +1,2 @@ +DeliveryName InstallName FileCheckSum FileFeature FileOwner +/build/linux/bundles/libpce_service_bundle.so /aesm/bundles/libpce_service_bundle.so 0 main STP \ No newline at end of file diff --git a/linux/installer/common/psw-dcap/BOM_install/libsgx-aesm-quote-ex-plugin.txt b/linux/installer/common/psw-dcap/BOM_install/libsgx-aesm-quote-ex-plugin.txt new file mode 100644 index 000000000..b3fc6fefc --- /dev/null +++ b/linux/installer/common/psw-dcap/BOM_install/libsgx-aesm-quote-ex-plugin.txt @@ -0,0 +1,2 @@ +DeliveryName InstallName FileCheckSum FileFeature FileOwner +/build/linux/bundles/libquote_ex_service_bundle.so /aesm/bundles/libquote_ex_service_bundle.so 0 main STP \ No newline at end of file diff --git a/linux/installer/common/psw-dcap/BOM_install/libsgx-dcap-default-qpl-devel.txt b/linux/installer/common/psw-dcap/BOM_install/libsgx-dcap-default-qpl-devel.txt new file mode 100644 index 000000000..46a874bc5 --- /dev/null +++ b/linux/installer/common/psw-dcap/BOM_install/libsgx-dcap-default-qpl-devel.txt @@ -0,0 +1 @@ +DeliveryName InstallName FileCheckSum FileFeature FileOwner diff --git a/linux/installer/common/psw-dcap/BOM_install/libsgx-dcap-default-qpl.txt b/linux/installer/common/psw-dcap/BOM_install/libsgx-dcap-default-qpl.txt new file mode 100644 index 000000000..88197ec66 --- /dev/null +++ b/linux/installer/common/psw-dcap/BOM_install/libsgx-dcap-default-qpl.txt @@ -0,0 +1,4 @@ +DeliveryName InstallName FileCheckSum FileFeature FileOwner +/external/dcap_source/QuoteGeneration/build/linux/libdcap_quoteprov.so /lib/libdcap_quoteprov.so 0 main STP +/external/dcap_source/QuoteGeneration/build/linux/libsgx_default_qcnl_wrapper.so /lib/libsgx_default_qcnl_wrapper.so 0 main STP +/external/dcap_source/QuoteGeneration/qcnl/linux/sgx_default_qcnl.conf /etc/sgx_default_qcnl.conf 0 main STP diff --git a/linux/installer/common/psw-dcap/BOM_install/libsgx-dcap-ql-devel.txt b/linux/installer/common/psw-dcap/BOM_install/libsgx-dcap-ql-devel.txt new file mode 100644 index 000000000..51a2c211e --- /dev/null +++ b/linux/installer/common/psw-dcap/BOM_install/libsgx-dcap-ql-devel.txt @@ -0,0 +1,2 @@ +DeliveryName InstallName FileCheckSum FileFeature FileOwner +/external/dcap_source/QuoteGeneration/quote_wrapper/ql/inc/sgx_dcap_ql_wrapper.h /include/sgx_dcap_ql_wrapper.h 0 main STP diff --git a/linux/installer/common/psw-dcap/BOM_install/libsgx-dcap-ql.txt b/linux/installer/common/psw-dcap/BOM_install/libsgx-dcap-ql.txt new file mode 100644 index 000000000..ed03036c3 --- /dev/null +++ b/linux/installer/common/psw-dcap/BOM_install/libsgx-dcap-ql.txt @@ -0,0 +1,2 @@ +DeliveryName InstallName FileCheckSum FileFeature FileOwner +/external/dcap_source/QuoteGeneration/build/linux/libsgx_dcap_ql.so /lib/libsgx_dcap_ql.so 0 main STP diff --git a/linux/installer/common/psw-dcap/BOM_install/libsgx-dcap-quote-verify-devel.txt b/linux/installer/common/psw-dcap/BOM_install/libsgx-dcap-quote-verify-devel.txt new file mode 100644 index 000000000..4b3363f6f --- /dev/null +++ b/linux/installer/common/psw-dcap/BOM_install/libsgx-dcap-quote-verify-devel.txt @@ -0,0 +1,3 @@ +DeliveryName InstallName FileCheckSum FileFeature FileOwner +/external/dcap_source/QuoteVerification/dcap_quoteverify/inc/sgx_dcap_quoteverify.h /include/sgx_dcap_quoteverify.h 0 main STP +/external/dcap_source/QuoteVerification/QvE/Include/sgx_qve_header.h /include/sgx_qve_header.h 0 main STP diff --git a/linux/installer/common/psw-dcap/BOM_install/libsgx-dcap-quote-verify.txt b/linux/installer/common/psw-dcap/BOM_install/libsgx-dcap-quote-verify.txt new file mode 100644 index 000000000..f46a51fa1 --- /dev/null +++ b/linux/installer/common/psw-dcap/BOM_install/libsgx-dcap-quote-verify.txt @@ -0,0 +1,2 @@ +DeliveryName InstallName FileCheckSum FileFeature FileOwner +/external/dcap_source/QuoteGeneration/build/linux/libsgx_dcap_quoteverify.so /lib/libsgx_dcap_quoteverify.so 0 main STP diff --git a/linux/installer/common/psw-dcap/BOM_install/libsgx-enclave-common-devel.txt b/linux/installer/common/psw-dcap/BOM_install/libsgx-enclave-common-devel.txt new file mode 100644 index 000000000..e0c0e1225 --- /dev/null +++ b/linux/installer/common/psw-dcap/BOM_install/libsgx-enclave-common-devel.txt @@ -0,0 +1,2 @@ +DeliveryName InstallName FileCheckSum FileFeature FileOwner +/psw/enclave_common/sgx_enclave_common.h /include/sgx_enclave_common.h 0 main STP diff --git a/linux/installer/common/psw-dcap/BOM_install/libsgx-enclave-common.txt b/linux/installer/common/psw-dcap/BOM_install/libsgx-enclave-common.txt new file mode 100644 index 000000000..eacb6d25f --- /dev/null +++ b/linux/installer/common/psw-dcap/BOM_install/libsgx-enclave-common.txt @@ -0,0 +1,4 @@ +DeliveryName InstallName FileCheckSum FileFeature FileOwner +/build/linux/libsgx_enclave_common.so /lib/libsgx_enclave_common.so 0 main STP +/linux/installer/common/psw-dcap/91-sgx-enclave.rules /etc/udev/rules.d/91-sgx-enclave.rules 0 main STP +/linux/installer/common/psw-dcap/remount-dev-exec.service /usr/lib/systemd/system/remount-dev-exec.service 0 main STP diff --git a/linux/installer/common/psw-dcap/BOM_install/libsgx-epid-devel.txt b/linux/installer/common/psw-dcap/BOM_install/libsgx-epid-devel.txt new file mode 100644 index 000000000..5a0d886ab --- /dev/null +++ b/linux/installer/common/psw-dcap/BOM_install/libsgx-epid-devel.txt @@ -0,0 +1,2 @@ +DeliveryName InstallName FileCheckSum FileFeature FileOwner +/common/inc/sgx_uae_epid.h /include/sgx_uae_epid.h 0 main STP \ No newline at end of file diff --git a/linux/installer/common/psw-dcap/BOM_install/libsgx-epid.txt b/linux/installer/common/psw-dcap/BOM_install/libsgx-epid.txt new file mode 100644 index 000000000..0b6f4c6a7 --- /dev/null +++ b/linux/installer/common/psw-dcap/BOM_install/libsgx-epid.txt @@ -0,0 +1,2 @@ +DeliveryName InstallName FileCheckSum FileFeature FileOwner +/build/linux/libsgx_epid.so /lib/libsgx_epid.so 0 main STP diff --git a/linux/installer/common/psw-dcap/BOM_install/libsgx-headers.txt b/linux/installer/common/psw-dcap/BOM_install/libsgx-headers.txt new file mode 100644 index 000000000..a77cbcc3f --- /dev/null +++ b/linux/installer/common/psw-dcap/BOM_install/libsgx-headers.txt @@ -0,0 +1,13 @@ +DeliveryName InstallName FileCheckSum FileFeature FileOwner +/common/inc/sgx_attributes.h /include/sgx_attributes.h 0 main STP +/common/inc/sgx_defs.h /include/sgx_defs.h 0 main STP +/common/inc/sgx_eid.h /include/sgx_eid.h 0 main STP +/common/inc/sgx_error.h /include/sgx_error.h 0 main STP +/common/inc/sgx_report.h /include/sgx_report.h main STP +/common/inc/sgx_key.h /include/sgx_key.h 0 main STP +/common/inc/sgx_quote.h /include/sgx_quote.h 0 main STP +/common/inc/sgx_urts.h /include/sgx_urts.h 0 main STP +/external/dcap_source/QuoteGeneration/quote_wrapper/common/inc/sgx_ql_lib_common.h /include/sgx_ql_lib_common.h 0 main STP +/external/dcap_source/QuoteGeneration/quote_wrapper/common/inc/sgx_quote_3.h /include/sgx_quote_3.h 0 main STP +/external/dcap_source/QuoteGeneration/quote_wrapper/common/inc/sgx_ql_quote.h /include/sgx_ql_quote.h 0 main STP +/external/dcap_source/QuoteGeneration/pce_wrapper/inc/sgx_pce.h /include/sgx_pce.h 0 main STP diff --git a/linux/installer/common/psw-dcap/BOM_install/libsgx-launch-devel.txt b/linux/installer/common/psw-dcap/BOM_install/libsgx-launch-devel.txt new file mode 100644 index 000000000..c707f0812 --- /dev/null +++ b/linux/installer/common/psw-dcap/BOM_install/libsgx-launch-devel.txt @@ -0,0 +1,2 @@ +DeliveryName InstallName FileCheckSum FileFeature FileOwner +/common/inc/sgx_uae_launch.h /include/sgx_uae_launch.h 0 main STP \ No newline at end of file diff --git a/linux/installer/common/psw-dcap/BOM_install/libsgx-launch.txt b/linux/installer/common/psw-dcap/BOM_install/libsgx-launch.txt new file mode 100644 index 000000000..f4c1a754d --- /dev/null +++ b/linux/installer/common/psw-dcap/BOM_install/libsgx-launch.txt @@ -0,0 +1,2 @@ +DeliveryName InstallName FileCheckSum FileFeature FileOwner +/build/linux/libsgx_launch.so /lib/libsgx_launch.so 0 main STP diff --git a/linux/installer/common/psw-dcap/BOM_install/libsgx-pce-logic.txt b/linux/installer/common/psw-dcap/BOM_install/libsgx-pce-logic.txt new file mode 100644 index 000000000..2abc37f16 --- /dev/null +++ b/linux/installer/common/psw-dcap/BOM_install/libsgx-pce-logic.txt @@ -0,0 +1,2 @@ +DeliveryName InstallName FileCheckSum FileFeature FileOwner +/external/dcap_source/QuoteGeneration/build/linux/libsgx_pce_logic.so /lib/libsgx_pce_logic.so 0 main STP diff --git a/linux/installer/common/psw-dcap/BOM_install/libsgx-qe3-logic.txt b/linux/installer/common/psw-dcap/BOM_install/libsgx-qe3-logic.txt new file mode 100644 index 000000000..30f2d3def --- /dev/null +++ b/linux/installer/common/psw-dcap/BOM_install/libsgx-qe3-logic.txt @@ -0,0 +1,3 @@ +DeliveryName InstallName FileCheckSum FileFeature FileOwner +/external/dcap_source/QuoteGeneration/build/linux/libsgx_qe3_logic.so /lib/libsgx_qe3_logic.so 0 main STP + diff --git a/linux/installer/common/psw-dcap/BOM_install/libsgx-quote-ex-devel.txt b/linux/installer/common/psw-dcap/BOM_install/libsgx-quote-ex-devel.txt new file mode 100644 index 000000000..6a3343375 --- /dev/null +++ b/linux/installer/common/psw-dcap/BOM_install/libsgx-quote-ex-devel.txt @@ -0,0 +1,2 @@ +DeliveryName InstallName FileCheckSum FileFeature FileOwner +/common/inc/sgx_uae_quote_ex.h /include/sgx_uae_quote_ex.h 0 main STP diff --git a/linux/installer/common/psw-dcap/BOM_install/libsgx-quote-ex.txt b/linux/installer/common/psw-dcap/BOM_install/libsgx-quote-ex.txt new file mode 100644 index 000000000..90d3db85d --- /dev/null +++ b/linux/installer/common/psw-dcap/BOM_install/libsgx-quote-ex.txt @@ -0,0 +1,2 @@ +DeliveryName InstallName FileCheckSum FileFeature FileOwner +/build/linux/libsgx_quote_ex.so /lib/libsgx_quote_ex.so 0 main STP diff --git a/linux/installer/common/psw-dcap/BOM_install/libsgx-ra-network-devel.txt b/linux/installer/common/psw-dcap/BOM_install/libsgx-ra-network-devel.txt new file mode 100644 index 000000000..a6866c11c --- /dev/null +++ b/linux/installer/common/psw-dcap/BOM_install/libsgx-ra-network-devel.txt @@ -0,0 +1,4 @@ +DeliveryName InstallName FileCheckSum FileFeature FileOwner +/external/dcap_source/tools/SGXPlatformRegistration/include/MPNetwork.h /include/MPNetwork.h 0 main STP +/external/dcap_source/tools/SGXPlatformRegistration/include/MPNetworkDefs.h /include/MPNetworkDefs.h 0 main STP +/external/dcap_source/tools/SGXPlatformRegistration/include/c_wrapper/mp_network.h /include/mp_network.h 0 main STP diff --git a/linux/installer/common/psw-dcap/BOM_install/libsgx-ra-network.txt b/linux/installer/common/psw-dcap/BOM_install/libsgx-ra-network.txt new file mode 100644 index 000000000..2f260bd5a --- /dev/null +++ b/linux/installer/common/psw-dcap/BOM_install/libsgx-ra-network.txt @@ -0,0 +1,2 @@ +DeliveryName InstallName FileCheckSum FileFeature FileOwner +/external/dcap_source/tools/SGXPlatformRegistration/build/lib64/libmpa_network.so /lib/libmpa_network.so 0 main STP diff --git a/linux/installer/common/psw-dcap/BOM_install/libsgx-ra-uefi-devel.txt b/linux/installer/common/psw-dcap/BOM_install/libsgx-ra-uefi-devel.txt new file mode 100644 index 000000000..ce5aee6ba --- /dev/null +++ b/linux/installer/common/psw-dcap/BOM_install/libsgx-ra-uefi-devel.txt @@ -0,0 +1,4 @@ +DeliveryName InstallName FileCheckSum FileFeature FileOwner +/external/dcap_source/tools/SGXPlatformRegistration/include/MPUefi.h /include/MPUefi.h 0 main STP +/external/dcap_source/tools/SGXPlatformRegistration/include/MultiPackageDefs.h /include/MultiPackageDefs.h 0 main STP +/external/dcap_source/tools/SGXPlatformRegistration/include/c_wrapper/mp_uefi.h /include/mp_uefi.h 0 main STP diff --git a/linux/installer/common/psw-dcap/BOM_install/libsgx-ra-uefi.txt b/linux/installer/common/psw-dcap/BOM_install/libsgx-ra-uefi.txt new file mode 100644 index 000000000..63356491e --- /dev/null +++ b/linux/installer/common/psw-dcap/BOM_install/libsgx-ra-uefi.txt @@ -0,0 +1,2 @@ +DeliveryName InstallName FileCheckSum FileFeature FileOwner +/external/dcap_source/tools/SGXPlatformRegistration/build/lib64/libmpa_uefi.so /lib/libmpa_uefi.so 0 main STP diff --git a/linux/installer/common/psw-dcap/BOM_install/libsgx-uae-service.txt b/linux/installer/common/psw-dcap/BOM_install/libsgx-uae-service.txt new file mode 100644 index 000000000..f75ab178b --- /dev/null +++ b/linux/installer/common/psw-dcap/BOM_install/libsgx-uae-service.txt @@ -0,0 +1,2 @@ +DeliveryName InstallName FileCheckSum FileFeature FileOwner +/build/linux/libsgx_uae_service.so /lib/libsgx_uae_service.so 0 main STP diff --git a/linux/installer/common/psw-dcap/BOM_install/libsgx-urts.txt b/linux/installer/common/psw-dcap/BOM_install/libsgx-urts.txt new file mode 100644 index 000000000..ad7c7c37c --- /dev/null +++ b/linux/installer/common/psw-dcap/BOM_install/libsgx-urts.txt @@ -0,0 +1,2 @@ +DeliveryName InstallName FileCheckSum FileFeature FileOwner +/build/linux/libsgx_urts.so /lib/libsgx_urts.so 0 main STP diff --git a/linux/installer/common/psw-dcap/BOM_install/sgx-aesm-service.txt b/linux/installer/common/psw-dcap/BOM_install/sgx-aesm-service.txt new file mode 100644 index 000000000..2da545006 --- /dev/null +++ b/linux/installer/common/psw-dcap/BOM_install/sgx-aesm-service.txt @@ -0,0 +1,14 @@ +DeliveryName InstallName FileCheckSum FileFeature FileOwner +/build/linux/bundles/liblinux_network_service_bundle.so /aesm/bundles/liblinux_network_service_bundle.so 0 main STP +/build/linux/libipc.so /aesm/libipc.so 0 main STP +/build/linux/liboal.so /aesm/liboal.so 0 main STP +/build/linux/libutils.so /aesm/libutils.so 0 main STP +/build/linux/liburts_internal.so /aesm/liburts_internal.so 0 main STP +/build/linux/libCppMicroServices.so.4.0.0 /aesm/libCppMicroServices.so.4.0.0 0 main STP +/build/linux/aesmd.conf /aesm/aesmd.conf 0 main STP +/build/linux/aesmd.service /aesm/aesmd.service 0 main STP +/build/linux/aesm_service /aesm/aesm_service 0 main STP +/psw/ae/aesm_service/config/network/aesmd.conf /aesm/conf/aesmd.conf 0 main STP +/linux/installer/common/psw-dcap/linksgx.sh /aesm/linksgx.sh 0 main STP +/linux/installer/common/psw-dcap/startup.sh /startup.sh 0 main STP +/linux/installer/common/psw-dcap/cleanup.sh /cleanup.sh 0 main STP diff --git a/linux/installer/common/psw-dcap/BOM_install/sgx-dcap-pccs.txt b/linux/installer/common/psw-dcap/BOM_install/sgx-dcap-pccs.txt new file mode 100644 index 000000000..bc91befbf --- /dev/null +++ b/linux/installer/common/psw-dcap/BOM_install/sgx-dcap-pccs.txt @@ -0,0 +1,75 @@ +DeliveryName InstallName FileCheckSum FileFeature FileOwner +/external/dcap_source/QuoteGeneration/pccs/config/default.json /config/default.json 0 main STP +/external/dcap_source/QuoteGeneration/pccs/constants/index.js /constants/index.js 0 main STP +/external/dcap_source/QuoteGeneration/pccs/constants/pccs_status_code.js /constants/pccs_status_code.js 0 main STP +/external/dcap_source/QuoteGeneration/pccs/controllers/identityController.js /controllers/identityController.js 0 main STP +/external/dcap_source/QuoteGeneration/pccs/controllers/index.js /controllers/index.js 0 main STP +/external/dcap_source/QuoteGeneration/pccs/controllers/pckcertController.js /controllers/pckcertController.js 0 main STP +/external/dcap_source/QuoteGeneration/pccs/controllers/pckcrlController.js /controllers/pckcrlController.js 0 main STP +/external/dcap_source/QuoteGeneration/pccs/controllers/platformCollateralController.js /controllers/platformCollateralController.js 0 main STP +/external/dcap_source/QuoteGeneration/pccs/controllers/platformsController.js /controllers/platformsController.js 0 main STP +/external/dcap_source/QuoteGeneration/pccs/controllers/refreshController.js /controllers/refreshController.js 0 main STP +/external/dcap_source/QuoteGeneration/pccs/controllers/rootcacrlController.js /controllers/rootcacrlController.js 0 main STP +/external/dcap_source/QuoteGeneration/pccs/controllers/tcbinfoController.js /controllers/tcbinfoController.js 0 main STP +/external/dcap_source/QuoteGeneration/pccs/controllers/crlController.js /controllers/crlController.js 0 main STP +/external/dcap_source/QuoteGeneration/pccs/dao/models/fmspc_tcbs.js /dao/models/fmspc_tcbs.js 0 main STP +/external/dcap_source/QuoteGeneration/pccs/dao/models/index.js /dao/models/index.js 0 main STP +/external/dcap_source/QuoteGeneration/pccs/dao/models/pck_cert.js /dao/models/pck_cert.js 0 main STP +/external/dcap_source/QuoteGeneration/pccs/dao/models/pck_certchain.js /dao/models/pck_certchain.js 0 main STP +/external/dcap_source/QuoteGeneration/pccs/dao/models/pck_crl.js /dao/models/pck_crl.js 0 main STP +/external/dcap_source/QuoteGeneration/pccs/dao/models/pcs_certificates.js /dao/models/pcs_certificates.js 0 main STP +/external/dcap_source/QuoteGeneration/pccs/dao/models/pcs_version.js /dao/models/pcs_version.js 0 main STP +/external/dcap_source/QuoteGeneration/pccs/dao/models/platform_tcbs.js /dao/models/platform_tcbs.js 0 main STP +/external/dcap_source/QuoteGeneration/pccs/dao/models/platforms_registered.js /dao/models/platforms_registered.js 0 main STP +/external/dcap_source/QuoteGeneration/pccs/dao/models/platforms.js /dao/models/platforms.js 0 main STP +/external/dcap_source/QuoteGeneration/pccs/dao/models/enclave_identities.js /dao/models/enclave_identities.js 0 main STP +/external/dcap_source/QuoteGeneration/pccs/dao/models/crl_cache.js /dao/models/crl_cache.js 0 main STP +/external/dcap_source/QuoteGeneration/pccs/dao/fmspcTcbDao.js /dao/fmspcTcbDao.js 0 main STP +/external/dcap_source/QuoteGeneration/pccs/dao/pckCertchainDao.js /dao/pckCertchainDao.js 0 main STP +/external/dcap_source/QuoteGeneration/pccs/dao/pckcertDao.js /dao/pckcertDao.js 0 main STP +/external/dcap_source/QuoteGeneration/pccs/dao/pckcrlDao.js /dao/pckcrlDao.js 0 main STP +/external/dcap_source/QuoteGeneration/pccs/dao/pcsCertificatesDao.js /dao/pcsCertificatesDao.js 0 main STP +/external/dcap_source/QuoteGeneration/pccs/dao/pcsVersionDao.js /dao/pcsVersionDao.js 0 main STP +/external/dcap_source/QuoteGeneration/pccs/dao/platformsDao.js /dao/platformsDao.js 0 main STP +/external/dcap_source/QuoteGeneration/pccs/dao/platformsRegDao.js /dao/platformsRegDao.js 0 main STP +/external/dcap_source/QuoteGeneration/pccs/dao/platformTcbsDao.js /dao/platformTcbsDao.js 0 main STP +/external/dcap_source/QuoteGeneration/pccs/dao/enclaveIdentityDao.js /dao/enclaveIdentityDao.js 0 main STP +/external/dcap_source/QuoteGeneration/pccs/dao/crlCacheDao.js /dao/crlCacheDao.js 0 main STP +/external/dcap_source/tools/PCKCertSelection/out/libPCKCertSelection.so /lib/libPCKCertSelection.so 0 main STP +/external/dcap_source/QuoteGeneration/pccs/lib_wrapper/pcklib_wrapper.js /lib_wrapper/pcklib_wrapper.js 0 main STP +/external/dcap_source/QuoteGeneration/pccs/middleware/auth.js /middleware/auth.js 0 main STP +/external/dcap_source/QuoteGeneration/pccs/middleware/error.js /middleware/error.js 0 main STP +/external/dcap_source/QuoteGeneration/pccs/middleware/addRequestId.js /middleware/addRequestId.js 0 main STP +/external/dcap_source/QuoteGeneration/pccs/migrations/00_db_initialize.up.sql /migrations/00_db_initialize.up.sql 0 main STP +/external/dcap_source/QuoteGeneration/pccs/migrations/01_db_version_1.js /migrations/01_db_version_1.js 0 main STP +/external/dcap_source/QuoteGeneration/pccs/migrations/02_db_version_2.js /migrations/02_db_version_2.js 0 main STP +/external/dcap_source/QuoteGeneration/pccs/pcs_client/pcs_client.js /pcs_client/pcs_client.js 0 main STP +/external/dcap_source/QuoteGeneration/pccs/routes/index.js /routes/index.js 0 main STP +/external/dcap_source/QuoteGeneration/pccs/services/identityService.js /services/identityService.js 0 main STP +/external/dcap_source/QuoteGeneration/pccs/services/index.js /services/index.js 0 main STP +/external/dcap_source/QuoteGeneration/pccs/services/pccs_schemas.js /services/pccs_schemas.js 0 main STP +/external/dcap_source/QuoteGeneration/pccs/services/pckcertService.js /services/pckcertService.js 0 main STP +/external/dcap_source/QuoteGeneration/pccs/services/pckcrlService.js /services/pckcrlService.js 0 main STP +/external/dcap_source/QuoteGeneration/pccs/services/platformCollateralService.js /services/platformCollateralService.js 0 main STP +/external/dcap_source/QuoteGeneration/pccs/services/platformsRegService.js /services/platformsRegService.js 0 main STP +/external/dcap_source/QuoteGeneration/pccs/services/platformsService.js /services/platformsService.js 0 main STP +/external/dcap_source/QuoteGeneration/pccs/services/refreshService.js /services/refreshService.js 0 main STP +/external/dcap_source/QuoteGeneration/pccs/services/rootcacrlService.js /services/rootcacrlService.js 0 main STP +/external/dcap_source/QuoteGeneration/pccs/services/tcbinfoService.js /services/tcbinfoService.js 0 main STP +/external/dcap_source/QuoteGeneration/pccs/services/crlService.js /services/crlService.js 0 main STP +/external/dcap_source/QuoteGeneration/pccs/services/caching_modes/cachingMode.js /services/caching_modes/cachingMode.js 0 main STP +/external/dcap_source/QuoteGeneration/pccs/services/caching_modes/cachingModeManager.js /services/caching_modes/cachingModeManager.js 0 main STP +/external/dcap_source/QuoteGeneration/pccs/services/logic/commonCacheLogic.js /services/logic/commonCacheLogic.js 0 main STP +/external/dcap_source/QuoteGeneration/pccs/services/logic/qvCollateralLogic.js /services/logic/qvCollateralLogic.js 0 main STP +/external/dcap_source/QuoteGeneration/pccs/utils/Logger.js /utils/Logger.js 0 main STP +/external/dcap_source/QuoteGeneration/pccs/utils/PccsError.js /utils/PccsError.js 0 main STP +/external/dcap_source/QuoteGeneration/pccs/utils/apputil.js /utils/apputil.js 0 main STP +/external/dcap_source/QuoteGeneration/pccs/x509/x509.js /x509/x509.js 0 main STP +/external/dcap_source/QuoteGeneration/pccs/install.sh /install.sh 0 main STP +/external/dcap_source/QuoteGeneration/pccs/package.json /package.json 0 main STP +/external/dcap_source/QuoteGeneration/pccs/npm-shrinkwrap.json /npm-shrinkwrap.json 0 main STP +/external/dcap_source/QuoteGeneration/pccs/pccs_server.js /pccs_server.js 0 main STP +/external/dcap_source/QuoteGeneration/pccs/pccs.service /pccs.service 0 main STP +/external/dcap_source/QuoteGeneration/pccs/startup.sh /startup.sh 0 main STP +/external/dcap_source/QuoteGeneration/pccs/cleanup.sh /cleanup.sh 0 main STP +/external/dcap_source/QuoteGeneration/pccs/README.md /README.md 0 main STP diff --git a/linux/installer/common/psw-dcap/BOM_install/sgx-pck-id-retrieval-tool.txt b/linux/installer/common/psw-dcap/BOM_install/sgx-pck-id-retrieval-tool.txt new file mode 100644 index 000000000..600fe91a3 --- /dev/null +++ b/linux/installer/common/psw-dcap/BOM_install/sgx-pck-id-retrieval-tool.txt @@ -0,0 +1,5 @@ +DeliveryName InstallName FileCheckSum FileFeature FileOwner +/external/dcap_source/tools/PCKRetrievalTool/network_setting.conf /network_setting.conf 0 main STP +/external/dcap_source/tools/PCKRetrievalTool/PCKIDRetrievalTool /PCKIDRetrievalTool 0 main STP +/external/dcap_source/tools/PCKRetrievalTool/README.txt /README.txt 0 main STP +/external/dcap_source/tools/PCKRetrievalTool/License.txt /License.txt 0 main STP diff --git a/linux/installer/common/psw-dcap/BOM_install/sgx-ra-service.txt b/linux/installer/common/psw-dcap/BOM_install/sgx-ra-service.txt new file mode 100644 index 000000000..3521a03f1 --- /dev/null +++ b/linux/installer/common/psw-dcap/BOM_install/sgx-ra-service.txt @@ -0,0 +1,8 @@ +DeliveryName InstallName FileCheckSum FileFeature FileOwner +/external/dcap_source/tools/SGXPlatformRegistration/build/bin/mpa_manage /mpa_manage 0 main STP +/external/dcap_source/tools/SGXPlatformRegistration/package/mpa_registration /mpa_registration 0 main STP +/external/dcap_source/tools/SGXPlatformRegistration/package/mpa_registration_tool.service /mpa_registration_tool.service 0 main STP +/external/dcap_source/tools/SGXPlatformRegistration/package/mpa_registration_tool.conf /mpa_registration_tool.conf 0 main STP +/external/dcap_source/tools/SGXPlatformRegistration/config/mpa_registration.conf /conf/mpa_registration.conf 0 main STP +/external/dcap_source/tools/SGXPlatformRegistration/package/startup.sh /startup.sh 0 main STP +/external/dcap_source/tools/SGXPlatformRegistration/package/cleanup.sh /cleanup.sh 0 main STP diff --git a/linux/installer/common/psw-dcap/BOM_source/psw-dcap-tarball.txt b/linux/installer/common/psw-dcap/BOM_source/psw-dcap-tarball.txt new file mode 100644 index 000000000..ceb1b72ad --- /dev/null +++ b/linux/installer/common/psw-dcap/BOM_source/psw-dcap-tarball.txt @@ -0,0 +1,19 @@ +DeliveryName InstallName FileCheckSum FileFeature FileOwner +/common /common 0 main STP +/external /external 0 main STP +/psw /psw 0 main STP +/sdk /sdk 0 main STP +/SampleCode /SampleCode 0 main STP +/buildenv.mk /buildenv.mk 0 main STP +/Makefile.psw_dcap /Makefile 0 main STP +/License.txt /License.txt 0 main STP +/README.md /README.md 0 main STP +/linux/installer/common/psw-dcap /linux/installer/common/psw-dcap 0 main STP +/linux/installer/common/sdk /linux/installer/common/sdk 0 main STP +/linux/installer/common/gen_source /linux/installer/common/gen_source 0 main STP +/linux/installer/common/licenses /linux/installer/common/licenses 0 main STP +/linux/installer/bin/build-installpkg.sh /linux/installer/bin/build-installpkg.sh 0 main STP +/linux/installer/bin/install-sgx-sdk.bin.tmpl /linux/installer/bin/install-sgx-sdk.bin.tmpl 0 main STP +/linux/installer/rpm/psw-dcap/build.sh /linux/installer/rpm/psw-dcap/build.sh 0 main STP +/linux/installer/rpm/psw-dcap/clean.sh /linux/installer/rpm/psw-dcap/clean.sh 0 main STP +/linux/installer/rpm/psw-dcap/psw-dcap.spec.tmpl /linux/installer/rpm/psw-dcap/psw-dcap.spec.tmpl 0 main STP diff --git a/linux/installer/common/psw-dcap/Makefile b/linux/installer/common/psw-dcap/Makefile new file mode 100644 index 000000000..4f05c94dc --- /dev/null +++ b/linux/installer/common/psw-dcap/Makefile @@ -0,0 +1,361 @@ +# +# 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 installConfig + +ACQUIRE_PSW_VERSION = $(shell awk \ + '$$2 ~ /$1/ { print substr($$3, 2, length($$3) - 2); }' \ + $(SRCDIR)/common/inc/internal/se_version.h) + +ACQUIRE_DCAP_VERSION = $(shell awk \ + '$$2 ~ /$1/ { print substr($$3, 2, length($$3) - 2); }' \ + $(SRCDIR)/external/dcap_source/QuoteGeneration/common/inc/internal/se_version.h) + +LE_FULL_VER:= $(call ACQUIRE_PSW_VERSION,LE_VERSION) +LE_MAJOR_VER:=$(word 1,$(subst ., ,$(LE_FULL_VER))) +QE_FULL_VER:= $(call ACQUIRE_PSW_VERSION,QE_VERSION) +QE_MAJOR_VER:=$(word 1,$(subst ., ,$(QE_FULL_VER))) +PCE_FULL_VER:= $(call ACQUIRE_PSW_VERSION,PCE_VERSION) +PCE_MAJOR_VER:=$(word 1,$(subst ., ,$(PCE_FULL_VER))) +PVE_FULL_VER:= $(call ACQUIRE_PSW_VERSION,PVE_VERSION) +PVE_MAJOR_VER:=$(word 1,$(subst ., ,$(PVE_FULL_VER))) +IDE_FULL_VER:= $(call ACQUIRE_DCAP_VERSION,IDE_VERSION) +IDE_MAJOR_VER:=$(word 1,$(subst ., ,$(IDE_FULL_VER))) +QE3_FULL_VER:= $(call ACQUIRE_DCAP_VERSION,QE3_VERSION) +QE3_MAJOR_VER:=$(word 1,$(subst ., ,$(QE3_FULL_VER))) +QVE_FULL_VER:= $(call ACQUIRE_DCAP_VERSION,QVE_VERSION) +QVE_MAJOR_VER:=$(word 1,$(subst ., ,$(QVE_FULL_VER))) +ECL_FULL_VER:= $(call ACQUIRE_PSW_VERSION,ENCLAVE_COMMON_VERSION) +ECL_MAJOR_VER:=$(word 1,$(subst ., ,$(ECL_FULL_VER))) +URTS_FULL_VER:= $(call ACQUIRE_PSW_VERSION,URTS_VERSION) +URTS_MAJOR_VER:=$(word 1,$(subst ., ,$(URTS_FULL_VER))) +UAE_SERVICE_FULL_VER:= $(call ACQUIRE_PSW_VERSION,UAE_SERVICE_VERSION) +UAE_SERVICE_MAJOR_VER:=$(word 1,$(subst ., ,$(UAE_SERVICE_FULL_VER))) +EPID_FULL_VER:= $(call ACQUIRE_PSW_VERSION,EPID_VERSION) +EPID_MAJOR_VER:=$(word 1,$(subst ., ,$(EPID_FULL_VER))) +LAUNCH_FULL_VER:= $(call ACQUIRE_PSW_VERSION,LAUNCH_VERSION) +LAUNCH_MAJOR_VER:=$(word 1,$(subst ., ,$(LAUNCH_FULL_VER))) +QUOTE_EX_FULL_VER:= $(call ACQUIRE_PSW_VERSION,QUOTE_EX_VERSION) +QUOTE_EX_MAJOR_VER:=$(word 1,$(subst ., ,$(QUOTE_EX_FULL_VER))) +QPL_FULL_VER:= $(call ACQUIRE_DCAP_VERSION,DEFAULT_QPL_VERSION) +QPL_MAJOR_VER:=$(word 1,$(subst ., ,$(QPL_FULL_VER))) +QCNL_FULL_VER:= $(call ACQUIRE_DCAP_VERSION,DEFAULT_QPL_VERSION) +QCNL_MAJOR_VER:=$(word 1,$(subst ., ,$(QCNL_FULL_VER))) +QL_FULL_VER:= $(call ACQUIRE_DCAP_VERSION,QUOTE_LOADER_VERSION) +QL_MAJOR_VER:=$(word 1,$(subst ., ,$(QL_FULL_VER))) +QVL_FULL_VER:= $(call ACQUIRE_DCAP_VERSION,QUOTE_VERIFIER_VERSION) +QVL_MAJOR_VER:=$(word 1,$(subst ., ,$(QVL_FULL_VER))) +RAN_FULL_VER:= $(call ACQUIRE_DCAP_VERSION,STRFILEVER) +RAN_MAJOR_VER:=$(word 1,$(subst ., ,$(RAN_FULL_VER))) +RAU_FULL_VER:= $(call ACQUIRE_DCAP_VERSION,STRFILEVER) +RAU_MAJOR_VER:=$(word 1,$(subst ., ,$(RAU_FULL_VER))) + +CUR_PATH:=$(realpath $(dir $(lastword $(MAKEFILE_LIST)))) +BOM_PATH:=$(CUR_PATH)/BOM_install +GEN_SCRIPT:=$(realpath $(CUR_PATH)/../gen_source/copy_source.py) + +PACKAGE_ROOT_PATH:=$(SRCDIR)/build/pkgroot + +USR_LIB_PATH:=/usr/$(notdir $(shell gcc -print-multi-os-directory))/$(shell dpkg-architecture -qDEB_HOST_MULTIARCH 2> /dev/null) +USR_INC_PATH=/usr/$(INC_DIR) +VAR_OPT_PATH:=/var/opt/aesmd + +# Support systemd by default(for Fedora build environment) +AESMD_CONF=aesmd.service +AESMD_CONF_DEL=aesmd.conf +AESMD_CONF_PATH=$(if $(wildcard /lib/systemd/system/.),/lib/systemd/system,/usr/lib/systemd/system) + +PCCS_CONF=pccs.service +PCCS_CONF_PATH=$(if $(wildcard /lib/systemd/system/.),/lib/systemd/system,/usr/lib/systemd/system) + +RAD_CONF=mpa_registration_tool.service +RAD_CONF_DEL=mpa_registration_tool.conf +RAD_CONF_PATH=$(if $(wildcard /lib/systemd/system/.),/lib/systemd/system,/usr/lib/systemd/system) + +TEST_COPYABLE = \( -d $1 -a -n "$$(shell ls -A $1 2> /dev/null)" \) + +define PRE_INSTALL_TEMPLATE +pre_$(1): | $(PACKAGE_ROOT_PATH) + python $(GEN_SCRIPT) --bom-file $(BOM_PATH)/$(1).txt \ + --src-path $(SRCDIR) --dst-path $$|/$(1) +endef + +define INSTALL_AESM_SERVICE_TEMPLATE +$(1): pre_$(1) | $(PACKAGE_ROOT_PATH) + install -d $$(shell readlink -m $(DESTDIR)/$$@) + test $(call TEST_COPYABLE,$$|/$$@/$(LIB_DIR)) && ( \ + install -d $$(shell readlink -m $(DESTDIR)/$$@/$(USR_LIB_PATH)) && \ + install $$|/$$@/$(LIB_DIR)/* $(DESTDIR)/$$@/$(USR_LIB_PATH) && \ + rm -fr $$|/$$@/$(LIB_DIR) ) ||: + test $(call TEST_COPYABLE,$$|/$$@/$(ETC_DIR)) && ( \ + install -d $$(shell readlink -m $(DESTDIR)/$$@/$(ETC_DIR)) && \ + cp -fr $$|/$$@/$(ETC_DIR)/* $(DESTDIR)/$$@/$(ETC_DIR) && \ + rm -fr $$|/$$@/$(ETC_DIR) ) ||: + test $(call TEST_COPYABLE,$$|/$$@/aesm/data) && ( \ + install -d $$(shell readlink -m $(DESTDIR)/$$@/$(VAR_OPT_PATH)) && \ + cp -fr $$|/$$@/aesm/data $(DESTDIR)/$$@/$(VAR_OPT_PATH) && \ + rm -fr $$|/$$@/aesm/data ) ||: + +post_$(1): $(1) | $(PACKAGE_ROOT_PATH) + test $(call TEST_COPYABLE,$$|/$$<) && ( \ + install -d $$(shell readlink -m $(DESTDIR)/$$ $(DESTDIR)/$(AESM_SERVICE_PACKAGE)/$(AESMD_CONF_PATH)/$(AESMD_CONF) + rm -f $(DESTDIR)/$(AESM_SERVICE_PACKAGE)/$(SGX_INSTALL_PATH)/$(AESM_SERVICE_PACKAGE)/aesm/$(AESMD_CONF) + rm -f $(DESTDIR)/$(AESM_SERVICE_PACKAGE)/$(SGX_INSTALL_PATH)/$(AESM_SERVICE_PACKAGE)/aesm/$(AESMD_CONF_DEL) + $(if $(wildcard $(DESTDIR)/$(AESM_SERVICE_PACKAGE)/$(SGX_INSTALL_PATH)/$(AESM_SERVICE_PACKAGE)/aesm/conf/*), \ + install -d $(shell readlink -m $(DESTDIR)/$(AESM_SERVICE_PACKAGE)/$(ETC_DIR)) && \ + cp -fr $(DESTDIR)/$(AESM_SERVICE_PACKAGE)/$(SGX_INSTALL_PATH)/$(AESM_SERVICE_PACKAGE)/aesm/conf/* \ + $(DESTDIR)/$(AESM_SERVICE_PACKAGE)/$(ETC_DIR) && \ + rm -fr $(DESTDIR)/$(AESM_SERVICE_PACKAGE)/$(SGX_INSTALL_PATH)/$(AESM_SERVICE_PACKAGE)/aesm/conf) + cd $(shell readlink -m $(DESTDIR)/$(AESM_ECDSA_PACKAGE)/$(SGX_INSTALL_PATH)/$(AESM_SERVICE_PACKAGE)/aesm) && \ + ln -fs $(shell readlink -m $(USR_LIB_PATH)/libsgx_qe3.signed.so.$(QE3_MAJOR_VER)) && \ + ln -fs $(shell readlink -m $(USR_LIB_PATH)/libsgx_qe3.signed.so) + cd $(shell readlink -m $(DESTDIR)/$(AESM_PCE_PACKAGE)/$(SGX_INSTALL_PATH)/$(AESM_SERVICE_PACKAGE)/aesm) && \ + ln -fs $(shell readlink -m $(USR_LIB_PATH)/libsgx_pce.signed.so.$(PCE_MAJOR_VER)) && \ + ln -fs $(shell readlink -m $(USR_LIB_PATH)/libsgx_pce.signed.so) && \ + ln -fs liburts_internal.so libsgx_urts.so + +PHONY+=install_$(DCAP_PCCS_PACKAGE) +install_$(DCAP_PCCS_PACKAGE): pre_$(DCAP_PCCS_PACKAGE) | $(PACKAGE_ROOT_PATH) + install -d $(shell readlink -m $(DESTDIR)/$(DCAP_PCCS_PACKAGE)/$(PCCS_CONF_PATH)) && \ + cp -f $|/$(DCAP_PCCS_PACKAGE)/$(PCCS_CONF) $(DESTDIR)/$(DCAP_PCCS_PACKAGE)/$(PCCS_CONF_PATH) && \ + rm -f $|/$(DCAP_PCCS_PACKAGE)/$(PCCS_CONF) + install -d $(shell readlink -m $(DESTDIR)/$(DCAP_PCCS_PACKAGE)/$(SGX_INSTALL_PATH)/$(DCAP_PCCS_PACKAGE)) && \ + cp -fr $|/$(DCAP_PCCS_PACKAGE)/* $(DESTDIR)/$(DCAP_PCCS_PACKAGE)/$(SGX_INSTALL_PATH)/$(DCAP_PCCS_PACKAGE) + +PHONY+=$(RA_SERVICE_PACKAGE) +$(RA_SERVICE_PACKAGE): pre_$(RA_SERVICE_PACKAGE) | $(PACKAGE_ROOT_PATH) + install -d $(shell readlink -m $(DESTDIR)/$@/$(SGX_INSTALL_PATH)/$@) && \ + cp -fr $|/$@/* $(DESTDIR)/$@/$(SGX_INSTALL_PATH)/$@ + +PHONY+=install_$(RA_SERVICE_PACKAGE) +install_$(RA_SERVICE_PACKAGE): $(RA_SERVICE_PACKAGE) + install -d $(shell readlink -m $(DESTDIR)/$ $(DESTDIR)/$ /dev/null +elif [ -d /etc/init/ ]; then + initctl reload-configuration + initctl stop aesmd +fi + +# Remove AESM user and group +userdel aesmd 2> /dev/null || true +groupdel aesmd 2> /dev/null || true + +# Keep the group if the driver still exists +if [ ! -c /dev/sgx/provision ]; then + groupdel sgx_prv 2> /dev/null || true +fi + +exit 0 diff --git a/linux/installer/common/psw-dcap/installConfig b/linux/installer/common/psw-dcap/installConfig new file mode 100644 index 000000000..9f99f0329 --- /dev/null +++ b/linux/installer/common/psw-dcap/installConfig @@ -0,0 +1,46 @@ +SGX_HEADERS_PACKAGE=libsgx-headers +URTS_PACKAGE=libsgx-urts +ENCLAVE_COMMON_PACKAGE=libsgx-enclave-common +ENCLAVE_COMMON_DEV_PACKAGE=libsgx-enclave-common-devel +EPID_PACKAGE=libsgx-epid +EPID_DEV_PACKAGE=libsgx-epid-devel +LAUNCH_PACKAGE=libsgx-launch +LAUNCH_DEV_PACKAGE=libsgx-launch-devel +QUOTE_EX_PACKAGE=libsgx-quote-ex +QUOTE_EX_DEV_PACKAGE=libsgx-quote-ex-devel +UAE_SERVICE_PACKAGE=libsgx-uae-service +AE_EPID_PACKAGE=libsgx-ae-epid +AE_LE_PACKAGE=libsgx-ae-le +AE_PCE_PACKAGE=libsgx-ae-pce +AESM_ECDSA_PACKAGE=libsgx-aesm-ecdsa-plugin +AESM_EPID_PACKAGE=libsgx-aesm-epid-plugin +AESM_LAUNCH_PACKAGE=libsgx-aesm-launch-plugin +AESM_PCE_PACKAGE=libsgx-aesm-pce-plugin +AESM_QUOTE_EX_PACKAGE=libsgx-aesm-quote-ex-plugin +AESM_SERVICE_PACKAGE=sgx-aesm-service + +AE_IDE_PACKAGE=libsgx-ae-id-enclave +AE_QE3_PACKAGE=libsgx-ae-qe3 +AE_QVE_PACKAGE=libsgx-ae-qve +QE3_LOGIC_PACKAGE=libsgx-qe3-logic +PCE_LOGIC_PACKAGE=libsgx-pce-logic +DCAP_QPL_PACKAGE=libsgx-dcap-default-qpl +DCAP_QPL_DEV_PACKAGE=libsgx-dcap-default-qpl-devel +DCAP_QL_PACKAGE=libsgx-dcap-ql +DCAP_QL_DEV_PACKAGE=libsgx-dcap-ql-devel +DCAP_QVL_PACKAGE=libsgx-dcap-quote-verify +DCAP_QVL_DEV_PACKAGE=libsgx-dcap-quote-verify-devel +DCAP_PCCS_PACKAGE=sgx-dcap-pccs + +PCK_ID_RETRIEVAL_TOOL_PACKAGE=sgx-pck-id-retrieval-tool +RA_NETWORK_PACKAGE=libsgx-ra-network +RA_NETWORK_DEV_PACKAGE=libsgx-ra-network-devel +RA_UEFI_PACKAGE=libsgx-ra-uefi +RA_UEFI_DEV_PACKAGE=libsgx-ra-uefi-devel +RA_SERVICE_PACKAGE=sgx-ra-service + +SGX_INSTALL_PATH=/opt/intel + +INC_DIR=include +LIB_DIR=lib +ETC_DIR=etc diff --git a/linux/installer/common/psw-dcap/linksgx.sh b/linux/installer/common/psw-dcap/linksgx.sh new file mode 100755 index 000000000..97536788e --- /dev/null +++ b/linux/installer/common/psw-dcap/linksgx.sh @@ -0,0 +1,55 @@ +#!/usr/bin/env bash +# +# 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. +# +# + +if test $(id -u) -ne 0; then + echo "Root privilege is required." + exit 1 +fi + +if [ -c /dev/sgx_provision -o -c /dev/sgx/provision ]; then + getent group sgx_prv &> /dev/null + if [ "$?" != "0" ]; then + # Add sgx_prv for dcap driver, which ensures that no matter what + # the order of package installation, aesmd can have access to + # the sgx_provision device file. + groupadd sgx_prv + + if ! which udevadm &> /dev/null; then + exit 0 + fi + udevadm control --reload || : + udevadm trigger || : + fi + usermod -aG sgx_prv aesmd &> /dev/null +fi + +echo diff --git a/linux/installer/common/psw-dcap/remount-dev-exec.service b/linux/installer/common/psw-dcap/remount-dev-exec.service new file mode 100644 index 000000000..ed4b7123e --- /dev/null +++ b/linux/installer/common/psw-dcap/remount-dev-exec.service @@ -0,0 +1,11 @@ +[Unit] +Description=Remount /dev as exec to allow AESM service to boot and load enclaves into SGX +After=udev.service + +[Service] +Type=oneshot +ExecStart=/bin/mount -o remount,exec /dev +RemainAfterExit=true + +[Install] +WantedBy=multi-user.target diff --git a/linux/installer/common/psw-dcap/startup.sh b/linux/installer/common/psw-dcap/startup.sh new file mode 100755 index 000000000..0f6e99ca1 --- /dev/null +++ b/linux/installer/common/psw-dcap/startup.sh @@ -0,0 +1,55 @@ +#!/usr/bin/env bash +# +# 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 -e + +if test $(id -u) -ne 0; then + echo "Root privilege is required." + exit 1 +fi + +# Create user and group if not exist +id -u aesmd &> /dev/null || \ + useradd -r -U -c "User for aesmd" \ + -d /var/opt/aesmd -s /sbin/nologin aesmd + +# Start the AESMD service +if [ -d /run/systemd/system ]; then + systemctl enable aesmd + systemctl start aesmd +elif [ -d /etc/init/ ]; then + initctl reload-configuration + initctl start aesmd +fi + +exit 0 diff --git a/linux/installer/common/psw/BOMs/psw_base.txt b/linux/installer/common/psw/BOMs/psw_base.txt index c6d60164a..193def27e 100644 --- a/linux/installer/common/psw/BOMs/psw_base.txt +++ b/linux/installer/common/psw/BOMs/psw_base.txt @@ -19,11 +19,12 @@ DeliveryName InstallName FileCheckSum FileFeature FileOwner /build/linux/bundles/libecdsa_quote_service_bundle.so /package/aesm/bundles/libecdsa_quote_service_bundle.so 0 main STP /build/linux/bundles/libquote_ex_service_bundle.so /package/aesm/bundles/libquote_ex_service_bundle.so 0 main STP /build/linux/le_prod_css.bin /package/aesm/le_prod_css.bin 0 main STP -/build/linux/libsgx_le.signed.so /package/aesm/libsgx_le.signed.so 0 main STP -/build/linux/libsgx_pve.signed.so /package/aesm/libsgx_pve.signed.so 0 main STP -/build/linux/libsgx_qe.signed.so /package/aesm/libsgx_qe.signed.so 0 main STP -/build/linux/libsgx_pce.signed.so /package/aesm/libsgx_pce.signed.so 0 main STP -/build/linux/libsgx_qe3.signed.so /package/aesm/libsgx_qe3.signed.so 0 main STP +/build/linux/libsgx_le.signed.so /package/aesm/libsgx_le.signed.so.1 0 main STP +/build/linux/libsgx_pve.signed.so /package/aesm/libsgx_pve.signed.so.1 0 main STP +/build/linux/libsgx_qe.signed.so /package/aesm/libsgx_qe.signed.so.1 0 main STP +/build/linux/libsgx_pce.signed.so /package/aesm/libsgx_pce.signed.so.1 0 main STP +/build/linux/libsgx_qe3.signed.so /package/aesm/libsgx_qe3.signed.so.1 0 main STP +/build/linux/libsgx_id_enclave.signed.so /package/aesm/libsgx_id_enclave.signed.so.1 0 main STP /linux/installer/common/psw/install.sh /scripts/install.sh 0 main STP /linux/installer/common/psw/Makefile /Makefile 0 main STP /psw/ae/aesm_service/config/network/aesmd.conf /package/aesm/conf/aesmd.conf 0 main STP diff --git a/linux/installer/common/psw/install.sh b/linux/installer/common/psw/install.sh index 9dc2e072d..f90e81de0 100755 --- a/linux/installer/common/psw/install.sh +++ b/linux/installer/common/psw/install.sh @@ -230,7 +230,7 @@ trigger_udev() { # Add sgx_prv for in-kernel driver. if [ -c /dev/sgx_provision -o -c /dev/sgx/provision ]; then - /usr/bin/getent group sgx_prv &> /dev/null || /usr/sbin/groupadd sgx_prv + getent group sgx_prv &> /dev/null || groupadd sgx_prv trigger_udev fi diff --git a/linux/installer/common/sdk/BOMs/sdk_base.txt b/linux/installer/common/sdk/BOMs/sdk_base.txt index 2fd10aeaa..c9e5f348e 100644 --- a/linux/installer/common/sdk/BOMs/sdk_base.txt +++ b/linux/installer/common/sdk/BOMs/sdk_base.txt @@ -16,6 +16,7 @@ DeliveryName InstallName FileCheckSum FileFeature FileOwner /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 @@ -40,6 +41,9 @@ DeliveryName InstallName FileCheckSum FileFeature FileOwner /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_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 /common/inc/stdc++/exception /package/include/stdc++/exception 0 main STP /common/inc/stdc++/linux/exception /package/include/stdc++/linux/exception 0 main STP /common/inc/stdc++/linux/typeinfo /package/include/stdc++/linux/typeinfo 0 main STP @@ -75,6 +79,9 @@ DeliveryName InstallName FileCheckSum FileFeature FileOwner /common/inc/tlibc/mbusafecrt.h /package/include/tlibc/mbusafecrt.h 0 main STP /common/inc/tlibc/pthread.h /package/include/tlibc/pthread.h 0 main STP /common/inc/sgx_pthread.edl /package/include/sgx_pthread.edl 0 main STP +/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 /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 @@ -265,6 +272,54 @@ DeliveryName InstallName FileCheckSum FileFeature FileOwner /SampleCode/SampleEnclavePCL/Seal/Seal.edl /package/SampleCode/SampleEnclavePCL/Seal/Seal.edl 0 main STP /SampleCode/SampleEnclavePCL/Seal/Seal.lds /package/SampleCode/SampleEnclavePCL/Seal/Seal.lds 0 main STP /SampleCode/SampleEnclavePCL/Seal/Seal_private_test.pem /package/SampleCode/SampleEnclavePCL/Seal/Seal_private_test.pem 0 main STP +/SampleCode/SampleAttestedTLS/AttestedTLSREADME.md /package/SampleCode/SampleAttestedTLS/AttestedTLSREADME.md 0 main STP +/SampleCode/SampleAttestedTLS/Makefile /package/SampleCode/SampleAttestedTLS/Makefile 0 main STP +/SampleCode/SampleAttestedTLS/prepare_sgxssl.sh /package/SampleCode/SampleAttestedTLS/prepare_sgxssl.sh 0 main STP +/SampleCode/SampleAttestedTLS/README.md /package/SampleCode/SampleAttestedTLS/README.md 0 main STP +/SampleCode/SampleAttestedTLS/sgxenv.mk /package/SampleCode/SampleAttestedTLS/sgxenv.mk 0 main STP +/SampleCode/SampleAttestedTLS/sgx_socket/htonl.c /package/SampleCode/SampleAttestedTLS/sgx_socket/htonl.c 0 main STP +/SampleCode/SampleAttestedTLS/sgx_socket/htons.c /package/SampleCode/SampleAttestedTLS/sgx_socket/htons.c 0 main STP +/SampleCode/SampleAttestedTLS/sgx_socket/trusted_sgx_socket.cpp /package/SampleCode/SampleAttestedTLS/sgx_socket/trusted_sgx_socket.cpp 0 main STP +/SampleCode/SampleAttestedTLS/sgx_socket/untrusted_sgx_socket.cpp /package/SampleCode/SampleAttestedTLS/sgx_socket/untrusted_sgx_socket.cpp 0 main STP +/SampleCode/SampleAttestedTLS/sgx_socket/include/byteswap.h /package/SampleCode/SampleAttestedTLS/sgx_socket/include/byteswap.h 0 main STP +/SampleCode/SampleAttestedTLS/sgx_socket/include/features.h /package/SampleCode/SampleAttestedTLS/sgx_socket/include/features.h 0 main STP +/SampleCode/SampleAttestedTLS/sgx_socket/include/netdb.h /package/SampleCode/SampleAttestedTLS/sgx_socket/include/netdb.h 0 main STP +/SampleCode/SampleAttestedTLS/sgx_socket/include/netinet/in.h /package/SampleCode/SampleAttestedTLS/sgx_socket/include/netinet/in.h 0 main STP +/SampleCode/SampleAttestedTLS/sgx_socket/include/bits/alltypes.h /package/SampleCode/SampleAttestedTLS/sgx_socket/include/bits/alltypes.h 0 main STP +/SampleCode/SampleAttestedTLS/sgx_socket/include/poll.h /package/SampleCode/SampleAttestedTLS/sgx_socket/include/poll.h 0 main STP +/SampleCode/SampleAttestedTLS/sgx_socket/include/sgx_socket.edl /package/SampleCode/SampleAttestedTLS/sgx_socket/include/sgx_socket.edl 0 main STP +/SampleCode/SampleAttestedTLS/sgx_socket/include/sys/socket.h /package/SampleCode/SampleAttestedTLS/sgx_socket/include/sys/socket.h 0 main STP +/SampleCode/SampleAttestedTLS/sgx_socket/include/sys/select.h /package/SampleCode/SampleAttestedTLS/sgx_socket/include/sys/select.h 0 main STP +/SampleCode/SampleAttestedTLS/server/Makefile /package/SampleCode/SampleAttestedTLS/server/Makefile 0 main STP +/SampleCode/SampleAttestedTLS/server/tls_server.edl /package/SampleCode/SampleAttestedTLS/server/tls_server.edl 0 main STP +/SampleCode/SampleAttestedTLS/server/enc/enclave.lds /package/SampleCode/SampleAttestedTLS/server/enc/enclave.lds 0 main STP +/SampleCode/SampleAttestedTLS/server/enc/Makefile /package/SampleCode/SampleAttestedTLS/server/enc/Makefile 0 main STP +/SampleCode/SampleAttestedTLS/server/enc/openssl_server.cpp /package/SampleCode/SampleAttestedTLS/server/enc/openssl_server.cpp 0 main STP +/SampleCode/SampleAttestedTLS/server/enc/private_test_key.pem /package/SampleCode/SampleAttestedTLS/server/enc/private_test_key.pem 0 main STP +/SampleCode/SampleAttestedTLS/server/enc/server_enc.config.xml /package/SampleCode/SampleAttestedTLS/server/enc/server_enc.config.xml 0 main STP +/SampleCode/SampleAttestedTLS/server/host/host.cpp /package/SampleCode/SampleAttestedTLS/server/host/host.cpp 0 main STP +/SampleCode/SampleAttestedTLS/server/host/Makefile /package/SampleCode/SampleAttestedTLS/server/host/Makefile 0 main STP +/SampleCode/SampleAttestedTLS/client/Makefile /package/SampleCode/SampleAttestedTLS/client/Makefile 0 main STP +/SampleCode/SampleAttestedTLS/client/tls_client.edl /package/SampleCode/SampleAttestedTLS/client/tls_client.edl 0 main STP +/SampleCode/SampleAttestedTLS/client/enc/client_enc.config.xml /package/SampleCode/SampleAttestedTLS/client/enc/client_enc.config.xml 0 main STP +/SampleCode/SampleAttestedTLS/client/enc/Makefile /package/SampleCode/SampleAttestedTLS/client/enc/Makefile 0 main STP +/SampleCode/SampleAttestedTLS/client/enc/enclave.lds /package/SampleCode/SampleAttestedTLS/client/enc/enclave.lds 0 main STP +/SampleCode/SampleAttestedTLS/client/enc/openssl_client.cpp /package/SampleCode/SampleAttestedTLS/client/enc/openssl_client.cpp 0 main STP +/SampleCode/SampleAttestedTLS/client/enc/private_test_key.pem /package/SampleCode/SampleAttestedTLS/client/enc/private_test_key.pem 0 main STP +/SampleCode/SampleAttestedTLS/client/host/host.cpp /package/SampleCode/SampleAttestedTLS/client/host/host.cpp 0 main STP +/SampleCode/SampleAttestedTLS/client/host/Makefile /package/SampleCode/SampleAttestedTLS/client/host/Makefile 0 main STP +/SampleCode/SampleAttestedTLS/non_enc_client/client.cpp /package/SampleCode/SampleAttestedTLS/non_enc_client/client.cpp 0 main STP +/SampleCode/SampleAttestedTLS/non_enc_client/Makefile /package/SampleCode/SampleAttestedTLS/non_enc_client/Makefile 0 main STP +/SampleCode/SampleAttestedTLS/common/common.h /package/SampleCode/SampleAttestedTLS/common/common.h 0 main STP +/SampleCode/SampleAttestedTLS/common/enclave.edl /package/SampleCode/SampleAttestedTLS/common/enclave.edl 0 main STP +/SampleCode/SampleAttestedTLS/common/err_msg.cpp /package/SampleCode/SampleAttestedTLS/common/err_msg.cpp 0 main STP +/SampleCode/SampleAttestedTLS/common/openssl_utility.cpp /package/SampleCode/SampleAttestedTLS/common/openssl_utility.cpp 0 main STP +/SampleCode/SampleAttestedTLS/common/openssl_utility.h /package/SampleCode/SampleAttestedTLS/common/openssl_utility.h 0 main STP +/SampleCode/SampleAttestedTLS/common/ucommon.cpp /package/SampleCode/SampleAttestedTLS/common/ucommon.cpp 0 main STP +/SampleCode/SampleAttestedTLS/common/tcommon.cpp /package/SampleCode/SampleAttestedTLS/common/tcommon.cpp 0 main STP +/SampleCode/SampleAttestedTLS/common/utility.cpp /package/SampleCode/SampleAttestedTLS/common/utility.cpp 0 main STP +/SampleCode/SampleAttestedTLS/common/utility.h /package/SampleCode/SampleAttestedTLS/common/utility.h 0 main STP +/SampleCode/SampleAttestedTLS/common/verify_callback.cpp /package/SampleCode/SampleAttestedTLS/common/verify_callback.cpp 0 main STP /SampleCode/Cxx11SGXDemo/App/App.cpp /package/SampleCode/Cxx11SGXDemo/App/App.cpp 0 main STP /SampleCode/Cxx11SGXDemo/App/App.h /package/SampleCode/Cxx11SGXDemo/App/App.h 0 main STP /SampleCode/Cxx11SGXDemo/App/TrustedLibrary/Libcxx.cpp /package/SampleCode/Cxx11SGXDemo/App/TrustedLibrary/Libcxx.cpp 0 main STP diff --git a/linux/installer/common/sdk/BOMs/sdk_cve_2020_0551_cf.txt b/linux/installer/common/sdk/BOMs/sdk_cve_2020_0551_cf.txt index 1f39d1022..ef2db28c1 100644 --- a/linux/installer/common/sdk/BOMs/sdk_cve_2020_0551_cf.txt +++ b/linux/installer/common/sdk/BOMs/sdk_cve_2020_0551_cf.txt @@ -12,4 +12,6 @@ DeliveryName InstallName FileCheckSum FileFeature FileOwner /build/linuxCF/libsgx_omp.a /package/lib64/cve_2020_0551_cf/libsgx_omp.a 0 main STP /build/linuxCF/libsgx_pthread.a /package/lib64/cve_2020_0551_cf/libsgx_pthread.a 0 main STP /build/linuxCF/libsgx_protobuf.a /package/lib64/cve_2020_0551_cf/libsgx_protobuf.a 0 main STP +/build/linuxCF/libsgx_ttls.a /package/lib64/cve_2020_0551_cf/libsgx_ttls.a 0 main STP +/build/linuxCF/libsgx_utls.a /package/lib64/cve_2020_0551_cf/libsgx_utls.a 0 main STP /external/dcap_source/QuoteGeneration/build/linuxCF/libsgx_dcap_tvl.a /package/lib64/cve_2020_0551_cf/libsgx_dcap_tvl.a 0 main STP diff --git a/linux/installer/common/sdk/BOMs/sdk_cve_2020_0551_load.txt b/linux/installer/common/sdk/BOMs/sdk_cve_2020_0551_load.txt index 18c9b35a4..6d12c01e2 100644 --- a/linux/installer/common/sdk/BOMs/sdk_cve_2020_0551_load.txt +++ b/linux/installer/common/sdk/BOMs/sdk_cve_2020_0551_load.txt @@ -12,4 +12,6 @@ DeliveryName InstallName FileCheckSum FileFeature FileOwner /build/linuxLOAD/libsgx_omp.a /package/lib64/cve_2020_0551_load/libsgx_omp.a 0 main STP /build/linuxLOAD/libsgx_pthread.a /package/lib64/cve_2020_0551_load/libsgx_pthread.a 0 main STP /build/linuxLOAD/libsgx_protobuf.a /package/lib64/cve_2020_0551_load/libsgx_protobuf.a 0 main STP +/build/linuxLOAD/libsgx_ttls.a /package/lib64/cve_2020_0551_load/libsgx_ttls.a 0 main STP +/build/linuxLOAD/libsgx_utls.a /package/lib64/cve_2020_0551_load/libsgx_utls.a 0 main STP /external/dcap_source/QuoteGeneration/build/linuxLOAD/libsgx_dcap_tvl.a /package/lib64/cve_2020_0551_load/libsgx_dcap_tvl.a 0 main STP diff --git a/linux/installer/common/sdk/BOMs/sdk_x64.txt b/linux/installer/common/sdk/BOMs/sdk_x64.txt index 497d7a924..d96b24c0b 100644 --- a/linux/installer/common/sdk/BOMs/sdk_x64.txt +++ b/linux/installer/common/sdk/BOMs/sdk_x64.txt @@ -43,6 +43,8 @@ DeliveryName InstallName FileCheckSum FileFeature FileOwner /build/linux/libsgx_pthread.a /package/lib64/libsgx_pthread.a 0 main STP /build/linux/libsgx_omp.a /package/lib64/libsgx_omp.a 0 main STP /build/linux/libsgx_protobuf.a /package/lib64/libsgx_protobuf.a 0 main STP +/build/linux/libsgx_ttls.a /package/lib64/libsgx_ttls.a 0 main STP +/build/linux/libsgx_utls.a /package/lib64/libsgx_utls.a 0 main STP /external/dcap_source/QuoteGeneration/build/linux/libsgx_dcap_tvl.a /package/lib64/libsgx_dcap_tvl.a 0 main STP /linux/installer/common/sdk/installConfig.x64 /scripts/installConfig 0 main STP /linux/installer/common/sdk/pkgconfig/x64/libsgx_uae_service_sim.pc /package/pkgconfig/libsgx_uae_service_sim.pc 0 main STP diff --git a/linux/installer/common/sgx-aesm-service/Makefile b/linux/installer/common/sgx-aesm-service/Makefile index 2b3d942a0..71face180 100644 --- a/linux/installer/common/sgx-aesm-service/Makefile +++ b/linux/installer/common/sgx-aesm-service/Makefile @@ -52,6 +52,13 @@ $(error "Unsupported platform - neither systemctl nor initctl is found!") endif endif +QE_VER=1.0.0 +PVE_VER=1.0.0 +LE_VER=1.0.0 +PCE_VER=1.0.0 +QE3_VER=1.0.0 +SPLIT_VERSION=$(word $2,$(subst ., ,$1)) + default: install: $(PACKAGES) @@ -71,10 +78,27 @@ install: $(PACKAGES) cp -fr $(DESTDIR)/$(AESM_SERVICE_PACKAGE_NAME)/$(AESM_SERVICE_PACKAGE_PATH)/$(AESM_SERVICE_PACKAGE_NAME)/aesm/conf/* \ $(DESTDIR)/$(AESM_SERVICE_PACKAGE_NAME)/$(ETC_DIR) && \ rm -fr $(DESTDIR)/$(AESM_SERVICE_PACKAGE_NAME)/$(AESM_SERVICE_PACKAGE_PATH)/$(AESM_SERVICE_PACKAGE_NAME)/aesm/conf)) + cd $(shell readlink -m $(DESTDIR)/$(AE_EPID_PACKAGE_NAME)/$(AESM_SERVICE_PACKAGE_PATH)/$(AESM_SERVICE_PACKAGE_NAME)/aesm) && \ + mv libsgx_qe.signed.so libsgx_qe.signed.so.$(QE_VER) && \ + ln -fs libsgx_qe.signed.so.$(QE_VER) libsgx_qe.signed.so.$(call SPLIT_VERSION,$(QE_VER),1) && \ + ln -fs libsgx_qe.signed.so.$(call SPLIT_VERSION,$(QE_VER),1) libsgx_qe.signed.so &&\ + mv libsgx_pve.signed.so libsgx_pve.signed.so.$(PVE_VER) && \ + ln -fs libsgx_pve.signed.so.$(PVE_VER) libsgx_pve.signed.so.$(call SPLIT_VERSION,$(PVE_VER),1) && \ + ln -fs libsgx_pve.signed.so.$(call SPLIT_VERSION,$(PVE_VER),1) libsgx_pve.signed.so + cd $(shell readlink -m $(DESTDIR)/$(AE_PCE_PACKAGE_NAME)/$(USR_LIB_PATH)) && \ + mv libsgx_pce.signed.so libsgx_pce.signed.so.$(PCE_VER) && \ + ln -fs libsgx_pce.signed.so.$(PCE_VER) libsgx_pce.signed.so.$(call SPLIT_VERSION,$(PCE_VER),1) && \ + ln -fs libsgx_pce.signed.so.$(call SPLIT_VERSION,$(PCE_VER),1) libsgx_pce.signed.so + cd $(shell readlink -m $(DESTDIR)/$(AE_LE_PACKAGE_NAME)/$(AESM_SERVICE_PACKAGE_PATH)/$(AESM_SERVICE_PACKAGE_NAME)/aesm) && \ + mv libsgx_le.signed.so libsgx_le.signed.so.$(LE_VER) && \ + ln -fs libsgx_le.signed.so.$(LE_VER) libsgx_le.signed.so.$(call SPLIT_VERSION,$(LE_VER),1) && \ + ln -fs libsgx_le.signed.so.$(call SPLIT_VERSION,$(LE_VER),1) libsgx_le.signed.so cd $(shell readlink -m $(DESTDIR)/$(AESM_ECDSA_PACKAGE_NAME)/$(AESM_SERVICE_PACKAGE_PATH)/$(AESM_SERVICE_PACKAGE_NAME)/aesm) && \ - ln -fs $(shell readlink -m $(USR_LIB_PATH)/libsgx_qe3.signed.so) && \ + ln -fs $(USR_LIB_PATH)/libsgx_qe3.signed.so.$(call SPLIT_VERSION,$(QE3_VER),1) && \ + ln -fs $(USR_LIB_PATH)/libsgx_qe3.signed.so && \ cd $(shell readlink -m $(DESTDIR)/$(AESM_PCE_PACKAGE_NAME)/$(AESM_SERVICE_PACKAGE_PATH)/$(AESM_SERVICE_PACKAGE_NAME)/aesm) && \ - ln -fs $(shell readlink -m $(USR_LIB_PATH)/libsgx_pce.signed.so) && \ + ln -fs $(USR_LIB_PATH)/libsgx_pce.signed.so.$(call SPLIT_VERSION,$(PCE_VER),1) && \ + ln -fs $(USR_LIB_PATH)/libsgx_pce.signed.so && \ ln -fs liburts_internal.so libsgx_urts.so $(PACKAGES): diff --git a/linux/installer/common/sgx-aesm-service/cleanup.sh b/linux/installer/common/sgx-aesm-service/cleanup.sh index 0f4bfd1b5..968d65018 100755 --- a/linux/installer/common/sgx-aesm-service/cleanup.sh +++ b/linux/installer/common/sgx-aesm-service/cleanup.sh @@ -44,17 +44,17 @@ if [ -d /run/systemd/system ]; then systemctl stop aesmd systemctl disable aesmd 2> /dev/null elif [ -d /etc/init/ ]; then - /sbin/initctl reload-configuration - /sbin/initctl stop aesmd + initctl reload-configuration + initctl stop aesmd fi # Remove AESM user and group -/usr/sbin/userdel aesmd 2> /dev/null || true -/usr/sbin/groupdel aesmd 2> /dev/null || true +userdel aesmd 2> /dev/null || true +groupdel aesmd 2> /dev/null || true # Keep the group if the driver still exists if [ ! -c /dev/sgx/provision ]; then - /usr/sbin/groupdel sgx_prv 2> /dev/null || true + groupdel sgx_prv 2> /dev/null || true fi exit 0 diff --git a/linux/installer/common/sgx-aesm-service/createTarball.sh b/linux/installer/common/sgx-aesm-service/createTarball.sh index c1536ffb1..55d05809c 100755 --- a/linux/installer/common/sgx-aesm-service/createTarball.sh +++ b/linux/installer/common/sgx-aesm-service/createTarball.sh @@ -63,6 +63,16 @@ python ${SCRIPT_DIR}/gen_source.py --bom=BOMs/sgx-aesm-service-package.txt --cle python ${SCRIPT_DIR}/gen_source.py --bom=../licenses/BOM_license.txt --cleanup=false # Create the tarball +QE_VERSION=$(awk '/QE_VERSION/ {print $3}' ${ROOT_DIR}/common/inc/internal/se_version.h|sed 's/^\"\(.*\)\"$/\1/') +PVE_VERSION=$(awk '/PVE_VERSION/ {print $3}' ${ROOT_DIR}/common/inc/internal/se_version.h|sed 's/^\"\(.*\)\"$/\1/') +LE_VERSION=$(awk '/LE_VERSION/ {print $3}' ${ROOT_DIR}/common/inc/internal/se_version.h|sed 's/^\"\(.*\)\"$/\1/') +PCE_VERSION=$(awk '/PCE_VERSION/ {print $3}' ${ROOT_DIR}/common/inc/internal/se_version.h|sed 's/^\"\(.*\)\"$/\1/') +QE3_VERSION=$(awk '/QE3_VERSION/ {print $3}' ${ROOT_DIR}/external/dcap_source/QuoteGeneration/common/inc/internal/se_version.h|sed 's/^\"\(.*\)\"$/\1/') pushd ${INSTALL_PATH} &> /dev/null +sed -i "s/QE_VER=.*/QE_VER=${QE_VERSION}/" Makefile +sed -i "s/PVE_VER=.*/PVE_VER=${PVE_VERSION}/" Makefile +sed -i "s/LE_VER=.*/LE_VER=${LE_VERSION}/" Makefile +sed -i "s/PCE_VER=.*/PCE_VER=${PCE_VERSION}/" Makefile +sed -i "s/QE3_VER=.*/QE3_VER=${QE3_VERSION}/" Makefile tar -zcvf ${TARBALL_NAME} * popd &> /dev/null diff --git a/linux/installer/common/sgx-aesm-service/startup.sh b/linux/installer/common/sgx-aesm-service/startup.sh index 9fce70d72..28e6032aa 100755 --- a/linux/installer/common/sgx-aesm-service/startup.sh +++ b/linux/installer/common/sgx-aesm-service/startup.sh @@ -40,7 +40,7 @@ fi # Create user and group if not exist id -u aesmd &> /dev/null || \ - /usr/sbin/useradd -r -U -c "User for aesmd" \ + useradd -r -U -c "User for aesmd" \ -d /var/opt/aesmd -s /sbin/nologin aesmd # Start the AESMD service @@ -48,8 +48,8 @@ if [ -d /run/systemd/system ]; then systemctl enable aesmd systemctl start aesmd elif [ -d /etc/init/ ]; then - /sbin/initctl reload-configuration - /sbin/initctl start aesmd + initctl reload-configuration + initctl start aesmd fi exit 0 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 987dc5c82..a045a0e5e 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.12), libsgx-aesm-pce-plugin(>= @dep_version@) +Depends: ${shlibs:Depends}, ${misc:Depends}, sgx-aesm-service(>= @dep_version@), libsgx-qe3-logic(>= 1.13), 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.12), libsgx-ae-pce(>= @dep_version@) +Depends: ${shlibs:Depends}, ${misc:Depends}, sgx-aesm-service(>= @dep_version@), libsgx-pce-logic(>= 1.13), 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/deb/sgx-aesm-service/sgx-aesm-service-1.0/debian/libsgx-ae-pce.postinst b/linux/installer/deb/sgx-aesm-service/sgx-aesm-service-1.0/debian/libsgx-ae-pce.postinst index 1cf07776a..a60c6391c 100644 --- a/linux/installer/deb/sgx-aesm-service/sgx-aesm-service-1.0/debian/libsgx-ae-pce.postinst +++ b/linux/installer/deb/sgx-aesm-service/sgx-aesm-service-1.0/debian/libsgx-ae-pce.postinst @@ -29,7 +29,7 @@ case "$1" in configure) # Add sgx_prv for in-kernel driver. if [ -c /dev/sgx_provision -o -c /dev/sgx/provision ]; then - /usr/bin/getent group sgx_prv &> /dev/null || /usr/sbin/groupadd sgx_prv + getent group sgx_prv &> /dev/null || groupadd sgx_prv trigger_udev fi ;; diff --git a/linux/installer/rpm/psw-dcap/build.sh b/linux/installer/rpm/psw-dcap/build.sh new file mode 100755 index 000000000..22c8eef5a --- /dev/null +++ b/linux/installer/rpm/psw-dcap/build.sh @@ -0,0 +1,103 @@ +#!/usr/bin/env bash +# +# 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 -e + +psw_dcap="psw-dcap" + +cur_dir=$(dirname "$0") +root_dir="${cur_dir}/../../../../" +dcap_dir="${root_dir}/external/dcap_source" +common_dir="${root_dir}/linux/installer/common" +common_psw_dcap_dir="${common_dir}/${psw_dcap}" + +psw_version=$(awk '/STRFILEVER/ {print substr($3, 2, length($3) - 2);}' \ + ${root_dir}/common/inc/internal/se_version.h) +rpm_build_dir=${psw_dcap}-${psw_version} + +source ${common_psw_dcap_dir}/installConfig + +pre_build() { + rm -fr ${cur_dir}/${rpm_build_dir} + mkdir -p ${cur_dir}/${rpm_build_dir}/{BUILD,RPMS,SOURCES,SPECS,SRPMS} +} + +update_spec() { + local min_version="4.12" + local rpm_version=$(rpmbuild --version 2> /dev/null | awk '{print $NF}') + local cur_version=$(echo -e "${rpm_version}\n${min_version}" | sort -V | head -n 1) + local dcap_version=$(awk '/STRFILEVER/ {print substr($3, 2, length($3) - 2);}' \ + ${dcap_dir}/QuoteGeneration/common/inc/internal/se_version.h) + + sed -e "s:@psw_version@:${psw_version}:" \ + -e "s:@dcap_version@:${dcap_version}:" \ + -e "s:@aesm_service_path@:${SGX_INSTALL_PATH}/${AESM_SERVICE_PACKAGE}:" \ + -e "s:@ra_service_path@:${SGX_INSTALL_PATH}/${RA_SERVICE_PACKAGE}:" \ + -e "s:@dcap_pccs_path@:${SGX_INSTALL_PATH}/${DCAP_PCCS_PACKAGE}:" \ + -e "s:@pck_id_retrieval_tool_path@:${SGX_INSTALL_PATH}/${PCK_ID_RETRIEVAL_TOOL_PACKAGE}:" \ + ${cur_dir}/${psw_dcap}.spec.tmpl > ${cur_dir}/${rpm_build_dir}/SPECS/${psw_dcap}.spec + + if [ "${min_version}" != "${cur_version}" ]; then + sed -i "s/^Recommends:/Requires: /" ${cur_dir}/${rpm_build_dir}/SPECS/${psw_dcap}.spec + fi +} + +create_upstream_tarball() { + tar -zcvf ${cur_dir}/${rpm_build_dir}/SOURCES/${psw_dcap}-${psw_version}.tar.gz \ + --exclude=$(realpath --relative-to=${root_dir} ${cur_dir}) \ + --directory=${root_dir} $(ls ${root_dir}) +} + +build_package() { + pushd ${cur_dir}/${rpm_build_dir} &> /dev/null + rpmbuild --define="_topdir `pwd`" -ba SPECS/${psw_dcap}.spec + popd &> /dev/null +} + +post_build() { + cp -f ${cur_dir}/${rpm_build_dir}/RPMS/**/*.rpm ${cur_dir} + cp -f ${cur_dir}/${rpm_build_dir}/SRPMS/*.rpm ${cur_dir} + cp -f ${cur_dir}/${rpm_build_dir}/SOURCES/*.tar.gz ${cur_dir} + cp -f ${cur_dir}/${rpm_build_dir}/SPECS/${psw_dcap}.spec ${cur_dir}/${psw_dcap}.spec.in + rm -fr ${cur_dir}/${rpm_build_dir} +} + +main() { + pre_build + update_spec + create_upstream_tarball + build_package + post_build +} + +main $@ diff --git a/linux/installer/rpm/psw-dcap/clean.sh b/linux/installer/rpm/psw-dcap/clean.sh new file mode 100755 index 000000000..bf674ae47 --- /dev/null +++ b/linux/installer/rpm/psw-dcap/clean.sh @@ -0,0 +1,36 @@ +#!/usr/bin/env bash +# +# 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 -e + +rm -f $(dirname "$0")/{*.rpm,*.tar.gz,*.spec.in} diff --git a/linux/installer/rpm/psw-dcap/psw-dcap.spec.tmpl b/linux/installer/rpm/psw-dcap/psw-dcap.spec.tmpl new file mode 100644 index 000000000..5c518cc5d --- /dev/null +++ b/linux/installer/rpm/psw-dcap/psw-dcap.spec.tmpl @@ -0,0 +1,521 @@ +#!/usr/bin/env bash +# +# 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. +# +# + +# +# 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. +# +# + +%define _aesm_service_path @aesm_service_path@ +%define _ra_service_path @ra_service_path@ +%define _dcap_pccs_path @dcap_pccs_path@ +%define _pck_id_retrieval_tool_path @pck_id_retrieval_tool_path@ +%define _psw_version @psw_version@ +%define _dcap_version @dcap_version@ +%define _license_file COPYING + +Name: sgx-aesm-service +Version: %{_psw_version} +Release: 1%{?dist} +Summary: Intel(R) Software Guard Extensions AESM Service + +License: BSD and MIT and Apache and GPL and BSD/GPLv2 dual and zlib/libpng and Eclipse Public License-v1.0 and Open Source and OpenSSL +URL: https://github.com/intel/linux-sgx +Source0: psw-dcap-%{version}.tar.gz + +BuildRequires: autoconf +BuildRequires: automake +BuildRequires: binutils +BuildRequires: libtool +BuildRequires: gcc +BuildRequires: gcc-c++ +BuildRequires: make +BuildRequires: cmake +BuildRequires: ocaml +BuildRequires: ocaml-ocamlbuild +BuildRequires: redhat-rpm-config +BuildRequires: openssl +BuildRequires: openssl-devel +BuildRequires: protobuf-compiler +BuildRequires: protobuf-devel +BuildRequires: libcurl-devel +BuildRequires: python +BuildRequires: perl + +%description +Intel(R) Software Guard Extensions AESM Service + +%package -n libsgx-ae-epid +Version: %{_psw_version} +Summary: Intel(R) Software Guard Extensions QE and PvE + +%description -n libsgx-ae-epid +Intel(R) Software Guard Extensions QE and PvE + +%package -n libsgx-ae-le +Version: %{_psw_version} +Summary: Intel(R) Software Guard Extensions LE + +%description -n libsgx-ae-le +Intel(R) Software Guard Extensions LE + +%package -n libsgx-ae-pce +Version: %{_psw_version} +Summary: Intel(R) Software Guard Extensions PCE + +%description -n libsgx-ae-pce +Intel(R) Software Guard Extensions PCE + +%package -n libsgx-aesm-ecdsa-plugin +Version: %{_psw_version} +Summary: ECDSA Quote Plugin for Intel(R) Software Guard Extensions AESM Service +Requires: %{name} >= %{version}-%{release} libsgx-qe3-logic >= %{_dcap_version}-%{release} libsgx-aesm-pce-plugin >= %{version}-%{release} + +%description -n libsgx-aesm-ecdsa-plugin +ECDSA Quote Plugin for Intel(R) Software Guard Extensions AESM Service + +%package -n libsgx-aesm-epid-plugin +Version: %{_psw_version} +Summary: EPID Quote Plugin for Intel(R) Software Guard Extensions AESM Service +Requires: %{name} >= %{version}-%{release} libsgx-ae-epid >= %{version}-%{release} libsgx-aesm-pce-plugin >= %{version}-%{release} + +%description -n libsgx-aesm-epid-plugin +EPID Quote Plugin for Intel(R) Software Guard Extensions AESM Service + +%package -n libsgx-aesm-launch-plugin +Version: %{_psw_version} +Summary: Launch Plugin for Intel(R) Software Guard Extensions AESM Service +Requires: %{name} >= %{version}-%{release} libsgx-ae-le >= %{version}-%{release} + +%description -n libsgx-aesm-launch-plugin +Launch Plugin for Intel(R) Software Guard Extensions AESM Service + +%package -n libsgx-aesm-pce-plugin +Version: %{_psw_version} +Summary: PCE Plugin for Intel(R) Software Guard Extensions AESM Service +Requires: %{name} >= %{version}-%{release} libsgx-pce-logic >= %{_dcap_version}-%{release} + +%description -n libsgx-aesm-pce-plugin +PCE Plugin for Intel(R) Software Guard Extensions AESM Service + +%package -n libsgx-aesm-quote-ex-plugin +Version: %{_psw_version} +Summary: Unified Quote Plugin for Intel(R) Software Guard Extensions AESM Service +Requires: %{name} >= %{version}-%{release} libsgx-aesm-ecdsa-plugin >= %{version}-%{release} +Recommends: libsgx-aesm-epid-plugin >= %{version}-%{release} + +%description -n libsgx-aesm-quote-ex-plugin +Unified Quote Plugin for Intel(R) Software Guard Extensions AESM Service + +%package -n libsgx-epid +Version: %{_psw_version} +Summary: Intel(R) Software Guard Extensions EPID Quote Service +Recommends: libsgx-aesm-epid-plugin >= %{version}-%{release} + +%description -n libsgx-epid +Intel(R) Software Guard Extensions EPID Quote Service + +%package -n libsgx-epid-devel +Version: %{_psw_version} +Summary: Intel(R) Software Guard Extensions EPID Quote Service for Developers +Requires: libsgx-epid = %{version}-%{release} libsgx-headers >= %{version}-%{release} + +%description -n libsgx-epid-devel +Intel(R) Software Guard Extensions EPID Quote Service for Developers + +%package -n libsgx-launch +Version: %{_psw_version} +Summary: Intel(R) Software Guard Extensions Launch Service +Recommends: libsgx-aesm-launch-plugin >= %{version}-%{release} + +%description -n libsgx-launch +Intel(R) Software Guard Extensions Launch Service + +%package -n libsgx-launch-devel +Version: %{_psw_version} +Summary: Intel(R) Software Guard Extensions Launch Service for Developers +Requires: libsgx-launch = %{version}-%{release} libsgx-headers >= %{version}-%{release} + +%description -n libsgx-launch-devel +Intel(R) Software Guard Extensions Launch Service for Developers + +%package -n libsgx-quote-ex +Version: %{_psw_version} +Summary: Intel(R) Software Guard Extensions Unified Quote Service +Recommends: libsgx-aesm-quote-ex-plugin >= %{version}-%{release} + +%description -n libsgx-quote-ex +Intel(R) Software Guard Extensions Unified Quote Service + +%package -n libsgx-quote-ex-devel +Version: %{_psw_version} +Summary: Intel(R) Software Guard Extensions Unified Quote Service for Developers +Requires: libsgx-quote-ex = %{version}-%{release} libsgx-headers >= %{version}-%{release} + +%description -n libsgx-quote-ex-devel +Intel(R) Software Guard Extensions Unified Quote Service for Developers + +%package -n libsgx-headers +Version: %{_psw_version} +Summary: Intel(R) Software Guard Extensions Basic Headers + +%description -n libsgx-headers +Intel(R) Software Guard Extensions Basic Headers + +%package -n libsgx-urts +Version: %{_psw_version} +Summary: Intel(R) Software Guard Extensions uRTS +Requires: libsgx-enclave-common >= %{version}-%{release} + +%description -n libsgx-urts +Intel(R) Software Guard Extensions uRTS + +%package -n libsgx-uae-service +Version: %{_psw_version} +Summary: Intel(R) Software Guard Extensions Untrusted AE Service +Requires: libsgx-epid >= %{version}-%{release} libsgx-launch >= %{version}-%{release} libsgx-quote-ex >= %{version}-%{release} + +%description -n libsgx-uae-service +Intel(R) Software Guard Extensions Untrusted AE Service + +%package -n libsgx-enclave-common +Version: %{_psw_version} +Summary: Intel(R) Software Guard Extensions Enclave Common Loader +Recommends: libsgx-launch >= %{version}-%{release} + +%description -n libsgx-enclave-common +Intel(R) Software Guard Extensions Enclave Common Loader + +%package -n libsgx-enclave-common-devel +Version: %{_psw_version} +Summary: Intel(R) Software Guard Extensions Enclave Common Loader for Developers +Requires: libsgx-enclave-common = %{version}-%{release} libsgx-headers >= %{version}-%{release} + +%description -n libsgx-enclave-common-devel +Intel(R) Software Guard Extensions Enclave Common Loader for Developers + +%package -n libsgx-ae-id-enclave +Version: %{_dcap_version} +Summary: Intel(R) Software Guard Extensions ID Enclave + +%description -n libsgx-ae-id-enclave +Intel(R) Software Guard Extensions ID Enclave + +%package -n libsgx-ae-qe3 +Version: %{_dcap_version} +Summary: Intel(R) Software Guard Extensions QE3 + +%description -n libsgx-ae-qe3 +Intel(R) Software Guard Extensions QE3 + +%package -n libsgx-ae-qve +Version: %{_dcap_version} +Summary: Intel(R) Software Guard Extensions QVE + +%description -n libsgx-ae-qve +Intel(R) Software Guard Extensions QVE + +%package -n libsgx-qe3-logic +Version: %{_dcap_version} +Summary: Intel(R) Software Guard Extensions QE3 logic +Requires: libsgx-urts >= %{_psw_version}-%{release} libsgx-ae-qe3 >= %{version}-%{release} libsgx-ae-id-enclave >= %{version}-%{release} + +%description -n libsgx-qe3-logic +Intel(R) Software Guard Extensions QE3 logic + +%package -n libsgx-pce-logic +Version: %{_dcap_version} +Summary: Intel(R) Software Guard Extensions PCE logic +Requires: libsgx-urts >= %{_psw_version}-%{release} libsgx-ae-pce >= %{_psw_version}-%{release} + +%description -n libsgx-pce-logic +Intel(R) Software Guard Extensions PCE logic + +%package -n libsgx-dcap-default-qpl +Version: %{_dcap_version} +Summary: Intel(R) Software Guard Extensions Default Quote Provider Library + +%description -n libsgx-dcap-default-qpl +Intel(R) Software Guard Extensions Default Quote Provider Library + +%package -n libsgx-dcap-default-qpl-devel +Version: %{_dcap_version} +Summary: Intel(R) Software Guard Extensions Default Quote Provider Library for Developers +Requires: libsgx-dcap-default-qpl = %{version}-%{release} + +%description -n libsgx-dcap-default-qpl-devel +Intel(R) Software Guard Extensions Default Quote Provider Library for Developers + +%package -n libsgx-dcap-ql +Version: %{_dcap_version} +Summary: Intel(R) Software Guard Extensions Data Center Attestation Primitives Quote Generation Library +Requires: libsgx-qe3-logic >= %{version}-%{release} libsgx-pce-logic >= %{version}-%{release} +Recommends: libsgx-dcap-quote-verify >= %{version}-%{release} libsgx-quote-ex >= %{_psw_version}-%{release} + +%description -n libsgx-dcap-ql +Intel(R) Software Guard Extensions Data Center Attestation Primitives Quote Generation Library + +%package -n libsgx-dcap-ql-devel +Version: %{_dcap_version} +Summary: Intel(R) Software Guard Extensions Data Center Attestation Primitives Quote Generation Library for Developers +Requires: libsgx-dcap-ql = %{version}-%{release} libsgx-headers >= %{_psw_version}-%{release} + +%description -n libsgx-dcap-ql-devel +Intel(R) Software Guard Extensions Data Center Attestation Primitives Quote Generation Library for Developers + +%package -n libsgx-dcap-quote-verify +Version: %{_dcap_version} +Summary: Intel(R) Software Guard Extensions Data Center Attestation Primitives Quote Verification Library +Recommends: libsgx-ae-qve >= %{version}-%{release} libsgx-urts >= %{_psw_version}-%{release} + +%description -n libsgx-dcap-quote-verify +Intel(R) Software Guard Extensions Data Center Attestation Primitives Quote Verification Library + +%package -n libsgx-dcap-quote-verify-devel +Version: %{_dcap_version} +Summary: Intel(R) Software Guard Extensions Data Center Attestation Primitives Quote Verification Library for Developers +Requires: libsgx-dcap-quote-verify = %{version}-%{release} libsgx-headers >= %{_psw_version}-%{release} + +%description -n libsgx-dcap-quote-verify-devel +Intel(R) Software Guard Extensions Data Center Attestation Primitives Quote Verification Library for Developers + +%package -n sgx-dcap-pccs +Version: %{_dcap_version} +Summary: Intel(R) Software Guard Extensions PCK Caching Service +Requires: gcc gcc-c++ make + +%description -n sgx-dcap-pccs +Intel(R) Software Guard Extensions PCK Caching Service + +%package -n libsgx-ra-network +Version: %{_dcap_version} +Summary: Intel(R) Software Guard Extensions Registration Agent Network Library + +%description -n libsgx-ra-network +Intel(R) Software Guard Extensions Registration Agent Network Library + +%package -n libsgx-ra-network-devel +Version: %{_dcap_version} +Summary: Intel(R) Software Guard Extensions Registration Agent Network Library for Developers +Requires: libsgx-ra-network = %{version}-%{release} + +%description -n libsgx-ra-network-devel +Intel(R) Software Guard Extensions Registration Agent Network Library for Developers + +%package -n libsgx-ra-uefi +Version: %{_dcap_version} +Summary: Intel(R) Software Guard Extensions Registration Agent UEFI Library + +%description -n libsgx-ra-uefi +Intel(R) Software Guard Extensions Registration Agent UEFI Library + +%package -n libsgx-ra-uefi-devel +Version: %{_dcap_version} +Summary: Intel(R) Software Guard Extensions Registration Agent UEFI Library for Developers +Requires: libsgx-ra-uefi = %{version}-%{release} + +%description -n libsgx-ra-uefi-devel +Intel(R) Software Guard Extensions Registration Agent UEFI Library for Developers + +%package -n sgx-ra-service +Version: %{_dcap_version} +Summary: Intel(R) Software Guard Extensions Registration Agent Service +Requires: libsgx-ra-uefi >= %{version}-%{release} libsgx-ra-network >= %{version}-%{release} + +%description -n sgx-ra-service +Intel(R) Software Guard Extensions Registration Agent Service + +%package -n sgx-pck-id-retrieval-tool +Version: %{_dcap_version} +Summary: Intel(R) Software Guard Extensions PCK Certs Retrieve Tool +Recommends: libsgx-urts >= %{_psw_version} libsgx-ae-pce >= %{version}-%{release} libsgx-ae-id-enclave >= %{version}-%{release} libsgx-ra-uefi >= %{version}-%{release} + +%description -n sgx-pck-id-retrieval-tool +Intel(R) Software Guard Extensions:this tool is used to collect the platform information to retrieve the PCK certs from PCS(Provisioning Certification Server) + +%prep +%setup -qc + +%build +%undefine _auto_set_build_flags +make %{?_smp_mflags} build + +%install +make DESTDIR=%{?buildroot} install + +for pkg in $(ls -A %{?buildroot} 2> /dev/null |grep -v "license"); do + install -d %{?buildroot}/${pkg}/%{_docdir}/${pkg} + find %{?buildroot}/license -type f -print0 | \ + xargs -0 -n1 cat >> %{?buildroot}/${pkg}/%{_docdir}/${pkg}/%{_license_file} + find %{?buildroot}/${pkg} -type d -exec \ + sh -c '(ls -p "{}"|grep />/dev/null)||echo "{}"' \; | \ + sed -e "s#^%{?buildroot}/${pkg}##" | \ + grep -v "^%{_libdir}" | \ + grep -v "^%{_includedir}" | \ + grep -v "^%{_sysconfdir}" | \ + grep -v "^%{_aesm_service_path}" | \ + grep -v "^%{_dcap_pccs_path}" | \ + grep -v "^%{_ra_service_path}" | \ + grep -v "^%{_pck_id_retrieval_tool_path}" | \ + sed -e "s#^#%dir #" > %{_specdir}/list-${pkg} + for f in $(find %{?buildroot}/${pkg}); do + if [ -d ${f} ]; then + echo ${f} | sed -e "s#^%{?buildroot}/${pkg}##" | \ + grep -E "^%{_aesm_service_path}|^%{_dcap_pccs_path}|^%{_ra_service_path}|^%{_pck_id_retrieval_tool_path}" | \ + sed -e "s#^#%dir #" >> %{_specdir}/list-${pkg} + else + echo ${f} | \ + sed -e "s#^%{?buildroot}/${pkg}##" >> %{_specdir}/list-${pkg} + fi + done + cp -r %{?buildroot}/${pkg}/* %{?buildroot}/ + rm -fr %{?buildroot}/${pkg} + sed -i -e 's:^/etc/.*\.conf:%config &:' \ + -e 's:^%{_dcap_pccs_path}/config/default\.json:%config &:' %{_specdir}/list-${pkg} +done +rm -fr %{?buildroot}/license + +%clean +make clean + +%files -f %{_specdir}/list-%{name} +%files -n libsgx-ae-epid -f %{_specdir}/list-libsgx-ae-epid +%files -n libsgx-ae-le -f %{_specdir}/list-libsgx-ae-le +%files -n libsgx-ae-pce -f %{_specdir}/list-libsgx-ae-pce +%files -n libsgx-aesm-ecdsa-plugin -f %{_specdir}/list-libsgx-aesm-ecdsa-plugin +%files -n libsgx-aesm-epid-plugin -f %{_specdir}/list-libsgx-aesm-epid-plugin +%files -n libsgx-aesm-launch-plugin -f %{_specdir}/list-libsgx-aesm-launch-plugin +%files -n libsgx-aesm-pce-plugin -f %{_specdir}/list-libsgx-aesm-pce-plugin +%files -n libsgx-aesm-quote-ex-plugin -f %{_specdir}/list-libsgx-aesm-quote-ex-plugin +%files -n libsgx-epid -f %{_specdir}/list-libsgx-epid +%files -n libsgx-epid-devel -f %{_specdir}/list-libsgx-epid-devel +%files -n libsgx-launch -f %{_specdir}/list-libsgx-launch +%files -n libsgx-launch-devel -f %{_specdir}/list-libsgx-launch-devel +%files -n libsgx-quote-ex -f %{_specdir}/list-libsgx-quote-ex +%files -n libsgx-quote-ex-devel -f %{_specdir}/list-libsgx-quote-ex-devel +%files -n libsgx-headers -f %{_specdir}/list-libsgx-headers +%files -n libsgx-urts -f %{_specdir}/list-libsgx-urts +%files -n libsgx-uae-service -f %{_specdir}/list-libsgx-uae-service +%files -n libsgx-enclave-common -f %{_specdir}/list-libsgx-enclave-common +%files -n libsgx-enclave-common-devel -f %{_specdir}/list-libsgx-enclave-common-devel +%files -n libsgx-ae-id-enclave -f %{_specdir}/list-libsgx-ae-id-enclave +%files -n libsgx-ae-qe3 -f %{_specdir}/list-libsgx-ae-qe3 +%files -n libsgx-ae-qve -f %{_specdir}/list-libsgx-ae-qve +%files -n libsgx-qe3-logic -f %{_specdir}/list-libsgx-qe3-logic +%files -n libsgx-pce-logic -f %{_specdir}/list-libsgx-pce-logic +%files -n libsgx-dcap-default-qpl -f %{_specdir}/list-libsgx-dcap-default-qpl +%files -n libsgx-dcap-default-qpl-devel -f %{_specdir}/list-libsgx-dcap-default-qpl-devel +%files -n libsgx-dcap-ql -f %{_specdir}/list-libsgx-dcap-ql +%files -n libsgx-dcap-ql-devel -f %{_specdir}/list-libsgx-dcap-ql-devel +%files -n libsgx-dcap-quote-verify -f %{_specdir}/list-libsgx-dcap-quote-verify +%files -n libsgx-dcap-quote-verify-devel -f %{_specdir}/list-libsgx-dcap-quote-verify-devel +%files -n sgx-dcap-pccs -f %{_specdir}/list-sgx-dcap-pccs +%files -n libsgx-ra-network -f %{_specdir}/list-libsgx-ra-network +%files -n libsgx-ra-network-devel -f %{_specdir}/list-libsgx-ra-network-devel +%files -n libsgx-ra-uefi -f %{_specdir}/list-libsgx-ra-uefi +%files -n libsgx-ra-uefi-devel -f %{_specdir}/list-libsgx-ra-uefi-devel +%files -n sgx-ra-service -f %{_specdir}/list-sgx-ra-service +%files -n sgx-pck-id-retrieval-tool -f %{_specdir}/list-sgx-pck-id-retrieval-tool + +%post +if [ -x %{_aesm_service_path}/startup.sh ]; then %{_aesm_service_path}/startup.sh; fi + +%preun +if [ -x %{_aesm_service_path}/cleanup.sh ]; then %{_aesm_service_path}/cleanup.sh; fi + +%post -n sgx-dcap-pccs +if [ -x %{_dcap_pccs_path}/startup.sh ]; then %{_dcap_pccs_path}/startup.sh; fi + +%preun -n sgx-dcap-pccs +if [ -x %{_dcap_pccs_path}/cleanup.sh ]; then %{_dcap_pccs_path}/cleanup.sh; fi + +%post -n sgx-ra-service +if [ -x %{_ra_service_path}/startup.sh ]; then %{_ra_service_path}/startup.sh; fi + +%preun -n sgx-ra-service +if [ -x %{_ra_service_path}/cleanup.sh ]; then %{_ra_service_path}/cleanup.sh; fi + +%post -n libsgx-enclave-common +trigger_udev() { + if ! which udevadm &> /dev/null; then + return 0 + fi + udevadm control --reload || : + udevadm trigger || : +} + +trigger_udev + +%post -n libsgx-ae-pce +trigger_udev() { + if ! which udevadm &> /dev/null; then + return 0 + fi + udevadm control --reload || : + udevadm trigger || : +} + +# Add sgx_prv for in-kernel driver. +if [ -c /dev/sgx_provision -o -c /dev/sgx/provision ]; then + getent group sgx_prv &> /dev/null || groupadd sgx_prv + trigger_udev +fi + +%changelog +* Mon Jun 7 2021 SGX Team +- Initial Release diff --git a/linux/installer/rpm/psw-dcap/sanitize.sh b/linux/installer/rpm/psw-dcap/sanitize.sh new file mode 100755 index 000000000..b5d7d700e --- /dev/null +++ b/linux/installer/rpm/psw-dcap/sanitize.sh @@ -0,0 +1,54 @@ +#!/usr/bin/env bash +# +# 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 -e + +tarball="linux-sgx" +psw_dcap="psw-dcap" + +cur_dir=$(dirname "$0") +root_dir="${cur_dir}/../../../../" +common_dir="${root_dir}/linux/installer/common" +common_psw_dcap_dir="${common_dir}/${psw_dcap}" +tarball_dir="${cur_dir}/${tarball}" + +make -C ${root_dir} preparation + +python ${common_dir}/gen_source/copy_source.py \ + --bom-file ${common_psw_dcap_dir}/BOM_source/psw-dcap-tarball.txt \ + --src-path ${root_dir} \ + --dst-path ${tarball_dir} \ + --cleanup + +tar -zcvf ${tarball}.tar.gz -C ${cur_dir} ${tarball} +rm -fr ${tarball_dir} diff --git a/linux/installer/rpm/sgx-aesm-service/libsgx-ae-pce.spec b/linux/installer/rpm/sgx-aesm-service/libsgx-ae-pce.spec index 31c0e2c3b..ebf1bc8ac 100644 --- a/linux/installer/rpm/sgx-aesm-service/libsgx-ae-pce.spec +++ b/linux/installer/rpm/sgx-aesm-service/libsgx-ae-pce.spec @@ -43,6 +43,8 @@ License: BSD License URL: https://github.com/intel/linux-sgx Source0: %{name}-%{version}.tar.gz +AutoProv: no + %description Intel(R) Software Guard Extensions PCE @@ -78,7 +80,7 @@ trigger_udev() { # Add sgx_prv for in-kernel driver. if [ -c /dev/sgx_provision -o -c /dev/sgx/provision ]; then - /usr/bin/getent group sgx_prv &> /dev/null || /usr/sbin/groupadd sgx_prv + getent group sgx_prv &> /dev/null || groupadd sgx_prv trigger_udev fi 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 c22dd7c82..aa50bbbc3 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.12 libsgx-aesm-pce-plugin >= %{version}-%{release} +Requires: sgx-aesm-service >= %{version}-%{release} libsgx-qe3-logic >= 1.13 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 4a3970422..36e3d1488 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.12 +Requires: sgx-aesm-service >= %{version}-%{release} libsgx-pce-logic >= 1.13 License: BSD License URL: https://github.com/intel/linux-sgx diff --git a/linux/reproducibility/build_and_launch_docker.sh b/linux/reproducibility/build_and_launch_docker.sh index f5e492911..da6837c1c 100755 --- a/linux/reproducibility/build_and_launch_docker.sh +++ b/linux/reproducibility/build_and_launch_docker.sh @@ -76,8 +76,8 @@ mount_dir="/linux-sgx" sdk_installer="" sgx_src="" -default_sdk_installer=sgx_linux_x64_sdk_reproducible_2.15.101.1.bin -default_sdk_installer_url=https://download.01.org/intel-sgx/sgx-linux/2.15.1/distro/nix_reproducibility/$default_sdk_installer +default_sdk_installer=sgx_linux_x64_sdk_reproducible_2.16.100.1.bin +default_sdk_installer_url=https://download.01.org/intel-sgx/sgx-linux/2.16/distro/nix_reproducibility/$default_sdk_installer usage() @@ -179,7 +179,7 @@ prepare_sgx_src() if [ "$sgx_src" != "" ]; then mkdir -p "$sgx_repo" && cp -a "$sgx_src/." "$sgx_repo" else - git clone -b sgx_2.15.101_reproducible https://github.com/intel/linux-sgx.git $sgx_repo + git clone -b sgx_2.16_reproducible https://github.com/intel/linux-sgx.git $sgx_repo fi cd "$sgx_repo" && make preparation diff --git a/linux/reproducibility/start_build.sh.tmp b/linux/reproducibility/start_build.sh.tmp index 827eaf298..8fa89de46 100644 --- a/linux/reproducibility/start_build.sh.tmp +++ b/linux/reproducibility/start_build.sh.tmp @@ -141,6 +141,8 @@ build_ae() cp qe.so $ae_out cd $sgx_repo/external/dcap_source/QuoteGeneration/quote_wrapper/quote/enclave/linux && make cp qe3.so $ae_out + cd $sgx_repo/external/dcap_source/QuoteGeneration/quote_wrapper/quote/id_enclave/linux && make + cp id_enclave.so $ae_out cd $sgx_repo/external/dcap_source/QuoteVerification/QvE && make cp qve.so $ae_out popd diff --git a/psw/ae/aesm_service/config/aesmd_service/aesmd.service b/psw/ae/aesm_service/config/aesmd_service/aesmd.service index 6ec62465b..253144667 100644 --- a/psw/ae/aesm_service/config/aesmd_service/aesmd.service +++ b/psw/ae/aesm_service/config/aesmd_service/aesmd.service @@ -28,5 +28,7 @@ DeviceAllow=/dev/isgx rw DeviceAllow=/dev/sgx rw DeviceAllow=/dev/sgx/enclave rw DeviceAllow=/dev/sgx/provision rw +DeviceAllow=/dev/sgx_enclave rw +DeviceAllow=/dev/sgx_provision rw [Install] WantedBy=multi-user.target diff --git a/psw/ae/aesm_service/source/CMakeLists.txt b/psw/ae/aesm_service/source/CMakeLists.txt index ac60d8816..07577d60a 100644 --- a/psw/ae/aesm_service/source/CMakeLists.txt +++ b/psw/ae/aesm_service/source/CMakeLists.txt @@ -32,6 +32,8 @@ if(SGX_DISABLE_PSE) add_definitions("-DSGX_DISABLE_PSE") endif() +add_definitions("-DOPENSSL_API_COMPAT=10101") + set(CMAKE_CXX_STANDARD_REQUIRED 1) set(CMAKE_CXX_STANDARD 11) set(CMAKE_SKIP_BUILD_RPATH true) diff --git a/psw/ae/aesm_service/source/core/main.cpp b/psw/ae/aesm_service/source/core/main.cpp index 0112a7b44..6e3f80bb6 100644 --- a/psw/ae/aesm_service/source/core/main.cpp +++ b/psw/ae/aesm_service/source/core/main.cpp @@ -89,10 +89,20 @@ int main(int argc, char *argv[]) { AESM_LOG_INIT_EX(noSyslog); - if(!noDaemon && daemon(0, 0) < 0) { - AESM_LOG_FATAL("Fail to set daemon."); - AESM_LOG_FINI(); - exit(1); + if(!noDaemon) { + fprintf (stderr, "aesm_service: warning: Turn to daemon. Use \"--no-daemon\" option to execute in foreground.\n"); + if(argv[0][0] != '/') { + AESM_LOG_FATAL("Require absolute path to set daemon."); + fprintf (stderr, "aesm_service: error: Require absolute path to set daemon.\n"); + AESM_LOG_FINI(); + exit(1); + } + if(daemon(0, 0) < 0) { + AESM_LOG_FATAL("Fail to set daemon."); + fprintf (stderr, "aesm_service: error: Fail to set daemon.\n"); + AESM_LOG_FINI(); + exit(1); + } } signal(SIGCHLD, SIG_IGN); signal(SIGHUP, signal_handler); @@ -105,6 +115,9 @@ int main(int argc, char *argv[]) { AESMLogicWrapper* aesmLogic = new AESMLogicWrapper(); if(aesmLogic->service_start()!=AE_SUCCESS){ AESM_LOG_ERROR("Fail to start service."); + if(noDaemon) { + fprintf (stderr, "aesm_service: error: Fail to start service.\n"); + } delete aesmLogic; AESM_LOG_FINI(); exit(1); diff --git a/psw/ae/aesm_service/source/oal/linux/aesm_util.cpp b/psw/ae/aesm_service/source/oal/linux/aesm_util.cpp index 95f718327..3861697da 100644 --- a/psw/ae/aesm_service/source/oal/linux/aesm_util.cpp +++ b/psw/ae/aesm_service/source/oal/linux/aesm_util.cpp @@ -198,14 +198,33 @@ ae_error_t aesm_get_pathname(aesm_data_type_t type, aesm_data_id_t id, char *buf if (xgid != INVALID_EGID){ return AE_FAILURE; } - if(strnlen(info->name, MAX_PATH)>=MAX_PATH-UPBOUND_OF_FORMAT){ + size_t length = strnlen(info->name, MAX_PATH); + if (length >= MAX_PATH-UPBOUND_OF_FORMAT) { return AE_FAILURE;//info->name is a constant string and the length of it should not be too long so that the defense in depth codition here should never be triggered. } - num_bytes = snprintf(local_info_name,MAX_PATH, "libsgx_%s.signed.so",info->name); - if(num_bytes<0||num_bytes>=MAX_PATH){ + strncpy(local_info_name, info->name, length + 1); + char * p_match = strstr(local_info_name, "signed.so"); + if (!p_match) { return AE_FAILURE; } - return aesm_get_path(local_info_name, buf, buf_size); + size_t signed_so_length = strlen("signed.so"); + if (p_match -local_info_name == length - signed_so_length) { + //info->name ends with "signed.so". Use whole name. + return aesm_get_path(local_info_name, buf, buf_size); + } + else if (p_match[signed_so_length] != '.') { + return AE_FAILURE; + } + else { + //info->name ends with "signed.so..". Use "signed.so.". + //skip "signed.so." and find next '.' + char* p_next_dot = strchr(p_match + signed_so_length + 1, '.' ); + if ( p_next_dot != NULL ) + { + *p_next_dot = '\0'; //null terminate the string + } + return aesm_get_path(local_info_name, buf, buf_size); + } }else if(info->loc == AESM_LOCATION_DATA){ if (xgid != INVALID_EGID){ return AE_FAILURE; diff --git a/psw/ae/aesm_service/source/oal/linux/persistent_storage_table.cpp b/psw/ae/aesm_service/source/oal/linux/persistent_storage_table.cpp index 42d442507..19aea936f 100644 --- a/psw/ae/aesm_service/source/oal/linux/persistent_storage_table.cpp +++ b/psw/ae/aesm_service/source/oal/linux/persistent_storage_table.cpp @@ -29,23 +29,23 @@ * */ - +#include "se_version.h" #include "persistent_storage_info.h" #include "util.h" //The ordering of the array must be same as the enumerartion aesm_data_id_t static const persistent_storage_info_t psinfos[]={ #ifdef REF_LE - { FT_ENCLAVE_NAME, AESM_LOCATION_EXE_FOLDER, AESM_FILE_ACCESS_PATH_ONLY, "ref_le" },//LE_ENCLAVE_FID + { FT_ENCLAVE_NAME, AESM_LOCATION_EXE_FOLDER, AESM_FILE_ACCESS_PATH_ONLY, "libsgx_ref_le.signed.so" },//LE_ENCLAVE_FID #else - { FT_ENCLAVE_NAME, AESM_LOCATION_EXE_FOLDER, AESM_FILE_ACCESS_PATH_ONLY, "le" },//LE_ENCLAVE_FID + { FT_ENCLAVE_NAME, AESM_LOCATION_EXE_FOLDER, AESM_FILE_ACCESS_PATH_ONLY, "libsgx_le.signed.so." LE_VERSION },//LE_ENCLAVE_FID #endif // REF_LE - {FT_ENCLAVE_NAME, AESM_LOCATION_EXE_FOLDER, AESM_FILE_ACCESS_PATH_ONLY, "qe"},//QE_ENCLAVE_FID - {FT_ENCLAVE_NAME, AESM_LOCATION_EXE_FOLDER, AESM_FILE_ACCESS_PATH_ONLY, "pve"},//PVE_ENCLAVE_FID - {FT_ENCLAVE_NAME, AESM_LOCATION_EXE_FOLDER, AESM_FILE_ACCESS_PATH_ONLY, "pse_op"},//PSE_OP_ENCLAVE_FID - {FT_ENCLAVE_NAME, AESM_LOCATION_EXE_FOLDER, AESM_FILE_ACCESS_PATH_ONLY, "pse_pr"},//PSE_PR_ENCLAVE_FID - {FT_ENCLAVE_NAME, AESM_LOCATION_EXE_FOLDER, AESM_FILE_ACCESS_PATH_ONLY, "pse_pr_2"},//PSE_PR_2_ENCLAVE_FID - {FT_ENCLAVE_NAME, AESM_LOCATION_EXE_FOLDER, AESM_FILE_ACCESS_PATH_ONLY, "pce"}, //PCE_ENCLAVE_FID + {FT_ENCLAVE_NAME, AESM_LOCATION_EXE_FOLDER, AESM_FILE_ACCESS_PATH_ONLY, "libsgx_qe.signed.so." QE_VERSION},//QE_ENCLAVE_FID + {FT_ENCLAVE_NAME, AESM_LOCATION_EXE_FOLDER, AESM_FILE_ACCESS_PATH_ONLY, "libsgx_pve.signed.so." PVE_VERSION},//PVE_ENCLAVE_FID + {FT_ENCLAVE_NAME, AESM_LOCATION_EXE_FOLDER, AESM_FILE_ACCESS_PATH_ONLY, "libsgx_pse_op.signed.so"},//PSE_OP_ENCLAVE_FID + {FT_ENCLAVE_NAME, AESM_LOCATION_EXE_FOLDER, AESM_FILE_ACCESS_PATH_ONLY, "libsgx_pse_pr.signed.so"},//PSE_PR_ENCLAVE_FID + {FT_ENCLAVE_NAME, AESM_LOCATION_EXE_FOLDER, AESM_FILE_ACCESS_PATH_ONLY, "libsgx_pse_pr_2.signed.so"},//PSE_PR_2_ENCLAVE_FID + {FT_ENCLAVE_NAME, AESM_LOCATION_EXE_FOLDER, AESM_FILE_ACCESS_PATH_ONLY, "libsgx_pce.signed.so." PCE_VERSION}, //PCE_ENCLAVE_FID {FT_PERSISTENT_STORAGE, AESM_LOCATION_EXE_FOLDER, AESM_FILE_ACCESS_PATH_ONLY, "le_prod_css.bin"},//LE_PROD_SIG_STRUCT_FID { FT_PERSISTENT_STORAGE, AESM_LOCATION_DATA, AESM_FILE_ACCESS_ALL, "active_extended_epid_group_id" }, // EXTENDED_EPID_GROUP_ID_FID { FT_PERSISTENT_STORAGE, AESM_LOCATION_MULTI_EXTENDED_EPID_GROUP_DATA, AESM_FILE_ACCESS_READ_ONLY, "extended_epid_group.blob" }, //EXTENDED_EPID_GROUP_BLOB_INFO_FID diff --git a/psw/ae/aesm_service/source/qcnl/CMakeLists.txt b/psw/ae/aesm_service/source/qcnl/CMakeLists.txt index 0feca6483..7fdafc30f 100644 --- a/psw/ae/aesm_service/source/qcnl/CMakeLists.txt +++ b/psw/ae/aesm_service/source/qcnl/CMakeLists.txt @@ -14,6 +14,7 @@ target_include_directories(sgx_default_qcnl_wrapper PRIVATE ${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 ) set_property(TARGET sgx_default_qcnl_wrapper APPEND_STRING PROPERTY LINK_FLAGS " -Wl,-z,defs") diff --git a/psw/ae/le/Makefile b/psw/ae/le/Makefile index 525f154d4..8923c8835 100644 --- a/psw/ae/le/Makefile +++ b/psw/ae/le/Makefile @@ -33,6 +33,7 @@ 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 @@ -52,7 +53,7 @@ CONFIG := config_linux.xml all: $(AENAME_OUT) $(SONAME): $(OBJS) - $(CXX) $(CXXFLAGS) -o $@ $(OBJS) -nostdlib -nodefaultlibs -nostartfiles $(LDTFLAGS) + $(CXX) $(CXXFLAGS) -o $@ $(OBJS) -nostdlib -nodefaultlibs -nostartfiles -Wl,-soname=libsgx_$(AENAME).signed.so.$(call SPLIT_VERSION,$(LE_VER),1) $(LDTFLAGS) $(STRIP) --strip-unneeded --remove-section=.comment --remove-section=.note $(SONAME) $(OBJ):$(AENAME)_t.c diff --git a/psw/ae/pce/Makefile b/psw/ae/pce/Makefile index d9d349d29..88ba9bffe 100644 --- a/psw/ae/pce/Makefile +++ b/psw/ae/pce/Makefile @@ -38,6 +38,8 @@ 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 \ @@ -59,7 +61,7 @@ all: pce_sim_private_key.pem endif $(SONAME): $(OBJS) - $(CXX) $(CXXFLAGS) -o $@ $(OBJS) -nostdlib -nodefaultlibs -nostartfiles $(LDTFLAGS) + $(CXX) $(CXXFLAGS) -o $@ $(OBJS) -nostdlib -nodefaultlibs -nostartfiles -Wl,-soname=libsgx_$(AENAME).signed.so.$(call SPLIT_VERSION,$(PCE_VER),1) $(LDTFLAGS) $(STRIP) --strip-unneeded --remove-section=.comment --remove-section=.note $(SONAME) pce.o: $(AENAME)_t.c diff --git a/psw/ae/pve/Makefile b/psw/ae/pve/Makefile index 8fb76cafd..171b6974b 100644 --- a/psw/ae/pve/Makefile +++ b/psw/ae/pve/Makefile @@ -36,6 +36,7 @@ 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 @@ -70,7 +71,7 @@ EPID: $(MAKE) -C $(EPID_SDK_DIR) 2> /dev/null $(SONAME): $(OBJS) EPID - $(CXX) $(CXXFLAGS) -o $@ $(OBJS) -nostdlib -nodefaultlibs -nostartfiles $(LDTFLAGS) + $(CXX) $(CXXFLAGS) -o $@ $(OBJS) -nostdlib -nodefaultlibs -nostartfiles -Wl,-soname=libsgx_$(AENAME).signed.so.$(call SPLIT_VERSION,$(PVE_VER),1) $(LDTFLAGS) $(STRIP) --strip-unneeded --remove-section=.comment --remove-section=.note $(SONAME) provision_enclave.o: $(AENAME)_t.c diff --git a/psw/ae/qe/Makefile b/psw/ae/qe/Makefile index 9571f932b..946399acd 100644 --- a/psw/ae/qe/Makefile +++ b/psw/ae/qe/Makefile @@ -36,6 +36,8 @@ 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 @@ -66,7 +68,7 @@ EPID: $(MAKE) -C $(EPID_SDK_DIR) 2> /dev/null $(SONAME): $(OBJS) EPID - $(CC) $(CFLAGS) -o $@ $(OBJS) -nostdlib -nodefaultlibs -nostartfiles $(LDTFLAGS) + $(CC) $(CFLAGS) -o $@ $(OBJS) -nostdlib -nodefaultlibs -nostartfiles -Wl,-soname=libsgx_$(AENAME).signed.so.$(call SPLIT_VERSION,$(QE_VER),1) $(LDTFLAGS) $(STRIP) --strip-unneeded --remove-section=.comment --remove-section=.note $(SONAME) $(OBJ): $(AENAME)_t.c diff --git a/psw/ae/qe/quoting_enclave.cpp b/psw/ae/qe/quoting_enclave.cpp index 78a0c27b4..6ae9ded32 100644 --- a/psw/ae/qe/quoting_enclave.cpp +++ b/psw/ae/qe/quoting_enclave.cpp @@ -292,13 +292,15 @@ uint32_t verify_blob( return QE_PARAMETER_ERROR; if(SGX_TRUSTED_EPID_BLOB_SIZE_SDK != blob_size) + { return QE_PARAMETER_ERROR; + } - // - // if we mispredict here and blob_size is too - // small, we might overflow - // - sgx_lfence(); + // + // if we mispredict here and blob_size is too + // small, we might overflow + // + sgx_lfence(); if(!sgx_is_within_enclave(p_blob, blob_size)) return QE_PARAMETER_ERROR; diff --git a/psw/ae/ref_le/Makefile b/psw/ae/ref_le/Makefile index f2b653dd2..6dd691271 100644 --- a/psw/ae/ref_le/Makefile +++ b/psw/ae/ref_le/Makefile @@ -66,7 +66,7 @@ REF_WL_GEN: $(MAKE) -C $(REF_WL_GEN_DIR) $(SONAME): $(AENAME)_t.o $(OBJ) - $(CXX) $(CXXFLAGS) -o $@ $(OBJ) $(AENAME)_t.o -nostdlib -nodefaultlibs -nostartfiles $(LDTFLAGS) + $(CXX) $(CXXFLAGS) -o $@ $(OBJ) $(AENAME)_t.o -nostdlib -nodefaultlibs -nostartfiles -Wl,-soname=${SIGNED_NAME}.$(call SPLIT_VERSION,$(LE_VER),1) $(LDTFLAGS) $(OBJ): %.o:%.cpp $(CXX) $(CXXFLAGS) -fno-exceptions -fno-rtti $(INCLUDE) $(DEFINES) -c $< -o $@ diff --git a/psw/enclave_common/sgx_enclave_common.cpp b/psw/enclave_common/sgx_enclave_common.cpp index ca881a4f4..b5aaa81e5 100644 --- a/psw/enclave_common/sgx_enclave_common.cpp +++ b/psw/enclave_common/sgx_enclave_common.cpp @@ -473,6 +473,11 @@ static void enclave_set_provision_access(int hdevice, void* enclave_base) { hdev_prov = open("/dev/sgx/provision", O_RDWR); if (-1 == hdev_prov) + { + //if /dev/sgx/provision is not present, try to open /dev/sgx_provision + hdev_prov = open("/dev/sgx_provision", O_RDWR); + } + if (-1 == hdev_prov) { //in-kernel driver can still succeed if the MRSIGNER is whitelisted for provision key SE_TRACE(SE_TRACE_WARNING, "\nOpen in-kernel driver node, failed: errno = %d\n", errno); diff --git a/psw/urts/linux/edmm_utility.cpp b/psw/urts/linux/edmm_utility.cpp index 40f572606..69e701a6b 100644 --- a/psw/urts/linux/edmm_utility.cpp +++ b/psw/urts/linux/edmm_utility.cpp @@ -101,6 +101,11 @@ bool get_driver_type(int *driver_type) int hdev = open("/dev/sgx/enclave", O_RDWR); //attempt to open the in-kernel driver if (-1 == hdev) + { + //if /dev/sgx/enclave is not present, try to open /dev/sgx_enclave + hdev = open("/dev/sgx_enclave", O_RDWR); + } + if (-1 == hdev) { hdev = open("/dev/isgx", O_RDWR); //attempt to open the out-of-tree driver if (-1 == hdev) @@ -150,6 +155,11 @@ extern "C" bool open_se_device(int driver_type, int *hdevice) if (driver_type == SGX_DRIVER_IN_KERNEL) { *hdevice = open("/dev/sgx/enclave", O_RDWR); //attempt to open the in-kernel driver + //if /dev/sgx/enclave is not present, try to open /dev/sgx_enclave + if(-1 == *hdevice) + { + *hdevice = open("/dev/sgx_enclave", O_RDWR); + } } else if (driver_type == SGX_DRIVER_DCAP) { diff --git a/psw/urts/linux/enclave_creator_hw.cpp b/psw/urts/linux/enclave_creator_hw.cpp index e7f3ebe71..d956e8181 100644 --- a/psw/urts/linux/enclave_creator_hw.cpp +++ b/psw/urts/linux/enclave_creator_hw.cpp @@ -170,9 +170,11 @@ int EnclaveCreatorHW::error_api2urts(uint32_t api_error) ret = SGX_ERROR_INVALID_PARAMETER; break; case ENCLAVE_OUT_OF_MEMORY: - case ENCLAVE_DEVICE_NO_RESOURCES: ret = SGX_ERROR_OUT_OF_MEMORY; break; + case ENCLAVE_DEVICE_NO_RESOURCES: + ret = SGX_ERROR_OUT_OF_EPC; + break; case ENCLAVE_SERVICE_TIMEOUT: ret = SGX_ERROR_SERVICE_TIMEOUT; break; diff --git a/psw/urts/linux/enter_enclave.S b/psw/urts/linux/enter_enclave.S index 8591d4072..fc3828e11 100644 --- a/psw/urts/linux/enter_enclave.S +++ b/psw/urts/linux/enter_enclave.S @@ -53,6 +53,32 @@ DECLARE_GLOBAL_FUNC set_xsave_info movl %edx, (%xax) ret +DECLARE_GLOBAL_FUNC vdso_sgx_enter_enclave_wrapper +EENTER_PROLOG + movl frame_arg0, %edi +#if defined(__x86_64__) + /* we defined fn as int, so we do sign extend.*/ + movslq %edi, %rdi +#endif + mov frame_arg1, %xsi + mov frame_arg2, %xdx + # clean the upper bits of YMM registers + lea_symbol g_clean_ymm, %xbx + movl (%xbx), %ecx + cmpl $0, %ecx + je 1f + vzeroupper + 1: + sub $(1*SE_WORDSIZE), %xsp + mov 2*SE_WORDSIZE(%xbp), %xcx + push %xcx + mov frame_arg3, %xcx + lea_pic vdso_sgx_enter_enclave, %r10 + call *(%r10) + mov %xax, %xsi +EENTER_EPILOG + + DECLARE_GLOBAL_FUNC __morestack //__morestack: @@ -134,6 +160,7 @@ EENTER_PROLOG .Lasync_exit_pointer: ENCLU + _CET_ENDBR .size __morestack, .-__morestack diff --git a/psw/urts/linux/isgx_user.h b/psw/urts/linux/isgx_user.h index 007dfd863..3c4dfdd00 100644 --- a/psw/urts/linux/isgx_user.h +++ b/psw/urts/linux/isgx_user.h @@ -283,4 +283,98 @@ struct sgx_modification_param { unsigned long flags; }; + + +struct sgx_enclave_run; + +/** + * typedef sgx_enclave_user_handler_t - Exit handler function accepted by + * __vdso_sgx_enter_enclave() + * @run: The run instance given by the caller + * + * The register parameters contain the snapshot of their values at enclave + * exit. An invalid ENCLU function number will cause -EINVAL to be returned + * to the caller. + * + * Return: + * - <= 0: The given value is returned back to the caller. + * - > 0: ENCLU function to invoke, either EENTER or ERESUME. + */ +typedef int (*sgx_enclave_user_handler_t)(long rdi, long rsi, long rdx, + long rsp, long r8, long r9, + struct sgx_enclave_run *run); + +/** + * struct sgx_enclave_run - the execution context of __vdso_sgx_enter_enclave() + * @tcs: TCS used to enter the enclave + * @function: The last seen ENCLU function (EENTER, ERESUME or EEXIT) + * @exception_vector: The interrupt vector of the exception + * @exception_error_code: The exception error code pulled out of the stack + * @exception_addr: The address that triggered the exception + * @user_handler: User provided callback run on exception + * @user_data: Data passed to the user handler + * @reserved Reserved for future extensions + * + * If @user_handler is provided, the handler will be invoked on all return paths + * of the normal flow. The user handler may transfer control, e.g. via a + * longjmp() call or a C++ exception, without returning to + * __vdso_sgx_enter_enclave(). + */ +struct sgx_enclave_run { + __u64 tcs; + __u32 function; + __u16 exception_vector; + __u16 exception_error_code; + __u64 exception_addr; + __u64 user_handler; + __u64 user_data; + __u8 reserved[216]; +}; + +/** + * typedef vdso_sgx_enter_enclave_t - Prototype for __vdso_sgx_enter_enclave(), + * a vDSO function to enter an SGX enclave. + * @rdi: Pass-through value for RDI + * @rsi: Pass-through value for RSI + * @rdx: Pass-through value for RDX + * @function: ENCLU function, must be EENTER or ERESUME + * @r8: Pass-through value for R8 + * @r9: Pass-through value for R9 + * @run: struct sgx_enclave_run, must be non-NULL + * + * NOTE: __vdso_sgx_enter_enclave() does not ensure full compliance with the + * x86-64 ABI, e.g. doesn't handle XSAVE state. Except for non-volatile + * general purpose registers, EFLAGS.DF, and RSP alignment, preserving/setting + * state in accordance with the x86-64 ABI is the responsibility of the enclave + * and its runtime, i.e. __vdso_sgx_enter_enclave() cannot be called from C + * code without careful consideration by both the enclave and its runtime. + * + * All general purpose registers except RAX, RBX and RCX are passed as-is to the + * enclave. RAX, RBX and RCX are consumed by EENTER and ERESUME and are loaded + * with @function, asynchronous exit pointer, and @run.tcs respectively. + * + * RBP and the stack are used to anchor __vdso_sgx_enter_enclave() to the + * pre-enclave state, e.g. to retrieve @run.exception and @run.user_handler + * after an enclave exit. All other registers are available for use by the + * enclave and its runtime, e.g. an enclave can push additional data onto the + * stack (and modify RSP) to pass information to the optional user handler (see + * below). + * + * Most exceptions reported on ENCLU, including those that occur within the + * enclave, are fixed up and reported synchronously instead of being delivered + * via a standard signal. Debug Exceptions (#DB) and Breakpoints (#BP) are + * never fixed up and are always delivered via standard signals. On synchrously + * reported exceptions, -EFAULT is returned and details about the exception are + * recorded in @run.exception, the optional sgx_enclave_exception struct. + * + * Return: + * - 0: ENCLU function was successfully executed. + * - -EINVAL: Invalid ENCL number (neither EENTER nor ERESUME). + */ +typedef int (*vdso_sgx_enter_enclave_t)(unsigned long rdi, unsigned long rsi, + unsigned long rdx, unsigned int function, + unsigned long r8, unsigned long r9, + struct sgx_enclave_run *run); + + #endif /* _UAPI_ASM_X86_SGX_H */ diff --git a/psw/urts/linux/sig_handler.cpp b/psw/urts/linux/sig_handler.cpp index 81a6d5e27..1e0c16bdc 100644 --- a/psw/urts/linux/sig_handler.cpp +++ b/psw/urts/linux/sig_handler.cpp @@ -40,6 +40,11 @@ #include #include #include +#include "isgx_user.h" +#include +#include +#include "se_error_internal.h" + typedef struct _ecall_param_t @@ -85,8 +90,17 @@ extern "C" void *get_aep(); extern "C" void *get_eenterp(); extern "C" void *get_eretp(); static struct sigaction g_old_sigact[_NSIG]; +vdso_sgx_enter_enclave_t vdso_sgx_enter_enclave = NULL; +extern "C" int vdso_sgx_enter_enclave_wrapper(unsigned long rdi, unsigned long rsi, + unsigned long rdx, unsigned int function, + unsigned long r8, unsigned long r9, + struct sgx_enclave_run *run); + + void reg_sig_handler(); +int do_ecall(const int fn, const void *ocall_table, const void *ms, CTrustThread *trust_thread); + void sig_handler(int signum, siginfo_t* siginfo, void *priv) { @@ -186,13 +200,19 @@ void sig_handler(int signum, siginfo_t* siginfo, void *priv) void reg_sig_handler() { + if(vdso_sgx_enter_enclave != NULL) + { + SE_TRACE(SE_TRACE_DEBUG, "vdso_sgx_enter_enclave exists, we won't use signal handler here\n"); + return; + } int ret = 0; struct sigaction sig_act; SE_TRACE(SE_TRACE_DEBUG, "signal handler is registered\n"); memset(&sig_act, 0, sizeof(sig_act)); sig_act.sa_sigaction = sig_handler; - sig_act.sa_flags = SA_SIGINFO | SA_NODEFER | SA_RESTART; + sig_act.sa_flags = SA_SIGINFO | SA_NODEFER | SA_RESTART | SA_ONSTACK; + sigemptyset(&sig_act.sa_mask); if(sigprocmask(SIG_SETMASK, NULL, &sig_act.sa_mask)) { @@ -224,10 +244,149 @@ void reg_sig_handler() extern "C" int enter_enclave(const tcs_t *tcs, const long fn, const void *ocall_table, const void *ms, CTrustThread *trust_thread); +extern "C" int stack_sticker(unsigned int proc, sgx_ocall_table_t *ocall_table, void *ms, CTrustThread *trust_thread, tcs_t *tcs); + +void* get_vdso_sym(const char* vdso_func_name) +{ + void *ret = NULL; + + uint8_t* vdso_address = (uint8_t*)getauxval(AT_SYSINFO_EHDR); + if(vdso_address == NULL) + { + return ret; + } + + auto elf64_header = (Elf64_Ehdr*)vdso_address; + auto section_header = (Elf64_Shdr*)(vdso_address + elf64_header->e_shoff); + auto sh_num = elf64_header->e_shnum; + char* dynstr = 0; + auto dynsym_header = section_header[0]; + auto found = false; + auto& section_name_string = section_header[elf64_header->e_shstrndx]; + + for (int i = 0; i < sh_num; i++) { + auto& sc_header = section_header[i]; + auto sc_name = (char*)(vdso_address + section_name_string.sh_offset + sc_header.sh_name); + if (strcmp(sc_name, ".dynstr") == 0) { + dynstr = (char*)(vdso_address + sc_header.sh_offset); + } + + if (strcmp(sc_name, ".dynsym") == 0) { + dynsym_header = sc_header; + found = true; + } + + if(dynstr != NULL && found == true){ + for (unsigned int si = 0; si < (dynsym_header.sh_size/dynsym_header.sh_entsize); si++) { + auto &sym = ((Elf64_Sym*)(vdso_address + dynsym_header.sh_offset))[si]; + auto vdname = dynstr + sym.st_name; + if (strcmp(vdname, vdso_func_name) == 0) { + ret = (vdso_address + sym.st_value); + break; + } + } + break; + } + } + + return ret; +} + + +static int sgx_urts_vdso_handler(long rdi, long rsi, long rdx, long ursp, long r8, long r9, + struct sgx_enclave_run *run) +{ + UNUSED(rdx); + UNUSED(ursp); + UNUSED(r8); + UNUSED(r9); + if(run->function == SE_ERESUME) + { + //need to handle exception here + __u64 *user_data = (__u64*)run->user_data; + void *ocall_table = reinterpret_cast(user_data[0]); + CTrustThread* trust_thread = reinterpret_cast(user_data[1]); + if(ocall_table == NULL || trust_thread == NULL) + { + run->user_data = SGX_ERROR_UNEXPECTED; + return 0; + } + + unsigned int ret = do_ecall(ECMD_EXCEPT, ocall_table, NULL, trust_thread); + if(SGX_SUCCESS == ret) + { + return SE_ERESUME; + } + else + { + //for vDSO handler, we have to return error code to trts + //instead of calling old signal handler if registered + run->user_data = (__u64)ret; + return 0; + } + } + else if(run->function == SE_EEXIT) + { + //return 0 for normal enclave ecall return + //return EENTER after invoking proper ocall with runtime specific convention + if(rdi == OCMD_ERET) + { + run->user_data = (__u64)rsi; + return 0; + } + else + { + __u64 *user_data = (__u64*)run->user_data; + sgx_ocall_table_t *ocall_table = reinterpret_cast(user_data[0]); + CTrustThread* trust_thread = reinterpret_cast(user_data[1]); + if(ocall_table == NULL || trust_thread == NULL) + { + run->user_data = SGX_ERROR_UNEXPECTED; + return 0; + } + + auto status = stack_sticker((unsigned int )rdi, ocall_table, (void *)rsi, + trust_thread, trust_thread->get_tcs()); + if(status == (int)SE_ERROR_READ_LOCK_FAIL) + { + run->user_data = SE_ERROR_READ_LOCK_FAIL; + return 0; + } + //move the ocall return result to rsi and set rdi to ECMD_ORET for ocall return to trts + __asm__ __volatile__("mov %%rax, %%rsi\n" + "mov %0, %%rdi\n" + : + :"i"(ECMD_ORET) + :"rsi","rdi"); + return SE_EENTER; + } + } + else if(run->function == SE_EENTER) + { + //enclave may lose EPC context due to power events + run->user_data = SGX_ERROR_ENCLAVE_LOST; + return 0; + } + + return 0; +} + +static void __attribute__((constructor)) vdso_detector(void) +{ +#ifdef SE_SIM + vdso_sgx_enter_enclave = NULL; +#else + if(vdso_sgx_enter_enclave == NULL) + { + vdso_sgx_enter_enclave = (vdso_sgx_enter_enclave_t)get_vdso_sym("__vdso_sgx_enter_enclave"); + } +#endif +} + int do_ecall(const int fn, const void *ocall_table, const void *ms, CTrustThread *trust_thread) { - int status = SGX_ERROR_UNEXPECTED; + int status = SGX_ERROR_UNEXPECTED; #ifdef SE_SIM CEnclave* enclave = trust_thread->get_enclave(); @@ -236,11 +395,35 @@ int do_ecall(const int fn, const void *ocall_table, const void *ms, CTrustThread if((pid_t)(eid >> 32) != getpid()) return SGX_ERROR_ENCLAVE_LOST; #endif - + tcs_t *tcs = trust_thread->get_tcs(); - - status = enter_enclave(tcs, fn, ocall_table, ms, trust_thread); - + + if(vdso_sgx_enter_enclave == NULL) + { + status = enter_enclave(tcs, fn, ocall_table, ms, trust_thread); + } + else + { + struct sgx_enclave_run run; + memset(&run, 0, sizeof(run)); + __u64 user_data[2] = {0}; + user_data[0] = (__u64)ocall_table; + user_data[1] = (__u64)trust_thread; + run.tcs = (__u64)tcs; + run.user_handler = (__u64)sgx_urts_vdso_handler; + run.user_data = (__u64) user_data; + int ret = vdso_sgx_enter_enclave_wrapper((unsigned long)fn, (unsigned long)ms, (unsigned long)ocall_table, SE_EENTER, + 0, 0, &run); + if(ret == 0) + { + status = (int)run.user_data; + } + else + { + status = SGX_ERROR_UNEXPECTED; + } + } + return status; } diff --git a/psw/urts/se_detect.cpp b/psw/urts/se_detect.cpp index 5d9d462fb..5528aa99b 100644 --- a/psw/urts/se_detect.cpp +++ b/psw/urts/se_detect.cpp @@ -32,6 +32,7 @@ #include "se_detect.h" #include "cpuid.h" +#include "sgx_attributes.h" bool is_se_supported() { @@ -70,6 +71,29 @@ bool try_read_xcr0(uint64_t *value) return true; } +bool check_pkru() +{ + int cpu_info[4] = {0, 0, 0, 0}; + + // Check if CR4.PKE is set. If yes, protection keys for usermode pages are enabled + // and OS supports the use of PKRU register. + __cpuidex(cpu_info, CPUID_FEATURE_FLAGS, 0); + if(!(cpu_info[2] & (1 << PKU_SHIFT)) || !(cpu_info[2] & (1 << PKE_SHIFT))) + { + return false; + } + + // Check if SECS.ATTRIBUTES.XFRM.PKRU can be set + cpu_info[0] = cpu_info[1] = cpu_info[2] = cpu_info[3] = 0; + __cpuidex(cpu_info, SE_LEAF, 1); + + if(!(cpu_info[2] & (1 << PKRU_SHIFT))) + { + return false; + } + return true; +} + bool get_plat_cap_by_cpuid(sgx_misc_attribute_t *se_misc_attr) { int cpu_info[4] = {0, 0, 0, 0}; @@ -91,6 +115,11 @@ bool get_plat_cap_by_cpuid(sgx_misc_attribute_t *se_misc_attr) { se_misc_attr->secs_attr.xfrm &= (((uint64_t)cpu_info[3] << 32) | cpu_info[2]); } + + if(check_pkru() == false) + { + se_misc_attr->secs_attr.xfrm &= ~(SGX_XFRM_PKRU); + } // use cpuid to get the misc_select __cpuidex(cpu_info, SE_LEAF, 0); se_misc_attr->misc_select = cpu_info[1]; diff --git a/psw/urts/se_detect.h b/psw/urts/se_detect.h index 6368b8f56..2bb02b613 100644 --- a/psw/urts/se_detect.h +++ b/psw/urts/se_detect.h @@ -40,6 +40,8 @@ #define CPUID_FEATURE_FLAGS 7 #define SE_FEATURE_SHIFT 2 #define SE1_SHIFT 0 +// ECX[9] +#define PKRU_SHIFT 9 // CPUID function 1 // ECX[26] enums general support for XSAVE @@ -51,6 +53,12 @@ // EAX[1] enums support for compaction extensions to XSAVE #define XSAVEC_SHIFT 1 +// CPUID function 07H, sub-function 0 +// ECX[3] enums whether protection key feature is supported for user mode pages. +// ECX[4] enums whether the OS supports use of the PKRU or not +#define PKU_SHIFT 3 +#define PKE_SHIFT 4 + bool is_se_supported(); bool try_read_xcr0(uint64_t *value); diff --git a/sdk/Makefile.source b/sdk/Makefile.source index 98d1b0115..6ebb8fb33 100644 --- a/sdk/Makefile.source +++ b/sdk/Makefile.source @@ -43,11 +43,13 @@ # - sgx_pcl: libsgx_pcl.a # - openmp: libsgx_omp.a # - protobuf: libsgx_protobuf.a +# - ttls: libsgx_ttls.a # - Untrtusted libraries # - ukey_exchange: libsgx_ukey_exchange.a # - uprotected_fs: libsgx_uprotected_fs.a # - ptrace: libsgx_ptrace.so, gdb-sgx-plugin # - sample_crypto: libsample_crypto.so (for sample code use) +# - utls: libsgx_utls.a # - Standalone, untrusted libraries # - libcapable: libsgx_capable.a libsgx_capable.so # - Tools @@ -64,7 +66,7 @@ LIBTCXX := $(BUILD_DIR)/libsgx_tcxx.a LIBTSE := $(BUILD_DIR)/libsgx_tservice.a .PHONY: components -components: tstdc tcxx tservice trts tcrypto tkey_exchange ukey_exchange tprotected_fs uprotected_fs ptrace sample_crypto libcapable simulation signtool edger8r tcmalloc sgx_pcl sgx_encrypt sgx_tswitchless sgx_uswitchless pthread openmp protobuf +components: tstdc tcxx tservice trts tcrypto tkey_exchange ukey_exchange tprotected_fs uprotected_fs ptrace sample_crypto libcapable simulation signtool edger8r tcmalloc sgx_pcl sgx_encrypt sgx_tswitchless sgx_uswitchless pthread openmp protobuf ttls utls # --------------------------------------------------- # tstdc @@ -74,7 +76,7 @@ components: tstdc tcxx tservice trts tcrypto tkey_exchange ukey_exchange tprotec tstdc: $(LIBTLIBC) $(LIBTLIBC): tlibthread compiler-rt tsafecrt tsetjmp tmm_rsrv - $(MAKE) -C tlibc/ -j4 2> /dev/null + $(MAKE) -C tlibc/ -j$(shell nproc) 2> /dev/null @$(MKDIR) $(BUILD_DIR)/.compiler-rt $(BUILD_DIR)/.tlibthread $(BUILD_DIR)/.tsafecrt $(BUILD_DIR)/.tsetjmp $(BUILD_DIR)/.tmm_rsrv @$(RM) -f $(BUILD_DIR)/.compiler-rt/* && cd $(BUILD_DIR)/.compiler-rt && $(AR) x $(LINUX_SDK_DIR)/compiler-rt/libcompiler-rt.a @$(RM) -f $(BUILD_DIR)/.tlibthread/* && cd $(BUILD_DIR)/.tlibthread && $(AR) x $(LINUX_SDK_DIR)/tlibthread/libtlibthread.a @@ -204,7 +206,16 @@ openmp: .PHONY: protobuf protobuf: +ifeq ($(MITIGATION-CVE-2020-0551),) + $(MAKE) -C $(LINUX_EXTERNAL_DIR)/protobuf BUILD_PROTOC=1 +else $(MAKE) -C $(LINUX_EXTERNAL_DIR)/protobuf +endif + +.PHONY: ttls +ttls: edger8r + $(MAKE) -C ttls + # --------------------------------------------------- # Untrusted libraries # --------------------------------------------------- @@ -224,6 +235,10 @@ ptrace: sample_crypto: $(MAKE) -C sample_libcrypto +.PHONY: utls +utls: + $(MAKE) -C utls + # --------------------------------------------------- # standalone, untrusted libraries # --------------------------------------------------- @@ -299,5 +314,7 @@ clean: $(MAKE) -C pthread clean $(MAKE) -C $(LINUX_EXTERNAL_DIR)/openmp clean $(MAKE) -C $(LINUX_EXTERNAL_DIR)/protobuf clean + $(MAKE) -C ttls clean + $(MAKE) -C utls clean @$(RM) $(LIBTLIBC) $(LIBTCXX) $(LIBTSE) @$(RM) $(BUILD_DIR)/libc++_Changes_SGX.txt diff --git a/sdk/cpprt/Makefile b/sdk/cpprt/Makefile index 544f86ee4..d1ac38a15 100644 --- a/sdk/cpprt/Makefile +++ b/sdk/cpprt/Makefile @@ -83,7 +83,7 @@ $(CPPRT): $(OBJS) prepare-libunwind libunwind libunwind: cd $(LIBUNWIND_DIR)/ && \ ( test -f Makefile || CFLAGS="$(CFLAGS)" ./autogen.sh ) && \ - $(MAKE) -j5 + $(MAKE) -j$(shell nproc) .PHONY: clean diff --git a/sdk/cpprt/linux/libunwind/src/se-iterate-phdr.c b/sdk/cpprt/linux/libunwind/src/se-iterate-phdr.c index 76c84d749..8d1144507 100644 --- a/sdk/cpprt/linux/libunwind/src/se-iterate-phdr.c +++ b/sdk/cpprt/linux/libunwind/src/se-iterate-phdr.c @@ -37,6 +37,7 @@ #endif #include +extern void *get_enclave_base(void); /** * This function is commonly provided by glibc for application to walk * through list of shared objects. It is needed inside Enclave so that @@ -51,7 +52,7 @@ int dl_iterate_phdr( ElfW(Ehdr) *ehdr; memset(&info, 0, sizeof(info)); - ehdr = (ElfW(Ehdr) *) &__ImageBase; + ehdr = (ElfW(Ehdr) *) get_enclave_base(); info.dlpi_addr = (ElfW(Addr)) ehdr; info.dlpi_name = ""; diff --git a/sdk/gperftools/gperftools-2.7/configure.ac b/sdk/gperftools/gperftools-2.7/configure.ac index c0c30efd9..bcc01eb50 100644 --- a/sdk/gperftools/gperftools-2.7/configure.ac +++ b/sdk/gperftools/gperftools-2.7/configure.ac @@ -160,7 +160,7 @@ AS_IF([test -n "$OBJCOPY"], [dnl [gpt_cv_objcopy_weaken=no]) AM_CONDITIONAL(HAVE_OBJCOPY_WEAKEN, test $gpt_cv_objcopy_weaken = yes) -AC_PROG_LIBTOOL +LT_INIT AC_C_INLINE AX_C___ATTRIBUTE__ diff --git a/sdk/libcapable/linux/Makefile b/sdk/libcapable/linux/Makefile index d1f4cba73..793e3584f 100644 --- a/sdk/libcapable/linux/Makefile +++ b/sdk/libcapable/linux/Makefile @@ -36,9 +36,9 @@ CXXFLAGS += -DDISABLE_TRACE CFLAGS += -DDISABLE_TRACE endif -CXXFLAGS += -fPIC -Werror +CXXFLAGS += -fPIC -Werror $(CET_FLAGS) -CFLAGS += -fPIC -Werror +CFLAGS += -fPIC -Werror $(CET_FLAGS) LDFLAGS += $(COMMON_LDFLAGS) INC += -I$(COMMON_DIR)/inc \ diff --git a/sdk/protected_code_loader/pcl_entry.cpp b/sdk/protected_code_loader/pcl_entry.cpp index c25ef7768..25643e082 100644 --- a/sdk/protected_code_loader/pcl_entry.cpp +++ b/sdk/protected_code_loader/pcl_entry.cpp @@ -35,7 +35,7 @@ #include #include #include - +#include "rts.h" /* * g_tbl holds the PCL table. Its content is set by enclave encryption tool at build time * It is located in its own section (PCLTBL_SECTION_NAME) so that @@ -66,7 +66,7 @@ uintptr_t g_pcl_imagebase = 0; * trusted runtime entry point. It extracts the decryption key from the sealed blob * and use it to decrypt the encrypted portions of the enclave binary. * @param INOUT void* elf_base, base address of enclave - * @param IN void* sealed_blob, the sealed blob + * @param IN void* ms, the marshaling struture passed by urts * @return sgx_status_t * SGX_ERROR_UNEXPECTED if * 1. Table inconsistencies: @@ -76,7 +76,7 @@ uintptr_t g_pcl_imagebase = 0; * Respective error returned from pcl_unseal_data, pcl_sha256, pcl_gcm_decrypt or pcl_increment_iv * SGX_SUCCESS if successfull */ -sgx_status_t pcl_entry(void* elf_base, void* sealed_blob) +sgx_status_t pcl_entry(void* elf_base, void* ms) { sgx_status_t ret = SGX_SUCCESS; pcl_table_t* tbl = &g_tbl; @@ -103,6 +103,18 @@ sgx_status_t pcl_entry(void* elf_base, void* sealed_blob) { return SGX_ERROR_UNEXPECTED; } + system_features_t * csi = (system_features_t *)ms; + if(!(pcl_is_outside_enclave(csi, sizeof(*csi)))) + { + return SGX_ERROR_UNEXPECTED; + } + sgx_lfence(); + + void *sealed_blob = csi->sealed_key; + if(NULL == sealed_blob) + { + return SGX_ERROR_UNEXPECTED; + } if(!(pcl_is_outside_enclave(sealed_blob, PCL_SEALED_BLOB_SIZE))) { return SGX_ERROR_UNEXPECTED; diff --git a/sdk/protected_fs/sgx_uprotected_fs/Makefile b/sdk/protected_fs/sgx_uprotected_fs/Makefile index 8fdbce8b5..5c0d19b02 100644 --- a/sdk/protected_fs/sgx_uprotected_fs/Makefile +++ b/sdk/protected_fs/sgx_uprotected_fs/Makefile @@ -36,7 +36,7 @@ INCLUDE += -I. \ -I$(COMMON_DIR)/inc/internal \ -I$(COMMON_DIR)/inc -CXXFLAGS += -fPIC -fno-rtti -Werror $(INCLUDE) +CXXFLAGS += -fPIC -fno-rtti -Werror $(INCLUDE) $(CET_FLAGS) SRC := $(wildcard *.cpp) OBJ := $(sort $(SRC:.cpp=.o)) diff --git a/sdk/selib/sgx_verify_report2.cpp b/sdk/selib/sgx_verify_report2.cpp new file mode 100644 index 000000000..6e9c85aa8 --- /dev/null +++ b/sdk/selib/sgx_verify_report2.cpp @@ -0,0 +1,158 @@ +/* + * 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. + * + */ + + +/** + * File: sgx_verify_report2.cpp + * Description: + * API for the mac structure of the cryptographic report verification + */ + +#include "sgx_utils.h" +#include "util.h" +#include +#include +#include "se_memcpy.h" +#include "sgx_trts.h" +#include "se_cdefs.h" +#include "sgx_report2.h" +#include "trts_inst.h" + +// add a version to tservice. +SGX_ACCESS_VERSION(tservice, 4) + + +sgx_status_t sgx_verify_report2(const sgx_report2_mac_struct_t *report_mac_struct) +{ + sgx_status_t err = SGX_ERROR_UNEXPECTED; + void *buffer = NULL; + size_t size = 0, buf_ptr = 0; + sgx_report2_mac_struct_t *tmp_report2_mac_struct = NULL; + everifyreport2_status_t everifyreport2_status = EVERIFYREPORT2_SUCCESS; + size_t i = 0; + // check parameters + // + // report must be within the enclave + if (!report_mac_struct || !sgx_is_within_enclave(report_mac_struct, sizeof(*report_mac_struct))) + { + err = SGX_ERROR_INVALID_PARAMETER; + goto CLEANUP; + } + + if (report_mac_struct->report_type.type != TEE_REPORT2_TYPE) + { + err = SGX_ERROR_INVALID_PARAMETER; + goto CLEANUP; + } + + if (report_mac_struct->report_type.subtype != TEE_REPORT2_SUBTYPE + || report_mac_struct->report_type.version != TEE_REPORT2_VERSION) + { + err = SGX_ERROR_INVALID_PARAMETER; + goto CLEANUP; + } + + //reserved bytes must be zero + if (report_mac_struct->report_type.reserved != 0) + { + err = SGX_ERROR_INVALID_PARAMETER; + goto CLEANUP; + } + + for (i = 0; i < sizeof(report_mac_struct->reserved1); ++i) + { + if (report_mac_struct->reserved1[i] != 0) + { + err = SGX_ERROR_INVALID_PARAMETER; + goto CLEANUP; + } + } + for (i = 0; i < sizeof(report_mac_struct->reserved2); ++i) + { + if (report_mac_struct->reserved2[i] != 0) + { + err = SGX_ERROR_INVALID_PARAMETER; + goto CLEANUP; + } + } + + // allocate memory + // + size = ROUND_TO(sizeof(sgx_report2_mac_struct_t), REPORT2_MAC_STRUCT_ALIGN_SIZE); + size += (REPORT2_MAC_STRUCT_ALIGN_SIZE - 1); + + buffer = malloc(size); + if (buffer == NULL) + { + err = SGX_ERROR_OUT_OF_MEMORY; + goto CLEANUP; + } + memset(buffer, 0, size); + buf_ptr = reinterpret_cast(buffer); + + buf_ptr = ROUND_TO(buf_ptr, REPORT2_MAC_STRUCT_ALIGN_SIZE); + tmp_report2_mac_struct = reinterpret_cast(buf_ptr); + + // Copy data from user buffer to the aligned memory + if (0 != memcpy_s(tmp_report2_mac_struct, sizeof(*tmp_report2_mac_struct), report_mac_struct, sizeof(*report_mac_struct))) { + err = SGX_ERROR_UNEXPECTED; + goto CLEANUP; + } + + // Do EVERIFYREPORT2 + everifyreport2_status = (everifyreport2_status_t)do_everifyreport2(tmp_report2_mac_struct); + switch (everifyreport2_status) + { + case EVERIFYREPORT2_SUCCESS: + err = SGX_SUCCESS; + break; + case EVERIFYREPORT2_INVALID_REPORTMACSTRUCT: + err = SGX_ERROR_MAC_MISMATCH; + break; + case EVERIFYREPORT2_INVALID_CPUSVN: + err = SGX_ERROR_INVALID_CPUSVN; + break; + case EVERIFYREPORT2_INVALID_LEAF: + err = SGX_ERROR_FEATURE_NOT_SUPPORTED; + break; + default: + err = SGX_ERROR_UNEXPECTED; + break; + } + +CLEANUP: + if (buffer) + { + free(buffer); + buffer = NULL; + } + return err; +} diff --git a/sdk/sign_tool/SignTool/Makefile b/sdk/sign_tool/SignTool/Makefile index 901850891..e0d241642 100644 --- a/sdk/sign_tool/SignTool/Makefile +++ b/sdk/sign_tool/SignTool/Makefile @@ -34,8 +34,8 @@ include ../../../buildenv.mk CXXFLAGS += -Werror CFLAGS += -Werror -CFLAGS += -fpie -CXXFLAGS += -fpie +CFLAGS += -fpie -DOPENSSL_API_COMPAT=10101 +CXXFLAGS += -fpie -DOPENSSL_API_COMPAT=10101 LDFLAGS := -pie $(COMMON_LDFLAGS) INC += $(ADDED_INC) diff --git a/sdk/sign_tool/SignTool/manage_metadata.cpp b/sdk/sign_tool/SignTool/manage_metadata.cpp index c3050b7a8..e75a18fe2 100644 --- a/sdk/sign_tool/SignTool/manage_metadata.cpp +++ b/sdk/sign_tool/SignTool/manage_metadata.cpp @@ -333,6 +333,24 @@ bool CMetadata::fill_enclave_css(const xml_parameter_t *para) //default setting m_metadata->enclave_css.body.attributes.xfrm = SGX_XFRM_LEGACY; m_metadata->enclave_css.body.attribute_mask.xfrm = SGX_XFRM_LEGACY | SGX_XFRM_RESERVED; // LEGACY and reservied bits would be checked. + switch(para[PKRU].value) + { + case FEATURE_MUST_BE_DISABLED: + // PKRU must be disabled + m_metadata->enclave_css.body.attributes.xfrm &= ~SGX_XFRM_PKRU; + m_metadata->enclave_css.body.attribute_mask.xfrm |= SGX_XFRM_PKRU; + break; + case FEATURE_MUST_BE_ENABLED: + // PKRU must be enabled + m_metadata->enclave_css.body.attributes.xfrm |= SGX_XFRM_PKRU; + m_metadata->enclave_css.body.attribute_mask.xfrm |= SGX_XFRM_PKRU; + break; + case FEATURE_LOADER_SELECTS: + default: + m_metadata->enclave_css.body.attributes.xfrm &= ~SGX_XFRM_PKRU; + m_metadata->enclave_css.body.attribute_mask.xfrm &= ~SGX_XFRM_PKRU; + break; + } m_metadata->enclave_css.body.isv_prod_id = (uint16_t)para[PRODID].value; m_metadata->enclave_css.body.isv_svn = (uint16_t)para[ISVSVN].value; @@ -1160,7 +1178,8 @@ bool CMetadata::get_xsave_size(uint64_t xfrm, uint32_t *xsave_size) {SGX_XFRM_AVX, 512 + 64 + 256}, // 256 for YMM0_H - YMM15_H registers {SGX_XFRM_MPX, 512 + 64 + 256 + 256}, // 256 for MPX {SGX_XFRM_AVX512, 512 + 64 + 256 + 256 + 1600}, // 1600 for k0 - k7, ZMM0_H - ZMM15_H, ZMM16 - ZMM31 -// PT, PKRU ... + // Ignore PT as PT is a supervisor state. + {SGX_XFRM_PKRU, 512 + 64 + 256 + 256 + 1600 + 64}, // 8 for PKRU, 56 for alignment }; bool ret = true; *xsave_size = 0; diff --git a/sdk/sign_tool/SignTool/manage_metadata.h b/sdk/sign_tool/SignTool/manage_metadata.h index c7685998d..856e6abc8 100644 --- a/sdk/sign_tool/SignTool/manage_metadata.h +++ b/sdk/sign_tool/SignTool/manage_metadata.h @@ -46,6 +46,10 @@ #define SSA_NUM 2 #define SSA_FRAME_SIZE 1 +#define FEATURE_MUST_BE_DISABLED 0 +#define FEATURE_MUST_BE_ENABLED 1 +#define FEATURE_LOADER_SELECTS 2 + typedef enum _para_type_t { PRODID = 0, @@ -78,7 +82,8 @@ typedef enum _para_type_t ISVEXTPRODID_L, ENCLAVEIMAGEADDRESS, ELRANGESTARTADDRESS, - ELRANGESIZE + ELRANGESIZE, + PKRU } para_type_t; typedef struct _xml_parameter_t diff --git a/sdk/sign_tool/SignTool/sign_tool.cpp b/sdk/sign_tool/SignTool/sign_tool.cpp index 32052b089..ea9f5317f 100644 --- a/sdk/sign_tool/SignTool/sign_tool.cpp +++ b/sdk/sign_tool/SignTool/sign_tool.cpp @@ -1305,7 +1305,8 @@ int main(int argc, char* argv[]) {"ISVEXTPRODID_L", ISVEXTPRODID_MAX, 0, 0, 0}, {"EnclaveImageAddress", 0xFFFFFFFFFFFFFFFF, 0x1000, 0, 0}, {"ELRangeStartAddress", 0xFFFFFFFFFFFFFFFF, 0, 0, 0}, - {"ELRangeSize", 0xFFFFFFFFFFFFFFFF, 0x1000, 0, 0}}; + {"ELRangeSize", 0xFFFFFFFFFFFFFFFF, 0x1000, 0, 0}, + {"PKRU", FEATURE_LOADER_SELECTS, FEATURE_MUST_BE_DISABLED, FEATURE_MUST_BE_DISABLED, 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/SEConfigureCPUSVN/linux/Makefile b/sdk/simulation/SEConfigureCPUSVN/linux/Makefile index e56de3f24..fce3a59ee 100644 --- a/sdk/simulation/SEConfigureCPUSVN/linux/Makefile +++ b/sdk/simulation/SEConfigureCPUSVN/linux/Makefile @@ -46,7 +46,7 @@ OBJS := $(sort $(SRCS:.cpp=.o)) WRAPPER_LIB_DIR := $(COMMON_DIR)/se_wrapper LDFLAGS := -L$(WRAPPER_LIB_DIR) -CXXFLAGS += -fpie +CXXFLAGS += -fpie $(CET_FLAGS) LDFLAGS += -pie $(COMMON_LDFLAGS) LDLIBS := -lwrapper diff --git a/sdk/simulation/driver_api/Makefile b/sdk/simulation/driver_api/Makefile index a83648d45..be3d6d28b 100644 --- a/sdk/simulation/driver_api/Makefile +++ b/sdk/simulation/driver_api/Makefile @@ -43,7 +43,7 @@ CPPFLAGS += -I$(COMMON_DIR)/inc/ \ -I$(LINUX_PSW_DIR)/urts \ -I$(LINUX_PSW_DIR)/urts/linux -CXXFLAGS += -fPIC -Werror +CXXFLAGS += -fPIC -Werror $(CET_FLAGS) .PHONY: all all: driver_api.o diff --git a/sdk/simulation/uae_service_sim/linux/Makefile b/sdk/simulation/uae_service_sim/linux/Makefile index e5ad2406f..b8826cd83 100644 --- a/sdk/simulation/uae_service_sim/linux/Makefile +++ b/sdk/simulation/uae_service_sim/linux/Makefile @@ -49,8 +49,10 @@ INCLUDES := -I.. \ -I$(LINUX_PSW_DIR)/ae/inc/internal \ -I$(LINUX_PSW_DIR)/ae/common -CXXFLAGS += -Wall -fPIC $(INCLUDES) -Werror -g -CFLAGS := $(filter-out -fPIC -Werror, $(CFLAGS)) -Wall $(INCLUDES) + +CXXFLAGS += -Wall -fPIC $(INCLUDES) -Werror -g -DOPENSSL_API_COMPAT=10101 $(CET_FLAGS) +CFLAGS := $(filter-out -fPIC -Werror, $(CFLAGS)) -Wall $(INCLUDES) -DOPENSSL_API_COMPAT=10101 $(CET_FLAGS) + RDRAND_LIBDIR := $(LINUX_EXTERNAL_DIR)/rdrand/src RDRAND_MAKEFILE := $(RDRAND_LIBDIR)/Makefile @@ -115,10 +117,10 @@ else endif libsgx_%_deploy.so: ../libsgx_%_deploy.c - $(CC) -I$(COMMON_DIR)/inc -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 SPLIT_VERSION,$($(shell echo $(@:libsgx_%_deploy.so=%_version)|tr a-z A-Z)),1)) $< -o $@ libsgx_uae_service_deploy.so: $(wildcard ../*_deploy.c) - $(CC) -I$(COMMON_DIR)/inc -fPIC -shared -Wl,-soname=$(@:_deploy.so=.so) $^ -o $@ + $(CC) -I$(COMMON_DIR)/inc $(CET_FLAGS) -fPIC -shared -Wl,-soname=$(@:_deploy.so=.so) $^ -o $@ $(BUILD_DIR): @$(MKDIR) $@ diff --git a/sdk/simulation/uinst/Makefile b/sdk/simulation/uinst/Makefile index 364dca22d..5895bcbda 100644 --- a/sdk/simulation/uinst/Makefile +++ b/sdk/simulation/uinst/Makefile @@ -46,7 +46,7 @@ CPPFLAGS += -I$(COMMON_DIR)/inc/ \ -I$(LINUX_PSW_DIR)/urts \ -I$(LINUX_PSW_DIR)/urts/linux -CXXFLAGS += -Werror -fPIC +CXXFLAGS += -Werror -fPIC $(CET_FLAGS) OBJ1 := linux/set_tls.o \ linux/restore_tls.o \ diff --git a/sdk/simulation/urtssim/linux/Makefile b/sdk/simulation/urtssim/linux/Makefile index d064c2ba6..f2be8b340 100644 --- a/sdk/simulation/urtssim/linux/Makefile +++ b/sdk/simulation/urtssim/linux/Makefile @@ -39,8 +39,8 @@ CXXFLAGS += -DDISABLE_TRACE CFLAGS += -DDISABLE_TRACE endif -CXXFLAGS += -fPIC -DSE_SIM -Werror -g -CFLAGS += -fPIC -DSE_SIM -Werror -g +CXXFLAGS += -fPIC -DSE_SIM -Werror -g $(CET_FLAGS) +CFLAGS += -fPIC -DSE_SIM -Werror -g $(CET_FLAGS) CPPFLAGS += $(ADDED_INC) #for ubuntu 11 and later version CPPFLAGS += -I$(COMMON_DIR)/inc \ @@ -181,7 +181,7 @@ ittnotify: CFLAGS= CXXFLAGS= $(MAKE) -C $(VTUNE_DIR)/sdk/src/ittnotify/ $(LIBURTS_DEPLOY):../urts_deploy.c - $(CC) -I$(COMMON_DIR)/inc -shared -fPIC -Wl,-soname=libsgx_urts.so $< -o $@ + $(CC) -I$(COMMON_DIR)/inc $(CET_FLAGS) -shared -fPIC -Wl,-soname=libsgx_urts.so $< -o $@ .PHONY: clean clean:: diff --git a/sdk/switchless/sgx_uswitchless/Makefile b/sdk/switchless/sgx_uswitchless/Makefile index 5ab23e018..7ba633d48 100644 --- a/sdk/switchless/sgx_uswitchless/Makefile +++ b/sdk/switchless/sgx_uswitchless/Makefile @@ -52,14 +52,14 @@ CPP_OBJS := $(CPP_SRCS:.cpp=.o) ALL_OBJS := $(CPP_OBJS) $(C_OBJS) SL_CXXFLAGS := $(CXXFLAGS) -SL_CXXFLAGS += -fPIC +SL_CXXFLAGS += -fPIC $(CET_FLAGS) SL_CXXFLAGS += -I$(COMMON_DIR)/inc \ -I$(COMMON_DIR)/inc/internal \ -I$(SL_DIR)/inc SL_CFLAGS := $(CFLAGS) -SL_CFLAGS += -Werror -D_GNU_SOURCE -fPIC +SL_CFLAGS += -Werror -D_GNU_SOURCE -fPIC $(CET_FLAGS) SL_CFLAGS += $(ADDED_INC) SL_CFLAGS += -I$(COMMON_DIR)/inc \ -I$(COMMON_DIR)/inc/internal \ diff --git a/sdk/tlibcrypto/Makefile b/sdk/tlibcrypto/Makefile index 629ff82cb..bb048e95e 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 -OBJ = init_tcrypto_lib.o sgx_aes_ctr.o sgx_rsa_encryption.o sgx_aes_gcm.o sgx_cmac128.o sgx_hmac.o sgx_ecc256.o sgx_ecc256_ecdsa.o sgx_sha256.o sgx_sha1.o sgx_sha256_msg.o sgx_ecc256_internal.o sgx_rsa3072.o sgx_internal.o +OBJ = init_tcrypto_lib.o sgx_aes_ctr.o sgx_rsa_encryption.o sgx_aes_gcm.o sgx_cmac128.o sgx_hmac.o sgx_ecc256.o sgx_ecc256_ecdsa.o sgx_sha384.o sgx_sha384_msg.o sgx_sha256.o sgx_sha1.o sgx_sha256_msg.o sgx_ecc256_internal.o sgx_rsa3072.o sgx_internal.o SHARED_OBJ = tcrypto_version.o sgx_common_init_ipp.o ifeq ($(USE_CRYPTO_LIB), 0) @@ -143,4 +143,4 @@ clean: .PHONY: rebuild rebuild: $(MAKE) clean - $(MAKE) all + $(MAKE) all \ No newline at end of file diff --git a/sdk/tlibcrypto/ipp/sgx_sha384.cpp b/sdk/tlibcrypto/ipp/sgx_sha384.cpp new file mode 100644 index 000000000..f2fda9fb2 --- /dev/null +++ b/sdk/tlibcrypto/ipp/sgx_sha384.cpp @@ -0,0 +1,134 @@ +/* + * 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" +#include "sgx_tcrypto.h" +#include "stdlib.h" + +#ifndef SAFE_FREE +#define SAFE_FREE(ptr) {if (NULL != (ptr)) {free(ptr); (ptr)=NULL;}} +#endif + + +/* 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) +{ + IppStatus ipp_ret = ippStsNoErr; + IppsHashState_rmf* p_temp_state = NULL; + + if (p_sha_handle == NULL) + return SGX_ERROR_INVALID_PARAMETER; + + 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)); + if (p_temp_state == NULL) + return SGX_ERROR_OUT_OF_MEMORY; + ipp_ret = ippsHashInit_rmf(p_temp_state, ippsHashMethod_SHA384()); + if (ipp_ret != ippStsNoErr) + { + SAFE_FREE(p_temp_state); + *p_sha_handle = NULL; + switch (ipp_ret) + { + case ippStsNullPtrErr: + case ippStsLengthErr: return SGX_ERROR_INVALID_PARAMETER; + default: return SGX_ERROR_UNEXPECTED; + } + } + + *p_sha_handle = p_temp_state; + return SGX_SUCCESS; +} + +/* 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 */ +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; + } + IppStatus ipp_ret = ippStsNoErr; + ipp_ret = ippsHashUpdate_rmf(p_src, src_len, (IppsHashState_rmf*)sha_handle); + switch (ipp_ret) + { + case ippStsNoErr: return SGX_SUCCESS; + case ippStsNullPtrErr: + 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 */ +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; + } + IppStatus ipp_ret = ippStsNoErr; + ipp_ret = ippsHashGetTag_rmf((Ipp8u*)p_hash, SGX_SHA384_HASH_SIZE, (IppsHashState_rmf*)sha_handle); + switch (ipp_ret) + { + case ippStsNoErr: return SGX_SUCCESS; + case ippStsNullPtrErr: + 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 */ +sgx_status_t sgx_sha384_close(sgx_sha_state_handle_t sha_handle) +{ + if (sha_handle == NULL) + { + return SGX_ERROR_INVALID_PARAMETER; + } + SAFE_FREE(sha_handle); + return SGX_SUCCESS; +} diff --git a/sdk/tlibcrypto/ipp/sgx_sha384_msg.cpp b/sdk/tlibcrypto/ipp/sgx_sha384_msg.cpp new file mode 100644 index 000000000..6d0db5f7d --- /dev/null +++ b/sdk/tlibcrypto/ipp/sgx_sha384_msg.cpp @@ -0,0 +1,65 @@ +/* + * 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 "sgx_tcrypto.h" +#include "ippcp.h" +#include "stdlib.h" + +#ifndef SAFE_FREE +#define SAFE_FREE(ptr) {if (NULL != (ptr)) {free(ptr); (ptr)=NULL;}} +#endif + + +/* SHA Hashing functions +* Parameters: +* Return: sgx_status_t - SGX_SUCCESS or failure as defined sgx_error.h +* Inputs: uint8_t *p_src - Pointer to input stream to be hashed +* uint32_t src_len - Length of input stream to be hashed +* Output: sgx_sha384_hash_t *p_hash - Resultant hash from operation */ +sgx_status_t sgx_sha384_msg(const uint8_t *p_src, uint32_t src_len, sgx_sha384_hash_t *p_hash) +{ + if ((p_src == NULL) || (p_hash == NULL)) + { + return SGX_ERROR_INVALID_PARAMETER; + } + + IppStatus ipp_ret = ippStsNoErr; + ipp_ret = ippsHashMessage_rmf((const Ipp8u *) p_src, src_len, (Ipp8u *)p_hash, ippsHashMethod_SHA384()); + switch (ipp_ret) + { + case ippStsNoErr: return SGX_SUCCESS; + case ippStsMemAllocErr: return SGX_ERROR_OUT_OF_MEMORY; + case ippStsNullPtrErr: + case ippStsLengthErr: return SGX_ERROR_INVALID_PARAMETER; + default: return SGX_ERROR_UNEXPECTED; + } +} diff --git a/sdk/tlibcrypto/sgxssl/sgx_aes_ctr.cpp b/sdk/tlibcrypto/sgxssl/sgx_aes_ctr.cpp index 0720864d9..f48037ce0 100644 --- a/sdk/tlibcrypto/sgxssl/sgx_aes_ctr.cpp +++ b/sdk/tlibcrypto/sgxssl/sgx_aes_ctr.cpp @@ -122,7 +122,7 @@ sgx_status_t sgx_aes_ctr_encrypt(const sgx_aes_ctr_128bit_key_t *p_key, const ui break; } - // Encryption success, increment counter + // Encryption success, increment the counter parameter to align with the behavior of IPP version. // len = src_len; while (len >= 0) { @@ -191,7 +191,7 @@ sgx_status_t sgx_aes_ctr_decrypt(const sgx_aes_ctr_128bit_key_t *p_key, const ui break; } // Success - // Increment counter + // Increment the counter parameter to align with the behavior of IPP version. // len = src_len; while (len >= 0) { diff --git a/sdk/tlibcrypto/sgxssl/sgx_sha384.cpp b/sdk/tlibcrypto/sgxssl/sgx_sha384.cpp new file mode 100644 index 000000000..951a400f0 --- /dev/null +++ b/sdk/tlibcrypto/sgxssl/sgx_sha384.cpp @@ -0,0 +1,157 @@ +/* + * 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 "se_tcrypto_common.h" +#include +#include +#include "sgx_tcrypto.h" +#include "stdlib.h" + +/* 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) +{ + if (p_sha_handle == NULL) { + return SGX_ERROR_INVALID_PARAMETER; + } + + EVP_MD_CTX* evp_ctx = NULL; + const EVP_MD* sha384_md = NULL; + sgx_status_t retval = SGX_ERROR_UNEXPECTED; + + do { + /* allocates, initializes and returns a digest context */ + evp_ctx = EVP_MD_CTX_new(); + if (evp_ctx == NULL) { + retval = SGX_ERROR_OUT_OF_MEMORY; + break; + } + + /* return EVP_MD structures for SHA384 digest algorithm */ + sha384_md = EVP_sha384(); + if (sha384_md == NULL) { + break; + } + + /* sets up digest context ctx to use a digest type, if impl is NULL then the default implementation of digest type is used */ + if (EVP_DigestInit_ex(evp_ctx, sha384_md, NULL) != 1) { + break; + } + + *p_sha_handle = evp_ctx; + retval = SGX_SUCCESS; + } while(0); + + if (SGX_SUCCESS != retval) { + if (evp_ctx != NULL) { + EVP_MD_CTX_free(evp_ctx); + } + } + + return retval; +} + +/* 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 */ +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; + } + + sgx_status_t retval = SGX_ERROR_UNEXPECTED; + + do { + /* hashes src_len bytes of data at p_src into the digest context sha_handle */ + if(EVP_DigestUpdate((EVP_MD_CTX*)sha_handle, p_src, src_len) != 1) { + break; + } + + retval = SGX_SUCCESS; + } while (0); + + return retval; +} + +/* 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 */ +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; + } + + sgx_status_t retval = SGX_ERROR_UNEXPECTED; + unsigned int hash_len = 0; + + do { + /* retrieves the digest value from sha_handle and places it in p_hash */ + if (EVP_DigestFinal_ex((EVP_MD_CTX*)sha_handle, (unsigned char *)p_hash, &hash_len) != 1) { + break; + } + + if (SGX_SHA384_HASH_SIZE != hash_len) { + break; + } + + retval = SGX_SUCCESS; + } while(0); + + return retval; +} + + +/* 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 */ +sgx_status_t sgx_sha384_close(sgx_sha_state_handle_t sha_handle) +{ + if (sha_handle == NULL) + { + return SGX_ERROR_INVALID_PARAMETER; + } + + EVP_MD_CTX_free((EVP_MD_CTX*)sha_handle); + + return SGX_SUCCESS; +} diff --git a/sdk/tlibcrypto/sgxssl/sgx_sha384_msg.cpp b/sdk/tlibcrypto/sgxssl/sgx_sha384_msg.cpp new file mode 100644 index 000000000..23dc713ce --- /dev/null +++ b/sdk/tlibcrypto/sgxssl/sgx_sha384_msg.cpp @@ -0,0 +1,63 @@ +/* + * 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 "se_tcrypto_common.h" +#include +#include +#include "sgx_tcrypto.h" + +/* SHA Hashing functions +* Parameters: +* Return: sgx_status_t - SGX_SUCCESS or failure as defined sgx_error.h +* Inputs: uint8_t *p_src - Pointer to input stream to be hashed +* uint32_t src_len - Length of input stream to be hashed +* Output: sgx_sha384_hash_t *p_hash - Resultant hash from operation */ +sgx_status_t sgx_sha384_msg(const uint8_t *p_src, uint32_t src_len, sgx_sha384_hash_t *p_hash) +{ + if ((p_src == NULL) || (p_hash == NULL)) + { + return SGX_ERROR_INVALID_PARAMETER; + } + + sgx_status_t retval = SGX_ERROR_UNEXPECTED; + + do { + /* generates digest of p_src */ + if (SHA384((const unsigned char *)p_src, src_len, (unsigned char *)p_hash) == NULL) { + break; + } + + retval = SGX_SUCCESS; + } while(0); + + + return retval; +} diff --git a/sdk/trts/init_enclave.cpp b/sdk/trts/init_enclave.cpp index b8c122569..525e9924f 100644 --- a/sdk/trts/init_enclave.cpp +++ b/sdk/trts/init_enclave.cpp @@ -98,12 +98,7 @@ extern "C" int init_enclave(void *enclave_base, void *ms) { // LFENCE before pcl_entry sgx_lfence(); - system_features_t * csi = (system_features_t *)ms; - if(NULL == csi->sealed_key) - { - return -1; - } - sgx_status_t ret = pcl_entry(enclave_base, csi->sealed_key); + sgx_status_t ret = pcl_entry(enclave_base, ms); if(SGX_SUCCESS != ret) { return -1; @@ -116,7 +111,7 @@ extern "C" int init_enclave(void *enclave_base, void *ms) return -1; } - g_enclave_base = (uint64_t)&__ImageBase; + 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 diff --git a/sdk/trts/linux/global_init.c b/sdk/trts/linux/global_init.c index a180adf3f..bfa41287e 100644 --- a/sdk/trts/linux/global_init.c +++ b/sdk/trts/linux/global_init.c @@ -135,6 +135,7 @@ static void do_atexit_aux(void) } } +extern void* get_enclave_base(void); /* auxiliary routines */ static void do_ctors_aux(void) { @@ -143,7 +144,7 @@ static void do_ctors_aux(void) fp_t *p = NULL; uintptr_t init_array_addr = 0; size_t init_array_size = 0; - const void *enclave_start = (const void*)&__ImageBase; + const void *enclave_start = get_enclave_base(); if (0 != elf_get_init_array(enclave_start, &init_array_addr, &init_array_size)|| init_array_addr == 0 || init_array_size == 0) return; @@ -164,7 +165,7 @@ static void do_dtors_aux(void) fp_t *p = NULL; uintptr_t uninit_array_addr; size_t uninit_array_size; - const void *enclave_start = (const void*)&__ImageBase; + const void *enclave_start = get_enclave_base(); elf_get_uninit_array(enclave_start, &uninit_array_addr, &uninit_array_size); diff --git a/sdk/trts/linux/trts_pic.S b/sdk/trts/linux/trts_pic.S index bb7395d28..92470a492 100644 --- a/sdk/trts/linux/trts_pic.S +++ b/sdk/trts/linux/trts_pic.S @@ -68,7 +68,7 @@ DECLARE_LOCAL_FUNC lock_enclave lock cmpxchgl %ecx, (%xdx) /* g_global_data.enclave_state == ENCLAVE_INIT_IN_PROGRESS */ ret /* xax: the initial value of enclave state */ -/* +/* * --------------------------------------------------------------------- * Function: thread_data_t* get_thread_data(void); * @@ -76,21 +76,21 @@ DECLARE_LOCAL_FUNC lock_enclave * --------------------------------------------------------------------- */ DECLARE_LOCAL_FUNC get_thread_data - READ_TD_DATA self_addr + READ_TD_DATA self_addr ret -/* +/* * --------------------------------------------------------------------- * Function: sys_word_t get_stack_guard(void); * * Get the value of stack_guard * --------------------------------------------------------------------- */ -DECLARE_LOCAL_FUNC get_stack_guard - READ_TD_DATA stack_guard +DECLARE_LOCAL_FUNC get_stack_guard + READ_TD_DATA stack_guard ret - -/* + +/* * --------------------------------------------------------------------- * Function: enclave_entry * The entry point of the enclave. @@ -103,7 +103,7 @@ DECLARE_LOCAL_FUNC get_stack_guard * XSI - the pointer to the marshalling structure */ DECLARE_GLOBAL_FUNC enclave_entry -/* +/* * ---------------------------------------------------------------------- * Dispatch code according to CSSA and the reason of EENTER * eax > 0 - exception handler @@ -229,14 +229,14 @@ DECLARE_GLOBAL_FUNC enclave_entry .Ldo_handler: mov %xax, %xdx /* XDX: cssa */ GET_STACK_BASE %xbx /* XAX: static stack, set sp to stack base */ - jmp .Lswitch_stack - + jmp .Lswitch_stack + /* Should not come here */ ud2 - + .cfi_endproc -/* +/* * ------------------------------------------------------------------------- * sgx_status_t do_ocall(unsigned int index, void *ms); * @@ -285,7 +285,7 @@ DECLARE_GLOBAL_FUNC enclave_entry */ DECLARE_LOCAL_FUNC do_ocall -/* +/* * 8 for GPR, 1 for TD.last_sp, 1 for ocall_index * 1 for OCALL_FLAG, 4 for shadow space. * Stack Pointer is 16-byte aligned under x86_64. @@ -358,7 +358,7 @@ DECLARE_LOCAL_FUNC do_ocall * set TD.last_sp = xsp */ READ_TD_DATA self_addr - mov %xax, %xbx + mov %xax, %xbx /* call update_ocall_lastsp */ #ifdef LINUX32 @@ -366,7 +366,7 @@ DECLARE_LOCAL_FUNC do_ocall #else mov %xsp, %xdi #endif - + call update_ocall_lastsp /* xax: td.last_sp */ #ifdef LINUX64 @@ -482,7 +482,7 @@ DECLARE_GLOBAL_FUNC asm_oret /* should not come here */ ud2 -/* +/* * ------------------------------------------------------------------------ * extern "C" int do_egetkey(key_request_t *key_request, key_128bit_t *key) * return value: @@ -507,7 +507,7 @@ DECLARE_LOCAL_FUNC do_egetkey SE_EPILOG -/* +/* * ------------------------------------------------------------------------- * extern "C" int do_ereport(sgx_target_info_t *target_info, sgx_report_data_t *report_data, sgx_report_t *report); * EREPORT: rbx - the address of TARGETINFO; @@ -527,23 +527,34 @@ Lereport_inst: ENCLU setc %al SE_EPILOG - + +.global Leverifyreport2_inst +DECLARE_LOCAL_FUNC do_everifyreport2 + SE_PROLOG + mov $SE_EVERIFYREPORT2, %xax /* EVERIFYREPORT2 leaf */ +Leverifyreport2_inst: + ENCLU + jz .Leverifyreport2_done /* if EVERIFYREPORT2 error, ZF flag is set and error code is set to xax */ + xor %xax, %xax +.Leverifyreport2_done: + SE_EPILOG + DECLARE_GLOBAL_FUNC do_eaccept SE_PROLOG mov $SE_EACCEPT, %eax ENCLU - cmp $SGX_SUCCESS, %eax - jnz abort + cmp $SGX_SUCCESS, %eax + jnz abort SE_EPILOG DECLARE_GLOBAL_FUNC do_emodpe SE_PROLOG - mov $SE_EMODPE, %eax + mov $SE_EMODPE, %eax ENCLU SE_EPILOG -#define _RDRAND_RETRY_TIMES 10 -/* +#define _RDRAND_RETRY_TIMES 10 +/* * ------------------------------------- * extern "C" uint32_t do_rdrand(uint32_t *rand); * return value: @@ -580,7 +591,7 @@ DECLARE_LOCAL_FUNC abort movl $ENCLAVE_CRASHED, (%xax) ud2 -/* +/* * ------------------------------------------------------------------------- * extern "C" __attribute__((regparm(1))) void continue_execution(sgx_exception_info_t *info); * ------------------------------------------------------------------------- diff --git a/sdk/trts/trts.cpp b/sdk/trts/trts.cpp index 2646a0e66..1ddd5f6eb 100644 --- a/sdk/trts/trts.cpp +++ b/sdk/trts/trts.cpp @@ -39,6 +39,7 @@ #include "global_data.h" #include "trts_internal.h" #include "internal/rts.h" +#include "trts_util.h" #ifdef SE_SIM #include "t_instructions.h" /* for `g_global_data_sim' */ @@ -318,3 +319,36 @@ int check_static_stack_canary(void *tcs) return 0; } +int SGXAPI sgx_rdpkru(uint32_t *val) +{ + if(!is_pkru_enabled()) + { + return 0; + } + + uint32_t c = 0; + uint32_t d, pkru; + + //Reads the value of PKRU into EAX and clears EDX. ECX must be 0 when RDPKRU is executed + asm volatile(".byte 0x0f,0x01,0xee" /* rdpkru */ + : "=a" (pkru), "=d" (d) + : "c" (c)); + + *val = pkru; + return 1; +} + +int SGXAPI sgx_wrpkru(uint32_t val) +{ + if(!is_pkru_enabled()) + { + return 0; + } + uint32_t c = 0, d = 0; + + // Writes the value of EAX into PKRU. ECX and EDX must be 0 when WRPKRU is executed + asm volatile(".byte 0x0f,0x01,0xef" /* wrpkru */ + : + : "a" (val), "c"(c), "d"(d)); + return 1; +} diff --git a/sdk/trts/trts_ecall.cpp b/sdk/trts/trts_ecall.cpp index bb12e7d23..68f08c618 100644 --- a/sdk/trts/trts_ecall.cpp +++ b/sdk/trts/trts_ecall.cpp @@ -278,7 +278,7 @@ static sgx_status_t trts_ecall(uint32_t ordinal, void *ms) } //change back the page permission - size_t enclave_start = (size_t)&__ImageBase; + size_t enclave_start = (size_t)get_enclave_base(); if((status = change_protection((void *)enclave_start)) != SGX_SUCCESS) { sgx_spin_unlock(&g_ife_lock); @@ -360,7 +360,7 @@ sgx_status_t do_init_thread(void *tcs, bool enclave_init) uintptr_t tls_addr = 0; size_t tdata_size = 0; - if(0 != GET_TLS_INFO(&__ImageBase, &tls_addr, &tdata_size)) + if(0 != GET_TLS_INFO(get_enclave_base(), &tls_addr, &tdata_size)) { return SGX_ERROR_UNEXPECTED; } @@ -397,6 +397,10 @@ sgx_status_t do_ecall(int index, void *ms, void *tcs) if(thread_data->stack_base_addr == thread_data->last_sp) { //root ecall + // + // If PKRU is supported, write 0 to PKRU register. + sgx_wrpkru(0); + if(_pthread_enabled()) { jmp_buf buf = {0}; @@ -473,6 +477,8 @@ sgx_status_t do_ecall_add_thread(void *ms) return status; } + sgx_lfence(); + const struct ms_tcs mtcs = *tcs; void* ptcs = mtcs.ptcs; if (ptcs == NULL) diff --git a/sdk/trts/trts_util.cpp b/sdk/trts/trts_util.cpp index c0b59ef42..6cc0c7b39 100644 --- a/sdk/trts/trts_util.cpp +++ b/sdk/trts/trts_util.cpp @@ -35,6 +35,8 @@ #include "util.h" #include "thread_data.h" #include "trts_internal.h" +#include "sgx_attributes.h" +#include "xsave.h" // No need to check the state of enclave or thread. // The functions should be called within an ECALL, so the enclave and thread must be initialized at that time. @@ -50,7 +52,7 @@ size_t get_enclave_end(void) void * get_heap_base(void) { - return GET_PTR(void, &__ImageBase, g_global_data.heap_offset); + return GET_PTR(void, get_enclave_base(), g_global_data.heap_offset); } size_t get_heap_size(void) @@ -85,7 +87,7 @@ size_t get_heap_min_size(void) void * get_rsrv_base(void) { - return GET_PTR(void, &__ImageBase, g_global_data.rsrv_offset); + return GET_PTR(void, get_enclave_base(), g_global_data.rsrv_offset); } size_t get_rsrv_end(void) @@ -191,7 +193,15 @@ bool is_utility_thread() return false; } -extern "C" size_t get_max_tcs_num() +size_t get_max_tcs_num() { return (size_t)g_global_data.tcs_max_num; } + +bool is_pkru_enabled() +{ + uint64_t xfrm = get_xfeature_state(); + if((xfrm & SGX_XFRM_PKRU) == SGX_XFRM_PKRU) + return true; + return false; +} diff --git a/sdk/trts/trts_util.h b/sdk/trts/trts_util.h index 1ca0ece36..88ef7ed92 100644 --- a/sdk/trts/trts_util.h +++ b/sdk/trts/trts_util.h @@ -58,6 +58,7 @@ int heap_init(void *_heap_base, size_t _heap_size, size_t _heap_min_size, int _i int feature_supported(const uint64_t *feature_set, uint32_t feature_shift); bool is_utility_thread(); size_t get_max_tcs_num(); +bool is_pkru_enabled(); #ifdef __cplusplus } diff --git a/sdk/trts/trts_veh.cpp b/sdk/trts/trts_veh.cpp index 7413d848c..e951b02af 100644 --- a/sdk/trts/trts_veh.cpp +++ b/sdk/trts/trts_veh.cpp @@ -294,6 +294,7 @@ static int expand_stack_by_pages(void *start_addr, size_t page_count) } extern "C" const char Lereport_inst; +extern "C" const char Leverifyreport2_inst; // trts_handle_exception(void *tcs) // the entry point for the exceptoin handling @@ -412,6 +413,14 @@ extern "C" sgx_status_t trts_handle_exception(void *tcs) ssa_gpr->REG(flags) |= 1; // Set CF to indicate error condition, see implementation of do_report() return SGX_SUCCESS; } + if (size_t(&Leverifyreport2_inst) == ssa_gpr->REG(ip) && SE_EVERIFYREPORT2 == ssa_gpr->REG(ax)) + { + // Handle the exception raised by everifyreport2 instruction + ssa_gpr->REG(ip) += 3; // Skip ENCLU, which is always a 3-byte instruction + ssa_gpr->REG(flags) |= 64; // Set ZF to indicate error condition, see implementation of do_everifyreport2() + ssa_gpr->REG(ax) = EVERIFYREPORT2_INVALID_LEAF; + return SGX_SUCCESS; + } if(ssa_gpr->exit_info.valid != 1) { // exception handlers are not allowed to call in a non-exception state diff --git a/sdk/tsafecrt/pal/src/safecrt/memomve_s.c b/sdk/tsafecrt/pal/src/safecrt/memmove_s.c similarity index 100% rename from sdk/tsafecrt/pal/src/safecrt/memomve_s.c rename to sdk/tsafecrt/pal/src/safecrt/memmove_s.c diff --git a/sdk/ttls/Makefile b/sdk/ttls/Makefile new file mode 100644 index 000000000..ee45fb5e9 --- /dev/null +++ b/sdk/ttls/Makefile @@ -0,0 +1,99 @@ +# +# 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. +# +# + +TOP_DIR = ../.. +include $(TOP_DIR)/buildenv.mk + +TLSNAME = sgx_ttls +EDLFILE = $(TOP_DIR)/common/inc/$(TLSNAME).edl + +ifeq ($(DEBUG), 1) + SGXSSL_TLIB = sgx_tsgxssld + SGXSSL_TCRYPTO = sgx_tsgxssl_cryptod +else + SGXSSL_TLIB = sgx_tsgxssl + SGXSSL_TCRYPTO = sgx_tsgxssl_crypto +endif + +SGX_QV_PATH ?= ../../external/dcap_source/QuoteVerification +PREBUILT_OPENSSL_PATH ?= $(SGX_QV_PATH)/../prebuilt/openssl + +INCLUDE += -I$(COMMON_DIR)/inc/tlibc \ + -I$(COMMON_DIR)/inc/internal \ + -I$(COMMON_DIR)/inc \ + -I$(LINUX_SDK_DIR)/tlibcxx/include \ + -I$(SGX_QV_PATH)/QvE/Include \ + -I$(SGX_QV_PATH)/../QuoteGeneration/quote_wrapper/common/inc \ + -I$(SGX_QV_PATH)/../QuoteGeneration/pce_wrapper/inc \ + -I$(SGX_QV_PATH)/dcap_tvl \ + -include./tsgxsslio.h \ + -I$(PREBUILT_OPENSSL_PATH)/inc + +CXXFLAGS += $(COMMON_FLAGS) $(ENCLAVE_CXXFLAGS) + +EDGER8R_DIR := $(LINUX_SDK_DIR)/edger8r/linux +EDGER8R := $(EDGER8R_DIR)/_build/Edger8r.native + +SRC := $(wildcard *.cpp) + +OBJ := $(sort $(SRC:.cpp=.o)) + +LIBNAME := libsgx_ttls.a + +.PHONY: all PREPARE_SGX_SSL +all: $(LIBNAME) | $(BUILD_DIR) + $(CP) $(LIBNAME) $| + +$(TLSNAME)_t.h: $(EDLFILE) $(EDGER8R) + $(EDGER8R) --trusted --header-only --search-path $(TOP_DIR)/common/inc $< + +$(EDGER8R): + $(MAKE) -C $(EDGER8R_DIR) + +$(LIBNAME): $(OBJ) + $(AR) rs $@ $(OBJ) + +$(OBJ): $(TLSNAME)_t.h +$(OBJ): %.o :%.cpp + $(CXX) $(CXXFLAGS) $(INCLUDE) -c $< -o $@ + +.PHONY: clean +clean: + @$(RM) *.o + @$(RM) $(COMMON_DIR)/src/*.o + @$(RM) *_t.* *_u.* + @$(RM) $(LIBNAME) $(BUILD_DIR)/$(LIBNAME) + $(MAKE) -C $(EDGER8R_DIR) clean + +.PHONY: rebuild +rebuild: + $(MAKE) clean + $(MAKE) all diff --git a/sdk/ttls/cert_generator.cpp b/sdk/ttls/cert_generator.cpp new file mode 100644 index 000000000..9c5a327e6 --- /dev/null +++ b/sdk/ttls/cert_generator.cpp @@ -0,0 +1,430 @@ +/** + * + * MIT License + * + * Copyright (c) Open Enclave SDK contributors. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE + * + */ + +#include +#include +#include +#include +#include +#include +#include +#include "cert_header.h" +#include "se_memcpy.h" + + +#define SSL_ERR_BREAK(x, y) {if(!x) { result = y; break;}} +#define X509_MAX_NAME_SIZE 256 + +#define SUBJECT_NAME "CN=Intel SGX Enclave,O=Intel Corporation,C=US" +#define DATE_NOT_VALID_BEFORE "20210401000000" +#define DATE_NOT_VALID_AFTER "20501231235959" + +/* + * Value used by the _decode_oid_to_str() function. Although the OID + * standard does not limit the depth of an OID definition tree (i.e., the + * number of arcs), our implementation only supports a simple decoding + * with a limited depth (i.e., decoding into a fixed size string). + */ + +/* + * Parse the name string into X509_NAME struct. The format of the string is + * "KEY1=VALUE1,KEY2=VALUE2,KEY3=VALUE3...". The implementation is based + * on the mbedtls_x509_string_to_names from Mbed TLS. + * Note that the string is expected to use commas as the separators instead + * of slashes as OpenSSL CLI does. Also, the implementation does not + * support multivalue-RDN names (with the "+" in the value). + */ +static X509_NAME* X509_parse_name(const char* name_string) +{ + const char* s = name_string; + const char* c = s; + const char* end = s + strlen(s); + int in_tag = 1; + char key[X509_MAX_NAME_SIZE]; + char data[X509_MAX_NAME_SIZE]; + char* d = data; + X509_NAME* name = NULL; + int error = 1; + + name = X509_NAME_new(); + if (name == NULL) + goto done; + + while (c <= end) + { + if (in_tag && *c == '=') + { + size_t len = (size_t)(c - s) + 1; + if (len > X509_MAX_NAME_SIZE) + goto done; + + if (memcpy_s(key, X509_MAX_NAME_SIZE, s, len)) + goto done; + key[len - 1] = '\0'; + s = c + 1; + in_tag = 0; + d = data; + } + + if (!in_tag && *c == '\\' && c != end) + { + c++; + /* Only support escaping commas */ + if (c == end || *c != ',') + goto done; + } + else if (!in_tag && (*c == ',' || c == end)) + { + /* + * The check of if(d - data == OE_X509_MAX_NAME_SIZE) + * below ensures that d should never go beyond the boundary of data. + * Place null that indicates the end of the string. + */ + *d = '\0'; + if (!X509_NAME_add_entry_by_txt( + name, key, MBSTRING_UTF8, (unsigned char*)data, -1, -1, 0)) + goto done; + + /* Skip the spaces after the comma */ + while (c < end && *(c + 1) == ' ') + c++; + s = c + 1; + in_tag = 1; + } + + if (!in_tag && s != c + 1) + { + *(d++) = *c; + if (d - data == X509_MAX_NAME_SIZE) + goto done; + } + + c++; + } + + error = 0; + +done: + if (error && name) + { + X509_NAME_free(name); + name = NULL; + } + + return name; +} + +static sgx_status_t sgx_gen_custom_x509_cert( + sgx_cert_config_t* config, + unsigned char* cert_buf, + size_t cert_buf_size, + size_t* bytes_written) +{ + sgx_status_t result = SGX_ERROR_UNEXPECTED; + X509* x509cert = NULL; + X509V3_CTX ctx; + BIO* bio = NULL; + X509_NAME* name = NULL; + EVP_PKEY* subject_issuer_key_pair = NULL; + X509_EXTENSION* ext = NULL; + ASN1_OBJECT* obj = NULL; + ASN1_OCTET_STRING* data = NULL; + BASIC_CONSTRAINTS* bc = NULL; + unsigned char* buf = NULL; + unsigned char* p = NULL; + char* oid = NULL; + char date_str[16]; + int len = 0; + int ret = 0; + + do { + // Initialize SGXSSL crypto + OPENSSL_init_crypto(0, NULL); + + x509cert = X509_new(); + subject_issuer_key_pair = EVP_PKEY_new(); + + /* Allocate buffer for certificate */ + if ((buf = (unsigned char*)malloc(cert_buf_size)) == NULL) + SSL_ERR_BREAK(buf, SGX_ERROR_OUT_OF_MEMORY); + + /* Set certificate info */ + + /* Parse public key */ + bio = BIO_new_mem_buf((const void*)config->public_key_buf, (int)config->public_key_buf_size); + SSL_ERR_BREAK(bio, SGX_ERROR_UNEXPECTED); + + if (!PEM_read_bio_PUBKEY(bio, &subject_issuer_key_pair, NULL, NULL)) + break; + + EVP_PKEY_base_id(subject_issuer_key_pair); + + BIO_free(bio); + bio = NULL; + + /* Parse private key */ + bio = BIO_new_mem_buf( + (const void*)config->private_key_buf, + (int)config->private_key_buf_size); + SSL_ERR_BREAK(bio, SGX_ERROR_UNEXPECTED); + + if (!PEM_read_bio_PrivateKey(bio, &subject_issuer_key_pair, NULL, NULL)) + break; + + BIO_free(bio); + bio = NULL; + + /* Set version to V3 */ + ret = X509_set_version(x509cert, 2); + SSL_ERR_BREAK(ret, SGX_ERROR_UNEXPECTED); + + /* Set key */ + ret = X509_set_pubkey(x509cert, subject_issuer_key_pair); + SSL_ERR_BREAK(ret, SGX_ERROR_UNEXPECTED); + + /* Covert the subject string to X509_name struct */ + name = X509_parse_name((const char*)config->subject_name); + SSL_ERR_BREAK(name, SGX_ERROR_UNEXPECTED); + + /* Set subject name */ + ret = X509_set_subject_name(x509cert, name); + SSL_ERR_BREAK(ret, SGX_ERROR_UNEXPECTED); + + X509_NAME_free(name); + name = NULL; + + /* Covert the issuer string to X509_name struct */ + name = X509_parse_name((const char*)config->issuer_name); + SSL_ERR_BREAK(name, SGX_ERROR_UNEXPECTED); + + /* Set issuer name */ + ret = X509_set_issuer_name(x509cert, name); + SSL_ERR_BREAK(ret, SGX_ERROR_UNEXPECTED); + + X509_NAME_free(name); + name = NULL; + + /* Set serial number */ + ret = ASN1_INTEGER_set(X509_get_serialNumber(x509cert), 1); + SSL_ERR_BREAK(ret, SGX_ERROR_UNEXPECTED); + + /* Convert the format YYYYMMDDHHMMSS to YYYYMMDDHHMMSSZ */ + strncpy(date_str, (const char*)config->date_not_valid_before, 14); + date_str[14] = 'Z'; + date_str[15] = '\0'; + + /* Set validity start date */ + ret = ASN1_TIME_set_string(X509_getm_notBefore(x509cert), date_str); + SSL_ERR_BREAK(ret, SGX_ERROR_UNEXPECTED); + + /* Convert the format YYYYMMDDHHMMSS to YYYYMMDDHHMMSSZ */ + strncpy(date_str, (const char*)config->date_not_valid_after, 14); + date_str[14] = 'Z'; + date_str[15] = '\0'; + + /* Set validity end date */ + ret = ASN1_TIME_set_string(X509_getm_notAfter(x509cert), date_str); + SSL_ERR_BREAK(ret, SGX_ERROR_UNEXPECTED); + + /* Initialize the ctx. Required by X509V3_EXT_conf_nid. */ + /* No configuration database */ + X509V3_set_ctx_nodb(&ctx); + /* Use the target as both issuer and subject for the self-signed + * certificate. */ + X509V3_set_ctx(&ctx, x509cert, x509cert, NULL, NULL, 0); + + /* Set the basic constraints extention */ + ext = X509V3_EXT_conf_nid(NULL, &ctx, NID_basic_constraints, "CA:FALSE"); + SSL_ERR_BREAK(ext, SGX_ERROR_UNEXPECTED); + + ret = X509_add_ext(x509cert, ext, -1); + SSL_ERR_BREAK(ret, SGX_ERROR_UNEXPECTED); + + X509_EXTENSION_free(ext); + ext = NULL; + + /* Set the subject key identifier extension */ + ext = X509V3_EXT_conf_nid(NULL, &ctx, NID_subject_key_identifier, "hash"); + SSL_ERR_BREAK(ext, SGX_ERROR_UNEXPECTED); + + ret = X509_add_ext(x509cert, ext, -1); + SSL_ERR_BREAK(ret, SGX_ERROR_UNEXPECTED); + + X509_EXTENSION_free(ext); + ext = NULL; + + /* Set the authority key identifier extension */ + ext = X509V3_EXT_conf_nid( + NULL, &ctx, NID_authority_key_identifier, "keyid:always"); + SSL_ERR_BREAK(ext, SGX_ERROR_UNEXPECTED); + + ret = X509_add_ext(x509cert, ext, -1); + SSL_ERR_BREAK(ret, SGX_ERROR_UNEXPECTED); + + X509_EXTENSION_free(ext); + ext = NULL; + + /* Set the custom extension */ + data = ASN1_OCTET_STRING_new(); + SSL_ERR_BREAK(data, SGX_ERROR_UNEXPECTED); + + ret = ASN1_OCTET_STRING_set( + data, + (const unsigned char*)config->quote_buf, + (int)config->quote_buf_size); + SSL_ERR_BREAK(ret, SGX_ERROR_UNEXPECTED); + + obj = OBJ_txt2obj(config->ext_oid, 1); + SSL_ERR_BREAK(obj, SGX_ERROR_UNEXPECTED); + + if (!X509_EXTENSION_create_by_OBJ(&ext, obj, 0, data)) + break; + + ret = X509_add_ext(x509cert, ext, -1); + SSL_ERR_BREAK(ret, SGX_ERROR_UNEXPECTED); + + /* Sign the certificate */ + if (!X509_sign(x509cert, subject_issuer_key_pair, EVP_sha256())) + break; + + /* + * Write to DER + * The use of temporary variable is mandatory. + * If p is not NULL, the i2d_x509 function writes the DER encoded data to + * the buffer at *p and increments p to point after the data just written. + */ + p = buf; + len = i2d_X509(x509cert, &p); + if (len <= 0) + break; + + *bytes_written = (size_t)len; + + /* Copy DER data to buffer */ + if (0 != (memcpy_s((void*)cert_buf, cert_buf_size, (const void*)buf, *bytes_written))) + break; + + result = SGX_SUCCESS; + + } while(0); + + if (x509cert) + X509_free(x509cert); + if (ext) + X509_EXTENSION_free(ext); + if (name) + X509_NAME_free(name); + if (bio) + BIO_free(bio); + if (obj) + ASN1_OBJECT_free(obj); + if (data) + ASN1_OCTET_STRING_free(data); + if (bc) + BASIC_CONSTRAINTS_free(bc); + if (subject_issuer_key_pair) + EVP_PKEY_free(subject_issuer_key_pair); + if (buf) + { + free(buf); + buf = NULL; + } + if (oid) + { + free(oid); + oid = NULL; + } + p = NULL; + + return result; +} + +sgx_status_t generate_x509_self_signed_certificate( + const unsigned char* oid, + size_t oid_size, + const unsigned char *subject_name, + const uint8_t *p_prv_key, + size_t prv_key_size, + const uint8_t *p_pub_key, + size_t pub_key_size, + const uint8_t* p_quote_buf, + size_t quote_size, + uint8_t **output_cert, + size_t *output_cert_size) +{ + sgx_status_t ret = SGX_ERROR_UNEXPECTED; + size_t bytes_written = 0; + uint8_t* cert_buf = NULL; + sgx_cert_config_t config; + size_t sgx_cert_size = 0; + + config.private_key_buf = (uint8_t*)p_prv_key; + config.private_key_buf_size = prv_key_size; + config.public_key_buf = (uint8_t*)p_pub_key; + config.public_key_buf_size = pub_key_size; + config.subject_name = (subject_name != NULL) + ? subject_name + : (const unsigned char*)SUBJECT_NAME; + config.issuer_name = config.subject_name; + config.date_not_valid_before = (unsigned char*)DATE_NOT_VALID_BEFORE; + config.date_not_valid_after = (unsigned char*)DATE_NOT_VALID_AFTER; + config.quote_buf = (uint8_t*)p_quote_buf; + config.quote_buf_size = quote_size; + config.ext_oid = (char*)oid; + config.ext_oid_size = oid_size; + + do { + // allocate memory for cert output buffer and leave room for paddings + sgx_cert_size = quote_size + pub_key_size + SGX_MIN_CERT_SIZE; + cert_buf = (uint8_t*)malloc(sgx_cert_size); + if (cert_buf == NULL) + break; + + try { + ret = sgx_gen_custom_x509_cert(&config, cert_buf, sgx_cert_size, &bytes_written); + + if (ret != SGX_SUCCESS) + break; + } + catch (...) { + ret = SGX_ERROR_UNEXPECTED; + break; + } + + *output_cert_size = (size_t)bytes_written; + *output_cert = cert_buf; + ret = SGX_SUCCESS; + } while (0); + + if (ret != SGX_SUCCESS) { + if(cert_buf) { + free(cert_buf); + cert_buf = NULL; + } + } + + return ret; +} diff --git a/sdk/ttls/cert_header.h b/sdk/ttls/cert_header.h new file mode 100644 index 000000000..054210be6 --- /dev/null +++ b/sdk/ttls/cert_header.h @@ -0,0 +1,142 @@ +/** + * + * MIT License + * + * Copyright (c) Open Enclave SDK contributors. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE + * + */ + +#ifndef _CERT_HEADER_H_ +#define _CERT_HEADER_H_ + +#include +#include +#include +#include "sgx_error.h" + + +#define SGX_CERT_MAGIC 0xa7a55f4322919317 +#define SGX_CERT_CHAIN_MAGIC 0xa87e5d8e25671870 +#define SGX_CRL_MAGIC 0x8f062e782b5760b2 +#define SGX_EC_PRIVATE_KEY_MAGIC 0x9ffae0517397b76c +#define SGX_EC_PUBLIC_KEY_MAGIC 0xb8e1d57e9be31ed7 +#define SGX_RSA_PRIVATE_KEY_MAGIC 0xba24987b29769828 +#define SGX_RSA_PUBLIC_KEY_MAGIC 0x92f1fdf6c81b4aaa + +// joint-ise-ccitt (2) country (16) usa (840) org (1) intel (113741) sgx (13.1) +#define X509_OID_FOR_QUOTE_STRING "1.2.840.113741.1.13.1" + +typedef struct _sgx_cert +{ + /* Internal private implementation */ + uint64_t impl[4]; +} sgx_cert_t; + +typedef struct _sgx_cert_chain +{ + /* Internal private implementation */ + uint64_t impl[4]; +} sgx_cert_chain_t; + +typedef struct _sgx_crl +{ + /* Internal private implementation */ + uint64_t impl[4]; +} sgx_crl_t; + +typedef struct _crl +{ + uint64_t magic; + X509_CRL* crl; +} crl_t; + +typedef struct _sgx_oid_string +{ + char buf[128]; +} sgx_oid_string_t; + +typedef struct _sgx_public_key_t +{ + EVP_PKEY* pkey; +} sgx_public_key_t; + +typedef struct _sgx_cert_config +{ + uint8_t* private_key_buf; + size_t private_key_buf_size; + uint8_t* public_key_buf; + size_t public_key_buf_size; + const unsigned char* subject_name; + const unsigned char* issuer_name; + unsigned char* date_not_valid_before; + unsigned char* date_not_valid_after; + uint8_t* quote_buf; + size_t quote_buf_size; + char* ext_oid; + size_t ext_oid_size; +} sgx_cert_config_t; + +/* includes all the headers from version number to subject unique identifier of + * a X509 certificate */ +#define SGX_MIN_CERT_SIZE 2048 +#define KEY_BUFF_SIZE SGX_MIN_CERT_SIZE + +#define SGX_TLS_SAFE_FREE(x) {if(x) {free(x); x=NULL;}} + +// Input: An issuer and subject key pair +// Output: A self-signed certificate embedded critical extension with quote +// Information as its content +sgx_status_t generate_x509_self_signed_certificate( + const unsigned char* oid, + size_t oid_size, + const unsigned char *subject_name, + const uint8_t *p_prv_key, + size_t prv_key_size, + const uint8_t *p_pub_key, + size_t pub_key_size, + const uint8_t* p_quote_buf, + size_t quote_size, + uint8_t **output_cert, + size_t *output_cert_size); + +sgx_status_t sgx_read_cert_in_der( + sgx_cert_t* cert, + const void* der_data, + size_t der_size); + +sgx_status_t sgx_cert_verify( + sgx_cert_t* cert, + sgx_cert_chain_t* chain, + const sgx_crl_t* const* crls, + size_t num_crls); + +sgx_status_t sgx_cert_find_extension( + const sgx_cert_t* cert, + const char* oid, + uint8_t* data, + uint32_t* size); + +sgx_status_t sgx_get_pubkey_from_cert( + const sgx_cert_t* cert, + uint8_t* pem_data, + size_t* pem_size); + +#endif diff --git a/sdk/ttls/cert_verifier.cpp b/sdk/ttls/cert_verifier.cpp new file mode 100644 index 000000000..0eb934e75 --- /dev/null +++ b/sdk/ttls/cert_verifier.cpp @@ -0,0 +1,544 @@ +/** + * + * MIT License + * + * Copyright (c) Open Enclave SDK contributors. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE + * + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "cert_header.h" + +typedef struct _cert +{ + uint64_t magic; + X509* x509; +} cert_t; + + +static void _cert_init(cert_t* impl, X509* x509) +{ + impl->magic = SGX_CERT_MAGIC; + impl->x509 = x509; +} + +static bool _cert_is_valid(const cert_t* impl) +{ + return impl && (impl->magic == SGX_CERT_MAGIC) && impl->x509; +} + +static void _cert_clear(cert_t* impl) +{ + if (impl) + { + impl->magic = 0; + impl->x509 = NULL; + } +} + +typedef struct _cert_chain +{ + uint64_t magic; + STACK_OF(X509) * sk; +} cert_chain_t; + +static bool _cert_chain_is_valid(const cert_chain_t* impl) +{ + return impl && (impl->magic == SGX_CERT_CHAIN_MAGIC) && impl->sk; +} + +/* Clone the certificate to clear any verification state */ +static X509* _clone_x509(X509* x509) +{ + X509* ret = NULL; + BIO* out = NULL; + BIO* in = NULL; + BUF_MEM* mem; + + if (!x509) + goto done; + + if (!(out = BIO_new(BIO_s_mem()))) + goto done; + + if (!PEM_write_bio_X509(out, x509)) + goto done; + + if (!BIO_get_mem_ptr(out, &mem)) + goto done; + + if (mem->length > INT_MAX) + goto done; + + if (!(in = BIO_new_mem_buf(mem->data, (int)mem->length))) + goto done; + + ret = PEM_read_bio_X509(in, NULL, 0, NULL); + +done: + + if (out) + BIO_free(out); + + if (in) + BIO_free(in); + + return ret; +} + +#if OPENSSL_VERSION_NUMBER < 0x10100000L +/* Needed because some versions of OpenSSL do not support X509_up_ref() */ +static int X509_up_ref(X509* x509) +{ + if (!x509) + return 0; + + CRYPTO_add(&x509->references, 1, CRYPTO_LOCK_X509); + return 1; +} + +static const STACK_OF(X509_EXTENSION) * X509_get0_extensions(const X509* x) +{ + if (!x->cert_info) + { + return NULL; + } + return x->cert_info->extensions; +} + +#endif + +static STACK_OF(X509) * _clone_chain(STACK_OF(X509) * chain) +{ + STACK_OF(X509)* sk = NULL; + int n = sk_X509_num(chain); + + if (!(sk = sk_X509_new(NULL))) + return NULL; + + for (int i = 0; i < n; i++) + { + X509* x509; + + if (!(x509 = sk_X509_value(chain, (int)i))) + return NULL; + + if (!(x509 = _clone_x509(x509))) + return NULL; + + if (!sk_X509_push(sk, x509)) + return NULL; + } + + return sk; +} + +static sgx_status_t _verify_cert( + X509* cert, + STACK_OF(X509) * chain_, + const sgx_crl_t* const* crls, + size_t num_crls) +{ + sgx_status_t result = SGX_ERROR_UNEXPECTED; + X509_STORE_CTX* ctx = NULL; + X509_STORE* store = NULL; + X509* x509 = NULL; + STACK_OF(X509)* chain = NULL; + + /* Clone the certificate to clear any cached verification state */ + if (!(x509 = _clone_x509(cert))) + goto end; + + /* Clone the chain to clear any cached verification state */ + if (chain_ && !(chain = _clone_chain(chain_))) + goto end; + + /* Create a store for the verification */ + if (!(store = X509_STORE_new())) + goto end; + + /* Create a context for verification */ + if (!(ctx = X509_STORE_CTX_new())) + goto end; + + /* Initialize the context that will be used to verify the certificate */ + if (!X509_STORE_CTX_init(ctx, store, NULL, NULL)) + goto end; + + /* Create a store with CRLs if needed */ + if (crls && num_crls) + { + X509_VERIFY_PARAM* verify_param = NULL; + + for (size_t i = 0; i < num_crls; i++) + { + crl_t* crl_impl = (crl_t*)crls[i]; + + /* X509_STORE_add_crl manages its own addition refcount */ + if (!X509_STORE_add_crl(store, crl_impl->crl)) + goto end; + } + + /* Get the verify parameter (must not be null) */ + if (!(verify_param = X509_STORE_CTX_get0_param(ctx))) + goto end; + + X509_VERIFY_PARAM_set_flags(verify_param, X509_V_FLAG_CRL_CHECK); + X509_VERIFY_PARAM_set_flags(verify_param, X509_V_FLAG_CRL_CHECK_ALL); + } + + /* Inject the certificate into the verification context */ + X509_STORE_CTX_set_cert(ctx, x509); + + /* Set the CA chain into the verification context */ + if (chain) + X509_STORE_CTX_trusted_stack(ctx, chain); + else + X509_STORE_add_cert(store, x509); + + /* Finally verify the certificate */ + if (!X509_verify_cert(ctx)) + { + int errorno = X509_STORE_CTX_get_error(ctx); + if (errorno != X509_V_OK) + goto end; + } + + result = SGX_SUCCESS; + +end: + if (x509) + X509_free(x509); + + if (chain) + sk_X509_pop_free(chain, X509_free); + + if (store) + X509_STORE_free(store); + + if (ctx) + X509_STORE_CTX_free(ctx); + + return result; +} + + +sgx_status_t sgx_read_cert_in_der( + sgx_cert_t* cert, + const void* der_data, + size_t der_size) +{ + sgx_status_t result = SGX_ERROR_UNEXPECTED; + cert_t* impl = (cert_t*)cert; + X509* x509 = NULL; + unsigned char* p = NULL; + + /* Zero-initialize the implementation */ + if (impl) + impl->magic = 0; + + /* Check parameters */ + if (!der_data || !der_size || der_size > INT_MAX || !cert) + return SGX_ERROR_INVALID_PARAMETER; + + /* Initialize OpenSSL (if not already initialized) */ + //sgxssl_crypto_initialize(); + + p = (unsigned char*)der_data; + + /* Convert the PEM BIO into a certificate object */ + if (!(x509 = d2i_X509(NULL, (const unsigned char**)&p, (int)der_size))) + goto end; + + _cert_init(impl, x509); + x509 = NULL; + + result = SGX_SUCCESS; + +end: + + X509_free(x509); + + return result; +} + +sgx_status_t sgx_cert_free(sgx_cert_t* cert) +{ + sgx_status_t result = SGX_ERROR_UNEXPECTED; + cert_t* impl = (cert_t*)cert; + + /* Check parameters */ + if (!_cert_is_valid(impl)) + goto end; + + /* Free the certificate */ + X509_free(impl->x509); + _cert_clear(impl); + + result = SGX_SUCCESS; + +end: + return result; +} + +sgx_status_t sgx_cert_verify( + sgx_cert_t* cert, + sgx_cert_chain_t* chain, + const sgx_crl_t* const* crls, + size_t num_crls) +{ + sgx_status_t result = SGX_ERROR_UNEXPECTED; + cert_t* cert_impl = (cert_t*)cert; + cert_chain_t* chain_impl = (cert_chain_t*)chain; + + /* Check for invalid cert parameter */ + if (!_cert_is_valid(cert_impl)) + return SGX_ERROR_INVALID_PARAMETER; + + /* Check for invalid chain parameter */ + if (chain && !_cert_chain_is_valid(chain_impl)) + return SGX_ERROR_INVALID_PARAMETER; + + /* Verify the certificate */ + _verify_cert( + cert_impl->x509, + (chain_impl != NULL ? chain_impl->sk : NULL), + crls, + num_crls); + + result = SGX_SUCCESS; + + return result; +} + +sgx_status_t sgx_cert_find_extension( + const sgx_cert_t* cert, + const char* oid, + uint8_t* data, + uint32_t* size) +{ + sgx_status_t result = SGX_ERROR_UNEXPECTED; + const cert_t* impl = (const cert_t*)cert; + const STACK_OF(X509_EXTENSION) * extensions; + int num_extensions; + + /* Reject invalid parameters */ + if (!_cert_is_valid(impl) || !oid || !size) { + result = SGX_ERROR_INVALID_PARAMETER; + goto done; + } + + /* Set a pointer to the stack of extensions (possibly NULL) */ + if (!(extensions = X509_get0_extensions(impl->x509))) + goto done; + + /* Get the number of extensions (possibly zero) */ + num_extensions = sk_X509_EXTENSION_num(extensions); + + /* Find the certificate with this OID */ + for (int i = 0; i < num_extensions; i++) + { + X509_EXTENSION* ext; + ASN1_OBJECT* obj; + sgx_oid_string_t ext_oid; + + /* Get the i-th extension from the stack */ + if (!(ext = sk_X509_EXTENSION_value(extensions, i))) + goto done; + + /* Get the OID */ + if (!(obj = X509_EXTENSION_get_object(ext))) + goto done; + + /* Get the string name of the OID */ + if (!OBJ_obj2txt(ext_oid.buf, sizeof(ext_oid.buf), obj, 1)) + goto done; + + /* If found then get the data */ + if (strcmp(ext_oid.buf, oid) == 0) + { + ASN1_OCTET_STRING* str; + + /* Get the data from the extension */ + if (!(str = X509_EXTENSION_get_data(ext))) + goto done; + + /* If the caller's buffer is too small, raise error */ + if ((size_t)str->length > *size) + { + *size = (size_t)str->length; + result = SGX_ERROR_INVALID_PARAMETER; + goto done; + } + + if (data) + { + memcpy(data, str->data, (size_t)str->length); + *size = (size_t)str->length; + result = SGX_SUCCESS; + goto done; + } + } + } + +done: + return result; +} + +sgx_status_t sgx_cert_get_public_key( + const sgx_cert_t* cert, + sgx_public_key_t* public_key) +{ + sgx_status_t result = SGX_ERROR_UNEXPECTED; + const cert_t* impl = (const cert_t*)cert; + EVP_PKEY* pkey = NULL; + + if (public_key) + memset(public_key, 0, sizeof(sgx_public_key_t)); + + if (!_cert_is_valid(impl) || !public_key) { + result = SGX_ERROR_INVALID_PARAMETER; + goto done; + } + + if (!(pkey = X509_get_pubkey(impl->x509))) { + result = SGX_ERROR_UNEXPECTED; + goto done; + } + + public_key->pkey = pkey; + pkey = NULL; + + result = SGX_SUCCESS; + +done: + + if (pkey) + { + EVP_PKEY_free(pkey); + } + + return result; +} + +sgx_status_t sgx_public_key_write_pem( + const sgx_public_key_t* key, + uint8_t* data, + size_t* size) +{ + sgx_status_t result = SGX_ERROR_UNEXPECTED; + BIO* bio = NULL; + const sgx_public_key_t* impl = (const sgx_public_key_t*)key; + const char null_terminator = '\0'; + + /* If buffer is null, then size must be zero */ + if (!key || (!data && *size != 0)) { + result = SGX_ERROR_INVALID_PARAMETER; + goto done; + } + + /* Create memory BIO object to write key to */ + if (!(bio = BIO_new(BIO_s_mem()))) { + result = SGX_ERROR_UNEXPECTED; + goto done; + } + + /* Write key to BIO */ + if (!PEM_write_bio_PUBKEY(bio, impl->pkey)) { + result = SGX_ERROR_UNEXPECTED; + goto done; + } + + /* Write a NULL terminator onto BIO */ + if (BIO_write(bio, &null_terminator, sizeof(null_terminator)) <= 0) { + result = SGX_ERROR_UNEXPECTED; + goto done; + } + + /* Copy the BIO onto caller's memory */ + { + BUF_MEM* mem; + + if (!BIO_get_mem_ptr(bio, &mem)) { + result = SGX_ERROR_UNEXPECTED; + goto done; + } + + /* If buffer is too small */ + if (*size < mem->length) + { + *size = mem->length; + + result = SGX_ERROR_OUT_OF_MEMORY; + goto done; + } + + /* Copy result to output buffer */ + memcpy(data, mem->data, mem->length); + *size = mem->length; + } + + result = SGX_SUCCESS; + +done: + + if (bio) + BIO_free(bio); + + return result; +} + + +sgx_status_t sgx_get_pubkey_from_cert( + const sgx_cert_t* cert, + uint8_t* pem_data, + size_t* pem_size) +{ + sgx_status_t result = SGX_ERROR_UNEXPECTED; + sgx_public_key_t public_key; + + if (SGX_SUCCESS != sgx_cert_get_public_key(cert, &public_key)) { + goto done; + } + + if (SGX_SUCCESS != sgx_public_key_write_pem(&public_key, pem_data, pem_size)) { + goto done; + } + + result = SGX_SUCCESS; + +done: + + if (public_key.pkey) { + EVP_PKEY_free(public_key.pkey); + public_key.pkey = NULL; + } + + return result; +} diff --git a/sdk/ttls/tsgxsslio.h b/sdk/ttls/tsgxsslio.h new file mode 100644 index 000000000..91de2d4da --- /dev/null +++ b/sdk/ttls/tsgxsslio.h @@ -0,0 +1,37 @@ +/* + * 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. + * + */ + +#ifndef _TSGXSSL_IO_H_ +#define _TSGXSSL_IO_H_ + +typedef void FILE; + +#endif // _TSGXSSL_IO_H_ diff --git a/sdk/ttls/ttls.cpp b/sdk/ttls/ttls.cpp new file mode 100644 index 000000000..63f37a921 --- /dev/null +++ b/sdk/ttls/ttls.cpp @@ -0,0 +1,378 @@ +/* + * 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 "sgx_ttls.h" +#include "sgx_utils.h" +#include "sgx_tcrypto.h" +#include "sgx_quote_3.h" +#include "cert_header.h" +#include "sgx_dcap_tvl.h" +#include +#include +#include "sgx_ttls_t.h" + +static const char* oid_sgx_quote = X509_OID_FOR_QUOTE_STRING; + +extern "C" quote3_error_t SGXAPI tee_get_certificate_with_evidence( + const unsigned char *p_subject_name, + const uint8_t *p_prv_key, + size_t private_key_size, + const uint8_t *p_pub_key, + size_t public_key_size, + uint8_t **pp_output_cert, + size_t *p_output_cert_size) +{ + sgx_status_t ret = SGX_ERROR_UNEXPECTED; + quote3_error_t func_ret = SGX_QL_ERROR_UNEXPECTED; + sgx_report_t app_report; + sgx_target_info_t target_info; + uint8_t *p_quote = NULL; + uint32_t quote_size = 0; + sgx_sha_state_handle_t sha_handle = NULL; + sgx_report_data_t report_data = { 0 }; + + if (p_subject_name == NULL || + p_prv_key == NULL || private_key_size <= 0 || + p_pub_key == NULL || public_key_size <= 0 || + pp_output_cert == NULL || p_output_cert_size == NULL) + return SGX_QL_ERROR_INVALID_PARAMETER; + + // only support PEM format key + if (strnlen(reinterpret_cast(p_pub_key), public_key_size) != public_key_size - 1 || + strnlen(reinterpret_cast(p_prv_key), private_key_size) != private_key_size -1) + return SGX_QL_ERROR_INVALID_PARAMETER; + + do { + //OCALL to get target info of QE + ret = sgx_tls_get_qe_target_info_ocall(&func_ret, &target_info, sizeof(sgx_target_info_t)); + if (ret != SGX_SUCCESS) { + func_ret = SGX_QL_ERROR_UNEXPECTED; + break; + } + if (func_ret != SGX_QL_SUCCESS) + break; + + //Use user provided input as report data + //report data = sha256(public key) || 0s + ret = sgx_sha256_init(&sha_handle); + if (ret != SGX_SUCCESS) { + func_ret = SGX_QL_ERROR_UNEXPECTED; + break; + } + + ret = sgx_sha256_update(p_pub_key, (uint32_t)public_key_size, sha_handle); + if (ret != SGX_SUCCESS) { + func_ret = SGX_QL_ERROR_UNEXPECTED; + break; + } + + ret = sgx_sha256_get_hash(sha_handle, reinterpret_cast(&report_data)); + if (ret != SGX_SUCCESS) { + func_ret = SGX_QL_ERROR_UNEXPECTED; + break; + } + + //generate report with returned QE target info + ret = sgx_create_report(&target_info, &report_data, &app_report); + if (ret != SGX_SUCCESS) { + func_ret = SGX_QL_ERROR_UNEXPECTED; + break; + } + + //OCALL to get quote size + ret = sgx_tls_get_quote_size_ocall(&func_ret, "e_size); + if (ret != SGX_SUCCESS) { + func_ret = SGX_QL_ERROR_UNEXPECTED; + break; + } + if (func_ret != SGX_QL_SUCCESS) + break; + + p_quote = (uint8_t *) malloc (quote_size); + if (p_quote == NULL) { + func_ret = SGX_QL_ERROR_OUT_OF_MEMORY; + break; + } + memset (p_quote, 0, quote_size); + + //OCALL to get quote + ret = sgx_tls_get_quote_ocall(&func_ret, &app_report, sizeof(sgx_report_t), p_quote, quote_size); + if (ret != SGX_SUCCESS) { + func_ret = SGX_QL_ERROR_UNEXPECTED; + break; + } + if (func_ret != SGX_QL_SUCCESS) + break; + + //Generate self-signed X.509 certiciate + //Make SGX quote as an extension + ret = generate_x509_self_signed_certificate( + (const unsigned char*) oid_sgx_quote, + strlen(oid_sgx_quote), + p_subject_name, + p_prv_key, + private_key_size, + p_pub_key, + public_key_size, + p_quote, + quote_size, + pp_output_cert, + p_output_cert_size); + if (ret != SGX_SUCCESS) { + func_ret = SGX_QL_ERROR_UNEXPECTED; + break; + } + + func_ret = SGX_QL_SUCCESS; + + } while (0); + + SGX_TLS_SAFE_FREE(p_quote); + + if (sha_handle) + sgx_sha256_close(sha_handle); + + return func_ret; +} + +extern "C" quote3_error_t tee_free_certificate(uint8_t* p_certificate) +{ + SGX_TLS_SAFE_FREE(p_certificate); + return SGX_QL_SUCCESS; +} + +extern "C" quote3_error_t tee_verify_certificate_with_evidence( + const uint8_t *p_cert_in_der, + size_t cert_in_der_len, + const time_t expiration_check_date, + sgx_ql_qv_result_t *p_qv_result, + uint8_t **pp_supplemental_data, + uint32_t *p_supplemental_data_size) +{ + sgx_status_t ret = SGX_ERROR_UNEXPECTED; + quote3_error_t func_ret = SGX_QL_ERROR_UNEXPECTED; + uint8_t *p_quote = NULL; + uint32_t quote_size = 0; + sgx_ql_qe_report_info_t qve_report_info; + uint32_t collateral_expiration_status = 0; + + sgx_cert_t cert = {0}; + uint8_t *pub_key_buff = NULL; + size_t pub_key_buff_size = KEY_BUFF_SIZE; + sgx_quote3_t *p_sgx_quote = NULL; + sgx_report_data_t *p_report_data = NULL; + sgx_report_data_t cert_pub_hash; + sgx_sha_state_handle_t sha_handle = NULL; + + //The ISVSVN threshold of Intel signed QvE + const sgx_isv_svn_t qve_isvsvn_threshold = 5; + + memset(&cert_pub_hash, 0, sizeof(sgx_report_data_t)); + + if (p_cert_in_der == NULL || + p_qv_result == NULL || + pp_supplemental_data == NULL || + p_supplemental_data_size == NULL) + return SGX_QL_ERROR_INVALID_PARAMETER; + + + do { + //verify X.509 certificate + pub_key_buff = (uint8_t*)malloc(KEY_BUFF_SIZE); + if (!pub_key_buff) { + func_ret = SGX_QL_OUT_OF_EPC; + break; + } + memset(pub_key_buff, 0, KEY_BUFF_SIZE); + + try { + ret = sgx_read_cert_in_der(&cert, p_cert_in_der, cert_in_der_len); + if (ret != SGX_SUCCESS) + break; + + // validate the certificate signature + ret = sgx_cert_verify(&cert, NULL, NULL, 0); + if (ret != SGX_SUCCESS) + break; + + // try to get quote from cert extension + if (sgx_cert_find_extension( + &cert, + oid_sgx_quote, + NULL, + "e_size) == SGX_ERROR_INVALID_PARAMETER) + { + p_quote = (uint8_t*)malloc(quote_size); + if (!p_quote) { + func_ret = SGX_QL_ERROR_OUT_OF_MEMORY; + break; + } + } + + if (sgx_cert_find_extension( + &cert, + oid_sgx_quote, + p_quote, + "e_size) != SGX_SUCCESS) + { + func_ret = SGX_QL_ERROR_UNEXPECTED; + break; + } + } + + catch (...) { + func_ret = SGX_QL_ERROR_UNEXPECTED; + break; + } + + //OCALL to get supplemental data size + ret = sgx_tls_get_supplemental_data_size_ocall(&func_ret, p_supplemental_data_size); + if (ret != SGX_SUCCESS) { + func_ret = SGX_QL_ERROR_UNEXPECTED; + break; + } + if (func_ret != SGX_QL_SUCCESS) + break; + + *pp_supplemental_data = (uint8_t *) malloc (*p_supplemental_data_size); + if (*pp_supplemental_data == NULL) { + func_ret = SGX_QL_OUT_OF_EPC; + break; + } + + ret = sgx_read_rand(reinterpret_cast (&qve_report_info.nonce), sizeof(sgx_quote_nonce_t)); + if (ret != SGX_SUCCESS) { + func_ret = SGX_QL_ERROR_UNEXPECTED; + break; + } + + ret = sgx_self_target(&qve_report_info.app_enclave_target_info); + if (ret != SGX_SUCCESS) { + func_ret = SGX_QL_ERROR_UNEXPECTED; + break; + } + + //OCALL to verify SGX quote + ret = sgx_tls_verify_quote_ocall( + &func_ret, + p_quote, + quote_size, + expiration_check_date, + p_qv_result, + &qve_report_info, + sizeof(sgx_ql_qe_report_info_t), + *pp_supplemental_data, + *p_supplemental_data_size); + + if (ret != SGX_SUCCESS) { + func_ret = SGX_QL_ERROR_UNEXPECTED; + break; + } + if (func_ret != SGX_QL_SUCCESS) + break; + + //call TVL API to verify the idenity of Intel signed QvE + func_ret = sgx_tvl_verify_qve_report_and_identity( + p_quote, + quote_size, + &qve_report_info, + expiration_check_date, + collateral_expiration_status, + *p_qv_result, + *pp_supplemental_data, + *p_supplemental_data_size, + qve_isvsvn_threshold); + + if (func_ret != SGX_QL_SUCCESS) + break; + + // extract public key from cert + ret = sgx_get_pubkey_from_cert(&cert, pub_key_buff, &pub_key_buff_size); + if (ret != SGX_SUCCESS) { + func_ret = SGX_QL_ERROR_UNEXPECTED; + break; + } + + // get hash of cert pub key + ret = sgx_sha256_init(&sha_handle); + if (ret != SGX_SUCCESS) { + func_ret = SGX_QL_ERROR_UNEXPECTED; + break; + } + + // public key + ret = sgx_sha256_update(pub_key_buff, (uint32_t)pub_key_buff_size, sha_handle); + if (ret != SGX_SUCCESS) { + func_ret = SGX_QL_ERROR_UNEXPECTED; + break; + } + + ret = sgx_sha256_get_hash(sha_handle, reinterpret_cast(&cert_pub_hash)); + if (ret != SGX_SUCCESS) { + func_ret = SGX_QL_ERROR_UNEXPECTED; + break; + } + + // get report data from quote + p_sgx_quote = (sgx_quote3_t *) p_quote; + + if (p_sgx_quote != NULL) { + p_report_data = &(p_sgx_quote->report_body.report_data); + } + else { + func_ret = SGX_QL_ERROR_UNEXPECTED; + break; + } + + // compare hash, only compare the first 32 bytes + if (memcmp(p_report_data, &cert_pub_hash, SGX_HASH_SIZE) != 0) { + func_ret = SGX_QL_ERROR_PUB_KEY_ID_MISMATCH; + break; + } + + } while(0); + + SGX_TLS_SAFE_FREE(pub_key_buff); + SGX_TLS_SAFE_FREE(p_quote); + if (func_ret != SGX_QL_SUCCESS) + SGX_TLS_SAFE_FREE(*pp_supplemental_data); + + if (sha_handle) + sgx_sha256_close(sha_handle); + + return func_ret; +} + +quote3_error_t tee_free_supplemental_data(uint8_t* p_supplemental_data) +{ + SGX_TLS_SAFE_FREE(p_supplemental_data); + return SGX_QL_SUCCESS; +} diff --git a/sdk/ukey_exchange/Makefile b/sdk/ukey_exchange/Makefile index 6b65a65df..191d8ddc4 100644 --- a/sdk/ukey_exchange/Makefile +++ b/sdk/ukey_exchange/Makefile @@ -32,8 +32,8 @@ TOP_DIR = ../.. include $(TOP_DIR)/buildenv.mk -CFLAGS += -Werror -CXXFLAGS += -Werror +CFLAGS += -Werror $(CET_FLAGS) +CXXFLAGS += -Werror $(CET_FLAGS) INCLUDE += -I$(COMMON_DIR)/inc/internal \ -I$(COMMON_DIR)/inc diff --git a/sdk/utls/Makefile b/sdk/utls/Makefile new file mode 100644 index 000000000..9c1d2e68a --- /dev/null +++ b/sdk/utls/Makefile @@ -0,0 +1,89 @@ +# +# 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. +# +# + +TOP_DIR = ../.. +include $(TOP_DIR)/buildenv.mk + +CERT_UTIL_DIR := ../ttls +SGX_QV_PATH ?= ../../external/dcap_source/QuoteVerification +PREBUILD_OPENSSL_PATH ?= $(SGX_QV_PATH)/../prebuilt/openssl + + +INCLUDE += -I. +INCLUDE += -I$(COMMON_DIR) \ + -I$(COMMON_DIR)/inc \ + -I$(COMMON_DIR)/inc/internal \ + -I$(PREBUILD_OPENSSL_PATH)/inc \ + -I$(CERT_UTIL_DIR) \ + -I$(SGX_QV_PATH)/QvE/Include \ + -I$(SGX_QV_PATH)/dcap_quoteverify/inc \ + -I$(SGX_QV_PATH)/../QuoteGeneration/quote_wrapper/common/inc \ + -I$(SGX_QV_PATH)/../QuoteGeneration/quote_wrapper/ql/inc \ + -I$(SGX_QV_PATH)/../QuoteGeneration/pce_wrapper/inc + + +CXXFLAGS += $(COMMON_FLAGS) $(COMMON_LDFLAGS) -fPIC -Werror -Wno-unused-parameter -g + + +vpath %.cpp .. $(COMMON_DIR)/src $(CERT_UTIL_DIR) + +SRC := utls.cpp + +HOST_CERT_SRC := cert_verifier.cpp + +OBJ := $(SRC:.cpp=.o) + +CERT_OBJ := $(HOST_CERT_SRC:.cpp=.o) + +LIBNAME = libsgx_utls.a + +.PHONY: all +all: $(LIBNAME) | $(BUILD_DIR) + $(CP) $(LIBNAME) $| + +$(OBJ): $(SRC) + $(CXX) $(CXXFLAGS) -Wno-deprecated-declarations $(INCLUDE) -c $< -o $@ + +$(CERT_OBJ): $(HOST_CERT_SRC) + $(CXX) $(CXXFLAGS) -Wno-deprecated-declarations $(INCLUDE) -c $< -o $@ + +$(LIBNAME): $(OBJ) $(CERT_OBJ) + $(AR) rs $@ $(OBJ) $(CERT_OBJ) + +.PHONY: clean +clean: + @$(RM) $(OBJ) $(CERT_OBJ) + @$(RM) $(LIBNAME) $(BUILD_DIR)/$(LIBNAME) + +.PHONY: rebuild +rebuild: + $(MAKE) clean + $(MAKE) all diff --git a/sdk/utls/utls.cpp b/sdk/utls/utls.cpp new file mode 100644 index 000000000..7b548f9d9 --- /dev/null +++ b/sdk/utls/utls.cpp @@ -0,0 +1,313 @@ +/* + * 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 "sgx_utls.h" +#include "sgx_utils.h" +#include "sgx_error.h" +#include "sgx_quote_3.h" +#include "cert_header.h" +#include "se_memcpy.h" + +#include "sgx_ql_quote.h" +#include "sgx_dcap_quoteverify.h" +#include "sgx_dcap_ql_wrapper.h" +#include "sgx_pce.h" + +#include +#include + +static const char* oid_sgx_quote = X509_OID_FOR_QUOTE_STRING; + +extern "C" quote3_error_t sgx_tls_get_qe_target_info_ocall(sgx_target_info_t *p_target_info, size_t target_info_size) +{ + if (p_target_info == NULL || target_info_size != sizeof(sgx_target_info_t)) + return SGX_QL_ERROR_INVALID_PARAMETER; + + return sgx_qe_get_target_info(p_target_info); + +} + +extern "C" quote3_error_t sgx_tls_get_quote_size_ocall(uint32_t *p_quote_size) +{ + return sgx_qe_get_quote_size(p_quote_size); +} + +extern "C" quote3_error_t sgx_tls_get_quote_ocall(sgx_report_t* p_report, size_t report_size, uint8_t *p_quote, size_t quote_size) +{ + quote3_error_t ret = SGX_QL_SUCCESS; + uint32_t tmp_quote_size = 0; + uint8_t *p_tmp_quote = NULL; + + + if (p_report == NULL || p_quote == NULL) + return SGX_QL_ERROR_INVALID_PARAMETER; + + do { + //Use DCAP quote generation in-proc mode by default + ret = sgx_qe_get_quote_size(&tmp_quote_size); + if (ret != SGX_QL_SUCCESS) { + break; + } + + if (tmp_quote_size == 0) + break; + + p_tmp_quote = (uint8_t*) malloc (tmp_quote_size); + if (p_tmp_quote == NULL) { + ret = SGX_QL_ERROR_OUT_OF_MEMORY; + break; + } + + if (tmp_quote_size != quote_size) { + ret = SGX_QL_ERROR_INVALID_PARAMETER; + break; + } + + memset(p_tmp_quote, 0, tmp_quote_size); + + // Get the Quote + ret = sgx_qe_get_quote(p_report, tmp_quote_size, p_tmp_quote); + if (ret != SGX_QL_SUCCESS) { + break; + } + + memset(p_quote, 0, quote_size); + memcpy_s(p_quote, tmp_quote_size, p_tmp_quote, tmp_quote_size); + + ret = SGX_QL_SUCCESS; + + } while(0); + + + if(p_tmp_quote) { + free(p_tmp_quote); + p_tmp_quote = NULL; + tmp_quote_size = 0; + } + + return ret; +} + +extern "C" quote3_error_t sgx_tls_get_supplemental_data_size_ocall(uint32_t *p_supplemental_data_size) +{ + return sgx_qv_get_quote_supplemental_data_size(p_supplemental_data_size); +} + +extern "C" quote3_error_t sgx_tls_verify_quote_ocall( + const uint8_t *p_quote, + uint32_t quote_size, + time_t expiration_check_date, + sgx_ql_qv_result_t *p_quote_verification_result, + sgx_ql_qe_report_info_t *p_qve_report_info, + size_t qve_report_info_size, + uint8_t *p_supplemental_data, + uint32_t supplemental_data_size) +{ + uint32_t collateral_expiration_status = 1; + + + if (p_quote == NULL || + p_quote_verification_result == NULL || + p_supplemental_data == NULL || + (p_qve_report_info == NULL && qve_report_info_size != 0) || + (p_qve_report_info != NULL && qve_report_info_size <= 0)) + return SGX_QL_ERROR_INVALID_PARAMETER; + + return sgx_qv_verify_quote( + p_quote, + quote_size, + NULL, + expiration_check_date, + &collateral_expiration_status, + p_quote_verification_result, + p_qve_report_info, + supplemental_data_size, + p_supplemental_data); +} + +extern "C" quote3_error_t tee_verify_certificate_with_evidence_host( + const uint8_t *p_cert_in_der, + size_t cert_in_der_len, + const time_t expiration_check_date, + sgx_ql_qv_result_t *p_qv_result, + uint8_t **pp_supplemental_data, + uint32_t *p_supplemental_data_size) +{ + sgx_status_t ret = SGX_ERROR_UNEXPECTED; + quote3_error_t func_ret = SGX_QL_ERROR_UNEXPECTED; + uint8_t *p_quote = NULL; + uint32_t quote_size = 0; + size_t pub_key_buff_size = KEY_BUFF_SIZE; + sgx_quote3_t *p_sgx_quote = NULL; + sgx_report_data_t *p_report_data = NULL; + sgx_report_data_t cert_pub_hash; + SHA256_CTX sha_handle; + + sgx_cert_t cert = {0}; + uint8_t *pub_key_buff = NULL; + + memset(&cert_pub_hash, 0, sizeof(sgx_report_data_t)); + + if (p_cert_in_der == NULL || + pp_supplemental_data == NULL) + return SGX_QL_ERROR_INVALID_PARAMETER; + + + do { + //verify X.509 certificate + pub_key_buff = (uint8_t*)malloc(KEY_BUFF_SIZE); + if (!pub_key_buff) { + func_ret = SGX_QL_OUT_OF_EPC; + break; + } + memset(pub_key_buff, 0, KEY_BUFF_SIZE); + + try { + ret = sgx_read_cert_in_der(&cert, p_cert_in_der, cert_in_der_len); + if (ret != SGX_SUCCESS) + break; + + // validate the certificate signature + ret = sgx_cert_verify(&cert, NULL, NULL, 0); + if (ret != SGX_SUCCESS) + break; + + // try to get quote from cert extension + if (sgx_cert_find_extension( + &cert, + oid_sgx_quote, + NULL, + "e_size) == SGX_ERROR_INVALID_PARAMETER) + { + p_quote = (uint8_t*)malloc(quote_size); + if (!p_quote) { + func_ret = SGX_QL_ERROR_OUT_OF_MEMORY; + break; + } + } + + if (sgx_cert_find_extension( + &cert, + oid_sgx_quote, + p_quote, + "e_size) != SGX_SUCCESS) + { + func_ret = SGX_QL_ERROR_UNEXPECTED; + break; + } + } + + catch (...) { + func_ret = SGX_QL_ERROR_UNEXPECTED; + break; + } + + func_ret = sgx_tls_get_supplemental_data_size_ocall(p_supplemental_data_size); + if (func_ret != SGX_QL_SUCCESS) { + break; + } + + *pp_supplemental_data = (uint8_t *) malloc (*p_supplemental_data_size); + if (*pp_supplemental_data == NULL) { + func_ret = SGX_QL_OUT_OF_EPC; + break; + } + + func_ret = sgx_tls_verify_quote_ocall (p_quote, + quote_size, + expiration_check_date, + p_qv_result, + NULL, + 0, + *pp_supplemental_data, + *p_supplemental_data_size); + + if (func_ret != SGX_QL_SUCCESS) + break; + + // extract public key from cert + ret = sgx_get_pubkey_from_cert(&cert, pub_key_buff, &pub_key_buff_size); + if (ret != SGX_SUCCESS) { + func_ret = SGX_QL_ERROR_UNEXPECTED; + break; + } + + // get hash of cert pub key + if (!SHA256_Init(&sha_handle)) { + func_ret = SGX_QL_ERROR_UNEXPECTED; + break; + } + + // public key + if (!SHA256_Update(&sha_handle, pub_key_buff, pub_key_buff_size)) { + func_ret = SGX_QL_ERROR_UNEXPECTED; + break; + } + + if (!SHA256_Final(reinterpret_cast(&cert_pub_hash), &sha_handle)) { + func_ret = SGX_QL_ERROR_UNEXPECTED; + break; + } + + // extract report data from quote + p_sgx_quote = (sgx_quote3_t *) p_quote; + + if (p_sgx_quote != NULL) { + p_report_data = &(p_sgx_quote->report_body.report_data); + } + else { + func_ret = SGX_QL_ERROR_UNEXPECTED; + break; + } + + // compare hash, only compare the first 32 bytes + if (memcmp(p_report_data, &cert_pub_hash, SGX_HASH_SIZE) != 0) { + func_ret = SGX_QL_ERROR_PUB_KEY_ID_MISMATCH; + break; + } + + + } while(0); + + SGX_TLS_SAFE_FREE(pub_key_buff); + SGX_TLS_SAFE_FREE(p_quote); + + if (func_ret != SGX_QL_SUCCESS) + SGX_TLS_SAFE_FREE(*pp_supplemental_data); + + return func_ret; +} + +extern "C" quote3_error_t tee_free_supplemental_data_host(uint8_t* p_supplemental_data) +{ + SGX_TLS_SAFE_FREE(p_supplemental_data); + return SGX_QL_SUCCESS; +}