Skip to content

Commit

Permalink
CDH/KMS/kbs: read parameters from env
Browse files Browse the repository at this point in the history
Related to confidential-containers#413. KBS client will also read parameters from env,
including:

- KBC_NAME: The KBC name, i.e. `cc_kbc`, `offline_fs_kbc` or
`online_sev_kbc`
- KBS_URL: The url of KBS
- KBS_PUBLICKEY_CERT: The public key cert of KBS

Signed-off-by: Xynnn007 <[email protected]>
  • Loading branch information
Xynnn007 committed Jan 19, 2024
1 parent 3bd4841 commit 298c10c
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 88 deletions.
23 changes: 20 additions & 3 deletions confidential-data-hub/kms/src/plugins/kbs/cc_kbc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,15 @@
// SPDX-License-Identifier: Apache-2.0
//

use std::env;

use async_trait::async_trait;
use kbs_protocol::{
client::KbsClient as KbsProtocolClient,
token_provider::{AATokenProvider, TokenProvider},
KbsClientCapabilities, ResourceUri,
};
use log::{info, warn};

use crate::{Error, Result};

Expand All @@ -23,12 +26,26 @@ impl CcKbc {
let token_provider = AATokenProvider::new()
.await
.map_err(|e| Error::KbsClientError(format!("create AA token provider failed: {e}")))?;

let client = kbs_protocol::KbsClientBuilder::with_token_provider(
Box::new(token_provider),
kbs_host_url,
)
.build()
.map_err(|e| Error::KbsClientError(format!("create kbs client failed: {e}")))?;
);

let client = match env::var("KBS_PUBLICKEY_CERT") {
Ok(cert_pem) => {
info!("Use KBS public key cert");
client.add_kbs_cert(&cert_pem)
}
Err(e) => {
warn!("KBS_PUBLICKEY_CERT get failed: {e:?}. Use no KBS public key certs.");
client
}
};

let client = client
.build()
.map_err(|e| Error::KbsClientError(format!("create kbs client failed: {e}")))?;
Ok(Self { client })
}
}
Expand Down
90 changes: 7 additions & 83 deletions confidential-data-hub/kms/src/plugins/kbs/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,20 +17,12 @@ use std::sync::Arc;

use async_trait::async_trait;
use lazy_static::lazy_static;
use log::debug;
pub use resource_uri::ResourceUri;
use serde::Deserialize;
use std::path::Path;
use std::sync::OnceLock;
use std::{env, fs};
use std::env;
use tokio::sync::Mutex;

use crate::{Annotations, Error, Getter, Result};

const PEER_POD_CONFIG_PATH: &str = "/run/peerpod/daemon.json";

static KATA_AGENT_CONFIG_PATH: OnceLock<String> = OnceLock::new();

enum RealClient {
#[cfg(feature = "kbs")]
Cc(cc_kbc::CcKbc),
Expand All @@ -41,18 +33,16 @@ enum RealClient {

impl RealClient {
async fn new() -> Result<Self> {
// Check for /run/peerpod/daemon.json to see if we are in a peer pod
// If so we need to read from the agent-config file, not /proc/cmdline
let (kbc, _kbs_host) = match Path::new(PEER_POD_CONFIG_PATH).exists() {
true => get_aa_params_from_config_file().await?,
false => get_aa_params_from_cmdline().await?,
};
let kbc = env::var("KBC_NAME")
.map_err(|_| Error::KbsClientError("KBC_NAME not set in env".to_string()))?;
let _kbs_url = env::var("KBS_URL")
.map_err(|_| Error::KbsClientError("KBS_URL not set in env".to_string()))?;

let c = match &kbc[..] {
#[cfg(feature = "kbs")]
"cc_kbc" => RealClient::Cc(cc_kbc::CcKbc::new(&_kbs_host).await?),
"cc_kbc" => RealClient::Cc(cc_kbc::CcKbc::new(&_kbs_url).await?),
#[cfg(feature = "sev")]
"online_sev_kbc" => RealClient::Sev(sev::OnlineSevKbc::new(&_kbs_host).await?),
"online_sev_kbc" => RealClient::Sev(sev::OnlineSevKbc::new(&_kbs_url).await?),
"offline_fs_kbc" => RealClient::OfflineFs(offline_fs::OfflineFsKbc::new().await?),
others => return Err(Error::KbsClientError(format!("unknown kbc name {others}, only support `cc_kbc`(feature `kbs`), `online_sev_kbc` (feature `sev`) and `offline_fs_kbc`."))),
};
Expand Down Expand Up @@ -116,69 +106,3 @@ impl KbcClient {
Ok(KbcClient {})
}
}

async fn get_aa_params_from_cmdline() -> Result<(String, String)> {
use tokio::fs;
debug!("get aa_kbc_params from kernel cmdline");
let cmdline = fs::read_to_string("/proc/cmdline")
.await
.map_err(|e| Error::KbsClientError(format!("read kernel cmdline failed: {e}")))?;
let aa_kbc_params = cmdline
.split_ascii_whitespace()
.find(|para| para.starts_with("agent.aa_kbc_params="))
.ok_or(Error::KbsClientError(
"no `agent.aa_kbc_params` provided in kernel commandline!".into(),
))?
.strip_prefix("agent.aa_kbc_params=")
.expect("must have a prefix")
.split("::")
.collect::<Vec<&str>>();

if aa_kbc_params.len() != 2 {
return Err(Error::KbsClientError(
"Illegal `agent.aa_kbc_params` format provided in kernel commandline.".to_string(),
));
}

Ok((aa_kbc_params[0].to_string(), aa_kbc_params[1].to_string()))
}

async fn get_aa_params_from_config_file() -> Result<(String, String)> {
debug!("get aa_kbc_params from file");
// We only care about the aa_kbc_params value at the moment
#[derive(Debug, Deserialize)]
struct AgentConfig {
aa_kbc_params: Option<String>,
}

// check env for KATA_AGENT_CONFIG_PATH, fall back to default path
let path: &String = KATA_AGENT_CONFIG_PATH.get_or_init(|| {
env::var("KATA_AGENT_CONFIG_PATH").unwrap_or_else(|_| "/etc/agent-config.toml".into())
});

debug!("reading agent config from {}", path);
let agent_config_str = fs::read_to_string(path)
.map_err(|e| Error::KbsClientError(format!("Failed to read {path} file: {e}")))?;

let agent_config: AgentConfig = toml::from_str(&agent_config_str)
.map_err(|e| Error::KbsClientError(format!("Failed to deserialize {path}: {e}")))?;

let aa_kbc_params = agent_config
.aa_kbc_params
.ok_or(Error::KbsClientError(format!(
"no `aa_kbc_params` found in {path}"
)))?;

let aa_kbc_params_vec = aa_kbc_params.split("::").collect::<Vec<&str>>();

if aa_kbc_params_vec.len() != 2 {
return Err(Error::KbsClientError(format!(
"Illegal `aa_kbc_params` format provided in {path}."
)));
}

Ok((
aa_kbc_params_vec[0].to_string(),
aa_kbc_params_vec[1].to_string(),
))
}
2 changes: 0 additions & 2 deletions confidential-data-hub/kms/src/plugins/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,6 @@ use strum::{AsRefStr, EnumString};

use crate::{Decrypter, Error, Getter, ProviderSettings, Result};

const _IN_GUEST_DEFAULT_KEY_PATH: &str = "/run/confidential-containers/cdh/kms-credential";

#[cfg(feature = "aliyun")]
pub mod aliyun;

Expand Down

0 comments on commit 298c10c

Please sign in to comment.