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 2020/01/04 07:57:12 UTC

[incubator-teaclave] 04/04: Move common types in teaclave_utils to teaclave_types

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

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

commit 58a1b20a4e7621b44736839ec9e805a105e3d2f4
Author: Mingshen Sun <bo...@mssun.me>
AuthorDate: Fri Jan 3 23:41:58 2020 -0800

    Move common types in teaclave_utils to teaclave_types
---
 attestation/Cargo.toml                             |   2 +
 attestation/src/ias.rs                             |  18 ++-
 attestation/src/report.rs                          |   9 +-
 attestation/src/verifier.rs                        |   2 +-
 common/service_app_utils/src/lib.rs                |   4 +-
 common/service_config/Cargo.toml                   |   3 +-
 common/service_config/src/lib.rs                   |   2 +-
 ipc/src/channel/tee_dep.rs                         |   3 +
 rpc/src/transport.rs                               |   5 +-
 services/teaclave_frontend/sgx_app/src/main.rs     |   2 +-
 .../teaclave_frontend/sgx_trusted_lib/src/lib.rs   |   8 +-
 third_party/crates-io                              |   2 +-
 types/Cargo.toml                                   |   3 +
 types/src/lib.rs                                   |  42 +++++++
 utils/Cargo.toml                                   |   3 +-
 utils/src/lib.rs                                   | 133 ++-------------------
 16 files changed, 105 insertions(+), 136 deletions(-)

diff --git a/attestation/Cargo.toml b/attestation/Cargo.toml
index fd34410..add3bae 100644
--- a/attestation/Cargo.toml
+++ b/attestation/Cargo.toml
@@ -15,6 +15,7 @@ default = []
 mesalock_sgx = ["sgx_tstd", "sgx_tcrypto", "sgx_rand", "sgx_tse"]
 
 [dependencies]
+hex = "0.4.0"
 anyhow       = { version = "1.0.26" }
 base64       = { version = "0.10.1" }
 bit-vec      = { version = "0.6.1", default-features = false }
@@ -39,3 +40,4 @@ sgx_types   = { version = "1.1.0" }
 
 teaclave_config = { path = "../config" }
 teaclave_utils  = { path = "../utils" }
+teaclave_types = { path = "../types" }
diff --git a/attestation/src/ias.rs b/attestation/src/ias.rs
index cbfdcf2..2c8280f 100644
--- a/attestation/src/ias.rs
+++ b/attestation/src/ias.rs
@@ -26,7 +26,6 @@ use std::io::{Read, Write};
 use std::net::TcpStream;
 use std::prelude::v1::*;
 use std::sync::Arc;
-use teaclave_utils;
 
 extern "C" {
     fn ocall_sgx_get_ias_socket(p_retval: *mut i32) -> sgx_status_t;
@@ -186,7 +185,7 @@ impl IasClient {
             let cert_str = header_map
                 .get("X-IASReport-Signing-Certificate")
                 .ok_or_else(|| Error::new(AttestationError::IasError))?;
-            let decoded_cert = teaclave_utils::percent_decode(cert_str)?;
+            let decoded_cert = percent_decode(cert_str)?;
             // We should get two concatenated PEM files at this step.
             let cert_content: Vec<&str> = decoded_cert.split("-----").collect();
             cert_content[2].to_string()
@@ -213,3 +212,18 @@ impl IasClient {
         header_map
     }
 }
+
+fn percent_decode(orig: &str) -> Result<String> {
+    let orig = orig.replace("%0A", "");
+    let v: Vec<&str> = orig.split('%').collect();
+    let mut ret = String::new();
+    ret.push_str(v[0]);
+    if v.len() > 1 {
+        for s in v[1..].iter() {
+            let digit = u8::from_str_radix(&s[0..2], 16)?;
+            ret.push(digit as char);
+            ret.push_str(&s[2..]);
+        }
+    }
+    Ok(ret)
+}
diff --git a/attestation/src/report.rs b/attestation/src/report.rs
index a4a2689..af9bece 100644
--- a/attestation/src/report.rs
+++ b/attestation/src/report.rs
@@ -19,6 +19,7 @@ use crate::ias::IasClient;
 use crate::AttestationError;
 use anyhow::Error;
 use anyhow::Result;
+use hex;
 use log::debug;
 use sgx_rand::os::SgxRng;
 use sgx_rand::Rng;
@@ -27,7 +28,6 @@ use sgx_tse::{rsgx_create_report, rsgx_verify_report};
 use sgx_types::sgx_ec256_public_t;
 use sgx_types::*;
 use std::prelude::v1::*;
-use teaclave_utils;
 
 extern "C" {
     fn ocall_sgx_init_quote(
@@ -116,7 +116,7 @@ impl IasReport {
         sigrl: &[u8],
         report: sgx_report_t,
         target_info: sgx_target_info_t,
-        ias_spid: &str,
+        ias_spid_str: &str,
     ) -> Result<Vec<u8>> {
         let mut rt: sgx_status_t = sgx_status_t::SGX_ERROR_UNEXPECTED;
         let (p_sigrl, sigrl_len) = if sigrl.is_empty() {
@@ -140,7 +140,10 @@ impl IasReport {
         let mut qe_report = sgx_report_t::default();
 
         let quote_type = sgx_quote_sign_type_t::SGX_LINKABLE_SIGNATURE;
-        let spid: sgx_spid_t = teaclave_utils::decode_spid(ias_spid)?;
+
+        let mut spid = sgx_types::sgx_spid_t::default();
+        let hex = hex::decode(ias_spid_str)?;
+        spid.id.copy_from_slice(&hex[..16]);
 
         let mut quote = vec![0; quote_len as usize];
 
diff --git a/attestation/src/verifier.rs b/attestation/src/verifier.rs
index 591dfa4..4d0561e 100644
--- a/attestation/src/verifier.rs
+++ b/attestation/src/verifier.rs
@@ -19,7 +19,7 @@ use crate::quote::SgxQuote;
 use std::hash::{Hash, Hasher};
 use std::vec::Vec;
 use teaclave_config::build_config::BUILD_CONFIG;
-use teaclave_utils::EnclaveMeasurement;
+use teaclave_types::EnclaveMeasurement;
 
 #[derive(Clone)]
 pub struct EnclaveAttr {
diff --git a/common/service_app_utils/src/lib.rs b/common/service_app_utils/src/lib.rs
index 7e21c17..045fcfa 100644
--- a/common/service_app_utils/src/lib.rs
+++ b/common/service_app_utils/src/lib.rs
@@ -2,10 +2,10 @@ use log::{error, info};
 use std::sync::Arc;
 use teaclave_binder::TeeBinder;
 
-pub fn init_tee() -> anyhow::Result<std::sync::Arc<TeeBinder>> {
+pub fn init_tee(enclave_name: &str) -> anyhow::Result<std::sync::Arc<TeeBinder>> {
     env_logger::init();
 
-    let tee = match TeeBinder::new(env!("CARGO_PKG_NAME"), 1) {
+    let tee = match TeeBinder::new(enclave_name, 1) {
         Ok(r) => {
             info!("Init TEE Successfully!");
             r
diff --git a/common/service_config/Cargo.toml b/common/service_config/Cargo.toml
index 98fae37..251231b 100644
--- a/common/service_config/Cargo.toml
+++ b/common/service_config/Cargo.toml
@@ -24,4 +24,5 @@ sgx_tstd  = { version = "1.1.0", features = ["net", "backtrace"], optional = tru
 
 teaclave_config = { path = "../../config" }
 teaclave_attestation = { path = "../../attestation" }
-teaclave_utils = { path = "../../utils" }
\ No newline at end of file
+teaclave_utils = { path = "../../utils" }
+teaclave_types = { path = "../../types" }
\ No newline at end of file
diff --git a/common/service_config/src/lib.rs b/common/service_config/src/lib.rs
index 7ee8c91..b090782 100644
--- a/common/service_config/src/lib.rs
+++ b/common/service_config/src/lib.rs
@@ -31,7 +31,7 @@ use teaclave_attestation::verifier::EnclaveAttr;
 use teaclave_config::build_config::BUILD_CONFIG;
 use teaclave_config::runtime_config;
 use teaclave_config::runtime_config::RuntimeConfig;
-use teaclave_utils::EnclaveMeasurement;
+use teaclave_types::EnclaveMeasurement;
 
 mod external;
 mod internal;
diff --git a/ipc/src/channel/tee_dep.rs b/ipc/src/channel/tee_dep.rs
index 6a04317..9e8ef86 100644
--- a/ipc/src/channel/tee_dep.rs
+++ b/ipc/src/channel/tee_dep.rs
@@ -37,10 +37,13 @@ impl IpcReceiver for ECallReceiver {
         V: serde::Serialize,
         X: IpcService<U, V>,
     {
+        debug!("from_slice");
         let input: U = serde_json::from_slice(&input_payload)?;
 
+        debug!("handle_invoke");
         let response = x.handle_invoke(input)?;
 
+        debug!("to_vec");
         let response_payload = serde_json::to_vec(&response)?;
 
         Ok(response_payload)
diff --git a/rpc/src/transport.rs b/rpc/src/transport.rs
index 22596a9..f47b47c 100644
--- a/rpc/src/transport.rs
+++ b/rpc/src/transport.rs
@@ -85,13 +85,16 @@ mod sgx_trusted_tls {
             V: for<'de> Deserialize<'de> + std::fmt::Debug,
             X: TeaclaveService<V, U>,
         {
+            let mut protocol = protocol::JsonProtocol::new(self);
+
             loop {
-                let mut protocol = protocol::JsonProtocol::new(self);
+                debug!("read_message");
                 let request: V = protocol.read_message()?;
                 debug!("request: {:?}", request);
                 let response: U = service.handle_request(request)?;
                 debug!("response: {:?}", response);
                 protocol.write_message(response)?;
+                debug!("write_messagge done");
             }
         }
     }
diff --git a/services/teaclave_frontend/sgx_app/src/main.rs b/services/teaclave_frontend/sgx_app/src/main.rs
index 8a9eebb..8fd63ac 100644
--- a/services/teaclave_frontend/sgx_app/src/main.rs
+++ b/services/teaclave_frontend/sgx_app/src/main.rs
@@ -36,7 +36,7 @@ use teaclave_service_app_utils;
 use teaclave_service_config;
 
 fn main() -> anyhow::Result<()> {
-    let tee = teaclave_service_app_utils::init_tee()?;
+    let tee = teaclave_service_app_utils::init_tee(env!("CARGO_PKG_NAME"))?;
     run(tee)?;
 
     Ok(())
diff --git a/services/teaclave_frontend/sgx_trusted_lib/src/lib.rs b/services/teaclave_frontend/sgx_trusted_lib/src/lib.rs
index 6270e33..56af6ef 100644
--- a/services/teaclave_frontend/sgx_trusted_lib/src/lib.rs
+++ b/services/teaclave_frontend/sgx_trusted_lib/src/lib.rs
@@ -93,7 +93,12 @@ fn handle_start_service(_args: &StartServiceInput) -> Result<StartServiceOutput>
             proto::TeaclaveFrontendResponse,
             proto::TeaclaveFrontendRequest,
         >::new_with_config(stream, &rc_config);
-        server.start(service::TeaclaveFrontendService)?;
+        match server.start(service::TeaclaveFrontendService) {
+            Ok(_) => (),
+            Err(e) => {
+                error!("Service exit, error: {}.", e);
+            }
+        }
     }
 }
 
@@ -104,6 +109,7 @@ fn handle_serve_connection(args: &ServeConnectionInput) -> Result<ServeConnectio
     let sender = &FD_QUEUE.sender;
     sender.send(args.socket_fd).unwrap();
 
+    debug!("handle_serve_connection success exit");
     Ok(ServeConnectionOutput::default())
 }
 
diff --git a/third_party/crates-io b/third_party/crates-io
index 80cc441..da708bf 160000
--- a/third_party/crates-io
+++ b/third_party/crates-io
@@ -1 +1 @@
-Subproject commit 80cc441d07d8f89f9f57fe32a72d49e418d2705e
+Subproject commit da708bf401034b70606de4235ef41bbb10056850
diff --git a/types/Cargo.toml b/types/Cargo.toml
index 6cb4d4d..83e1b12 100644
--- a/types/Cargo.toml
+++ b/types/Cargo.toml
@@ -14,3 +14,6 @@ mesalock_sgx = ["sgx_tstd"]
 sgx_tstd  = { version = "1.1.0", features = ["net", "backtrace"], optional = true }
 anyhow    = { version = "1.0.26" }
 sgx_types = "1.1.0"
+hex = "0.4.0"
+serde        = { version = "1.0.92" }
+serde_derive = { version = "1.0.92" }
diff --git a/types/src/lib.rs b/types/src/lib.rs
index 73e80f6..69faf72 100644
--- a/types/src/lib.rs
+++ b/types/src/lib.rs
@@ -2,6 +2,13 @@
 #[cfg(feature = "mesalock_sgx")]
 extern crate sgx_tstd as std;
 
+#[cfg(feature = "mesalock_sgx")]
+use std::prelude::v1::*;
+
+use hex;
+use serde::Deserializer;
+use serde_derive::Deserialize;
+
 /// Status for Ecall
 #[repr(C)]
 #[derive(Debug)]
@@ -26,3 +33,38 @@ impl EnclaveStatus {
         self.0 == 0x0000_000c
     }
 }
+
+pub type SgxMeasurement = [u8; sgx_types::SGX_HASH_SIZE];
+
+#[derive(Debug, Deserialize, Copy, Clone, Eq, PartialEq)]
+pub struct EnclaveMeasurement {
+    #[serde(deserialize_with = "from_hex")]
+    pub mr_signer: SgxMeasurement,
+    #[serde(deserialize_with = "from_hex")]
+    pub mr_enclave: SgxMeasurement,
+}
+
+impl EnclaveMeasurement {
+    pub fn new(mr_enclave: SgxMeasurement, mr_signer: SgxMeasurement) -> Self {
+        Self {
+            mr_enclave,
+            mr_signer,
+        }
+    }
+}
+
+/// Deserializes a hex string to a `SgxMeasurement` (i.e., [0; 32]).
+pub fn from_hex<'de, D>(deserializer: D) -> Result<SgxMeasurement, D::Error>
+where
+    D: Deserializer<'de>,
+{
+    use serde::de::Error;
+    use serde::Deserialize;
+    String::deserialize(deserializer).and_then(|string| {
+        let v = hex::decode(&string).map_err(|_| Error::custom("ParseError"))?;
+        let mut array = [0; sgx_types::SGX_HASH_SIZE];
+        let bytes = &v[..array.len()]; // panics if not enough data
+        array.copy_from_slice(bytes);
+        Ok(array)
+    })
+}
diff --git a/utils/Cargo.toml b/utils/Cargo.toml
index 64206c6..ee076e9 100644
--- a/utils/Cargo.toml
+++ b/utils/Cargo.toml
@@ -8,7 +8,7 @@ edition = "2018"
 
 [features]
 default = []
-mesalock_sgx = ["sgx_tstd"]
+mesalock_sgx = ["sgx_tstd", "teaclave_types/mesalock_sgx"]
 
 [dependencies]
 ring         = { version = "0.16.5" }
@@ -17,3 +17,4 @@ serde_derive = { version = "1.0.92" }
 sgx_tstd     = { version = "1.1.0", optional = true }
 sgx_types    = { version = "1.1.0" }
 toml         = { version = "0.5.3" }
+teaclave_types = { path = "../types" }
diff --git a/utils/src/lib.rs b/utils/src/lib.rs
index a7f774c..0ff541e 100644
--- a/utils/src/lib.rs
+++ b/utils/src/lib.rs
@@ -4,127 +4,9 @@ extern crate sgx_tstd as std;
 #[cfg(feature = "mesalock_sgx")]
 use std::prelude::v1::*;
 
-use serde::Deserializer;
 use serde_derive::Deserialize;
 use std::collections::HashMap;
-
-use std::error::Error;
-use std::fmt;
-
-type Result<T> = std::result::Result<T, UtilsError>;
-use sgx_types::SGX_HASH_SIZE;
-
-pub type SgxMeasurement = [u8; SGX_HASH_SIZE];
-
-#[derive(Debug)]
-pub enum UtilsError {
-    ParseError,
-}
-
-impl fmt::Display for UtilsError {
-    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
-        write!(f, "Teaclave utils error")
-    }
-}
-
-impl Error for UtilsError {
-    fn description(&self) -> &str {
-        "Teaclave utils error"
-    }
-}
-
-fn decode_hex_digit(digit: char) -> Result<u8> {
-    match digit {
-        '0'..='9' => Ok(digit as u8 - b'0'),
-        'a'..='f' => Ok(digit as u8 - b'a' + 10),
-        'A'..='F' => Ok(digit as u8 - b'A' + 10),
-        _ => Err(UtilsError::ParseError),
-    }
-}
-
-fn decode_hex(hex: &str) -> Result<Vec<u8>> {
-    let mut r: Vec<u8> = Vec::new();
-    let mut chars = hex.chars().enumerate();
-    loop {
-        let (_, first) = match chars.next() {
-            None => break,
-            Some(elt) => elt,
-        };
-        if first == ' ' {
-            continue;
-        }
-        let (_, second) = chars.next().ok_or_else(|| UtilsError::ParseError)?;
-        r.push((decode_hex_digit(first)? << 4) | decode_hex_digit(second)?);
-    }
-    Ok(r)
-}
-
-pub fn decode_spid(hex: &str) -> Result<sgx_types::sgx_spid_t> {
-    let mut spid = sgx_types::sgx_spid_t::default();
-    let hex = hex.trim();
-
-    if hex.len() < 16 * 2 {
-        return Err(UtilsError::ParseError);
-    }
-
-    let decoded_vec = decode_hex(hex)?;
-
-    spid.id.copy_from_slice(&decoded_vec[..16]);
-
-    Ok(spid)
-}
-
-pub fn percent_decode(orig: &str) -> Result<String> {
-    let orig = orig.replace("%0A", "");
-    let v: Vec<&str> = orig.split('%').collect();
-    let mut ret = String::new();
-    ret.push_str(v[0]);
-    if v.len() > 1 {
-        for s in v[1..].iter() {
-            let digit = u8::from_str_radix(&s[0..2], 16).map_err(|_| UtilsError::ParseError)?;
-            ret.push(digit as char);
-            ret.push_str(&s[2..]);
-        }
-    }
-    Ok(ret)
-}
-
-/// Deserializes a hex string to a `SgxMeasurement` (i.e., [0; 32]).
-pub fn from_hex<'de, D>(deserializer: D) -> std::result::Result<SgxMeasurement, D::Error>
-where
-    D: Deserializer<'de>,
-{
-    use serde::de::Error;
-    use serde::Deserialize;
-    String::deserialize(deserializer).and_then(|string| {
-        let v = decode_hex(&string).map_err(|_| Error::custom("ParseError"))?;
-        let mut array = [0; SGX_HASH_SIZE];
-        let bytes = &v[..array.len()]; // panics if not enough data
-        array.copy_from_slice(bytes);
-        Ok(array)
-    })
-}
-
-#[derive(Debug, Deserialize)]
-#[serde(transparent)]
-struct EnclaveInfoToml(HashMap<String, EnclaveMeasurement>);
-
-#[derive(Debug, Deserialize, Copy, Clone, Eq, PartialEq)]
-pub struct EnclaveMeasurement {
-    #[serde(deserialize_with = "from_hex")]
-    pub mr_signer: SgxMeasurement,
-    #[serde(deserialize_with = "from_hex")]
-    pub mr_enclave: SgxMeasurement,
-}
-
-impl EnclaveMeasurement {
-    pub fn new(mr_enclave: SgxMeasurement, mr_signer: SgxMeasurement) -> Self {
-        Self {
-            mr_enclave,
-            mr_signer,
-        }
-    }
-}
+use teaclave_types;
 
 pub fn verify_enclave_info<T, U>(enclave_info: &[u8], public_keys: &[T], signatures: &[U]) -> bool
 where
@@ -151,12 +33,21 @@ where
     true
 }
 
-pub fn load_enclave_info(content: &str) -> std::collections::HashMap<String, EnclaveMeasurement> {
+#[derive(Debug, Deserialize)]
+#[serde(transparent)]
+struct EnclaveInfoToml(HashMap<String, teaclave_types::EnclaveMeasurement>);
+
+pub fn load_enclave_info(
+    content: &str,
+) -> std::collections::HashMap<String, teaclave_types::EnclaveMeasurement> {
     let config: EnclaveInfoToml =
         toml::from_str(&content).expect("Content not correct, unable to load enclave info.");
     let mut info_map = std::collections::HashMap::new();
     for (k, v) in config.0 {
-        info_map.insert(k, EnclaveMeasurement::new(v.mr_enclave, v.mr_signer));
+        info_map.insert(
+            k,
+            teaclave_types::EnclaveMeasurement::new(v.mr_enclave, v.mr_signer),
+        );
     }
 
     info_map


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