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/24 04:15:25 UTC

[incubator-teaclave] branch master updated: [core] Optimize RPC tls config (#190)

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 ead453f  [core] Optimize RPC tls config (#190)
ead453f is described below

commit ead453f37702ac2a27d0341de77d097aa9da57cd
Author: Zhaofeng Chen <zf...@apache.org>
AuthorDate: Mon Dec 23 20:15:15 2019 -0800

    [core] Optimize RPC tls config (#190)
---
 mesatee_core/src/rpc/sgx/client.rs | 109 ++++++++++++++++----------------
 mesatee_core/src/rpc/sgx/mod.rs    |  21 +------
 mesatee_core/src/rpc/sgx/ra.rs     | 124 ++++++++++++++++++++++---------------
 mesatee_core/src/rpc/sgx/server.rs | 122 ++++++++++++++----------------------
 teaclave_config/build.config.toml  |   3 -
 teaclave_config/config_gen/main.rs |   5 --
 6 files changed, 183 insertions(+), 201 deletions(-)

diff --git a/mesatee_core/src/rpc/sgx/client.rs b/mesatee_core/src/rpc/sgx/client.rs
index b762178..9e408e6 100644
--- a/mesatee_core/src/rpc/sgx/client.rs
+++ b/mesatee_core/src/rpc/sgx/client.rs
@@ -19,6 +19,8 @@ use std::sync::Arc;
 
 use crate::rpc::sgx::EnclaveAttr;
 
+#[cfg(feature = "mesalock_sgx")]
+use sgx_types::sgx_sha256_hash_t;
 #[cfg(not(feature = "mesalock_sgx"))]
 use std::sync::RwLock;
 #[cfg(feature = "mesalock_sgx")]
@@ -29,89 +31,92 @@ use std::collections::HashMap;
 use lazy_static::lazy_static;
 
 lazy_static! {
-    static ref CLIENTCONFIGCACHE: RwLock<HashMap<u64, Arc<rustls::ClientConfig>>> =
-        { RwLock::new(HashMap::new()) };
+    static ref CLIENT_CONFIG_CACHE: RwLock<ClientConfigCache> =
+        { RwLock::new(ClientConfigCache::default()) };
+}
+
+#[cfg(feature = "mesalock_sgx")]
+#[derive(Default)]
+struct ClientConfigCache {
+    private_key_sha256: sgx_sha256_hash_t,
+    target_configs: HashMap<Arc<EnclaveAttr>, Arc<rustls::ClientConfig>>,
 }
 
 #[cfg(not(feature = "mesalock_sgx"))]
-pub(crate) fn get_tls_config(server_attr: EnclaveAttr) -> Arc<rustls::ClientConfig> {
-    // We believe a client from untrusted side do not change his tls cert
-    // during single execution.
-    let cattr_hash: u64 = server_attr.calculate_hash();
-    if let Ok(cfg_cache) = CLIENTCONFIGCACHE.try_read() {
-        if let Some(cfg) = cfg_cache.get(&cattr_hash) {
+#[derive(Default)]
+struct ClientConfigCache {
+    target_configs: HashMap<Arc<EnclaveAttr>, Arc<rustls::ClientConfig>>,
+}
+
+#[cfg(feature = "mesalock_sgx")]
+pub(crate) fn get_tls_config(server_attr: Arc<EnclaveAttr>) -> Arc<rustls::ClientConfig> {
+    use crate::rpc::sgx::ra::get_ra_cert;
+
+    // To re-use existing TLS cache, we need to first check if the server has
+    // updated his RA cert
+    let cert_key = get_ra_cert();
+
+    // TODO: add wrapper function
+    if let Ok(cfg_cache) = CLIENT_CONFIG_CACHE.try_read() {
+        if let Some(cfg) = cfg_cache.target_configs.get(&server_attr) {
             return cfg.clone();
         }
     }
 
-    let mut client_cfg = rustls::ClientConfig::new();
+    let certs = vec![rustls::Certificate(cert_key.cert)];
+    let privkey = rustls::PrivateKey(cert_key.private_key);
 
+    let mut client_cfg = rustls::ClientConfig::new();
+    client_cfg.set_single_client_cert(certs, privkey);
     client_cfg
         .dangerous()
-        .set_certificate_verifier(Arc::new(server_attr));
+        .set_certificate_verifier(server_attr.clone());
     client_cfg.versions.clear();
     client_cfg.versions.push(rustls::ProtocolVersion::TLSv1_2);
 
     let final_arc = Arc::new(client_cfg);
 
-    if let Ok(mut cfg_cache) = CLIENTCONFIGCACHE.try_write() {
-        let _ = cfg_cache.insert(cattr_hash, final_arc.clone());
+    // TODO: add wrapper function
+    if let Ok(mut cfg_cache) = CLIENT_CONFIG_CACHE.try_write() {
+        if cfg_cache.private_key_sha256 != cert_key.private_key_sha256 {
+            *cfg_cache = ClientConfigCache {
+                private_key_sha256: cert_key.private_key_sha256,
+                target_configs: HashMap::new(),
+            }
+        }
+
+        let _ = cfg_cache
+            .target_configs
+            .insert(server_attr, final_arc.clone());
     }
 
     final_arc
 }
 
-#[cfg(feature = "mesalock_sgx")]
-pub(crate) fn get_tls_config(server_attr: EnclaveAttr) -> Arc<rustls::ClientConfig> {
-    use super::calc_hash;
-    use crate::rpc::sgx::ra::get_ra_cert;
-
-    // To re-use existing TLS cache, we need to first check if the server has
-    // updated his RA cert
-    let (cert_key, invalidate_cache) = get_ra_cert();
-
-    // calc_hash generates a u64 for (EnclaveAttr, CertKeyPair)
-    // According to the below code, as long as cert_key is unchanged,
-    // the `client_cfg` would not change, because it only take two
-    // parameters: EnclaveAttr, and CertKeyPair
-    let stat_hash: u64 = calc_hash(&server_attr, &cert_key);
-
-    if !invalidate_cache {
-        if let Ok(cfg_cache) = CLIENTCONFIGCACHE.try_read() {
-            if let Some(cfg) = cfg_cache.get(&stat_hash) {
-                return cfg.clone();
-            }
-        }
-    } else {
-        match CLIENTCONFIGCACHE.write() {
-            Ok(mut cfg_cache) => {
-                info!("CLIENTCONFIGCACHE invalidate all config cache!");
-                cfg_cache.clear();
-            }
-            Err(_) => {
-                // Poisoned
-                // I don't think we should panic here.
-                error!("CLIENTCONFIGCACHE invalidate cache failed!");
-            }
+#[cfg(not(feature = "mesalock_sgx"))]
+pub(crate) fn get_tls_config(server_attr: Arc<EnclaveAttr>) -> Arc<rustls::ClientConfig> {
+    // We believe a client from untrusted side do not change his tls cert
+    // during single execution.
+    if let Ok(cfg_cache) = CLIENT_CONFIG_CACHE.try_read() {
+        if let Some(cfg) = cfg_cache.target_configs.get(&server_attr) {
+            return cfg.clone();
         }
     }
 
-    let mut certs = std::vec::Vec::new();
-    certs.push(rustls::Certificate(cert_key.cert));
-    let privkey = rustls::PrivateKey(cert_key.private_key);
-
     let mut client_cfg = rustls::ClientConfig::new();
-    client_cfg.set_single_client_cert(certs, privkey);
+
     client_cfg
         .dangerous()
-        .set_certificate_verifier(Arc::new(server_attr));
+        .set_certificate_verifier(server_attr.clone());
     client_cfg.versions.clear();
     client_cfg.versions.push(rustls::ProtocolVersion::TLSv1_2);
 
     let final_arc = Arc::new(client_cfg);
 
-    if let Ok(mut cfg_cache) = CLIENTCONFIGCACHE.try_write() {
-        let _ = cfg_cache.insert(stat_hash, final_arc.clone());
+    if let Ok(mut cfg_cache) = CLIENT_CONFIG_CACHE.try_write() {
+        let _ = cfg_cache
+            .target_configs
+            .insert(server_attr, final_arc.clone());
     }
 
     final_arc
diff --git a/mesatee_core/src/rpc/sgx/mod.rs b/mesatee_core/src/rpc/sgx/mod.rs
index c9f4f0a..f6b45ff 100644
--- a/mesatee_core/src/rpc/sgx/mod.rs
+++ b/mesatee_core/src/rpc/sgx/mod.rs
@@ -25,6 +25,8 @@ use std::hash::{Hash, Hasher};
 use std::io::{self, Read, Write};
 use std::marker::PhantomData;
 use std::net::TcpStream;
+use std::sync::Arc;
+
 #[cfg(feature = "mesalock_sgx")]
 use std::prelude::v1::*;
 
@@ -82,24 +84,7 @@ impl Hash for EnclaveAttr {
     }
 }
 
-#[cfg(feature = "mesalock_sgx")]
-pub(crate) fn calc_hash(ea: &EnclaveAttr, crp: &ra::CertKeyPair) -> u64 {
-    use std::collections::hash_map::DefaultHasher;
-    let mut s = DefaultHasher::new();
-    ea.hash(&mut s);
-    crp.hash(&mut s);
-    s.finish()
-}
-
 impl EnclaveAttr {
-    #[cfg(not(feature = "mesalock_sgx"))]
-    fn calculate_hash(&self) -> u64 {
-        use std::collections::hash_map::DefaultHasher;
-        let mut s = DefaultHasher::new();
-        self.hash(&mut s);
-        s.finish()
-    }
-
     fn check_in_cert_quote(&self, cert_der: &[u8]) -> bool {
         if cfg!(sgx_sim) {
             return true;
@@ -279,7 +264,7 @@ where
 {
     type Config = PipeClientConfig;
     fn open(config: Self::Config) -> Result<Self> {
-        let rustls_client_cfg = client::get_tls_config(config.server_attr);
+        let rustls_client_cfg = client::get_tls_config(Arc::new(config.server_attr));
         let sess = rustls::ClientSession::new(&rustls_client_cfg, config.hostname.as_ref());
 
         Ok(PipeClient {
diff --git a/mesatee_core/src/rpc/sgx/ra.rs b/mesatee_core/src/rpc/sgx/ra.rs
index e71162f..bbe20a1 100644
--- a/mesatee_core/src/rpc/sgx/ra.rs
+++ b/mesatee_core/src/rpc/sgx/ra.rs
@@ -88,6 +88,36 @@ extern "C" {
 pub(crate) struct CertKeyPair {
     pub cert: Vec<u8>,
     pub private_key: Vec<u8>,
+    pub private_key_sha256: sgx_sha256_hash_t,
+}
+
+impl CertKeyPair {
+    fn new() -> Result<CertKeyPair> {
+        let cert_key_pair = mayfail! {
+            let ecc_handle = SgxEccHandle::new();
+            _open_result =<< ecc_handle.open();
+            (prv_k, pub_k) =<< ecc_handle.create_key_pair();
+            _close_result =<< ecc_handle.close();
+
+            AttnReport {
+                report: attn_report,
+                signature: sig,
+                certificate: cert,
+            } =<< create_attestation_report(&pub_k);
+            let payload = [attn_report, sig, cert].join("|");
+
+            let cert_der = gen_ecc_cert(payload, &prv_k, &pub_k);
+            let prv_key_der = convert_ec_private_to_der(&prv_k, &pub_k);
+            sha256 =<< rsgx_sha256_slice(&prv_key_der);
+            ret CertKeyPair {
+                cert: cert_der,
+                private_key: prv_key_der,
+                private_key_sha256: sha256
+            }
+        }?;
+
+        Ok(cert_key_pair)
+    }
 }
 
 #[derive(Clone)]
@@ -102,6 +132,7 @@ lazy_static! {
             cert_key: CertKeyPair {
                 cert: Vec::<u8>::new(),
                 private_key: Vec::<u8>::new(),
+                private_key_sha256: sgx_sha256_hash_t::default(),
             },
             gen_time: SystemTime::UNIX_EPOCH,
         })
@@ -481,7 +512,7 @@ fn is_tls_config_updated(gen_time: &SystemTime) -> bool {
     dur.is_ok() && dur.unwrap() < max_allowed_diff
 }
 
-pub(crate) fn get_ra_cert() -> (CertKeyPair, bool) {
+pub(crate) fn get_ra_cert() -> CertKeyPair {
     // Check if the global cert valid
     // If valid, use it directly
     // If invalid, update it before use.
@@ -494,7 +525,7 @@ pub(crate) fn get_ra_cert() -> (CertKeyPair, bool) {
         // Simple crash in that case.
         let cache = RACACHE.read().unwrap();
         if is_tls_config_updated(&cache.gen_time) {
-            return (cache.cert_key.clone(), false);
+            return cache.cert_key.clone();
         }
     }
 
@@ -508,11 +539,11 @@ pub(crate) fn get_ra_cert() -> (CertKeyPair, bool) {
     // No other reader/writer exists in this branch
     // Toc tou check
     if is_tls_config_updated(&cache.gen_time) {
-        return (cache.cert_key.clone(), false);
+        return cache.cert_key.clone();
     }
 
     // Do the renew
-    if renew_ra_cert(&mut cache).is_err() {
+    *cache = match renew_ra_cert() {
         // If RA renewal fails, we do not crash for the following reasons.
         // 1. Crashing the enclave causes most data to be lost permanently,
         //    since we do not have persistent key-value storage yet. On the
@@ -523,54 +554,43 @@ pub(crate) fn get_ra_cert() -> (CertKeyPair, bool) {
         // 3. The certificate has a 90 days valid duration. If RA keeps
         //    failing for 90 days, the enclave itself will not serve any
         //    client.
-        error!("RACACHE renewal failed");
-        panic!();
-    }
+        Err(e) => {
+            error!("RACACHE renewal failed: {:?}", e);
+            panic!()
+        }
+        Ok(new_cache) => new_cache,
+    };
 
-    (cache.cert_key.clone(), true)
+    cache.cert_key.clone()
 }
 
-fn renew_ra_cert(global_ra_cert: &mut RACache) -> Result<()> {
-    let ecc_handle = SgxEccHandle::new();
-
-    global_ra_cert.cert_key = mayfail! {
-        _open_result =<< ecc_handle.open();
-        (prv_k, pub_k) =<< ecc_handle.create_key_pair();
-        AttnReport {
-            report: attn_report,
-            signature: sig,
-            certificate: cert,
-        } =<< create_attestation_report(&pub_k);
-        let payload = attn_report + "|" + &sig + "|" + &cert;
-        let cert_key = gen_ecc_cert(payload, &prv_k, &pub_k, &ecc_handle);
-        _close_result =<< ecc_handle.close();
-        ret cert_key
-    }?;
-
-    global_ra_cert.gen_time = SystemTime::now();
+fn renew_ra_cert() -> Result<RACache> {
+    let cert_key = CertKeyPair::new()?;
+    let gen_time = SystemTime::now();
+    Ok(RACache { cert_key, gen_time })
+}
 
-    Ok(())
+fn make_ecc_public_key_bytes(pub_k: &sgx_ec256_public_t) -> Vec<u8> {
+    // Generate public key bytes
+    // The first must be 4, encoding for "uncompressed".
+    // Ref: https://github.com/briansmith/ring/blob/772fc080898c7b330fff99701c2a534580ebbf8c/src/ec/suite_b/public_key.rs#L30
+    let mut pub_key_bytes: Vec<u8> = vec![4];
+    pub_key_bytes.extend(pub_k.gx.iter().rev());
+    pub_key_bytes.extend(pub_k.gy.iter().rev());
+    pub_key_bytes
 }
 
 fn gen_ecc_cert(
     payload: String,
     prv_k: &sgx_ec256_private_t,
     pub_k: &sgx_ec256_public_t,
-    ecc_handle: &SgxEccHandle,
-) -> CertKeyPair {
+) -> Vec<u8> {
     const ISSUER: &str = "MesaTEE";
     const SUBJECT: &str = "MesaTEE";
 
     use super::cert::*;
 
-    // Generate public key bytes since both DER will use it
-    let mut pub_key_bytes: Vec<u8> = vec![4];
-    let mut pk_gx = pub_k.gx;
-    pk_gx.reverse();
-    let mut pk_gy = pub_k.gy;
-    pk_gy.reverse();
-    pub_key_bytes.extend_from_slice(&pk_gx);
-    pub_key_bytes.extend_from_slice(&pk_gy);
+    let pub_key_bytes = make_ecc_public_key_bytes(pub_k);
 
     // Generate Certificate DER
     let tbs_cert_der = yasna::construct_der(|writer| {
@@ -628,6 +648,10 @@ fn gen_ecc_cert(
 
     // There will be serious problems if this call fails. We might as well
     // panic in this case, thus unwrap()
+
+    let ecc_handle = SgxEccHandle::new();
+    ecc_handle.open().unwrap();
+
     let sig = ecc_handle
         .ecdsa_sign_slice(&tbs_cert_der.as_slice(), &prv_k)
         .unwrap();
@@ -647,7 +671,7 @@ fn gen_ecc_cert(
         });
     });
 
-    let cert_der = yasna::construct_der(|writer| {
+    yasna::construct_der(|writer| {
         writer.write_sequence(|writer| {
             writer.next().write_der(&tbs_cert_der.as_slice());
             CertSignAlgo::dump(writer.next(), cert_sign_algo);
@@ -655,10 +679,19 @@ fn gen_ecc_cert(
                 .next()
                 .write_bitvec(&bit_vec::BitVec::from_bytes(&sig_der.as_slice()));
         });
-    });
+    })
+}
+
+fn convert_ec_private_to_der(prv_k: &sgx_ec256_private_t, pub_k: &sgx_ec256_public_t) -> Vec<u8> {
+    // Generate public key bytes
+    let pub_key_bytes = make_ecc_public_key_bytes(pub_k);
+
+    // Generate private key bytes
+    let mut prv_key_bytes: Vec<u8> = vec![];
+    prv_key_bytes.extend(prv_k.r.iter().rev());
 
     // Generate Private Key DER
-    let key_der = yasna::construct_der(|writer| {
+    yasna::construct_der(|writer| {
         writer.write_sequence(|writer| {
             writer.next().write_u8(0);
             writer.next().write_sequence(|writer| {
@@ -676,9 +709,7 @@ fn gen_ecc_cert(
             let inner_key_der = yasna::construct_der(|writer| {
                 writer.write_sequence(|writer| {
                     writer.next().write_u8(1);
-                    let mut prv_k_r = prv_k.r;
-                    prv_k_r.reverse();
-                    writer.next().write_bytes(&prv_k_r);
+                    writer.next().write_bytes(&prv_key_bytes);
                     writer
                         .next()
                         .write_tagged(yasna::Tag::context(1), |writer| {
@@ -688,10 +719,5 @@ fn gen_ecc_cert(
             });
             writer.next().write_bytes(&inner_key_der);
         });
-    });
-
-    CertKeyPair {
-        cert: cert_der,
-        private_key: key_der,
-    }
+    })
 }
diff --git a/mesatee_core/src/rpc/sgx/server.rs b/mesatee_core/src/rpc/sgx/server.rs
index 19f25bd..be6c281 100644
--- a/mesatee_core/src/rpc/sgx/server.rs
+++ b/mesatee_core/src/rpc/sgx/server.rs
@@ -17,107 +17,81 @@
 
 use std::collections::HashMap;
 use std::sync::Arc;
-#[cfg(not(feature = "mesalock_sgx"))]
-use std::sync::RwLock;
-#[cfg(feature = "mesalock_sgx")]
-use std::sync::SgxRwLock as RwLock;
 use std::vec::Vec;
 
-use teaclave_config::build_config::BUILD_CONFIG;
-
 use crate::rpc::sgx::EnclaveAttr;
 use crate::Error;
 use crate::ErrorKind;
 use crate::Result;
 
+use sgx_types::sgx_sha256_hash_t;
+use std::sync::SgxRwLock as RwLock;
+
 use lazy_static::lazy_static;
 
 lazy_static! {
-    static ref SVRCONFIGCACHE: RwLock<HashMap<u64, Arc<rustls::ServerConfig>>> =
-        { RwLock::new(HashMap::new()) };
+    static ref SERVER_CONFIG_CACHE: RwLock<ServerConfigCache> =
+        { RwLock::new(ServerConfigCache::default()) };
+}
+
+#[derive(Default)]
+struct ServerConfigCache {
+    private_key_sha256: sgx_sha256_hash_t,
+    target_configs: HashMap<Arc<EnclaveAttr>, Arc<rustls::ServerConfig>>,
 }
 
 pub(crate) fn get_tls_config(
     client_attr: Option<EnclaveAttr>,
 ) -> Result<Arc<rustls::ServerConfig>> {
-    use super::calc_hash;
     use crate::rpc::sgx::ra::get_ra_cert;
 
     // To re-use existing TLS cache, we need to first check if the server has
     // updated his RA cert
-    let (cert_key, invalidate_cache) = get_ra_cert();
-
-    let attr_with_hash = client_attr.map(|attr| {
-        // This branch is for accepting socket from Enclaves
-        // calc_hash generates a u64 for (EnclaveAttr, CertKeyPair)
-        // According to the below code, as long as cert_key is unchanged,
-        // the `mutual_cfg` would not change, because it only take two
-        // parameters: EnclaveAttr, and CertKeyPair
-        let hash = calc_hash(&attr, &cert_key);
-        (attr, hash)
-    });
+    let cert_key = get_ra_cert();
+
+    let client_attr = match client_attr {
+        Some(attr) => Arc::new(attr),
+        None => {
+            let mut certs = Vec::new();
+            certs.push(rustls::Certificate(cert_key.cert));
+            let privkey = rustls::PrivateKey(cert_key.private_key);
+            // Build a default authenticator which allow every authenticated client
+            let authenticator = rustls::NoClientAuth::new();
+            let mut cfg = rustls::ServerConfig::new(authenticator);
+            cfg.set_single_cert(certs, privkey)
+                .map_err(|_| Error::from(ErrorKind::TLSError))?;
+            return Ok(Arc::new(cfg));
+        }
+    };
 
-    // invalidate_cache is true iff. ra is renewed in the above func call
-    // if ra cert is pulled from cache, then we can try to do it quickly.
-    if !invalidate_cache {
-        if let Some(&(_, new_hash)) = attr_with_hash.as_ref() {
-            if let Ok(cfg_cache) = SVRCONFIGCACHE.try_read() {
-                if let Some(cfg) = cfg_cache.get(&new_hash) {
-                    // Everything matched. Be quick!
-                    return Ok(cfg.clone());
-                }
-            }
-        };
-    } else {
-        // ra cert is updated. so we need to invalidate the cache
-        // THIS IS BLOCKING!
-        match SVRCONFIGCACHE.write() {
-            Ok(mut cfg_cache) => {
-                info!("SVRCONFIGCACHE invalidate all config cache!");
-                cfg_cache.clear();
-            }
-            Err(x) => {
-                // Poisoned
-                error!("SVRCONFIGCACHE invalidate cache failed {}!", x);
-            }
+    if let Ok(cfg_cache) = SERVER_CONFIG_CACHE.try_read() {
+        if let Some(cfg) = cfg_cache.target_configs.get(&client_attr) {
+            // Hit Cache. Be quick!
+            return Ok(cfg.clone());
         }
     }
 
-    let root_ca_bin = BUILD_CONFIG.sp_root_ca_cert;
-    let mut ca_reader = std::io::BufReader::new(&root_ca_bin[..]);
-    let mut rc_store = rustls::RootCertStore::empty();
-
-    // Build a root ca storage
-    rc_store
-        .add_pem_file(&mut ca_reader)
-        .map_err(|_| Error::from(ErrorKind::TLSError))?;
-
-    let mut certs = Vec::new();
-    certs.push(rustls::Certificate(cert_key.cert));
+    let certs = vec![rustls::Certificate(cert_key.cert)];
     let privkey = rustls::PrivateKey(cert_key.private_key);
 
-    if let Some((client_attr, stat_hash)) = attr_with_hash {
-        // We assigned Some(u64) to new_hash when client_attr is some.
-        // So in this branch, new_hash should always be Some(u64)
-        let mut mutual_cfg = rustls::ServerConfig::new(Arc::new(client_attr));
-        mutual_cfg
-            .set_single_cert(certs, privkey)
-            .map_err(|_| Error::from(ErrorKind::TLSError))?;
+    let mut server_cfg = rustls::ServerConfig::new(client_attr.clone());
+    server_cfg
+        .set_single_cert(certs, privkey)
+        .map_err(|_| Error::from(ErrorKind::TLSError))?;
 
-        let final_arc = Arc::new(mutual_cfg); // Create an Arc
+    let final_arc = Arc::new(server_cfg);
 
-        if let Ok(mut cfg_cache) = SVRCONFIGCACHE.try_write() {
-            let _ = cfg_cache.insert(stat_hash, final_arc.clone()); // Overwrite
+    if let Ok(mut cfg_cache) = SERVER_CONFIG_CACHE.try_write() {
+        if cfg_cache.private_key_sha256 != cert_key.private_key_sha256 {
+            *cfg_cache = ServerConfigCache {
+                private_key_sha256: cert_key.private_key_sha256,
+                target_configs: HashMap::new(),
+            }
         }
-
-        Ok(final_arc)
-    } else {
-        // Build a default authenticator which allow every authenticated client
-        let authenticator = rustls::NoClientAuth::new();
-        let mut cfg = rustls::ServerConfig::new(authenticator);
-        cfg.set_single_cert(certs, privkey)
-            .map_err(|_| Error::from(ErrorKind::TLSError))?;
-
-        Ok(Arc::new(cfg))
+        let _ = cfg_cache
+            .target_configs
+            .insert(client_attr, final_arc.clone()); // Overwrite
     }
+
+    Ok(final_arc)
 }
diff --git a/teaclave_config/build.config.toml b/teaclave_config/build.config.toml
index 7f9174d..de6a585 100644
--- a/teaclave_config/build.config.toml
+++ b/teaclave_config/build.config.toml
@@ -1,8 +1,5 @@
 # Teaclave Build Config
 
-# Service provider's root CA certificate to verify clients
-sp_root_ca_cert = { path = "../keys/sp_root_ca_cert.pem" }
-
 # Intel Attestation Service root CA certificate to verify attestation report
 ias_root_ca_cert = { path = "../keys/ias_root_ca_cert.pem" }
 
diff --git a/teaclave_config/config_gen/main.rs b/teaclave_config/config_gen/main.rs
index ecfbcdf..82ce9c9 100644
--- a/teaclave_config/config_gen/main.rs
+++ b/teaclave_config/config_gen/main.rs
@@ -9,7 +9,6 @@ use std::path::PathBuf;
 
 #[derive(Serialize, Deserialize)]
 struct BuildConfigToml {
-    sp_root_ca_cert: ConfigSource,
     ias_root_ca_cert: ConfigSource,
     auditor_public_keys: Vec<ConfigSource>,
     rpc_max_message_size: u32,
@@ -45,7 +44,6 @@ fn main() {
     let contents = fs::read_to_string(&args[1]).expect("Something went wrong reading the file");
     let config: BuildConfigToml = toml::from_str(&contents).expect("Failed to parse the config.");
 
-    let sp_root_ca_cert = display_config_source(&config.sp_root_ca_cert);
     let ias_root_ca_cert = display_config_source(&config.ias_root_ca_cert);
 
     let mut auditor_public_keys = String::new();
@@ -61,20 +59,17 @@ fn main() {
         r#"
     #[derive(Debug)]
     pub struct BuildConfig<'a> {{
-        pub sp_root_ca_cert: &'a [u8],
         pub ias_root_ca_cert: &'a [u8],
         pub auditor_public_keys: &'a [&'a [u8];{}],
         pub rpc_max_message_size: u64,
     }}
 
     pub static BUILD_CONFIG: BuildConfig<'static> = BuildConfig {{
-        sp_root_ca_cert: {},
         ias_root_ca_cert: {},
         auditor_public_keys: {},
         rpc_max_message_size: {},
     }};"#,
         config.auditor_public_keys.len(),
-        sp_root_ca_cert,
         ias_root_ca_cert,
         auditor_public_keys,
         config.rpc_max_message_size


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