You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@teaclave.apache.org by ms...@apache.org on 2019/12/18 04:15:19 UTC

[incubator-teaclave] branch master updated: [config] Make runtime config optional and handle none config at enclave init (#172)

This is an automated email from the ASF dual-hosted git repository.

mssun pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/incubator-teaclave.git


The following commit(s) were added to refs/heads/master by this push:
     new 4220e33  [config] Make runtime config optional and handle none config at enclave init (#172)
4220e33 is described below

commit 4220e331550de7421a76702bbee1ad574cb6ae87
Author: Mingshen Sun <bo...@mssun.me>
AuthorDate: Tue Dec 17 20:15:13 2019 -0800

    [config] Make runtime config optional and handle none config at enclave init (#172)
    
    * [config] Make runtime config optional and handle none config at enclave init
    
    * Add mesatee_core::init_service()
---
 mesatee_core/Cargo.toml                            |  7 +--
 mesatee_core/src/config/external.rs                | 13 +++--
 mesatee_core/src/config/internal.rs                | 42 +++++++++++----
 mesatee_core/src/lib.rs                            | 17 ++++++
 mesatee_core/src/rpc/sgx/mod.rs                    | 10 ++--
 mesatee_core/src/rpc/sgx/ra.rs                     |  8 +--
 mesatee_services/acs/sgx_app/build.rs              | 13 -----
 mesatee_services/acs/sgx_trusted_lib/Cargo.toml    |  1 +
 mesatee_services/acs/sgx_trusted_lib/src/sgx.rs    | 12 +----
 mesatee_services/fns/sgx_app/build.rs              | 13 -----
 mesatee_services/fns/sgx_trusted_lib/Cargo.toml    |  1 +
 .../fns/sgx_trusted_lib/src/sgx/mod.rs             | 12 +----
 mesatee_services/kms/sgx_app/build.rs              | 13 -----
 mesatee_services/kms/sgx_app/src/main.rs           |  2 +-
 mesatee_services/kms/sgx_trusted_lib/Cargo.toml    |  1 +
 mesatee_services/kms/sgx_trusted_lib/src/sgx.rs    | 12 +----
 mesatee_services/tdfs/sgx_app/build.rs             | 13 -----
 mesatee_services/tdfs/sgx_app/src/main.rs          |  2 +-
 mesatee_services/tdfs/sgx_trusted_lib/Cargo.toml   |  1 +
 mesatee_services/tdfs/sgx_trusted_lib/src/sgx.rs   | 12 +----
 mesatee_services/tms/sgx_trusted_lib/Cargo.toml    |  1 +
 mesatee_services/tms/sgx_trusted_lib/src/sgx.rs    | 12 +----
 teaclave_config/Cargo.toml                         |  1 +
 teaclave_config/src/lib.rs                         | 60 +++++++++++++++++-----
 tests/functional_test/sgx_app/build.rs             | 13 -----
 tests/functional_test/sgx_trusted_lib/src/sgx.rs   | 12 +----
 26 files changed, 133 insertions(+), 171 deletions(-)

diff --git a/mesatee_core/Cargo.toml b/mesatee_core/Cargo.toml
index c11468b..fb5aec2 100644
--- a/mesatee_core/Cargo.toml
+++ b/mesatee_core/Cargo.toml
@@ -17,12 +17,13 @@ ipc = []
 
 [dependencies]
 cfg-if       = { version = "0.1.9" }
+env_logger   = { version = "0.7.1" }
+lazy_static  = { version = "1.0.2", features = ["spin_no_std"] }
 log          = { version = "0.4.6" }
+rustls       = { version = "0.16.0", features = ["dangerous_configuration"] }
 serde        = { version = "1.0.92" }
 serde_derive = { version = "1.0.92" }
 serde_json   = { version = "1.0.39" }
-rustls       = { version = "0.16.0", features = ["dangerous_configuration"] }
-lazy_static  = { version = "1.0.2", features = ["spin_no_std"] }
 chrono       = { version = "0.4.6" }
 ring         = { version = "0.16.5" }
 webpki       = { version = "0.21.0" }
@@ -36,7 +37,7 @@ uuid         = { version = "0.7.4", features = ["v4"] }
 net2         = { version = "0.2.33" }
 toml         = { version = "0.5.3" }
 
-sgx_tstd  = { version = "1.0.9", features = ["net"], optional = true }
+sgx_tstd  = { version = "1.0.9", features = ["net", "backtrace"], optional = true }
 sgx_types = { version = "1.0.9" }
 sgx_urts  = { version = "1.0.9" }
 sgx_tcrypto = { version = "1.0.9", optional = true }
diff --git a/mesatee_core/src/config/external.rs b/mesatee_core/src/config/external.rs
index a7288d2..ff2f783 100644
--- a/mesatee_core/src/config/external.rs
+++ b/mesatee_core/src/config/external.rs
@@ -18,34 +18,37 @@
 use super::get_trusted_enclave_attr;
 use super::ServiceConfig;
 use super::{InboundDesc, OutboundDesc, TargetDesc};
-use teaclave_config::runtime_config::RUNTIME_CONFIG;
+use teaclave_config::runtime_config;
 
 pub struct External;
 impl External {
     pub fn tms() -> ServiceConfig {
         ServiceConfig::new(
-            RUNTIME_CONFIG.api_endpoints.tms.listen_address,
+            runtime_config::config().api_endpoints.tms.listen_address,
             InboundDesc::External,
         )
     }
 
     pub fn fns() -> ServiceConfig {
         ServiceConfig::new(
-            RUNTIME_CONFIG.api_endpoints.fns.listen_address,
+            runtime_config::config().api_endpoints.fns.listen_address,
             InboundDesc::External,
         )
     }
 
     pub fn tdfs() -> ServiceConfig {
         ServiceConfig::new(
-            RUNTIME_CONFIG.api_endpoints.tdfs.listen_address,
+            runtime_config::config().api_endpoints.tdfs.listen_address,
             InboundDesc::External,
         )
     }
 
     pub fn target_fns() -> TargetDesc {
         TargetDesc::new(
-            RUNTIME_CONFIG.api_endpoints.fns.advertised_address,
+            runtime_config::config()
+                .api_endpoints
+                .fns
+                .advertised_address,
             OutboundDesc::Sgx(get_trusted_enclave_attr(vec!["fns"])),
         )
     }
diff --git a/mesatee_core/src/config/internal.rs b/mesatee_core/src/config/internal.rs
index 5e0c7f8..7b91e8b 100644
--- a/mesatee_core/src/config/internal.rs
+++ b/mesatee_core/src/config/internal.rs
@@ -20,62 +20,86 @@ use super::InboundDesc;
 use super::OutboundDesc;
 use super::ServiceConfig;
 use super::TargetDesc;
-use teaclave_config::runtime_config::RUNTIME_CONFIG;
+use teaclave_config::runtime_config;
 
 pub struct Internal;
 impl Internal {
     pub fn tms() -> ServiceConfig {
         ServiceConfig::new(
-            RUNTIME_CONFIG.internal_endpoints.tms.listen_address,
+            runtime_config::config()
+                .internal_endpoints
+                .tms
+                .listen_address,
             InboundDesc::Sgx(get_trusted_enclave_attr(vec!["fns"])),
         )
     }
 
     pub fn kms() -> ServiceConfig {
         ServiceConfig::new(
-            RUNTIME_CONFIG.internal_endpoints.kms.listen_address,
+            runtime_config::config()
+                .internal_endpoints
+                .kms
+                .listen_address,
             InboundDesc::Sgx(get_trusted_enclave_attr(vec!["fns", "tdfs"])),
         )
     }
 
     pub fn tdfs() -> ServiceConfig {
         ServiceConfig::new(
-            RUNTIME_CONFIG.internal_endpoints.tdfs.listen_address,
+            runtime_config::config()
+                .internal_endpoints
+                .tdfs
+                .listen_address,
             InboundDesc::Sgx(get_trusted_enclave_attr(vec!["fns", "tms"])),
         )
     }
 
     pub fn acs() -> ServiceConfig {
         ServiceConfig::new(
-            RUNTIME_CONFIG.internal_endpoints.acs.listen_address,
+            runtime_config::config()
+                .internal_endpoints
+                .acs
+                .listen_address,
             InboundDesc::Sgx(get_trusted_enclave_attr(vec!["kms", "tms", "tdfs"])),
         )
     }
 
     pub fn target_tms() -> TargetDesc {
         TargetDesc::new(
-            RUNTIME_CONFIG.internal_endpoints.tms.advertised_address,
+            runtime_config::config()
+                .internal_endpoints
+                .tms
+                .advertised_address,
             OutboundDesc::Sgx(get_trusted_enclave_attr(vec!["tms"])),
         )
     }
 
     pub fn target_kms() -> TargetDesc {
         TargetDesc::new(
-            RUNTIME_CONFIG.internal_endpoints.kms.advertised_address,
+            runtime_config::config()
+                .internal_endpoints
+                .kms
+                .advertised_address,
             OutboundDesc::Sgx(get_trusted_enclave_attr(vec!["kms"])),
         )
     }
 
     pub fn target_tdfs() -> TargetDesc {
         TargetDesc::new(
-            RUNTIME_CONFIG.internal_endpoints.tdfs.advertised_address,
+            runtime_config::config()
+                .internal_endpoints
+                .tdfs
+                .advertised_address,
             OutboundDesc::Sgx(get_trusted_enclave_attr(vec!["tdfs"])),
         )
     }
 
     pub fn target_acs() -> TargetDesc {
         TargetDesc::new(
-            RUNTIME_CONFIG.internal_endpoints.acs.advertised_address,
+            runtime_config::config()
+                .internal_endpoints
+                .acs
+                .advertised_address,
             OutboundDesc::Sgx(get_trusted_enclave_attr(vec!["acs"])),
         )
     }
diff --git a/mesatee_core/src/lib.rs b/mesatee_core/src/lib.rs
index ca81562..41a92b7 100644
--- a/mesatee_core/src/lib.rs
+++ b/mesatee_core/src/lib.rs
@@ -53,3 +53,20 @@ pub use serde::Serialize;
 pub mod prelude;
 
 pub mod config;
+
+#[cfg(feature = "mesalock_sgx")]
+pub fn init_service(name: &str) -> Result<()> {
+    use teaclave_config::runtime_config;
+
+    debug!("Enclave [{}]: Initializing...", name);
+
+    env_logger::init();
+    #[cfg(debug_assertions)]
+    let _ = backtrace::enable_backtrace(format!("{}.enclave.signed.so", name), PrintFormat::Full);
+    if runtime_config::is_initialized() {
+        return Err(Error::from(ErrorKind::ECallError));
+    }
+    crate::rpc::sgx::prelude();
+
+    Ok(())
+}
diff --git a/mesatee_core/src/rpc/sgx/mod.rs b/mesatee_core/src/rpc/sgx/mod.rs
index 0281608..aad1b57 100644
--- a/mesatee_core/src/rpc/sgx/mod.rs
+++ b/mesatee_core/src/rpc/sgx/mod.rs
@@ -36,7 +36,7 @@ use crate::rpc::RpcClient;
 use crate::Result;
 
 use teaclave_config::build_config::BUILD_CONFIG;
-use teaclave_config::runtime_config::RUNTIME_CONFIG;
+use teaclave_config::runtime_config;
 use teaclave_utils;
 use teaclave_utils::EnclaveMeasurement;
 
@@ -68,16 +68,18 @@ pub(crate) fn load_presigned_enclave_info() -> HashMap<String, EnclaveMeasuremen
     #[cfg(feature = "mesalock_sgx")]
     use std::untrusted::fs;
 
-    let ConfigSource::Path(ref enclave_info_path) = RUNTIME_CONFIG.audit.enclave_info;
+    let ConfigSource::Path(ref enclave_info_path) = runtime_config::config().audit.enclave_info;
     let enclave_info_content = fs::read_to_string(enclave_info_path)
         .unwrap_or_else(|_| panic!("Cannot find enclave info at {:?}.", enclave_info_path));
 
-    if RUNTIME_CONFIG.audit.auditor_signatures.len() < BUILD_CONFIG.auditor_public_keys.len() {
+    if runtime_config::config().audit.auditor_signatures.len()
+        < BUILD_CONFIG.auditor_public_keys.len()
+    {
         panic!("Number of auditor signatures is not enough for verification.")
     }
 
     let mut signatures: Vec<Vec<u8>> = vec![];
-    for ConfigSource::Path(ref path) in &RUNTIME_CONFIG.audit.auditor_signatures {
+    for ConfigSource::Path(ref path) in &runtime_config::config().audit.auditor_signatures {
         let signature =
             fs::read(path).unwrap_or_else(|_| panic!("Cannot find signature file {:?}.", path));
         signatures.push(signature);
diff --git a/mesatee_core/src/rpc/sgx/ra.rs b/mesatee_core/src/rpc/sgx/ra.rs
index 3973a5c..3bdfa77 100644
--- a/mesatee_core/src/rpc/sgx/ra.rs
+++ b/mesatee_core/src/rpc/sgx/ra.rs
@@ -48,7 +48,7 @@ use lazy_static::lazy_static;
 use super::fail::MayfailTrace;
 use crate::{Error, ErrorKind, Result};
 
-use teaclave_config::runtime_config::RUNTIME_CONFIG;
+use teaclave_config::runtime_config;
 use teaclave_utils;
 
 pub const CERT_VALID_DAYS: i64 = 90i64;
@@ -270,7 +270,7 @@ fn talk_to_intel_ias(fd: c_int, req: String) -> Result<Vec<u8>> {
 fn get_sigrl_from_intel(fd: c_int, gid: u32) -> Result<Vec<u8>> {
     let req = format!(
         "GET {}{:08x} HTTP/1.1\r\nHOST: {}\r\nOcp-Apim-Subscription-Key: {}\r\nConnection: Close\r\n\r\n",
-        SIGRL_SUFFIX, gid, DEV_HOSTNAME, &RUNTIME_CONFIG.env.ias_key
+        SIGRL_SUFFIX, gid, DEV_HOSTNAME, &runtime_config::config().env.ias_key
     );
 
     mayfail! {
@@ -288,7 +288,7 @@ fn get_report_from_intel(fd: c_int, quote: &[u8]) -> Result<AttnReport> {
     let req = format!("POST {} HTTP/1.1\r\nHOST: {}\r\nOcp-Apim-Subscription-Key: {}\r\nConnection: Close\r\nContent-Length:{}\r\nContent-Type: application/json\r\n\r\n{}",
                            REPORT_SUFFIX,
                            DEV_HOSTNAME,
-                           &RUNTIME_CONFIG.env.ias_key,
+                           &runtime_config::config().env.ias_key,
                            encoded_json.len(),
                            encoded_json);
 
@@ -404,7 +404,7 @@ fn create_attestation_report(pub_k: &sgx_ec256_public_t) -> Result<AttnReport> {
     };
     let p_report = &rep as *const sgx_report_t;
     let quote_type = sgx_quote_sign_type_t::SGX_LINKABLE_SIGNATURE;
-    let spid: sgx_spid_t = teaclave_utils::decode_spid(&RUNTIME_CONFIG.env.ias_spid)?;
+    let spid: sgx_spid_t = teaclave_utils::decode_spid(&runtime_config::config().env.ias_spid)?;
     let p_spid = &spid as *const sgx_spid_t;
     let p_nonce = &quote_nonce as *const sgx_quote_nonce_t;
     let p_qe_report = &mut qe_report as *mut sgx_report_t;
diff --git a/mesatee_services/acs/sgx_app/build.rs b/mesatee_services/acs/sgx_app/build.rs
index b35cb27..b92afb5 100644
--- a/mesatee_services/acs/sgx_app/build.rs
+++ b/mesatee_services/acs/sgx_app/build.rs
@@ -16,7 +16,6 @@
 // under the License.
 
 use std::env;
-use std::io::Write;
 use std::path::PathBuf;
 
 fn choose_sgx_dylib(is_sim: bool) {
@@ -33,18 +32,6 @@ fn main() {
     let sdk_dir = env::var("SGX_SDK").unwrap_or("/opt/intel/sgxsdk".into());
     println!("cargo:rustc-link-search=native={}/lib64", sdk_dir);
 
-    // This would triggers `unwrap()` which results in panic, if no such env
-    // var found. Cargo documents say that this env variable is provided by
-    // cargo. See
-    // https://doc.rust-lang.org/cargo/reference/environment-variables.html
-    let enclave_name = env!("CARGO_PKG_NAME");
-
-    // Once we enclave_name ready, write it to `../pkg_name`
-    std::fs::File::create("../pkg_name")
-        .unwrap()
-        .write_all(enclave_name.as_bytes())
-        .unwrap();
-
     let out_path = env::var_os("ENCLAVE_OUT_DIR").unwrap_or("out".into());
     let out_dir = &PathBuf::from(out_path);
 
diff --git a/mesatee_services/acs/sgx_trusted_lib/Cargo.toml b/mesatee_services/acs/sgx_trusted_lib/Cargo.toml
index 8cf853b..712240c 100644
--- a/mesatee_services/acs/sgx_trusted_lib/Cargo.toml
+++ b/mesatee_services/acs/sgx_trusted_lib/Cargo.toml
@@ -28,3 +28,4 @@ mesatee_core    = { version = "0.1.0" }
 sgx_cov         = { version = "0.1.0", optional = true }
 sgx_tstd        = { version = "1.0.9", features = ["net", "backtrace"], optional = true }
 sgx_types       = { version = "1.0.9" }
+teaclave_config = { path = "../../../teaclave_config" }
diff --git a/mesatee_services/acs/sgx_trusted_lib/src/sgx.rs b/mesatee_services/acs/sgx_trusted_lib/src/sgx.rs
index c074e8d..88e84df 100644
--- a/mesatee_services/acs/sgx_trusted_lib/src/sgx.rs
+++ b/mesatee_services/acs/sgx_trusted_lib/src/sgx.rs
@@ -26,9 +26,6 @@ use mesatee_core::config;
 use mesatee_core::prelude::*;
 use mesatee_core::{Error, ErrorKind, Result};
 
-use env_logger;
-use std::backtrace::{self, PrintFormat};
-
 use crate::acs::ACSEnclave;
 
 register_ecall_handler!(
@@ -79,14 +76,7 @@ const MODEL_TEXT: &str = include_str!("../../model.conf");
 
 #[handle_ecall]
 fn handle_init_enclave(_args: &InitEnclaveInput) -> Result<InitEnclaveOutput> {
-    debug!("Enclave [ACS]: Initializing...");
-
-    env_logger::init();
-    let _ = backtrace::enable_backtrace(
-        concat!(include_str!("../../pkg_name"), ".enclave.signed.so"),
-        PrintFormat::Full,
-    );
-    mesatee_core::rpc::sgx::prelude();
+    mesatee_core::init_service(env!("CARGO_PKG_NAME"))?;
 
     eprintln!("setting up acs model");
 
diff --git a/mesatee_services/fns/sgx_app/build.rs b/mesatee_services/fns/sgx_app/build.rs
index b35cb27..b92afb5 100644
--- a/mesatee_services/fns/sgx_app/build.rs
+++ b/mesatee_services/fns/sgx_app/build.rs
@@ -16,7 +16,6 @@
 // under the License.
 
 use std::env;
-use std::io::Write;
 use std::path::PathBuf;
 
 fn choose_sgx_dylib(is_sim: bool) {
@@ -33,18 +32,6 @@ fn main() {
     let sdk_dir = env::var("SGX_SDK").unwrap_or("/opt/intel/sgxsdk".into());
     println!("cargo:rustc-link-search=native={}/lib64", sdk_dir);
 
-    // This would triggers `unwrap()` which results in panic, if no such env
-    // var found. Cargo documents say that this env variable is provided by
-    // cargo. See
-    // https://doc.rust-lang.org/cargo/reference/environment-variables.html
-    let enclave_name = env!("CARGO_PKG_NAME");
-
-    // Once we enclave_name ready, write it to `../pkg_name`
-    std::fs::File::create("../pkg_name")
-        .unwrap()
-        .write_all(enclave_name.as_bytes())
-        .unwrap();
-
     let out_path = env::var_os("ENCLAVE_OUT_DIR").unwrap_or("out".into());
     let out_dir = &PathBuf::from(out_path);
 
diff --git a/mesatee_services/fns/sgx_trusted_lib/Cargo.toml b/mesatee_services/fns/sgx_trusted_lib/Cargo.toml
index 1d8c555..0baaf99 100644
--- a/mesatee_services/fns/sgx_trusted_lib/Cargo.toml
+++ b/mesatee_services/fns/sgx_trusted_lib/Cargo.toml
@@ -43,3 +43,4 @@ sgx_tstd             = { version = "1.0.9", features = ["net", "backtrace"], opt
 sgx_types            = { version = "1.0.9" }
 gbdt                 = { version = "0.1.0", features = ["input", "enable_training"] }
 rusty-machine        = { version = "0.5.4" }
+teaclave_config = { path = "../../../teaclave_config" }
diff --git a/mesatee_services/fns/sgx_trusted_lib/src/sgx/mod.rs b/mesatee_services/fns/sgx_trusted_lib/src/sgx/mod.rs
index 1a14243..351e3f4 100644
--- a/mesatee_services/fns/sgx_trusted_lib/src/sgx/mod.rs
+++ b/mesatee_services/fns/sgx_trusted_lib/src/sgx/mod.rs
@@ -23,9 +23,6 @@ use mesatee_core::config;
 use mesatee_core::prelude::*;
 use mesatee_core::Result;
 
-use env_logger;
-use std::backtrace::{self, PrintFormat};
-
 use crate::fns::FNSEnclave;
 use crate::global::register_trusted_worker_statically;
 
@@ -38,15 +35,8 @@ register_ecall_handler!(
 
 #[handle_ecall]
 fn handle_init_enclave(_args: &InitEnclaveInput) -> Result<InitEnclaveOutput> {
-    debug!("Enclave [FNS]: Initializing...");
-
-    env_logger::init();
-    let _ = backtrace::enable_backtrace(
-        concat!(include_str!("../../../pkg_name"), ".enclave.signed.so"),
-        PrintFormat::Full,
-    );
+    mesatee_core::init_service(env!("CARGO_PKG_NAME"))?;
 
-    mesatee_core::rpc::sgx::prelude();
     register_trusted_worker_statically();
     Ok(InitEnclaveOutput::default())
 }
diff --git a/mesatee_services/kms/sgx_app/build.rs b/mesatee_services/kms/sgx_app/build.rs
index b35cb27..b92afb5 100644
--- a/mesatee_services/kms/sgx_app/build.rs
+++ b/mesatee_services/kms/sgx_app/build.rs
@@ -16,7 +16,6 @@
 // under the License.
 
 use std::env;
-use std::io::Write;
 use std::path::PathBuf;
 
 fn choose_sgx_dylib(is_sim: bool) {
@@ -33,18 +32,6 @@ fn main() {
     let sdk_dir = env::var("SGX_SDK").unwrap_or("/opt/intel/sgxsdk".into());
     println!("cargo:rustc-link-search=native={}/lib64", sdk_dir);
 
-    // This would triggers `unwrap()` which results in panic, if no such env
-    // var found. Cargo documents say that this env variable is provided by
-    // cargo. See
-    // https://doc.rust-lang.org/cargo/reference/environment-variables.html
-    let enclave_name = env!("CARGO_PKG_NAME");
-
-    // Once we enclave_name ready, write it to `../pkg_name`
-    std::fs::File::create("../pkg_name")
-        .unwrap()
-        .write_all(enclave_name.as_bytes())
-        .unwrap();
-
     let out_path = env::var_os("ENCLAVE_OUT_DIR").unwrap_or("out".into());
     let out_dir = &PathBuf::from(out_path);
 
diff --git a/mesatee_services/kms/sgx_app/src/main.rs b/mesatee_services/kms/sgx_app/src/main.rs
index 78f5c84..a50577b 100644
--- a/mesatee_services/kms/sgx_app/src/main.rs
+++ b/mesatee_services/kms/sgx_app/src/main.rs
@@ -31,7 +31,7 @@ use teaclave_binder::TeeBinder;
 fn main() -> Result<()> {
     env_logger::init();
 
-    let tee = match TeeBinder::new("kms", 1) {
+    let tee = match TeeBinder::new(env!("CARGO_PKG_NAME"), 1) {
         Ok(r) => {
             info!("Init TEE Successfully!");
             r
diff --git a/mesatee_services/kms/sgx_trusted_lib/Cargo.toml b/mesatee_services/kms/sgx_trusted_lib/Cargo.toml
index c1c61d9..9513eab 100644
--- a/mesatee_services/kms/sgx_trusted_lib/Cargo.toml
+++ b/mesatee_services/kms/sgx_trusted_lib/Cargo.toml
@@ -29,3 +29,4 @@ mesatee_core    = { version = "0.1.0" }
 sgx_cov         = { version = "0.1.0", optional = true }
 sgx_tstd        = { version = "1.0.9", features = ["net", "backtrace"], optional = true }
 sgx_types       = { version = "1.0.9" }
+teaclave_config = { path = "../../../teaclave_config" }
diff --git a/mesatee_services/kms/sgx_trusted_lib/src/sgx.rs b/mesatee_services/kms/sgx_trusted_lib/src/sgx.rs
index 06fbbdc..491fe5b 100644
--- a/mesatee_services/kms/sgx_trusted_lib/src/sgx.rs
+++ b/mesatee_services/kms/sgx_trusted_lib/src/sgx.rs
@@ -23,9 +23,6 @@ use mesatee_core::config;
 use mesatee_core::prelude::*;
 use mesatee_core::Result;
 
-use env_logger;
-use std::backtrace::{self, PrintFormat};
-
 use crate::kms::KMSEnclave;
 
 register_ecall_handler!(
@@ -70,14 +67,7 @@ fn handle_serve_connection(args: &ServeConnectionInput) -> Result<ServeConnectio
 
 #[handle_ecall]
 fn handle_init_enclave(_args: &InitEnclaveInput) -> Result<InitEnclaveOutput> {
-    debug!("Enclave [KMS]: Initializing...");
-
-    env_logger::init();
-    let _ = backtrace::enable_backtrace(
-        concat!(include_str!("../../pkg_name"), ".enclave.signed.so"),
-        PrintFormat::Full,
-    );
-    mesatee_core::rpc::sgx::prelude();
+    mesatee_core::init_service(env!("CARGO_PKG_NAME"))?;
 
     Ok(InitEnclaveOutput::default())
 }
diff --git a/mesatee_services/tdfs/sgx_app/build.rs b/mesatee_services/tdfs/sgx_app/build.rs
index b35cb27..b92afb5 100644
--- a/mesatee_services/tdfs/sgx_app/build.rs
+++ b/mesatee_services/tdfs/sgx_app/build.rs
@@ -16,7 +16,6 @@
 // under the License.
 
 use std::env;
-use std::io::Write;
 use std::path::PathBuf;
 
 fn choose_sgx_dylib(is_sim: bool) {
@@ -33,18 +32,6 @@ fn main() {
     let sdk_dir = env::var("SGX_SDK").unwrap_or("/opt/intel/sgxsdk".into());
     println!("cargo:rustc-link-search=native={}/lib64", sdk_dir);
 
-    // This would triggers `unwrap()` which results in panic, if no such env
-    // var found. Cargo documents say that this env variable is provided by
-    // cargo. See
-    // https://doc.rust-lang.org/cargo/reference/environment-variables.html
-    let enclave_name = env!("CARGO_PKG_NAME");
-
-    // Once we enclave_name ready, write it to `../pkg_name`
-    std::fs::File::create("../pkg_name")
-        .unwrap()
-        .write_all(enclave_name.as_bytes())
-        .unwrap();
-
     let out_path = env::var_os("ENCLAVE_OUT_DIR").unwrap_or("out".into());
     let out_dir = &PathBuf::from(out_path);
 
diff --git a/mesatee_services/tdfs/sgx_app/src/main.rs b/mesatee_services/tdfs/sgx_app/src/main.rs
index f7ac9a6..6b12eb0 100644
--- a/mesatee_services/tdfs/sgx_app/src/main.rs
+++ b/mesatee_services/tdfs/sgx_app/src/main.rs
@@ -33,7 +33,7 @@ use std::thread;
 fn main() -> Result<()> {
     env_logger::init();
 
-    let tee = match TeeBinder::new("tdfs", 1) {
+    let tee = match TeeBinder::new(env!("CARGO_PKG_NAME"), 1) {
         Ok(r) => {
             info!("Init TEE Successfully!");
             r
diff --git a/mesatee_services/tdfs/sgx_trusted_lib/Cargo.toml b/mesatee_services/tdfs/sgx_trusted_lib/Cargo.toml
index d85137d..88d9402 100644
--- a/mesatee_services/tdfs/sgx_trusted_lib/Cargo.toml
+++ b/mesatee_services/tdfs/sgx_trusted_lib/Cargo.toml
@@ -30,3 +30,4 @@ kms_proto           = { path = "../../kms/proto", optional = true}
 sgx_cov             = { version = "0.1.0", optional = true }
 sgx_tstd            = { version = "1.0.9", features = ["net", "backtrace"], optional = true }
 sgx_types           = { version = "1.0.9" }
+teaclave_config = { path = "../../../teaclave_config" }
diff --git a/mesatee_services/tdfs/sgx_trusted_lib/src/sgx.rs b/mesatee_services/tdfs/sgx_trusted_lib/src/sgx.rs
index b1c1a65..e3bf309 100644
--- a/mesatee_services/tdfs/sgx_trusted_lib/src/sgx.rs
+++ b/mesatee_services/tdfs/sgx_trusted_lib/src/sgx.rs
@@ -21,9 +21,6 @@ use mesatee_core::config;
 use mesatee_core::prelude::*;
 use mesatee_core::Result;
 
-use env_logger;
-use std::backtrace::{self, PrintFormat};
-
 use crate::data_store::add_test_infomation;
 use crate::tdfs_external::DFSExternalEnclave;
 use crate::tdfs_internal::DFSInternalEnclave;
@@ -92,14 +89,7 @@ fn handle_serve_connection(args: &ServeConnectionInput) -> Result<ServeConnectio
 
 #[handle_ecall]
 fn handle_init_enclave(_args: &InitEnclaveInput) -> Result<InitEnclaveOutput> {
-    debug!("Enclave [TDFS]: Initializing...");
-
-    env_logger::init();
-    let _ = backtrace::enable_backtrace(
-        concat!(include_str!("../../pkg_name"), ".enclave.signed.so"),
-        PrintFormat::Full,
-    );
-    mesatee_core::rpc::sgx::prelude();
+    mesatee_core::init_service(env!("CARGO_PKG_NAME"))?;
 
     add_test_infomation();
 
diff --git a/mesatee_services/tms/sgx_trusted_lib/Cargo.toml b/mesatee_services/tms/sgx_trusted_lib/Cargo.toml
index b0c3a1f..85e8f54 100644
--- a/mesatee_services/tms/sgx_trusted_lib/Cargo.toml
+++ b/mesatee_services/tms/sgx_trusted_lib/Cargo.toml
@@ -33,3 +33,4 @@ tdfs_internal_client = { path = "../../tdfs/internal/client", optional = true }
 sgx_cov              = { version = "0.1.0", optional = true }
 sgx_tstd             = { version = "1.0.9", features = ["net", "backtrace"], optional = true }
 sgx_types            = { version = "1.0.9" }
+teaclave_config = { path = "../../../teaclave_config" }
diff --git a/mesatee_services/tms/sgx_trusted_lib/src/sgx.rs b/mesatee_services/tms/sgx_trusted_lib/src/sgx.rs
index dd87b0f..6d8378d 100644
--- a/mesatee_services/tms/sgx_trusted_lib/src/sgx.rs
+++ b/mesatee_services/tms/sgx_trusted_lib/src/sgx.rs
@@ -22,9 +22,6 @@ use mesatee_core::config;
 use mesatee_core::prelude::*;
 use mesatee_core::Result;
 
-use env_logger;
-use std::backtrace::{self, PrintFormat};
-
 use crate::tms_external::TMSExternalEnclave;
 use crate::tms_internal::TMSInternalEnclave;
 
@@ -37,14 +34,7 @@ register_ecall_handler!(
 
 #[handle_ecall]
 fn handle_init_enclave(_args: &InitEnclaveInput) -> Result<InitEnclaveOutput> {
-    debug!("Enclave [TMS]: Initializing...");
-
-    env_logger::init();
-    let _ = backtrace::enable_backtrace(
-        concat!(include_str!("../../pkg_name"), ".enclave.signed.so"),
-        PrintFormat::Full,
-    );
-    mesatee_core::rpc::sgx::prelude();
+    mesatee_core::init_service(env!("CARGO_PKG_NAME"))?;
 
     if cfg!(test_mode) {
         crate::data_store::add_test_information();
diff --git a/teaclave_config/Cargo.toml b/teaclave_config/Cargo.toml
index 5dc8ba8..2d01ea3 100644
--- a/teaclave_config/Cargo.toml
+++ b/teaclave_config/Cargo.toml
@@ -16,3 +16,4 @@ serde = "1.0.93"
 serde_derive = "1.0.93"
 sgx_tstd  = { version = "1.0.9", optional = true }
 toml = "0.5.1"
+log          = { version = "0.4.6" }
diff --git a/teaclave_config/src/lib.rs b/teaclave_config/src/lib.rs
index 0fd56ca..bfbea76 100644
--- a/teaclave_config/src/lib.rs
+++ b/teaclave_config/src/lib.rs
@@ -2,6 +2,8 @@
 #![cfg_attr(feature = "mesalock_sgx", no_std)]
 #[cfg(feature = "mesalock_sgx")]
 extern crate sgx_tstd as std;
+#[macro_use]
+extern crate log;
 
 pub use runtime_config::ConfigSource;
 
@@ -78,26 +80,58 @@ pub mod runtime_config {
         pub ias_key: String,
     }
 
+    pub fn is_initialized() -> bool {
+        RUNTIME_CONFIG.is_some()
+    }
+
+    pub fn config() -> &'static RuntimeConfig {
+        RUNTIME_CONFIG
+            .as_ref()
+            .expect("Invalid runtime config, should gracefully exit during enclave_init!!")
+    }
+
     lazy_static! {
-        pub static ref RUNTIME_CONFIG: RuntimeConfig = {
+        static ref RUNTIME_CONFIG: Option<RuntimeConfig> = {
             #[cfg(feature = "mesalock_sgx")]
             use std::prelude::v1::*;
-            let contents = fs::read_to_string("runtime.config.toml")
-                .expect("Something went wrong reading the runtime config file.");
-            let mut config: RuntimeConfig = toml::from_str(&contents).unwrap();
+            let contents = match fs::read_to_string("runtime.config.toml") {
+                Ok(c) => c,
+                Err(_) => {
+                    error!("Something went wrong reading the runtime config file.");
+                    return None;
+                }
+            };
+            let mut config: RuntimeConfig = match toml::from_str(&contents) {
+                Ok(c) => c,
+                Err(_) => {
+                    error!("Something went wrong reading the runtime config file.");
+                    return None;
+                }
+            };
             if !cfg!(sgx_sim) {
-                let ias_spid = env::var("IAS_SPID")
-                    .expect("Cannot find IAS_SPID from environment variables.")
-                    .trim()
-                    .to_string();
-                let ias_key = env::var("IAS_KEY")
-                    .expect("Cannot find IAS_KEY from environment variables.")
-                    .trim()
-                    .to_string();
+                let ias_spid = match env::var("IAS_SPID") {
+                    Ok(e) => e.trim().to_string(),
+                    Err(_) => {
+                        error!("Cannot find IAS_SPID from environment variables.");
+                        return None;
+                    }
+                };
+                let ias_key = match env::var("IAS_KEY") {
+                    Ok(e) => e.trim().to_string(),
+                    Err(_) => {
+                        error!("Cannot find IAS_KEY from environment variables.");
+                        return None;
+                    }
+                };
+                if ias_spid.len() != 32 || ias_key.len() != 32 {
+                    error!("IAS_SPID or IAS_KEY format error.");
+                    return None;
+                }
+
                 config.env = EnvConfig { ias_spid, ias_key };
             }
 
-            config
+            Some(config)
         };
     }
 }
diff --git a/tests/functional_test/sgx_app/build.rs b/tests/functional_test/sgx_app/build.rs
index b35cb27..b92afb5 100644
--- a/tests/functional_test/sgx_app/build.rs
+++ b/tests/functional_test/sgx_app/build.rs
@@ -16,7 +16,6 @@
 // under the License.
 
 use std::env;
-use std::io::Write;
 use std::path::PathBuf;
 
 fn choose_sgx_dylib(is_sim: bool) {
@@ -33,18 +32,6 @@ fn main() {
     let sdk_dir = env::var("SGX_SDK").unwrap_or("/opt/intel/sgxsdk".into());
     println!("cargo:rustc-link-search=native={}/lib64", sdk_dir);
 
-    // This would triggers `unwrap()` which results in panic, if no such env
-    // var found. Cargo documents say that this env variable is provided by
-    // cargo. See
-    // https://doc.rust-lang.org/cargo/reference/environment-variables.html
-    let enclave_name = env!("CARGO_PKG_NAME");
-
-    // Once we enclave_name ready, write it to `../pkg_name`
-    std::fs::File::create("../pkg_name")
-        .unwrap()
-        .write_all(enclave_name.as_bytes())
-        .unwrap();
-
     let out_path = env::var_os("ENCLAVE_OUT_DIR").unwrap_or("out".into());
     let out_dir = &PathBuf::from(out_path);
 
diff --git a/tests/functional_test/sgx_trusted_lib/src/sgx.rs b/tests/functional_test/sgx_trusted_lib/src/sgx.rs
index 5f43cf9..9b5454c 100644
--- a/tests/functional_test/sgx_trusted_lib/src/sgx.rs
+++ b/tests/functional_test/sgx_trusted_lib/src/sgx.rs
@@ -22,9 +22,6 @@ use mesatee_core::ipc::protos::ecall::{RunFunctionalTestInput, RunFunctionalTest
 use mesatee_core::prelude::*;
 use mesatee_core::Result;
 
-use env_logger;
-use std::backtrace::{self, PrintFormat};
-
 use crate::tests;
 use sgx_tunittest::*;
 
@@ -59,14 +56,7 @@ fn handle_run_functional_test(_args: &RunFunctionalTestInput) -> Result<RunFunct
 
 #[handle_ecall]
 fn handle_init_enclave(_args: &InitEnclaveInput) -> Result<InitEnclaveOutput> {
-    info!("Enclave [Functional Test]: Initialized.");
-
-    env_logger::init();
-    let _ = backtrace::enable_backtrace(
-        concat!(include_str!("../../pkg_name"), ".enclave.signed.so"),
-        PrintFormat::Full,
-    );
-    mesatee_core::rpc::sgx::prelude();
+    mesatee_core::init_service(env!("CARGO_PKG_NAME"))?;
 
     Ok(InitEnclaveOutput::default())
 }


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@teaclave.apache.org
For additional commands, e-mail: commits-help@teaclave.apache.org