From 6425ac97978d884ac1e95843e300389fd88d2fef Mon Sep 17 00:00:00 2001 From: chenmaodong Date: Tue, 6 Jul 2021 21:30:34 +0800 Subject: [PATCH] sync patches from openEuler-20.03-LTS-SP2 Signed-off-by: chenmaodong --- ...-error-of-missing-CMAKE_CXX_COMPILER.patch | 43 + 0010-fix-sgxssl-edl.patch | 23 + 0011-update-docs-build_install.md.patch | 25 + 0012-modify-the-prompt-information.patch | 25 + ...w-error-code-and-del-redundant-print.patch | 62 + 0014-fix-error-print.patch | 25 + 0015-set-umask-in-sign_tool.sh.patch | 24 + ...he-race-of-ecall-and-enclave-destroy.patch | 133 + ...ng-and-null-pointer-dereference-issu.patch | 52 + 0018-update-sign_tool.doc.patch | 50 + ...-normalized-codegen-from-arm-and-x86.patch | 157 ++ ...rm-e-parameter-normalize-c-parameter.patch | 329 +++ ...bsolute-path-to-find-enclave.sign.so.patch | 49 + 0022-add-example-of-using-sgxssl-lib.patch | 942 +++++++ ...s_enclave-is-not-compiled-by-default.patch | 25 + ...place-minial-cmake-from-3.12-to-3.10.patch | 68 + ...dd-example-for-LRT-long-running-task.patch | 517 ++++ ...ockerfile-to-build-lrt-example-image.patch | 172 ++ ...e-the-milestone-picture-with-English.patch | 29 + ...use-the-sgx-device-plugin-from-intel.patch | 73 + 0029-some-adaptations-for-trustzone.patch | 2159 +++++++++++++++++ ...x-two-step-mode-bug-add-dump-command.patch | 234 ++ 0031-set-signtool_v3.py-path.patch | 166 ++ 0032-del-size_to_aligned_size.patch | 25 + ...ror-information-when-missing-c-and-m.patch | 34 + ...rmalize-the-log-printed-by-PrintInfo.patch | 55 + 0035-itrustee-add-lrt-support-itrustee.patch | 99 + ...e-can-pull-image-from-hub.oepkgs.net.patch | 26 + ...about-file-parameter-path-for-sign_t.patch | 26 + ...-use-after-free-in-cc_enclave_create.patch | 805 ++++++ ...-memory-when-it-come-to-error_handle.patch | 79 + README.en.md | 48 +- README.md | 962 ++++---- secGear.spec | 136 +- 34 files changed, 7097 insertions(+), 580 deletions(-) create mode 100644 0009-fix-cmake-error-of-missing-CMAKE_CXX_COMPILER.patch create mode 100644 0010-fix-sgxssl-edl.patch create mode 100644 0011-update-docs-build_install.md.patch create mode 100644 0012-modify-the-prompt-information.patch create mode 100644 0013-parse-new-error-code-and-del-redundant-print.patch create mode 100644 0014-fix-error-print.patch create mode 100644 0015-set-umask-in-sign_tool.sh.patch create mode 100644 0016-1.fix-the-race-of-ecall-and-enclave-destroy.patch create mode 100644 0017-fix-wrong-spelling-and-null-pointer-dereference-issu.patch create mode 100644 0018-update-sign_tool.doc.patch create mode 100644 0019-normalized-codegen-from-arm-and-x86.patch create mode 100644 0020-rm-e-parameter-normalize-c-parameter.patch create mode 100644 0021-example-use-absolute-path-to-find-enclave.sign.so.patch create mode 100644 0022-add-example-of-using-sgxssl-lib.patch create mode 100644 0023-tls_enclave-is-not-compiled-by-default.patch create mode 100644 0024-Cmake-replace-minial-cmake-from-3.12-to-3.10.patch create mode 100644 0025-example-add-example-for-LRT-long-running-task.patch create mode 100644 0026-example-add-Dockerfile-to-build-lrt-example-image.patch create mode 100644 0027-Change-to-use-the-milestone-picture-with-English.patch create mode 100644 0028-example-use-the-sgx-device-plugin-from-intel.patch create mode 100644 0029-some-adaptations-for-trustzone.patch create mode 100644 0030-fix-sgx-two-step-mode-bug-add-dump-command.patch create mode 100644 0031-set-signtool_v3.py-path.patch create mode 100644 0032-del-size_to_aligned_size.patch create mode 100644 0033-modify-the-error-information-when-missing-c-and-m.patch create mode 100644 0034-normalize-the-log-printed-by-PrintInfo.patch create mode 100644 0035-itrustee-add-lrt-support-itrustee.patch create mode 100644 0036-enclave-use-the-can-pull-image-from-hub.oepkgs.net.patch create mode 100644 0037-add-description-about-file-parameter-path-for-sign_t.patch create mode 100644 0038-fix-use-after-free-in-cc_enclave_create.patch create mode 100644 0039-clean-memory-when-it-come-to-error_handle.patch diff --git a/0009-fix-cmake-error-of-missing-CMAKE_CXX_COMPILER.patch b/0009-fix-cmake-error-of-missing-CMAKE_CXX_COMPILER.patch new file mode 100644 index 0000000..78c9932 --- /dev/null +++ b/0009-fix-cmake-error-of-missing-CMAKE_CXX_COMPILER.patch @@ -0,0 +1,43 @@ +From ca6b3ab02bd3d1853a88d637b38daf45c737e15e Mon Sep 17 00:00:00 2001 +From: =?UTF-8?q?=E7=AB=A0=E6=9F=B3=E7=87=95?= +Date: Thu, 4 Mar 2021 11:16:05 +0800 +Subject: [PATCH 1/1] =?UTF-8?q?=E4=BF=AE=E6=94=B9cmake=E9=94=99=E8=AF=AF?= +MIME-Version: 1.0 +Content-Type: text/plain; charset=UTF-8 +Content-Transfer-Encoding: 8bit + +Signed-off-by: root +--- + src/enclave_src/CMakeLists.txt | 2 +- + tools/codegener/CMakeLists.txt | 2 +- + 2 files changed, 2 insertions(+), 2 deletions(-) + +diff --git a/src/enclave_src/CMakeLists.txt b/src/enclave_src/CMakeLists.txt +index cb09b5c..66a36ea 100644 +--- a/src/enclave_src/CMakeLists.txt ++++ b/src/enclave_src/CMakeLists.txt +@@ -8,7 +8,7 @@ + # PURPOSE. + # See the Mulan PSL v2 for more details. + +-project(secgear_tee) ++project(secgear_tee C) + + set(target_lib secgear_tee) + set(LIBRARY_INSTALL /lib64) +diff --git a/tools/codegener/CMakeLists.txt b/tools/codegener/CMakeLists.txt +index c5fd618..0f8b5af 100644 +--- a/tools/codegener/CMakeLists.txt ++++ b/tools/codegener/CMakeLists.txt +@@ -10,7 +10,7 @@ + + include(ExternalProject) + +-project(CodeGen) ++project(CodeGen C) + + find_program(DUNE dune) + +-- +2.27.0 + diff --git a/0010-fix-sgxssl-edl.patch b/0010-fix-sgxssl-edl.patch new file mode 100644 index 0000000..ef67833 --- /dev/null +++ b/0010-fix-sgxssl-edl.patch @@ -0,0 +1,23 @@ +From 171ab61244c87058ab7b4a9f5ea0fbb1d5a84bbc Mon Sep 17 00:00:00 2001 +From: liwei3013 +Date: Sat, 27 Feb 2021 11:32:50 +0800 +Subject: [PATCH 1/6] fix sgxssl edl + +Signed-off-by: liwei3013 +--- + inc/host_inc/sgx/secgear_tssl.edl | 2 +- + 1 file changed, 1 insertion(+), 1 deletion(-) + +diff --git a/inc/host_inc/sgx/secgear_tssl.edl b/inc/host_inc/sgx/secgear_tssl.edl +index 707c344..2ae7d85 100644 +--- a/inc/host_inc/sgx/secgear_tssl.edl ++++ b/inc/host_inc/sgx/secgear_tssl.edl +@@ -1,4 +1,4 @@ + // To do: develop key libraries of secGear version, to be compatible with SGX and GP. + enclave { +- from "sgx_tstdc.edl" import *; ++ from "sgx_tsgxssl.edl" import *; + }; +-- +2.27.0 + diff --git a/0011-update-docs-build_install.md.patch b/0011-update-docs-build_install.md.patch new file mode 100644 index 0000000..1853aec --- /dev/null +++ b/0011-update-docs-build_install.md.patch @@ -0,0 +1,25 @@ +From a960391b449cdc9dc081dbab28e9fbc0aa093cf0 Mon Sep 17 00:00:00 2001 +From: liwei3013 +Date: Mon, 8 Mar 2021 10:19:54 +0800 +Subject: [PATCH 2/6] update docs/build_install.md. + +--- + docs/build_install.md | 2 +- + 1 file changed, 1 insertion(+), 1 deletion(-) + +diff --git a/docs/build_install.md b/docs/build_install.md +index 9ba1adb..482e8c2 100644 +--- a/docs/build_install.md ++++ b/docs/build_install.md +@@ -3,7 +3,7 @@ Install secGear + openEuler x86 + + 1. Refer to https://01.org/intel-software-guard-extensions/downloads download and install the 2.11 +- sgx driver, sgx psw, sgx sdx. In the directory of sgx sdk, source environment(for use sgx-sign) ++ sgx driver, sgx psw, sgx sdk. In the directory of sgx sdk, source environment(for use sgx-sign) + + 2. Refer to https://github.com/ocaml/opam/releases download and install the opam-2.0.7-x86_64-linux. + Run "./opam-2.0.7-x86_64-linux init" +-- +2.27.0 + diff --git a/0012-modify-the-prompt-information.patch b/0012-modify-the-prompt-information.patch new file mode 100644 index 0000000..a1f34be --- /dev/null +++ b/0012-modify-the-prompt-information.patch @@ -0,0 +1,25 @@ +From 4fc7411abfeef1d80b1ff97ef674322e7391e55d Mon Sep 17 00:00:00 2001 +From: zgzxx +Date: Wed, 10 Mar 2021 09:37:54 +0800 +Subject: [PATCH 3/6] modify the prompt information + +--- + tools/codegener/intel/Util.ml | 2 +- + 1 file changed, 1 insertion(+), 1 deletion(-) + +diff --git a/tools/codegener/intel/Util.ml b/tools/codegener/intel/Util.ml +index 9629e54..f5f9afc 100644 +--- a/tools/codegener/intel/Util.ml ++++ b/tools/codegener/intel/Util.ml +@@ -62,7 +62,7 @@ let dedup_list lst = + let usage (progname: string) = + eprintf "usage: %s [options] ...\n" progname; + eprintf "\n[options]\n\ +---search-path Specify the search path of EDL files\n\ ++--search-path Specify the search path of the dependent files of the EDL files\n\ + --use-prefix Prefix untrusted proxy with Enclave name\n\ + --header-only Only generate header files\n\ + --untrusted Generate untrusted proxy and bridge\n\ +-- +2.27.0 + diff --git a/0013-parse-new-error-code-and-del-redundant-print.patch b/0013-parse-new-error-code-and-del-redundant-print.patch new file mode 100644 index 0000000..9489089 --- /dev/null +++ b/0013-parse-new-error-code-and-del-redundant-print.patch @@ -0,0 +1,62 @@ +From c11313e25c077743ec9fb88d4463a18370dcb881 Mon Sep 17 00:00:00 2001 +From: zgzxx +Date: Thu, 11 Mar 2021 10:46:05 +0800 +Subject: [PATCH 4/6] parse new error code and del redundant print + +--- + inc/host_inc/status.h | 2 +- + src/host_src/enclave_internal.c | 2 +- + src/host_src/sgx/sgx_enclave.c | 4 +++- + 3 files changed, 5 insertions(+), 3 deletions(-) + +diff --git a/inc/host_inc/status.h b/inc/host_inc/status.h +index 84c092a..1d18d2e 100644 +--- a/inc/host_inc/status.h ++++ b/inc/host_inc/status.h +@@ -56,7 +56,7 @@ typedef enum _enclave_result_t + CC_ERROR_INVALID_ISVSVN, /* The isv svn is greater than the enclave's isv svn */ + CC_ERROR_INVALID_KEYNAME, /* The key name is an unsupported value */ + CC_ERROR_AE_INVALID_EPIDBLOB, /* Indicates epid blob verification error */ +- CC_ERROR_SERVICE_INVALID_PRIVILEGE, /* Enclave has no privilege to get launch token */ ++ CC_ERROR_SERVICE_INVALID_PRIVILEGE, /* Enclave not authorized to run */ + CC_ERROR_EPID_MEMBER_REVOKED, /* The EPID group membership is revoked */ + CC_ERROR_UPDATE_NEEDED, /* SDK need to be update*/ + CC_ERROR_MC_NOT_FOUND, /* The Monotonic Counter doesn't exist or has been invalided */ +diff --git a/src/host_src/enclave_internal.c b/src/host_src/enclave_internal.c +index 9a172bd..962fc07 100644 +--- a/src/host_src/enclave_internal.c ++++ b/src/host_src/enclave_internal.c +@@ -64,7 +64,7 @@ static err2str g_secgearerror [] = + {CC_ERROR_INVALID_ISVSVN, "The isv svn is greater than the enclave's isv svn."}, + {CC_ERROR_INVALID_KEYNAME, "The key name is an unsupported value."}, + {CC_ERROR_AE_INVALID_EPIDBLOB, "Indicates epid blob verification error."}, +- {CC_ERROR_SERVICE_INVALID_PRIVILEGE, "Enclave has no privilege to get launch token."}, ++ {CC_ERROR_SERVICE_INVALID_PRIVILEGE, "Enclave not authorized to run."}, + {CC_ERROR_EPID_MEMBER_REVOKED, "The EPID group membership is revoked."}, + {CC_ERROR_UPDATE_NEEDED, "SDK need to be update."}, + {CC_ERROR_MC_NOT_FOUND, "The Monotonic Counter doesn't exist or has been invalided."}, +diff --git a/src/host_src/sgx/sgx_enclave.c b/src/host_src/sgx/sgx_enclave.c +index b37c748..a40c408 100644 +--- a/src/host_src/sgx/sgx_enclave.c ++++ b/src/host_src/sgx/sgx_enclave.c +@@ -59,6 +59,8 @@ cc_enclave_result_t conversion_res_status(uint32_t enclave_res, enclave_type_ver + return CC_ERROR_OUT_OF_TCS; + case SGX_ERROR_ENCLAVE_CRASHED: + return CC_ERROR_ENCLAVE_DEAD; ++ case SGX_ERROR_SERVICE_INVALID_PRIVILEGE: ++ return CC_ERROR_SERVICE_INVALID_PRIVILEGE; + default: + return CC_ERROR_UNEXPECTED; + } +@@ -131,7 +133,7 @@ cc_enclave_result_t _sgx_create(cc_enclave_t **enclave, const enclave_features_t + NULL, &(l_context->edi), NULL); + if (sgx_res != SGX_SUCCESS) { + res = conversion_res_status(sgx_res, (*enclave)->type); +- print_error_goto("Failed to create sgx enclave %s\n",cc_enclave_res2_str(res)); ++ print_error_goto("Failed to create sgx enclave\n"); + } + break; + case 1: +-- +2.27.0 + diff --git a/0014-fix-error-print.patch b/0014-fix-error-print.patch new file mode 100644 index 0000000..eadc8dd --- /dev/null +++ b/0014-fix-error-print.patch @@ -0,0 +1,25 @@ +From c9938ba0cf6b79b341efb18501827daea67c96ad Mon Sep 17 00:00:00 2001 +From: whzhe +Date: Thu, 11 Mar 2021 16:45:20 +0800 +Subject: [PATCH 5/6] fix error print + +--- + tools/codegener/intel/Util.ml | 2 +- + 1 file changed, 1 insertion(+), 1 deletion(-) + +diff --git a/tools/codegener/intel/Util.ml b/tools/codegener/intel/Util.ml +index f5f9afc..a77637e 100644 +--- a/tools/codegener/intel/Util.ml ++++ b/tools/codegener/intel/Util.ml +@@ -187,7 +187,7 @@ let get_file_path (fname: string) = + try + List.find Sys.file_exists fn_list + with +- Not_found -> failwithf "File not found within search paths: %s\n" fname ++ Not_found -> failwithf "File not found within search paths or search paths is permisson denied: %s\n" fname + + (* Get the short name of the given file name. + * ------------------------------------------ +-- +2.27.0 + diff --git a/0015-set-umask-in-sign_tool.sh.patch b/0015-set-umask-in-sign_tool.sh.patch new file mode 100644 index 0000000..37e6220 --- /dev/null +++ b/0015-set-umask-in-sign_tool.sh.patch @@ -0,0 +1,24 @@ +From c5b813e96262f2af0596d8c5e164aafcd64fb60c Mon Sep 17 00:00:00 2001 +From: yanlu +Date: Fri, 12 Mar 2021 11:42:11 +0800 +Subject: [PATCH 6/6] set umask in sign_tool.sh + +--- + tools/sign_tool/sign_tool.sh | 1 + + 1 file changed, 1 insertion(+) + +diff --git a/tools/sign_tool/sign_tool.sh b/tools/sign_tool/sign_tool.sh +index 9aaf663..8f2189c 100755 +--- a/tools/sign_tool/sign_tool.sh ++++ b/tools/sign_tool/sign_tool.sh +@@ -265,6 +265,7 @@ if [ -z $OUT_FILE ]; then + echo "Error: missing out file" + exit -1 + fi ++umask 0077 + check_results=`uname -m` + if [ "${ENCLAVE_TYPE}"x == "sgx"x ]; then + if [ "${check_results}"x != "x86_64"x ]; then +-- +2.27.0 + diff --git a/0016-1.fix-the-race-of-ecall-and-enclave-destroy.patch b/0016-1.fix-the-race-of-ecall-and-enclave-destroy.patch new file mode 100644 index 0000000..d6e4ab5 --- /dev/null +++ b/0016-1.fix-the-race-of-ecall-and-enclave-destroy.patch @@ -0,0 +1,133 @@ +From 1680c15af6226a8a205f37162e54dc85a3dfc2b0 Mon Sep 17 00:00:00 2001 +From: chenmaodong +Date: Wed, 17 Mar 2021 12:34:24 +0800 +Subject: 1.fix the race of ecall and enclave destroy 2.add a used flag for + context in case of double destroy or double create + +Signed-off-by: chenmaodong +--- + environment | 3 ++- + inc/host_inc/enclave.h | 4 +++- + src/host_src/CMakeLists.txt | 4 ++-- + src/host_src/enclave.c | 14 +++++++++++--- + src/host_src/sgx/sgx_enclave.c | 2 ++ + 5 files changed, 20 insertions(+), 7 deletions(-) + +diff --git a/environment b/environment +index a45ff9e..c438449 100644 +--- a/environment ++++ b/environment +@@ -1,2 +1,3 @@ +-export CC_SDK=$(pwd) ++file_dir=`readlink -f ${BASH_SOURCE[0]}` ++export CC_SDK=`dirname $file_dir` + export PATH=$PATH:$CC_SDK/bin/ +diff --git a/inc/host_inc/enclave.h b/inc/host_inc/enclave.h +index b063ce9..ca9e8da 100644 +--- a/inc/host_inc/enclave.h ++++ b/inc/host_inc/enclave.h +@@ -16,7 +16,7 @@ + #include + #include + #include +- ++#include + + #include "status.h" + +@@ -62,6 +62,8 @@ typedef struct _enclave { + enclave_type_version_t type; + char *path; + uint32_t flags; ++ pthread_rwlock_t rwlock; ++ bool used_flag; + void *private_data; + /*enclave engine context manage, only one pointer*/ + struct list_ops_desc *list_ops_node; +diff --git a/src/host_src/CMakeLists.txt b/src/host_src/CMakeLists.txt +index df4d3bf..25d245f 100644 +--- a/src/host_src/CMakeLists.txt ++++ b/src/host_src/CMakeLists.txt +@@ -25,8 +25,8 @@ endif() + add_library(secgear SHARED enclave.c enclave_internal.c ocall_log.c enclave_ocall.c) + add_library(secgearsim SHARED enclave.c enclave_internal.c ocall_log.c enclave_ocall.c) + +-target_link_libraries(secgear dl) +-target_link_libraries(secgearsim dl) ++target_link_libraries(secgear dl pthread) ++target_link_libraries(secgearsim dl pthread) + + set_target_properties(secgear PROPERTIES + SKIP_BUILD_RPATH TRUE) +diff --git a/src/host_src/enclave.c b/src/host_src/enclave.c +index dc8c5ed..204c808 100644 +--- a/src/host_src/enclave.c ++++ b/src/host_src/enclave.c +@@ -109,7 +109,7 @@ done: + static bool check_flag(cc_enclave_result_t *res, const char *path, uint32_t flags, const enclave_features_t *features, + const uint32_t features_count, cc_enclave_t **enclave) + { +- if (enclave == NULL || *enclave != NULL) { ++ if (enclave == NULL || (*enclave != NULL && (*enclave)->used_flag == true)) { + *res = CC_ERROR_INVALID_ENCLAVE_ID; + return false; + } +@@ -217,11 +217,14 @@ cc_enclave_result_t cc_enclave_create(const char *path, enclave_type_t type, uin + if (((GP_ENCLAVE_TYPE_0 <= type_version) && (type_version < GP_ENCLAVE_TYPE_MAX)) && (flags & SECGEAR_DEBUG_FLAG)) { + print_warning("This enclave scheme does not support enter enclave debugging\n"); + } +- ++ + /* initialize the context */ ++ ++ pthread_rwlock_init(&(l_context->rwlock), NULL); + l_context->path = l_path; + l_context->flags = flags; + l_context->type = type_version; ++ l_context->used_flag = true; + + /* if an enclave is created multiple times, first find it in the global list, + * maybe the information about this engine has been filled in the list +@@ -280,11 +283,13 @@ cc_enclave_result_t cc_enclave_destroy(cc_enclave_t *context) + p_tee_unregistered unregistered_funcc; + + /* check context and enclave engine context */ +- if (!context || !context->list_ops_node) { ++ if (!context || !context->list_ops_node || !context->list_ops_node->ops_desc || ++ !context->list_ops_node->ops_desc->ops || context->used_flag == false) { + print_error_term("Function context parameter error\n"); + return CC_ERROR_BAD_PARAMETERS; + } + ++ pthread_rwlock_wrlock(&(context->rwlock)); + if (context->list_ops_node->ops_desc->ops->cc_destroy_enclave != NULL) { + res = context->list_ops_node->ops_desc->ops->cc_destroy_enclave(context); + SECGEAR_CHECK_RES(res); +@@ -322,6 +327,9 @@ done: + free(context->path); + } + if (context) { ++ pthread_rwlock_unlock(&context->rwlock); ++ pthread_rwlock_destroy(&context->rwlock); ++ explicit_bzero(context, sizeof(cc_enclave_t)); + free(context); + } + return res; +diff --git a/src/host_src/sgx/sgx_enclave.c b/src/host_src/sgx/sgx_enclave.c +index a40c408..258c58a 100644 +--- a/src/host_src/sgx/sgx_enclave.c ++++ b/src/host_src/sgx/sgx_enclave.c +@@ -200,8 +200,10 @@ cc_enclave_result_t cc_enclave_sgx_call_function( + (void)output_buffer_size; + sgx_status_t status; + cc_enclave_result_t cc_status; ++ pthread_rwlock_rdlock(&(enclave->rwlock)); + status = sgx_ecall(((sgx_context_t *)(enclave->private_data))->edi, (int)function_id, ocall_table, ms); + cc_status = conversion_res_status(status, enclave->type); ++ pthread_rwlock_unlock(&(enclave->rwlock)); + return cc_status; + } + +-- +1.8.3.1 + diff --git a/0017-fix-wrong-spelling-and-null-pointer-dereference-issu.patch b/0017-fix-wrong-spelling-and-null-pointer-dereference-issu.patch new file mode 100644 index 0000000..5395c62 --- /dev/null +++ b/0017-fix-wrong-spelling-and-null-pointer-dereference-issu.patch @@ -0,0 +1,52 @@ +From 9d0ff75bf869574b5f96079cf5494fe11d20f160 Mon Sep 17 00:00:00 2001 +From: zgzxx +Date: Sat, 20 Mar 2021 17:27:36 +0800 +Subject: [PATCH] fix wrong spelling and null pointer dereference issue + + +diff --git a/tools/codegener/intel/CodeGen.ml b/tools/codegener/intel/CodeGen.ml +index dc43942..d9ccf7c 100644 +--- a/tools/codegener/intel/CodeGen.ml ++++ b/tools/codegener/intel/CodeGen.ml +@@ -872,7 +872,11 @@ let gen_func_uproxy (tf: Ast.trusted_func) (idx: int) (ec: enclave_content) = + let sgx_ecall_fn = get_sgx_fname SGX_ECALL tf.Ast.tf_is_switchless in + + (* Normal case - do ECALL with marshaling structure*) +- let ecall_with_ms = sprintf "result = enclave->list_ops_node->ops_desc->ops->cc_ecall_enclave( \n\ ++ let ecall_with_ms = sprintf "if(!enclave || !enclave->list_ops_node || !enclave->list_ops_node->ops_desc ||\n\ ++ \t\t!enclave->list_ops_node->ops_desc->ops || \n\ ++ \t\t!enclave->list_ops_node->ops_desc->ops->cc_ecall_enclave)\n\ ++ \t\treturn CC_ERROR_BAD_PARAMETERS; ++ result = enclave->list_ops_node->ops_desc->ops->cc_ecall_enclave( \n\ + \t\tenclave,\n\ + \t\t%d,\n\ + \t\tNULL,\n\ +@@ -885,7 +889,11 @@ let gen_func_uproxy (tf: Ast.trusted_func) (idx: int) (ec: enclave_content) = + (* Rare case - the trusted function doesn't have parameter nor return value. + * In this situation, no marshaling structure is required - passing in NULL. + *) +- let ecall_null = sprintf "result = enclave->list_ops_node->ops_desc->ops->cc_ecall_enclave( \n\ ++ let ecall_null = sprintf "if(!enclave || !enclave->list_ops_node || !enclave->list_ops_node->ops_desc ||\n\ ++ \t\t!enclave->list_ops_node->ops_desc->ops || \n\ ++ \t\t!enclave->list_ops_node->ops_desc->ops->cc_ecall_enclave)\n\ ++ \t\treturn CC_ERROR_BAD_PARAMETERS; ++ result = enclave->list_ops_node->ops_desc->ops->cc_ecall_enclave( \n\ + \t\tenclave,\n\ + \t\t%d,\n\ + \t\tNULL,\n\ +diff --git a/tools/codegener/intel/Util.ml b/tools/codegener/intel/Util.ml +index a77637e..9dd22bd 100644 +--- a/tools/codegener/intel/Util.ml ++++ b/tools/codegener/intel/Util.ml +@@ -187,7 +187,7 @@ let get_file_path (fname: string) = + try + List.find Sys.file_exists fn_list + with +- Not_found -> failwithf "File not found within search paths or search paths is permisson denied: %s\n" fname ++ Not_found -> failwithf "File not found within search paths or search paths is permission denied: %s\n" fname + + (* Get the short name of the given file name. + * ------------------------------------------ +-- +2.27.0 + diff --git a/0018-update-sign_tool.doc.patch b/0018-update-sign_tool.doc.patch new file mode 100644 index 0000000..d23f019 --- /dev/null +++ b/0018-update-sign_tool.doc.patch @@ -0,0 +1,50 @@ +From 8a586fc5fa249ced59ae495357c64baa7c6201f0 Mon Sep 17 00:00:00 2001 +From: yanlu +Date: Thu, 25 Mar 2021 15:27:32 +0800 +Subject: [PATCH 01/14] update sign_tool.doc + +--- + docs/sign_tool.md | 8 ++++---- + 1 file changed, 4 insertions(+), 4 deletions(-) + +diff --git a/docs/sign_tool.md b/docs/sign_tool.md +index 3a49d5b..26805bd 100644 +--- a/docs/sign_tool.md ++++ b/docs/sign_tool.md +@@ -4,7 +4,7 @@ The sign_tool.sh helps to sign the enclave. + + ## The sign_tool.sh + +-The sign_tool.sh uses the 'sgx_sign' tool in SGX SDK for signing the sgx enclave and the 'sign_too.py' for signing the trustzone enclave. ++The sign_tool.sh uses the 'sgx_sign' tool in SGX SDK for signing the sgx enclave and the 'sign_tool.py' for signing the trustzone enclave. + + The tool supports the following two modes: + +@@ -13,21 +13,21 @@ The tool supports the following two modes: + + For example: + +- `$ ./signtool.sh –d sign –x trustzone –i test.enclave -m manifest.txt –e device_pubkey.pem –o signed.enclave ` ++ `$ ./sign_tool.sh –d sign –x trustzone –i test.enclave -m manifest.txt –e device_pubkey.pem –o signed.enclave ` + + + - two-step method, it is used when the signature needs to be obtained from the signing organization or the private key is stored on another secure platform. + + For example: + (1) generate the digest value. +- `$ ./signtool.sh –d digest –x trustzone –i input -m manifest.txt –e device_pubkey.pem –o digest.data ` ++ `$ ./sign_tool.sh –d digest –x trustzone –i input -m manifest.txt –e device_pubkey.pem –o digest.data ` + + For trustzone, temporary files KeyInfo.enc, rawData.enc, and rawDataHash.bin are generated in the current directory. And for sgx, a temporary file signdata is generated in the current directory. The temporary file is required when generating the signed enclave in step 3 and is deleted after the signed enclave is generated. + + (2) send the digest.data to the signing organization or platform and get the signature. + + (3) use the signature to generate the signed enclave. +- `$ ./signtool.sh –d sign –x trustzone –i input -m manifest.txt –p pub.pem –e device_pubkey.pem –s signature –o signed.enclave ` ++ `$ ./sign_tool.sh –d sign –x trustzone –i input -m manifest.txt –p pub.pem –e device_pubkey.pem –s signature –o signed.enclave ` + + ## sign_tool.sh parameter + +-- +2.27.0 + diff --git a/0019-normalized-codegen-from-arm-and-x86.patch b/0019-normalized-codegen-from-arm-and-x86.patch new file mode 100644 index 0000000..923097c --- /dev/null +++ b/0019-normalized-codegen-from-arm-and-x86.patch @@ -0,0 +1,157 @@ +From 3b7651a53017e41726b80b24fc1757c06cf73ba7 Mon Sep 17 00:00:00 2001 +From: whzhe +Date: Mon, 12 Apr 2021 10:33:17 +0800 +Subject: [PATCH 02/14] normalized codegen from arm and x86 + +--- + README.en.md | 3 +-- + README.md | 5 ++--- + docs/codegener.md | 14 +++++--------- + examples/helloworld/CMakeLists.txt | 3 +-- + examples/seal_data/CMakeLists.txt | 3 +-- + tools/codegener/CMakeLists.txt | 8 +------- + 6 files changed, 11 insertions(+), 25 deletions(-) + +diff --git a/README.en.md b/README.en.md +index fa47d03..909358f 100644 +--- a/README.en.md ++++ b/README.en.md +@@ -50,16 +50,15 @@ Then save as test.edl + set(EDL_FILE test.edl) + set(LOCAL_ROOT_PATH "$ENV{CC_SDK}") + set(SECGEAR_INSTALL_PATH /lib64/) ++ set(CODEGEN codegen) + if(CC_GP) + set(CODETYPE trustzone) +- set(CODEGEN codegen_arm64) + execute_process(COMMAND uuidgen -r OUTPUT_VARIABLE UUID) + string(REPLACE "\n" "" UUID ${UUID}) + add_definitions(-DPATH="/data/${UUID}.sec") + endif() + if(CC_SGX) + set(CODETYPE sgx) +- set(CODEGEN codegen_x86_64) + add_definitions(-DPATH="${CMAKE_CURRENT_BINARY_DIR}/enclave/enclave.signed.so") + endif() + add_subdirectory(${CURRENT_ROOT_PATH}/enclave) +diff --git a/README.md b/README.md +index 54c32e3..fafe3f9 100644 +--- a/README.md ++++ b/README.md +@@ -42,16 +42,15 @@ SecGear则是面向计算产业的机密计算安全应用开发套件。旨在 + set(EDL_FILE test.edl) + set(LOCAL_ROOT_PATH "$ENV{CC_SDK}") + set(SECGEAR_INSTALL_PATH /lib64/) ++ set(CODEGEN codegen) + if(CC_GP) + set(CODETYPE trustzone) +- set(CODEGEN codegen_arm64) + execute_process(COMMAND uuidgen -r OUTPUT_VARIABLE UUID) + string(REPLACE "\n" "" UUID ${UUID}) + add_definitions(-DPATH="/data/${UUID}.sec") + endif() + if(CC_SGX) + set(CODETYPE sgx) +- set(CODEGEN codegen_x86_64) + add_definitions(-DPATH="${CMAKE_CURRENT_BINARY_DIR}/enclave/enclave.signed.so") + endif() + add_subdirectory(${CURRENT_ROOT_PATH}/enclave) +diff --git a/docs/codegener.md b/docs/codegener.md +index cc20013..85fc6a0 100644 +--- a/docs/codegener.md ++++ b/docs/codegener.md +@@ -1,19 +1,15 @@ +-# Getting started with the codegen_x86_64/codegen_arm64 ++# Getting started with the codegen + +-The codegen_x86_64/codegen_arm64 helps to define these special functions through the `edl` files and assist user to using enclave. ++The codegen helps to define these special functions through the `edl` files and assist user to using enclave. + +-## The codegen_x86_64/codegen_arm64 ++## The codegen + +-The codegen_x86_64/codegen_arm64 is based on the 'edger8r' tool in SGX SDK. ++The codegen is based on the 'edger8r' tool in SGX SDK. + - For example + ``` + $ codegen_arm64 --trustzone test.edl + ``` +-OR +-``` +-$ codegen_x86_64 --sgx test.edl +-``` +-**Note**: using the `codegen_x86_64/codegen_arm64 --help` to get more details. ++**Note**: using the `codegen --help` to get more details. + + ## EDL format + - For SGX(x86) +diff --git a/examples/helloworld/CMakeLists.txt b/examples/helloworld/CMakeLists.txt +index a758f1c..5da2a6b 100644 +--- a/examples/helloworld/CMakeLists.txt ++++ b/examples/helloworld/CMakeLists.txt +@@ -16,10 +16,10 @@ set(CURRENT_ROOT_PATH ${CMAKE_CURRENT_SOURCE_DIR}) + + #set edl name + set(EDL_FILE helloworld.edl) ++set(CODEGEN codegen) + + if(CC_GP) + set(CODETYPE trustzone) +- set(CODEGEN codegen_arm64) + execute_process(COMMAND uuidgen -r OUTPUT_VARIABLE UUID) + string(REPLACE "\n" "" UUID ${UUID}) + add_definitions(-DPATH="/data/${UUID}.sec") +@@ -27,7 +27,6 @@ endif() + + if(CC_SGX) + set(CODETYPE sgx) +- set(CODEGEN codegen_x86_64) + add_definitions(-DPATH="${CMAKE_CURRENT_BINARY_DIR}/enclave/enclave.signed.so") + endif() + +diff --git a/examples/seal_data/CMakeLists.txt b/examples/seal_data/CMakeLists.txt +index 20e2fd5..503fe0d 100644 +--- a/examples/seal_data/CMakeLists.txt ++++ b/examples/seal_data/CMakeLists.txt +@@ -17,10 +17,10 @@ set(CMAKE_C_STANDARD 99) + set(CURRENT_ROOT_PATH ${CMAKE_CURRENT_SOURCE_DIR}) + + set(EDL_FILE seal_data.edl) ++set(CODEGEN codegen) + + if(CC_GP) + set(CODETYPE trustzone) +- set(CODEGEN codegen_arm64) + execute_process(COMMAND uuidgen -r + OUTPUT_VARIABLE UUID) + string(REPLACE "\n" "" UUID ${UUID}) +@@ -29,7 +29,6 @@ endif() + + if(CC_SGX) + set(CODETYPE sgx) +- set(CODEGEN codegen_x86_64) + add_definitions(-DPATH="${CMAKE_CURRENT_BINARY_DIR}/enclave/seal_data.signed.so") + endif() + +diff --git a/tools/codegener/CMakeLists.txt b/tools/codegener/CMakeLists.txt +index 0f8b5af..e52d894 100644 +--- a/tools/codegener/CMakeLists.txt ++++ b/tools/codegener/CMakeLists.txt +@@ -18,13 +18,7 @@ if(NOT DUNE) + message(FATAL_ERROR "Please check your dune installation") + endif() + +-if(CC_SGX) +- set(code codegen_x86_64) +-endif() +- +-if(CC_GP) +- set(code codegen_arm64) +-endif() ++set(code codegen) + + ExternalProject_Add(codegen + SOURCE_DIR ${LOCAL_ROOT_PATH}/tools/codegener +-- +2.27.0 + diff --git a/0020-rm-e-parameter-normalize-c-parameter.patch b/0020-rm-e-parameter-normalize-c-parameter.patch new file mode 100644 index 0000000..a856e33 --- /dev/null +++ b/0020-rm-e-parameter-normalize-c-parameter.patch @@ -0,0 +1,329 @@ +From f7995d756490c966659976153630403ba9941c18 Mon Sep 17 00:00:00 2001 +From: yanlu +Date: Mon, 12 Apr 2021 11:17:16 +0800 +Subject: [PATCH 03/14] rm -e parameter, normalize -c parameter + +--- + README.en.md | 12 ++---- + README.md | 10 ++--- + docs/sign_tool.md | 12 +++--- + examples/helloworld/enclave/CMakeLists.txt | 6 +-- + examples/seal_data/enclave/CMakeLists.txt | 7 +--- + .../enclave/rsa_public_key_cloud.pem | 11 ------ + .../sign_tool}/rsa_public_key_cloud.pem | 0 + tools/sign_tool/sign_tool.sh | 39 +++++++------------ + 8 files changed, 29 insertions(+), 68 deletions(-) + delete mode 100644 examples/seal_data/enclave/rsa_public_key_cloud.pem + rename {examples/helloworld/enclave => tools/sign_tool}/rsa_public_key_cloud.pem (100%) + +diff --git a/README.en.md b/README.en.md +index fa47d03..0acc4f8 100644 +--- a/README.en.md ++++ b/README.en.md +@@ -254,8 +254,6 @@ Set sign tool and the security side log printing level + if(CC_GP) + #set signed output + set(OUTPUT ${UUID}.sec) +- #set itrustee device key +- set(DEVICEPEM ${CMAKE_CURRENT_SOURCE_DIR}/rsa_public_key_cloud.pem) + + set(WHITE_LIST_0 /vendor/bin/helloworld) + set(WHITE_LIST_1 /vendor/bin/secgear_test) +@@ -270,8 +268,7 @@ Set sign tool and the security side log printing level + + WHITE_LIS_X sets the whitelist of itrustee, only the host binary of these paths can call this secure image, + and up to 8 list paths can be configured. WHITE_LIST_OWNER set user, this user will be applied to all whitelist paths. +-DEVICEPEM public key is used by itrustee and is used to encrypt the enclave image of the security side with the +-dynamically generated aes key. Finally, set the name of the security side image after the final signature, and ++Finally, set the name of the security side image after the final signature, and + generate auxiliary code. + + if(CC_SGX) +@@ -339,8 +336,8 @@ so -nostdinc -nodefaultlibs -nostdlib -nodefaultlibs compile link options was in + + add_custom_command(TARGET ${PREFIX} + POST_BUILD +- COMMAND bash ${SIGN_TOOL} -d sign -x trustzone -i lib${PREFIX}.so -m ${CMAKE_CURRENT_SOURCE_DIR}/manifest.txt +- -e ${DEVICEPEM} -o ${CMAKE_CURRENT_BINARY_DIR}/${OUTPUT}) ++ COMMAND bash ${SIGN_TOOL} -d sign -x trustzone -i lib${PREFIX}.so -c ${CMAKE_CURRENT_SOURCE_DIR}/manifest.txt ++ -o ${CMAKE_CURRENT_BINARY_DIR}/${OUTPUT}) + + install(FILES ${CMAKE_CURRENT_BINARY_DIR}/${OUTPUT} + DESTINATION /data +@@ -425,9 +422,6 @@ configuration file. For details, please refer to the official development docum + Write itrustee related configuration files + The gpd.ta.appID in the manifest.txt.in file is the uuid configuration item, which is dynamically generated, + and the other configuration items can refer to the itrustee development document. +- +-Copy the rsa_public_key_cloud.pem device public key from other examples in the project to the enclave directory. +-The device public key here is used to encrypt the enclave image with the temporarily generated aes key. + + ### 5 build and install test + +diff --git a/README.md b/README.md +index 54c32e3..77bebd6 100644 +--- a/README.md ++++ b/README.md +@@ -236,8 +236,6 @@ test_t.h:该头文件为自动生成代码工具codegen通过edl文件生成 + if(CC_GP) + #set signed output + set(OUTPUT ${UUID}.sec) +- #set itrustee device key +- set(DEVICEPEM ${CMAKE_CURRENT_SOURCE_DIR}/rsa_public_key_cloud.pem) + + set(WHITE_LIST_0 /vendor/bin/helloworld) + set(WHITE_LIST_1 /vendor/bin/secgear_test) +@@ -252,7 +250,6 @@ test_t.h:该头文件为自动生成代码工具codegen通过edl文件生成 + + WHITE_LIST_x:为设置iTrustee的二进制白名单,只有这里定义的白名单,在非安全侧的二进制才可以调用安全侧的动态库。上限为8个。 + WHITE_LIST_OWNER:为设置运行二进制的用户,只有该用户才可以调用安全侧动态库。 +-DEVICEPEM:该公钥用来动态生成aes秘钥 + AUTO_FILES:由edl文件生成的安全侧二进制文件 + + if(CC_SGX) +@@ -319,8 +316,8 @@ AUTO_FILES:由edl文件生成的安全侧二进制文件 + + add_custom_command(TARGET ${PREFIX} + POST_BUILD +- COMMAND bash ${SIGN_TOOL} -d sign -x trustzone -i lib${PREFIX}.so -m ${CMAKE_CURRENT_SOURCE_DIR}/manifest.txt +- -e ${DEVICEPEM} -o ${CMAKE_CURRENT_BINARY_DIR}/${OUTPUT}) ++ COMMAND bash ${SIGN_TOOL} -d sign -x trustzone -i lib${PREFIX}.so -c ${CMAKE_CURRENT_SOURCE_DIR}/manifest.txt ++ -o ${CMAKE_CURRENT_BINARY_DIR}/${OUTPUT}) + + install(FILES ${CMAKE_CURRENT_BINARY_DIR}/${OUTPUT} + DESTINATION /data +@@ -391,7 +388,6 @@ itrustee需要链接secgear_tee动态库,提供seal接口等。 + 编写itrustee enclave相关配置文件 + mainfest.txt.in:其中gpd.ta.appID 为动态生成uuid。其他配置参见itrustee开发文档。 + +-rsa_public_key_cloud.pem文件请将其他examples的中的拷贝过来,这里的设备公钥用于使用临时生成的aes密钥用于对enclave动态库进行加密。 + + #### 5 构建 安装 + +diff --git a/docs/sign_tool.md b/docs/sign_tool.md +index 26805bd..ccaa2e6 100644 +--- a/docs/sign_tool.md ++++ b/docs/sign_tool.md +@@ -13,36 +13,34 @@ The tool supports the following two modes: + + For example: + +- `$ ./sign_tool.sh –d sign –x trustzone –i test.enclave -m manifest.txt –e device_pubkey.pem –o signed.enclave ` ++ `$ ./sign_tool.sh –d sign –x trustzone –i test.enclave -c manifest.txt –o signed.enclave ` + + + - two-step method, it is used when the signature needs to be obtained from the signing organization or the private key is stored on another secure platform. + + For example: + (1) generate the digest value. +- `$ ./sign_tool.sh –d digest –x trustzone –i input -m manifest.txt –e device_pubkey.pem –o digest.data ` ++ `$ ./sign_tool.sh –d digest –x trustzone –i input -c manifest.txt –o digest.data ` + + For trustzone, temporary files KeyInfo.enc, rawData.enc, and rawDataHash.bin are generated in the current directory. And for sgx, a temporary file signdata is generated in the current directory. The temporary file is required when generating the signed enclave in step 3 and is deleted after the signed enclave is generated. + + (2) send the digest.data to the signing organization or platform and get the signature. + + (3) use the signature to generate the signed enclave. +- `$ ./sign_tool.sh –d sign –x trustzone –i input -m manifest.txt –p pub.pem –e device_pubkey.pem –s signature –o signed.enclave ` ++ `$ ./sign_tool.sh –d sign –x trustzone –i input -c manifest.txt –p pub.pem –s signature –o signed.enclave ` + + ## sign_tool.sh parameter + + ``` + -a API_LEVEL, indicates trustzone GP API version, defalut is 1. +- -c config file. ++ -c basic config file. + -d sign tool command, sign/digest. + The sign command is used to generate a signed enclave. + The digest command is used to generate a digest value. +- -e the device's public key certificate, used to protect the AES key of the encrypted rawdata, +- required by trustzone. + -f OTRP_FLAG, indicates whether the OTRP standard protocol is supported, default is 0. + -i enclave to be signed. + -k private key required for single-step method, required when trustzone TA_TYPE is 2 or sgx. +- -m manifest file, required by trustzone. ++ -m additional config for trustzone when TA_TYPE is 2. + -o output parameters, the sign command outputs sigend enclave, the digest command outputs digest value. + -p signing server public key certificate, required for two-step method. + -s the signed digest value required for two-step method, this parameter is empty to indicate single-step method. +diff --git a/examples/helloworld/enclave/CMakeLists.txt b/examples/helloworld/enclave/CMakeLists.txt +index c1638f8..0aefdae 100644 +--- a/examples/helloworld/enclave/CMakeLists.txt ++++ b/examples/helloworld/enclave/CMakeLists.txt +@@ -27,8 +27,6 @@ add_definitions(-DPRINT_LEVEL=${PRINT_LEVEL}) + if(CC_GP) + #set signed output + set(OUTPUT ${UUID}.sec) +- #set itrustee device key +- set(DEVICEPEM ${CMAKE_CURRENT_SOURCE_DIR}/rsa_public_key_cloud.pem) + #set whilelist. default: /vendor/bin/teec_hello + set(WHITE_LIST_0 /vendor/bin/helloworld) + set(WHITE_LIST_OWNER root) +@@ -101,8 +99,8 @@ if(CC_GP) + + add_custom_command(TARGET ${PREFIX} + POST_BUILD +- COMMAND bash ${SIGN_TOOL} -d sign -x trustzone -i ${CMAKE_LIBRARY_OUTPUT_DIRECTORY}/lib${PREFIX}.so -m ${CMAKE_CURRENT_SOURCE_DIR}/manifest.txt +- -e ${DEVICEPEM} -o ${CMAKE_LIBRARY_OUTPUT_DIRECTORY}/${OUTPUT}) ++ COMMAND bash ${SIGN_TOOL} -d sign -x trustzone -i ${CMAKE_LIBRARY_OUTPUT_DIRECTORY}/lib${PREFIX}.so -c ${CMAKE_CURRENT_SOURCE_DIR}/manifest.txt ++ -o ${CMAKE_LIBRARY_OUTPUT_DIRECTORY}/${OUTPUT}) + + install(FILES ${CMAKE_LIBRARY_OUTPUT_DIRECTORY}/${OUTPUT} + DESTINATION /data +diff --git a/examples/seal_data/enclave/CMakeLists.txt b/examples/seal_data/enclave/CMakeLists.txt +index 20851bd..0ddcbd5 100644 +--- a/examples/seal_data/enclave/CMakeLists.txt ++++ b/examples/seal_data/enclave/CMakeLists.txt +@@ -24,9 +24,6 @@ add_definitions(-DPRINT_LEVEL=${PRINT_LEVEL}) + if(CC_GP) + #set signed output + set(OUTPUT ${UUID}.sec) +- #set itrustee device key +- set(DEVICEPEM ${CMAKE_CURRENT_SOURCE_DIR}/rsa_public_key_cloud.pem) +- + set(AUTO_FILES ${CMAKE_CURRENT_BINARY_DIR}/${PREFIX}_t.h ${CMAKE_CURRENT_BINARY_DIR}/${PREFIX}_t.c ${CMAKE_CURRENT_BINARY_DIR}/${PREFIX}_args.h) + #set whilelist. default: /vendor/bin/teec_hello + set(WHITE_LIST_0 /vendor/bin/seal_data) +@@ -97,8 +94,8 @@ if(CC_GP) + + add_custom_command(TARGET ${PREFIX} + POST_BUILD +- COMMAND bash ${SIGN_TOOL} -d sign -x trustzone -a 2 -i ${CMAKE_LIBRARY_OUTPUT_DIRECTORY}/lib${PREFIX}.so -m ${CMAKE_CURRENT_SOURCE_DIR}/manifest.txt +- -e ${DEVICEPEM} -o ${CMAKE_LIBRARY_OUTPUT_DIRECTORY}/${OUTPUT}) ++ COMMAND bash ${SIGN_TOOL} -d sign -x trustzone -a 2 -i ${CMAKE_LIBRARY_OUTPUT_DIRECTORY}/lib${PREFIX}.so -c ${CMAKE_CURRENT_SOURCE_DIR}/manifest.txt ++ -o ${CMAKE_LIBRARY_OUTPUT_DIRECTORY}/${OUTPUT}) + + install(FILES ${CMAKE_LIBRARY_OUTPUT_DIRECTORY}/${OUTPUT} + DESTINATION /data +diff --git a/examples/seal_data/enclave/rsa_public_key_cloud.pem b/examples/seal_data/enclave/rsa_public_key_cloud.pem +deleted file mode 100644 +index a321f63..0000000 +--- a/examples/seal_data/enclave/rsa_public_key_cloud.pem ++++ /dev/null +@@ -1,11 +0,0 @@ +------BEGIN PUBLIC KEY----- +-MIIBojANBgkqhkiG9w0BAQEFAAOCAY8AMIIBigKCAYEAzAPwbnbgBg7JgXERA9Bx +-p7GLI1S3e1zL83RMd2+GXb6kO4yMKUL3NUCE2HhA2BtQYmLyGovx59UUcKnU58is +-Xux++kH+A2shmOPjYvEFuX0Kt8tc19b8M9b/iHsY8ZmKykqia2a5U+IrECRFJo5p +-DWUnl7jrHVtq78BSR1c7iXG1frrEC0AYCuqKJo/fxfmOKL0Y9mENCB3nAwjn9unD +-BsO/OhkqvvB3nkeuMfNKPh4wCqtQPve13eTojbuxjX/3ePijplTI5X2Gr+n6Ximn +-fYRlytQmMgMl/db0ARSKNApq9bmwzVNrnGWWZWJksdRvf6iL7t17Gs4L9AApOuC9 +-WkzxPvwp5ZUqjsGd4oJGWeC6ZE6BTw2vxE+xMFI9uAKHxq9pBKkcGMa0g4fANNNV +-+W+8JZGanxEXKB3y/M7BCyQAPCWOHC/RNjmRA1gczLYCPzC4pWu935UZdF1RR6zY +-CD3t+FoOGGET/g4CwWgyhb5qkp65Hs6ayYt/DUAqo+yBAgMBAAE= +------END PUBLIC KEY----- +diff --git a/examples/helloworld/enclave/rsa_public_key_cloud.pem b/tools/sign_tool/rsa_public_key_cloud.pem +similarity index 100% +rename from examples/helloworld/enclave/rsa_public_key_cloud.pem +rename to tools/sign_tool/rsa_public_key_cloud.pem +diff --git a/tools/sign_tool/sign_tool.sh b/tools/sign_tool/sign_tool.sh +index 8f2189c..212db5d 100755 +--- a/tools/sign_tool/sign_tool.sh ++++ b/tools/sign_tool/sign_tool.sh +@@ -21,16 +21,14 @@ print_help(){ + echo "sign tool usage: ./sign_tool.sh [options] ..." + echo "[options]" + echo "-a API_LEVEL, indicates trustzone GP API version, defalut is 1." +- echo "-c config file." ++ echo "-c basic config file." + echo "-d sign tool command, sign/digest." + echo " The sign command is used to generate a signed enclave." + echo " The digest command is used to generate a digest value." +- echo "-e the device's public key certificate, used to protect the AES key of the encrypted rawdata," +- echo " required by trustzone." + echo "-f OTRP_FLAG, indicates whether the OTRP standard protocol is supported, default is 0." + echo "-i enclave to be signed." + echo "-k private key required for single-step method, required when trustzone TA_TYPE is 2 or sgx." +- echo "-m manifest file, required by trustzone." ++ echo "-m additional config for trustzone when TA_TYPE is 2." + echo "-o output parameters, the sign command outputs sigend enclave, the digest command outputs" + echo " digest value." + echo "-p signing server public key certificate, required for two-step method." +@@ -42,7 +40,7 @@ print_help(){ + + } + +-while getopts "d:i:x:m:a:f:t:c:e:k:p:s:o:h" opt ++while getopts "d:i:x:m:a:f:t:c:k:p:s:o:h" opt + do + case $opt in + d) +@@ -73,7 +71,7 @@ do + echo "Error: parameter for -m is missing or incorrect" + exit -1 + fi +- MANIFIST=$OPTARG ++ A_CONFIG_FILE=$OPTARG + ;; + a) + if [[ $OPTARG =~ ^[1-3]$ ]]; then +@@ -118,13 +116,6 @@ do + fi + CONFIG_FILE=$OPTARG + ;; +- e) +- if [[ $OPTARG == -* ]]; then +- echo "Error: parameter for -e is missing or incorrect" +- exit -1 +- fi +- DEVICE_PUBKEY=$OPTARG +- ;; + k) + if [[ $OPTARG == -* ]]; then + echo "Error: parameter for -k is missing or incorrect" +@@ -169,23 +160,21 @@ fi + + itrustee_start_sign(){ + # check_native_sign +- if [ -z $MANIFIST ]; then +- echo "Error: missing manifest file for signing iTrustee enclave" +- exit -1 +- fi +- if [ -z $DEVICE_PUBKEY ]; then +- echo "Error: missing device pubkey for signing iTrustee enclave" ++ MANIFEST=$CONFIG_FILE ++ if [ -z $MANIFEST ]; then ++ echo "Error: missing config file for signing iTrustee enclave" + exit -1 + fi + + if [ ${TA_TYPE} == 2 ]; then +- if [ -z $CONFIG_FILE]; then +- echo "Error: TA TYPE = 2, missing config file for signing iTrustee enclave" ++ if [ -z $A_CONFIG_FILE]; then ++ echo "Error: TA TYPE = 2, missing additional config file for signing iTrustee enclave" + exit -1 + fi + else +- CONFIG_FILE="NULL" ++ A_CONFIG_FILE="NULL" + fi ++ DEVICE_PUBKEY=${localpath}/rsa_public_key_cloud.pem + + if [ "${CMD}"x == "sign"x ]; then + if [ -z $SIGNATURE ]; then +@@ -194,18 +183,18 @@ itrustee_start_sign(){ + echo "missing the signature private key" + exit -1 + fi +- python ${localpath}/sign_tool.py "sign" "${DEBUG}" "${IN_ENCLAVE}" "${OUT_FILE}" "${MANIFIST}" "${OTRP_FLAG}" "${TA_TYPE}" "${API_LEVEL}" "${DEVICE_PUBKEY}" "${CONFIG_FILE}" "${SIG_KEY}" ++ python ${localpath}/sign_tool.py "sign" "${DEBUG}" "${IN_ENCLAVE}" "${OUT_FILE}" "${MANIFEST}" "${OTRP_FLAG}" "${TA_TYPE}" "${API_LEVEL}" "${DEVICE_PUBKEY}" "${A_CONFIG_FILE}" "${SIG_KEY}" + else + DEBUG=0 + if [ -z $SERVER_PUBKEY ]; then + echo "Error: missing server public key for verifying signature" + exit -1 + fi +- python ${localpath}/sign_tool.py "sign" "${DEBUG}" "${IN_ENCLAVE}" "${OUT_FILE}" "${MANIFIST}" "${OTRP_FLAG}" "${TA_TYPE}" "${API_LEVEL}" "${DEVICE_PUBKEY}" "${CONFIG_FILE}" "${SIGNATURE}" "${SERVER_PUBKEY}" ++ python ${localpath}/sign_tool.py "sign" "${DEBUG}" "${IN_ENCLAVE}" "${OUT_FILE}" "${MANIFEST}" "${OTRP_FLAG}" "${TA_TYPE}" "${API_LEVEL}" "${DEVICE_PUBKEY}" "${A_CONFIG_FILE}" "${SIGNATURE}" "${SERVER_PUBKEY}" + fi + elif [ "${CMD}"x == "digest"x ]; then + DEBUG=0 +- python ${localpath}/sign_tool.py "digest" "${DEBUG}" "${IN_ENCLAVE}" "${OUT_FILE}" "${MANIFIST}" "${OTRP_FLAG}" "${TA_TYPE}" "${API_LEVEL}" "${DEVICE_PUBKEY}" "${CONFIG_FILE}" ++ python ${localpath}/sign_tool.py "digest" "${DEBUG}" "${IN_ENCLAVE}" "${OUT_FILE}" "${MANIFEST}" "${OTRP_FLAG}" "${TA_TYPE}" "${API_LEVEL}" "${DEVICE_PUBKEY}" "${A_CONFIG_FILE}" + else + echo "Error: illegal command" + fi +-- +2.27.0 + diff --git a/0021-example-use-absolute-path-to-find-enclave.sign.so.patch b/0021-example-use-absolute-path-to-find-enclave.sign.so.patch new file mode 100644 index 0000000..6ed1a91 --- /dev/null +++ b/0021-example-use-absolute-path-to-find-enclave.sign.so.patch @@ -0,0 +1,49 @@ +From 19d48667d6220aaa150f052e66a1847e3ba8f8d4 Mon Sep 17 00:00:00 2001 +From: Li Feng +Date: Tue, 13 Apr 2021 06:40:43 +0000 +Subject: [PATCH 04/14] example: use absolute path to find enclave.sign.so + +Signed-off-by: Li Feng +--- + examples/helloworld/host/main.c | 18 +++++++++++++++++- + 1 file changed, 17 insertions(+), 1 deletion(-) + +diff --git a/examples/helloworld/host/main.c b/examples/helloworld/host/main.c +index e4c4ec4..51993ce 100644 +--- a/examples/helloworld/host/main.c ++++ b/examples/helloworld/host/main.c +@@ -11,6 +11,8 @@ + */ + + #include ++#include ++#include + #include "enclave.h" + #include "helloworld_u.h" + +@@ -26,7 +28,21 @@ int main() + + printf("Create secgear enclave\n"); + +- res = cc_enclave_create(path, AUTO_ENCLAVE_TYPE, 0, SECGEAR_DEBUG_FLAG, NULL, 0, &context); ++ char real_p[PATH_MAX]; ++ /* check file exists, if not exist then use absolute path */ ++ if (realpath(path, real_p) == NULL) { ++ if (getcwd(real_p, sizeof(real_p)) == NULL) { ++ printf("Cannot find enclave.sign.so"); ++ return -1; ++ } ++ if (PATH_MAX - strlen(real_p) <= strlen("/enclave.signed.so")) { ++ printf("Failed to strcat enclave.sign.so path"); ++ return -1; ++ } ++ (void)strcat(real_p, "/enclave.signed.so"); ++ } ++ ++ res = cc_enclave_create(real_p, AUTO_ENCLAVE_TYPE, 0, SECGEAR_DEBUG_FLAG, NULL, 0, &context); + if (res != CC_SUCCESS) { + printf("Create enclave error\n"); + return res; +-- +2.27.0 + diff --git a/0022-add-example-of-using-sgxssl-lib.patch b/0022-add-example-of-using-sgxssl-lib.patch new file mode 100644 index 0000000..fd84a9d --- /dev/null +++ b/0022-add-example-of-using-sgxssl-lib.patch @@ -0,0 +1,942 @@ +From 607634479a08e5150482990343c19e2e45efc583 Mon Sep 17 00:00:00 2001 +From: yanlu +Date: Fri, 19 Feb 2021 11:09:51 +0800 +Subject: [PATCH 05/14] add example of using sgxssl lib + +--- + CMakeLists.txt | 1 + + docs/build_install.md | 4 + + examples/tls_enclave/CMakeLists.txt | 30 +++ + examples/tls_enclave/client/CMakeLists.txt | 38 +++ + examples/tls_enclave/client/tls_client.c | 100 +++++++ + examples/tls_enclave/enclave/CMakeLists.txt | 96 +++++++ + .../tls_enclave/enclave/Enclave.config.xml | 12 + + examples/tls_enclave/enclave/Enclave.lds | 11 + + examples/tls_enclave/enclave/enclave_server.c | 249 ++++++++++++++++++ + examples/tls_enclave/host/CMakeLists.txt | 56 ++++ + examples/tls_enclave/host/main.c | 179 +++++++++++++ + examples/tls_enclave/tls_enclave.edl | 26 ++ + examples/tls_enclave/tls_enclave.md | 17 ++ + 13 files changed, 819 insertions(+) + create mode 100644 examples/tls_enclave/CMakeLists.txt + create mode 100644 examples/tls_enclave/client/CMakeLists.txt + create mode 100644 examples/tls_enclave/client/tls_client.c + create mode 100644 examples/tls_enclave/enclave/CMakeLists.txt + create mode 100644 examples/tls_enclave/enclave/Enclave.config.xml + create mode 100644 examples/tls_enclave/enclave/Enclave.lds + create mode 100644 examples/tls_enclave/enclave/enclave_server.c + create mode 100644 examples/tls_enclave/host/CMakeLists.txt + create mode 100644 examples/tls_enclave/host/main.c + create mode 100644 examples/tls_enclave/tls_enclave.edl + create mode 100644 examples/tls_enclave/tls_enclave.md + +diff --git a/CMakeLists.txt b/CMakeLists.txt +index 98862a3..1653287 100644 +--- a/CMakeLists.txt ++++ b/CMakeLists.txt +@@ -57,6 +57,7 @@ endif() + if(CC_SGX) + add_subdirectory(${LOCAL_ROOT_PATH}/examples/helloworld) + add_subdirectory(${LOCAL_ROOT_PATH}/examples/seal_data) ++ add_subdirectory(${LOCAL_ROOT_PATH}/examples/tls_enclave) + endif() + + install(FILES ${LOCAL_ROOT_PATH}/conf/logrotate.d/secgear +diff --git a/docs/build_install.md b/docs/build_install.md +index 9ba1adb..636df90 100644 +--- a/docs/build_install.md ++++ b/docs/build_install.md +@@ -13,6 +13,10 @@ openEuler x86 + 3. source environment && mkdir debug && cd debug + && cmake -DCMAKE_BUILD_TYPE=Debug -DCC_SGX=ON -DSGXSDK="sgx_sdk path" .. && make && sudo make install + ++4. To run example tls_enclave, refer to https://gitee.com/src-openeuler/intel-sgx-ssl ++ download and install intel-sgx-ssl firstly. ++ source environment && mkdir debug && cd debug && cmake -DCMAKE_BUILD_TYPE=Debug -DCC_SGX=ON -DSGXSDK="sgx_sdk path" ++ && -DENCLAVE_SSL="sgxssl path" .. && make && sudo make install + + openEuler arm + +diff --git a/examples/tls_enclave/CMakeLists.txt b/examples/tls_enclave/CMakeLists.txt +new file mode 100644 +index 0000000..5b1693a +--- /dev/null ++++ b/examples/tls_enclave/CMakeLists.txt +@@ -0,0 +1,30 @@ ++# Copyright (c) Huawei Technologies Co., Ltd. 2020. All rights reserved. ++# secGear is licensed under the Mulan PSL v2. ++# You can use this software according to the terms and conditions of the Mulan PSL v2. ++# You may obtain a copy of Mulan PSL v2 at: ++# http://license.coscl.org.cn/MulanPSL2 ++# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR ++# IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR ++# PURPOSE. ++# See the Mulan PSL v2 for more details. ++ ++project(TlsEnclave C) ++ ++set(CMAKE_C_STANDARD 99) ++ ++set(CURRENT_ROOT_PATH ${CMAKE_CURRENT_SOURCE_DIR}) ++ ++#set edl name ++set(EDL_FILE tls_enclave.edl) ++#set auto code prefix ++set(PREFIX tls_enclave) ++set(CODEGEN codegen) ++ ++if(CC_SGX) ++ set(CODETYPE sgx) ++ add_definitions(-DPATH="${CMAKE_CURRENT_BINARY_DIR}/enclave/enclave.signed.so") ++endif() ++ ++add_subdirectory(${CURRENT_ROOT_PATH}/enclave) ++add_subdirectory(${CURRENT_ROOT_PATH}/host) ++add_subdirectory(${CURRENT_ROOT_PATH}/client) +diff --git a/examples/tls_enclave/client/CMakeLists.txt b/examples/tls_enclave/client/CMakeLists.txt +new file mode 100644 +index 0000000..a83b5e3 +--- /dev/null ++++ b/examples/tls_enclave/client/CMakeLists.txt +@@ -0,0 +1,38 @@ ++# Copyright (c) Huawei Technologies Co., Ltd. 2020. All rights reserved. ++# secGear is licensed under the Mulan PSL v2. ++# You can use this software according to the terms and conditions of the Mulan PSL v2. ++# You may obtain a copy of Mulan PSL v2 at: ++# http://license.coscl.org.cn/MulanPSL2 ++# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR ++# IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR ++# PURPOSE. ++# See the Mulan PSL v2 for more details. ++ ++set(OUTPUT tls_client) ++set(SOURCE_FILE ${CMAKE_CURRENT_SOURCE_DIR}/tls_client.c) ++ ++set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -fPIE") ++set(CMAKE_C_FLAGS_RELEASE "${CMAKE_C_FLAGS} -s") ++ ++if(${CMAKE_VERSION} VERSION_LESS "3.13.0") ++ link_directories(${CMAKE_LIBRARY_OUTPUT_DIRECTORY}) ++endif() ++ ++add_executable(${OUTPUT} ${SOURCE_FILE} ${AUTO_FILES}) ++ ++if(${CMAKE_VERSION} VERSION_GREATER_EQUAL "3.13.0") ++ target_link_directories(${OUTPUT} PRIVATE ++ ${CMAKE_LIBRARY_OUTPUT_DIRECTORY}) ++endif() ++ ++target_link_libraries(${OUTPUT} ssl crypto) ++ ++set_target_properties(${OUTPUT} PROPERTIES SKIP_BUILD_RPATH TRUE) ++ ++if(CC_SGX) ++ install(TARGETS ${OUTPUT} ++ RUNTIME ++ DESTINATION ${CMAKE_BINARY_DIR}/bin/ ++ PERMISSIONS OWNER_EXECUTE OWNER_WRITE OWNER_READ) ++endif() ++ +diff --git a/examples/tls_enclave/client/tls_client.c b/examples/tls_enclave/client/tls_client.c +new file mode 100644 +index 0000000..e05425b +--- /dev/null ++++ b/examples/tls_enclave/client/tls_client.c +@@ -0,0 +1,100 @@ ++/* ++ * Copyright (c) Huawei Technologies Co., Ltd. 2020. All rights reserved. ++ * secGear is licensed under the Mulan PSL v2. ++ * You can use this software according to the terms and conditions of the Mulan PSL v2. ++ * You may obtain a copy of Mulan PSL v2 at: ++ * http://license.coscl.org.cn/MulanPSL2 ++ * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR ++ * IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR ++ * PURPOSE. ++ * See the Mulan PSL v2 for more details. ++ */ ++ ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include "openssl/evp.h" ++#include "openssl/x509.h" ++#include "openssl/pem.h" ++#include "openssl/ssl.h" ++ ++#define BUF_LEN 1024 ++ ++int main(int argc, const char *argv[]) ++{ ++ struct sockaddr_in client_addr; ++ int fd = 0; ++ const SSL_METHOD *meth = NULL; ++ SSL_CTX *ctx = NULL; ++ SSL *ssl = NULL; ++ char buf[BUF_LEN] = {0}; ++ int ret = -1; ++ ++ if (argc != 3) { ++ printf("usage: %s port ca_file\n", argv[0]); ++ return -1; ++ } ++ ++ SSL_load_error_strings(); ++ SSLeay_add_ssl_algorithms(); ++ meth = TLS_method(); ++ if (meth == NULL) { ++ return -1; ++ } ++ ctx = SSL_CTX_new(meth); ++ if (ctx == NULL) { ++ return -1; ++ } ++ SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, NULL); ++ if (SSL_CTX_load_verify_locations(ctx, argv[2], NULL) <= 0) { ++ goto end; ++ } ++ memset(&client_addr, 0, sizeof(client_addr)); ++ client_addr.sin_family = AF_INET; ++ client_addr.sin_port = htons(atoi(argv[1])); ++ client_addr.sin_addr.s_addr = inet_addr("127.0.0.1"); ++ fd = socket(AF_INET, SOCK_STREAM, 0); ++ if (fd < 0) { ++ goto end; ++ } ++ ret = connect(fd, (struct sockaddr *)&client_addr, sizeof(client_addr)); ++ if (ret < 0) { ++ goto end; ++ } ++ ssl = SSL_new(ctx); ++ if (ssl == NULL) { ++ goto end; ++ } ++ SSL_set_fd(ssl, fd); ++ if (SSL_connect(ssl) <= 0) { ++ goto end; ++ } ++ if (SSL_write(ssl, "hello enclave!", sizeof("hello enclave!")) <= 0) { ++ goto end; ++ } ++ printf("send data: %s\n", "hello enclave!"); ++ if (SSL_read(ssl, buf, BUF_LEN - 1) <= 0) { ++ goto end; ++ } ++ printf("receive data: %s\n", buf); ++ ret = 0; ++ ++end: ++ if (ssl != NULL) { ++ SSL_shutdown(ssl); ++ SSL_free(ssl); ++ } ++ if (ctx != NULL) { ++ SSL_CTX_free(ctx); ++ } ++ if (fd > 0) { ++ close(fd); ++ } ++ return ret; ++} +diff --git a/examples/tls_enclave/enclave/CMakeLists.txt b/examples/tls_enclave/enclave/CMakeLists.txt +new file mode 100644 +index 0000000..5002e1b +--- /dev/null ++++ b/examples/tls_enclave/enclave/CMakeLists.txt +@@ -0,0 +1,96 @@ ++# Copyright (c) Huawei Technologies Co., Ltd. 2020. All rights reserved. ++# secGear is licensed under the Mulan PSL v2. ++# You can use this software according to the terms and conditions of the Mulan PSL v2. ++# You may obtain a copy of Mulan PSL v2 at: ++# http://license.coscl.org.cn/MulanPSL2 ++# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR ++# IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR ++# PURPOSE. ++# See the Mulan PSL v2 for more details. ++ ++#set sign key ++set(PEM Enclave_private.pem) ++ ++#set sign tool ++set(SIGN_TOOL ${LOCAL_ROOT_PATH}/tools/sign_tool/sign_tool.sh) ++ ++#set enclave src code ++set(SOURCE_FILES ${CMAKE_CURRENT_SOURCE_DIR}/enclave_server.c) ++ ++#set log level ++set(PRINT_LEVEL 3) ++add_definitions(-DPRINT_LEVEL=${PRINT_LEVEL}) ++ ++if(NOT IS_DIRECTORY ${ENCLAVE_SSL}) ++ message(FATAL_ERROR "Please provide the correct ENCLAVE_SSL path") ++endif() ++ ++if(CC_SGX) ++ #set signed output ++ set(OUTPUT enclave.signed.so) ++ set(AUTO_FILES ${CMAKE_CURRENT_BINARY_DIR}/${PREFIX}_t.h ${CMAKE_CURRENT_BINARY_DIR}/${PREFIX}_t.c) ++ add_custom_command(OUTPUT ${AUTO_FILES} ++ DEPENDS ${CURRENT_ROOT_PATH}/${EDL_FILE} ++ COMMAND ${CODEGEN} --${CODETYPE} --trusted ${CURRENT_ROOT_PATH}/${EDL_FILE} --search-path ${LOCAL_ROOT_PATH}/inc/host_inc/sgx --search-path ${SGXSDK}/include --search-path ${ENCLAVE_SSL}/include) ++endif() ++ ++set(COMMON_C_FLAGS "-W -Wall -Werror -fno-short-enums -fno-omit-frame-pointer -fstack-protector \ ++ -Wstack-protector --param ssp-buffer-size=4 -frecord-gcc-switches -Wextra -nostdinc -nodefaultlibs \ ++ -fno-peephole -fno-peephole2 -Wno-main -Wno-error=unused-parameter \ ++ -Wno-error=unused-but-set-variable -Wno-error=format-truncation=") ++ ++set(COMMON_C_LINK_FLAGS "-Wl,-z,now -Wl,-z,relro -Wl,-z,noexecstack -Wl,-nostdlib -nodefaultlibs -nostartfiles") ++ ++if(CC_SGX) ++ set(SGX_MODE HW) ++ set(CMAKE_C_FLAGS "${COMMON_C_FLAGS} -m64 -fvisibility=hidden -include${ENCLAVE_SSL}/include/tsgxsslio.h") ++ set(CMAKE_C_FLAGS_RELEASE "${CMAKE_C_FLAGS} -s") ++ ++ if(${SGX_MODE} STREQUAL HW) ++ set(Trts_Library_Name sgx_trts) ++ set(Service_Library_Name sgx_tservice) ++ else() ++ set(Trts_Library_Name sgx_trts_sim) ++ set(Service_Library_Name sgx_tservice_sim) ++ endif() ++ ++ set(CMAKE_SHARED_LINKER_FLAGS "${COMMON_C_LINK_FLAGS} -Wl,-z,defs -Wl,-pie -Bstatic -Bsymbolic -eenclave_entry \ ++ -Wl,--export-dynamic -Wl,--defsym,__ImageBase=0 -Wl,--gc-sections -Wl,--version-script=${CMAKE_CURRENT_SOURCE_DIR}/Enclave.lds") ++ ++ if(${CMAKE_VERSION} VERSION_LESS "3.13.0") ++ link_directories(${ENCLAVE_SSL}/lib64 ++ ${SGXSDK}/lib64 ++ ${CMAKE_BINARY_DIR}/lib) ++ endif() ++ ++ add_library(${PREFIX} SHARED ${SOURCE_FILES} ${AUTO_FILES}) ++ ++ target_include_directories(${PREFIX} PRIVATE ++ ${CMAKE_CURRENT_BINARY_DIR} ++ ${SGXSDK}/include/tlibc ++ ${SGXSDK}/include/libcxx ++ ${SGXSDK}/include ++ ${ENCLAVE_SSL}/include ++ ${LOCAL_ROOT_PATH}/inc/host_inc ++ ${LOCAL_ROOT_PATH}/inc/host_inc/sgx ++ ${LOCAL_ROOT_PATH}/inc/enclave_inc ++ ${LOCAL_ROOT_PATH}/inc/enclave_inc/sgx ++ ) ++ ++ if(${CMAKE_VERSION} VERSION_GREATER_EQUAL "3.13.0") ++ target_link_directories(${PREFIX} PRIVATE ++ ${ENCLAVE_SSL}/lib64 ++ ${SGXSDK}/lib64 ++ ${CMAKE_BINARY_DIR}/lib) ++ endif() ++ ++ target_link_libraries(${PREFIX} -lsecgear_tee -Wl,--whole-archive ${Trts_Library_Name} -lsgx_tsgxssl -Wl,--no-whole-archive -Wl,--start-group -lsgx_tsgxssl_ssl -lsgx_tsgxssl_crypto -lsgx_tstdc -lsgx_tcxx -lsgx_tcrypto -lsgx_pthread -l${Service_Library_Name} -Wl,--end-group) ++ ++ add_custom_command(TARGET ${PREFIX} ++ POST_BUILD ++ COMMAND umask 0177 ++ COMMAND openssl genrsa -3 -out ${PEM} 3072 ++ COMMAND bash ${SIGN_TOOL} -d sign -x sgx -i ${CMAKE_LIBRARY_OUTPUT_DIRECTORY}/lib${PREFIX}.so -k ${PEM} -o ${OUTPUT} -c ${CMAKE_CURRENT_SOURCE_DIR}/Enclave.config.xml) ++endif() ++ ++set_target_properties(${PREFIX} PROPERTIES SKIP_BUILD_RPATH TRUE) +diff --git a/examples/tls_enclave/enclave/Enclave.config.xml b/examples/tls_enclave/enclave/Enclave.config.xml +new file mode 100644 +index 0000000..e94c9bc +--- /dev/null ++++ b/examples/tls_enclave/enclave/Enclave.config.xml +@@ -0,0 +1,12 @@ ++ ++ 0 ++ 0 ++ 0x40000 ++ 0x100000 ++ 10 ++ 1 ++ ++ 0 ++ 0 ++ 0xFFFFFFFF ++ +diff --git a/examples/tls_enclave/enclave/Enclave.lds b/examples/tls_enclave/enclave/Enclave.lds +new file mode 100644 +index 0000000..ab77e64 +--- /dev/null ++++ b/examples/tls_enclave/enclave/Enclave.lds +@@ -0,0 +1,11 @@ ++enclave.so ++{ ++ global: ++ g_global_data_sim; ++ g_global_data; ++ enclave_entry; ++ g_peak_heap_used; ++ local: ++ *; ++}; ++ +diff --git a/examples/tls_enclave/enclave/enclave_server.c b/examples/tls_enclave/enclave/enclave_server.c +new file mode 100644 +index 0000000..848eb9c +--- /dev/null ++++ b/examples/tls_enclave/enclave/enclave_server.c +@@ -0,0 +1,249 @@ ++/* ++ * Copyright (c) Huawei Technologies Co., Ltd. 2020. All rights reserved. ++ * secGear is licensed under the Mulan PSL v2. ++ * You can use this software according to the terms and conditions of the Mulan PSL v2. ++ * You may obtain a copy of Mulan PSL v2 at: ++ * http://license.coscl.org.cn/MulanPSL2 ++ * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR ++ * IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR ++ * PURPOSE. ++ * See the Mulan PSL v2 for more details. ++ */ ++ ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include "tls_enclave_t.h" ++#include "status.h" ++#include "secgear_dataseal.h" ++ ++#define BUF_SIZE 1024 ++#define MAX_ENC_KEY_LEN 4096 ++#define ADD_DATA_RAW "add mac text" ++ ++size_t seal_key(const char *file_name, size_t file_name_len, char *password, size_t pw_len, ++ char *enc_buf, size_t enc_buf_len) ++{ ++ BIO *r_key = NULL; ++ BIO *r_prikey = NULL; ++ RSA *rsa_key = NULL; ++ uint8_t *buf = NULL; ++ uint32_t buf_len, sealed_data_len; ++ int res = 0; ++ int retval = CC_FAIL; ++ ++ if (file_name == NULL || file_name_len == 0 || password == NULL || pw_len == 0 || enc_buf == NULL) { ++ return 0; ++ } ++ r_key = BIO_new_file(file_name, "r"); ++ if (r_key == NULL) { ++ goto end; ++ }; ++ rsa_key = PEM_read_bio_RSAPrivateKey(r_key, NULL, NULL, password); ++ if (rsa_key == NULL) { ++ goto end; ++ }; ++ r_prikey = BIO_new(BIO_s_mem()); ++ if (r_prikey == NULL) { ++ goto end; ++ } ++ if (!PEM_write_bio_RSAPrivateKey(r_prikey, rsa_key, NULL, NULL, 0, NULL, NULL)) { ++ goto end; ++ } ++ buf_len = BIO_ctrl_pending(r_prikey); ++ if (buf_len == 0) { ++ goto end; ++ } ++ buf = (uint8_t *)malloc(buf_len); ++ if (buf == NULL) { ++ goto end; ++ } ++ if ((size_t)BIO_read(r_prikey, buf, buf_len) != buf_len) { ++ goto end; ++ } ++ sealed_data_len = cc_enclave_get_sealed_data_size(buf_len, strlen((const char *)ADD_DATA_RAW)); ++ if (sealed_data_len == UINT32_MAX || enc_buf_len < sealed_data_len) { ++ goto end; ++ } ++ retval = cc_enclave_seal_data((uint8_t *)buf, buf_len, (cc_enclave_sealed_data_t *)enc_buf, enc_buf_len, ++ (uint8_t*)ADD_DATA_RAW, strlen((const char*)ADD_DATA_RAW)); ++ if (retval != CC_SUCCESS) { ++ goto end; ++ } ++ res = sealed_data_len; ++ ++end: ++ BIO_free(r_key); ++ BIO_free(r_prikey); ++ RSA_free(rsa_key); ++ if (buf != NULL) { ++ memset(buf, 0, buf_len); ++ free(buf); ++ }; ++ memset(password, 0, pw_len); ++ return res; ++} ++ ++int unseal_enc_data(char **data_p, size_t *data_len_p, const char *enc_data) ++{ ++ char *add_data = NULL; ++ char *data = NULL; ++ size_t add_len = 0; ++ size_t data_len = 0; ++ int retval = CC_FAIL; ++ ++ add_len = cc_enclave_get_add_text_size((const cc_enclave_sealed_data_t *)enc_data); ++ data_len = cc_enclave_get_encrypted_text_size((const cc_enclave_sealed_data_t *)enc_data); ++ if (data_len == 0 || add_len != strlen((const char*)ADD_DATA_RAW)) { ++ return CC_FAIL; ++ } ++ data = malloc(data_len); ++ add_data = malloc(add_len); ++ if (data == NULL || add_data == NULL) { ++ goto end; ++ } ++ memset(data, 0, data_len); ++ retval = cc_enclave_unseal_data((cc_enclave_sealed_data_t *)enc_data, (uint8_t *)data, (uint32_t *)&data_len, ++ (uint8_t *)add_data, (uint32_t *)&add_len); ++ if (retval != CC_SUCCESS) { ++ goto end; ++ } ++ if (strncmp((const char *)add_data, (const char*)ADD_DATA_RAW, strlen((const char*)ADD_DATA_RAW)) != 0) { ++ retval = CC_FAIL; ++ goto end; ++ } ++ *data_p = data; ++ *data_len_p = data_len; ++ retval = CC_SUCCESS; ++ ++end: ++ if (add_data != NULL) { ++ memset(add_data, 0, add_len); ++ free(add_data); ++ } ++ if (retval != CC_SUCCESS && data != NULL) { ++ memset(data, 0, data_len); ++ free(data); ++ } ++ return retval; ++} ++ ++int set_ctx_key(SSL_CTX *ctx, const char *enc_key_file_name) ++{ ++ BIO *in_bio = NULL; ++ EVP_PKEY *pkey = NULL; ++ char *raw_key = NULL; ++ size_t raw_key_len = 0; ++ BIO *key_bio = NULL; ++ char *enc_key = NULL; ++ int retval = CC_FAIL; ++ int res = CC_FAIL; ++ ++ key_bio = BIO_new_file(enc_key_file_name, "r"); ++ if (key_bio == NULL) { ++ goto end; ++ }; ++ enc_key = (char *)malloc(MAX_ENC_KEY_LEN); ++ if (enc_key == NULL) { ++ goto end; ++ } ++ if (BIO_read(key_bio, enc_key, MAX_ENC_KEY_LEN) <= 0) { ++ goto end; ++ } ++ res = unseal_enc_data(&raw_key, &raw_key_len, enc_key); ++ if (res != CC_SUCCESS || raw_key_len == 0) { ++ goto end; ++ } ++ in_bio = BIO_new_mem_buf(raw_key, raw_key_len); ++ if (in_bio == NULL) { ++ goto end; ++ } ++ pkey = PEM_read_bio_PrivateKey(in_bio, NULL, NULL, NULL); ++ if (pkey == NULL) { ++ goto end; ++ } ++ if (!SSL_CTX_use_PrivateKey(ctx, pkey)) { ++ goto end; ++ } ++ retval = CC_SUCCESS; ++ ++end: ++ EVP_PKEY_free(pkey); ++ BIO_free(in_bio); ++ BIO_free(key_bio); ++ if (enc_key != NULL) { ++ free(enc_key); ++ } ++ if (raw_key != NULL) { ++ memset(raw_key, 0, raw_key_len); ++ free(raw_key); ++ } ++ return retval; ++} ++ ++int start_enclave_tls(int client_fd,const char *cert, size_t cert_len, const char *enc_key, size_t enc_key_len) ++{ ++ char buf[BUF_SIZE] = {0}; ++ const SSL_METHOD *meth = NULL; ++ SSL_CTX *ctx = NULL; ++ SSL *ssl = NULL; ++ int res = 0; ++ int retval = CC_FAIL; ++ ++ if (client_fd <= 0 || cert == NULL || cert_len == 0 || enc_key == NULL || enc_key_len == 0) { ++ return CC_ERROR_BAD_PARAMETERS; ++ } ++ SSL_load_error_strings(); ++ SSLeay_add_ssl_algorithms(); ++ meth = TLS_method(); ++ if (meth == NULL) { ++ return CC_FAIL; ++ } ++ ctx = SSL_CTX_new(meth); ++ if (ctx == NULL) { ++ return CC_FAIL; ++ } ++ if (SSL_CTX_use_certificate_file(ctx, cert, SSL_FILETYPE_PEM) <= 0) { ++ goto end; ++ } ++ if (set_ctx_key(ctx, enc_key) != CC_SUCCESS){ ++ goto end; ++ } ++ if (!SSL_CTX_check_private_key(ctx)) { ++ goto end; ++ } ++ ssl = SSL_new(ctx); ++ if (ssl == NULL) { ++ goto end; ++ } ++ SSL_set_fd(ssl, client_fd); ++ if (SSL_set_cipher_list(ssl, "ECDHE-RSA-AES128-GCM-SHA256") != 1) { ++ goto end; ++ } ++ if (SSL_accept(ssl) <= 0) { ++ goto end; ++ } ++ res = SSL_read(ssl, buf, BUF_SIZE -1); ++ if (res <= 0) { ++ goto end; ++ } ++ if (SSL_write(ssl, buf, res) <= 0) { ++ goto end; ++ } ++ retval = CC_SUCCESS; ++ ++end: ++ if (ssl != NULL) { ++ SSL_shutdown(ssl); ++ SSL_free(ssl); ++ } ++ if (ctx != NULL) { ++ SSL_CTX_free(ctx); ++ } ++ memset(buf, 0, BUF_SIZE); ++ return retval; ++} +diff --git a/examples/tls_enclave/host/CMakeLists.txt b/examples/tls_enclave/host/CMakeLists.txt +new file mode 100644 +index 0000000..2f4c8ac +--- /dev/null ++++ b/examples/tls_enclave/host/CMakeLists.txt +@@ -0,0 +1,56 @@ ++# Copyright (c) Huawei Technologies Co., Ltd. 2020. All rights reserved. ++# secGear is licensed under the Mulan PSL v2. ++# You can use this software according to the terms and conditions of the Mulan PSL v2. ++# You may obtain a copy of Mulan PSL v2 at: ++# http://license.coscl.org.cn/MulanPSL2 ++# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR ++# IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR ++# PURPOSE. ++# See the Mulan PSL v2 for more details. ++ ++#set host exec name ++set(OUTPUT secgear_tls) ++#set host src code ++set(SOURCE_FILE ${CMAKE_CURRENT_SOURCE_DIR}/main.c) ++ ++#set auto code ++if(CC_SGX) ++ set(AUTO_FILES ${CMAKE_CURRENT_BINARY_DIR}/${PREFIX}_u.h ${CMAKE_CURRENT_BINARY_DIR}/${PREFIX}_u.c) ++ add_custom_command(OUTPUT ${AUTO_FILES} ++ DEPENDS ${CURRENT_ROOT_PATH}/${EDL_FILE} ++ COMMAND ${CODEGEN} --${CODETYPE} --untrusted ${CURRENT_ROOT_PATH}/${EDL_FILE} --search-path ${LOCAL_ROOT_PATH}/inc/host_inc/sgx --search-path ${SGXSDK}/include --search-path ${ENCLAVE_SSL}/include) ++endif() ++ ++set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -fPIE") ++set(CMAKE_C_FLAGS_RELEASE "${CMAKE_C_FLAGS} -s") ++ ++if(CC_SGX) ++ if(${CMAKE_VERSION} VERSION_LESS "3.13.0") ++ link_directories(${CMAKE_LIBRARY_OUTPUT_DIRECTORY} ${SGXSSL}/lib64) ++ endif() ++ set(SGX_MODE HW) ++ if(${SGX_MODE} STREQUAL HW) ++ set(Urts_Library_Name sgx_urts) ++ else() ++ set(Urts_Library_Name sgx_urts_sim) ++ endif() ++ add_executable(${OUTPUT} ${SOURCE_FILE} ${AUTO_FILES}) ++ target_include_directories(${OUTPUT} PRIVATE ++ ${LOCAL_ROOT_PATH}/inc/host_inc ++ ${LOCAL_ROOT_PATH}/inc/host_inc/sgx ++ ${CMAKE_CURRENT_BINARY_DIR}) ++ if(${CMAKE_VERSION} VERSION_GREATER_EQUAL "3.13.0") ++ target_link_directories(${OUTPUT} PRIVATE ${CMAKE_LIBRARY_OUTPUT_DIRECTORY} ${ENCLAVE_SSL}/lib64) ++ endif() ++ target_link_libraries(${OUTPUT} secgear ${Urts_Library_Name} pthread ssl crypto sgx_usgxssl) ++endif() ++ ++set_target_properties(${OUTPUT} PROPERTIES SKIP_BUILD_RPATH TRUE) ++ ++if(CC_SGX) ++ install(TARGETS ${OUTPUT} ++ RUNTIME ++ DESTINATION ${CMAKE_BINARY_DIR}/bin/ ++ PERMISSIONS OWNER_EXECUTE OWNER_WRITE OWNER_READ) ++endif() ++ +diff --git a/examples/tls_enclave/host/main.c b/examples/tls_enclave/host/main.c +new file mode 100644 +index 0000000..4407e64 +--- /dev/null ++++ b/examples/tls_enclave/host/main.c +@@ -0,0 +1,179 @@ ++/* ++ * Copyright (c) Huawei Technologies Co., Ltd. 2020. All rights reserved. ++ * secGear is licensed under the Mulan PSL v2. ++ * You can use this software according to the terms and conditions of the Mulan PSL v2. ++ * You may obtain a copy of Mulan PSL v2 at: ++ * http://license.coscl.org.cn/MulanPSL2 ++ * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR ++ * IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR ++ * PURPOSE. ++ * See the Mulan PSL v2 for more details. ++ */ ++ ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include "openssl/evp.h" ++#include "openssl/x509.h" ++#include "openssl/pem.h" ++#include "openssl/ssl.h" ++#include "tls_enclave_u.h" ++#include "enclave.h" ++ ++#define BUF_LEN 1024 ++#define MAX_LISTEN_FD 64 ++#define PASS_MAX 32 ++#define MAX_ENC_KEY_LEN 4096 ++#define ENC_KEY_FILE_NAME "enc_key" ++ ++int set_echo_mode(int fd, int option) ++{ ++ struct termios term; ++ if (tcgetattr(fd, &term) != 0) { ++ return CC_FAIL; ++ } ++ if (option) { ++ term.c_lflag |= (ECHO | ECHOE | ECHOK | ECHONL); ++ } else { ++ term.c_lflag &= ~(ECHO | ECHOE | ECHOK | ECHONL); ++ } ++ if (tcsetattr(fd, TCSAFLUSH, &term) != 0) { ++ return CC_FAIL; ++ } ++ return CC_SUCCESS; ++} ++ ++int get_password_and_seal_key(cc_enclave_t *context, const char *key_file_name, const char *enc_key_file_name) ++{ ++ int res = CC_FAIL; ++ size_t retval = 0; ++ size_t pw_len = 0; ++ char password[PASS_MAX] = {0}; ++ char *enc_key = NULL; ++ FILE *fp = NULL; ++ ++ printf("Please input password:\n"); ++ if (set_echo_mode(STDIN_FILENO, 0)) { ++ return CC_FAIL; ++ } ++ if (fgets((char *)password, PASS_MAX, stdin) == NULL) { ++ return CC_FAIL; ++ } ++ pw_len = strlen((const char *)password); ++ if (password[pw_len - 1] == '\n') { ++ password[pw_len-1] = 0; ++ pw_len--; ++ } ++ if (set_echo_mode(STDIN_FILENO, 1)) { ++ goto end; ++ } ++ enc_key = malloc(MAX_ENC_KEY_LEN); ++ if (enc_key == NULL) { ++ goto end; ++ } ++ res = seal_key(context, &retval, key_file_name, strlen(key_file_name) + 1, password, pw_len + 1, ++ enc_key, MAX_ENC_KEY_LEN); ++ if (res != CC_SUCCESS || retval == 0) { ++ res = CC_FAIL; ++ goto end; ++ } ++ fp = fopen(enc_key_file_name, "w+"); ++ if (fp == NULL) { ++ res = CC_FAIL; ++ goto end; ++ } ++ if (fwrite(enc_key, sizeof(char), retval, fp) != retval) { ++ fclose(fp); ++ res = CC_FAIL; ++ goto end; ++ } ++ fclose(fp); ++ if (remove(key_file_name) == 0) { ++ printf("delete origin key file success!\n"); ++ } else { ++ printf("delete origin key file error!\n"); ++ res = CC_FAIL; ++ } ++ ++end: ++ memset(password, 0, pw_len); ++ return res; ++} ++ ++int start_server(int port) ++{ ++ int server_fd = socket(AF_INET, SOCK_STREAM, 0); ++ struct sockaddr_in serv_addr; ++ memset(&serv_addr, 0, sizeof(serv_addr)); ++ serv_addr.sin_family = AF_INET; ++ serv_addr.sin_port = htons(port); ++ serv_addr.sin_addr.s_addr = htonl(INADDR_ANY); ++ if (bind(server_fd, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0) { ++ return -1; ++ } ++ listen(server_fd, MAX_LISTEN_FD); ++ return server_fd; ++} ++ ++int main(int argc, const char *argv[]) ++{ ++ char *path = PATH; ++ cc_enclave_t *context = NULL; ++ struct sockaddr_in client_addr; ++ socklen_t client_len; ++ int server_fd = -1; ++ int tlsc_fd = -1; ++ cc_enclave_result_t res = CC_FAIL; ++ int retval = 0; ++ ++ if (argc != 4) { ++ printf("usage: %s port cert_file key_file\n", argv[0]); ++ return CC_FAIL; ++ } ++ ++ server_fd = start_server(atoi(argv[1])); ++ if (server_fd < 0) { ++ return CC_FAIL; ++ } ++ tlsc_fd = accept(server_fd, (struct sockaddr *)&client_addr, &client_len); ++ if (tlsc_fd < 0) { ++ return CC_FAIL; ++ } ++ printf("Create secgear enclave\n"); ++ res = cc_enclave_create(path, AUTO_ENCLAVE_TYPE, 0, SECGEAR_DEBUG_FLAG, NULL, 0, &context); ++ if (res != CC_SUCCESS) { ++ printf("Create enclave error\n"); ++ goto end; ++ } ++ res = get_password_and_seal_key(context, argv[3], ENC_KEY_FILE_NAME); ++ if (res != CC_SUCCESS) { ++ printf("get_password_and_seal_key error\n"); ++ goto end; ++ } ++ res = start_enclave_tls(context, &retval, tlsc_fd, argv[2], strlen(argv[2]) + 1, ENC_KEY_FILE_NAME, ++ strlen(ENC_KEY_FILE_NAME) + 1); ++ if (res != CC_SUCCESS || retval != CC_SUCCESS) { ++ printf("start_enclave_tls error\n"); ++ goto end; ++ } ++ ++ printf("enclve tls finish\n"); ++ ++end: ++ if (context != NULL) { ++ res = cc_enclave_destroy(context); ++ if(res != CC_SUCCESS) { ++ printf("Destroy enclave error\n"); ++ } ++ } ++ close(tlsc_fd); ++ close(server_fd); ++ return res; ++} +diff --git a/examples/tls_enclave/tls_enclave.edl b/examples/tls_enclave/tls_enclave.edl +new file mode 100644 +index 0000000..93e9a70 +--- /dev/null ++++ b/examples/tls_enclave/tls_enclave.edl +@@ -0,0 +1,26 @@ ++/* ++ * Copyright (c) Huawei Technologies Co., Ltd. 2020. All rights reserved. ++ * secGear is licensed under the Mulan PSL v2. ++ * You can use this software according to the terms and conditions of the Mulan PSL v2. ++ * You may obtain a copy of Mulan PSL v2 at: ++ * http://license.coscl.org.cn/MulanPSL2 ++ * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR ++ * IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR ++ * PURPOSE. ++ * See the Mulan PSL v2 for more details. ++ */ ++ ++enclave { ++ include "stdbool.h" ++ include "secgear_urts.h" ++ from "secgear_tstdc.edl" import *; ++ from "secgear_tssl.edl" import *; ++ trusted { ++ public size_t seal_key([in, size = file_name_len] const char *file_name, size_t file_name_len, ++ [in, size = pw_len] char *password, size_t pw_len, ++ [out, size = enc_buf_len] char *enc_buf, size_t enc_buf_len); ++ public int start_enclave_tls(int client_fd, ++ [in, size = cert_len] const char *cert, size_t cert_len, ++ [in, size = enc_key_len] const char *enc_key, size_t enc_key_len); ++ }; ++}; +diff --git a/examples/tls_enclave/tls_enclave.md b/examples/tls_enclave/tls_enclave.md +new file mode 100644 +index 0000000..e81d70c +--- /dev/null ++++ b/examples/tls_enclave/tls_enclave.md +@@ -0,0 +1,17 @@ ++#Getting started with the tls_enclave example ++ ++In the scenario where a user already has a certificate and private on the host side, the tls_enclve provides an example how to protect the private key and how to estabilish a TLS connection with enclave in Linux SGX environment. ++ ++1. Install secGear and intel-sgx-ssl(http://gitee.com/src-openEuler/intel-sgx-ssl). ++2. Enter the development directory ../secGear, source environment && mkdir debug && cd debug ++&& cmake -DCMAKE_BUILD_TYPE=Debug -DCC_SGX=on -DSGXSDK="sgx_sdk path" -DENCLAVE_SSL="sgxssl path" .. ++3. To run secgear_tls, the certificate and key used by the TLS server needs to be generated, the following example generate signed certificate only for testing. ++(1) generate RSA key: ++ openssl genrsa -f4 -aes256 -out server.key 3072 ++ follow the screen instructions to enter the pass phrase for protecting private key, the pass phrase should meet certain complexity requirements. ++(2) generate self-signed certificate ++ openssl req -new -x509 -days 365 -key server.key -out server.pem -sha256 -subj "/C=CN/ST=GD/L=SZ/O=test/OU=test/CN=test" ++4. start secgear_tls, sudo debug/bin/secgear_tls 9090 server.pem server.key & ++ start tls_client, sudo debug/bin/tls_client 9090 server.pem ++ follow the screen instructions to enter the pass phrase to usee the private key. ++ After exectued successfully, the private key is deleted and only the key encrypted by enclave is saved. +-- +2.27.0 + diff --git a/0023-tls_enclave-is-not-compiled-by-default.patch b/0023-tls_enclave-is-not-compiled-by-default.patch new file mode 100644 index 0000000..c2080de --- /dev/null +++ b/0023-tls_enclave-is-not-compiled-by-default.patch @@ -0,0 +1,25 @@ +From 90df8d9c0ac4ee7cbe24971ed4a8c4c6ac86c3b1 Mon Sep 17 00:00:00 2001 +From: yanlu +Date: Thu, 15 Apr 2021 11:49:27 +0800 +Subject: [PATCH 06/14] tls_enclave is not compiled by default + +--- + CMakeLists.txt | 2 +- + 1 file changed, 1 insertion(+), 1 deletion(-) + +diff --git a/CMakeLists.txt b/CMakeLists.txt +index 1653287..b1fe4a4 100644 +--- a/CMakeLists.txt ++++ b/CMakeLists.txt +@@ -57,7 +57,7 @@ endif() + if(CC_SGX) + add_subdirectory(${LOCAL_ROOT_PATH}/examples/helloworld) + add_subdirectory(${LOCAL_ROOT_PATH}/examples/seal_data) +- add_subdirectory(${LOCAL_ROOT_PATH}/examples/tls_enclave) ++# add_subdirectory(${LOCAL_ROOT_PATH}/examples/tls_enclave) + endif() + + install(FILES ${LOCAL_ROOT_PATH}/conf/logrotate.d/secgear +-- +2.27.0 + diff --git a/0024-Cmake-replace-minial-cmake-from-3.12-to-3.10.patch b/0024-Cmake-replace-minial-cmake-from-3.12-to-3.10.patch new file mode 100644 index 0000000..67c822d --- /dev/null +++ b/0024-Cmake-replace-minial-cmake-from-3.12-to-3.10.patch @@ -0,0 +1,68 @@ +From 20d6808fd639e4506fd1a383cf59094a17773775 Mon Sep 17 00:00:00 2001 +From: Li Feng +Date: Mon, 26 Apr 2021 09:26:46 +0000 +Subject: [PATCH 07/14] Cmake: replace minial cmake from 3.12 to 3.10 + +Signed-off-by: Li Feng +--- + CMakeLists.txt | 2 +- + README.en.md | 2 +- + README.md | 2 +- + examples/seal_data/CMakeLists.txt | 2 +- + 4 files changed, 4 insertions(+), 4 deletions(-) + +diff --git a/CMakeLists.txt b/CMakeLists.txt +index b1fe4a4..a4d1668 100644 +--- a/CMakeLists.txt ++++ b/CMakeLists.txt +@@ -8,7 +8,7 @@ + # PURPOSE. + # See the Mulan PSL v2 for more details. + +-cmake_minimum_required(VERSION 3.12 FATAL_ERROR) ++cmake_minimum_required(VERSION 3.10 FATAL_ERROR) + project(secGear C) + + set(CMAKE_C_STANDARD 99) +diff --git a/README.en.md b/README.en.md +index a33a50c..4df13b0 100644 +--- a/README.en.md ++++ b/README.en.md +@@ -43,7 +43,7 @@ Then save as test.edl + + ### 2 Write the top-level CMakeLists.txt + +- cmake_minimum_required(VERSION 3.12 FATAL_ERROR) ++ cmake_minimum_required(VERSION 3.10 FATAL_ERROR) + project(TEST C) + set(CMAKE_C_STANDARD 99) + set(CURRENT_ROOT_PATH ${CMAKE_CURRENT_SOURCE_DIR}) +diff --git a/README.md b/README.md +index 971ddca..a90450b 100644 +--- a/README.md ++++ b/README.md +@@ -35,7 +35,7 @@ SecGear则是面向计算产业的机密计算安全应用开发套件。旨在 + + ### 2 编写最外层CMakeLists.txt文件 + +- cmake_minimum_required(VERSION 3.12 FATAL_ERROR) ++ cmake_minimum_required(VERSION 3.10 FATAL_ERROR) + project(TEST C) + set(CMAKE_C_STANDARD 99) + set(CURRENT_ROOT_PATH ${CMAKE_CURRENT_SOURCE_DIR}) +diff --git a/examples/seal_data/CMakeLists.txt b/examples/seal_data/CMakeLists.txt +index 503fe0d..3577301 100644 +--- a/examples/seal_data/CMakeLists.txt ++++ b/examples/seal_data/CMakeLists.txt +@@ -8,7 +8,7 @@ + # PURPOSE. + # See the Mulan PSL v2 for more details. + +-cmake_minimum_required(VERSION 3.12) ++cmake_minimum_required(VERSION 3.10) + + project(SealData C) + +-- +2.27.0 + diff --git a/0025-example-add-example-for-LRT-long-running-task.patch b/0025-example-add-example-for-LRT-long-running-task.patch new file mode 100644 index 0000000..5ca148a --- /dev/null +++ b/0025-example-add-example-for-LRT-long-running-task.patch @@ -0,0 +1,517 @@ +From d8d225ed834a9cfe63b305ccd2ce97f5b3ebdfb4 Mon Sep 17 00:00:00 2001 +From: Li Feng +Date: Mon, 26 Apr 2021 09:32:12 +0000 +Subject: [PATCH 08/14] example: add example for LRT(long running task) + +Signed-off-by: Li Feng +--- + CMakeLists.txt | 1 + + examples/lrt/CMakeLists.txt | 34 +++++ + examples/lrt/enclave/CMakeLists.txt | 158 ++++++++++++++++++++++++ + examples/lrt/enclave/Enclave.config.xml | 12 ++ + examples/lrt/enclave/Enclave.lds | 11 ++ + examples/lrt/enclave/lrt.c | 23 ++++ + examples/lrt/enclave/manifest.txt.in | 8 ++ + examples/lrt/host/CMakeLists.txt | 85 +++++++++++++ + examples/lrt/host/main.c | 70 +++++++++++ + examples/lrt/lrt.edl | 19 +++ + 10 files changed, 421 insertions(+) + create mode 100644 examples/lrt/CMakeLists.txt + create mode 100644 examples/lrt/enclave/CMakeLists.txt + create mode 100644 examples/lrt/enclave/Enclave.config.xml + create mode 100644 examples/lrt/enclave/Enclave.lds + create mode 100644 examples/lrt/enclave/lrt.c + create mode 100644 examples/lrt/enclave/manifest.txt.in + create mode 100644 examples/lrt/host/CMakeLists.txt + create mode 100644 examples/lrt/host/main.c + create mode 100644 examples/lrt/lrt.edl + +diff --git a/CMakeLists.txt b/CMakeLists.txt +index a4d1668..1d036ea 100644 +--- a/CMakeLists.txt ++++ b/CMakeLists.txt +@@ -58,6 +58,7 @@ if(CC_SGX) + add_subdirectory(${LOCAL_ROOT_PATH}/examples/helloworld) + add_subdirectory(${LOCAL_ROOT_PATH}/examples/seal_data) + # add_subdirectory(${LOCAL_ROOT_PATH}/examples/tls_enclave) ++# add_subdirectory(${LOCAL_ROOT_PATH}/examples/lrt) + endif() + + install(FILES ${LOCAL_ROOT_PATH}/conf/logrotate.d/secgear +diff --git a/examples/lrt/CMakeLists.txt b/examples/lrt/CMakeLists.txt +new file mode 100644 +index 0000000..9059590 +--- /dev/null ++++ b/examples/lrt/CMakeLists.txt +@@ -0,0 +1,34 @@ ++# Copyright (c) Huawei Technologies Co., Ltd. 2020. All rights reserved. ++# secGear is licensed under the Mulan PSL v2. ++# You can use this software according to the terms and conditions of the Mulan PSL v2. ++# You may obtain a copy of Mulan PSL v2 at: ++# http://license.coscl.org.cn/MulanPSL2 ++# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR ++# IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR ++# PURPOSE. ++# See the Mulan PSL v2 for more details. ++ ++project(HelloWorldLRT C) ++ ++set(CMAKE_C_STANDARD 99) ++ ++set(CURRENT_ROOT_PATH ${CMAKE_CURRENT_SOURCE_DIR}) ++ ++#set edl name ++set(EDL_FILE lrt.edl) ++set(CODEGEN codegen) ++ ++if(CC_GP) ++ set(CODETYPE trustzone) ++ execute_process(COMMAND uuidgen -r OUTPUT_VARIABLE UUID) ++ string(REPLACE "\n" "" UUID ${UUID}) ++ add_definitions(-DPATH="/data/${UUID}.sec") ++endif() ++ ++if(CC_SGX) ++ set(CODETYPE sgx) ++ add_definitions(-DPATH="${CMAKE_CURRENT_BINARY_DIR}/enclave/enclave.signed.so") ++endif() ++ ++add_subdirectory(${CURRENT_ROOT_PATH}/enclave) ++add_subdirectory(${CURRENT_ROOT_PATH}/host) +diff --git a/examples/lrt/enclave/CMakeLists.txt b/examples/lrt/enclave/CMakeLists.txt +new file mode 100644 +index 0000000..64494cc +--- /dev/null ++++ b/examples/lrt/enclave/CMakeLists.txt +@@ -0,0 +1,158 @@ ++# Copyright (c) Huawei Technologies Co., Ltd. 2020. All rights reserved. ++# secGear is licensed under the Mulan PSL v2. ++# You can use this software according to the terms and conditions of the Mulan PSL v2. ++# You may obtain a copy of Mulan PSL v2 at: ++# http://license.coscl.org.cn/MulanPSL2 ++# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR ++# IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR ++# PURPOSE. ++# See the Mulan PSL v2 for more details. ++ ++#set auto code prefix ++set(PREFIX lrt) ++ ++#set sign key ++set(PEM Enclave_private.pem) ++ ++#set sign tool ++set(SIGN_TOOL ${LOCAL_ROOT_PATH}/tools/sign_tool/sign_tool.sh) ++ ++#set enclave src code ++set(SOURCE_FILES ${CMAKE_CURRENT_SOURCE_DIR}/lrt.c) ++ ++#set log level ++set(PRINT_LEVEL 3) ++add_definitions(-DPRINT_LEVEL=${PRINT_LEVEL}) ++ ++if(CC_GP) ++ #set signed output ++ set(OUTPUT ${UUID}.sec) ++ #set whilelist. default: /vendor/bin/teec_hello ++ set(WHITE_LIST_0 /vendor/bin/helloworld) ++ set(WHITE_LIST_OWNER root) ++ set(WHITE_LIST_1 /vendor/bin/secgear_helloworld) ++ set(WHITELIST WHITE_LIST_0 WHITE_LIST_1) ++ ++ set(AUTO_FILES ${CMAKE_CURRENT_BINARY_DIR}/${PREFIX}_t.h ${CMAKE_CURRENT_BINARY_DIR}/${PREFIX}_t.c ${CMAKE_CURRENT_BINARY_DIR}/${PREFIX}_args.h) ++ add_custom_command(OUTPUT ${AUTO_FILES} ++ DEPENDS ${CURRENT_ROOT_PATH}/${EDL_FILE} ++ COMMAND ${CODEGEN} --${CODETYPE} --trusted ${CURRENT_ROOT_PATH}/${EDL_FILE} --search-path ${LOCAL_ROOT_PATH}/inc/host_inc/gp) ++endif() ++ ++if(CC_SGX) ++ set(OUTPUT enclave.signed.so) ++ set(AUTO_FILES ${CMAKE_CURRENT_BINARY_DIR}/${PREFIX}_t.h ${CMAKE_CURRENT_BINARY_DIR}/${PREFIX}_t.c) ++ add_custom_command(OUTPUT ${AUTO_FILES} ++ DEPENDS ${CURRENT_ROOT_PATH}/${EDL_FILE} ++ COMMAND ${CODEGEN} --${CODETYPE} --trusted ${CURRENT_ROOT_PATH}/${EDL_FILE} --search-path ${LOCAL_ROOT_PATH}/inc/host_inc/sgx --search-path ${SGXSDK}/include) ++endif() ++ ++set(COMMON_C_FLAGS "-W -Wall -Werror -fno-short-enums -fno-omit-frame-pointer -fstack-protector \ ++ -Wstack-protector --param ssp-buffer-size=4 -frecord-gcc-switches -Wextra -nostdinc -nodefaultlibs \ ++ -fno-peephole -fno-peephole2 -Wno-main -Wno-error=unused-parameter \ ++ -Wno-error=unused-but-set-variable -Wno-error=format-truncation=") ++ ++set(COMMON_C_LINK_FLAGS "-Wl,-z,now -Wl,-z,relro -Wl,-z,noexecstack -Wl,-nostdlib -nodefaultlibs -nostartfiles") ++ ++if(CC_GP) ++ configure_file("${CMAKE_CURRENT_SOURCE_DIR}/manifest.txt.in" "${CMAKE_CURRENT_SOURCE_DIR}/manifest.txt") ++ ++ set(CMAKE_C_FLAGS "${COMMON_C_FLAGS} -march=armv8-a ") ++ set(CMAKE_C_FLAGS_RELEASE "${CMAKE_C_FLAGS} -s -fPIC") ++ set(CMAKE_SHARED_LINKER_FLAGS "${COMMON_C_LINK_FLAGS} -Wl,-s") ++ ++ set(ITRUSTEE_TEEDIR ${iTrusteeSDK}/) ++ set(ITRUSTEE_LIBC ${iTrusteeSDK}/thirdparty/open_source/musl/libc) ++ ++ if(${CMAKE_VERSION} VERSION_LESS "3.13.0") ++ link_directories(${CMAKE_BINARY_DIR}/lib/) ++ endif() ++ ++ add_library(${PREFIX} SHARED ${SOURCE_FILES} ${AUTO_FILES}) ++ ++ target_include_directories( ${PREFIX} PRIVATE ++ ${CMAKE_CURRENT_BINARY_DIR} ++ ${LOCAL_ROOT_PATH}/inc/host_inc ++ ${LOCAL_ROOT_PATH}/inc/host_inc/gp ++ ${LOCAL_ROOT_PATH}/inc/enclave_inc ++ ${LOCAL_ROOT_PATH}/inc/enclave_inc/gp ++ ${ITRUSTEE_TEEDIR}/include/TA ++ ${ITRUSTEE_TEEDIR}/include/TA/huawei_ext ++ ${ITRUSTEE_LIBC}/arch/aarch64 ++ ${ITRUSTEE_LIBC}/ ++ ${ITRUSTEE_LIBC}/arch/arm/bits ++ ${ITRUSTEE_LIBC}/arch/generic ++ ${ITRUSTEE_LIBC}/arch/arm ++ ${LOCAL_ROOT_PATH}/inc/enclave_inc/gp/itrustee) ++ ++ if(${CMAKE_VERSION} VERSION_GREATER_EQUAL "3.13.0") ++ target_link_directories(${PREFIX} PRIVATE ++ ${CMAKE_BINARY_DIR}/lib/) ++ endif() ++ ++ foreach(WHITE_LIST ${WHITELIST}) ++ add_definitions(-D${WHITE_LIST}="${${WHITE_LIST}}") ++ endforeach(WHITE_LIST) ++ add_definitions(-DWHITE_LIST_OWNER="${WHITE_LIST_OWNER}") ++ ++ target_link_libraries(${PREFIX} -lsecgear_tee) ++ ++ add_custom_command(TARGET ${PREFIX} ++ POST_BUILD ++ COMMAND bash ${SIGN_TOOL} -d sign -x trustzone -i ${CMAKE_LIBRARY_OUTPUT_DIRECTORY}/lib${PREFIX}.so -c ${CMAKE_CURRENT_SOURCE_DIR}/manifest.txt ++ -o ${CMAKE_LIBRARY_OUTPUT_DIRECTORY}/${OUTPUT}) ++ ++ install(FILES ${CMAKE_LIBRARY_OUTPUT_DIRECTORY}/${OUTPUT} ++ DESTINATION /data ++ PERMISSIONS OWNER_EXECUTE OWNER_WRITE OWNER_READ GROUP_READ GROUP_EXECUTE WORLD_READ WORLD_EXECUTE) ++ ++endif() ++ ++if(CC_SGX) ++ set(SGX_DIR ${SGXSDK}) ++ set(CMAKE_C_FLAGS "${COMMON_C_FLAGS} -m64 -fvisibility=hidden") ++ set(CMAKE_C_FLAGS_RELEASE "${CMAKE_C_FLAGS} -s") ++ set(LINK_LIBRARY_PATH ${SGX_DIR}/lib64) ++ ++ if(CC_SIM) ++ set(Trts_Library_Name sgx_trts_sim) ++ set(Service_Library_Name sgx_tservice_sim) ++ else() ++ set(Trts_Library_Name sgx_trts) ++ set(Service_Library_Name sgx_tservice) ++ endif() ++ ++ set(Crypto_Library_Name sgx_tcrypto) ++ ++ set(CMAKE_SHARED_LINKER_FLAGS "${COMMON_C_LINK_FLAGS} -Wl,-z,defs -Wl,-pie -Bstatic -Bsymbolic -eenclave_entry \ ++ -Wl,--export-dynamic -Wl,--defsym,__ImageBase=0 -Wl,--gc-sections -Wl,--version-script=${CMAKE_CURRENT_SOURCE_DIR}/Enclave.lds") ++ ++ if(${CMAKE_VERSION} VERSION_LESS "3.13.0") ++ link_directories(${LINK_LIBRARY_PATH}) ++ endif() ++ ++ add_library(${PREFIX} SHARED ${SOURCE_FILES} ${AUTO_FILES}) ++ ++ target_include_directories(${PREFIX} PRIVATE ++ ${CMAKE_CURRENT_BINARY_DIR} ++ ${SGX_DIR}/include/tlibc ++ ${SGX_DIR}/include/libcxx ++ ${SGX_DIR}/include ++ ${LOCAL_ROOT_PATH}/inc/host_inc ++ ${LOCAL_ROOT_PATH}/inc/host_inc/sgx) ++ ++ if(${CMAKE_VERSION} VERSION_GREATER_EQUAL "3.13.0") ++ target_link_directories(${PREFIX} PRIVATE ++ ${LINK_LIBRARY_PATH}) ++ endif() ++ ++ target_link_libraries(${PREFIX} -Wl,--whole-archive ${Trts_Library_Name} -Wl,--no-whole-archive ++ -Wl,--start-group -lsgx_tstdc -lsgx_tcxx -l${Crypto_Library_Name} -l${Service_Library_Name} -Wl,--end-group) ++ add_custom_command(TARGET ${PREFIX} ++ POST_BUILD ++ COMMAND umask 0177 ++ COMMAND openssl genrsa -3 -out ${PEM} 3072 ++ COMMAND bash ${SIGN_TOOL} -d sign -x sgx -i ${CMAKE_LIBRARY_OUTPUT_DIRECTORY}/lib${PREFIX}.so -k ${PEM} -o ${OUTPUT} -c ${CMAKE_CURRENT_SOURCE_DIR}/Enclave.config.xml) ++endif() ++ ++set_target_properties(${PREFIX} PROPERTIES SKIP_BUILD_RPATH TRUE) +diff --git a/examples/lrt/enclave/Enclave.config.xml b/examples/lrt/enclave/Enclave.config.xml +new file mode 100644 +index 0000000..e94c9bc +--- /dev/null ++++ b/examples/lrt/enclave/Enclave.config.xml +@@ -0,0 +1,12 @@ ++ ++ 0 ++ 0 ++ 0x40000 ++ 0x100000 ++ 10 ++ 1 ++ ++ 0 ++ 0 ++ 0xFFFFFFFF ++ +diff --git a/examples/lrt/enclave/Enclave.lds b/examples/lrt/enclave/Enclave.lds +new file mode 100644 +index 0000000..ab77e64 +--- /dev/null ++++ b/examples/lrt/enclave/Enclave.lds +@@ -0,0 +1,11 @@ ++enclave.so ++{ ++ global: ++ g_global_data_sim; ++ g_global_data; ++ enclave_entry; ++ g_peak_heap_used; ++ local: ++ *; ++}; ++ +diff --git a/examples/lrt/enclave/lrt.c b/examples/lrt/enclave/lrt.c +new file mode 100644 +index 0000000..982e50c +--- /dev/null ++++ b/examples/lrt/enclave/lrt.c +@@ -0,0 +1,23 @@ ++/* ++ * Copyright (c) Huawei Technologies Co., Ltd. 2020. All rights reserved. ++ * secGear is licensed under the Mulan PSL v2. ++ * You can use this software according to the terms and conditions of the Mulan PSL v2. ++ * You may obtain a copy of Mulan PSL v2 at: ++ * http://license.coscl.org.cn/MulanPSL2 ++ * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR ++ * IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR ++ * PURPOSE. ++ * See the Mulan PSL v2 for more details. ++ */ ++ ++#include ++#include ++#include "lrt_t.h" ++ ++#define TA_HELLO_WORLD "Secgear Long Running Task!" ++#define BUF_MAX 32 ++int get_string(char *buf) ++{ ++ strncpy(buf, TA_HELLO_WORLD, strlen(TA_HELLO_WORLD) + 1); ++ return 0; ++} +diff --git a/examples/lrt/enclave/manifest.txt.in b/examples/lrt/enclave/manifest.txt.in +new file mode 100644 +index 0000000..7b8ecf5 +--- /dev/null ++++ b/examples/lrt/enclave/manifest.txt.in +@@ -0,0 +1,8 @@ ++gpd.ta.appID: @UUID@ ++gpd.ta.service_name: test0108 ++gpd.ta.singleInstance: true ++gpd.ta.multiSession: false ++gpd.ta.multiCommand: false ++gpd.ta.instanceKeepAlive: false ++gpd.ta.dataSize: 16384 ++gpd.ta.stackSize: 20480 +diff --git a/examples/lrt/host/CMakeLists.txt b/examples/lrt/host/CMakeLists.txt +new file mode 100644 +index 0000000..13f891a +--- /dev/null ++++ b/examples/lrt/host/CMakeLists.txt +@@ -0,0 +1,85 @@ ++# Copyright (c) Huawei Technologies Co., Ltd. 2020. All rights reserved. ++# secGear is licensed under the Mulan PSL v2. ++# You can use this software according to the terms and conditions of the Mulan PSL v2. ++# You may obtain a copy of Mulan PSL v2 at: ++# http://license.coscl.org.cn/MulanPSL2 ++# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR ++# IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR ++# PURPOSE. ++# See the Mulan PSL v2 for more details. ++ ++#set auto code prefix ++set(PREFIX lrt) ++#set host exec name ++set(OUTPUT secgear_lrt) ++#set host src code ++set(SOURCE_FILE ${CMAKE_CURRENT_SOURCE_DIR}/main.c) ++ ++#set auto code ++if(CC_GP) ++ set(AUTO_FILES ${CMAKE_CURRENT_BINARY_DIR}/${PREFIX}_u.h ${CMAKE_CURRENT_BINARY_DIR}/${PREFIX}_u.c ${CMAKE_CURRENT_BINARY_DIR}/${PREFIX}_args.h) ++ add_custom_command(OUTPUT ${AUTO_FILES} ++ DEPENDS ${CURRENT_ROOT_PATH}/${EDL_FILE} ++ COMMAND ${CODEGEN} --${CODETYPE} --untrusted ${CURRENT_ROOT_PATH}/${EDL_FILE} --search-path ${LOCAL_ROOT_PATH}/inc/host_inc/gp) ++endif() ++ ++if(CC_SGX) ++ set(AUTO_FILES ${CMAKE_CURRENT_BINARY_DIR}/${PREFIX}_u.h ${CMAKE_CURRENT_BINARY_DIR}/${PREFIX}_u.c) ++ add_custom_command(OUTPUT ${AUTO_FILES} ++ DEPENDS ${CURRENT_ROOT_PATH}/${EDL_FILE} ++ COMMAND ${CODEGEN} --${CODETYPE} --untrusted ${CURRENT_ROOT_PATH}/${EDL_FILE} --search-path ${LOCAL_ROOT_PATH}/inc/host_inc/sgx --search-path ${SGXSDK}/include) ++endif() ++ ++set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -fPIE") ++set(CMAKE_C_FLAGS_RELEASE "${CMAKE_C_FLAGS} -s") ++ ++if(CC_GP) ++ if(${CMAKE_VERSION} VERSION_LESS "3.13.0") ++ link_directories(${CMAKE_LIBRARY_OUTPUT_DIRECTORY}) ++ endif() ++ add_executable(${OUTPUT} ${SOURCE_FILE} ${AUTO_FILES}) ++ target_include_directories(${OUTPUT} PRIVATE ++ ${LOCAL_ROOT_PATH}/inc/host_inc ++ ${LOCAL_ROOT_PATH}/inc/host_inc/gp ++ ${CMAKE_CURRENT_BINARY_DIR}) ++ if(${CMAKE_VERSION} VERSION_GREATER_EQUAL "3.13.0") ++ target_link_directories(${OUTPUT} PRIVATE ${CMAKE_LIBRARY_OUTPUT_DIRECTORY}) ++ endif() ++endif() ++ ++if(CC_SGX) ++ if(${CMAKE_VERSION} VERSION_LESS "3.13.0") ++ link_directories(${CMAKE_LIBRARY_OUTPUT_DIRECTORY}) ++ endif() ++ add_executable(${OUTPUT} ${SOURCE_FILE} ${AUTO_FILES}) ++ target_include_directories(${OUTPUT} PRIVATE ++ ${LOCAL_ROOT_PATH}/inc/host_inc ++ ${LOCAL_ROOT_PATH}/inc/host_inc/sgx ++ ${CMAKE_CURRENT_BINARY_DIR}) ++ if(${CMAKE_VERSION} VERSION_GREATER_EQUAL "3.13.0") ++ target_link_directories(${OUTPUT} PRIVATE ${CMAKE_LIBRARY_OUTPUT_DIRECTORY}) ++ endif() ++endif() ++ ++if(CC_SIM) ++ target_link_libraries(${OUTPUT} secgearsim) ++else() ++ target_link_libraries(${OUTPUT} secgear) ++endif() ++set_target_properties(${OUTPUT} PROPERTIES SKIP_BUILD_RPATH TRUE) ++ ++if(CC_GP) ++ #itrustee install whitelist /vender/bin/teec_hello ++ install(TARGETS ${OUTPUT} ++ RUNTIME ++ DESTINATION /vendor/bin/ ++ PERMISSIONS OWNER_EXECUTE OWNER_WRITE OWNER_READ) ++endif() ++ ++if(CC_SGX) ++ install(TARGETS ${OUTPUT} ++ RUNTIME ++ DESTINATION ${CMAKE_BINARY_DIR}/bin/ ++ PERMISSIONS OWNER_EXECUTE OWNER_WRITE OWNER_READ) ++endif() ++ +diff --git a/examples/lrt/host/main.c b/examples/lrt/host/main.c +new file mode 100644 +index 0000000..ba078c7 +--- /dev/null ++++ b/examples/lrt/host/main.c +@@ -0,0 +1,70 @@ ++/* ++ * Copyright (c) Huawei Technologies Co., Ltd. 2020. All rights reserved. ++ * secGear is licensed under the Mulan PSL v2. ++ * You can use this software according to the terms and conditions of the Mulan PSL v2. ++ * You may obtain a copy of Mulan PSL v2 at: ++ * http://license.coscl.org.cn/MulanPSL2 ++ * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR ++ * IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR ++ * PURPOSE. ++ * See the Mulan PSL v2 for more details. ++ */ ++ ++#include ++#include ++#include ++#include "enclave.h" ++#include "lrt_u.h" ++ ++#define BUF_LEN 32 ++ ++int main() ++{ ++ int retval = 0; ++ char *path = PATH; ++ char buf[BUF_LEN]; ++ cc_enclave_t *context = NULL; ++ cc_enclave_result_t res; ++ ++ printf("Create secgear enclave\n"); ++ ++ char real_p[PATH_MAX]; ++ /* check file exists, if not exist then use absolute path */ ++ if (realpath(path, real_p) == NULL) { ++ if (getcwd(real_p, sizeof(real_p)) == NULL) { ++ printf("Cannot find enclave.sign.so"); ++ return -1; ++ } ++ if (PATH_MAX - strlen(real_p) <= strlen("/enclave.signed.so")) { ++ printf("Failed to strcat enclave.sign.so path"); ++ return -1; ++ } ++ (void)strcat(real_p, "/enclave.signed.so"); ++ } ++ ++ res = cc_enclave_create(real_p, AUTO_ENCLAVE_TYPE, 0, SECGEAR_DEBUG_FLAG, NULL, 0, &context); ++ if (res != CC_SUCCESS) { ++ printf("Create enclave error\n"); ++ return res; ++ } ++ ++ while(true) { ++ res = get_string(context, &retval, buf); ++ if (res != CC_SUCCESS || retval != (int)CC_SUCCESS) { ++ printf("Ecall enclave error\n"); ++ goto out; ++ } else { ++ printf("%s\n", buf); ++ } ++ sleep(1); ++ } ++ ++out: ++ if (context != NULL) { ++ res = cc_enclave_destroy(context); ++ if(res != CC_SUCCESS) { ++ printf("Destroy enclave error\n"); ++ } ++ } ++ return res; ++} +diff --git a/examples/lrt/lrt.edl b/examples/lrt/lrt.edl +new file mode 100644 +index 0000000..73dc375 +--- /dev/null ++++ b/examples/lrt/lrt.edl +@@ -0,0 +1,19 @@ ++/* ++ * Copyright (c) Huawei Technologies Co., Ltd. 2020. All rights reserved. ++ * secGear is licensed under the Mulan PSL v2. ++ * You can use this software according to the terms and conditions of the Mulan PSL v2. ++ * You may obtain a copy of Mulan PSL v2 at: ++ * http://license.coscl.org.cn/MulanPSL2 ++ * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR ++ * IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR ++ * PURPOSE. ++ * See the Mulan PSL v2 for more details. ++ */ ++ ++enclave { ++ include "secgear_urts.h" ++ from "secgear_tstdc.edl" import *; ++ trusted { ++ public int get_string([out, size=32]char *buf); ++ }; ++}; +-- +2.27.0 + diff --git a/0026-example-add-Dockerfile-to-build-lrt-example-image.patch b/0026-example-add-Dockerfile-to-build-lrt-example-image.patch new file mode 100644 index 0000000..a2d9d96 --- /dev/null +++ b/0026-example-add-Dockerfile-to-build-lrt-example-image.patch @@ -0,0 +1,172 @@ +From 2f5b3b98d7c4705ef761e9898116b2206b7c6729 Mon Sep 17 00:00:00 2001 +From: Li Feng +Date: Tue, 13 Apr 2021 07:59:54 +0000 +Subject: [PATCH 09/14] example: add Dockerfile to build lrt example image + +Signed-off-by: Li Feng +--- + examples/lrt/Dockerfile | 33 +++++++++++++++++++ + examples/lrt/device_plugin.yaml | 57 +++++++++++++++++++++++++++++++++ + examples/lrt/enclave.yaml | 46 ++++++++++++++++++++++++++ + 3 files changed, 136 insertions(+) + create mode 100644 examples/lrt/Dockerfile + create mode 100644 examples/lrt/device_plugin.yaml + create mode 100644 examples/lrt/enclave.yaml + +diff --git a/examples/lrt/Dockerfile b/examples/lrt/Dockerfile +new file mode 100644 +index 0000000..dadf2b7 +--- /dev/null ++++ b/examples/lrt/Dockerfile +@@ -0,0 +1,33 @@ ++# Copyright (c) Huawei Technologies Co., Ltd. 2020. All rights reserved. ++# secGear is licensed under the Mulan PSL v2. ++# You can use this software according to the terms and conditions of the Mulan PSL v2. ++# You may obtain a copy of Mulan PSL v2 at: ++# http://license.coscl.org.cn/MulanPSL2 ++# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR ++# IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR ++# PURPOSE. ++# See the Mulan PSL v2 for more details. ++ ++# steps to build example image: ++# 1. build the secGear project at host ++# # cd secGear/ ++# # source environment ++# # source /opt/intel/sgxsdk/environment ++# # mkdir debug && cd debug ++# # cmake -DCMAKE_BUILD_TYPE=Debug -DCC_SGX=ON -DSGXSDK=/opt/intel/sgxsdk .. ++# # make ++# 2. build the example image ++# # cd ../examples/lrt/ ++# # docker build -t secgear_hello -f ./Dockerfile ../../ ++ ++ ++FROM hub.oepkgs.net/lifeng2221dd1/sgx_base_hw:latest ++ ++COPY debug/lib/sgx/libsgx_0.so /lib64/ ++COPY debug/lib/libsecgear.so /usr/lib/ ++COPY debug/examples/lrt/host/secgear_lrt /home/ ++COPY debug/examples/lrt/enclave/enclave.signed.so /home/ ++ ++WORKDIR /home ++ ++ENTRYPOINT ["/home/secgear_lrt"] +diff --git a/examples/lrt/device_plugin.yaml b/examples/lrt/device_plugin.yaml +new file mode 100644 +index 0000000..9a470da +--- /dev/null ++++ b/examples/lrt/device_plugin.yaml +@@ -0,0 +1,57 @@ ++# Copyright (c) Huawei Technologies Co., Ltd. 2020. All rights reserved. ++# secGear is licensed under the Mulan PSL v2. ++# You can use this software according to the terms and conditions of the Mulan PSL v2. ++# You may obtain a copy of Mulan PSL v2 at: ++# http://license.coscl.org.cn/MulanPSL2 ++# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR ++# IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR ++# PURPOSE. ++# See the Mulan PSL v2 for more details. ++# steps to deploy device plugin: ++# # cd secGear/ ++# # cd ./examples/lrt/ ++# # kubectl apply -f ./device_plugin.yaml ++ ++apiVersion: apps/v1 ++kind: DaemonSet ++metadata: ++ name: sgx-device-plugin-ds ++ namespace: kube-system ++spec: ++ selector: ++ matchLabels: ++ k8s-app: sgx-device-plugin ++ template: ++ metadata: ++ annotations: ++ scheduler.alpha.kubernetes.io/critical-pod: "" ++ labels: ++ k8s-app: sgx-device-plugin ++ spec: ++ containers: ++ - image: hub.oepkgs.net/lifeng2221dd1/hw-ali-device-plugin:devel ++ imagePullPolicy: IfNotPresent ++ name: sgx-device-plugin ++ securityContext: ++ allowPrivilegeEscalation: false ++ capabilities: ++ drop: ++ - ALL ++ volumeMounts: ++ - mountPath: /var/lib/kubelet/device-plugins ++ name: device-plugin ++ - mountPath: /dev ++ name: dev ++ tolerations: ++ - effect: NoSchedule ++ key: alibabacloud.com/sgx_epc_MiB ++ operator: Exists ++ volumes: ++ - hostPath: ++ path: /var/lib/kubelet/device-plugins ++ type: DirectoryOrCreate ++ name: device-plugin ++ - hostPath: ++ path: /dev ++ type: Directory ++ name: dev +diff --git a/examples/lrt/enclave.yaml b/examples/lrt/enclave.yaml +new file mode 100644 +index 0000000..8efdada +--- /dev/null ++++ b/examples/lrt/enclave.yaml +@@ -0,0 +1,46 @@ ++# Copyright (c) Huawei Technologies Co., Ltd. 2020. All rights reserved. ++# secGear is licensed under the Mulan PSL v2. ++# You can use this software according to the terms and conditions of the Mulan PSL v2. ++# You may obtain a copy of Mulan PSL v2 at: ++# http://license.coscl.org.cn/MulanPSL2 ++# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR ++# IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR ++# PURPOSE. ++# See the Mulan PSL v2 for more details. ++# steps to deploy device plugin: ++# # cd secGear/ ++# # cd ./examples/lrt/ ++# # kubectl apply -f ./enclave.yaml ++apiVersion: apps/v1 ++kind: Deployment ++metadata: ++ name: helloworld ++ namespace: default ++spec: ++ replicas: 2 ++ selector: ++ matchLabels: ++ app: helloworld ++ template: ++ metadata: ++ labels: ++ app: helloworld ++ spec: ++ containers: ++ - name: hell_lifeng ++ image: secgear_hello ++ imagePullPolicy: IfNotPresent ++ name: helloworld ++ resources: ++ limits: ++ cpu: 250m ++ memory: 512Mi ++ alibabacloud.com/sgx_epc_MiB: 2 ++ volumeMounts: ++ - mountPath: /var/run/aesmd/aesm.socket ++ name: aesmsocket ++ volumes: ++ - hostPath: ++ path: /var/run/aesmd/aesm.socket ++ type: Socket ++ name: aesmsocket +-- +2.27.0 + diff --git a/0027-Change-to-use-the-milestone-picture-with-English.patch b/0027-Change-to-use-the-milestone-picture-with-English.patch new file mode 100644 index 0000000..323a4ee --- /dev/null +++ b/0027-Change-to-use-the-milestone-picture-with-English.patch @@ -0,0 +1,29 @@ +From 4fe112079e599cf779dacde08181f22ad62ede51 Mon Sep 17 00:00:00 2001 +From: blue +Date: Thu, 29 Apr 2021 20:53:21 +0800 +Subject: [PATCH 10/14] Change to use the milestone picture with English + +--- + README.en.md | 4 ++-- + 1 file changed, 2 insertions(+), 2 deletions(-) + +diff --git a/README.en.md b/README.en.md +index 4df13b0..aa8c4a8 100644 +--- a/README.en.md ++++ b/README.en.md +@@ -1,4 +1,4 @@ +-secGear ++secGear + + secGear + ============================ +@@ -502,5 +502,5 @@ secGear introduce the signing tool to sign the enclave. + + Milestone + --------- +-secGear ++secGear + +-- +2.27.0 + diff --git a/0028-example-use-the-sgx-device-plugin-from-intel.patch b/0028-example-use-the-sgx-device-plugin-from-intel.patch new file mode 100644 index 0000000..160f440 --- /dev/null +++ b/0028-example-use-the-sgx-device-plugin-from-intel.patch @@ -0,0 +1,73 @@ +From 3af4a40bef20df36ece7f7f87c44eccf8a8b3a60 Mon Sep 17 00:00:00 2001 +From: Li Feng +Date: Mon, 17 May 2021 10:21:32 +0800 +Subject: [PATCH 11/14] example: use the sgx device plugin from intel + +deployment: +1. kubectl apply -f ./examples/lrt/device_plugin.yaml +2. kubectl apply -f ./examples/lrt/enclave.yaml +3. kubectl get pods -A + +NAMESPACE NAME READY STATUS RESTARTS AGE +default helloworld-d75bf5f9f-wgdf7 1/1 Running 0 36m +default helloworld-d75bf5f9f-xthkk 1/1 Running 0 36m +kube-system calico-kube-controllers-6d7b4db76c-7t8lv 1/1 Running 1 42h +kube-system calico-node-kcxd7 1/1 Running 1 42h +kube-system coredns-6d56c8448f-ctf7m 1/1 Running 1 42h +kube-system coredns-6d56c8448f-k7z5c 1/1 Running 1 42h +kube-system etcd-lifeng 1/1 Running 2 2d +kube-system kube-apiserver-lifeng 1/1 Running 4 2d +kube-system kube-controller-manager-lifeng 1/1 Running 2 2d +kube-system kube-proxy-xvvz5 1/1 Running 2 2d +kube-system kube-scheduler-lifeng 1/1 Running 2 2d +kube-system sgx-device-plugin-ds-4sbhk 1/1 Running 0 4m + +Signed-off-by: Li Feng +--- + CMakeLists.txt | 2 +- + examples/lrt/device_plugin.yaml | 2 +- + examples/lrt/enclave.yaml | 2 +- + 3 files changed, 3 insertions(+), 3 deletions(-) + +diff --git a/CMakeLists.txt b/CMakeLists.txt +index 1d036ea..3886316 100644 +--- a/CMakeLists.txt ++++ b/CMakeLists.txt +@@ -58,7 +58,7 @@ if(CC_SGX) + add_subdirectory(${LOCAL_ROOT_PATH}/examples/helloworld) + add_subdirectory(${LOCAL_ROOT_PATH}/examples/seal_data) + # add_subdirectory(${LOCAL_ROOT_PATH}/examples/tls_enclave) +-# add_subdirectory(${LOCAL_ROOT_PATH}/examples/lrt) ++ add_subdirectory(${LOCAL_ROOT_PATH}/examples/lrt) + endif() + + install(FILES ${LOCAL_ROOT_PATH}/conf/logrotate.d/secgear +diff --git a/examples/lrt/device_plugin.yaml b/examples/lrt/device_plugin.yaml +index 9a470da..ce8724d 100644 +--- a/examples/lrt/device_plugin.yaml ++++ b/examples/lrt/device_plugin.yaml +@@ -29,7 +29,7 @@ spec: + k8s-app: sgx-device-plugin + spec: + containers: +- - image: hub.oepkgs.net/lifeng2221dd1/hw-ali-device-plugin:devel ++ - image: hub.oepkgs.net/lifeng2221dd1/intel-sgx-device-plugin-hw:isgx + imagePullPolicy: IfNotPresent + name: sgx-device-plugin + securityContext: +diff --git a/examples/lrt/enclave.yaml b/examples/lrt/enclave.yaml +index 8efdada..b1bc19b 100644 +--- a/examples/lrt/enclave.yaml ++++ b/examples/lrt/enclave.yaml +@@ -35,7 +35,7 @@ spec: + limits: + cpu: 250m + memory: 512Mi +- alibabacloud.com/sgx_epc_MiB: 2 ++ sgx.intel.com/huawei_sgx_epc_MiB: 2 + volumeMounts: + - mountPath: /var/run/aesmd/aesm.socket + name: aesmsocket +-- +2.27.0 + diff --git a/0029-some-adaptations-for-trustzone.patch b/0029-some-adaptations-for-trustzone.patch new file mode 100644 index 0000000..90b5113 --- /dev/null +++ b/0029-some-adaptations-for-trustzone.patch @@ -0,0 +1,2159 @@ +From 45cf3b4bb86d5dc9d149f5e6056e9b2cb27eff63 Mon Sep 17 00:00:00 2001 +From: zgzxx +Date: Tue, 18 May 2021 14:27:31 +0800 +Subject: [PATCH 12/14] some adaptations for trustzone + +--- + CMakeLists.txt | 11 +- + README.en.md | 2 +- + README.md | 2 +- + docs/sign_tool.md | 19 +- + examples/CMakeLists.txt | 28 ++ + examples/helloworld/CMakeLists.txt | 3 +- + examples/helloworld/enclave/CMakeLists.txt | 16 +- + examples/helloworld/enclave/config_cloud.ini | 49 ++ + examples/helloworld/enclave/manifest.txt | 7 + + examples/helloworld/enclave/manifest.txt.in | 8 - + examples/helloworld/host/CMakeLists.txt | 7 +- + examples/helloworld/host/main.c | 1 + + examples/seal_data/CMakeLists.txt | 4 +- + examples/seal_data/enclave/CMakeLists.txt | 19 +- + examples/seal_data/enclave/config_cloud.ini | 49 ++ + examples/seal_data/enclave/manifest.txt | 7 + + examples/seal_data/enclave/manifest.txt.in | 8 - + examples/seal_data/host/CMakeLists.txt | 1 + + .../gp/itrustee/itrustee_seal_data.c | 3 +- + src/host_src/gp/CMakeLists.txt | 4 +- + src/host_src/gp/gp_enclave.c | 4 +- + .../{ => cloud}/rsa_public_key_cloud.pem | 0 + tools/sign_tool/generate_signature.py | 56 +++ + tools/sign_tool/manifest.py | 170 ++++--- + tools/sign_tool/sign_tool.py | 471 ------------------ + tools/sign_tool/sign_tool.sh | 141 ++---- + tools/sign_tool/signtool_v3.py | 428 ++++++++++++++++ + 27 files changed, 802 insertions(+), 716 deletions(-) + create mode 100644 examples/CMakeLists.txt + create mode 100644 examples/helloworld/enclave/config_cloud.ini + create mode 100644 examples/helloworld/enclave/manifest.txt + delete mode 100644 examples/helloworld/enclave/manifest.txt.in + create mode 100644 examples/seal_data/enclave/config_cloud.ini + create mode 100644 examples/seal_data/enclave/manifest.txt + delete mode 100644 examples/seal_data/enclave/manifest.txt.in + rename tools/sign_tool/{ => cloud}/rsa_public_key_cloud.pem (100%) + create mode 100644 tools/sign_tool/generate_signature.py + delete mode 100644 tools/sign_tool/sign_tool.py + create mode 100644 tools/sign_tool/signtool_v3.py + +diff --git a/CMakeLists.txt b/CMakeLists.txt +index 3886316..b373328 100644 +--- a/CMakeLists.txt ++++ b/CMakeLists.txt +@@ -49,17 +49,8 @@ add_subdirectory(src) + + execute_process(COMMAND mkdir ${LOCAL_ROOT_PATH}/bin) + +-if(CC_GP) +- add_subdirectory(${LOCAL_ROOT_PATH}/examples/seal_data) +- add_subdirectory(${LOCAL_ROOT_PATH}/examples/helloworld) +-endif() ++add_subdirectory(examples) + +-if(CC_SGX) +- add_subdirectory(${LOCAL_ROOT_PATH}/examples/helloworld) +- add_subdirectory(${LOCAL_ROOT_PATH}/examples/seal_data) +-# add_subdirectory(${LOCAL_ROOT_PATH}/examples/tls_enclave) +- add_subdirectory(${LOCAL_ROOT_PATH}/examples/lrt) +-endif() + + install(FILES ${LOCAL_ROOT_PATH}/conf/logrotate.d/secgear + DESTINATION /etc/logrotate.d/) +diff --git a/README.en.md b/README.en.md +index aa8c4a8..8aaa1b0 100644 +--- a/README.en.md ++++ b/README.en.md +@@ -335,7 +335,7 @@ so -nostdinc -nodefaultlibs -nostdlib -nodefaultlibs compile link options was in + + add_custom_command(TARGET ${PREFIX} + POST_BUILD +- COMMAND bash ${SIGN_TOOL} -d sign -x trustzone -i lib${PREFIX}.so -c ${CMAKE_CURRENT_SOURCE_DIR}/manifest.txt ++ COMMAND bash ${SIGN_TOOL} -d sign -x trustzone -i lib${PREFIX}.so -c ${CMAKE_CURRENT_SOURCE_DIR}/manifest.txt -m ${CMAKE_CURRENT_SOURCE_DIR}/config_cloud.ini + -o ${CMAKE_CURRENT_BINARY_DIR}/${OUTPUT}) + + install(FILES ${CMAKE_CURRENT_BINARY_DIR}/${OUTPUT} +diff --git a/README.md b/README.md +index a90450b..b95dcc9 100644 +--- a/README.md ++++ b/README.md +@@ -315,7 +315,7 @@ AUTO_FILES:由edl文件生成的安全侧二进制文件 + + add_custom_command(TARGET ${PREFIX} + POST_BUILD +- COMMAND bash ${SIGN_TOOL} -d sign -x trustzone -i lib${PREFIX}.so -c ${CMAKE_CURRENT_SOURCE_DIR}/manifest.txt ++ COMMAND bash ${SIGN_TOOL} -d sign -x trustzone -i lib${PREFIX}.so -c ${CMAKE_CURRENT_SOURCE_DIR}/manifest.txt -m ${CMAKE_CURRENT_SOURCE_DIR}/config_cloud.ini + -o ${CMAKE_CURRENT_BINARY_DIR}/${OUTPUT}) + + install(FILES ${CMAKE_CURRENT_BINARY_DIR}/${OUTPUT} +diff --git a/docs/sign_tool.md b/docs/sign_tool.md +index ccaa2e6..399e4c5 100644 +--- a/docs/sign_tool.md ++++ b/docs/sign_tool.md +@@ -13,38 +13,37 @@ The tool supports the following two modes: + + For example: + +- `$ ./sign_tool.sh –d sign –x trustzone –i test.enclave -c manifest.txt –o signed.enclave ` ++ `$ ./sign_tool.sh –d sign –x trustzone –i test.enclave -c manifest.txt -m config_cloud.ini –o signed.enclave ` + + + - two-step method, it is used when the signature needs to be obtained from the signing organization or the private key is stored on another secure platform. + + For example: + (1) generate the digest value. +- `$ ./sign_tool.sh –d digest –x trustzone –i input -c manifest.txt –o digest.data ` ++ `$ ./sign_tool.sh –d digest –x trustzone –i input -c manifest.txt -m config_cloud.ini –o digest.data ` + + For trustzone, temporary files KeyInfo.enc, rawData.enc, and rawDataHash.bin are generated in the current directory. And for sgx, a temporary file signdata is generated in the current directory. The temporary file is required when generating the signed enclave in step 3 and is deleted after the signed enclave is generated. + + (2) send the digest.data to the signing organization or platform and get the signature. + + (3) use the signature to generate the signed enclave. +- `$ ./sign_tool.sh –d sign –x trustzone –i input -c manifest.txt –p pub.pem –s signature –o signed.enclave ` ++ `$ ./sign_tool.sh –d sign –x trustzone –i input -c manifest.txt -m config_cloud.ini –s signature –o signed.enclave ` + + ## sign_tool.sh parameter + + ``` +- -a API_LEVEL, indicates trustzone GP API version, defalut is 1. + -c basic config file. + -d sign tool command, sign/digest. + The sign command is used to generate a signed enclave. + The digest command is used to generate a digest value. +- -f OTRP_FLAG, indicates whether the OTRP standard protocol is supported, default is 0. + -i enclave to be signed. +- -k private key required for single-step method, required when trustzone TA_TYPE is 2 or sgx. +- -m additional config for trustzone when TA_TYPE is 2. +- -o output parameters, the sign command outputs sigend enclave, the digest command outputs digest value. ++ -k private key required for single-step method ++ -m additional config_cloud.ini for trustzone. ++ -o output parameters, the sign command outputs sigend enclave, the digest command outputs ++ digest value. + -p signing server public key certificate, required for two-step method. +- -s the signed digest value required for two-step method, this parameter is empty to indicate single-step method. +- -t trustzone TA_TYPE, default is 1. ++ -s the signed digest value required for two-step method, this parameter is empty to indicate ++ single-step method. + -x enclave type, sgx or trustzone. + -h printf help message. + ``` +diff --git a/examples/CMakeLists.txt b/examples/CMakeLists.txt +new file mode 100644 +index 0000000..cfd0171 +--- /dev/null ++++ b/examples/CMakeLists.txt +@@ -0,0 +1,28 @@ ++add_custom_target(copy ALL ++ COMMAND mkdir -p ${CMAKE_BINARY_DIR}/inc/secGear ++ COMMAND cp ${LOCAL_ROOT_PATH}/inc/host_inc/*.h ${CMAKE_BINARY_DIR}/inc/secGear/ ++ COMMAND cp ${LOCAL_ROOT_PATH}/inc/enclave_inc/*.h ${CMAKE_BINARY_DIR}/inc/secGear/) ++ ++if(CC_GP) ++ add_custom_command(TARGET copy ++ POST_BUILD ++ COMMAND cp ${LOCAL_ROOT_PATH}/inc/host_inc/gp/*.edl ${CMAKE_BINARY_DIR}/inc/secGear/ ++ COMMAND cp ${LOCAL_ROOT_PATH}/inc/host_inc/gp/*.h ${CMAKE_BINARY_DIR}/inc/secGear/ ++ COMMAND cp ${LOCAL_ROOT_PATH}/inc/enclave_inc/gp/*.h ${CMAKE_BINARY_DIR}/inc/secGear/ ++ COMMAND cp ${LOCAL_ROOT_PATH}/inc/enclave_inc/gp/itrustee/*.h ${CMAKE_BINARY_DIR}/inc/secGear/) ++ add_subdirectory(seal_data) ++ add_subdirectory(helloworld) ++endif() ++ ++if(CC_SGX) ++ add_custom_command(TARGET copy ++ POST_BUILD ++ COMMAND cp ${LOCAL_ROOT_PATH}/inc/host_inc/sgx/*.h ${CMAKE_BINARY_DIR}/inc/secGear/ ++ COMMAND cp ${LOCAL_ROOT_PATH}/inc/host_inc/sgx/*.edl ${CMAKE_BINARY_DIR}/inc/secGear/ ++ COMMAND cp ${LOCAL_ROOT_PATH}/inc/enclave_inc/sgx/*.h ${CMAKE_BINARY_DIR}/inc/secGear/) ++ add_subdirectory(seal_data) ++ add_subdirectory(helloworld) ++ #add_subdirectory(tls_enclave) ++ #add_subdirectory(lrt) ++endif() ++ +diff --git a/examples/helloworld/CMakeLists.txt b/examples/helloworld/CMakeLists.txt +index 5da2a6b..843a573 100644 +--- a/examples/helloworld/CMakeLists.txt ++++ b/examples/helloworld/CMakeLists.txt +@@ -20,8 +20,7 @@ set(CODEGEN codegen) + + if(CC_GP) + set(CODETYPE trustzone) +- execute_process(COMMAND uuidgen -r OUTPUT_VARIABLE UUID) +- string(REPLACE "\n" "" UUID ${UUID}) ++ set(UUID f68fd704-6eb1-4d14-b218-722850eb3ef0) + add_definitions(-DPATH="/data/${UUID}.sec") + endif() + +diff --git a/examples/helloworld/enclave/CMakeLists.txt b/examples/helloworld/enclave/CMakeLists.txt +index 0aefdae..f7967ef 100644 +--- a/examples/helloworld/enclave/CMakeLists.txt ++++ b/examples/helloworld/enclave/CMakeLists.txt +@@ -55,7 +55,6 @@ set(COMMON_C_FLAGS "-W -Wall -Werror -fno-short-enums -fno-omit-frame-pointer + set(COMMON_C_LINK_FLAGS "-Wl,-z,now -Wl,-z,relro -Wl,-z,noexecstack -Wl,-nostdlib -nodefaultlibs -nostartfiles") + + if(CC_GP) +- configure_file("${CMAKE_CURRENT_SOURCE_DIR}/manifest.txt.in" "${CMAKE_CURRENT_SOURCE_DIR}/manifest.txt") + + set(CMAKE_C_FLAGS "${COMMON_C_FLAGS} -march=armv8-a ") + set(CMAKE_C_FLAGS_RELEASE "${CMAKE_C_FLAGS} -s -fPIC") +@@ -72,6 +71,7 @@ if(CC_GP) + + target_include_directories( ${PREFIX} PRIVATE + ${CMAKE_CURRENT_BINARY_DIR} ++ ${LOCAL_ROOT_PATH}/debug/inc + ${LOCAL_ROOT_PATH}/inc/host_inc + ${LOCAL_ROOT_PATH}/inc/host_inc/gp + ${LOCAL_ROOT_PATH}/inc/enclave_inc +@@ -97,14 +97,14 @@ if(CC_GP) + + target_link_libraries(${PREFIX} -lsecgear_tee) + +- add_custom_command(TARGET ${PREFIX} +- POST_BUILD +- COMMAND bash ${SIGN_TOOL} -d sign -x trustzone -i ${CMAKE_LIBRARY_OUTPUT_DIRECTORY}/lib${PREFIX}.so -c ${CMAKE_CURRENT_SOURCE_DIR}/manifest.txt +- -o ${CMAKE_LIBRARY_OUTPUT_DIRECTORY}/${OUTPUT}) ++ #for trustzone compiling, you should connact us to get config and private_key.pem for test, so we will not sign and install binary in this example # ++ # add_custom_command(TARGET ${PREFIX} ++ # POST_BUILD ++ # COMMAND bash ${SIGN_TOOL} -d sign -x trustzone -i ${CMAKE_LIBRARY_OUTPUT_DIRECTORY}/lib${PREFIX}.so -c ${CMAKE_CURRENT_SOURCE_DIR}/manifest.txt -m ${CMAKE_CURRENT_SOURCE_DIR}/config_cloud.ini -o ${CMAKE_LIBRARY_OUTPUT_DIRECTORY}/${OUTPUT}) + +- install(FILES ${CMAKE_LIBRARY_OUTPUT_DIRECTORY}/${OUTPUT} +- DESTINATION /data +- PERMISSIONS OWNER_EXECUTE OWNER_WRITE OWNER_READ GROUP_READ GROUP_EXECUTE WORLD_READ WORLD_EXECUTE) ++ # install(FILES ${CMAKE_LIBRARY_OUTPUT_DIRECTORY}/${OUTPUT} ++ # DESTINATION /data ++ # PERMISSIONS OWNER_EXECUTE OWNER_WRITE OWNER_READ GROUP_READ GROUP_EXECUTE WORLD_READ WORLD_EXECUTE) + + endif() + +diff --git a/examples/helloworld/enclave/config_cloud.ini b/examples/helloworld/enclave/config_cloud.ini +new file mode 100644 +index 0000000..552f59c +--- /dev/null ++++ b/examples/helloworld/enclave/config_cloud.ini +@@ -0,0 +1,49 @@ ++[config] ++;0 means debug ++;1 means release ++;[fixed value] ++releaseType = 1 ++;;; ++;0 means TA not installed by OTRP ++;1 means TA installed by OTRP ++otrpFlag = 0 ++;;; ++;server address for signing TA ++serverIp= ++;;; ++;public key for encrypt TA ++;[fixed value] ++encryptKey = cloud/rsa_public_key_cloud.pem ++;;; ++;public key length ++;[fixed value] ++encryptKeyLen = 3072 ++;;; ++;0 means not sign ++;1 means signed by local private ++;2 means signed using native sign tool; ++;3 means signed by CI ++;[fixed value] ++signType = 1 ++;;; ++;private key for signing TA ++;[private key owned by yourself] ++signKey = ../../examples/helloworld/enclave/cert/private_key.pem ++;;; ++;private key length for signing TA ++;[key length should be 4096 for security enhance] ++signKeyLen = 4096 ++;;; ++;0 means SHA256 hash type ++;1 means SHA512 hash type ++;[set value to 0 by default] ++hashType = 0 ++;;; ++;0 means padding type is pkcs1v15 ++;1 means padding type is PSS ++;[set value to 0 by default] ++paddingType = 0 ++;;; ++;config file ++;[signed config file by Huawei] ++configPath= ../../examples/helloworld/enclave/signed_config/config +diff --git a/examples/helloworld/enclave/manifest.txt b/examples/helloworld/enclave/manifest.txt +new file mode 100644 +index 0000000..d78354e +--- /dev/null ++++ b/examples/helloworld/enclave/manifest.txt +@@ -0,0 +1,7 @@ ++gpd.ta.appID: f68fd704-6eb1-4d14-b218-722850eb3ef0 ++gpd.ta.service_name: rsa-demo ++gpd.ta.singleInstance: true ++gpd.ta.multiSession: false ++gpd.ta.instanceKeepAlive: false ++gpd.ta.dataSize: 819200 ++gpd.ta.stackSize: 40960 +diff --git a/examples/helloworld/enclave/manifest.txt.in b/examples/helloworld/enclave/manifest.txt.in +deleted file mode 100644 +index 7b8ecf5..0000000 +--- a/examples/helloworld/enclave/manifest.txt.in ++++ /dev/null +@@ -1,8 +0,0 @@ +-gpd.ta.appID: @UUID@ +-gpd.ta.service_name: test0108 +-gpd.ta.singleInstance: true +-gpd.ta.multiSession: false +-gpd.ta.multiCommand: false +-gpd.ta.instanceKeepAlive: false +-gpd.ta.dataSize: 16384 +-gpd.ta.stackSize: 20480 +diff --git a/examples/helloworld/host/CMakeLists.txt b/examples/helloworld/host/CMakeLists.txt +index 1c96ffd..60173a9 100644 +--- a/examples/helloworld/host/CMakeLists.txt ++++ b/examples/helloworld/host/CMakeLists.txt +@@ -38,9 +38,10 @@ if(CC_GP) + link_directories(${CMAKE_LIBRARY_OUTPUT_DIRECTORY}) + endif() + add_executable(${OUTPUT} ${SOURCE_FILE} ${AUTO_FILES}) +- target_include_directories(${OUTPUT} PRIVATE +- ${LOCAL_ROOT_PATH}/inc/host_inc +- ${LOCAL_ROOT_PATH}/inc/host_inc/gp ++ target_include_directories(${OUTPUT} PRIVATE ++ ${LOCAL_ROOT_PATH}/debug/inc ++ ${LOCAL_ROOT_PATH}/inc/host_inc ++ ${LOCAL_ROOT_PATH}/inc/host_inc/gp + ${CMAKE_CURRENT_BINARY_DIR}) + if(${CMAKE_VERSION} VERSION_GREATER_EQUAL "3.13.0") + target_link_directories(${OUTPUT} PRIVATE ${CMAKE_LIBRARY_OUTPUT_DIRECTORY}) +diff --git a/examples/helloworld/host/main.c b/examples/helloworld/host/main.c +index 51993ce..7213a5e 100644 +--- a/examples/helloworld/host/main.c ++++ b/examples/helloworld/host/main.c +@@ -15,6 +15,7 @@ + #include + #include "enclave.h" + #include "helloworld_u.h" ++#include "string.h" + + #define BUF_LEN 32 + +diff --git a/examples/seal_data/CMakeLists.txt b/examples/seal_data/CMakeLists.txt +index 3577301..dce8b81 100644 +--- a/examples/seal_data/CMakeLists.txt ++++ b/examples/seal_data/CMakeLists.txt +@@ -21,9 +21,7 @@ set(CODEGEN codegen) + + if(CC_GP) + set(CODETYPE trustzone) +- execute_process(COMMAND uuidgen -r +- OUTPUT_VARIABLE UUID) +- string(REPLACE "\n" "" UUID ${UUID}) ++ set(UUID 9cb38838-2766-42be-8b7b-0d184a996066) + add_definitions(-DPATH="/data/${UUID}.sec") + endif() + +diff --git a/examples/seal_data/enclave/CMakeLists.txt b/examples/seal_data/enclave/CMakeLists.txt +index 0ddcbd5..b24e498 100644 +--- a/examples/seal_data/enclave/CMakeLists.txt ++++ b/examples/seal_data/enclave/CMakeLists.txt +@@ -52,7 +52,6 @@ set(COMMON_C_FLAGS "-W -Wall -Werror -fno-short-enums -fno-omit-frame-pointer + set(COMMON_C_LINK_FLAGS "-Wl,-z,now -Wl,-z,relro -Wl,-z,noexecstack -Wl,-nostdlib -nodefaultlibs -nostartfiles") + + if(CC_GP) +- configure_file("${CMAKE_CURRENT_SOURCE_DIR}/manifest.txt.in" "${CMAKE_CURRENT_SOURCE_DIR}/manifest.txt") + set(CMAKE_C_FLAGS "${COMMON_C_FLAGS} -march=armv8-a ") + set(CMAKE_C_FLAGS_RELEASE "${CMAKE_C_FLAGS} -s") + set(CMAKE_SHARED_LINKER_FLAGS "${COMMON_C_LINK_FLAGS} -Wl,-s -fPIC") +@@ -67,6 +66,7 @@ if(CC_GP) + + target_include_directories( ${PREFIX} PRIVATE + ${CMAKE_CURRENT_BINARY_DIR} ++ ${LOCAL_ROOT_PATH}/debug/inc + ${LOCAL_ROOT_PATH}/inc/host_inc + ${LOCAL_ROOT_PATH}/inc/host_inc/gp + ${LOCAL_ROOT_PATH}/inc/enclave_inc +@@ -91,15 +91,14 @@ if(CC_GP) + endforeach(WHITE_LIST) + + target_link_libraries(${PREFIX} -lsecgear_tee) +- +- add_custom_command(TARGET ${PREFIX} +- POST_BUILD +- COMMAND bash ${SIGN_TOOL} -d sign -x trustzone -a 2 -i ${CMAKE_LIBRARY_OUTPUT_DIRECTORY}/lib${PREFIX}.so -c ${CMAKE_CURRENT_SOURCE_DIR}/manifest.txt +- -o ${CMAKE_LIBRARY_OUTPUT_DIRECTORY}/${OUTPUT}) +- +- install(FILES ${CMAKE_LIBRARY_OUTPUT_DIRECTORY}/${OUTPUT} +- DESTINATION /data +- PERMISSIONS OWNER_EXECUTE OWNER_WRITE OWNER_READ GROUP_READ GROUP_EXECUTE WORLD_READ WORLD_EXECUTE) ++ # for trustzone compiling, you should connact us to get config and private_key.pem for test, so we will not sign and install binary in this example # ++ # add_custom_command(TARGET ${PREFIX} ++ # POST_BUILD ++ # COMMAND bash ${SIGN_TOOL} -d sign -x trustzone -i ${CMAKE_LIBRARY_OUTPUT_DIRECTORY}/lib${PREFIX}.so -c ${CMAKE_CURRENT_SOURCE_DIR}/manifest.txt -m ${CMAKE_CURRENT_SOURCE_DIR}/config_cloud.ini -o ${CMAKE_LIBRARY_OUTPUT_DIRECTORY}/${OUTPUT}) ++ ++ # install(FILES ${CMAKE_LIBRARY_OUTPUT_DIRECTORY}/${OUTPUT} ++ # DESTINATION /data ++ # PERMISSIONS OWNER_EXECUTE OWNER_WRITE OWNER_READ GROUP_READ GROUP_EXECUTE WORLD_READ WORLD_EXECUTE) + + endif() + +diff --git a/examples/seal_data/enclave/config_cloud.ini b/examples/seal_data/enclave/config_cloud.ini +new file mode 100644 +index 0000000..f0c0e39 +--- /dev/null ++++ b/examples/seal_data/enclave/config_cloud.ini +@@ -0,0 +1,49 @@ ++[config] ++;0 means debug ++;1 means release ++;[fixed value] ++releaseType = 1 ++;;; ++;0 means TA not installed by OTRP ++;1 means TA installed by OTRP ++otrpFlag = 0 ++;;; ++;server address for signing TA ++serverIp= ++;;; ++;public key for encrypt TA ++;[fixed value] ++encryptKey = cloud/rsa_public_key_cloud.pem ++;;; ++;public key length ++;[fixed value] ++encryptKeyLen = 3072 ++;;; ++;0 means not sign ++;1 means signed by local private ++;2 means signed using native sign tool; ++;3 means signed by CI ++;[fixed value] ++signType = 1 ++;;; ++;private key for signing TA ++;[private key owned by yourself] ++signKey = ../../examples/seal_data/enclave/cert/private_key.pem ++;;; ++;private key length for signing TA ++;[key length should be 4096 for security enhance] ++signKeyLen = 4096 ++;;; ++;0 means SHA256 hash type ++;1 means SHA512 hash type ++;[set value to 0 by default] ++hashType = 0 ++;;; ++;0 means padding type is pkcs1v15 ++;1 means padding type is PSS ++;[set value to 0 by default] ++paddingType = 0 ++;;; ++;config file ++;[signed config file by Huawei] ++configPath= ../../examples/seal_data/enclave/signed_config/config +diff --git a/examples/seal_data/enclave/manifest.txt b/examples/seal_data/enclave/manifest.txt +new file mode 100644 +index 0000000..e845fd7 +--- /dev/null ++++ b/examples/seal_data/enclave/manifest.txt +@@ -0,0 +1,7 @@ ++gpd.ta.appID: 9cb38838-2766-42be-8b7b-0d184a996066 ++gpd.ta.service_name: secstorage-demo ++gpd.ta.singleInstance: true ++gpd.ta.multiSession: false ++gpd.ta.instanceKeepAlive: False ++gpd.ta.dataSize: 819200 ++gpd.ta.stackSize: 40960 +diff --git a/examples/seal_data/enclave/manifest.txt.in b/examples/seal_data/enclave/manifest.txt.in +deleted file mode 100644 +index 749815a..0000000 +--- a/examples/seal_data/enclave/manifest.txt.in ++++ /dev/null +@@ -1,8 +0,0 @@ +-gpd.ta.appID: @UUID@ +-gpd.ta.service_name: seal_data +-gpd.ta.singleInstance: true +-gpd.ta.multiSession: false +-gpd.ta.multiCommand: false +-gpd.ta.instanceKeepAlive: false +-gpd.ta.dataSize: 4038400 +-gpd.ta.stackSize: 6048000 +diff --git a/examples/seal_data/host/CMakeLists.txt b/examples/seal_data/host/CMakeLists.txt +index 75b33f7..691cd07 100644 +--- a/examples/seal_data/host/CMakeLists.txt ++++ b/examples/seal_data/host/CMakeLists.txt +@@ -40,6 +40,7 @@ if(CC_GP) + endif() + add_executable(${OUTPUT} ${SOURCE_FILE} ${AUTO_FILES}) + target_include_directories(${OUTPUT} PRIVATE ++ ${LOCAL_ROOT_PATH}/debug/inc + ${LOCAL_ROOT_PATH}/inc/host_inc + ${LOCAL_ROOT_PATH}/inc/host_inc/gp + ${CMAKE_CURRENT_BINARY_DIR}) +diff --git a/src/enclave_src/gp/itrustee/itrustee_seal_data.c b/src/enclave_src/gp/itrustee/itrustee_seal_data.c +index 5b1676a..cf13bd9 100644 +--- a/src/enclave_src/gp/itrustee/itrustee_seal_data.c ++++ b/src/enclave_src/gp/itrustee/itrustee_seal_data.c +@@ -221,12 +221,11 @@ TEE_Result itrustee_unseal_data(void *sealed_data, uint8_t *decrypted_data, uint + SLogError("malloc key_buf failed\n"); + return TEE_ERROR_OUT_OF_MEMORY; + } +- result = TEE_EXT_DeriveTARootKey(salt, strlen(salt), key_buf, key_len); ++ result = TEE_EXT_DeriveTARootKey(salt, SEAL_KEY_SALT_LEN, key_buf, key_len); + if (result != TEE_SUCCESS) { + SLogError("DeriveTARootKey failed"); + goto done; + } +- + *decrypted_data_len = tmp_sealed_data->encrypted_data_len; + *mac_data_len = tmp_sealed_data->aad_len; + result = aes_seal_unseal_data(key_buf, key_len, (uint8_t *)&(tmp_sealed_data->nonce), SEAL_DATA_NONCE_LEN, +diff --git a/src/host_src/gp/CMakeLists.txt b/src/host_src/gp/CMakeLists.txt +index 37635ec..ca6d87f 100644 +--- a/src/host_src/gp/CMakeLists.txt ++++ b/src/host_src/gp/CMakeLists.txt +@@ -11,8 +11,6 @@ + set(gp_engine gp_0) + + # to do itrustee sdk Open Source +-set(itrustee_lib ) +- + set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib/gp) + + if(${CMAKE_VERSION} VERSION_LESS "3.13.0") +@@ -33,7 +31,7 @@ endif() + + set_target_properties(${gp_engine} PROPERTIES SKIP_BUILD_RPATH TRUE) + #link iTrustee teec lib +-target_link_libraries(${gp_engine} ${itrustee_lib} secgear pthread) ++target_link_libraries(${gp_engine} secgear pthread teec_adaptor) + + install(TARGETS ${gp_engine} + LIBRARY +diff --git a/src/host_src/gp/gp_enclave.c b/src/host_src/gp/gp_enclave.c +index b185958..86ea941 100644 +--- a/src/host_src/gp/gp_enclave.c ++++ b/src/host_src/gp/gp_enclave.c +@@ -25,7 +25,7 @@ + + #define OCALL_AGENT_REGISTER_SUCCESS 0 + #define OCALL_AGENT_REGISTER_FAIL 1 +- ++#define SECGEAR_OCALL 0 + #define MAX_LEN 4096 + + static pthread_cond_t g_cond = PTHREAD_COND_INITIALIZER; +@@ -535,7 +535,7 @@ cc_enclave_result_t cc_enclave_call_function( + /* for ocall thread */ + ires = pthread_mutex_lock(&g_mtx_flag); + SECGEAR_CHECK_MUTEX_RES(ires); +- if (!(g_list_ops.pthread_flag)) { ++ if (g_list_ops.pthread_flag || SECGEAR_OCALL) { + param.agent_id = *(uint32_t *)ms; + param.num = ((ocall_enclave_table_t *)ocall_table)->num; + param.ocalls = ((ocall_enclave_table_t *)ocall_table)->ocalls; +diff --git a/tools/sign_tool/rsa_public_key_cloud.pem b/tools/sign_tool/cloud/rsa_public_key_cloud.pem +similarity index 100% +rename from tools/sign_tool/rsa_public_key_cloud.pem +rename to tools/sign_tool/cloud/rsa_public_key_cloud.pem +diff --git a/tools/sign_tool/generate_signature.py b/tools/sign_tool/generate_signature.py +new file mode 100644 +index 0000000..b3264ba +--- /dev/null ++++ b/tools/sign_tool/generate_signature.py +@@ -0,0 +1,56 @@ ++#!/usr/bin/env python ++# coding:utf-8 ++#---------------------------------------------------------------------------- ++# Copyright (c) Huawei Technologies Co., Ltd. 2020-2020. All rights reserved. ++# iTrustee licensed under the Mulan PSL v2. ++# You can use this software according to the terms and conditions of the Mulan ++# PSL v2. ++# You may obtain a copy of Mulan PSL v2 at: ++# http://license.coscl.org.cn/MulanPSL2 ++# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY ++# KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ++# NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. ++# See the Mulan PSL v2 for more details. ++# Description: tools for generating a trusted application load image ++# Author: Li mingjuan ++# Create: 2020-10-27 ++#---------------------------------------------------------------------------- ++ ++import struct ++import os ++import hashlib ++import subprocess ++ ++HASH256 = 0 ++HASH512 = 1 ++ ++def gen_hash(hash_type, in_file_path, out_file_path): ++ in_file_size = os.path.getsize(in_file_path) ++ # Initialize a SHA256 object from the Python hash library ++ if int(hash_type) == HASH256: ++ hash_op = hashlib.sha256() ++ elif int(hash_type) == HASH512: ++ hash_op = hashlib.sha512() ++ # Set the input buffer and return the output digest ++ with open(in_file_path, 'rb') as in_file: ++ hash_op.update(in_file.read(in_file_size)) ++ ++ #-----hash file used for ras sign--- ++ with open(out_file_path, 'wb') as hash_fp: ++ # fixed hash prefix value ++ hash_fp.write(struct.pack('B'*19, 0x30, 0x31, 0x30, 0x0d, 0x06, \ ++ 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01, \ ++ 0x05, 0x00, 0x04, 0x20)) ++ hash_fp.write(hash_op.digest()) ++ return ++ ++def gen_ta_signature(cfg, hash_file_path, out_file_path): ++ cmd = "openssl rsautl -sign -inkey {} -in {} -out {}".\ ++ format(cfg.sign_key, hash_file_path, out_file_path) ++ try: ++ subprocess.check_output(cmd.split(), shell=False) ++ except Exception: ++ print("sign operation failed") ++ raise RuntimeError ++ return ++ +diff --git a/tools/sign_tool/manifest.py b/tools/sign_tool/manifest.py +index 4de8407..9cc2360 100644 +--- a/tools/sign_tool/manifest.py ++++ b/tools/sign_tool/manifest.py +@@ -1,10 +1,20 @@ + #!/usr/bin/env python + # coding:utf-8 + #---------------------------------------------------------------------------- +-# Copyright @ Huawei Technologies Co., Ltd. 2018-2019. All rights reserved. +-# tools for generating a trusted application load image ++# Copyright (c) Huawei Technologies Co., Ltd. 2018-2020. All rights reserved. ++# iTrustee licensed under the Mulan PSL v2. ++# You can use this software according to the terms and conditions of the Mulan ++# PSL v2. ++# You may obtain a copy of Mulan PSL v2 at: ++# http://license.coscl.org.cn/MulanPSL2 ++# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY ++# KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ++# NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. ++# See the Mulan PSL v2 for more details. ++# Description: tools for generating a trusted application load image ++# Author: Li mingjuan ++# Create: 2018-02-20 + #---------------------------------------------------------------------------- +- + import string + import struct + import uuid +@@ -14,31 +24,32 @@ PRODUCT_TA_IMAGE = 1 + PRODUCT_DYN_LIB = 2 + PRODUCT_SERVICE_IMAGE = 3 + +-class TEE_UUID: ++ ++class PackUuid: + # Structure object to align and package the TEE_UUID +- s = struct.Struct('IHH8b') ++ data = struct.Struct('IHH8b') + + def __init__(self, data): +- unpacked_data = (TEE_UUID.s).unpack(str.encode(data)) ++ unpacked_data = (PackUuid.data).unpack(str.encode(data)) + self.unpacked_data = unpacked_data +- self.timeLow = unpacked_data[0] +- self.timeMid = unpacked_data[1] +- self.timeHiAndVersion = unpacked_data[2] +- self.clockSeqAndNode = unpacked_data[3] ++ self.time_low = unpacked_data[0] ++ self.time_mid = unpacked_data[1] ++ self.time_hi_version = unpacked_data[2] ++ self.clock_seq_node = unpacked_data[3] + +- def printValues(self): ++ def print_values(self): + print("ATTRIBUTE / VALUE") + for attr, value in self.__dict__.items(): + print(attr, value) + +- def getPackedData(self): +- values = [self.timeLow, +- self.timeMid, +- self.timeHiAndVersion, +- self.clockSeqAndNode, ++ def get_pack_data(self): ++ values = [self.time_low, ++ self.time_mid, ++ self.time_hi_version, ++ self.clock_seq_node, + ] + +- return (TEE_UUID.s).pack(*values) ++ return (PackUuid.data).pack(*values) + + + #---------------------------------------------------------------------------- +@@ -47,10 +58,10 @@ class TEE_UUID: + class Manifest: + + # Structure object to align and package the Manifest +- s = struct.Struct('I' * 6) ++ data = struct.Struct('I' * 6) + + def __init__(self, data): +- unpacked_data = (Manifest.s).unpack(str.encode(data)) ++ unpacked_data = (Manifest.data).unpack(str.encode(data)) + self.unpacked_data = unpacked_data + self.single_instance = unpacked_data[0] + self.multi_session = unpacked_data[1] +@@ -59,12 +70,12 @@ class Manifest: + self.stack_size = unpacked_data[4] + self.instancekeepalive = unpacked_data[5] + +- def printValues(self): ++ def print_values(self): + print("ATTRIBUTE / VALUE") + for attr, value in self.__dict__.items(): + print(attr, value) + +- def getPackedData(self): ++ def get_pack_data(self): + values = [self.single_instance, + self.multi_session, + self.multi_command, +@@ -73,21 +84,22 @@ class Manifest: + self.instancekeepalive, + ] + +- return (Manifest.s).pack(*values) ++ return (Manifest.data).pack(*values) ++ + + #---------------------------------------------------------------------------- + # verify property name in manifest file + #---------------------------------------------------------------------------- +-def verify_property_name(strLine): ++def verify_property_name(str_line): + print('verify property name') + alphas = string.ascii_letters + string.digits + cont = "".join([alphas, '-', '_', '.']) +- if len(strLine) > 1: +- if strLine[0] not in alphas: ++ if len(str_line) > 1: ++ if str_line[0] not in alphas: + print('invalid first letter in property name') + return False + else: +- for otherchar in strLine[1:]: ++ for otherchar in str_line[1:]: + if otherchar not in cont: + print('invalid char in property name') + return False +@@ -97,35 +109,37 @@ def verify_property_name(strLine): + + return True + ++ + #---------------------------------------------------------------------------- + # verify property value in manifest file + #---------------------------------------------------------------------------- +-def verify_property_value(strLine): ++def verify_property_value(str_line): + print('verify property value') +- filt_letter = chr(0) + chr(10) +chr(13) +- for thechar in strLine: ++ filt_letter = chr(0) + chr(10) + chr(13) ++ for thechar in str_line: + if thechar in filt_letter: + print('invalid letter in prop value') + return False + return True + ++ + #---------------------------------------------------------------------------- + # remove tabs and space in property value + #---------------------------------------------------------------------------- +-def trailing_space_tabs(strLine): ++def trailing_space_tabs(str_line): + print('trailing space tabs in value head and trail') +- space_tabs = chr(9) + chr(32) +chr(160) +- space_tabs_newlines = space_tabs + chr(10) +chr(13) ++ space_tabs = chr(9) + chr(32) + chr(160) ++ space_tabs_newlines = space_tabs + chr(10) + chr(13) + print('tab: {}'.format(space_tabs)) + +- print('str in: {}'.format(strLine)) ++ print('str in: {}'.format(str_line)) + index = 0 +- for thechar in strLine: ++ for thechar in str_line: + if thechar in space_tabs: + index += 1 + else: + break +- headvalue = strLine[index:] ++ headvalue = str_line[index:] + + strlen = len(headvalue) + +@@ -137,21 +151,20 @@ def trailing_space_tabs(strLine): + else: + break + +- #print 'str len: '+str(strlen) +- strRet = headvalue[0:strlen+1] + chr(10) +- print('str ret: {}'.format(strRet)) ++ str_ret = headvalue[0:strlen+1] + chr(10) ++ print('str ret: {}'.format(str_ret)) ++ ++ return str_ret + +- return strRet + + #---------------------------------------------------------------------------- + # verify manifest file, parse manifest file, generate a new manfiest file + #---------------------------------------------------------------------------- +-def parserManifest(manifest, manifestDataPath, mani_ext): ++def parser_manifest(manifest, manifest_data_path, mani_ext): + print('verify manifest') +- targetType = PRODUCT_TA_IMAGE ++ target_type = PRODUCT_TA_IMAGE + +- uuid_val_flag = 1 +- uuid_val = TEE_UUID('\0' * 16) ++ uuid_val = PackUuid('\0' * 16) + + #manifest default + manifest_val = Manifest('\0'*24) +@@ -166,30 +179,29 @@ def parserManifest(manifest, manifestDataPath, mani_ext): + service_name = 'external_service' + + with open(manifest, 'r') as mani_fp, open(mani_ext, 'wb') as mani_ext_fp: +- for eachLine in mani_fp: +- print(eachLine) +- if eachLine.startswith("#") or not len(eachLine.strip()): ++ for each_line in mani_fp: ++ print(each_line) ++ if each_line.startswith("#") or not len(each_line.strip()): + continue +- index = eachLine.find(':', 1, len(eachLine)) +- #print 'index name : value is ' + str(index) ++ index = each_line.find(':', 1, len(each_line)) + +- prop_name = eachLine[0:index] #no ':' +- prop_name_t = eachLine[0:index+1] #with ':' +- prop_value_t = eachLine[index+1:] ++ prop_name = each_line[0:index] ++ prop_name_t = each_line[0:index+1] ++ prop_value_t = each_line[index+1:] + print('name is: {}; value is: {}'.format(prop_name, prop_value_t)) + + prop_value = trailing_space_tabs(prop_value_t) + prop_len = len(prop_value) +- prop_value_v = prop_value[0:prop_len-1]# mv last letter ++ prop_value_v = prop_value[0:prop_len-1] + print('prop value_v: {}'.format(prop_value_v)) + + if verify_property_name(prop_name) is False: + print('manifest format invalid, please check it') +- return (False, 0, 0, 0) ++ return (False, 0) + + if verify_property_value(prop_value_v) is False: + print('manifest format invalid, please check it') +- return (False, 0, 0, 0) ++ return (False, 0) + + # name:value to lowcase, and parse manifest + prop_name_low = prop_name.lower() +@@ -197,58 +209,54 @@ def parserManifest(manifest, manifestDataPath, mani_ext): + if 'gpd.ta.appid' == prop_name_low: + print("compare name is srv id") + uuid_val = uuid.UUID(prop_value_v) +- uuid_val_flag = 0 + print('uuid str {}'.format(uuid_val)) + print('val fields {}'.format(uuid_val.fields)) + + elif 'gpd.ta.singleinstance' == prop_name_low: + prop_value_low = prop_value_v.lower() + if 'true' == prop_value_low: +- manifest_val.single_instance = 1; ++ manifest_val.single_instance = 1 + elif 'false' == prop_value_low: +- manifest_val.single_instance = 0; ++ manifest_val.single_instance = 0 + else: + print('single_instance value error!') + + elif 'gpd.ta.multisession' == prop_name_low: + prop_value_low = prop_value_v.lower() + if 'true' == prop_value_low: +- manifest_val.multi_session = 1; ++ manifest_val.multi_session = 1 + elif 'false' == prop_value_low: +- manifest_val.multi_session = 0; ++ manifest_val.multi_session = 0 + else: + print('multi_session value error!') + + elif 'gpd.ta.multicommand' == prop_name_low: + prop_value_low = prop_value_v.lower() + if 'true' == prop_value_low: +- manifest_val.multi_command = 1; ++ manifest_val.multi_command = 1 + elif 'false' == prop_value_low: +- manifest_val.multi_command = 0; ++ manifest_val.multi_command = 0 + else: + print('multi_command value error!') + + elif 'gpd.ta.instancekeepalive' == prop_name_low: + prop_value_low = prop_value_v.lower() + if 'true' == prop_value_low: +- manifest_val.instancekeepalive = 1; ++ manifest_val.instancekeepalive = 1 + elif 'false' == prop_value_low: +- manifest_val.instancekeepalive = 0; ++ manifest_val.instancekeepalive = 0 + else: + print('instancekeepalive value error!') + + elif 'gpd.ta.datasize' == prop_name_low: +- #manifest_val.heap_size = prop_value_v.atoi() + manifest_val.heap_size = int(prop_value_v) + print('b') + + elif 'gpd.ta.stacksize' == prop_name_low: +- #manifest_val.stack_size = prop_value_v.atoi() + manifest_val.stack_size = int(prop_value_v) + print('b') + + elif 'gpd.ta.service_name' == prop_name_low: +- #manifest_val.stack_size = prop_value_v.atoi() + service_name = prop_value_v + print('b') + +@@ -260,11 +268,11 @@ def parserManifest(manifest, manifestDataPath, mani_ext): + if 'gpd.ta.is_tee_service' == prop_name_low: + prop_value_low = prop_value_v.lower() + if 'true' == prop_value_low: +- targetType = PRODUCT_SERVICE_IMAGE ++ target_type = PRODUCT_SERVICE_IMAGE + elif 'gpd.ta.is_lib' == prop_name_low: + prop_value_low = prop_value_v.lower() + if 'true' == prop_value_low: +- targetType = PRODUCT_DYN_LIB ++ target_type = PRODUCT_DYN_LIB + + #write the whole parsed manifest into sample.manifest file + +@@ -277,14 +285,11 @@ def parserManifest(manifest, manifestDataPath, mani_ext): + + # get manifest string file len + manifest_str_size = os.path.getsize(mani_ext) +- if manifest_str_size > 152: +- print("extra manifest string exceed MAX len 152") +- raise RuntimeError + print('manifest str size {}'.format(manifest_str_size)) + + # 2> manifest + service_name + print("bytes len {}".format(len(uuid_val.bytes_le))) +- print("bytes len {}".format(len(manifest_val.getPackedData()))) ++ print("bytes len {}".format(len(manifest_val.get_pack_data()))) + print("bytes len {}".format(len(service_name))) + + # 3> unparsed manifest, string manifest +@@ -294,23 +299,24 @@ def parserManifest(manifest, manifestDataPath, mani_ext): + print("manifest strint: {}".format(manifest_string_buf)) + + #---- write manifest parse context to manifest file +- with open(manifestDataPath, 'wb') as out_manifest_fp: ++ with open(manifest_data_path, 'wb') as out_manifest_fp: + out_manifest_fp.write(uuid_val.bytes_le) + out_manifest_fp.write(str.encode(service_name)) +- out_manifest_fp.write(manifest_val.getPackedData()) ++ out_manifest_fp.write(manifest_val.get_pack_data()) + +- productName = str(uuid_val) +- if targetType == PRODUCT_TA_IMAGE: ++ product_name = str(uuid_val) ++ if target_type == PRODUCT_TA_IMAGE: + print("product type is ta image") +- productName = "".join([productName, ".sec"]) +- elif targetType == PRODUCT_SERVICE_IMAGE: ++ product_name = "".join([product_name, ".sec"]) ++ elif target_type == PRODUCT_SERVICE_IMAGE: + print("product type is service") +- productName = "".join([productName, service_name, "_svr.sec"]) +- elif targetType == PRODUCT_DYN_LIB: ++ product_name = "".join([product_name, service_name, "_svr.sec"]) ++ elif target_type == PRODUCT_DYN_LIB: + print("product type is dyn lib") +- productName = "".join([productName, service_name, ".so.sec"]) ++ product_name = "".join([product_name, service_name, ".so.sec"]) + else: + print("invalid product type!") + raise RuntimeError + +- return (True, productName, uuid_val_flag) ++ return (True, product_name) ++ +diff --git a/tools/sign_tool/sign_tool.py b/tools/sign_tool/sign_tool.py +deleted file mode 100644 +index 1e6e37d..0000000 +--- a/tools/sign_tool/sign_tool.py ++++ /dev/null +@@ -1,471 +0,0 @@ +-#!/usr/bin/env python +-# coding:utf-8 +-#---------------------------------------------------------------------------- +-# Copyright @ Huawei Technologies Co., Ltd. 2018-2019. All rights reserved. +-# tools for generating a trusted application load image +-#---------------------------------------------------------------------------- +- +-import struct +-import sys +-import os +-import hashlib +-import binascii +-import subprocess +-import shutil +- +-from manifest import * +- +-DEBUG = 0 +-VERSION = 3 +-TA_VERSION = 3 +-# TA_TYPE 1 stand for v3.0 +-# TA_TYPE 2 stand for v3.1(with config and cert) +-TA_TYPE = 0 +- +-API_LEVEL = 1 +-PRODUCT_NAME = "" +- +-# OTRP_FLAG 1 stand for otrp sec, and only can load sec by otrp mode +-# OTRP_FLAG 0 stand for no-otrp sec, and only can load sec by tzdriver mode +-OTRP_FLAG = 0 +- +-MAGIC1 = 0xA5A55A5A +-MAGIC2 = 0x55AA +- +-# low 8 bits:key is derived from root key +-# high 8 bits:key len is 3072, if value is 0 or 1, then key len is 2048 +-KEY_VERSION = 0x0202 +- +-SIGN_ALG_V3 = 0x10002048 +-SIGN_ALG_V4 = 0x10004096 +- +-HASH256_LEN = 256 +-HASH512_LEN = 512 +- +-ENCRYPTED_KEYINFO_LEN =256 +-SIGNATURE_LEN_256 = 256 +-SIGNATURE_LEN_512 = 512 +- +-SUCCESS = 0 +- +-# ELF Definitions +-ELF_TYPE = 32 +-ELF_HDR_SIZE = 52 +-ELF_PHDR_SIZE = 32 +-ELF_INFO_MAGIC0_INDEX = 0 +-ELF_INFO_MAGIC1_INDEX = 1 +-ELF_INFO_MAGIC2_INDEX = 2 +-ELF_INFO_MAGIC3_INDEX = 3 +-ELF_INFO_MAGIC0 = 127 #'\x7f' +-ELF_INFO_MAGIC1 = 69 #'E' +-ELF_INFO_MAGIC2 = 76 #'L' +-ELF_INFO_MAGIC3 = 70 #'F' +-ELF_INFO_CLASS_INDEX = 4 +-ELF_INFO_CLASS = 1 #'\x01' +-ELF_INFO_VERSION_INDEX = 6 +-ELF_INFO_VERSION_CURRENT = 1 #'\x01' +-ELF_BLOCK_ALIGN = 0x1000 +-ELF_HEAD_FORMAT = '' +- +-#---------------------------------------------------------------------------- +-# ELF File Header Check +-#---------------------------------------------------------------------------- +-class Elf_Header: +- def __init__(self, data): +- # Algin data obj in ELF header +- if(ELF_TYPE == 64): +- self.s = struct.Struct('16sHHIQQQIHHHHHH') +- else: +- self.s = struct.Struct('16sHHIIIIIHHHHHH') +- +- unpacked_data = (self.s).unpack(data) +- self.unpacked_data = unpacked_data +- self.elf_ident = unpacked_data[0] +- self.elf_type = unpacked_data[1] +- self.elf_machine = unpacked_data[2] +- self.elf_version = unpacked_data[3] +- self.elf_entry = unpacked_data[4] +- self.elf_phoff = unpacked_data[5] +- self.elf_shoff = unpacked_data[6] +- self.elf_flags = unpacked_data[7] +- self.elf_ehsize = unpacked_data[8] +- self.elf_phentsize = unpacked_data[9] +- self.elf_phnum = unpacked_data[10] +- self.elf_shentsize = unpacked_data[11] +- self.elf_shnum = unpacked_data[12] +- self.elf_shstrndx = unpacked_data[13] +- +- def printValues(self): +- print("ATTRIBUTE / VALUE") +- for attr, value in self.__dict__.items(): +- print(attr, value) +- +- def getPackedData(self): +- values = [self.elf_ident, +- self.elf_type, +- self.elf_machine, +- self.elf_version, +- self.elf_entry, +- self.elf_phoff, +- self.elf_shoff, +- self.elf_flags, +- self.elf_ehsize, +- self.elf_phentsize, +- self.elf_phnum, +- self.elf_shentsize, +- self.elf_shnum, +- self.elf_shstrndx +- ] +- +- return (self.s).pack(*values) +- +-#---------------------------------------------------------------------------- +-# Verify ELF header contents from an input ELF file +-#---------------------------------------------------------------------------- +-def verify_elf_header(elf_header): +- s = struct.unpack('BBBBBBBBBBBBBBBB', elf_header.elf_ident) +- if (s[ELF_INFO_MAGIC0_INDEX] != ELF_INFO_MAGIC0) or \ +- (s[ELF_INFO_MAGIC1_INDEX] != ELF_INFO_MAGIC1) or \ +- (s[ELF_INFO_MAGIC2_INDEX] != ELF_INFO_MAGIC2) or \ +- (s[ELF_INFO_MAGIC3_INDEX] != ELF_INFO_MAGIC3) or \ +- (s[ELF_INFO_CLASS_INDEX] != ELF_INFO_CLASS) or \ +- (s[ELF_INFO_VERSION_INDEX] != ELF_INFO_VERSION_CURRENT): +- +- return False +- else: +- return True +- +-def get_elf_type(elfFile): +- EI_NIDENT = 16 +- global ELF_TYPE +- global ELF_HDR_SIZE +- global ELF_HEAD_FORMAT +- global ELF_INFO_CLASS +- +- elfFile.seek(0x0, 0) +- elf_ident = elfFile.read(EI_NIDENT) +- ''' check EI_CLASS, 32-bit or 64-bit''' +- elfStr = bytes.decode(elf_ident) +- s = struct.unpack('BBBBBBBBBBBBBBBB', elf_ident) +- if s[4] == 2: +- print("64 bit type") +- ELF_TYPE = 64 +- ELF_HDR_SIZE = 64 +- ELF_HEAD_FORMAT = "HHIQQQIHHHHHH" +- ELF_INFO_CLASS = 2 +- elif s[4] == 1: +- print("32 bit type") +- ELF_TYPE = 32 +- ELF_HDR_SIZE = 52 +- ELF_HEAD_FORMAT = "HHIIIIIHHHHHH" +- ELF_INFO_CLASS = 1 +- else: +- raise RuntimeError("Unknown ELF file type") +- return +- +-def generateHeader(contentLen): +- return struct.pack('IHHII', MAGIC1, MAGIC2, VERSION, contentLen, KEY_VERSION) +- +-def generateAesKeyInfo(ivFilePath, keyFilePath, outFilePath): +- # Aes key is randomly generated and temporarily stored in the file in plaintext, please ensure security. +- try: +- subprocess.check_output(["openssl", "rand", "-out", format(ivFilePath), "16"], shell=False) +- subprocess.check_output(["openssl", "rand", "-out", format(keyFilePath), "32"], shell=False) +- except: +- print("rand operation failed") +- raise RuntimeError +- +- with open(outFilePath, 'wb') as outFile: +- outFile.write(struct.pack('I', 32)) +- outFile.write(struct.pack('I', 16)) +- if DEBUG == 0 or TA_TYPE == 1: +- outFile.write(struct.pack('I', SIGN_ALG_V3)) +- elif TA_TYPE == 2: +- outFile.write(struct.pack('I', SIGN_ALG_V4)) +- else: +- print("target sign type is not supported: {}".format(TA_TYPE)) +- raise RuntimeError +- +- with open(keyFilePath, 'rb') as keyFile: +- outFile.write(keyFile.read(32)) +- +- with open(ivFilePath, 'rb') as ivFile: +- outFile.write(ivFile.read(16)) +- +- return +- +-def encryptAesKeyInfo(pubkeyFilePath, inFilePath, outFilePath): +- try: +- subprocess.check_output(["openssl", "rsautl", "-encrypt", "-pubin", "-oaep", \ +- "-inkey", format(pubkeyFilePath), "-in", format(inFilePath), "-out", format(outFilePath)], shell=False) +- except: +- print("RSA encrypt operation failed") +- raise RuntimeError +- return +- +-def generateHash(hashLen, inFilePath, outFilePath): +- inFileSize = os.path.getsize(inFilePath) +- # Initialize a SHA256 object from the Python hash library +- if hashLen == HASH256_LEN: +- hashOp = hashlib.sha256() +- elif hashLen == HASH512_LEN: +- hashOp = hashlib.sha512() +- # Set the input buffer and return the output digest +- with open(inFilePath, 'rb') as inFile: +- hashOp.update(inFile.read(inFileSize)) +- +- #-----hash file used for ras sign--- +- with open(outFilePath, 'wb') as hash_fp: +- # fixed hash prefix value +- hash_fp.write(struct.pack('B'*19, 0x30, 0x31, 0x30, 0x0d, 0x06, 0x09, 0x60, +- 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01, 0x05, 0x00, 0x04, 0x20)) +- hash_fp.write(hashOp.digest()) +- return +- +-def generateSignature(priKeyPath, inFilePath, outFilePath): +- if TA_TYPE == 1: +- print("generate dummy signature for DEBUG version") +- with open(outFilePath, 'wb') as f: +- f.write(str.encode('\0'*256, encoding='utf-8')) +- elif TA_TYPE == 2: +- try: +- subprocess.check_output(["openssl", "rsautl", "-sign", "-inkey", format(priKeyPath), \ +- "-in", format(inFilePath), " -out", format(outFilePath)], shell=False) +- except: +- print("sign operation failed") +- raise RuntimeError +- return +- +-def checkSignature(rawDataHashPath, inSignature, serverPubKey): +- try: +- subprocess.check_output(["openssl", "pkeyutl", "-verify", "-in", format(rawDataHashPath), \ +- "-sigfile", format(inSignature), "-pubin", "-inkey", format(serverPubKey)], shell=False) +- except: +- print("check operation failed") +- raise RuntimeError +- return +- +-def generateRawData(manifestDataPath, manifestExtFilePath, elfFilePath, configFilePath, rawFilePath): +- manifestDataSize = os.path.getsize(manifestDataPath) +- manifestExtSize = os.path.getsize(manifestExtFilePath) +- elfFileSize = os.path.getsize(elfFilePath) +- configFileSize = 0 +- +- with open(rawFilePath, 'wb') as f: +- header = "" +- if TA_TYPE == 2: +- configFileSize = os.path.getsize(configFilePath) +- header = struct.pack('IIIII', TA_VERSION, manifestDataSize, manifestExtSize, elfFileSize, configFileSize) +- f.write(header) +- +- with open(manifestDataPath, 'rb') as manifestData: +- f.write(manifestData.read(manifestDataSize)) +- +- with open(manifestExtFilePath, 'rb') as manifestExt: +- f.write(manifestExt.read(manifestExtSize)) +- +- with open(elfFilePath, 'rb') as elfFile: +- get_elf_type(elfFile) +- elfFile.seek(0x0, 0) +- elfFileHaderBuf = elfFile.read(ELF_HDR_SIZE) +- elfFileHader = Elf_Header(elfFileHaderBuf) +- if verify_elf_header(elfFileHader) is False: +- print("verify elf header failed") +- raise RuntimeError +- elfFile.seek(0x0, 0) +- f.write(elfFile.read(elfFileSize)) +- +- if TA_TYPE == 2: +- with open(configFilePath, 'rb') as configFile: +- f.write(configFile.read(configFileSize)) +- return +- +-def aesEncrypt(keyPath, ivPath, inFilePath, outfilePath): +- keySize = os.path.getsize(keyPath) +- with open(keyPath, 'rb') as key: +- keyData = key.read(keySize) +- hexKeyStr = binascii.b2a_hex(keyData) +- +- ivSize = os.path.getsize(ivPath) +- with open(ivPath, 'rb') as iv: +- ivData = iv.read(ivSize) +- hexIvStr = binascii.b2a_hex(ivData) +- +- try: +- subprocess.check_output(["openssl", "enc", "-aes-256-cbc", "-in", format(inFilePath), \ +- "-out", format(outfilePath), "-K", format(bytes.decode(hexKeyStr)), \ +- "-iv", format(bytes.decode(hexIvStr))], shell=False) +- except: +- print("AES encrypt operation failed") +- raise RuntimeError +- +- return +- +-def updateManifestTaApiLevel(manifest): +- line = "\ngpd.ta.api_level:{}\n".format(API_LEVEL) +- with open(manifest, "w") as f: +- f.writelines(line) +- +-def updateManifestTaOtrpFlag(manifest): +- data = '' +- with open(manifest, 'r') as f: +- for line in f: +- if line.startswith("#") or not "gpd.ta.otrp_flag" in line: +- data += line +- line = "\ngpd.ta.otrp_flag:{}\n".format('true') +- data += line +- with open(manifest, "w") as f: +- f.writelines(data) +- +-def generateDataForSign(contentLen, key_info, raw_file, data_sign): +- keyInfoLen = os.path.getsize(key_info) +- rawFileLen = os.path.getsize(raw_file) +- +- with open(data_sign, 'wb') as data_fp, \ +- open(key_info, 'rb') as key_fp, open(raw_file, 'rb') as raw_fp: +- data_fp.write(generateHeader(contentLen)) +- data_fp.write(key_fp.read(keyInfoLen)) +- data_fp.write(raw_fp.read(rawFileLen)) +- +- +-def generateDigest(enclavePath, manifestPath, deviceKeyPath, configFilePath, rawDataHashPath, encKeyInfoFilePath, \ +- encRawFilePath): +- inPath = os.getcwd() +- ivFilePath = os.path.join(inPath, "iv.bin") +- keyFilePath = os.path.join(inPath, "aeskey.bin") +- keyInfoFilePath = os.path.join(inPath, "KeyInfo") +- rawFilePath = os.path.join(inPath, "rawData") +- manifestDataPath = os.path.join(inPath, "manifestData.bin") +- manifestExtPath = os.path.join(inPath, "manifestExt.bin") +- dataForSignPath = os.path.join(inPath, "dataForSign.bin") +- +- #mandentory input files +- manifestFilePath = manifestPath +- elfFilePath = enclavePath +- pubkeyFilePath = deviceKeyPath +- +- (ret, PRODUCT_NAME, flag) = parserManifest(manifestFilePath, manifestDataPath, manifestExtPath) +- updateManifestTaApiLevel(manifestExtPath) +- +- if OTRP_FLAG == 1: +- print("package otrp sec file\n") +- updateManifestTaOtrpFlag(manifestExtPath) +- +- generateRawData(manifestDataPath, manifestExtPath, elfFilePath, configFilePath, rawFilePath) +- +- #generate AES key info to encrypt raw data +- generateAesKeyInfo(ivFilePath, keyFilePath, keyInfoFilePath) +- encryptAesKeyInfo(pubkeyFilePath, keyInfoFilePath, encKeyInfoFilePath) +- +- aesEncrypt(keyFilePath, ivFilePath, rawFilePath, encRawFilePath) +- +- contentLen = 0 +- if DEBUG == 0 or TA_TYPE == 1: +- contentLen = os.path.getsize(encKeyInfoFilePath) + SIGNATURE_LEN_256 + os.path.getsize(encRawFilePath) +- elif TA_TYPE == 2: +- contentLen = os.path.getsize(encKeyInfoFilePath) + SIGNATURE_LEN_512 + os.path.getsize(encRawFilePath) +- else: +- print("target sign type is not supported: {}".format(TA_TYPE)) +- raise RuntimeError +- +- generateDataForSign(contentLen, keyInfoFilePath, rawFilePath, dataForSignPath) +- +- generateHash(HASH256_LEN, dataForSignPath, rawDataHashPath) +- +- #remove temp files +- os.remove(ivFilePath) +- os.remove(keyFilePath) +- os.remove(keyInfoFilePath) +- os.remove(rawFilePath) +- os.remove(manifestDataPath) +- os.remove(manifestExtPath) +- os.remove(dataForSignPath) +- return +- +-def generateSecEnclave(priKeyPath, rawDataHashPath, encKeyInfoFilePath, encRawFilePath, inSignature, serverPubKey, \ +- outFile): +- inPath = os.getcwd() +- signatureFilePath = inSignature +- if DEBUG == 1: +- signatureFilePath = os.path.join(inPath, "signature.bin") +- generateSignature(priKeyPath, rawDataHashPath, signatureFilePath) +- else: +- checkSignature(rawDataHashPath, inSignature, serverPubKey) +- +- contentLen = 0 +- if DEBUG == 0 or TA_TYPE == 1: +- contentLen = os.path.getsize(encKeyInfoFilePath) + SIGNATURE_LEN_256 + os.path.getsize(encRawFilePath) +- elif TA_TYPE == 2: +- contentLen = os.path.getsize(encKeyInfoFilePath) + SIGNATURE_LEN_512 + os.path.getsize(encRawFilePath) +- else: +- print("target sign type is not supported: {}".format(TA_TYPE)) +- raise RuntimeError +- +- # secImagePath = os.path.join(outPath, productName) +- secImagePath = outFile +- with open(secImagePath, 'wb') as secImage: +- # write to sec file [1.header info] +- secImage.write(generateHeader(contentLen)) +- # write to sec file [2.AES key info] +- encKeyInfoSize = os.path.getsize(encKeyInfoFilePath) +- with open(encKeyInfoFilePath, 'rb') as encKeyInfo: +- secImage.write(encKeyInfo.read(encKeyInfoSize)) +- # write to sec file [3.signature] +- signatureSize = os.path.getsize(signatureFilePath) +- with open(signatureFilePath, 'rb') as signatureFile: +- secImage.write(signatureFile.read(signatureSize)) +- # write to sec file [4.encrypted raw data] +- encRawDataSize = os.path.getsize(encRawFilePath) +- with open(encRawFilePath, 'rb') as encRawData: +- secImage.write(encRawData.read(encRawDataSize)) +- +- if DEBUG == 1: +- os.remove(signatureFilePath) +- +- print("=========================SUCCESS============================") +- print("generate TA(V3 format) load image success: ") +- print(secImagePath) +- print("============================================================") +- return +- +-if __name__ == '__main__': +- argvs = sys.argv +- priKeyPath = "" +- configFilePath = "" +- cmd = argvs[1] +- DEBUG = int(argvs[2]) +- enclavePath = argvs[3] +- outFile = argvs[4] +- manifestPath = argvs[5] +- OTRP_FLAG = int(argvs[6]) +- TA_TYPE = int(argvs[7]) +- API_LEVEL = int(argvs[8]) +- DEVICE_PUBKEY = argvs[9] +- configFilePath = argvs[10] +- +- os.umask(127) +- inPath = os.getcwd() +- encKeyInfoFilePath = os.path.join(inPath, "KeyInfo.enc") +- encRawFilePath = os.path.join(inPath, "rawData.enc") +- rawDataHashPath = os.path.join(inPath, "rawDataHash.bin") +- +- if cmd == "digest": +- generateDigest(enclavePath, manifestPath, DEVICE_PUBKEY, configFilePath, rawDataHashPath, encKeyInfoFilePath, \ +- encRawFilePath) +- shutil.copy(rawDataHashPath, outFile) +- elif cmd == "sign": +- if DEBUG == 0: +- inSignature = argvs[11] +- serverPubKey = argvs[12] +- else: +- if TA_TYPE == 2: +- priKeyPath = argvs[11] +- inSignature = "" +- serverPubKey = "" +- generateDigest(enclavePath, manifestPath, DEVICE_PUBKEY, configFilePath, rawDataHashPath, \ +- encKeyInfoFilePath, encRawFilePath) +- generateSecEnclave(priKeyPath, rawDataHashPath, encKeyInfoFilePath, encRawFilePath, inSignature, \ +- serverPubKey, outFile) +- os.remove(rawDataHashPath) +- os.remove(encKeyInfoFilePath) +- os.remove(encRawFilePath) +diff --git a/tools/sign_tool/sign_tool.sh b/tools/sign_tool/sign_tool.sh +index 212db5d..5fd7d5b 100755 +--- a/tools/sign_tool/sign_tool.sh ++++ b/tools/sign_tool/sign_tool.sh +@@ -10,39 +10,42 @@ + + #!/bin/bash + VERSION=3 +-TA_TYPE=1 +-OTRP_FLAG=0 +-API_LEVEL=1 +-DEBUG=0 ++API_LEVEL=2 ++ONE_STEP_MODE=1 ++A_CONFIG_FILE="NULL" + + localpath="$(cd "$(dirname "$0")"; pwd)" + + print_help(){ + echo "sign tool usage: ./sign_tool.sh [options] ..." + echo "[options]" +- echo "-a API_LEVEL, indicates trustzone GP API version, defalut is 1." + echo "-c basic config file." + echo "-d sign tool command, sign/digest." + echo " The sign command is used to generate a signed enclave." + echo " The digest command is used to generate a digest value." +- echo "-f OTRP_FLAG, indicates whether the OTRP standard protocol is supported, default is 0." + echo "-i enclave to be signed." +- echo "-k private key required for single-step method, required when trustzone TA_TYPE is 2 or sgx." +- echo "-m additional config for trustzone when TA_TYPE is 2." ++ echo "-k private key required for single-step method" ++ echo "-m additional config_cloud.ini for trustzone." + echo "-o output parameters, the sign command outputs sigend enclave, the digest command outputs" + echo " digest value." + echo "-p signing server public key certificate, required for two-step method." + echo "-s the signed digest value required for two-step method, this parameter is empty to indicate" + echo " single-step method." +- echo "-t trustzone TA_TYPE, default is 1." + echo "-x enclave type, sgx or trustzone." + echo "-h printf help message." + + } + +-while getopts "d:i:x:m:a:f:t:c:k:p:s:o:h" opt ++while getopts "c:d:i:k:m:o:p:s:x:h" opt + do + case $opt in ++ c) ++ if [[ $OPTARG == -* ]]; then ++ echo "Error: parameter for -c is missing or incorrect" ++ exit -1 ++ fi ++ CONFIG_FILE=$OPTARG ++ ;; + d) + if [[ $OPTARG == -* ]]; then + echo "Error: parameter for -d is missing or incorrect" +@@ -58,13 +61,12 @@ do + fi + IN_ENCLAVE=$OPTARG + ;; +- x) ++ k) + if [[ $OPTARG == -* ]]; then +- echo "Error: parameter for -x is missing or incorrect" ++ echo "Error: parameter for -k is missing or incorrect" + exit -1 +- fi +- typeset -l ENCLAVE_TYPE +- ENCLAVE_TYPE=$OPTARG ++ fi ++ SIG_KEY=$OPTARG + ;; + m) + if [[ $OPTARG == -* ]]; then +@@ -73,55 +75,12 @@ do + fi + A_CONFIG_FILE=$OPTARG + ;; +- a) +- if [[ $OPTARG =~ ^[1-3]$ ]]; then +- API_LEVEL=$OPTARG +- else +- if [[ $OPTARG == -* ]]; then +- echo "Error: parameter for -a is missing or incorrect" +- exit -1 +- fi +- echo "Error: illegal API LEVEL" +- exit -1 +- fi +- ;; +- f) +- if [[ $OPTARG =~ ^[0-1]$ ]]; then +- OTRP_FLAG=$OPTARG +- else +- if [[ $OPTARG == -* ]]; then +- echo "Error: parameter for -f is missing or incorrect" +- exit -1 +- fi +- echo "Error: illegal OTRP FLAG" +- exit -1 +- fi +- ;; +- t) +- if [[ $OPTARG =~ ^[1-2]$ ]]; then +- TA_TYPE=$OPTARG +- else +- if [[ $OPTARG == -* ]]; then +- echo "Error: parameter for -t is missing or incorrect" +- exit -1 +- fi +- echo "Error: illegal TA TYPE" +- exit -1 +- fi +- ;; +- c) +- if [[ $OPTARG == -* ]]; then +- echo "Error: parameter for -c is missing or incorrect" +- exit -1 +- fi +- CONFIG_FILE=$OPTARG +- ;; +- k) ++ o) + if [[ $OPTARG == -* ]]; then +- echo "Error: parameter for -k is missing or incorrect" ++ echo "Error: parameter for -o is missing or incorrect" + exit -1 + fi +- SIG_KEY=$OPTARG ++ OUT_FILE=$OPTARG + ;; + p) + if [[ $OPTARG == -* ]]; then +@@ -137,12 +96,13 @@ do + fi + SIGNATURE=$OPTARG + ;; +- o) ++ x) + if [[ $OPTARG == -* ]]; then +- echo "Error: parameter for -o is missing or incorrect" ++ echo "Error: parameter for -x is missing or incorrect" + exit -1 +- fi +- OUT_FILE=$OPTARG ++ fi ++ typeset -l ENCLAVE_TYPE ++ ENCLAVE_TYPE=$OPTARG + ;; + h) + print_help +@@ -160,47 +120,48 @@ fi + + itrustee_start_sign(){ + # check_native_sign +- MANIFEST=$CONFIG_FILE +- if [ -z $MANIFEST ]; then ++ if [ -z $A_CONFIG_FILE ]; then + echo "Error: missing config file for signing iTrustee enclave" + exit -1 + fi + +- if [ ${TA_TYPE} == 2 ]; then +- if [ -z $A_CONFIG_FILE]; then +- echo "Error: TA TYPE = 2, missing additional config file for signing iTrustee enclave" +- exit -1 +- fi +- else +- A_CONFIG_FILE="NULL" +- fi +- DEVICE_PUBKEY=${localpath}/rsa_public_key_cloud.pem +- + if [ "${CMD}"x == "sign"x ]; then + if [ -z $SIGNATURE ]; then +- DEBUG=1 +- if [ -z $SIG_KEY ] && [ ${TA_TYPE} == 2 ]; then +- echo "missing the signature private key" ++ ONE_STEP_MODE=1 ++ if [ -z $CONFIG_FILE ]; then ++ echo "Error: missing config file for signing iTrustee enclave" + exit -1 + fi +- python ${localpath}/sign_tool.py "sign" "${DEBUG}" "${IN_ENCLAVE}" "${OUT_FILE}" "${MANIFEST}" "${OTRP_FLAG}" "${TA_TYPE}" "${API_LEVEL}" "${DEVICE_PUBKEY}" "${A_CONFIG_FILE}" "${SIG_KEY}" +- else +- DEBUG=0 +- if [ -z $SERVER_PUBKEY ]; then +- echo "Error: missing server public key for verifying signature" ++ if [ -z $IN_ENCLAVE ]; then ++ echo "Error: missing enclave file" + exit -1 + fi +- python ${localpath}/sign_tool.py "sign" "${DEBUG}" "${IN_ENCLAVE}" "${OUT_FILE}" "${MANIFEST}" "${OTRP_FLAG}" "${TA_TYPE}" "${API_LEVEL}" "${DEVICE_PUBKEY}" "${A_CONFIG_FILE}" "${SIGNATURE}" "${SERVER_PUBKEY}" ++ python ${localpath}/signtool_v3.py "sign" "${ONE_STEP_MODE}" "${IN_ENCLAVE}" "${OUT_FILE}" "${CONFIG_FILE}" "${A_CONFIG_FILE}" "${API_LEVEL}" ++ else ++ ONE_STEP_MODE=0 ++ python ${localpath}/signtool_v3.py "sign" "${ONE_STEP_MODE}" "NULL" "${OUT_FILE}" "NULL" "${A_CONFIG_FILE}" "${API_LEVEL}" "${SIGNATURE}" + fi + elif [ "${CMD}"x == "digest"x ]; then +- DEBUG=0 +- python ${localpath}/sign_tool.py "digest" "${DEBUG}" "${IN_ENCLAVE}" "${OUT_FILE}" "${MANIFEST}" "${OTRP_FLAG}" "${TA_TYPE}" "${API_LEVEL}" "${DEVICE_PUBKEY}" "${A_CONFIG_FILE}" ++ ONE_STEP_MODE=0 ++ if [ -z $CONFIG_FILE ]; then ++ echo "Error: missing config file for signing iTrustee enclave" ++ exit -1 ++ fi ++ if [ -z $IN_ENCLAVE ]; then ++ echo "Error: missing enclave file" ++ exit -1 ++ fi ++ python ${localpath}/signtool_v3.py "digest" "${ONE_STEP_MODE}" "${IN_ENCLAVE}" "${OUT_FILE}" "${CONFIG_FILE}" "${A_CONFIG_FILE}" "${API_LEVEL}" + else + echo "Error: illegal command" + fi + } + + sgx_start_sign(){ ++ if [ -z $IN_ENCLAVE ]; then ++ echo "Error: missing enclave file" ++ exit -1 ++ fi + SIGDATA_FILE="signdata" + if [ "${CMD}"x == "sign"x ]; then + if [ -z $SIG_KEY ]; then +@@ -246,10 +207,6 @@ if [ -z $ENCLAVE_TYPE ]; then + echo "Error: missing enclave type" + exit -1 + fi +-if [ -z $IN_ENCLAVE ]; then +- echo "Error: missing enclave file" +- exit -1 +-fi + if [ -z $OUT_FILE ]; then + echo "Error: missing out file" + exit -1 +diff --git a/tools/sign_tool/signtool_v3.py b/tools/sign_tool/signtool_v3.py +new file mode 100644 +index 0000000..dae036f +--- /dev/null ++++ b/tools/sign_tool/signtool_v3.py +@@ -0,0 +1,428 @@ ++#!/usr/bin/env python ++# coding:utf-8 ++#---------------------------------------------------------------------------- ++# Copyright (c) Huawei Technologies Co., Ltd. 2018-2020. All rights reserved. ++# iTrustee licensed under the Mulan PSL v2. ++# You can use this software according to the terms and conditions of the Mulan ++# PSL v2. ++# You may obtain a copy of Mulan PSL v2 at: ++# http://license.coscl.org.cn/MulanPSL2 ++# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY ++# KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ++# NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. ++# See the Mulan PSL v2 for more details. ++# Description: tools for generating a trusted application load image ++# Author: Li mingjuan ++# Create: 2018-02-20 ++#---------------------------------------------------------------------------- ++ ++import struct ++import os ++import sys ++import stat ++import hashlib ++import binascii ++import subprocess ++import shutil ++import getpass ++import argparse ++ ++try: ++ from configparser import SafeConfigParser ++except ImportError: ++ from ConfigParser import SafeConfigParser ++ ++from manifest import parser_manifest ++from generate_signature import gen_ta_signature ++from generate_signature import gen_hash ++ ++# fixed value, {1, 2} version are abandoned. ++VERSION = 3 ++TA_VERSION = 3 ++ ++MAX_EXT_PROP_LEN = 152 ++ ++MAGIC1 = 0xA5A55A5A ++MAGIC2 = 0x55AA ++ ++# ELF Definitions ++ELF_TYPE = 32 ++ELF_HDR_SIZE = 52 ++ELF_PHDR_SIZE = 32 ++ELF_INFO_MAGIC0_INDEX = 0 ++ELF_INFO_MAGIC1_INDEX = 1 ++ELF_INFO_MAGIC2_INDEX = 2 ++ELF_INFO_MAGIC3_INDEX = 3 ++#'\x7f' ++ELF_INFO_MAGIC0 = 127 ++#'E' ++ELF_INFO_MAGIC1 = 69 ++#'L' ++ELF_INFO_MAGIC2 = 76 ++#'F' ++ELF_INFO_MAGIC3 = 70 ++ELF_INFO_CLASS_INDEX = 4 ++ELF_INFO_CLASS_32 = 1 ++ELF_INFO_CLASS_64 = 2 ++ELF_INFO_VERSION_INDEX = 6 ++ELF_INFO_VERSION_CURRENT = 1 ++ELF_BLOCK_ALIGN = 0x1000 ++ ++ ++#---------------------------------------------------------------------------- ++# Verify ELF header contents from an input ELF file ++#---------------------------------------------------------------------------- ++def verify_elf_header(elf_path): ++ elf_type = 0 ++ with open(elf_path, 'rb') as elf: ++ elf_data = struct.unpack('B'*16, elf.read(16)) ++ elf_type = elf_data[4] ++ if ((elf_data[ELF_INFO_MAGIC0_INDEX] != ELF_INFO_MAGIC0) or \ ++ (elf_data[ELF_INFO_MAGIC1_INDEX] != ELF_INFO_MAGIC1) or \ ++ (elf_data[ELF_INFO_MAGIC2_INDEX] != ELF_INFO_MAGIC2) or \ ++ (elf_data[ELF_INFO_MAGIC3_INDEX] != ELF_INFO_MAGIC3) or \ ++ (elf_data[ELF_INFO_VERSION_INDEX] != \ ++ ELF_INFO_VERSION_CURRENT)): ++ print("invalid elf header info") ++ raise RuntimeError ++ ++ if ((elf_type == 1 and elf_data[ELF_INFO_CLASS_INDEX] != \ ++ ELF_INFO_CLASS_32) or \ ++ (elf_type == 2 and elf_data[ELF_INFO_CLASS_INDEX] != \ ++ ELF_INFO_CLASS_64) or \ ++ (elf_type != 1 and elf_type != 2)): ++ print("invliad elf format") ++ raise RuntimeError ++ return ++ ++ ++class Configuration: ++ release_type = 0 ++ otrp_flag = 0 ++ sign_type = 0 ++ public_key = "" ++ pub_key_len = 0 ++ server_ip = "" ++ config_path = "" ++ sign_key = "" ++ sign_key_len = 2048 ++ hash_type = 0 ++ padding_type = 0 ++ ++ def __init__(self, file_name): ++ parser = SafeConfigParser() ++ parser.read(file_name) ++ self.release_type = parser.get("config", "releaseType") ++ self.otrp_flag = parser.get("config", "otrpFlag") ++ self.sign_type = parser.get("config", "signType") ++ self.public_key = parser.get("config", "encryptKey") ++ self.pub_key_len = parser.get("config", "encryptKeyLen") ++ self.server_ip = parser.get("config", "serverIp") ++ self.config_path = parser.get("config", "configPath") ++ self.sign_key = parser.get("config", "signKey") ++ self.sign_key_len = parser.get("config", "signKeyLen") ++ self.hash_type = parser.get("config", "hashType") ++ self.padding_type = parser.get("config", "paddingType") ++ ++ ++def gen_header(content_len, key_version): ++ return struct.pack('IHHII', MAGIC1, MAGIC2, VERSION, content_len, \ ++ key_version) ++ ++ ++def gen_aes_key_info(cfg, iv_file_path, key_file_path, out_file_path): ++ rand_iv_cmd = "openssl rand -out {} 16".format(iv_file_path) ++ rand_key_cmd = "openssl rand -out {} 32".format(key_file_path) ++ try: ++ subprocess.check_output(rand_iv_cmd.split(), shell=False) ++ subprocess.check_output(rand_key_cmd.split(), shell=False) ++ except Exception: ++ print("rand operation failed") ++ raise RuntimeError ++ ++ os.chmod(iv_file_path, stat.S_IWUSR | stat.S_IRUSR) ++ os.chmod(key_file_path, stat.S_IWUSR | stat.S_IRUSR) ++ ++ sign_alg = 0 ++ sign_alg = sign_alg | (int(cfg.release_type) << 28) ++ sign_alg = sign_alg | (int(cfg.padding_type) << 27) ++ sign_alg = sign_alg | (int(cfg.hash_type) << 26) ++ if cfg.sign_key_len == "2048": ++ sign_alg = sign_alg | 0x00002048 ++ elif cfg.sign_key_len == "4096": ++ sign_alg = sign_alg | 0x00004096 ++ ++ print("sign_alg value is 0x%x" % sign_alg) ++ with open(out_file_path, 'wb') as out_file: ++ out_file.write(struct.pack('I', 32)) ++ out_file.write(struct.pack('I', 16)) ++ out_file.write(struct.pack('I', sign_alg)) ++ ++ with open(key_file_path, 'rb') as key_file: ++ out_file.write(key_file.read(32)) ++ ++ with open(iv_file_path, 'rb') as iv_file: ++ out_file.write(iv_file.read(16)) ++ ++ os.chmod(out_file_path, stat.S_IWUSR | stat.S_IRUSR) ++ return ++ ++ ++def encrypt_aes_key(pubkey_path, in_path, out_path): ++ cmd = "openssl rsautl -encrypt -pubin -oaep -inkey {} -in {} -out {}". \ ++ format(pubkey_path, in_path, out_path) ++ try: ++ subprocess.check_output(cmd.split(), shell=False) ++ except Exception: ++ print("RSA encrypt operation failed") ++ raise RuntimeError ++ os.chmod(out_path, stat.S_IWUSR | stat.S_IRUSR) ++ return ++ ++def gen_signature(cfg, uuid_str, raw_data_path, hash_file_path, out_file_path): ++ gen_ta_signature(cfg, uuid_str, raw_data_path, hash_file_path, out_file_path) ++ os.chmod(out_file_path, stat.S_IWUSR | stat.S_IRUSR) ++ return ++ ++def gen_raw_data(manifest_data_path, manifest_ext_path, elf_file_path, \ ++ config_path, raw_file_path): ++ manifest_size = os.path.getsize(manifest_data_path) ++ manifest_ext_size = os.path.getsize(manifest_ext_path) ++ elf_size = os.path.getsize(elf_file_path) ++ config_size = 0 ++ ++ if manifest_ext_size > MAX_EXT_PROP_LEN: ++ print("too much data in \"manifest.txt\" to be handled. \ ++ extra string len %d" \ ++ % manifest_ext_size) ++ raise RuntimeError ++ ++ verify_elf_header(elf_file_path) ++ ++ with open(raw_file_path, 'wb') as file_op: ++ header = "" ++ if os.path.isfile(config_path): ++ config_size = os.path.getsize(config_path) ++ header = struct.pack('IIIII', TA_VERSION, manifest_size, \ ++ manifest_ext_size, \ ++ elf_size, config_size) ++ file_op.write(header) ++ ++ with open(manifest_data_path, 'rb') as manifest_data: ++ file_op.write(manifest_data.read(manifest_size)) ++ ++ with open(manifest_ext_path, 'rb') as manifest_ext: ++ file_op.write(manifest_ext.read(manifest_ext_size)) ++ ++ with open(elf_file_path, 'rb') as elf: ++ file_op.write(elf.read(elf_size)) ++ if config_size != 0: ++ with open(config_path, 'rb') as config: ++ file_op.write(config.read(config_size)) ++ return ++ ++ ++def aes_encrypt(key_path, iv_path, in_file_path, out_file_path): ++ key_size = os.path.getsize(key_path) ++ with open(key_path, 'rb') as key_file: ++ key_data = key_file.read(key_size) ++ hex_key_str = binascii.b2a_hex(key_data) ++ ++ iv_size = os.path.getsize(iv_path) ++ with open(iv_path, 'rb') as iv_file: ++ iv_data = iv_file.read(iv_size) ++ hex_iv_str = binascii.b2a_hex(iv_data) ++ ++ cmd = "openssl enc -aes-256-cbc -in {} -out {} -K {} -iv {}".\ ++ format(in_file_path, out_file_path, \ ++ bytes.decode(hex_key_str), bytes.decode(hex_iv_str)) ++ try: ++ subprocess.check_output(cmd.split(), shell=False) ++ except Exception: ++ print("AES encrypt operation failed") ++ raise RuntimeError ++ ++ os.chmod(out_file_path, stat.S_IWUSR | stat.S_IRUSR) ++ return ++ ++def update_api_level(api_level, manifest): ++ data = '' ++ with open(manifest, 'r') as file_op: ++ for line in file_op: ++ if line.startswith("#") or not "gpd.ta.api_level" in line: ++ data += line ++ line = "\ngpd.ta.api_level:{}\n".format(api_level) ++ data += line ++ with open(manifest, "w") as file_op: ++ file_op.writelines(data) ++ ++ ++def update_otrp_flag(manifest): ++ data = '' ++ with open(manifest, 'r') as file_op: ++ for line in file_op: ++ if line.startswith("#") or not "gpd.ta.otrp_flag" in line: ++ data += line ++ line = "\ngpd.ta.otrp_flag:{}\n".format('true') ++ data += line ++ with open(manifest, "w") as file_op: ++ file_op.writelines(data) ++ ++ ++def gen_data_for_sign(header, key_info, raw_file, data_sign): ++ key_info_len = os.path.getsize(key_info) ++ raw_file_len = os.path.getsize(raw_file) ++ ++ with open(data_sign, 'wb') as data_fp, \ ++ open(key_info, 'rb') as key_fp, open(raw_file, 'rb') as raw_fp: ++ data_fp.write(header) ++ data_fp.write(key_fp.read(key_info_len)) ++ data_fp.write(raw_fp.read(raw_file_len)) ++ ++ ++def gen_key_version(cfg): ++ if cfg.pub_key_len == '3072': ++ return int(0x0202) ++ if cfg.pub_key_len == '2048': ++ return int(0x0002) ++ print("unhandled pulic key len %s" % cfg.pub_key_len) ++ raise RuntimeError ++ ++ ++def generate_digest(cfg, api_level, enclave_file, manifest_file, hash_path, enc_key_path, enc_raw_path): ++ # temporary files ++ in_path = os.path.dirname(os.path.abspath(manifest_file)) ++ temp_path = os.path.join(in_path, "temp") ++ shutil.rmtree(temp_path, ignore_errors=True) ++ os.mkdir(temp_path) ++ os.chmod(temp_path, stat.S_IRWXU) ++ iv_file_path = os.path.join(temp_path, "iv.bin") ++ key_file_path = os.path.join(temp_path, "aeskey.bin") ++ key_info_path = os.path.join(temp_path, "KeyInfo") ++ raw_file_path = os.path.join(temp_path, "rawData") ++ manifest_data_path = os.path.join(temp_path, "manifestData.bin") ++ manifest_ext_path = os.path.join(temp_path, "manifestExt.bin") ++ data_for_sign_path = os.path.join(temp_path, "dataForSign.bin") ++ signature_path = os.path.join(temp_path, "signature.bin") ++ ++ # mandentory input files ++ manifest_path = manifest_file ++ elf_file_path = enclave_file ++ ++ ret, product_name = parser_manifest(manifest_path, \ ++ manifest_data_path, manifest_ext_path) ++ if ret is False: ++ raise RuntimeError ++ ++ update_api_level(api_level, manifest_ext_path) ++ ++ if cfg.otrp_flag == 1: ++ print("package otrp sec file\n") ++ update_otrp_flag(manifest_ext_path) ++ ++ gen_raw_data(manifest_data_path, manifest_ext_path, elf_file_path, \ ++ cfg.config_path, raw_file_path) ++ ++ # generate AES key info to encrypt raw data ++ gen_aes_key_info(cfg, iv_file_path, key_file_path, key_info_path) ++ encrypt_aes_key(cfg.public_key, key_info_path, enc_key_path) ++ ++ aes_encrypt(key_file_path, iv_file_path, raw_file_path, enc_raw_path) ++ ++ # generate Main Header ++ content_len = os.path.getsize(enc_key_path) + \ ++ (int(cfg.sign_key_len) / 8) + \ ++ os.path.getsize(enc_raw_path) ++ key_version = gen_key_version(cfg) ++ header = gen_header(int(content_len), key_version) ++ ++ gen_data_for_sign(header, key_info_path, raw_file_path, data_for_sign_path) ++ ++ gen_hash(cfg.hash_type, data_for_sign_path, hash_path) ++ ++ #remove temp files ++ os.remove(iv_file_path) ++ os.remove(key_file_path) ++ os.remove(key_info_path) ++ os.remove(raw_file_path) ++ os.remove(manifest_data_path) ++ os.remove(manifest_ext_path) ++ os.remove(data_for_sign_path) ++ return ++ ++def gen_sec_image(cfg, enc_raw_path, enc_key_path, signature_path, out_file): ++ content_len = os.path.getsize(enc_key_path) + \ ++ (int(cfg.sign_key_len) / 8) + \ ++ os.path.getsize(enc_raw_path) ++ key_version = gen_key_version(cfg) ++ header = gen_header(int(content_len), key_version) ++ sec_img_path = out_file ++ with open(sec_img_path, 'wb') as sec_image: ++ # write to sec file [1.header info] ++ sec_image.write(header) ++ # write to sec file [2.AES key info] ++ enc_key_size = os.path.getsize(enc_key_path) ++ with open(enc_key_path, 'rb') as enc_key_info: ++ sec_image.write(enc_key_info.read(enc_key_size)) ++ # write to sec file [3.signature] ++ signature_size = os.path.getsize(signature_path) ++ with open(signature_path, 'rb') as signature_file: ++ sec_image.write(signature_file.read(signature_size)) ++ # write to sec file [4.encrypted raw data] ++ enc_raw_size = os.path.getsize(enc_raw_path) ++ with open(enc_raw_path, 'rb') as enc_raw_data: ++ sec_image.write(enc_raw_data.read(enc_raw_size)) ++ ++ print("=========================SUCCESS============================") ++ print("generate TA(V3 format) load image success: ") ++ print(sec_img_path) ++ print("============================================================") ++ ++ return ++ ++ ++def main(): ++ argvs = sys.argv ++ cmd = argvs[1] ++ one_step_mode = int(argvs[2]) ++ enclave_path = argvs[3] ++ out_file = argvs[4] ++ manifest_file = argvs[5] ++ cloud_config = argvs[6] ++ cfg = Configuration(cloud_config) ++ api_level = int(argvs[7]) ++ ++ os.umask(127) ++ ++ in_path = os.path.dirname(os.path.abspath(cloud_config)) ++ temp_path = os.path.join(in_path, "temp") ++ enc_key_path = os.path.join(temp_path, "KeyInfo.enc") ++ enc_raw_path = os.path.join(temp_path, "rawData.enc") ++ hash_path = os.path.join(temp_path, "rawDataHash.bin") ++ temp_signature = os.path.join(temp_path, "tempSignature") ++ ++ sign_tool_dir = os.path.dirname(os.path.abspath(__file__)) ++ os.chdir(sign_tool_dir) ++ if cmd == "digest": ++ generate_digest(cfg, api_level, enclave_path, manifest_file, hash_path, enc_key_path, enc_raw_path) ++ shutil.copy(hash_path, out_file) ++ elif cmd == "sign": ++ if one_step_mode == 0: ++ in_signature = argvs[8] ++ gen_sec_image(cfg, enc_raw_path, enc_key_path, in_signature, out_file) ++ else: ++ generate_digest(cfg, api_level, enclave_path, manifest_file, hash_path, enc_key_path, enc_raw_path) ++ gen_ta_signature(cfg, hash_path, temp_signature) ++ in_signature = temp_signature ++ gen_sec_image(cfg, enc_raw_path, enc_key_path, in_signature, out_file) ++ os.remove(temp_signature) ++ os.remove(enc_key_path) ++ os.remove(enc_raw_path) ++ os.remove(hash_path) ++ #remove temp files ++ shutil.rmtree(temp_path) ++ ++ ++if __name__ == '__main__': ++ main() ++ +-- +2.27.0 + diff --git a/0030-fix-sgx-two-step-mode-bug-add-dump-command.patch b/0030-fix-sgx-two-step-mode-bug-add-dump-command.patch new file mode 100644 index 0000000..d8b4647 --- /dev/null +++ b/0030-fix-sgx-two-step-mode-bug-add-dump-command.patch @@ -0,0 +1,234 @@ +From 583ac889ade73e8ffa96844dcc29a511e6c5a615 Mon Sep 17 00:00:00 2001 +From: yanlu +Date: Wed, 19 May 2021 15:45:24 +0800 +Subject: [PATCH 13/14] fix sgx two-step mode bug, add dump command + +--- + docs/sign_tool.md | 49 +++++++++++++--------- + examples/helloworld/enclave/CMakeLists.txt | 2 +- + examples/helloworld/host/CMakeLists.txt | 8 ++-- + examples/seal_data/enclave/CMakeLists.txt | 2 +- + examples/seal_data/host/CMakeLists.txt | 8 ++-- + tools/sign_tool/sign_tool.sh | 39 +++++++++-------- + 6 files changed, 62 insertions(+), 46 deletions(-) + +diff --git a/docs/sign_tool.md b/docs/sign_tool.md +index 399e4c5..e6c6e3b 100644 +--- a/docs/sign_tool.md ++++ b/docs/sign_tool.md +@@ -4,7 +4,7 @@ The sign_tool.sh helps to sign the enclave. + + ## The sign_tool.sh + +-The sign_tool.sh uses the 'sgx_sign' tool in SGX SDK for signing the sgx enclave and the 'sign_tool.py' for signing the trustzone enclave. ++The sign_tool.sh uses the 'sgx_sign' tool in SGX SDK for signing the sgx enclave and the 'signtool_v3.py' for signing the trustzone enclave. + + The tool supports the following two modes: + +@@ -19,33 +19,44 @@ The tool supports the following two modes: + - two-step method, it is used when the signature needs to be obtained from the signing organization or the private key is stored on another secure platform. + + For example: +- (1) generate the digest value. +- `$ ./sign_tool.sh –d digest –x trustzone –i input -c manifest.txt -m config_cloud.ini –o digest.data ` ++ (1) generate the signing material. ++ `$ ./sign_tool.sh –d digest –x trustzone –i input -c manifest.txt -m config_cloud.ini –o signing.data ` + + For trustzone, temporary files KeyInfo.enc, rawData.enc, and rawDataHash.bin are generated in the current directory. And for sgx, a temporary file signdata is generated in the current directory. The temporary file is required when generating the signed enclave in step 3 and is deleted after the signed enclave is generated. + +- (2) send the digest.data to the signing organization or platform and get the signature. +- +- (3) use the signature to generate the signed enclave. +- `$ ./sign_tool.sh –d sign –x trustzone –i input -c manifest.txt -m config_cloud.ini –s signature –o signed.enclave ` ++ (2) send the signing.data to the signing organization or platform and get the signature. ++ For trustzone, use rsautl command to sign the signing material. ++ ++ `$ openssl rsautl -sign -inkey sign_key.pem -in signing.data -out signature ` ++ ++ For sgx, use dgst command to sign the signing material. ++ ++ `$ openssl dgst -sha256 -sign sign_key.pem -keyform PEM -out signature signing.data ` ++ ++ (3) use the signature to generate the signed enclave. ++ ++ `$ ./sign_tool.sh –d sign –x trustzone –i input -c manifest.txt -m config_cloud.ini –s signature –o signed.enclave ` + + ## sign_tool.sh parameter + + ``` + -c basic config file. +- -d sign tool command, sign/digest. ++ -d sign tool command, sign/digest/dump. + The sign command is used to generate a signed enclave. +- The digest command is used to generate a digest value. +- -i enclave to be signed. +- -k private key required for single-step method +- -m additional config_cloud.ini for trustzone. +- -o output parameters, the sign command outputs sigend enclave, the digest command outputs +- digest value. +- -p signing server public key certificate, required for two-step method. +- -s the signed digest value required for two-step method, this parameter is empty to indicate +- single-step method. +- -x enclave type, sgx or trustzone. +- -h printf help message. ++ The digest command is used to generate signing material. ++ The dump command is used to generate metadata for sgx signed enclave. ++ -i input parameter, which is enclave to be signed for digest/sign command, and signed enclave for ++ dump command. ++ -k private key required for single-step method. ++ -m additional config_cloud.ini for trustzone. ++ -o output parameter, the sign command outputs signed enclave, the digest command outputs signing ++ material, the dump command outputs data containing the SIGStruct metadata for the SGX signed ++ enclave, which is submitted to Intel for whitelisting. ++ -p signing server public key certificate, required for sgx two-step method. ++ -s the signature value required for two-step method, this parameter is empty to indicate ++ single-step method. ++ -x enclave type, sgx or trustzone. ++ -h print help message. + ``` + **Note**: + Using the `./sign_tool.sh -h` to get help information. +diff --git a/examples/helloworld/enclave/CMakeLists.txt b/examples/helloworld/enclave/CMakeLists.txt +index f7967ef..98f50ac 100644 +--- a/examples/helloworld/enclave/CMakeLists.txt ++++ b/examples/helloworld/enclave/CMakeLists.txt +@@ -71,7 +71,7 @@ if(CC_GP) + + target_include_directories( ${PREFIX} PRIVATE + ${CMAKE_CURRENT_BINARY_DIR} +- ${LOCAL_ROOT_PATH}/debug/inc ++ ${LOCAL_ROOT_PATH}/${CMAKE_BINARY_DIR}/inc + ${LOCAL_ROOT_PATH}/inc/host_inc + ${LOCAL_ROOT_PATH}/inc/host_inc/gp + ${LOCAL_ROOT_PATH}/inc/enclave_inc +diff --git a/examples/helloworld/host/CMakeLists.txt b/examples/helloworld/host/CMakeLists.txt +index 60173a9..c6f2166 100644 +--- a/examples/helloworld/host/CMakeLists.txt ++++ b/examples/helloworld/host/CMakeLists.txt +@@ -39,10 +39,10 @@ if(CC_GP) + endif() + add_executable(${OUTPUT} ${SOURCE_FILE} ${AUTO_FILES}) + target_include_directories(${OUTPUT} PRIVATE +- ${LOCAL_ROOT_PATH}/debug/inc +- ${LOCAL_ROOT_PATH}/inc/host_inc +- ${LOCAL_ROOT_PATH}/inc/host_inc/gp +- ${CMAKE_CURRENT_BINARY_DIR}) ++ ${LOCAL_ROOT_PATH}/${CMAKE_BINARY_DIR}/inc ++ ${LOCAL_ROOT_PATH}/inc/host_inc ++ ${LOCAL_ROOT_PATH}/inc/host_inc/gp ++ ${CMAKE_CURRENT_BINARY_DIR}) + if(${CMAKE_VERSION} VERSION_GREATER_EQUAL "3.13.0") + target_link_directories(${OUTPUT} PRIVATE ${CMAKE_LIBRARY_OUTPUT_DIRECTORY}) + endif() +diff --git a/examples/seal_data/enclave/CMakeLists.txt b/examples/seal_data/enclave/CMakeLists.txt +index b24e498..542163e 100644 +--- a/examples/seal_data/enclave/CMakeLists.txt ++++ b/examples/seal_data/enclave/CMakeLists.txt +@@ -66,7 +66,7 @@ if(CC_GP) + + target_include_directories( ${PREFIX} PRIVATE + ${CMAKE_CURRENT_BINARY_DIR} +- ${LOCAL_ROOT_PATH}/debug/inc ++ ${LOCAL_ROOT_PATH}/${CMAKE_BINARY_DIR}/inc + ${LOCAL_ROOT_PATH}/inc/host_inc + ${LOCAL_ROOT_PATH}/inc/host_inc/gp + ${LOCAL_ROOT_PATH}/inc/enclave_inc +diff --git a/examples/seal_data/host/CMakeLists.txt b/examples/seal_data/host/CMakeLists.txt +index 691cd07..a0986d1 100644 +--- a/examples/seal_data/host/CMakeLists.txt ++++ b/examples/seal_data/host/CMakeLists.txt +@@ -40,10 +40,10 @@ if(CC_GP) + endif() + add_executable(${OUTPUT} ${SOURCE_FILE} ${AUTO_FILES}) + target_include_directories(${OUTPUT} PRIVATE +- ${LOCAL_ROOT_PATH}/debug/inc +- ${LOCAL_ROOT_PATH}/inc/host_inc +- ${LOCAL_ROOT_PATH}/inc/host_inc/gp +- ${CMAKE_CURRENT_BINARY_DIR}) ++ ${LOCAL_ROOT_PATH}/${CMAKE_BINARY_DIR}/inc ++ ${LOCAL_ROOT_PATH}/inc/host_inc ++ ${LOCAL_ROOT_PATH}/inc/host_inc/gp ++ ${CMAKE_CURRENT_BINARY_DIR}) + if(${CMAKE_VERSION} VERSION_GREATER_EQUAL "3.13.0") + target_link_directories(${OUTPUT} PRIVATE ${CMAKE_LIBRARY_OUTPUT_DIRECTORY}) + endif() +diff --git a/tools/sign_tool/sign_tool.sh b/tools/sign_tool/sign_tool.sh +index 5fd7d5b..9906bff 100755 +--- a/tools/sign_tool/sign_tool.sh ++++ b/tools/sign_tool/sign_tool.sh +@@ -20,19 +20,22 @@ print_help(){ + echo "sign tool usage: ./sign_tool.sh [options] ..." + echo "[options]" + echo "-c basic config file." +- echo "-d sign tool command, sign/digest." ++ echo "-d sign tool command, sign/digest/dump." + echo " The sign command is used to generate a signed enclave." +- echo " The digest command is used to generate a digest value." +- echo "-i enclave to be signed." +- echo "-k private key required for single-step method" ++ echo " The digest command is used to generate signing material." ++ echo " The dump command is used to generate metadata for sgx signed enclave." ++ echo "-i input parameter, which is enclave to be signed for digest/sign command, and signed enclave for" ++ echo " dump command." ++ echo "-k private key required for single-step method." + echo "-m additional config_cloud.ini for trustzone." +- echo "-o output parameters, the sign command outputs sigend enclave, the digest command outputs" +- echo " digest value." +- echo "-p signing server public key certificate, required for two-step method." +- echo "-s the signed digest value required for two-step method, this parameter is empty to indicate" ++ echo "-o output parameter, the sign command outputs signed enclave, the digest command outputs signing" ++ echo " material, the dump command outputs data containing the SIGStruct metadata for the SGX signed" ++ echo " enclave, which is submitted to Intel for whitelisting." ++ echo "-p signing server public key certificate, required for sgx two-step method." ++ echo "-s the signature value required for two-step method, this parameter is empty to indicate" + echo " single-step method." + echo "-x enclave type, sgx or trustzone." +- echo "-h printf help message." ++ echo "-h print help message." + + } + +@@ -164,12 +167,12 @@ sgx_start_sign(){ + fi + SIGDATA_FILE="signdata" + if [ "${CMD}"x == "sign"x ]; then +- if [ -z $SIG_KEY ]; then +- echo "Error: missing sign key" +- exit -1 +- fi + if [ -z $SIGNATURE ]; then +- if [ -z $CONFIG_FILE ]; then ++ if [ -z $SIG_KEY ]; then ++ echo "Error: missing sign key" ++ exit -1 ++ fi ++ if [ -z $CONFIG_FILE ]; then + sgx_sign sign -enclave ${IN_ENCLAVE} -key ${SIG_KEY} -out ${OUT_FILE} + else + sgx_sign sign -enclave ${IN_ENCLAVE} -key ${SIG_KEY} -out ${OUT_FILE} -config ${CONFIG_FILE} +@@ -180,9 +183,9 @@ sgx_start_sign(){ + exit -1 + fi + if [ -z $CONFIG_FILE ]; then +- sgx_sign catsig -enclave ${IN_ENCLAVE} -key ${SERVER_PUBKEY} -sig ${SIGNATURE} -unsignd ${SIGDATA_FILE} -out ${OUT_FILE} ++ sgx_sign catsig -enclave ${IN_ENCLAVE} -key ${SERVER_PUBKEY} -sig ${SIGNATURE} -unsigned ${SIGDATA_FILE} -out ${OUT_FILE} + else +- sgx_sign catsig -enclave ${IN_ENCLAVE} -key ${SERVER_PUBKEY} -sig ${SIGNATURE} -unsignd ${SIGDATA_FILE} -out ${OUT_FILE} -config ${CONFIG_FILE} ++ sgx_sign catsig -enclave ${IN_ENCLAVE} -key ${SERVER_PUBKEY} -sig ${SIGNATURE} -unsigned ${SIGDATA_FILE} -out ${OUT_FILE} -config ${CONFIG_FILE} + fi + rm -rf ${SIGDATA_FILE} + fi +@@ -192,7 +195,9 @@ sgx_start_sign(){ + else + sgx_sign gendata -enclave ${IN_ENCLAVE} -out ${SIGDATA_FILE} -config ${CONFIG_FILE} + fi +- openssl dgst -sha256 -out ${OUT_FILE} ${SIGDATA_FILE} ++ cp ${SIGDATA_FILE} ${OUT_FILE} ++ elif [ "${CMD}"x == "dump"x ]; then ++ sgx_sign dump -enclave ${IN_ENCLAVE} -dumpfile ${OUT_FILE} + else + echo "Error: illegal command" + fi +-- +2.27.0 + diff --git a/0031-set-signtool_v3.py-path.patch b/0031-set-signtool_v3.py-path.patch new file mode 100644 index 0000000..e031757 --- /dev/null +++ b/0031-set-signtool_v3.py-path.patch @@ -0,0 +1,166 @@ +From 2d9a481617422a423612417835a48b0614716f2d Mon Sep 17 00:00:00 2001 +From: yanlu +Date: Thu, 20 May 2021 10:40:25 +0800 +Subject: [PATCH 14/14] set signtool_v3.py path + +--- + README.en.md | 2 +- + README.md | 2 +- + examples/helloworld/enclave/CMakeLists.txt | 2 +- + examples/helloworld/host/CMakeLists.txt | 2 +- + examples/seal_data/enclave/CMakeLists.txt | 2 +- + examples/seal_data/host/CMakeLists.txt | 2 +- + src/enclave_src/CMakeLists.txt | 2 +- + src/host_src/CMakeLists.txt | 2 +- + tools/sign_tool/sign_tool.sh | 13 +++++++++---- + 9 files changed, 17 insertions(+), 12 deletions(-) + +diff --git a/README.en.md b/README.en.md +index 8aaa1b0..ec7ada0 100644 +--- a/README.en.md ++++ b/README.en.md +@@ -49,7 +49,7 @@ Then save as test.edl + set(CURRENT_ROOT_PATH ${CMAKE_CURRENT_SOURCE_DIR}) + set(EDL_FILE test.edl) + set(LOCAL_ROOT_PATH "$ENV{CC_SDK}") +- set(SECGEAR_INSTALL_PATH /lib64/) ++ set(SECGEAR_INSTALL_PATH /usr/lib64/) + set(CODEGEN codegen) + if(CC_GP) + set(CODETYPE trustzone) +diff --git a/README.md b/README.md +index b95dcc9..2d09831 100644 +--- a/README.md ++++ b/README.md +@@ -41,7 +41,7 @@ SecGear则是面向计算产业的机密计算安全应用开发套件。旨在 + set(CURRENT_ROOT_PATH ${CMAKE_CURRENT_SOURCE_DIR}) + set(EDL_FILE test.edl) + set(LOCAL_ROOT_PATH "$ENV{CC_SDK}") +- set(SECGEAR_INSTALL_PATH /lib64/) ++ set(SECGEAR_INSTALL_PATH /usr/lib64/) + set(CODEGEN codegen) + if(CC_GP) + set(CODETYPE trustzone) +diff --git a/examples/helloworld/enclave/CMakeLists.txt b/examples/helloworld/enclave/CMakeLists.txt +index 98f50ac..0546183 100644 +--- a/examples/helloworld/enclave/CMakeLists.txt ++++ b/examples/helloworld/enclave/CMakeLists.txt +@@ -71,7 +71,7 @@ if(CC_GP) + + target_include_directories( ${PREFIX} PRIVATE + ${CMAKE_CURRENT_BINARY_DIR} +- ${LOCAL_ROOT_PATH}/${CMAKE_BINARY_DIR}/inc ++ ${CMAKE_BINARY_DIR}/inc + ${LOCAL_ROOT_PATH}/inc/host_inc + ${LOCAL_ROOT_PATH}/inc/host_inc/gp + ${LOCAL_ROOT_PATH}/inc/enclave_inc +diff --git a/examples/helloworld/host/CMakeLists.txt b/examples/helloworld/host/CMakeLists.txt +index c6f2166..96985cb 100644 +--- a/examples/helloworld/host/CMakeLists.txt ++++ b/examples/helloworld/host/CMakeLists.txt +@@ -39,7 +39,7 @@ if(CC_GP) + endif() + add_executable(${OUTPUT} ${SOURCE_FILE} ${AUTO_FILES}) + target_include_directories(${OUTPUT} PRIVATE +- ${LOCAL_ROOT_PATH}/${CMAKE_BINARY_DIR}/inc ++ ${CMAKE_BINARY_DIR}/inc + ${LOCAL_ROOT_PATH}/inc/host_inc + ${LOCAL_ROOT_PATH}/inc/host_inc/gp + ${CMAKE_CURRENT_BINARY_DIR}) +diff --git a/examples/seal_data/enclave/CMakeLists.txt b/examples/seal_data/enclave/CMakeLists.txt +index 542163e..f80efb8 100644 +--- a/examples/seal_data/enclave/CMakeLists.txt ++++ b/examples/seal_data/enclave/CMakeLists.txt +@@ -66,7 +66,7 @@ if(CC_GP) + + target_include_directories( ${PREFIX} PRIVATE + ${CMAKE_CURRENT_BINARY_DIR} +- ${LOCAL_ROOT_PATH}/${CMAKE_BINARY_DIR}/inc ++ ${CMAKE_BINARY_DIR}/inc + ${LOCAL_ROOT_PATH}/inc/host_inc + ${LOCAL_ROOT_PATH}/inc/host_inc/gp + ${LOCAL_ROOT_PATH}/inc/enclave_inc +diff --git a/examples/seal_data/host/CMakeLists.txt b/examples/seal_data/host/CMakeLists.txt +index a0986d1..19920b4 100644 +--- a/examples/seal_data/host/CMakeLists.txt ++++ b/examples/seal_data/host/CMakeLists.txt +@@ -40,7 +40,7 @@ if(CC_GP) + endif() + add_executable(${OUTPUT} ${SOURCE_FILE} ${AUTO_FILES}) + target_include_directories(${OUTPUT} PRIVATE +- ${LOCAL_ROOT_PATH}/${CMAKE_BINARY_DIR}/inc ++ ${CMAKE_BINARY_DIR}/inc + ${LOCAL_ROOT_PATH}/inc/host_inc + ${LOCAL_ROOT_PATH}/inc/host_inc/gp + ${CMAKE_CURRENT_BINARY_DIR}) +diff --git a/src/enclave_src/CMakeLists.txt b/src/enclave_src/CMakeLists.txt +index 66a36ea..f6d353c 100644 +--- a/src/enclave_src/CMakeLists.txt ++++ b/src/enclave_src/CMakeLists.txt +@@ -11,7 +11,7 @@ + project(secgear_tee C) + + set(target_lib secgear_tee) +-set(LIBRARY_INSTALL /lib64) ++set(LIBRARY_INSTALL /usr/lib64) + + set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib) + +diff --git a/src/host_src/CMakeLists.txt b/src/host_src/CMakeLists.txt +index 25d245f..a545e27 100644 +--- a/src/host_src/CMakeLists.txt ++++ b/src/host_src/CMakeLists.txt +@@ -10,7 +10,7 @@ + + set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -fvisibility=hidden -fPIC -Wno-stringop-overflow") + +-set(LIBRARY_INSTALL /lib64) ++set(LIBRARY_INSTALL /usr/lib64) + + include_directories(${LOCAL_ROOT_PATH}/inc/host_inc) + +diff --git a/tools/sign_tool/sign_tool.sh b/tools/sign_tool/sign_tool.sh +index 9906bff..5469f80 100755 +--- a/tools/sign_tool/sign_tool.sh ++++ b/tools/sign_tool/sign_tool.sh +@@ -12,9 +12,14 @@ + VERSION=3 + API_LEVEL=2 + ONE_STEP_MODE=1 +-A_CONFIG_FILE="NULL" + + localpath="$(cd "$(dirname "$0")"; pwd)" ++pypath="/lib/secGear" ++if [ -f ${localpath}/signtool_v3.py ]; then ++ signtoolpath=${localpath} ++else ++ signtoolpath=${pypath} ++fi + + print_help(){ + echo "sign tool usage: ./sign_tool.sh [options] ..." +@@ -139,10 +144,10 @@ itrustee_start_sign(){ + echo "Error: missing enclave file" + exit -1 + fi +- python ${localpath}/signtool_v3.py "sign" "${ONE_STEP_MODE}" "${IN_ENCLAVE}" "${OUT_FILE}" "${CONFIG_FILE}" "${A_CONFIG_FILE}" "${API_LEVEL}" ++ python ${signtoolpath}/signtool_v3.py "sign" "${ONE_STEP_MODE}" "${IN_ENCLAVE}" "${OUT_FILE}" "${CONFIG_FILE}" "${A_CONFIG_FILE}" "${API_LEVEL}" + else + ONE_STEP_MODE=0 +- python ${localpath}/signtool_v3.py "sign" "${ONE_STEP_MODE}" "NULL" "${OUT_FILE}" "NULL" "${A_CONFIG_FILE}" "${API_LEVEL}" "${SIGNATURE}" ++ python ${signtoolpath}/signtool_v3.py "sign" "${ONE_STEP_MODE}" "NULL" "${OUT_FILE}" "NULL" "${A_CONFIG_FILE}" "${API_LEVEL}" "${SIGNATURE}" + fi + elif [ "${CMD}"x == "digest"x ]; then + ONE_STEP_MODE=0 +@@ -154,7 +159,7 @@ itrustee_start_sign(){ + echo "Error: missing enclave file" + exit -1 + fi +- python ${localpath}/signtool_v3.py "digest" "${ONE_STEP_MODE}" "${IN_ENCLAVE}" "${OUT_FILE}" "${CONFIG_FILE}" "${A_CONFIG_FILE}" "${API_LEVEL}" ++ python ${signtoolpath}/signtool_v3.py "digest" "${ONE_STEP_MODE}" "${IN_ENCLAVE}" "${OUT_FILE}" "${CONFIG_FILE}" "${A_CONFIG_FILE}" "${API_LEVEL}" + else + echo "Error: illegal command" + fi +-- +2.27.0 + diff --git a/0032-del-size_to_aligned_size.patch b/0032-del-size_to_aligned_size.patch new file mode 100644 index 0000000..d0f3c33 --- /dev/null +++ b/0032-del-size_to_aligned_size.patch @@ -0,0 +1,25 @@ +From f31970aac34d3e6fb6c50508ec5d5d4e07da0e0a Mon Sep 17 00:00:00 2001 +From: zgzxx +Date: Fri, 21 May 2021 11:14:06 +0800 +Subject: [PATCH] del size_to_aligned_size + +--- + tools/codegener/Commonfunc.ml | 2 +- + 1 file changed, 1 insertion(+), 1 deletion(-) + +diff --git a/tools/codegener/Commonfunc.ml b/tools/codegener/Commonfunc.ml +index 42d62c4..6f3966a 100644 +--- a/tools/codegener/Commonfunc.ml ++++ b/tools/codegener/Commonfunc.ml +@@ -428,7 +428,7 @@ let set_in_memcpy (fd : func_decl) = + sprintf "for (int i = 0; i < %s; i++) {\n if((%s + i)->%s) {\n memcpy(in_buf + %s_p + tmp_size, (uint8_t *)(%s + i)->%s, %s);\n tmp_size += size_to_aligned_size(%s);\n }\n }\n tmp_size = 0;\n " (get_param_count pty) decl.identifier mem_decl.identifier mem_decl.identifier decl.identifier mem_decl.identifier (get_sizestr_2 (mem_pty, mem_decl) decl) (get_sizestr_2 (mem_pty, mem_decl) decl) in + [ + "/* Copy in_params to in_buf*/"; +- sprintf "memcpy(in_buf, &args_size, size_to_aligned_size(sizeof(%s_size_t)));" fd.fname; ++ sprintf "memcpy(in_buf, &args_size, sizeof(%s_size_t));" fd.fname; + if in_memcpy <> [] then + concat "\n " in_memcpy ^ "\n " ^ + concat "\n " +-- +2.27.0 + diff --git a/0033-modify-the-error-information-when-missing-c-and-m.patch b/0033-modify-the-error-information-when-missing-c-and-m.patch new file mode 100644 index 0000000..7ccc725 --- /dev/null +++ b/0033-modify-the-error-information-when-missing-c-and-m.patch @@ -0,0 +1,34 @@ +From 909a866a5023c8f23b504ce1307283df834d2b55 Mon Sep 17 00:00:00 2001 +From: yanlu +Date: Wed, 26 May 2021 11:49:49 +0800 +Subject: [PATCH 1/6] modify the error information when missing -c and -m + +--- + tools/sign_tool/sign_tool.sh | 4 ++-- + 1 file changed, 2 insertions(+), 2 deletions(-) + +diff --git a/tools/sign_tool/sign_tool.sh b/tools/sign_tool/sign_tool.sh +index 5469f80..0435a67 100755 +--- a/tools/sign_tool/sign_tool.sh ++++ b/tools/sign_tool/sign_tool.sh +@@ -129,7 +129,7 @@ fi + itrustee_start_sign(){ + # check_native_sign + if [ -z $A_CONFIG_FILE ]; then +- echo "Error: missing config file for signing iTrustee enclave" ++ echo "Error: missing additional config_cloud.ini file for signing iTrustee enclave" + exit -1 + fi + +@@ -137,7 +137,7 @@ itrustee_start_sign(){ + if [ -z $SIGNATURE ]; then + ONE_STEP_MODE=1 + if [ -z $CONFIG_FILE ]; then +- echo "Error: missing config file for signing iTrustee enclave" ++ echo "Error: missing basic config file for signing iTrustee enclave" + exit -1 + fi + if [ -z $IN_ENCLAVE ]; then +-- +2.27.0 + diff --git a/0034-normalize-the-log-printed-by-PrintInfo.patch b/0034-normalize-the-log-printed-by-PrintInfo.patch new file mode 100644 index 0000000..a4662e0 --- /dev/null +++ b/0034-normalize-the-log-printed-by-PrintInfo.patch @@ -0,0 +1,55 @@ +From 5a34d5f560f1b35b4ae8892e07ff852af1a7a38a Mon Sep 17 00:00:00 2001 +From: chenmaodong +Date: Mon, 31 May 2021 14:26:34 +0800 +Subject: [PATCH 2/6] normalize the log printed by PrintInfo + +Signed-off-by: chenmaodong +--- + inc/enclave_inc/gp/itrustee/secgear_log.h | 31 +++++++++++------------ + 1 file changed, 15 insertions(+), 16 deletions(-) + +diff --git a/inc/enclave_inc/gp/itrustee/secgear_log.h b/inc/enclave_inc/gp/itrustee/secgear_log.h +index 2e27b05..819fa86 100644 +--- a/inc/enclave_inc/gp/itrustee/secgear_log.h ++++ b/inc/enclave_inc/gp/itrustee/secgear_log.h +@@ -24,22 +24,21 @@ + #define PRINT_STRACE 2 + #define PRINT_DEBUG 3 + +-#define PrintInfo(level, fmt, args...) \ +- if (level <= PRINT_LEVEL) { \ +- switch (level) { \ +- case 0: \ +- SLog("%s %s: " fmt "\n", "[secGear][ERROR]", __FUNCTION__, ## args); \ +- break; \ +- case 1: \ +- SLog("%s %s: " fmt "\n", "[secGear][WARNING]", __FUNCTION__, ## args); \ +- break; \ +- case 2: \ +- SLog("%s %s: " fmt "\n", "[secGear][STRACE]", __FUNCTION__, ## args); \ +- break; \ +- default: \ +- SLog("%s %s: " fmt "\n", "[secGear][DEBUG]", __FUNCTION__, ## args); \ +- } \ ++#define PrintInfo(level, fmt, args...) \ ++ if (level <= PRINT_LEVEL) { \ ++ switch (level) { \ ++ case 0: \ ++ SLog("%s " fmt "\n", "[secGear][ERROR]", ## args); \ ++ break; \ ++ case 1: \ ++ SLog("%s " fmt "\n", "[secGear][WARNING]", ## args); \ ++ break; \ ++ case 2: \ ++ SLog("%s " fmt "\n", "[secGear][STRACE]", ## args); \ ++ break; \ ++ default: \ ++ SLog("%s " fmt "\n", "[secGear][DEBUG]", ## args); \ ++ } \ + } + +- + #endif +-- +2.27.0 + diff --git a/0035-itrustee-add-lrt-support-itrustee.patch b/0035-itrustee-add-lrt-support-itrustee.patch new file mode 100644 index 0000000..dad75a4 --- /dev/null +++ b/0035-itrustee-add-lrt-support-itrustee.patch @@ -0,0 +1,99 @@ +From 7fceb33ffd6e4f09faa6ba717f80ba6a51591f36 Mon Sep 17 00:00:00 2001 +From: LiFeng +Date: Tue, 1 Jun 2021 16:38:18 +0800 +Subject: [PATCH 3/6] itrustee: add lrt support itrustee + +Signed-off-by: LiFeng +--- + examples/CMakeLists.txt | 1 + + examples/lrt/CMakeLists.txt | 5 +++-- + examples/lrt/enclave/CMakeLists.txt | 17 ++++++++++++----- + examples/lrt/host/main.c | 1 + + 4 files changed, 17 insertions(+), 7 deletions(-) + +diff --git a/examples/CMakeLists.txt b/examples/CMakeLists.txt +index cfd0171..07fc0fb 100644 +--- a/examples/CMakeLists.txt ++++ b/examples/CMakeLists.txt +@@ -12,6 +12,7 @@ if(CC_GP) + COMMAND cp ${LOCAL_ROOT_PATH}/inc/enclave_inc/gp/itrustee/*.h ${CMAKE_BINARY_DIR}/inc/secGear/) + add_subdirectory(seal_data) + add_subdirectory(helloworld) ++ #add_subdirectory(lrt) + endif() + + if(CC_SGX) +diff --git a/examples/lrt/CMakeLists.txt b/examples/lrt/CMakeLists.txt +index 9059590..45283a3 100644 +--- a/examples/lrt/CMakeLists.txt ++++ b/examples/lrt/CMakeLists.txt +@@ -20,8 +20,9 @@ set(CODEGEN codegen) + + if(CC_GP) + set(CODETYPE trustzone) +- execute_process(COMMAND uuidgen -r OUTPUT_VARIABLE UUID) +- string(REPLACE "\n" "" UUID ${UUID}) ++ # execute_process(COMMAND uuidgen -r OUTPUT_VARIABLE UUID) ++ #string(REPLACE "\n" "" UUID ${UUID}) ++ set(UUID f68fd704-6eb1-4d14-b218-722850eb3ef0) + add_definitions(-DPATH="/data/${UUID}.sec") + endif() + +diff --git a/examples/lrt/enclave/CMakeLists.txt b/examples/lrt/enclave/CMakeLists.txt +index 64494cc..acd1607 100644 +--- a/examples/lrt/enclave/CMakeLists.txt ++++ b/examples/lrt/enclave/CMakeLists.txt +@@ -28,9 +28,9 @@ if(CC_GP) + #set signed output + set(OUTPUT ${UUID}.sec) + #set whilelist. default: /vendor/bin/teec_hello +- set(WHITE_LIST_0 /vendor/bin/helloworld) ++ set(WHITE_LIST_0 /vendor/bin/lrt) + set(WHITE_LIST_OWNER root) +- set(WHITE_LIST_1 /vendor/bin/secgear_helloworld) ++ set(WHITE_LIST_1 /vendor/bin/secgear_lrt) + set(WHITELIST WHITE_LIST_0 WHITE_LIST_1) + + set(AUTO_FILES ${CMAKE_CURRENT_BINARY_DIR}/${PREFIX}_t.h ${CMAKE_CURRENT_BINARY_DIR}/${PREFIX}_t.c ${CMAKE_CURRENT_BINARY_DIR}/${PREFIX}_args.h) +@@ -55,7 +55,7 @@ set(COMMON_C_FLAGS "-W -Wall -Werror -fno-short-enums -fno-omit-frame-pointer + set(COMMON_C_LINK_FLAGS "-Wl,-z,now -Wl,-z,relro -Wl,-z,noexecstack -Wl,-nostdlib -nodefaultlibs -nostartfiles") + + if(CC_GP) +- configure_file("${CMAKE_CURRENT_SOURCE_DIR}/manifest.txt.in" "${CMAKE_CURRENT_SOURCE_DIR}/manifest.txt") ++ # configure_file("${CMAKE_CURRENT_SOURCE_DIR}/manifest.txt.in" "${CMAKE_CURRENT_SOURCE_DIR}/manifest.txt") + + set(CMAKE_C_FLAGS "${COMMON_C_FLAGS} -march=armv8-a ") + set(CMAKE_C_FLAGS_RELEASE "${CMAKE_C_FLAGS} -s -fPIC") +@@ -99,8 +99,15 @@ if(CC_GP) + + add_custom_command(TARGET ${PREFIX} + POST_BUILD +- COMMAND bash ${SIGN_TOOL} -d sign -x trustzone -i ${CMAKE_LIBRARY_OUTPUT_DIRECTORY}/lib${PREFIX}.so -c ${CMAKE_CURRENT_SOURCE_DIR}/manifest.txt +- -o ${CMAKE_LIBRARY_OUTPUT_DIRECTORY}/${OUTPUT}) ++ # COMMAND bash ${SIGN_TOOL} -d sign -x trustzone -i ${CMAKE_LIBRARY_OUTPUT_DIRECTORY}/lib${PREFIX}.so -c ${CMAKE_CURRENT_SOURCE_DIR}/manifest.txt -m ${CMAKE_CURRENT_SOURCE_DIR}/config_cloud.ini -o ${CMAKE_LIBRARY_OUTPUT_DIRECTORY}/${OUTPUT} ++ COMMAND bash ${SIGN_TOOL} -d digest -x trustzone -i ${CMAKE_LIBRARY_OUTPUT_DIRECTORY}/lib${PREFIX}.so -c ${CMAKE_CURRENT_SOURCE_DIR}/manifest.txt ++ -m ${CMAKE_CURRENT_SOURCE_DIR}/config_cloud.ini -o ${CMAKE_LIBRARY_OUTPUT_DIRECTORY}/temp_hash ++ COMMAND openssl rsautl -sign -inkey ${CMAKE_CURRENT_SOURCE_DIR}/cert/private_key.pem -in ${CMAKE_LIBRARY_OUTPUT_DIRECTORY}/temp_hash -out ${CMAKE_LIBRARY_OUTPUT_DIRECTORY}/temp_signature ++ COMMAND bash ${SIGN_TOOL} -d sign -x trustzone -s ${CMAKE_LIBRARY_OUTPUT_DIRECTORY}/temp_signature -m ${CMAKE_CURRENT_SOURCE_DIR}/config_cloud.ini -o ${CMAKE_LIBRARY_OUTPUT_DIRECTORY}/${OUTPUT} ++ # COMMAND rm -rf ${CMAKE_LIBRARY_OUTPUT_DIRECTORY}/temp_hash ++ #COMMAND rm -rf ${CMAKE_LIBRARY_OUTPUT_DIRECTORY}/temp_signature ++ ) ++ + + install(FILES ${CMAKE_LIBRARY_OUTPUT_DIRECTORY}/${OUTPUT} + DESTINATION /data +diff --git a/examples/lrt/host/main.c b/examples/lrt/host/main.c +index ba078c7..92ff47a 100644 +--- a/examples/lrt/host/main.c ++++ b/examples/lrt/host/main.c +@@ -13,6 +13,7 @@ + #include + #include + #include ++#include + #include "enclave.h" + #include "lrt_u.h" + +-- +2.27.0 + diff --git a/0036-enclave-use-the-can-pull-image-from-hub.oepkgs.net.patch b/0036-enclave-use-the-can-pull-image-from-hub.oepkgs.net.patch new file mode 100644 index 0000000..6cba74b --- /dev/null +++ b/0036-enclave-use-the-can-pull-image-from-hub.oepkgs.net.patch @@ -0,0 +1,26 @@ +From 764886f9baa739d9688cb1875692b4687434153b Mon Sep 17 00:00:00 2001 +From: LiFeng +Date: Tue, 1 Jun 2021 18:48:30 +0800 +Subject: [PATCH 4/6] enclave: use the can-pull image from hub.oepkgs.net + +Signed-off-by: LiFeng +--- + examples/lrt/enclave.yaml | 2 +- + 1 file changed, 1 insertion(+), 1 deletion(-) + +diff --git a/examples/lrt/enclave.yaml b/examples/lrt/enclave.yaml +index b1bc19b..7734a24 100644 +--- a/examples/lrt/enclave.yaml ++++ b/examples/lrt/enclave.yaml +@@ -28,7 +28,7 @@ spec: + spec: + containers: + - name: hell_lifeng +- image: secgear_hello ++ image: hub.oepkgs.net/lifeng2221dd1/hello_secgear:v1.0 + imagePullPolicy: IfNotPresent + name: helloworld + resources: +-- +2.27.0 + diff --git a/0037-add-description-about-file-parameter-path-for-sign_t.patch b/0037-add-description-about-file-parameter-path-for-sign_t.patch new file mode 100644 index 0000000..823daa8 --- /dev/null +++ b/0037-add-description-about-file-parameter-path-for-sign_t.patch @@ -0,0 +1,26 @@ +From ac2ccfb69c60dba6eb472d2d62da53f5890a07ce Mon Sep 17 00:00:00 2001 +From: yanlu +Date: Wed, 2 Jun 2021 15:04:34 +0800 +Subject: [PATCH 5/6] add description about file parameter path for + sign_tool.sh + +--- + docs/sign_tool.md | 2 +- + 1 file changed, 1 insertion(+), 1 deletion(-) + +diff --git a/docs/sign_tool.md b/docs/sign_tool.md +index e6c6e3b..a092f19 100644 +--- a/docs/sign_tool.md ++++ b/docs/sign_tool.md +@@ -4,7 +4,7 @@ The sign_tool.sh helps to sign the enclave. + + ## The sign_tool.sh + +-The sign_tool.sh uses the 'sgx_sign' tool in SGX SDK for signing the sgx enclave and the 'signtool_v3.py' for signing the trustzone enclave. ++The sign_tool.sh uses the 'sgx_sign' tool in SGX SDK for signing the sgx enclave and the 'signtool_v3.py' for signing the trustzone enclave. When signing the trustzone enclave, it is recommended that use the absolute path to specify the file parameters, if provide a relative path, is should be a path relative to 'signtool_v3.py'. + + The tool supports the following two modes: + +-- +2.27.0 + diff --git a/0038-fix-use-after-free-in-cc_enclave_create.patch b/0038-fix-use-after-free-in-cc_enclave_create.patch new file mode 100644 index 0000000..e306e0b --- /dev/null +++ b/0038-fix-use-after-free-in-cc_enclave_create.patch @@ -0,0 +1,805 @@ +From f82ae0a78901c62644a53257d72fbc932d350ed7 Mon Sep 17 00:00:00 2001 +From: chenmaodong +Date: Wed, 2 Jun 2021 17:16:56 +0800 +Subject: [PATCH 6/6] fix use-after-free in cc_enclave_create The last + parameter 'enclave' of cc_enclave_create will not be a double pointer, it'll + be a single pointer now. Besides, the memory of parameter 'enclave' will + malloc and free by users, you can check the example to find how to use it. + +Signed-off-by: chenmaodong +--- + examples/helloworld/host/CMakeLists.txt | 4 +- + examples/helloworld/host/main.c | 14 ++-- + examples/lrt/host/CMakeLists.txt | 4 +- + examples/lrt/host/main.c | 6 +- + examples/seal_data/host/CMakeLists.txt | 4 +- + examples/seal_data/host/main.c | 13 ++-- + examples/tls_enclave/host/main.c | 6 +- + inc/host_inc/enclave.h | 14 ++-- + inc/host_inc/enclave_internal.h | 12 +-- + .../gp/itrustee/bottom_memory_check.c | 17 +++- + src/host_src/enclave.c | 78 +++++++------------ + src/host_src/enclave_internal.c | 4 +- + src/host_src/gp/gp_enclave.c | 18 ++--- + src/host_src/sgx/sgx_enclave.c | 29 +++---- + tools/codegener/Genuntrust.ml | 21 ++++- + tools/codegener/intel/CodeGen.ml | 18 ++++- + 16 files changed, 144 insertions(+), 118 deletions(-) + +diff --git a/examples/helloworld/host/CMakeLists.txt b/examples/helloworld/host/CMakeLists.txt +index 96985cb..3710954 100644 +--- a/examples/helloworld/host/CMakeLists.txt ++++ b/examples/helloworld/host/CMakeLists.txt +@@ -63,9 +63,9 @@ if(CC_SGX) + endif() + + if(CC_SIM) +- target_link_libraries(${OUTPUT} secgearsim) ++ target_link_libraries(${OUTPUT} secgearsim pthread) + else() +- target_link_libraries(${OUTPUT} secgear) ++ target_link_libraries(${OUTPUT} secgear pthread) + endif() + set_target_properties(${OUTPUT} PROPERTIES SKIP_BUILD_RPATH TRUE) + +diff --git a/examples/helloworld/host/main.c b/examples/helloworld/host/main.c +index 7213a5e..a26fb6f 100644 +--- a/examples/helloworld/host/main.c ++++ b/examples/helloworld/host/main.c +@@ -25,6 +25,10 @@ int main() + char *path = PATH; + char buf[BUF_LEN]; + cc_enclave_t *context = NULL; ++ context = (cc_enclave_t *)malloc(sizeof(cc_enclave_t)); ++ if (!context) { ++ return CC_ERROR_OUT_OF_MEMORY; ++ } + cc_enclave_result_t res; + + printf("Create secgear enclave\n"); +@@ -43,7 +47,7 @@ int main() + (void)strcat(real_p, "/enclave.signed.so"); + } + +- res = cc_enclave_create(real_p, AUTO_ENCLAVE_TYPE, 0, SECGEAR_DEBUG_FLAG, NULL, 0, &context); ++ res = cc_enclave_create(real_p, AUTO_ENCLAVE_TYPE, 0, SECGEAR_DEBUG_FLAG, NULL, 0, context); + if (res != CC_SUCCESS) { + printf("Create enclave error\n"); + return res; +@@ -56,11 +60,9 @@ int main() + printf("%s\n", buf); + } + +- if (context != NULL) { +- res = cc_enclave_destroy(context); +- if(res != CC_SUCCESS) { +- printf("Destroy enclave error\n"); +- } ++ res = cc_enclave_destroy(context); ++ if(res != CC_SUCCESS) { ++ printf("Destroy enclave error\n"); + } + return res; + } +diff --git a/examples/lrt/host/CMakeLists.txt b/examples/lrt/host/CMakeLists.txt +index 13f891a..1266384 100644 +--- a/examples/lrt/host/CMakeLists.txt ++++ b/examples/lrt/host/CMakeLists.txt +@@ -62,9 +62,9 @@ if(CC_SGX) + endif() + + if(CC_SIM) +- target_link_libraries(${OUTPUT} secgearsim) ++ target_link_libraries(${OUTPUT} secgearsim pthread) + else() +- target_link_libraries(${OUTPUT} secgear) ++ target_link_libraries(${OUTPUT} secgear pthread) + endif() + set_target_properties(${OUTPUT} PROPERTIES SKIP_BUILD_RPATH TRUE) + +diff --git a/examples/lrt/host/main.c b/examples/lrt/host/main.c +index ba078c7..fd735d4 100644 +--- a/examples/lrt/host/main.c ++++ b/examples/lrt/host/main.c +@@ -24,6 +24,10 @@ int main() + char *path = PATH; + char buf[BUF_LEN]; + cc_enclave_t *context = NULL; ++ context = (cc_enclave_t*)malloc(sizeof(cc_enclave_t)); ++ if (!context) { ++ return CC_ERROR_OUT_OF_MEMORY; ++ } + cc_enclave_result_t res; + + printf("Create secgear enclave\n"); +@@ -42,7 +46,7 @@ int main() + (void)strcat(real_p, "/enclave.signed.so"); + } + +- res = cc_enclave_create(real_p, AUTO_ENCLAVE_TYPE, 0, SECGEAR_DEBUG_FLAG, NULL, 0, &context); ++ res = cc_enclave_create(real_p, AUTO_ENCLAVE_TYPE, 0, SECGEAR_DEBUG_FLAG, NULL, 0, context); + if (res != CC_SUCCESS) { + printf("Create enclave error\n"); + return res; +diff --git a/examples/seal_data/host/CMakeLists.txt b/examples/seal_data/host/CMakeLists.txt +index 19920b4..ef750b0 100644 +--- a/examples/seal_data/host/CMakeLists.txt ++++ b/examples/seal_data/host/CMakeLists.txt +@@ -64,9 +64,9 @@ if(CC_SGX) + endif() + + if(CC_SIM) +- target_link_libraries(${OUTPUT} secgearsim) ++ target_link_libraries(${OUTPUT} secgearsim pthread) + else() +- target_link_libraries(${OUTPUT} secgear) ++ target_link_libraries(${OUTPUT} secgear pthread) + endif() + set_target_properties(${OUTPUT} PROPERTIES SKIP_BUILD_RPATH TRUE) + +diff --git a/examples/seal_data/host/main.c b/examples/seal_data/host/main.c +index ddfa253..9b1c4a6 100644 +--- a/examples/seal_data/host/main.c ++++ b/examples/seal_data/host/main.c +@@ -22,8 +22,7 @@ int main() + char *path = PATH; + char buf[BUF_LEN]; + cc_enclave_result_t res; +- cc_enclave_t *context = NULL; +- ++ cc_enclave_t context = {0}; + printf("Create secgear enclave\n"); + res = cc_enclave_create(path, AUTO_ENCLAVE_TYPE, 0, SECGEAR_DEBUG_FLAG, NULL, 0, &context); + if (res != CC_SUCCESS) { +@@ -31,18 +30,16 @@ int main() + return res; + } + +- res = seal_data_test_func(context, &retval, buf, BUF_LEN); ++ res = seal_data_test_func(&context, &retval, buf, BUF_LEN); + if (res != CC_SUCCESS || retval != (int)CC_SUCCESS) { + printf("Ecall enclave error\n"); + } else { + printf("%s\n", buf); + } + +- if (context != NULL) { +- res = cc_enclave_destroy(context); +- if(res != CC_SUCCESS) { +- printf("Destroy enclave error\n"); +- } ++ res = cc_enclave_destroy(&context); ++ if(res != CC_SUCCESS) { ++ printf("Destroy enclave error\n"); + } + return res; + } +diff --git a/examples/tls_enclave/host/main.c b/examples/tls_enclave/host/main.c +index 4407e64..c801558 100644 +--- a/examples/tls_enclave/host/main.c ++++ b/examples/tls_enclave/host/main.c +@@ -126,6 +126,10 @@ int main(int argc, const char *argv[]) + { + char *path = PATH; + cc_enclave_t *context = NULL; ++ context = (cc_enclave_t*)malloc(sizeof(cc_enclave_t)); ++ if (!context) { ++ return CC_ERROR_OUT_OF_MEMORY; ++ } + struct sockaddr_in client_addr; + socklen_t client_len; + int server_fd = -1; +@@ -147,7 +151,7 @@ int main(int argc, const char *argv[]) + return CC_FAIL; + } + printf("Create secgear enclave\n"); +- res = cc_enclave_create(path, AUTO_ENCLAVE_TYPE, 0, SECGEAR_DEBUG_FLAG, NULL, 0, &context); ++ res = cc_enclave_create(path, AUTO_ENCLAVE_TYPE, 0, SECGEAR_DEBUG_FLAG, NULL, 0, context); + if (res != CC_SUCCESS) { + printf("Create enclave error\n"); + goto end; +diff --git a/inc/host_inc/enclave.h b/inc/host_inc/enclave.h +index ca9e8da..1e3aefb 100644 +--- a/inc/host_inc/enclave.h ++++ b/inc/host_inc/enclave.h +@@ -74,13 +74,13 @@ typedef struct _enclave { + * hrough this attribute + * */ + CC_API_SPEC cc_enclave_result_t cc_enclave_create( +- const char *path, +- enclave_type_t type, +- uint32_t version, +- uint32_t flags, +- const enclave_features_t *features, +- const uint32_t features_count, +- cc_enclave_t **enclave); ++ const char *path, ++ enclave_type_t type, ++ uint32_t version, ++ uint32_t flags, ++ const enclave_features_t *features, ++ const uint32_t features_count, ++ cc_enclave_t *enclave); + + CC_API_SPEC cc_enclave_result_t cc_enclave_destroy(cc_enclave_t *context); + +diff --git a/inc/host_inc/enclave_internal.h b/inc/host_inc/enclave_internal.h +index 771b7a3..5541557 100644 +--- a/inc/host_inc/enclave_internal.h ++++ b/inc/host_inc/enclave_internal.h +@@ -33,9 +33,9 @@ typedef enum _enclave_state { + /*the ops function structure is used to ecall, create, and destroy specific enclave*/ + struct cc_enclave_ops { + cc_enclave_result_t (*cc_create_enclave)( +- cc_enclave_t **enclave, +- const enclave_features_t *features, +- const uint32_t features_count); ++ cc_enclave_t *enclave, ++ const enclave_features_t *features, ++ const uint32_t features_count); + + cc_enclave_result_t (*cc_destroy_enclave)(cc_enclave_t *enclave); + +@@ -83,12 +83,12 @@ typedef struct _list_ops_management { + } list_ops_management; + + /*enclave engine register, unregister function*/ +-typedef cc_enclave_result_t (*p_tee_registered)(cc_enclave_t **context, void *handle); ++typedef cc_enclave_result_t (*p_tee_registered)(cc_enclave_t *context, void *handle); + typedef cc_enclave_result_t (*p_tee_unregistered)(cc_enclave_t *context, enclave_type_version_t type); + + + /*creating enclave, first check in the list whether this engine has been added */ +-uint32_t look_tee_in_list(enclave_type_version_t type, cc_enclave_t **); ++uint32_t look_tee_in_list(enclave_type_version_t type, cc_enclave_t *); + + enclave_type_version_t match_tee_type_version(enclave_type_t type, uint32_t version); + +@@ -101,7 +101,7 @@ cc_enclave_result_t find_engine_registered(void *handle, p_tee_registered *p_fun + + //////////////////////////////////////////////////////////////////////////////////////////// + /*each engine needs to implement registered, and the unregistered function declaration*/ +-CC_API_SPEC cc_enclave_result_t cc_tee_registered(cc_enclave_t **context, void *handle); ++CC_API_SPEC cc_enclave_result_t cc_tee_registered(cc_enclave_t *context, void *handle); + CC_API_SPEC cc_enclave_result_t cc_tee_unregistered(cc_enclave_t *context, enclave_type_version_t type_version); + CC_API_SPEC void add_ops_list(struct list_ops_desc *node); + CC_API_SPEC void remove_ops_list(const struct list_ops_desc *node); +diff --git a/src/enclave_src/gp/itrustee/bottom_memory_check.c b/src/enclave_src/gp/itrustee/bottom_memory_check.c +index 9b26c00..c32b2c3 100644 +--- a/src/enclave_src/gp/itrustee/bottom_memory_check.c ++++ b/src/enclave_src/gp/itrustee/bottom_memory_check.c +@@ -12,6 +12,8 @@ + + #include "bottom_memory_check.h" + #include "tee_mem_mgmt_api.h" ++#include "tee_log.h" ++ + /* + * param buffer [IN] point to buffer address + * param size [IN] buffer size to be checked +@@ -21,7 +23,12 @@ + */ + bool itrustee_memory_in_enclave(const void *buffer, uint32_t size) + { +- return TEE_IsSecureMemory(buffer, size); ++ if (!TEE_CheckMemoryAccessRights(TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_ANY_OWNER, buffer, size)) { ++ return true; ++ } else if (!TEE_CheckMemoryAccessRights(TEE_MEMORY_ACCESS_WRITE | TEE_MEMORY_ACCESS_ANY_OWNER, buffer, size)) { ++ return true; ++ } ++ return false; + } + + /* +@@ -31,8 +38,12 @@ bool itrustee_memory_in_enclave(const void *buffer, uint32_t size) + * retval false target buffer is within enclave + * retval true target buffer is outside of enclave + */ +- + bool itrustee_memory_out_enclave(const void *buffer, uint32_t size) + { +- return !TEE_IsSecureMemory(buffer, size); ++ if (!TEE_CheckMemoryAccessRights(TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_ANY_OWNER, buffer, size) && ++ !TEE_CheckMemoryAccessRights(TEE_MEMORY_ACCESS_WRITE | TEE_MEMORY_ACCESS_ANY_OWNER, buffer, size)) { ++ return false; ++ } ++ return true; + } ++ +diff --git a/src/host_src/enclave.c b/src/host_src/enclave.c +index 204c808..4b75b6e 100644 +--- a/src/host_src/enclave.c ++++ b/src/host_src/enclave.c +@@ -34,9 +34,8 @@ static void check_dlopen_engine(p_tee_unregistered unregistered_func, cc_enclave + pthread_mutex_unlock(&(g_list_ops.mutex_work)); + } + +- +-static void error_handle(cc_enclave_t **l_context, void *handle, p_tee_registered registered_func, +- p_tee_unregistered unregistered_func, cc_enclave_t ***enclave, char* path, bool check) ++static void error_handle(cc_enclave_t *l_context, void *handle, p_tee_registered registered_func, ++ p_tee_unregistered unregistered_func, char* path, bool check) + { + cc_enclave_result_t tmp_res; + if (check == true) { +@@ -46,19 +45,19 @@ static void error_handle(cc_enclave_t **l_context, void *handle, p_tee_registere + pthread_mutex_unlock(&(g_list_ops.mutex_work)); + } + /* in list find engine: handle is null and l_context is not null */ +- if (*l_context != NULL && (*l_context)->list_ops_node && !handle) { +- tmp_res = find_engine_registered((*l_context)->list_ops_node->ops_desc->handle, NULL, &unregistered_func); ++ if (l_context != NULL && l_context->list_ops_node && !handle) { ++ tmp_res = find_engine_registered(l_context->list_ops_node->ops_desc->handle, NULL, &unregistered_func); + if (tmp_res != CC_SUCCESS) { + print_error_term("Can not find unregistered in the failed exit phase\n"); + } else { +- check_dlopen_engine(unregistered_func, *l_context); ++ check_dlopen_engine(unregistered_func, l_context); + } + } + /* handle is not null, means dlopen is ok */ + if (handle) { + /* check if registered invoke success */ +- if ((*l_context) != NULL && registered_func && unregistered_func && (*l_context)->list_ops_node) { +- check_dlopen_engine(unregistered_func,*l_context); ++ if (l_context != NULL && registered_func && unregistered_func && l_context->list_ops_node) { ++ check_dlopen_engine(unregistered_func, l_context); + } else { + /* means registered func invoke fail OR find_engine_registered fail */ + dlclose(handle); +@@ -67,14 +66,6 @@ static void error_handle(cc_enclave_t **l_context, void *handle, p_tee_registere + if (path) { + free(path); + } +- +- if (*l_context) { +- free(*l_context); +- } +- *l_context = NULL; +- if (*enclave != NULL) { +- **enclave = NULL; +- } + } + + /* Lock to check the number of enclave +@@ -107,9 +98,9 @@ done: + * uses the currently unsupported bit. the simulation feature and the debug mode only supports sgx + */ + static bool check_flag(cc_enclave_result_t *res, const char *path, uint32_t flags, const enclave_features_t *features, +- const uint32_t features_count, cc_enclave_t **enclave) ++ const uint32_t features_count, cc_enclave_t *enclave) + { +- if (enclave == NULL || (*enclave != NULL && (*enclave)->used_flag == true)) { ++ if (enclave == NULL || (enclave != NULL && enclave->used_flag == true)) { + *res = CC_ERROR_INVALID_ENCLAVE_ID; + return false; + } +@@ -140,18 +131,6 @@ static bool chose_engine_type(cc_enclave_result_t *res, enclave_type_t type, uin + return true; + } + +-static bool allocate_context_memory(cc_enclave_result_t *res, cc_enclave_t **l_context) +-{ +- *l_context = (cc_enclave_t *)malloc(sizeof(cc_enclave_t)); +- if (*l_context == NULL) { +- *res = CC_ERROR_OUT_OF_MEMORY; +- print_error_term("Memory out \n"); +- return false; +- } +- memset(*l_context, 0, sizeof(cc_enclave_t)); +- return true; +-} +- + /* check and transform enclave paths */ + static bool check_transform_path(cc_enclave_result_t *res, const char *path, char **l_path) + { +@@ -182,7 +161,7 @@ static bool check_transform_path(cc_enclave_result_t *res, const char *path, cha + + /* The enclave variable is the output context when successfully created */ + cc_enclave_result_t cc_enclave_create(const char *path, enclave_type_t type, uint32_t version, uint32_t flags, +- const enclave_features_t *features, const uint32_t features_count, cc_enclave_t **enclave) ++ const enclave_features_t *features, const uint32_t features_count, cc_enclave_t *enclave) + { + int32_t ires = 0; + uint32_t uires = 0; +@@ -191,7 +170,6 @@ cc_enclave_result_t cc_enclave_create(const char *path, enclave_type_t type, uin + char *l_path = NULL; + + cc_enclave_result_t res; +- cc_enclave_t *l_context = NULL; + enclave_type_version_t type_version; + + p_tee_registered registered_func = NULL; +@@ -208,8 +186,8 @@ cc_enclave_result_t cc_enclave_create(const char *path, enclave_type_t type, uin + return res; + } + +- if (!check_transform_path(&res, path, &l_path) || !chose_engine_type(&res, type, version, &type_version) +- || !allocate_context_memory(&res, &l_context)) { ++ memset(enclave, 0, sizeof(cc_enclave_t)); ++ if (!check_transform_path(&res, path, &l_path) || !chose_engine_type(&res, type, version, &type_version)) { + goto done; + } + +@@ -220,11 +198,11 @@ cc_enclave_result_t cc_enclave_create(const char *path, enclave_type_t type, uin + + /* initialize the context */ + +- pthread_rwlock_init(&(l_context->rwlock), NULL); +- l_context->path = l_path; +- l_context->flags = flags; +- l_context->type = type_version; +- l_context->used_flag = true; ++ pthread_rwlock_init(&(enclave->rwlock), NULL); ++ enclave->path = l_path; ++ enclave->flags = flags; ++ enclave->type = type_version; ++ enclave->used_flag = true; + + /* if an enclave is created multiple times, first find it in the global list, + * maybe the information about this engine has been filled in the list +@@ -232,7 +210,7 @@ cc_enclave_result_t cc_enclave_create(const char *path, enclave_type_t type, uin + ires = pthread_mutex_lock(&(g_list_ops.mutex_work)); + SECGEAR_CHECK_MUTEX_RES_CC(ires, res); + if (g_list_ops.count > 0) { +- uires = look_tee_in_list(type_version, &l_context); ++ uires = look_tee_in_list(type_version, enclave); + } + ires = pthread_mutex_unlock(&(g_list_ops.mutex_work)); + SECGEAR_CHECK_MUTEX_RES_CC(ires, res); +@@ -252,7 +230,7 @@ cc_enclave_result_t cc_enclave_create(const char *path, enclave_type_t type, uin + res = find_engine_registered(handle, ®istered_func, &unregistered_func); + SECGEAR_CHECK_RES_UNLOCK(res); + +- res = (*registered_func)(&l_context, handle); ++ res = (*registered_func)(enclave, handle); + SECGEAR_CHECK_RES_UNLOCK(res); + + ires = pthread_mutex_unlock(&(g_list_ops.mutex_work)); +@@ -260,10 +238,9 @@ cc_enclave_result_t cc_enclave_create(const char *path, enclave_type_t type, uin + } + + /* call the registered function of each engine */ +- *enclave = l_context; +- if (l_context->list_ops_node != NULL && l_context->list_ops_node->ops_desc->ops->cc_create_enclave != NULL) { ++ if (enclave->list_ops_node != NULL && enclave->list_ops_node->ops_desc->ops->cc_create_enclave != NULL) { + /* failure of this function will not bring out additional memory that needs to be managed */ +- res = l_context->list_ops_node->ops_desc->ops->cc_create_enclave(enclave, features, features_count); ++ res = enclave->list_ops_node->ops_desc->ops->cc_create_enclave(enclave, features, features_count); + SECGEAR_CHECK_RES(res); + } else { + print_error_goto("Enclave type version %d no valid ops function", type_version); +@@ -271,11 +248,10 @@ cc_enclave_result_t cc_enclave_create(const char *path, enclave_type_t type, uin + + return CC_SUCCESS; + done: +- error_handle(&l_context, handle, registered_func, unregistered_func, &enclave, l_path, check); ++ error_handle(enclave, handle, registered_func, unregistered_func, l_path, check); + return res; + } + +- + cc_enclave_result_t cc_enclave_destroy(cc_enclave_t *context) + { + int32_t ires = 0; +@@ -289,7 +265,10 @@ cc_enclave_result_t cc_enclave_destroy(cc_enclave_t *context) + return CC_ERROR_BAD_PARAMETERS; + } + +- pthread_rwlock_wrlock(&(context->rwlock)); ++ ires = pthread_rwlock_wrlock(&(context->rwlock)); ++ if (ires) { ++ return CC_ERROR_BUSY; ++ } + if (context->list_ops_node->ops_desc->ops->cc_destroy_enclave != NULL) { + res = context->list_ops_node->ops_desc->ops->cc_destroy_enclave(context); + SECGEAR_CHECK_RES(res); +@@ -302,7 +281,7 @@ cc_enclave_result_t cc_enclave_destroy(cc_enclave_t *context) + SECGEAR_CHECK_RES(res); + + /* lock call unregistered func */ +- pthread_mutex_lock(&(g_list_ops.mutex_work)); ++ ires = pthread_mutex_lock(&(g_list_ops.mutex_work)); + SECGEAR_CHECK_MUTEX_RES_CC(ires, res); + /* call enclave engine free node */ + res = (*unregistered_funcc)(context, context->list_ops_node->ops_desc->type_version); +@@ -318,7 +297,7 @@ cc_enclave_result_t cc_enclave_destroy(cc_enclave_t *context) + } + /* free enclave number resources */ + g_list_ops.enclaveState.enclave_count--; +- pthread_mutex_unlock(&(g_list_ops.mutex_work)); ++ ires = pthread_mutex_unlock(&(g_list_ops.mutex_work)); + SECGEAR_CHECK_MUTEX_RES_CC(ires, res); + + res = CC_SUCCESS; +@@ -330,7 +309,6 @@ done: + pthread_rwlock_unlock(&context->rwlock); + pthread_rwlock_destroy(&context->rwlock); + explicit_bzero(context, sizeof(cc_enclave_t)); +- free(context); + } + return res; + } +diff --git a/src/host_src/enclave_internal.c b/src/host_src/enclave_internal.c +index 962fc07..b30a207 100644 +--- a/src/host_src/enclave_internal.c ++++ b/src/host_src/enclave_internal.c +@@ -318,7 +318,7 @@ enclave_type_version_t match_tee_type_version(enclave_type_t type, uint32_t vers + /* find return 1, otherwise 0 + * Lock: prevent it from being intercepted by other insertion + * operations when searching, not in this function, but in the calling function */ +-uint32_t look_tee_in_list(enclave_type_version_t type, cc_enclave_t **context) ++uint32_t look_tee_in_list(enclave_type_version_t type, cc_enclave_t *context) + { + uint32_t res = 0; + struct list_ops_desc *p = g_list_ops.list_head; +@@ -328,7 +328,7 @@ uint32_t look_tee_in_list(enclave_type_version_t type, cc_enclave_t **context) + /* this enclave ref +1 */ + ++(p->ops_desc->count); + /* Assign the found node to the context */ +- (*context)->list_ops_node = p; ++ context->list_ops_node = p; + break; + } + p = p->next; +diff --git a/src/host_src/gp/gp_enclave.c b/src/host_src/gp/gp_enclave.c +index 86ea941..c7554de 100644 +--- a/src/host_src/gp/gp_enclave.c ++++ b/src/host_src/gp/gp_enclave.c +@@ -343,13 +343,13 @@ cleanup: + } + + /* itrustee enclave engine create func */ +-cc_enclave_result_t _gp_create(cc_enclave_t **enclave, ++cc_enclave_result_t _gp_create(cc_enclave_t *enclave, + const enclave_features_t *features, const uint32_t features_count) + { + TEEC_Result result_tee; + cc_enclave_result_t result_cc; + +- if (!*enclave) { ++ if (!enclave) { + print_error_term("Context parameter error\n"); + return CC_ERROR_BAD_PARAMETERS; + } +@@ -361,7 +361,7 @@ cc_enclave_result_t _gp_create(cc_enclave_t **enclave, + } + + gp_context_t *gp_context = NULL; +- result_cc = malloc_and_init_context(&gp_context, (*enclave)->path, (*enclave)->type); ++ result_cc = malloc_and_init_context(&gp_context, enclave->path, enclave->type); + if (result_cc != CC_SUCCESS) { + return result_cc; + } +@@ -372,18 +372,18 @@ cc_enclave_result_t _gp_create(cc_enclave_t **enclave, + operation.started = 1; + operation.paramTypes = TEEC_PARAM_TYPES(TEEC_NONE, TEEC_NONE, TEEC_MEMREF_TEMP_INPUT, TEEC_MEMREF_TEMP_INPUT); + +- (gp_context->ctx).ta_path = (uint8_t*)(*enclave)->path; ++ (gp_context->ctx).ta_path = (uint8_t*)enclave->path; + + uint32_t origin; + result_tee = TEEC_OpenSession(&(gp_context->ctx), &(gp_context->session), &gp_context->uuid, + TEEC_LOGIN_IDENTIFY, NULL, &operation, &origin); + if (result_tee != TEEC_SUCCESS) { +- result_cc = conversion_res_status(result_tee, (*enclave)->type); ++ result_cc = conversion_res_status(result_tee, enclave->type); + print_error_term("TEEC open session failed\n"); + goto cleanup; + } + print_debug("TEEC open session success\n"); +- (*enclave)->private_data = (void *)gp_context; ++ enclave->private_data = (void *)gp_context; + return CC_SUCCESS; + cleanup: + TEEC_FinalizeContext(&(gp_context->ctx)); +@@ -606,17 +606,17 @@ struct list_ops_desc g_node = { + #define OPS_STRU g_ops + + /* enclave engine registered */ +-cc_enclave_result_t cc_tee_registered(cc_enclave_t **context, void *handle) ++cc_enclave_result_t cc_tee_registered(cc_enclave_t *context, void *handle) + { + /* 1 check enclave type; 2-4 check node fill */ + size_t len = strlen(OPS_NAME.name); +- if (OPS_NAME.type_version != (*context)->type || OPS_NODE.ops_desc != &OPS_NAME || ++ if (OPS_NAME.type_version != context->type || OPS_NODE.ops_desc != &OPS_NAME || + len >= MAX_ENGINE_NAME_LEN || OPS_NAME.ops != &OPS_STRU) { + print_error_goto("The struct cc_enclave_ops_desc initialization error\n"); + } + + OPS_NAME.handle = handle; +- (*context)->list_ops_node = &OPS_NODE; ++ context->list_ops_node = &OPS_NODE; + add_ops_list(&OPS_NODE); + return CC_SUCCESS; + done: +diff --git a/src/host_src/sgx/sgx_enclave.c b/src/host_src/sgx/sgx_enclave.c +index 258c58a..aa26957 100644 +--- a/src/host_src/sgx/sgx_enclave.c ++++ b/src/host_src/sgx/sgx_enclave.c +@@ -70,7 +70,8 @@ cc_enclave_result_t conversion_res_status(uint32_t enclave_res, enclave_type_ver + } + } + +-cc_enclave_result_t _sgx_create_with_features(cc_enclave_t **enclave, const enclave_features_t *features, sgx_context_t **l_context) ++cc_enclave_result_t _sgx_create_with_features(cc_enclave_t *enclave, const enclave_features_t *features, ++ sgx_context_t *l_context) + { + cc_enclave_result_t res; + sgx_status_t sgx_res; +@@ -90,8 +91,8 @@ cc_enclave_result_t _sgx_create_with_features(cc_enclave_t **enclave, const encl + l_config.num_uworkers = l_switch->host_worker; + + enclave_ex_p[SGX_CREATE_ENCLAVE_EX_SWITCHLESS_BIT_IDX] = (const void *)&l_config; +- sgx_res = sgx_create_enclave_ex((*enclave)->path, (uint32_t)((*enclave)->flags & SECGEAR_DEBUG_FLAG), NULL, +- NULL, &((*l_context)->edi), NULL, SGX_CREATE_ENCLAVE_EX_SWITCHLESS, enclave_ex_p); ++ sgx_res = sgx_create_enclave_ex(enclave->path, (uint32_t)(enclave->flags & SECGEAR_DEBUG_FLAG), NULL, ++ NULL, &(l_context->edi), NULL, SGX_CREATE_ENCLAVE_EX_SWITCHLESS, enclave_ex_p); + } else if (features->setting_type & _CESGX_PROTECTED_CODE_LOADER_FEATURES) { + /* For the Sealing Enclave and the IP Enclave to be able to seal and unseal the + decryption key, both enclaves must be signed with the same Intel SGX ISV +@@ -100,14 +101,14 @@ cc_enclave_result_t _sgx_create_with_features(cc_enclave_t **enclave, const encl + l_plc = (cesgx_plc_config_t *)features->feature_desc; + SECGEAR_CHECK_SIZE(l_plc->len); + SECGEAR_CHECK_CHAR(l_plc->path); +- sgx_res = sgx_create_encrypted_enclave((*enclave)->path, (uint32_t)((*enclave)->flags & SECGEAR_DEBUG_FLAG), NULL, +- NULL, &((*l_context)->edi), NULL, (uint8_t *)l_plc->path); ++ sgx_res = sgx_create_encrypted_enclave(enclave->path, (uint32_t)(enclave->flags & SECGEAR_DEBUG_FLAG), NULL, ++ NULL, &(l_context->edi), NULL, (uint8_t *)l_plc->path); + } else { + res = CC_ERROR_BAD_STATE; + print_error_goto("The set feature is currently not supported\n"); + } + if (sgx_res != SGX_SUCCESS) { +- res = conversion_res_status(sgx_res, (*enclave)->type); ++ res = conversion_res_status(sgx_res, enclave->type); + print_error_goto("Failed to create sgx enclave %s\n",cc_enclave_res2_str(res)); + } + res = CC_SUCCESS; +@@ -115,7 +116,7 @@ done: + return res; + } + +-cc_enclave_result_t _sgx_create(cc_enclave_t **enclave, const enclave_features_t *features, ++cc_enclave_result_t _sgx_create(cc_enclave_t *enclave, const enclave_features_t *features, + const uint32_t features_count) + { + cc_enclave_result_t res = CC_ERROR_UNEXPECTED; +@@ -129,15 +130,15 @@ cc_enclave_result_t _sgx_create(cc_enclave_t **enclave, const enclave_features_t + } + switch (features_count) { + case 0: +- sgx_res = sgx_create_enclave((*enclave)->path, (uint32_t)((*enclave)->flags & SECGEAR_DEBUG_FLAG), NULL, ++ sgx_res = sgx_create_enclave(enclave->path, (uint32_t)(enclave->flags & SECGEAR_DEBUG_FLAG), NULL, + NULL, &(l_context->edi), NULL); + if (sgx_res != SGX_SUCCESS) { +- res = conversion_res_status(sgx_res, (*enclave)->type); ++ res = conversion_res_status(sgx_res, enclave->type); + print_error_goto("Failed to create sgx enclave\n"); + } + break; + case 1: +- res = _sgx_create_with_features(enclave, features, &l_context); ++ res = _sgx_create_with_features(enclave, features, l_context); + if (res != CC_SUCCESS) { + goto done; + } +@@ -146,7 +147,7 @@ cc_enclave_result_t _sgx_create(cc_enclave_t **enclave, const enclave_features_t + res = CC_ERROR_BAD_STATE; + print_error_goto("SGX currently does not support setting features\n"); + } +- (*enclave)->private_data = (void *)l_context; ++ enclave->private_data = (void *)l_context; + return CC_SUCCESS; + done: + if (l_context) { +@@ -229,15 +230,15 @@ struct list_ops_desc sgx_ops_node = { + #define OPS_NODE sgx_ops_node + #define OPS_STRU sgx_ops + +-cc_enclave_result_t cc_tee_registered(cc_enclave_t **context, void *handle) ++cc_enclave_result_t cc_tee_registered(cc_enclave_t *context, void *handle) + { + size_t len = strlen(OPS_NAME.name); +- if (OPS_NAME.type_version != (*context)->type || OPS_NODE.ops_desc != &OPS_NAME || ++ if (OPS_NAME.type_version != context->type || OPS_NODE.ops_desc != &OPS_NAME || + len >= MAX_ENGINE_NAME_LEN || OPS_NAME.ops != &OPS_STRU) { + print_error_goto("The struct cc_enclave_ops_desc initialization error\n"); + } + OPS_NAME.handle = handle; +- (*context)->list_ops_node = &OPS_NODE; ++ context->list_ops_node = &OPS_NODE; + add_ops_list(&OPS_NODE); + return CC_SUCCESS; + done: +diff --git a/tools/codegener/Genuntrust.ml b/tools/codegener/Genuntrust.ml +index 8edbc8b..7171ef2 100644 +--- a/tools/codegener/Genuntrust.ml ++++ b/tools/codegener/Genuntrust.ml +@@ -49,6 +49,20 @@ let get_param_count (pt: parameter_type) = + let set_call_user_func (fd : func_decl) = + [ + "/* Call the cc_enclave function */"; ++ "if (!enclave) {"; ++ " ret = CC_ERROR_BAD_PARAMETERS;"; ++ " goto exit;"; ++ "}"; ++ "if (pthread_rwlock_rdlock(&enclave->rwlock)) {"; ++ " ret = CC_ERROR_BUSY;"; ++ " goto exit;"; ++ "}"; ++ "if (!enclave->list_ops_node || !enclave->list_ops_node->ops_desc ||"; ++ " !enclave->list_ops_node->ops_desc->ops ||"; ++ " !enclave->list_ops_node->ops_desc->ops->cc_ecall_enclave) {"; ++ " ret = CC_ERROR_BAD_PARAMETERS;"; ++ " goto exit;"; ++ "}"; + "if ((ret = enclave->list_ops_node->ops_desc->ops->cc_ecall_enclave("; + " enclave,"; + sprintf " fid_%s," fd.fname; +@@ -57,8 +71,13 @@ let set_call_user_func (fd : func_decl) = + " out_buf,"; + " out_buf_size,"; + " &ms,"; +- " &ocall_table)) != CC_SUCCESS)"; ++ " &ocall_table)) != CC_SUCCESS) {"; ++ " pthread_rwlock_unlock(&enclave->rwlock);"; ++ " goto exit; }"; ++ "if (pthread_rwlock_unlock(&enclave->rwlock)) {"; ++ " ret = CC_ERROR_BUSY;"; + " goto exit;"; ++ "}"; + ] + + let set_ecall_func_arguments (fd : func_decl) = +diff --git a/tools/codegener/intel/CodeGen.ml b/tools/codegener/intel/CodeGen.ml +index d9ccf7c..6fb05fb 100644 +--- a/tools/codegener/intel/CodeGen.ml ++++ b/tools/codegener/intel/CodeGen.ml +@@ -872,7 +872,11 @@ let gen_func_uproxy (tf: Ast.trusted_func) (idx: int) (ec: enclave_content) = + let sgx_ecall_fn = get_sgx_fname SGX_ECALL tf.Ast.tf_is_switchless in + + (* Normal case - do ECALL with marshaling structure*) +- let ecall_with_ms = sprintf "if(!enclave || !enclave->list_ops_node || !enclave->list_ops_node->ops_desc ||\n\ ++ let ecall_with_ms = sprintf "if(!enclave) \n\ ++ \t\treturn CC_ERROR_BAD_PARAMETERS; ++ if (pthread_rwlock_rdlock(&enclave->rwlock))\n\ ++ \t\treturn CC_ERROR_BUSY; ++ if (!enclave->list_ops_node || !enclave->list_ops_node->ops_desc ||\n\ + \t\t!enclave->list_ops_node->ops_desc->ops || \n\ + \t\t!enclave->list_ops_node->ops_desc->ops->cc_ecall_enclave)\n\ + \t\treturn CC_ERROR_BAD_PARAMETERS; +@@ -884,12 +888,17 @@ let gen_func_uproxy (tf: Ast.trusted_func) (idx: int) (ec: enclave_content) = + \t\tNULL,\n\ + \t\t0,\n\ + \t\t&%s,\n\ +- \t\t%s);\n" idx ms_struct_val ocall_table_ptr in ++ \t\t%s); ++ pthread_rwlock_unlock(&enclave->rwlock);\n" idx ms_struct_val ocall_table_ptr in + + (* Rare case - the trusted function doesn't have parameter nor return value. + * In this situation, no marshaling structure is required - passing in NULL. + *) +- let ecall_null = sprintf "if(!enclave || !enclave->list_ops_node || !enclave->list_ops_node->ops_desc ||\n\ ++ let ecall_null = sprintf "if(!enclave) \n\ ++ \t\treturn CC_ERROR_BAD_PARAMETERS; ++ if (pthread_rwlock_rdlock(&enclave->rwlock))\n\ ++ \t\treturn CC_ERROR_BUSY; ++ if(!enclave || !enclave->list_ops_node || !enclave->list_ops_node->ops_desc ||\n\ + \t\t!enclave->list_ops_node->ops_desc->ops || \n\ + \t\t!enclave->list_ops_node->ops_desc->ops->cc_ecall_enclave)\n\ + \t\treturn CC_ERROR_BAD_PARAMETERS; +@@ -901,7 +910,8 @@ let gen_func_uproxy (tf: Ast.trusted_func) (idx: int) (ec: enclave_content) = + \t\tNULL,\n\ + \t\t0,\n\ + \t\tNULL,\n\ +- \t\t%s);\n" idx ocall_table_ptr ++ \t\t%s); ++ pthread_rwlock_unlock(&enclave->rwlock);\n" idx ocall_table_ptr + in + let update_retval = sprintf "if (result == CC_SUCCESS && %s) *%s = %s.%s;" + retval_name retval_name ms_struct_val ms_retval_name in +-- +2.27.0 + diff --git a/0039-clean-memory-when-it-come-to-error_handle.patch b/0039-clean-memory-when-it-come-to-error_handle.patch new file mode 100644 index 0000000..5f61d13 --- /dev/null +++ b/0039-clean-memory-when-it-come-to-error_handle.patch @@ -0,0 +1,79 @@ +From 8b70a9d74bcbb07cd8f33664398b1e5a41a46033 Mon Sep 17 00:00:00 2001 +From: chenmaodong +Date: Thu, 3 Jun 2021 21:01:34 +0800 +Subject: [PATCH] clean memory when it come to error_handle delete the rdlock + because we do it in proxy function in *_u.c + +Signed-off-by: chenmaodong +--- + src/host_src/enclave.c | 16 ++++++++++------ + src/host_src/sgx/sgx_enclave.c | 2 -- + 2 files changed, 10 insertions(+), 8 deletions(-) + +diff --git a/src/host_src/enclave.c b/src/host_src/enclave.c +index 4b75b6e..8d6c8a6 100644 +--- a/src/host_src/enclave.c ++++ b/src/host_src/enclave.c +@@ -34,7 +34,7 @@ static void check_dlopen_engine(p_tee_unregistered unregistered_func, cc_enclave + pthread_mutex_unlock(&(g_list_ops.mutex_work)); + } + +-static void error_handle(cc_enclave_t *l_context, void *handle, p_tee_registered registered_func, ++static void error_handle(cc_enclave_t *enclave, void *handle, p_tee_registered registered_func, + p_tee_unregistered unregistered_func, char* path, bool check) + { + cc_enclave_result_t tmp_res; +@@ -45,19 +45,19 @@ static void error_handle(cc_enclave_t *l_context, void *handle, p_tee_registered + pthread_mutex_unlock(&(g_list_ops.mutex_work)); + } + /* in list find engine: handle is null and l_context is not null */ +- if (l_context != NULL && l_context->list_ops_node && !handle) { +- tmp_res = find_engine_registered(l_context->list_ops_node->ops_desc->handle, NULL, &unregistered_func); ++ if (enclave != NULL && enclave->list_ops_node && !handle) { ++ tmp_res = find_engine_registered(enclave->list_ops_node->ops_desc->handle, NULL, &unregistered_func); + if (tmp_res != CC_SUCCESS) { + print_error_term("Can not find unregistered in the failed exit phase\n"); + } else { +- check_dlopen_engine(unregistered_func, l_context); ++ check_dlopen_engine(unregistered_func, enclave); + } + } + /* handle is not null, means dlopen is ok */ + if (handle) { + /* check if registered invoke success */ +- if (l_context != NULL && registered_func && unregistered_func && l_context->list_ops_node) { +- check_dlopen_engine(unregistered_func, l_context); ++ if (enclave != NULL && registered_func && unregistered_func && enclave->list_ops_node) { ++ check_dlopen_engine(unregistered_func, enclave); + } else { + /* means registered func invoke fail OR find_engine_registered fail */ + dlclose(handle); +@@ -66,6 +66,10 @@ static void error_handle(cc_enclave_t *l_context, void *handle, p_tee_registered + if (path) { + free(path); + } ++ ++ if (enclave) { ++ explicit_bzero(enclave, sizeof(cc_enclave_t)); ++ } + } + + /* Lock to check the number of enclave +diff --git a/src/host_src/sgx/sgx_enclave.c b/src/host_src/sgx/sgx_enclave.c +index aa26957..7b61ba8 100644 +--- a/src/host_src/sgx/sgx_enclave.c ++++ b/src/host_src/sgx/sgx_enclave.c +@@ -201,10 +201,8 @@ cc_enclave_result_t cc_enclave_sgx_call_function( + (void)output_buffer_size; + sgx_status_t status; + cc_enclave_result_t cc_status; +- pthread_rwlock_rdlock(&(enclave->rwlock)); + status = sgx_ecall(((sgx_context_t *)(enclave->private_data))->edi, (int)function_id, ocall_table, ms); + cc_status = conversion_res_status(status, enclave->type); +- pthread_rwlock_unlock(&(enclave->rwlock)); + return cc_status; + } + +-- +2.27.0 + diff --git a/README.en.md b/README.en.md index a8768cb..aa8c4a8 100644 --- a/README.en.md +++ b/README.en.md @@ -1,4 +1,4 @@ -secGear +secGear secGear ============================ @@ -43,23 +43,22 @@ Then save as test.edl ### 2 Write the top-level CMakeLists.txt - cmake_minimum_required(VERSION 3.12 FATAL_ERROR) + cmake_minimum_required(VERSION 3.10 FATAL_ERROR) project(TEST C) set(CMAKE_C_STANDARD 99) set(CURRENT_ROOT_PATH ${CMAKE_CURRENT_SOURCE_DIR}) set(EDL_FILE test.edl) set(LOCAL_ROOT_PATH "$ENV{CC_SDK}") set(SECGEAR_INSTALL_PATH /lib64/) + set(CODEGEN codegen) if(CC_GP) set(CODETYPE trustzone) - set(CODEGEN codegen_arm64) execute_process(COMMAND uuidgen -r OUTPUT_VARIABLE UUID) string(REPLACE "\n" "" UUID ${UUID}) add_definitions(-DPATH="/data/${UUID}.sec") endif() if(CC_SGX) set(CODETYPE sgx) - set(CODEGEN codegen_x86_64) add_definitions(-DPATH="${CMAKE_CURRENT_BINARY_DIR}/enclave/enclave.signed.so") endif() add_subdirectory(${CURRENT_ROOT_PATH}/enclave) @@ -170,10 +169,9 @@ Set compile and link options if(${CMAKE_VERSION} VERSION_GREATER_EQUAL "3.13.0") target_link_directories(${OUTPUT} PRIVATE ${SECGEAR_INSTALL_PATH}) endif() - target_link_libraries(${OUTPUT} secgear) endif() -In the case of iTrustee, set the search paths of the header file and the link file, and compile the final non-secure binary. +In the case of iTrustee, set the search paths of the header file and compile the final non-secure binary. if(CC_SGX) if(${CMAKE_VERSION} VERSION_LESS "3.13.0") @@ -187,12 +185,16 @@ In the case of iTrustee, set the search paths of the header file and the link fi if(${CMAKE_VERSION} VERSION_GREATER_EQUAL "3.13.0") target_link_directories(${OUTPUT} PRIVATE ${SECGEAR_INSTALL_PATH}) endif() - target_link_libraries(${OUTPUT} secgear) endif() -In the case of sgx, set the search paths of the header file and the link file, and compile the final non-secure binary. +In the case of sgx, set the search paths of the header file and compile the final non-secure binary. - set_target_properties(${OUTPUT} PROPERTIES SKIP_BUILD_RPATH TRUE) + if(CC_SIM) + target_link_libraries(${OUTPUT} secgearsim) + else() + target_link_libraries(${OUTPUT} secgear) + endif() + set_target_properties(${OUTPUT} PROPERTIES SKIP_BUILD_RPATH TRUE) if(CC_GP) install(TARGETS ${OUTPUT} RUNTIME @@ -206,8 +208,9 @@ In the case of sgx, set the search paths of the header file and the link file, a PERMISSIONS OWNER_EXECUTE OWNER_WRITE OWNER_READ) endif() -Specify the installation path of the final binary. The non-secure side image of iTrustee must be installed on the -specified whitelist. The whitelist configuration will be introduced below. +Based on -DCC_SIM=ON or none transferred from cmake, linking secgear or secgearsim. Specify the installation +path of the final binary. The non-secure side image of iTrustee must be installed on the specified whitelist. +The whitelist configuration will be introduced below. ### 4 Write security side code, CMakeLists.txt and some configuration files @@ -250,8 +253,6 @@ Set sign tool and the security side log printing level if(CC_GP) #set signed output set(OUTPUT ${UUID}.sec) - #set itrustee device key - set(DEVICEPEM ${CMAKE_CURRENT_SOURCE_DIR}/rsa_public_key_cloud.pem) set(WHITE_LIST_0 /vendor/bin/helloworld) set(WHITE_LIST_1 /vendor/bin/secgear_test) @@ -266,8 +267,7 @@ Set sign tool and the security side log printing level WHITE_LIS_X sets the whitelist of itrustee, only the host binary of these paths can call this secure image, and up to 8 list paths can be configured. WHITE_LIST_OWNER set user, this user will be applied to all whitelist paths. -DEVICEPEM public key is used by itrustee and is used to encrypt the enclave image of the security side with the -dynamically generated aes key. Finally, set the name of the security side image after the final signature, and +Finally, set the name of the security side image after the final signature, and generate auxiliary code. if(CC_SGX) @@ -335,8 +335,8 @@ so -nostdinc -nodefaultlibs -nostdlib -nodefaultlibs compile link options was in add_custom_command(TARGET ${PREFIX} POST_BUILD - COMMAND bash ${SIGN_TOOL} -d sign -x trustzone -i lib${PREFIX}.so -m ${CMAKE_CURRENT_SOURCE_DIR}/manifest.txt - -e ${DEVICEPEM} -o ${CMAKE_CURRENT_BINARY_DIR}/${OUTPUT}) + COMMAND bash ${SIGN_TOOL} -d sign -x trustzone -i lib${PREFIX}.so -c ${CMAKE_CURRENT_SOURCE_DIR}/manifest.txt + -o ${CMAKE_CURRENT_BINARY_DIR}/${OUTPUT}) install(FILES ${CMAKE_CURRENT_BINARY_DIR}/${OUTPUT} DESTINATION /data @@ -353,18 +353,17 @@ whitelist macro. Next, you need to link to the secgear_tee library, in which the random numbers, seal, unseal, etc. The last step is to sign and install. if(CC_SGX) - set(SGX_MODE HW) set(SGX_DIR ${SGXSDK}) set(CMAKE_C_FLAGS "${COMMON_C_FLAGS} -m64 -fvisibility=hidden") set(CMAKE_C_FLAGS_RELEASE "${CMAKE_C_FLAGS} -s") set(LINK_LIBRARY_PATH ${SGX_DIR}/lib64) - if(${SGX_MODE} STREQUAL HW) - set(Trts_Library_Name sgx_trts) - set(Service_Library_Name sgx_tservice) - else() + if(CC_SIM) set(Trts_Library_Name sgx_trts_sim) set(Service_Library_Name sgx_tservice_sim) + else() + set(Trts_Library_Name sgx_trts) + set(Service_Library_Name sgx_tservice) endif() set(Crypto_Library_Name sgx_tcrypto) @@ -422,9 +421,6 @@ configuration file. For details, please refer to the official development docum Write itrustee related configuration files The gpd.ta.appID in the manifest.txt.in file is the uuid configuration item, which is dynamically generated, and the other configuration items can refer to the itrustee development document. - -Copy the rsa_public_key_cloud.pem device public key from other examples in the project to the enclave directory. -The device public key here is used to encrypt the enclave image with the temporarily generated aes key. ### 5 build and install test @@ -506,5 +502,5 @@ secGear introduce the signing tool to sign the enclave. Milestone --------- -secGear +secGear diff --git a/README.md b/README.md index fa47d03..a90450b 100644 --- a/README.md +++ b/README.md @@ -1,513 +1,449 @@ -secGear - -secGear -============================ - -Introduction ------------ - -secGear is an SDK to develop confidential computing apps based on hardware enclave features. The target is to use -single source code for developers to develop apps running on different hardware. Currently secGear support Intel SGX -and iTrustee running in ARM Trustzone. - -Build and Install ----------------- - -- [reference build & install](./docs/build_install.md) - -Develop Application and Compile ------------------------------- - -Assuming the development directory is .../secGear/examples/test/ - -### 1 Write edl interface description - - enclave { - include "secgear_urts.h" - from "secgear_tstdc.edl" import *; - trusted { - public int get_string([out, size=32]char *buf); - }; - }; - -include "secgear_urts.h", from "secgear_tstdc.edl" import *, to shield the difference between sgx and iTrustee when -calling the C library. So as long as you use the c library functions, for the consistency of your development code, -the default is to import these two files. - -For details about edl syntax, please refer to the sgx development document Enclave Definition Language Syntax section. -At present, sgx and iTrustee are compatible with each other in basic types, pointer buffers, and deep copy of -structures, but currently only sgx supports such things as user_check, Granting Access to ECALLs, Using Switchless -Calls and so on. - -Then save as test.edl - -### 2 Write the top-level CMakeLists.txt - - cmake_minimum_required(VERSION 3.12 FATAL_ERROR) - project(TEST C) - set(CMAKE_C_STANDARD 99) - set(CURRENT_ROOT_PATH ${CMAKE_CURRENT_SOURCE_DIR}) - set(EDL_FILE test.edl) - set(LOCAL_ROOT_PATH "$ENV{CC_SDK}") - set(SECGEAR_INSTALL_PATH /lib64/) - if(CC_GP) - set(CODETYPE trustzone) - set(CODEGEN codegen_arm64) - execute_process(COMMAND uuidgen -r OUTPUT_VARIABLE UUID) - string(REPLACE "\n" "" UUID ${UUID}) - add_definitions(-DPATH="/data/${UUID}.sec") - endif() - if(CC_SGX) - set(CODETYPE sgx) - set(CODEGEN codegen_x86_64) - add_definitions(-DPATH="${CMAKE_CURRENT_BINARY_DIR}/enclave/enclave.signed.so") - endif() - add_subdirectory(${CURRENT_ROOT_PATH}/enclave) - add_subdirectory(${CURRENT_ROOT_PATH}/host) - -Set the CODETYPE EDL_FILE and CODETYPE attributes, which will be used when automatically generated later. -On the arm platform, the build enclave image needs to be named with a unique UUID, so it is dynamically uniquely -generated using the uuidgen command. The defined DPATH macro is used when loading the enclave image. - - -### 3 Write the non-secure side code and CMakeLists.txt - -#### 3.1 Create a new host directory and write main.c - - #include - #include "enclave.h" - #include "test_u.h" - - #define BUF_LEN 32 - - int main() - { - int retval = 0; - char *path = PATH; - char buf[BUF_LEN]; - cc_enclave_t *context = NULL; - cc_enclave_result_t res; - - res = cc_enclave_create(path, AUTO_ENCLAVE_TYPE, 0, SECGEAR_DEBUG_FLAG, NULL, 0, &context); - ... - - res = get_string(context, &retval, buf); - if (res != CC_SUCCESS || retval != (int)CC_SUCCESS) { - printf("Ecall enclave error\n"); - } else { - printf("%s\n", buf); - } - - if (context != NULL) { - res = cc_enclave_destroy(context); - ... - } - return res; - } - -#include "enclave.h", import the secGear header file, #include "test_u.h" import the automatically generated code -header file. Next, call cc_enclave_create(...) to create the enclave context, and then call the wrapper of the -interface described in the edl file to enter the enclave to execute confidential code. -Finally, call cc_enclave_destroy(...) to destroy the enclave context. - -Note that the interface called here has more context and retval parameters than defined in edl file before. -This is because this function, generated by the automatic code generation tool according to edl, is a wrapper about -the real enclave code, and its declaration is in the test_u.h header file. Where the context parameter it is the -cc_enclave_t * context created before, and retval is the return value of the function defined in edl, and the res -parameter is the return value of the wrapped function. The prefix of test_u.h is consistent with the prefix of test.edl. - -If the function defined in edl does not return a value, such as "public void get_string([out, size=32]char *buf);", -then the prototype called by the user will be "res = get_string(context, buf);". - -According to these rules, you can write code when the wrapper function is not generated by code generation tool and -place the wrapper function generation in the compilation phase, which simplifies the development and compilation steps. - -#### 3.2 Write the CMakeLists.txt file of the host. - - #set auto code prefix - set(PREFIX test) - #set host exec name - set(OUTPUT secgear_test) - #set host src code - set(SOURCE_FILE ${CMAKE_CURRENT_SOURCE_DIR}/main.c) - -Set some variables, which are described in comments. - - #set auto code - if(CC_GP) - set(AUTO_FILES ${CMAKE_CURRENT_BINARY_DIR}/${PREFIX}_u.h ${CMAKE_CURRENT_BINARY_DIR}/${PREFIX}_u.c ${CMAKE_CURRENT_BINARY_DIR}/${PREFIX}_args.h) - add_custom_command(OUTPUT ${AUTO_FILES} - DEPENDS ${CURRENT_ROOT_PATH}/${EDL_FILE} - COMMAND ${CODEGEN} --${CODETYPE} --untrusted ${CURRENT_ROOT_PATH}/${EDL_FILE} --search-path ${LOCAL_ROOT_PATH}/inc/host_inc/gp) - endif() - - if(CC_SGX) - set(AUTO_FILES ${CMAKE_CURRENT_BINARY_DIR}/${PREFIX}_u.h ${CMAKE_CURRENT_BINARY_DIR}/${PREFIX}_u.c) - add_custom_command(OUTPUT ${AUTO_FILES} - DEPENDS ${CURRENT_ROOT_PATH}/${EDL_FILE} - COMMAND ${CODEGEN} --${CODETYPE} --untrusted ${CURRENT_ROOT_PATH}/${EDL_FILE} --search-path ${LOCAL_ROOT_PATH}/inc/host_inc/sgx --search-path ${SGXSDK}/include) - endif() - -Use the code generation tool to generate auxiliary code based on the edl. Variables such as CODEGEN and CODETYPE are -defined at the top of CMakeList.txt. --search-path is used to search for other edl files imported in test.edl. -When SGX is used, the edl imported in test.edl indirectly depends on the edl of the SGX SDK. Therefore, the search -path of the SGX SDK is also specified here. - - set(CMAKE_C_FLAGS "-fstack-protector-all -W -Wall -Werror -Wextra -Werror=array-bounds -D_FORTIFY_SOURCE=2 -O2 -ftrapv -fPIE") - set(CMAKE_EXE_LINKER_FLAGS "-Wl,-z,relro -Wl,-z,now -Wl,-z,noexecstack") - -Set compile and link options - - if(CC_GP) - if(${CMAKE_VERSION} VERSION_LESS "3.13.0") - link_directories(${SECGEAR_INSTALL_PATH}) - endif() - add_executable(${OUTPUT} ${SOURCE_FILE} ${AUTO_FILES}) - target_include_directories(${OUTPUT} PRIVATE - ${LOCAL_ROOT_PATH}/inc/host_inc - ${LOCAL_ROOT_PATH}/inc/host_inc/gp - ${CMAKE_CURRENT_BINARY_DIR}) - if(${CMAKE_VERSION} VERSION_GREATER_EQUAL "3.13.0") - target_link_directories(${OUTPUT} PRIVATE ${SECGEAR_INSTALL_PATH}) - endif() - endif() - -In the case of iTrustee, set the search paths of the header file and compile the final non-secure binary. - - if(CC_SGX) - if(${CMAKE_VERSION} VERSION_LESS "3.13.0") - link_directories(${SECGEAR_INSTALL_PATH}) - endif() - add_executable(${OUTPUT} ${SOURCE_FILE} ${AUTO_FILES}) - target_include_directories(${OUTPUT} PRIVATE - ${LOCAL_ROOT_PATH}/inc/host_inc - ${LOCAL_ROOT_PATH}/inc/host_inc/sgx - ${CMAKE_CURRENT_BINARY_DIR}) - if(${CMAKE_VERSION} VERSION_GREATER_EQUAL "3.13.0") - target_link_directories(${OUTPUT} PRIVATE ${SECGEAR_INSTALL_PATH}) - endif() - endif() - -In the case of sgx, set the search paths of the header file and compile the final non-secure binary. - - if(CC_SIM) - target_link_libraries(${OUTPUT} secgearsim) - else() - target_link_libraries(${OUTPUT} secgear) - endif() - set_target_properties(${OUTPUT} PROPERTIES SKIP_BUILD_RPATH TRUE) - if(CC_GP) - install(TARGETS ${OUTPUT} - RUNTIME - DESTINATION /vendor/bin/ - PERMISSIONS OWNER_EXECUTE OWNER_WRITE OWNER_READ) - endif() - if(CC_SGX) - install(TARGETS ${OUTPUT} - RUNTIME - DESTINATION ${CMAKE_BINARY_DIR}/bin/ - PERMISSIONS OWNER_EXECUTE OWNER_WRITE OWNER_READ) - endif() - -Based on -DCC_SIM=ON or none transferred from cmake, linking secgear or secgearsim. Specify the installation -path of the final binary. The non-secure side image of iTrustee must be installed on the specified whitelist. -The whitelist configuration will be introduced below. - -### 4 Write security side code, CMakeLists.txt and some configuration files - -#### 4.1 Create a new enclave directory and write hello.c - - #include - #include - #include "test_t.h" - - #define TA_HELLO_WORLD "secGear hello world!" - #define BUF_MAX 32 - int get_string(char *buf) - { - strncpy(buf, TA_HELLO_WORLD, strlen(TA_HELLO_WORLD) + 1); - return 0; - } - -Import the test_t.h generated by the automatic code generation tool, and then write the function according to the -interface description in test.edl. - -#### 4.2 Write CMakeLists.txt - - #set auto code prefix - set(PREFIX test) - #set sign key - set(PEM Enclave_private.pem) - -Set the name used to sign the enclave private key - - #set sign tool - set(SIGN_TOOL ${LOCAL_ROOT_PATH}/tools/sign_tool/sign_tool.sh) - #set enclave src code - set(SOURCE_FILES ${CMAKE_CURRENT_SOURCE_DIR}/hello.c) - #set log level - set(PRINT_LEVEL 3) - add_definitions(-DPRINT_LEVEL=${PRINT_LEVEL}) - -Set sign tool and the security side log printing level - - if(CC_GP) - #set signed output - set(OUTPUT ${UUID}.sec) - #set itrustee device key - set(DEVICEPEM ${CMAKE_CURRENT_SOURCE_DIR}/rsa_public_key_cloud.pem) - - set(WHITE_LIST_0 /vendor/bin/helloworld) - set(WHITE_LIST_1 /vendor/bin/secgear_test) - set(WHITE_LIST_OWNER root) - set(WHITELIST WHITE_LIST_0 WHITE_LIST_1) - - set(AUTO_FILES ${CMAKE_CURRENT_BINARY_DIR}/${PREFIX}_t.h ${CMAKE_CURRENT_BINARY_DIR}/${PREFIX}_t.c ${CMAKE_CURRENT_BINARY_DIR}/${PREFIX}_args.h) - add_custom_command(OUTPUT ${AUTO_FILES} - DEPENDS ${CURRENT_ROOT_PATH}/${EDL_FILE} - COMMAND ${CODEGEN} --${CODETYPE} --trusted ${CURRENT_ROOT_PATH}/${EDL_FILE} --search-path ${LOCAL_ROOT_PATH}/inc/host_inc/gp) - endif() - -WHITE_LIS_X sets the whitelist of itrustee, only the host binary of these paths can call this secure image, -and up to 8 list paths can be configured. WHITE_LIST_OWNER set user, this user will be applied to all whitelist paths. -DEVICEPEM public key is used by itrustee and is used to encrypt the enclave image of the security side with the -dynamically generated aes key. Finally, set the name of the security side image after the final signature, and -generate auxiliary code. - - if(CC_SGX) - set(OUTPUT enclave.signed.so) - set(AUTO_FILES ${CMAKE_CURRENT_BINARY_DIR}/${PREFIX}_t.h ${CMAKE_CURRENT_BINARY_DIR}/${PREFIX}_t.c) - add_custom_command(OUTPUT ${AUTO_FILES} - DEPENDS ${CURRENT_ROOT_PATH}/${EDL_FILE} - COMMAND ${CODEGEN} --${CODETYPE} --trusted ${CURRENT_ROOT_PATH}/${EDL_FILE} --search-path ${LOCAL_ROOT_PATH}/inc/host_inc/sgx --search-path ${SGXSDK}/include) - endif() - -In the case of sgx, set the name of the security side image after the final signature, and generate auxiliary code. - - set(COMMON_C_FLAGS "-W -Wall -Werror -fno-short-enums -fno-omit-frame-pointer -fstack-protector \ - -Wstack-protector --param ssp-buffer-size=4 -frecord-gcc-switches -Wextra -nostdinc -nodefaultlibs \ - -fno-peephole -fno-peephole2 -Wno-main -Wno-error=unused-parameter \ - -Wno-error=unused-but-set-variable -Wno-error=format-truncation=") - - set(COMMON_C_LINK_FLAGS "-Wl,-z,now -Wl,-z,relro -Wl,-z,noexecstack -Wl,-nostdlib -nodefaultlibs -nostartfiles") - -Set the security side, no matter whether it is sgx or itrustee will use some compilation and link options, for -example, because the security side is different from the non-secure side, the default library of host OS cannot be used, -so -nostdinc -nodefaultlibs -nostdlib -nodefaultlibs compile link options was introduced. - - if(CC_GP) - configure_file("${CMAKE_CURRENT_SOURCE_DIR}/manifest.txt.in" "${CMAKE_CURRENT_SOURCE_DIR}/manifest.txt") - - set(CMAKE_C_FLAGS "${COMMON_C_FLAGS} -march=armv8-a ") - set(CMAKE_C_FLAGS_RELEASE "${CMAKE_C_FLAGS} -s -fPIC") - set(CMAKE_SHARED_LINKER_FLAGS "${COMMON_C_LINK_FLAGS} -Wl,-s") - - set(ITRUSTEE_TEEDIR ${iTrusteeSDK}/) - set(ITRUSTEE_LIBC ${iTrusteeSDK}/thirdparty/open_source/musl/libc) - - if(${CMAKE_VERSION} VERSION_LESS "3.13.0") - link_directories(${SECGEAR_INSTALL_PATH}) - endif() - - add_library(${PREFIX} SHARED ${SOURCE_FILES} ${AUTO_FILES}) - - target_include_directories( ${PREFIX} PRIVATE - ${CMAKE_CURRENT_BINARY_DIR} - ${LOCAL_ROOT_PATH}/inc/host_inc - ${LOCAL_ROOT_PATH}/inc/host_inc/gp - ${LOCAL_ROOT_PATH}/inc/enclave_inc - ${LOCAL_ROOT_PATH}/inc/enclave_inc/gp - ${ITRUSTEE_TEEDIR}/include/TA - ${ITRUSTEE_TEEDIR}/include/TA/huawei_ext - ${ITRUSTEE_LIBC}/arch/aarch64 - ${ITRUSTEE_LIBC}/ - ${ITRUSTEE_LIBC}/arch/arm/bits - ${ITRUSTEE_LIBC}/arch/generic - ${ITRUSTEE_LIBC}/arch/arm - ${LOCAL_ROOT_PATH}/inc/enclave_inc/gp/itrustee) - - if(${CMAKE_VERSION} VERSION_GREATER_EQUAL "3.13.0") - target_link_directories(${PREFIX} PRIVATE ${SECGEAR_INSTALL_PATH}) - endif() - - foreach(WHITE_LIST ${WHITELIST}) - add_definitions(-D${WHITE_LIST}="${${WHITE_LIST}}") - endforeach(WHITE_LIST) - add_definitions(-DWHITE_LIST_OWNER="${WHITE_LIST_OWNER}") - - target_link_libraries(${PREFIX} -lsecgear_tee) - - add_custom_command(TARGET ${PREFIX} - POST_BUILD - COMMAND bash ${SIGN_TOOL} -d sign -x trustzone -i lib${PREFIX}.so -m ${CMAKE_CURRENT_SOURCE_DIR}/manifest.txt - -e ${DEVICEPEM} -o ${CMAKE_CURRENT_BINARY_DIR}/${OUTPUT}) - - install(FILES ${CMAKE_CURRENT_BINARY_DIR}/${OUTPUT} - DESTINATION /data - PERMISSIONS OWNER_EXECUTE OWNER_WRITE OWNER_READ GROUP_READ GROUP_EXECUTE WORLD_READ WORLD_EXECUTE) - - endif() - -In the case of iTrustee, generate the configuration file manifest.txt, which details of the configuration file will -be explained later, specify some compilation options related to itrustee, set the search paths of the header file and -the link file, and compile the enclave binary. - -Regarding the use of itrustee ocall, there are some other notes, which will be introduced later. Then define the -whitelist macro. Next, you need to link to the secgear_tee library, in which there are interfaces for generating -random numbers, seal, unseal, etc. The last step is to sign and install. - - if(CC_SGX) - set(SGX_DIR ${SGXSDK}) - set(CMAKE_C_FLAGS "${COMMON_C_FLAGS} -m64 -fvisibility=hidden") - set(CMAKE_C_FLAGS_RELEASE "${CMAKE_C_FLAGS} -s") - set(LINK_LIBRARY_PATH ${SGX_DIR}/lib64) - - if(CC_SIM) - set(Trts_Library_Name sgx_trts_sim) - set(Service_Library_Name sgx_tservice_sim) - else() - set(Trts_Library_Name sgx_trts) - set(Service_Library_Name sgx_tservice) - endif() - - set(Crypto_Library_Name sgx_tcrypto) - - set(CMAKE_SHARED_LINKER_FLAGS "${COMMON_C_LINK_FLAGS} -Wl,-z,defs -Wl,-pie -Bstatic -Bsymbolic -eenclave_entry \ - -Wl,--export-dynamic -Wl,--defsym,__ImageBase=0 -Wl,--gc-sections -Wl,--version-script=${CMAKE_CURRENT_SOURCE_DIR}/Enclave.lds") - - if(${CMAKE_VERSION} VERSION_LESS "3.13.0") - link_directories(${LINK_LIBRARY_PATH}) - endif() - - add_library(${PREFIX} SHARED ${SOURCE_FILES} ${AUTO_FILES}) - - target_include_directories(${PREFIX} PRIVATE - ${CMAKE_CURRENT_BINARY_DIR} - ${SGX_DIR}/include/tlibc - ${SGX_DIR}/include/libcxx - ${SGX_DIR}/include - ${LOCAL_ROOT_PATH}/inc/host_inc - ${LOCAL_ROOT_PATH}/inc/host_inc/sgx) - - if(${CMAKE_VERSION} VERSION_GREATER_EQUAL "3.13.0") - target_link_directories(${PREFIX} PRIVATE - ${LINK_LIBRARY_PATH}) - endif() - - target_link_libraries(${PREFIX} -Wl,--whole-archive ${Trts_Library_Name} -Wl,--no-whole-archive - -Wl,--start-group -lsgx_tstdc -lsgx_tcxx -l${Crypto_Library_Name} -l${Service_Library_Name} -Wl,--end-group) - add_custom_command(TARGET ${PREFIX} - POST_BUILD - COMMAND openssl genrsa -3 -out ${PEM} 3072 - COMMAND bash ${SIGN_TOOL} -d sign -x sgx -i lib${PREFIX}.so -k ${PEM} -o ${OUTPUT} -c ${CMAKE_CURRENT_SOURCE_DIR}/Enclave.config.xml) - endif() - -In the case of sgx, specify some compilation, link options related to sgx. When linking libraries, sgx and itrustee -are quite different. This is because itrustee is a secure OS with more capabilities, such as musl libc and openssl. -When compiling and link itrustee's enclave, there is no need to link some basic libraries. But sgx has no OS concept. -The basic library interfaces to be called on the security side are all given in the sgx sdk in the form of static -libraries, so this requires us to link these static libraries, and in order to be able to use these static libraries -correctly, some libraries must be linked between specified options, such as sgx_trts. - -For more detailed information, please refer to the Makefile of sgx examples. Finally, sign the enclave with the -configuration file, which will be introduced later. Note that secGear does not currently support remote authentication. - - set_target_properties(${PREFIX} PROPERTIES SKIP_BUILD_RPATH TRUE) - -Set some safe compilation options. - -#### 4.3 Enclave image configuration file - -Write sgx enclave related configuration files -The configuration content in the Enclave.config.xml and Enclave.lds files is the same as the official sgx -configuration file. For details, please refer to the official development document. - -Write itrustee related configuration files -The gpd.ta.appID in the manifest.txt.in file is the uuid configuration item, which is dynamically generated, -and the other configuration items can refer to the itrustee development document. - -Copy the rsa_public_key_cloud.pem device public key from other examples in the project to the enclave directory. -The device public key here is used to encrypt the enclave image with the temporarily generated aes key. - -### 5 build and install test - -Enter the development directory .../secGear/examples/test/, then run mkdir debug && cd debug -&& cmake -DCMAKE_BUILD_TYPE=Debug -DCC_SGX=ON -DSGXSDK=sgx_sdk path .. && make && sudo make install OR -mkdir debug && cd debug && cmake -DCMAKE_BUILD_TYPE=Debug -DCC_GP=ON -DiTrusteeSDK=gp_sdk path .. && make -&& sudo make install - -Log ---- -Non-secure side log record: - -Non-secure side development, similar to ordinary development, users can implement non-secure side application logs -by themselves - -Security side log record: - -Security side development, due to restrictions on the different security capabilities of each platform, it is -impossible to directly develop the log function like the non-secure side, Therefore, we provide the PrintInfo -interface to record the security side log to the Syslog system. The related configuration files secgear and secgear.conf -have been installed in the system directory during the build and install secGear phase. - -Note that when using on itrustee, you need to import the secgear_log.h header file, but sgx does not need it. -Because sgx implements the log function through ocall, the relevant code is in the auxiliary code. And when the -configuration file is installed, you need to run "systemctl restart rsyslog" to make the log effective. - -Finally, in order to enable itrustee logs to be dumped to the place specified in the configuration file, you also -need to run /vendor/bin/tlogcat -f. The tlogcat tool is a part of the itrustee sdk. - -The meaning of log level (set(PRINT_LEVEL 3)). - - PRINT_ERROR 0 - PRINT_WARNING 1 - PRINT_STRACE 2 - PRINT_DEBUG 3 - -At present, there are some differences in the usage of the log function. After the itrustee ocall function is stable, -the usage will be unified. - -Use ocall ---------- - -The secGear ocall function can be used normally on the sgx platform. There are currently restrictions on itrustee: - - only the specified a3d88d2a-ae2a-4ea5-a37d-35fc5f607e9e uuid can be used, - and two programs that enable ocall cannot be run at the same time, - and config cannot be enabled. ta.instanceKeepAlive. - -Moreover, if the underlying itrustee does not enable ocall, the SDK will only report an error registration ocall failure, -and the ecall function can be used normally. - -Seal, generate random number interface --------------------------------------- - -The related interface is defined in secgear_dataseal.h, secgear_random.h. For usage, please refer to examples/seal_data. -Note: Since the feature for itrustee to derive keys is still not perfect, seal related interfaces are not currently -supported on the itrustee platform. - -Remote authentication capability is currently not supported. ------------------------------------------------------------- - -secGear does not currently support plc, switchless and other about sgx features. --------------------------------------------------------------------------------- - -Learning More About codegener ----------------------------- - -secGear Introduce EDL (Enclave Description Languate) and intermediate code generation tool codegener. EDL is -compatible with Intel SGX's definition. - -- [Learn how to use codegener](./docs/codegener.md) - -Learning More About sign_tool ------------------------------ - -secGear introduce the signing tool to sign the enclave. - -- [Learn how to use signing tool](./docs/sign_tool.md) - -Milestone ---------- -secGear - +secGear + +secGear +============================ + +介绍 +----------- + +SecGear则是面向计算产业的机密计算安全应用开发套件。旨在方便开发者在不同的硬件设备上提供统一开发框架。目前secGear支持intel SGX硬件和Trustzone itrustee。 + +构建、安装 +---------------- + +- [详见 构建、安装](./docs/build_install.md) + +开发应用和编译 +------------------------------ + +开发目录 .../secGear/examples/test/ + +### 1 编写edl接口文件 + + enclave { + include "secgear_urts.h" + from "secgear_tstdc.edl" import *; + trusted { + public int get_string([out, size=32]char *buf); + }; + }; +'include "secgear_urts.h" from "secgear_tstdc.edl" import *'是为了屏蔽SGX和iTrustee在调用libc库之间的差异。所以为了开发代码的一致性,默认导入这两个文件。 +有关edl语法的详细信息,请参阅SGX开发文档定义的EDL(Enclave Definition Language)语法部分。 +目前SGX和iTrustee在基本类型、指针类型和深拷贝方面是相互兼容的。对于user_check、private ecalls、switchless特性仅支持sgx硬件。 + +保存文件名为test.edl + +### 2 编写最外层CMakeLists.txt文件 + + cmake_minimum_required(VERSION 3.10 FATAL_ERROR) + project(TEST C) + set(CMAKE_C_STANDARD 99) + set(CURRENT_ROOT_PATH ${CMAKE_CURRENT_SOURCE_DIR}) + set(EDL_FILE test.edl) + set(LOCAL_ROOT_PATH "$ENV{CC_SDK}") + set(SECGEAR_INSTALL_PATH /lib64/) + set(CODEGEN codegen) + if(CC_GP) + set(CODETYPE trustzone) + execute_process(COMMAND uuidgen -r OUTPUT_VARIABLE UUID) + string(REPLACE "\n" "" UUID ${UUID}) + add_definitions(-DPATH="/data/${UUID}.sec") + endif() + if(CC_SGX) + set(CODETYPE sgx) + add_definitions(-DPATH="${CMAKE_CURRENT_BINARY_DIR}/enclave/enclave.signed.so") + endif() + add_subdirectory(${CURRENT_ROOT_PATH}/enclave) + add_subdirectory(${CURRENT_ROOT_PATH}/host) + +EDL_FILE、CODETYPE:稍后自动构建的时候会用到这些属性。 +UUID:在iTrustee中,构建安全enclave动态库需要使用UUID命名,这里由uuidgen命令自动生成。 +DPATH:用于定义非安全侧使用安全侧动态库的绝对路径 + +### 3 编写非安全侧代码和CMakeLists.txt文件 + +#### 3.1 创建host目录和main.c文件 + + #include + #include "enclave.h" + #include "test_u.h" + + #define BUF_LEN 32 + + int main() + { + int retval = 0; + char *path = PATH; + char buf[BUF_LEN]; + cc_enclave_t *context = NULL; + cc_enclave_result_t res; + + res = cc_enclave_create(path, AUTO_ENCLAVE_TYPE, 0, SECGEAR_DEBUG_FLAG, NULL, 0, &context); + ... + + res = get_string(context, &retval, buf); + if (res != CC_SUCCESS || retval != (int)CC_SUCCESS) { + printf("Ecall enclave error\n"); + } else { + printf("%s\n", buf); + } + + if (context != NULL) { + res = cc_enclave_destroy(context); + ... + } + return res; + } + +enclave.h: secGear库头文件 +test_u.h: 根据edl文件自动生成的非安全侧头文件。 +cc_enclave_create: 用于创建enclave安全上下文。 +get_string: 根据edl中trusted定义的安全侧代理函数,该代理函数用于进入到安全侧执行安全代码。 +cc_enclave_destroy: 用于销毁enclave安全上下文。 + +注意:这里调用的get_string函数与在edl中定义的get_string函数有些不同,这里的参数比edl中定义的多了前两个参数,分别是enclave安全上下文 +和retval参数。这是因为codegen(自动生成代码工具)通过edl生成的非安全侧代理函数,其声明在test_u.h中。 +如果在edl中定义的函数无返回值时,例如"public void get_string([out,size=32] char *buf);"则非安全侧代理函数为 +"res=get_string(context, buf)"(这里就不在有retval参数) + +#### 3.2 编写非安全侧CMakeLists.txt + + #set auto code prefix + set(PREFIX test) + #set host exec name + set(OUTPUT secgear_test) + #set host src code + set(SOURCE_FILE ${CMAKE_CURRENT_SOURCE_DIR}/main.c) + +设置预备的基础变量 + + #set auto code + if(CC_GP) + set(AUTO_FILES ${CMAKE_CURRENT_BINARY_DIR}/${PREFIX}_u.h ${CMAKE_CURRENT_BINARY_DIR}/${PREFIX}_u.c ${CMAKE_CURRENT_BINARY_DIR}/${PREFIX}_args.h) + add_custom_command(OUTPUT ${AUTO_FILES} + DEPENDS ${CURRENT_ROOT_PATH}/${EDL_FILE} + COMMAND ${CODEGEN} --${CODETYPE} --untrusted ${CURRENT_ROOT_PATH}/${EDL_FILE} --search-path ${LOCAL_ROOT_PATH}/inc/host_inc/gp) + endif() + + if(CC_SGX) + set(AUTO_FILES ${CMAKE_CURRENT_BINARY_DIR}/${PREFIX}_u.h ${CMAKE_CURRENT_BINARY_DIR}/${PREFIX}_u.c) + add_custom_command(OUTPUT ${AUTO_FILES} + DEPENDS ${CURRENT_ROOT_PATH}/${EDL_FILE} + COMMAND ${CODEGEN} --${CODETYPE} --untrusted ${CURRENT_ROOT_PATH}/${EDL_FILE} --search-path ${LOCAL_ROOT_PATH}/inc/host_inc/sgx --search-path ${SGXSDK}/include) + endif() + +设置使用代码辅助生成工具根据edl文件生成辅助代码。CODEGEN和CODETYPE等变量定义在CMakeList.txt文件.--search-path用于搜索在edl文件中导入依赖的其他edl文件。 +当使用SGX时,需要导入sgx提供的基础edl,因此这里指定了SGXSDK的patch "--search-path ${SGXSDK}/include)"。 + + set(CMAKE_C_FLAGS "-fstack-protector-all -W -Wall -Werror -Wextra -Werror=array-bounds -D_FORTIFY_SOURCE=2 -O2 -ftrapv -fPIE") + set(CMAKE_EXE_LINKER_FLAGS "-Wl,-z,relro -Wl,-z,now -Wl,-z,noexecstack") + +设置编译选项和链接选项 + + if(CC_GP) + if(${CMAKE_VERSION} VERSION_LESS "3.13.0") + link_directories(${SECGEAR_INSTALL_PATH}) + endif() + add_executable(${OUTPUT} ${SOURCE_FILE} ${AUTO_FILES}) + target_include_directories(${OUTPUT} PRIVATE + ${LOCAL_ROOT_PATH}/inc/host_inc + ${LOCAL_ROOT_PATH}/inc/host_inc/gp + ${CMAKE_CURRENT_BINARY_DIR}) + if(${CMAKE_VERSION} VERSION_GREATER_EQUAL "3.13.0") + target_link_directories(${OUTPUT} PRIVATE ${SECGEAR_INSTALL_PATH}) + endif() + endif() + +在iTrustee硬件环境上,设置头文件的搜索路径及编译生成非安全侧二进制文件。 + + if(CC_SGX) + if(${CMAKE_VERSION} VERSION_LESS "3.13.0") + link_directories(${SECGEAR_INSTALL_PATH}) + endif() + add_executable(${OUTPUT} ${SOURCE_FILE} ${AUTO_FILES}) + target_include_directories(${OUTPUT} PRIVATE + ${LOCAL_ROOT_PATH}/inc/host_inc + ${LOCAL_ROOT_PATH}/inc/host_inc/sgx + ${CMAKE_CURRENT_BINARY_DIR}) + if(${CMAKE_VERSION} VERSION_GREATER_EQUAL "3.13.0") + target_link_directories(${OUTPUT} PRIVATE ${SECGEAR_INSTALL_PATH}) + endif() + endif() + +在SGX硬件环境上,设置头文件的搜索路径及编译生成非安全侧二进制文件。 + + if(CC_SIM) + target_link_libraries(${OUTPUT} secgearsim) + else() + target_link_libraries(${OUTPUT} secgear) + endif() + set_target_properties(${OUTPUT} PROPERTIES SKIP_BUILD_RPATH TRUE) + if(CC_GP) + install(TARGETS ${OUTPUT} + RUNTIME + DESTINATION /vendor/bin/ + PERMISSIONS OWNER_EXECUTE OWNER_WRITE OWNER_READ) + endif() + if(CC_SGX) + install(TARGETS ${OUTPUT} + RUNTIME + DESTINATION ${CMAKE_BINARY_DIR}/bin/ + PERMISSIONS OWNER_EXECUTE OWNER_WRITE OWNER_READ) + endif() + + +设置secGear链接库,当指定模拟模式CC_SIM时链接libsecgearsim.so,否则链接libsecgear.so。 +在iTrustee硬件环境上需指定安装固定的安全白名单。 + +### 4 编写安全侧代码、CMakeList.txt及基础配置文件 + +#### 4.1 创建enclave目录 编写hello.c + + #include + #include + #include "test_t.h" + + #define TA_HELLO_WORLD "secGear hello world!" + #define BUF_MAX 32 + int get_string(char *buf) + { + strncpy(buf, TA_HELLO_WORLD, strlen(TA_HELLO_WORLD) + 1); + return 0; + } + +test_t.h:该头文件为自动生成代码工具codegen通过edl文件生成的头文件。该头文件命名为edl文件名加"_t"。 + +#### 4.2 编写CMakeList.txt文件 + + #set auto code prefix + set(PREFIX test) + #set sign key + set(PEM Enclave_private.pem) + +设置enclave签名私钥 + + #set sign tool + set(SIGN_TOOL ${LOCAL_ROOT_PATH}/tools/sign_tool/sign_tool.sh) + #set enclave src code + set(SOURCE_FILES ${CMAKE_CURRENT_SOURCE_DIR}/hello.c) + #set log level + set(PRINT_LEVEL 3) + add_definitions(-DPRINT_LEVEL=${PRINT_LEVEL}) + +设置签名工具已经安全侧打印日志level + + if(CC_GP) + #set signed output + set(OUTPUT ${UUID}.sec) + + set(WHITE_LIST_0 /vendor/bin/helloworld) + set(WHITE_LIST_1 /vendor/bin/secgear_test) + set(WHITE_LIST_OWNER root) + set(WHITELIST WHITE_LIST_0 WHITE_LIST_1) + + set(AUTO_FILES ${CMAKE_CURRENT_BINARY_DIR}/${PREFIX}_t.h ${CMAKE_CURRENT_BINARY_DIR}/${PREFIX}_t.c ${CMAKE_CURRENT_BINARY_DIR}/${PREFIX}_args.h) + add_custom_command(OUTPUT ${AUTO_FILES} + DEPENDS ${CURRENT_ROOT_PATH}/${EDL_FILE} + COMMAND ${CODEGEN} --${CODETYPE} --trusted ${CURRENT_ROOT_PATH}/${EDL_FILE} --search-path ${LOCAL_ROOT_PATH}/inc/host_inc/gp) + endif() + +WHITE_LIST_x:为设置iTrustee的二进制白名单,只有这里定义的白名单,在非安全侧的二进制才可以调用安全侧的动态库。上限为8个。 +WHITE_LIST_OWNER:为设置运行二进制的用户,只有该用户才可以调用安全侧动态库。 +AUTO_FILES:由edl文件生成的安全侧二进制文件 + + if(CC_SGX) + set(OUTPUT enclave.signed.so) + set(AUTO_FILES ${CMAKE_CURRENT_BINARY_DIR}/${PREFIX}_t.h ${CMAKE_CURRENT_BINARY_DIR}/${PREFIX}_t.c) + add_custom_command(OUTPUT ${AUTO_FILES} + DEPENDS ${CURRENT_ROOT_PATH}/${EDL_FILE} + COMMAND ${CODEGEN} --${CODETYPE} --trusted ${CURRENT_ROOT_PATH}/${EDL_FILE} --search-path ${LOCAL_ROOT_PATH}/inc/host_inc/sgx --search-path ${SGXSDK}/include) + endif() + +设置自动生成代码及签名动态库。 + + set(COMMON_C_FLAGS "-W -Wall -Werror -fno-short-enums -fno-omit-frame-pointer -fstack-protector \ + -Wstack-protector --param ssp-buffer-size=4 -frecord-gcc-switches -Wextra -nostdinc -nodefaultlibs \ + -fno-peephole -fno-peephole2 -Wno-main -Wno-error=unused-parameter \ + -Wno-error=unused-but-set-variable -Wno-error=format-truncation=") + + set(COMMON_C_LINK_FLAGS "-Wl,-z,now -Wl,-z,relro -Wl,-z,noexecstack -Wl,-nostdlib -nodefaultlibs -nostartfiles") + +设置安全侧便编译选项和链接选项。由于安全侧和非安全侧不同,非安全侧的标准动态库不能被安全侧链接。例如:"-nostdlib -nodefaultlibs -nostartfiles" + + + if(CC_GP) + configure_file("${CMAKE_CURRENT_SOURCE_DIR}/manifest.txt.in" "${CMAKE_CURRENT_SOURCE_DIR}/manifest.txt") + + set(CMAKE_C_FLAGS "${COMMON_C_FLAGS} -march=armv8-a ") + set(CMAKE_C_FLAGS_RELEASE "${CMAKE_C_FLAGS} -s -fPIC") + set(CMAKE_SHARED_LINKER_FLAGS "${COMMON_C_LINK_FLAGS} -Wl,-s") + + set(ITRUSTEE_TEEDIR ${iTrusteeSDK}/) + set(ITRUSTEE_LIBC ${iTrusteeSDK}/thirdparty/open_source/musl/libc) + + if(${CMAKE_VERSION} VERSION_LESS "3.13.0") + link_directories(${SECGEAR_INSTALL_PATH}) + endif() + + add_library(${PREFIX} SHARED ${SOURCE_FILES} ${AUTO_FILES}) + + target_include_directories( ${PREFIX} PRIVATE + ${CMAKE_CURRENT_BINARY_DIR} + ${LOCAL_ROOT_PATH}/inc/host_inc + ${LOCAL_ROOT_PATH}/inc/host_inc/gp + ${LOCAL_ROOT_PATH}/inc/enclave_inc + ${LOCAL_ROOT_PATH}/inc/enclave_inc/gp + ${ITRUSTEE_TEEDIR}/include/TA + ${ITRUSTEE_TEEDIR}/include/TA/huawei_ext + ${ITRUSTEE_LIBC}/arch/aarch64 + ${ITRUSTEE_LIBC}/ + ${ITRUSTEE_LIBC}/arch/arm/bits + ${ITRUSTEE_LIBC}/arch/generic + ${ITRUSTEE_LIBC}/arch/arm + ${LOCAL_ROOT_PATH}/inc/enclave_inc/gp/itrustee) + + if(${CMAKE_VERSION} VERSION_GREATER_EQUAL "3.13.0") + target_link_directories(${PREFIX} PRIVATE ${SECGEAR_INSTALL_PATH}) + endif() + + foreach(WHITE_LIST ${WHITELIST}) + add_definitions(-D${WHITE_LIST}="${${WHITE_LIST}}") + endforeach(WHITE_LIST) + add_definitions(-DWHITE_LIST_OWNER="${WHITE_LIST_OWNER}") + + target_link_libraries(${PREFIX} -lsecgear_tee) + + add_custom_command(TARGET ${PREFIX} + POST_BUILD + COMMAND bash ${SIGN_TOOL} -d sign -x trustzone -i lib${PREFIX}.so -c ${CMAKE_CURRENT_SOURCE_DIR}/manifest.txt + -o ${CMAKE_CURRENT_BINARY_DIR}/${OUTPUT}) + + install(FILES ${CMAKE_CURRENT_BINARY_DIR}/${OUTPUT} + DESTINATION /data + PERMISSIONS OWNER_EXECUTE OWNER_WRITE OWNER_READ GROUP_READ GROUP_EXECUTE WORLD_READ WORLD_EXECUTE) + + endif() + +manifest.txt:itrustee安全侧配置文件,后面对该文件进行详解 +指定itrustee特性编译选项,设置引用头文件和动态库的路径。 +前面声明的白名单在这里定义。 +itrustee需要链接secgear_tee动态库,提供seal接口等。 + + if(CC_SGX) + set(SGX_DIR ${SGXSDK}) + set(CMAKE_C_FLAGS "${COMMON_C_FLAGS} -m64 -fvisibility=hidden") + set(CMAKE_C_FLAGS_RELEASE "${CMAKE_C_FLAGS} -s") + set(LINK_LIBRARY_PATH ${SGX_DIR}/lib64) + + if(CC_SIM) + set(Trts_Library_Name sgx_trts_sim) + set(Service_Library_Name sgx_tservice_sim) + else() + set(Trts_Library_Name sgx_trts) + set(Service_Library_Name sgx_tservice) + endif() + + set(Crypto_Library_Name sgx_tcrypto) + + set(CMAKE_SHARED_LINKER_FLAGS "${COMMON_C_LINK_FLAGS} -Wl,-z,defs -Wl,-pie -Bstatic -Bsymbolic -eenclave_entry \ + -Wl,--export-dynamic -Wl,--defsym,__ImageBase=0 -Wl,--gc-sections -Wl,--version-script=${CMAKE_CURRENT_SOURCE_DIR}/Enclave.lds") + + if(${CMAKE_VERSION} VERSION_LESS "3.13.0") + link_directories(${LINK_LIBRARY_PATH}) + endif() + + add_library(${PREFIX} SHARED ${SOURCE_FILES} ${AUTO_FILES}) + + target_include_directories(${PREFIX} PRIVATE + ${CMAKE_CURRENT_BINARY_DIR} + ${SGX_DIR}/include/tlibc + ${SGX_DIR}/include/libcxx + ${SGX_DIR}/include + ${LOCAL_ROOT_PATH}/inc/host_inc + ${LOCAL_ROOT_PATH}/inc/host_inc/sgx) + + if(${CMAKE_VERSION} VERSION_GREATER_EQUAL "3.13.0") + target_link_directories(${PREFIX} PRIVATE + ${LINK_LIBRARY_PATH}) + endif() + + target_link_libraries(${PREFIX} -Wl,--whole-archive ${Trts_Library_Name} -Wl,--no-whole-archive + -Wl,--start-group -lsgx_tstdc -lsgx_tcxx -l${Crypto_Library_Name} -l${Service_Library_Name} -Wl,--end-group) + add_custom_command(TARGET ${PREFIX} + POST_BUILD + COMMAND openssl genrsa -3 -out ${PEM} 3072 + COMMAND bash ${SIGN_TOOL} -d sign -x sgx -i lib${PREFIX}.so -k ${PEM} -o ${OUTPUT} -c ${CMAKE_CURRENT_SOURCE_DIR}/Enclave.config.xml) + endif() + + +在SGX硬件环境上,指定一些与sgx相关的编译选项、链接选项。链接动态库时有所不同,因为itrustee是一个具有更多功能的安全操作系统。提供如muslibc和openssl。在编译和链接itrustee时不用链接一些基本库,但是sgx没有OS概念。所以要在安全侧调用这些基本库的接口都要以静态的形式在sgxsdk中给出。例如"sgx_trts" + +有关更多详细信息,请参阅sgx示例的Makefile。最后用enclave配置文件完成签名,稍后将进行介绍。secGear尚不支持远程身份验证。 + +#### 4.3 编写安全侧配置文件 + +编写与sgx enclave相关的配置文件中Enclave.config.xml文件及enclave.lds文件与官方sgx配置相同。详情参阅官方开发文档。 + +编写itrustee enclave相关配置文件 +mainfest.txt.in:其中gpd.ta.appID 为动态生成uuid。其他配置参见itrustee开发文档。 + + +#### 5 构建 安装 + +进入开发目录:cd .../secGear/example/test/ +创建debug目录:mkdir debug && cd debug +cmake构建:cmake -DCMAKE_BUILD_TYPE=Debug -DCC_SGX=ON -DSGXSDK=sgx_sdk path .. && make && sudo make install (sgx硬件环境) + cmake -DCMAKE_BUILD_TYPE=Debug -DCC_GP=ON -DiTrusteeSDK=gp_sdk path .. && make && sudo make install (itrustee硬件环境) + +Log +--- +非安全侧日志记录: + +非安全侧是开发与普通开发环境一样,可使用通用打印日志接口。 + +安全侧日志记录: + +由于各架构安全能力不同的限制,为了像非安全侧一样开发使用日志打印功能,因为我们提供了PrintInfo接口将安全端日志记录到syslog系统中。 +相关配置文件为 conf/logrotate.d/secgear和conf/rsyslog.d/secgear.conf文件,安装时将安装在系统目录/etc/中。 + +注意:在itrustee上,需要include secgear_log.h头文件,但是sgx不需要,sgx通过ocall功能实现的,所以相关代码生成在辅助代码中。 +当文件安装成功后需要运行"systemctl restart rsyslog"使日志功能生效。 + +日志等级: + + PRINT_ERROR 0 + PRINT_WARNING 1 + PRINT_STRACE 2 + PRINT_DEBUG 3 + +使用ocall +--------- + +目前ocall仅在sgx平台支持,itrustee尚不支持。 + +seal, generate_random接口 +-------------------------------------- + +接口定义在secgear_dataseal.h、secgear_random.h中。 +注意:由于itrustee派生密钥的功能仍然不完善,因此目前还没有与密封相关的接口在itrustee平台上支持。 + +远程证明(尚不支持) +-------------------------------------- + +了解更多关于codegener +-------------------------------------- + +secGear引入EDL(Enclave Description Language)和中间代码辅助生成工具codegener。edl与intel sgx定义兼容。 + + +- [了解更多关于codegener](./docs/codegener.md) + +了解更多关于sign_tool +----------------------------- + + +- [了解更多关于签名工具](./docs/sign_tool.md) + +里程碑 +--------- +secGear diff --git a/secGear.spec b/secGear.spec index 8f5bacc..284e79e 100644 --- a/secGear.spec +++ b/secGear.spec @@ -1,8 +1,8 @@ Name: secGear Version: 0.1.0 -Release: 11%{?dist} +Release: 17%{?dist} Summary: secGear is an SDK to develop confidential computing apps based on hardware enclave features -ExclusiveArch: x86_64 + Group: OS Security License: Mulan PSL v2 @@ -17,94 +17,130 @@ Patch4: 0005-delete-unnecessary-README.cn.md.patch Patch5: 0006-fix-issues-about-double-create-destory.patch Patch6: 0007-to-make-secGear-log-more-clear.patch Patch7: 0008-modify-path-error.patch -Patch8: 0009-fix-sgxssl-edl.patch -Patch9: 0010-update-docs-build_install.md.patch -Patch10: 0011-modify-the-prompt-information.patch -Patch11: 0012-parse-new-error-code-and-del-redundant-print.patch -Patch12: 0013-fix-error-print.patch -Patch13: 0014-set-umask-in-sign_tool.sh.patch -Patch14: 0015-1.fix-the-race-of-ecall-and-enclave-destroy.patch -Patch15: 0016-fix-wrong-spelling-and-null-pointer-dereference-issu.patch - -BuildRequires: gcc python3 automake autoconf libtool -BUildRequires: glibc glibc-devel +Patch8: 0009-fix-cmake-error-of-missing-CMAKE_CXX_COMPILER.patch +Patch9: 0010-fix-sgxssl-edl.patch +Patch10: 0011-update-docs-build_install.md.patch +Patch11: 0012-modify-the-prompt-information.patch +Patch12: 0013-parse-new-error-code-and-del-redundant-print.patch +Patch13: 0014-fix-error-print.patch +Patch14: 0015-set-umask-in-sign_tool.sh.patch +Patch15: 0016-1.fix-the-race-of-ecall-and-enclave-destroy.patch +Patch16: 0017-fix-wrong-spelling-and-null-pointer-dereference-issu.patch +Patch17: 0018-update-sign_tool.doc.patch +Patch18: 0019-normalized-codegen-from-arm-and-x86.patch +Patch19: 0020-rm-e-parameter-normalize-c-parameter.patch +Patch20: 0021-example-use-absolute-path-to-find-enclave.sign.so.patch +Patch21: 0022-add-example-of-using-sgxssl-lib.patch +Patch22: 0023-tls_enclave-is-not-compiled-by-default.patch +Patch23: 0024-Cmake-replace-minial-cmake-from-3.12-to-3.10.patch +Patch24: 0025-example-add-example-for-LRT-long-running-task.patch +Patch25: 0026-example-add-Dockerfile-to-build-lrt-example-image.patch +Patch26: 0027-Change-to-use-the-milestone-picture-with-English.patch +Patch27: 0028-example-use-the-sgx-device-plugin-from-intel.patch +Patch28: 0029-some-adaptations-for-trustzone.patch +Patch29: 0030-fix-sgx-two-step-mode-bug-add-dump-command.patch +Patch30: 0031-set-signtool_v3.py-path.patch +Patch31: 0032-del-size_to_aligned_size.patch +Patch32: 0033-modify-the-error-information-when-missing-c-and-m.patch +Patch33: 0034-normalize-the-log-printed-by-PrintInfo.patch +Patch34: 0035-itrustee-add-lrt-support-itrustee.patch +Patch35: 0036-enclave-use-the-can-pull-image-from-hub.oepkgs.net.patch +Patch36: 0037-add-description-about-file-parameter-path-for-sign_t.patch +Patch37: 0038-fix-use-after-free-in-cc_enclave_create.patch +Patch38: 0039-clean-memory-when-it-come-to-error_handle.patch + +BuildRequires: gcc python automake autoconf libtool +BUildRequires: glibc glibc-devel cmake ocaml-dune %ifarch x86_64 BUildRequires: linux-sgx-driver sgxsdk libsgx-launch libsgx-urts +%else +BUildRequires: itrustee_sdk %endif -BUildRequires: cmake ocaml-dune -Requires: rsyslog +Requires: rsyslog %ifarch x86_64 -Requires: linux-sgx-driver sgxsdk libsgx-launch libsgx-urts +Requires: linux-sgx-driver sgxsdk libsgx-launch libsgx-urts +%else +Requires: itrustee_sdk %endif + %description secGear is an SDK to develop confidential computing apps based on hardware enclave features -%package devel -Summary: Development files for %{name} -Requires: %{name}%{?isa} = %{version}-%{release} +%package devel +Summary: Development files for %{name} +Requires: %{name}%{?isa} = %{version}-%{release} cmake %description devel -The %{name}-devel is package contains Header file for developing applications that +The %{name}-devel is package contains Header file for developing applications that us %{name} -%package sim -Summary: simulation package files for %{name} -Requires: %{name}%{?isa} = %{version}-%{release} -%description sim +%ifarch x86_64 +%package sim +Summary: simulation package files for %{name} +Requires: %{name}%{?isa} = %{version}-%{release} +%description sim The %{name}-sim is package contains simulation libraries for developing applications +%endif %prep %autosetup -n %{name} -p1 - %build source ./environment %ifarch x86_64 source /opt/intel/sgxsdk/environment cmake -DCMAKE_BUILD_TYPE=Debug -DCC_SGX=on -DSGXSDK=/opt/intel/sgxsdk -make +make %else -#The itrustee OS is not released +cmake -DCMAKE_BUILD_TYPE=Debug -DCC_GP=on -DiTrusteeSDK=/opt/itrustee_sdk +make %endif - %install make install DESTDIR=%{buildroot} install -d %{buildroot}/%{_datarootdir}/licenses/secGear install -pm 644 License/Third_Party_Open_Source_Software_Notice.md %{buildroot}/%{_datarootdir}/licenses/secGear install -d %{buildroot}/%{_includedir}/secGear -#install -pm 644 inc/host_inc/* %{buildroot}/%{_includedir}/secGear/host_inc -%ifarch x86_64 install -d %{buildroot}/%{_bindir} +install -pm 751 bin/codegen %{buildroot}/%{_bindir} +install -pm 751 tools/sign_tool/sign_tool.sh %{buildroot}/%{_bindir} +install -d %{buildroot}/%{_sysconfdir}/secGear/cloud +install -d %{buildroot}/lib/secGear/ +install -pm 751 tools/sign_tool/*.py %{buildroot}/lib/secGear +install -pm 644 tools/sign_tool/cloud/rsa_public_key_cloud.pem %{buildroot}/%{_sysconfdir}/secGear/cloud +%ifarch x86_64 install -pm 644 inc/host_inc/*.h %{buildroot}/%{_includedir}/secGear install -pm 644 inc/host_inc/sgx/*.h %{buildroot}/%{_includedir}/secGear install -pm 644 inc/host_inc/sgx/*.edl %{buildroot}/%{_includedir}/secGear install -pm 644 inc/enclave_inc/*.h %{buildroot}/%{_includedir}/secGear install -pm 644 inc/enclave_inc/sgx/*.h %{buildroot}/%{_includedir}/secGear -install -pm 751 bin/codegen_x86_64 %{buildroot}/%{_bindir} -install -pm 751 tools/sign_tool/sign_tool.sh %{buildroot}/%{_bindir} %else install -d %{buildroot}/%{_includedir}/secGear install -pm 644 inc/host_inc/*.h %{buildroot}/%{_includedir}/secGear install -pm 644 inc/host_inc/gp/*.h %{buildroot}/%{_includedir}/secGear +install -pm 644 inc/host_inc/gp/*.edl %{buildroot}/%{_includedir}/secGear install -pm 644 inc/enclave_inc/*.h %{buildroot}/%{_includedir}/secGear install -pm 644 inc/enclave_inc/gp/*.h %{buildroot}/%{_includedir}/secGear +install -pm 644 inc/enclave_inc/gp/itrustee/*.h %{buildroot}/%{_includedir}/secGear %endif pushd %{buildroot} rm `find . -name secgear_helloworld` -rf rm `find . -name secgear_seal_data` -rf +%ifarch aarch64 +rm `find . -name libsecgearsim.so` -rf +%endif popd %files %license License/LICENSE %license License/Third_Party_Open_Source_Software_Notice.md %defattr(-,root,root) -/%{_lib}/libsecgear_tee.a -/%{_lib}/libsecgear.so +%{_libdir}/libsecgear_tee.a +%{_libdir}/libsecgear.so %ifarch x86_64 -/%{_lib}/libsgx_0.so +%{_libdir}/libsgx_0.so %else -#The itrustee OS is not released +%{_libdir}/libgp_0.so %endif %config(noreplace) %attr(0600,root,root) %{_sysconfdir}/rsyslog.d/secgear.conf %config(noreplace) %attr(0600,root,root) %{_sysconfdir}/logrotate.d/secgear @@ -112,18 +148,36 @@ popd %files devel %{_bindir}/* %{_includedir}/secGear/* +/lib/secGear/* +%{_sysconfdir}/secGear/cloud/rsa_public_key_cloud.pem +%ifarch x86_64 %files sim %defattr(-,root,root) %license License/LICENSE -/%{_lib}/libsecgearsim.so -%ifarch x86_64 -/%{_lib}/libsgxsim_0.so -%else -#The itrustee OS is not released +%{_libdir}/libsecgearsim.so +%{_libdir}/libsgxsim_0.so %endif %changelog +* Fri June 4 2021 chenmaodong - 0.1.0-17 +- DESC: clean enclave memory when it comes to error_handle + +* Thu June 3 2021 chenmaodong - 0.1.0-16 +- DESC: backport some patches from openeuler secGear + +* Wed June 2 2021 chenmaodong - 0.1.0-15 +- DESC: fix uaf in cc_enclave_create + +* Thu May 20 2021 chenmaodong - 0.1.0-14 +- DESC: update some bugfix form openeuler secGear + +* Wed May 12 2021 yanlu - 0.1.0-13 +- DESC: update signtool and codegen + +* Thu Apr 27 2021 chenmaodong - 0.1.0-12 +- DESC: add cmake to Requires + * Tue Apr 13 2021 wanghongzhe - 0.1.0-11 - DESC: add licenses and thirdparty opensource notice -- Gitee