removed some of the unwraps; more testing required

This commit is contained in:
ghe0 2025-03-21 03:49:16 +02:00
parent 422e04a538
commit a3d604845b
Signed by: ghe0
GPG Key ID: 451028EE56A0FBB4
4 changed files with 72 additions and 64 deletions

@ -17,7 +17,7 @@ pub struct AccountData {
wallet_address: String, wallet_address: String,
wallet_path: String, wallet_path: String,
hratls_pubkey: String, hratls_pubkey: String,
hratls_path: String, hratls_key_path: String,
mrsigner: String, mrsigner: String,
mrsigner_key_path: String, mrsigner_key_path: String,
} }
@ -43,6 +43,9 @@ impl super::HumanOutput for AccountData {
println!("Hop on discord to get an airdrop: https://discord.gg/DcfYczAMtD \n") println!("Hop on discord to get an airdrop: https://discord.gg/DcfYczAMtD \n")
} }
} }
if !self.mrsigner.is_empty() {
println!("The MRSIGNER for apps is: {}", self.mrsigner);
}
} }
} }
@ -59,13 +62,19 @@ pub enum Error {
#[error("Parsing of the yaml config file failed: {0}")] #[error("Parsing of the yaml config file failed: {0}")]
YamlFormat(#[from] serde_yaml::Error), YamlFormat(#[from] serde_yaml::Error),
#[error("The private key of the DeTEE account got corrupted.")] #[error("The private key of the DeTEE account got corrupted.")]
CorruptedKey, CorruptedWalletKey,
#[error("The private ED25519 key used for HRATLS got corrupted: {0}")]
CorruptedHratlsKey(String),
#[error("The MRSIGNER key (used for signing apps) got corrupted: {0}")]
CorruptedMrSigner(String),
#[error("Failed to generate key using openssl: {0}")] #[error("Failed to generate key using openssl: {0}")]
Openssl(String), Openssl(String),
#[error{"Failed to retrive/download the artefact"}] #[error{"Failed to retrive/download the artefact"}]
ArtefactError, ArtefactError,
#[error{"SSH key not defined. Run `detee-cli account` for more info."}] #[error{"SSH key not defined. Run `detee-cli account` for more info."}]
SshKeyNoDefined, SshKeyNoDefined,
#[error{"RSA Error: {0}"}]
RSAError(#[from] openssl::error::ErrorStack),
} }
impl Config { impl Config {
@ -227,9 +236,9 @@ impl Config {
Ok(SigningKey::from_bytes( Ok(SigningKey::from_bytes(
&bs58::decode(std::fs::read_to_string(Self::detee_wallet_key_path()?)?.trim()) &bs58::decode(std::fs::read_to_string(Self::detee_wallet_key_path()?)?.trim())
.into_vec() .into_vec()
.map_err(|_| Error::CorruptedKey)? .map_err(|_| Error::CorruptedWalletKey)?
.try_into() .try_into()
.map_err(|_| Error::CorruptedKey)?, .map_err(|_| Error::CorruptedWalletKey)?,
)) ))
} }
@ -345,103 +354,100 @@ impl Config {
Err(_) => log::error!("This error should never happen. Please report this bug."), Err(_) => log::error!("This error should never happen. Please report this bug."),
} }
// TODO: Also populate these fields: match Self::mrsigner_key_path() {
// hratls_pubkey: String, Ok(path) => {
// hratls_path: String, account_data.mrsigner_key_path = path;
// mrsigner: String, match Self::get_mrsigner() {
// signing_key_path: String, Ok(mrsigner) => account_data.mrsigner = mrsigner,
Err(e) => {
log::error!("Could not load MRSIGNER key: {e}")
}
}
}
Err(e) => log::error!("Please report this bug. Could not get MRSIGNER path: {e}"),
}
match Self::hratls_key_path() {
Ok(path) => {
account_data.hratls_key_path = path;
match Self::get_hratls_pubkey_hex() {
Ok(pubkey) => account_data.hratls_pubkey = pubkey,
Err(e) => {
log::error!("Could not load HRATLS key: {e}")
}
}
}
Err(e) => log::error!("Please report this bug. Could not get HRATLS key path: {e}"),
}
account_data account_data
} }
} }
impl Config { impl Config {
pub fn get_hratls_private_key() -> String { pub fn get_hratls_private_key() -> Result<String, Error> {
std::fs::read_to_string(Self::hratls_private_key_path()) let private_key_path = Self::hratls_key_path()?;
.unwrap_or_else(|_| Self::create_hratls_key().expect("Failed to create HRATLS key"))
}
fn create_hratls_key() -> Result<String, Box<dyn std::error::Error>> {
let private_key_path = Self::hratls_private_key_path();
if Path::new(&private_key_path).exists() { if Path::new(&private_key_path).exists() {
log::debug!("Found HRaTLS private key at {private_key_path}"); log::debug!("Found HRaTLS private key at {private_key_path}");
return Err("Key already exists.".into()); return Ok(std::fs::read_to_string(private_key_path)
.map_err(|e| Error::CorruptedHratlsKey(e.to_string()))?);
} }
let key = PKey::generate_ed25519()?; let key = PKey::generate_ed25519()?;
let mut key_file = File::create(private_key_path)?; let mut key_file = File::create(private_key_path)?;
let pem_pkcs8 = key.private_key_to_pem_pkcs8()?; let pem_pkcs8 = key.private_key_to_pem_pkcs8()?;
key_file.write_all(&pem_pkcs8)?; key_file.write_all(&pem_pkcs8)?;
Ok(String::from_utf8(pem_pkcs8)?) Ok(String::from_utf8(pem_pkcs8).map_err(|e| Error::CorruptedHratlsKey(e.to_string()))?)
} }
pub fn get_hratls_pubkey_hex() -> String { pub fn get_hratls_pubkey_hex() -> Result<String, Error> {
let private_key_pem_str = Self::get_hratls_private_key(); let private_key_pem_str = Self::get_hratls_private_key()?;
let private_key = PKey::private_key_from_pem(private_key_pem_str.as_ref()).unwrap(); let private_key = PKey::private_key_from_pem(private_key_pem_str.as_ref())?;
let pubkey = private_key.raw_public_key().unwrap(); let pubkey = private_key.raw_public_key()?;
pubkey.iter().fold(String::new(), |acc, x| acc + &format!("{:02X?}", x)) Ok(pubkey.iter().fold(String::new(), |acc, x| acc + &format!("{:02X?}", x)))
} }
pub fn hratls_private_key_path() -> String { pub fn hratls_key_path() -> Result<String, Error> {
Self::path_dir().unwrap() + ("/hratls_private_key.pem") Ok(Self::path_dir()? + ("/hratls_private_key.pem"))
} }
} }
impl Config { impl Config {
pub fn get_mrsigner() -> String { pub fn get_mrsigner() -> Result<String, Error> {
let mut signing_key_mod = Self::get_mrsigner_rsa_key().n().to_vec(); let mut signing_key_mod = Self::get_mrsigner_rsa_key()?.n().to_vec();
signing_key_mod.reverse(); // make it little endian signing_key_mod.reverse(); // make it little endian
// TODO: double check if hasher can actually fail
let mut hasher = Hasher::new(MessageDigest::sha256()).unwrap(); let mut hasher = Hasher::new(MessageDigest::sha256()).unwrap();
hasher.update(&signing_key_mod).unwrap(); hasher.update(&signing_key_mod).unwrap();
let mr_signer_raw = hasher.finish().unwrap(); let mr_signer_raw = hasher.finish().unwrap();
let mut mr_signer = [0u8; 32]; let mut mr_signer = [0u8; 32];
mr_signer.copy_from_slice(&mr_signer_raw[..32]); mr_signer.copy_from_slice(&mr_signer_raw[..32]);
mr_signer.iter().fold(String::new(), |acc, x| acc + &format!("{:02X?}", x)) Ok(mr_signer.iter().fold(String::new(), |acc, x| acc + &format!("{:02X?}", x)))
} }
fn get_mrsigner_rsa_key() -> Rsa<Private> { fn get_mrsigner_rsa_key() -> Result<Rsa<Private>, Error> {
let signing_key_pem_str = std::fs::read_to_string(Self::mrsigner_key_path()) let signing_key_pem_str = Self::create_mrsigner_rsa_key()?;
.unwrap_or_else(|_| { Ok(Rsa::private_key_from_pem(signing_key_pem_str.as_ref())
Self::create_mrsigner_rsa_key().expect("Failed to create enclave signing key") .map_err(|e| Error::CorruptedMrSigner(e.to_string()))?)
});
Rsa::private_key_from_pem(signing_key_pem_str.as_ref()).unwrap()
} }
fn create_mrsigner_rsa_key() -> Result<String, Box<dyn std::error::Error>> { fn create_mrsigner_rsa_key() -> Result<String, Error> {
let signing_key_path = Self::mrsigner_key_path(); let signing_key_path = Self::mrsigner_key_path()?;
if Path::new(&signing_key_path).exists() { if Path::new(&signing_key_path).exists() {
log::debug!("Found signing_key at {signing_key_path}"); log::debug!("Found signing_key at {signing_key_path}");
return Err("Key already exists.".into()); return Ok(std::fs::read_to_string(signing_key_path)
.map_err(|e| Error::CorruptedMrSigner(e.to_string()))?);
} }
let key = Rsa::generate_with_e(3072, BigNum::from_u32(3)?.as_ref())?; let key = Rsa::generate_with_e(3072, BigNum::from_u32(3)?.as_ref())?;
let mut key_file = File::create(signing_key_path)?; let mut key_file = File::create(signing_key_path)?;
let pem_pkcs8 = key.private_key_to_pem()?; let pem_pkcs8 = key.private_key_to_pem()?;
key_file.write_all(&pem_pkcs8)?; key_file.write_all(&pem_pkcs8)?;
Ok(String::from_utf8(pem_pkcs8)?) Ok(String::from_utf8(pem_pkcs8).map_err(|e| Error::CorruptedMrSigner(e.to_string()))?)
} }
pub fn mrsigner_key_path() -> String { pub fn mrsigner_key_path() -> Result<String, Error> {
Self::path_dir().unwrap() + ("/app_signing_key.pem") Ok(Self::path_dir()? + ("/app_signing_key.pem"))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_hratls_private_key() {
let hratls_private_key = Config::get_hratls_private_key();
println!("hratls_private_key:\n{hratls_private_key}");
}
#[test]
fn test_mr_signer() {
let mr_signer = Config::get_mrsigner();
println!("mr_signer: {mr_signer}",);
} }
} }

@ -39,7 +39,7 @@ pub async fn new_app(app_deploy_config: AppDeployConfig) -> Result<NewAppRes> {
req.uuid = "".to_string(); req.uuid = "".to_string();
req.locked_nano = locked_nano; req.locked_nano = locked_nano;
req.admin_pubkey = Config::get_detee_wallet()?; req.admin_pubkey = Config::get_detee_wallet()?;
req.hratls_pubkey = Config::get_hratls_pubkey_hex(); req.hratls_pubkey = Config::get_hratls_pubkey_hex()?;
let mut daemon_serivce = BrainAppCliClient::connect(Config::get_brain_url()).await?; let mut daemon_serivce = BrainAppCliClient::connect(Config::get_brain_url()).await?;
let res = daemon_serivce.deploy_app(sign_request(req)?).await?; let res = daemon_serivce.deploy_app(sign_request(req)?).await?;

@ -29,6 +29,8 @@ pub enum Error {
SgxHRatls(#[from] detee_sgx::error::SgxError), SgxHRatls(#[from] detee_sgx::error::SgxError),
#[error("DtpmConfig: {0}")] #[error("DtpmConfig: {0}")]
DtpmConfig(String), DtpmConfig(String),
#[error(transparent)]
ConfigError(#[from] crate::config::Error),
} }
type Result<T> = std::result::Result<T, Error>; type Result<T> = std::result::Result<T, Error>;
@ -37,9 +39,9 @@ pub async fn connect_dtpm_grpc_client(
hratls_uri: String, hratls_uri: String,
package_mr_enclave: Option<[u8; 32]>, package_mr_enclave: Option<[u8; 32]>,
) -> Result<DtpmConfigManagerClient<Channel>> { ) -> Result<DtpmConfigManagerClient<Channel>> {
let private_key_pem = Config::get_hratls_private_key(); let private_key_pem = Config::get_hratls_private_key()?;
let mut mr_signer = [0u8; 32]; let mut mr_signer = [0u8; 32];
hex::decode_to_slice(Config::get_mrsigner(), &mut mr_signer)?; hex::decode_to_slice(Config::get_mrsigner()?, &mut mr_signer)?;
let mr_signers = vec![mr_signer]; let mr_signers = vec![mr_signer];
let _ = rustls::crypto::aws_lc_rs::default_provider().install_default(); let _ = rustls::crypto::aws_lc_rs::default_provider().install_default();

@ -11,8 +11,8 @@ pub fn package_enclave(
.collect::<Vec<_>>() .collect::<Vec<_>>()
.join(" "); .join(" ");
let signing_key_path = Config::mrsigner_key_path(); let signing_key_path = Config::mrsigner_key_path()?;
let hratls_key_path = Config::hratls_private_key_path(); let hratls_key_path = Config::hratls_key_path()?;
let docker_package_str = if package_type == "public" { let docker_package_str = if package_type == "public" {
format!( format!(