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/19 00:14:31 UTC

[incubator-teaclave] branch master updated: [config] Reorganize mesate_core/config and teaclave_config (#182)

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 a6ddc99  [config] Reorganize mesate_core/config and teaclave_config (#182)
a6ddc99 is described below

commit a6ddc99c10c29b253f7e4023f82fa615dcdd9bb1
Author: Mingshen Sun <bo...@mssun.me>
AuthorDate: Wed Dec 18 16:14:24 2019 -0800

    [config] Reorganize mesate_core/config and teaclave_config (#182)
---
 mesatee_core/src/config/external.rs | 13 ++++-----
 mesatee_core/src/config/internal.rs | 42 ++++++----------------------
 mesatee_core/src/config/mod.rs      | 55 +++++++++++++++++++++++++++----------
 mesatee_core/src/lib.rs             |  3 +-
 mesatee_core/src/rpc/sgx/mod.rs     | 39 --------------------------
 mesatee_core/src/rpc/sgx/ra.rs      |  8 +++---
 teaclave_config/src/lib.rs          | 52 +++++++++++++++++++++++------------
 7 files changed, 94 insertions(+), 118 deletions(-)

diff --git a/mesatee_core/src/config/external.rs b/mesatee_core/src/config/external.rs
index ff2f783..d13e4f2 100644
--- a/mesatee_core/src/config/external.rs
+++ b/mesatee_core/src/config/external.rs
@@ -16,39 +16,36 @@
 // under the License.
 
 use super::get_trusted_enclave_attr;
+use super::runtime_config;
 use super::ServiceConfig;
 use super::{InboundDesc, OutboundDesc, TargetDesc};
-use teaclave_config::runtime_config;
 
 pub struct External;
 impl External {
     pub fn tms() -> ServiceConfig {
         ServiceConfig::new(
-            runtime_config::config().api_endpoints.tms.listen_address,
+            runtime_config().api_endpoints.tms.listen_address,
             InboundDesc::External,
         )
     }
 
     pub fn fns() -> ServiceConfig {
         ServiceConfig::new(
-            runtime_config::config().api_endpoints.fns.listen_address,
+            runtime_config().api_endpoints.fns.listen_address,
             InboundDesc::External,
         )
     }
 
     pub fn tdfs() -> ServiceConfig {
         ServiceConfig::new(
-            runtime_config::config().api_endpoints.tdfs.listen_address,
+            runtime_config().api_endpoints.tdfs.listen_address,
             InboundDesc::External,
         )
     }
 
     pub fn target_fns() -> TargetDesc {
         TargetDesc::new(
-            runtime_config::config()
-                .api_endpoints
-                .fns
-                .advertised_address,
+            runtime_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 7b91e8b..f76eaec 100644
--- a/mesatee_core/src/config/internal.rs
+++ b/mesatee_core/src/config/internal.rs
@@ -16,90 +16,66 @@
 // under the License.
 
 use super::get_trusted_enclave_attr;
+use super::runtime_config;
 use super::InboundDesc;
 use super::OutboundDesc;
 use super::ServiceConfig;
 use super::TargetDesc;
-use teaclave_config::runtime_config;
 
 pub struct Internal;
 impl Internal {
     pub fn tms() -> ServiceConfig {
         ServiceConfig::new(
-            runtime_config::config()
-                .internal_endpoints
-                .tms
-                .listen_address,
+            runtime_config().internal_endpoints.tms.listen_address,
             InboundDesc::Sgx(get_trusted_enclave_attr(vec!["fns"])),
         )
     }
 
     pub fn kms() -> ServiceConfig {
         ServiceConfig::new(
-            runtime_config::config()
-                .internal_endpoints
-                .kms
-                .listen_address,
+            runtime_config().internal_endpoints.kms.listen_address,
             InboundDesc::Sgx(get_trusted_enclave_attr(vec!["fns", "tdfs"])),
         )
     }
 
     pub fn tdfs() -> ServiceConfig {
         ServiceConfig::new(
-            runtime_config::config()
-                .internal_endpoints
-                .tdfs
-                .listen_address,
+            runtime_config().internal_endpoints.tdfs.listen_address,
             InboundDesc::Sgx(get_trusted_enclave_attr(vec!["fns", "tms"])),
         )
     }
 
     pub fn acs() -> ServiceConfig {
         ServiceConfig::new(
-            runtime_config::config()
-                .internal_endpoints
-                .acs
-                .listen_address,
+            runtime_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::config()
-                .internal_endpoints
-                .tms
-                .advertised_address,
+            runtime_config().internal_endpoints.tms.advertised_address,
             OutboundDesc::Sgx(get_trusted_enclave_attr(vec!["tms"])),
         )
     }
 
     pub fn target_kms() -> TargetDesc {
         TargetDesc::new(
-            runtime_config::config()
-                .internal_endpoints
-                .kms
-                .advertised_address,
+            runtime_config().internal_endpoints.kms.advertised_address,
             OutboundDesc::Sgx(get_trusted_enclave_attr(vec!["kms"])),
         )
     }
 
     pub fn target_tdfs() -> TargetDesc {
         TargetDesc::new(
-            runtime_config::config()
-                .internal_endpoints
-                .tdfs
-                .advertised_address,
+            runtime_config().internal_endpoints.tdfs.advertised_address,
             OutboundDesc::Sgx(get_trusted_enclave_attr(vec!["tdfs"])),
         )
     }
 
     pub fn target_acs() -> TargetDesc {
         TargetDesc::new(
-            runtime_config::config()
-                .internal_endpoints
-                .acs
-                .advertised_address,
+            runtime_config().internal_endpoints.acs.advertised_address,
             OutboundDesc::Sgx(get_trusted_enclave_attr(vec!["acs"])),
         )
     }
diff --git a/mesatee_core/src/config/mod.rs b/mesatee_core/src/config/mod.rs
index 75bc97c..7d6bd8a 100644
--- a/mesatee_core/src/config/mod.rs
+++ b/mesatee_core/src/config/mod.rs
@@ -18,13 +18,20 @@
 // ip/port is dynamically dispatched for fns client.
 // we cannot use the &'static str in this struct.
 
-use crate::rpc::sgx::load_presigned_enclave_info;
 use crate::rpc::sgx::EnclaveAttr;
 use std::collections::HashMap;
 use std::net::SocketAddr;
 use std::prelude::v1::*;
+use teaclave_config::build_config::BUILD_CONFIG;
+use teaclave_config::runtime_config;
+use teaclave_config::runtime_config::RuntimeConfig;
 use teaclave_utils::EnclaveMeasurement;
 
+mod external;
+mod internal;
+pub use external::External;
+pub use internal::Internal;
+
 #[derive(Clone)]
 pub struct TargetDesc {
     pub addr: SocketAddr,
@@ -74,12 +81,43 @@ impl ServiceConfig {
 
 use lazy_static::lazy_static;
 
+fn load_presigned_enclave_info() -> HashMap<String, EnclaveMeasurement> {
+    if runtime_config().audit.auditor_signatures.len() < BUILD_CONFIG.auditor_public_keys.len() {
+        panic!("Number of auditor signatures is not enough for verification.")
+    }
+
+    if !teaclave_utils::verify_enclave_info(
+        &runtime_config().audit.enclave_info.as_bytes(),
+        BUILD_CONFIG.auditor_public_keys,
+        &runtime_config().audit.auditor_signatures,
+    ) {
+        panic!("Failed to verify the signatures of enclave info.");
+    }
+
+    teaclave_utils::load_enclave_info(&runtime_config().audit.enclave_info)
+}
+
 lazy_static! {
-    pub static ref ENCLAVE_IDENTITIES: HashMap<String, EnclaveMeasurement> =
+    static ref RUNTIME_CONFIG: Option<RuntimeConfig> =
+        RuntimeConfig::from_toml("runtime.config.toml");
+    static ref ENCLAVE_IDENTITIES: HashMap<String, EnclaveMeasurement> =
         load_presigned_enclave_info();
 }
 
-// let (test_mr_signer, test_mr_enclave) = ENCLAVE_IDENTITIES.get("functional_test").unwrap();
+pub fn is_runtime_config_initialized() -> bool {
+    RUNTIME_CONFIG.is_some()
+}
+
+pub fn runtime_config() -> &'static RuntimeConfig {
+    RUNTIME_CONFIG
+        .as_ref()
+        .expect("Invalid runtime config, should gracefully exit during enclave_init!")
+}
+
+fn universal_quote_check(quote: &crate::rpc::sgx::auth::SgxQuote) -> bool {
+    quote.status != crate::rpc::sgx::auth::SgxQuoteStatus::UnknownBadStatus
+}
+
 pub fn get_trusted_enclave_attr(service_names: Vec<&str>) -> EnclaveAttr {
     let measures = service_names
         .iter()
@@ -90,14 +128,3 @@ pub fn get_trusted_enclave_attr(service_names: Vec<&str>) -> EnclaveAttr {
         quote_checker: universal_quote_check,
     }
 }
-
-use crate::rpc::sgx::auth::*;
-
-pub(crate) fn universal_quote_check(quote: &SgxQuote) -> bool {
-    quote.status != SgxQuoteStatus::UnknownBadStatus
-}
-
-mod external;
-pub use external::External;
-mod internal;
-pub use internal::Internal;
diff --git a/mesatee_core/src/lib.rs b/mesatee_core/src/lib.rs
index 076dc05..66c8275 100644
--- a/mesatee_core/src/lib.rs
+++ b/mesatee_core/src/lib.rs
@@ -57,7 +57,6 @@ pub mod config;
 #[cfg(feature = "mesalock_sgx")]
 pub fn init_service(name: &str) -> Result<()> {
     use std::backtrace;
-    use teaclave_config::runtime_config;
 
     debug!("Enclave [{}]: Initializing...", name);
 
@@ -71,7 +70,7 @@ pub fn init_service(name: &str) -> Result<()> {
         error!("Cannot enable backtrace");
         return Err(Error::from(ErrorKind::ECallError));
     }
-    if !runtime_config::is_initialized() {
+    if !config::is_runtime_config_initialized() {
         error!("Runtime config is not initialized");
         return Err(Error::from(ErrorKind::ECallError));
     }
diff --git a/mesatee_core/src/rpc/sgx/mod.rs b/mesatee_core/src/rpc/sgx/mod.rs
index aad1b57..c9f4f0a 100644
--- a/mesatee_core/src/rpc/sgx/mod.rs
+++ b/mesatee_core/src/rpc/sgx/mod.rs
@@ -21,7 +21,6 @@
 use serde::{de::DeserializeOwned, Serialize};
 #[cfg(feature = "mesalock_sgx")]
 use sgx_types::c_int;
-use std::collections::HashMap;
 use std::hash::{Hash, Hasher};
 use std::io::{self, Read, Write};
 use std::marker::PhantomData;
@@ -35,8 +34,6 @@ use crate::rpc::{EnclaveService, RpcServer};
 use crate::rpc::RpcClient;
 use crate::Result;
 
-use teaclave_config::build_config::BUILD_CONFIG;
-use teaclave_config::runtime_config;
 use teaclave_utils;
 use teaclave_utils::EnclaveMeasurement;
 
@@ -60,42 +57,6 @@ pub fn prelude() {
     ra::get_ra_cert();
 }
 
-pub(crate) fn load_presigned_enclave_info() -> HashMap<String, EnclaveMeasurement> {
-    use teaclave_config::ConfigSource;
-
-    #[cfg(not(feature = "mesalock_sgx"))]
-    use std::fs;
-    #[cfg(feature = "mesalock_sgx")]
-    use std::untrusted::fs;
-
-    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::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::config().audit.auditor_signatures {
-        let signature =
-            fs::read(path).unwrap_or_else(|_| panic!("Cannot find signature file {:?}.", path));
-        signatures.push(signature);
-    }
-
-    if !teaclave_utils::verify_enclave_info(
-        enclave_info_content.as_bytes(),
-        BUILD_CONFIG.auditor_public_keys,
-        &signatures,
-    ) {
-        panic!("Failed to verify the signatures of enclave info.");
-    }
-
-    teaclave_utils::load_enclave_info(&enclave_info_content)
-}
-
 #[derive(Clone)]
 pub struct EnclaveAttr {
     pub measures: Vec<EnclaveMeasurement>,
diff --git a/mesatee_core/src/rpc/sgx/ra.rs b/mesatee_core/src/rpc/sgx/ra.rs
index 3bdfa77..e71162f 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;
+use crate::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::config().env.ias_key
+        SIGRL_SUFFIX, gid, DEV_HOSTNAME, &runtime_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::config().env.ias_key,
+                           &runtime_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::config().env.ias_spid)?;
+    let spid: sgx_spid_t = teaclave_utils::decode_spid(&runtime_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/teaclave_config/src/lib.rs b/teaclave_config/src/lib.rs
index bfbea76..91b166f 100644
--- a/teaclave_config/src/lib.rs
+++ b/teaclave_config/src/lib.rs
@@ -1,6 +1,7 @@
 // Use sgx_tstd to replace Rust's default std
 #![cfg_attr(feature = "mesalock_sgx", no_std)]
 #[cfg(feature = "mesalock_sgx")]
+#[macro_use]
 extern crate sgx_tstd as std;
 #[macro_use]
 extern crate log;
@@ -16,12 +17,14 @@ pub mod runtime_config {
     #[cfg(not(feature = "mesalock_sgx"))]
     use std::fs;
     #[cfg(feature = "mesalock_sgx")]
+    use std::prelude::v1::*;
+    #[cfg(feature = "mesalock_sgx")]
     use std::untrusted::fs;
 
-    use lazy_static::lazy_static;
     use serde_derive::Deserialize;
     use std::env;
     use std::net::SocketAddr;
+    use std::path::Path;
     use std::path::PathBuf;
     use std::string::String;
     use std::vec::Vec;
@@ -64,8 +67,14 @@ pub mod runtime_config {
 
     #[derive(Debug, Deserialize)]
     pub struct AuditConfig {
-        pub enclave_info: ConfigSource,
-        pub auditor_signatures: Vec<ConfigSource>,
+        #[serde(rename(deserialize = "enclave_info"))]
+        enclave_info_source: ConfigSource,
+        #[serde(rename(deserialize = "auditor_signatures"))]
+        auditor_signatures_source: Vec<ConfigSource>,
+        #[serde(skip_deserializing)]
+        pub enclave_info: String,
+        #[serde(skip_deserializing)]
+        pub auditor_signatures: Vec<Vec<u8>>,
     }
 
     #[derive(Debug, Deserialize)]
@@ -80,21 +89,10 @@ 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! {
-        static ref RUNTIME_CONFIG: Option<RuntimeConfig> = {
-            #[cfg(feature = "mesalock_sgx")]
+    impl RuntimeConfig {
+        pub fn from_toml<T: AsRef<Path>>(path: T) -> Option<Self> {
             use std::prelude::v1::*;
-            let contents = match fs::read_to_string("runtime.config.toml") {
+            let contents = match fs::read_to_string(path) {
                 Ok(c) => c,
                 Err(_) => {
                     error!("Something went wrong reading the runtime config file.");
@@ -108,6 +106,24 @@ pub mod runtime_config {
                     return None;
                 }
             };
+
+            config.audit.enclave_info = match &config.audit.enclave_info_source {
+                ConfigSource::Path(ref enclave_info_path) => fs::read_to_string(enclave_info_path)
+                    .unwrap_or_else(|_| {
+                        panic!("Cannot find enclave info at {:?}.", enclave_info_path)
+                    }),
+            };
+
+            let mut signatures: Vec<Vec<u8>> = vec![];
+            for source in &config.audit.auditor_signatures_source {
+                let signature = match source {
+                    ConfigSource::Path(ref path) => fs::read(path)
+                        .unwrap_or_else(|_| panic!("Cannot find signature file {:?}.", path)),
+                };
+                signatures.push(signature);
+            }
+            config.audit.auditor_signatures = signatures;
+
             if !cfg!(sgx_sim) {
                 let ias_spid = match env::var("IAS_SPID") {
                     Ok(e) => e.trim().to_string(),
@@ -132,7 +148,7 @@ pub mod runtime_config {
             }
 
             Some(config)
-        };
+        }
     }
 }
 


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