|
| 1 | +// SPDX-License-Identifier: Apache-2.0 |
| 2 | + |
| 3 | +//! Provisioner plugin for KBS. |
| 4 | +//! |
| 5 | +//! Generates per-VM LUKS encryption keys and stores them in the KBS resource |
| 6 | +//! storage so that attested guests can retrieve them via the standard |
| 7 | +//! `/kbs/v0/resource/...` path. |
| 8 | +//! |
| 9 | +//! The hook sidecar calls `POST /kbs/v0/provisioner/provision` before the VM |
| 10 | +//! boots and receives `{uuid, oemstring, mrconfigid}` to inject into SMBIOS. |
| 11 | +//! On boot the guest attests and fetches the key through the `resource` plugin. |
| 12 | +
|
| 13 | +use std::collections::HashMap; |
| 14 | + |
| 15 | +use actix_web::http::Method; |
| 16 | +use anyhow::{anyhow, bail, Result}; |
| 17 | +use base64::{engine::general_purpose::STANDARD as B64, Engine}; |
| 18 | +use key_value_storage::{KeyValueStorageInstance, SetParameters, StorageBackendConfig}; |
| 19 | +use rand::Rng; |
| 20 | +use serde::{Deserialize, Serialize}; |
| 21 | +use sha2::{Digest, Sha384}; |
| 22 | +use uuid::Uuid; |
| 23 | + |
| 24 | +use super::resource::RESOURCE_STORAGE_NAMESPACE; |
| 25 | + |
| 26 | +// Config (deserialized from kbs-config.toml) |
| 27 | +#[derive(Deserialize, Clone, Debug, PartialEq)] |
| 28 | +pub struct ProvisionerConfig { |
| 29 | + /// URL that will be embedded in `initdata.toml` for the guest. |
| 30 | + pub kbs_url: String, |
| 31 | + |
| 32 | + /// Length of the random LUKS key in bytes (default 32). |
| 33 | + #[serde(default = "default_key_length")] |
| 34 | + pub key_length: usize, |
| 35 | +} |
| 36 | + |
| 37 | +fn default_key_length() -> usize { |
| 38 | + 32 |
| 39 | +} |
| 40 | + |
| 41 | +pub struct Provisioner { |
| 42 | + storage: KeyValueStorageInstance, |
| 43 | + kbs_url: String, |
| 44 | + key_length: usize, |
| 45 | + // TODO: This in-memory cache grows unboundedly and uses std::sync::Mutex |
| 46 | + // which can block the async runtime. More critically, the cache does |
| 47 | + // not survive KBS restarts: if the sidecar re-provisions the same VM |
| 48 | + // after a restart, a new UUID/key pair is generated, replacing the |
| 49 | + // original resource. The VM's LUKS volume would then fail to unlock |
| 50 | + // because the key no longer matches. The cache (or the vm->resource |
| 51 | + // mapping) must be persisted to the storage backend so it can be |
| 52 | + // restored on startup. |
| 53 | + cache: tokio::sync::RwLock<HashMap<String, ProvisionResponse>>, |
| 54 | +} |
| 55 | + |
| 56 | +#[derive(Serialize, Deserialize, Clone)] |
| 57 | +struct ProvisionRequest { |
| 58 | + vm_name: String, |
| 59 | + #[serde(default = "default_namespace")] |
| 60 | + namespace: String, |
| 61 | +} |
| 62 | + |
| 63 | +fn default_namespace() -> String { |
| 64 | + "default".into() |
| 65 | +} |
| 66 | + |
| 67 | +#[derive(Serialize, Clone)] |
| 68 | +struct ProvisionResponse { |
| 69 | + uuid: String, |
| 70 | + oemstring: String, |
| 71 | + mrconfigid: String, |
| 72 | + resource_path: String, |
| 73 | +} |
| 74 | + |
| 75 | +#[derive(Serialize)] |
| 76 | +struct StatusResponse { |
| 77 | + status: String, |
| 78 | +} |
| 79 | + |
| 80 | +impl Provisioner { |
| 81 | + pub async fn new( |
| 82 | + config: ProvisionerConfig, |
| 83 | + storage_backend_config: &StorageBackendConfig, |
| 84 | + ) -> Result<Self> { |
| 85 | + let storage = storage_backend_config |
| 86 | + .backends |
| 87 | + .to_client_with_namespace( |
| 88 | + storage_backend_config.storage_type, |
| 89 | + RESOURCE_STORAGE_NAMESPACE, |
| 90 | + ) |
| 91 | + .await |
| 92 | + .map_err(|e| anyhow!("Provisioner: failed to init storage backend: {e}"))?; |
| 93 | + |
| 94 | + Ok(Self { |
| 95 | + storage, |
| 96 | + kbs_url: config.kbs_url, |
| 97 | + key_length: config.key_length, |
| 98 | + cache:tokio::sync::RwLock::new(HashMap::new()), |
| 99 | + }) |
| 100 | + } |
| 101 | +} |
| 102 | + |
| 103 | +impl Provisioner { |
| 104 | + // TODO: This generates an alphanumeric string (~5.95 bits of entropy per |
| 105 | + // char, ~190 bits for 32 chars). Use OsRng with raw bytes + base64/hex |
| 106 | + // encoding to get a full 256-bit key. |
| 107 | + fn generate_random_key(&self) -> String { |
| 108 | + const CHARSET: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; |
| 109 | + let mut rng = rand::thread_rng(); |
| 110 | + (0..self.key_length) |
| 111 | + .map(|_| { |
| 112 | + let idx = rng.gen_range(0..CHARSET.len()); |
| 113 | + CHARSET[idx] as char |
| 114 | + }) |
| 115 | + .collect() |
| 116 | + } |
| 117 | + |
| 118 | + fn generate_initdata_toml(&self, resource_path: &str) -> String { |
| 119 | + format!( |
| 120 | + "algorithm = \"sha384\"\n\ |
| 121 | + version = \"0.1.0\"\n\ |
| 122 | + \n\ |
| 123 | + [data]\n\ |
| 124 | + \"trustee.kbs.url\" = \"{}\"\n\ |
| 125 | + \"trustee.kbs.resource\" = \"{}\"\n", |
| 126 | + self.kbs_url, resource_path |
| 127 | + ) |
| 128 | + } |
| 129 | + |
| 130 | + fn generate_confdata_toml(luks_key: &str) -> String { |
| 131 | + format!( |
| 132 | + "version = \"0.1.0\"\n\ |
| 133 | + \n\ |
| 134 | + [data]\n\ |
| 135 | + \"io.cryptsetup.key.text.root\" = \"{}\"\n", |
| 136 | + luks_key |
| 137 | + ) |
| 138 | + } |
| 139 | + |
| 140 | + async fn handle_provision(&self, body: &[u8]) -> Result<Vec<u8>> { |
| 141 | + let req: ProvisionRequest = serde_json::from_slice(body) |
| 142 | + .map_err(|e| anyhow!("invalid JSON body: {e}"))?; |
| 143 | + |
| 144 | + let cache_key = format!("{}/{}", req.namespace, req.vm_name); |
| 145 | + |
| 146 | + // Return cached result if already provisioned |
| 147 | + if let Some(cached) = self.cache.read().await.get(&cache_key) { |
| 148 | + return Ok(serde_json::to_vec(cached)?); |
| 149 | + } |
| 150 | + |
| 151 | + // TODO: UUIDv4 is random but not tied to VM identity. A more robust |
| 152 | + // approach would derive the UUID deterministically from the VM's |
| 153 | + // attributes (e.g. name + namespace + cluster ID) to ensure |
| 154 | + // idempotency and traceability across re-provisions. |
| 155 | + // A uniqueness check against existing storage entries should also |
| 156 | + // be added to avoid collisions before writing the resource. |
| 157 | + let trustee_uuid = Uuid::new_v4().to_string(); |
| 158 | + let resource_path = format!("default/{trustee_uuid}/root"); |
| 159 | + let luks_key = self.generate_random_key(); |
| 160 | + |
| 161 | + let initdata_toml = self.generate_initdata_toml(&resource_path); |
| 162 | + let confdata_toml = Self::generate_confdata_toml(&luks_key); |
| 163 | + |
| 164 | + let oemstring = B64.encode(initdata_toml.as_bytes()); |
| 165 | + let mrconfigid = { |
| 166 | + let digest = Sha384::digest(initdata_toml.as_bytes()); |
| 167 | + B64.encode(digest) |
| 168 | + }; |
| 169 | + |
| 170 | + // Write the confdata (LUKS key) to storage via the same backend |
| 171 | + // that the `resource` plugin reads from. |
| 172 | + // TODO: Using overwrite: true could silently replace another VM's key |
| 173 | + // on UUID collision. Use overwrite: false and handle the conflict error, |
| 174 | + // or check existence before writing. |
| 175 | + self.storage |
| 176 | + .set( |
| 177 | + &resource_path, |
| 178 | + confdata_toml.as_bytes(), |
| 179 | + SetParameters { overwrite: true }, |
| 180 | + ) |
| 181 | + .await |
| 182 | + .map_err(|e| anyhow!("failed to write resource: {e}"))?; |
| 183 | + |
| 184 | + // NOTE: The sidecar currently only consumes `oemstring` and `mrconfigid`. |
| 185 | + // `uuid` and `resource_path` are included for debugging/deprovision but |
| 186 | + // are redundant for the sidecar since `oemstring` (base64 of initdata.toml) |
| 187 | + // already embeds the resource_path. |
| 188 | + let response = ProvisionResponse { |
| 189 | + uuid: trustee_uuid, |
| 190 | + oemstring, |
| 191 | + mrconfigid, |
| 192 | + resource_path, |
| 193 | + }; |
| 194 | + |
| 195 | + self.cache.write().await.insert(cache_key, response.clone()); |
| 196 | + |
| 197 | + Ok(serde_json::to_vec(&response)?) |
| 198 | + } |
| 199 | + |
| 200 | + async fn handle_deprovision(&self, path: &[&str]) -> Result<Vec<u8>> { |
| 201 | + let trustee_uuid = path.first().ok_or_else(|| anyhow!("missing uuid in path"))?; |
| 202 | + let resource_path = format!("default/{trustee_uuid}/root"); |
| 203 | + |
| 204 | + let _ = self.storage.delete(&resource_path).await; |
| 205 | + |
| 206 | + // Remove from cache |
| 207 | + self.cache.write().await.retain(|_, v| v.uuid != *trustee_uuid); |
| 208 | + |
| 209 | + Ok(serde_json::to_vec(&StatusResponse { |
| 210 | + status: "deleted".into(), |
| 211 | + })?) |
| 212 | + } |
| 213 | +} |
| 214 | + |
| 215 | +#[async_trait::async_trait] |
| 216 | +impl super::super::plugin_manager::ClientPlugin for Provisioner { |
| 217 | + async fn handle( |
| 218 | + &self, |
| 219 | + body: &[u8], |
| 220 | + _query: &HashMap<String, String>, |
| 221 | + path: &[&str], |
| 222 | + method: &Method, |
| 223 | + ) -> Result<Vec<u8>> { |
| 224 | + match (method.as_str(), path.first().copied()) { |
| 225 | + ("POST", Some("provision")) => self.handle_provision(body).await, |
| 226 | + ("DELETE", Some("provision")) => { |
| 227 | + self.handle_deprovision(&path[1..]).await |
| 228 | + } |
| 229 | + ("GET", Some("healthz")) => { |
| 230 | + Ok(serde_json::to_vec(&StatusResponse { |
| 231 | + status: "healthy".into(), |
| 232 | + })?) |
| 233 | + } |
| 234 | + _ => bail!("unsupported: {} /kbs/v0/provisioner/{}", method, path.join("/")), |
| 235 | + } |
| 236 | + } |
| 237 | + |
| 238 | + async fn validate_auth( |
| 239 | + &self, |
| 240 | + _body: &[u8], |
| 241 | + _query: &HashMap<String, String>, |
| 242 | + _path: &[&str], |
| 243 | + _method: &Method, |
| 244 | + ) -> Result<bool> { |
| 245 | + // Return true so KBS routes through the admin auth path |
| 246 | + // (instead of the attestation token path which requires a TEE session). |
| 247 | + // |
| 248 | + // NOTE: Currently relies on InsecureAllowAll admin backend for dev. |
| 249 | + // For production, switch to Simple admin with JWT-signed requests |
| 250 | + // and scoped roles, e.g.: |
| 251 | + // [admin] type = "Simple" |
| 252 | + // [[admin.personas]] id = "provisioner" public_key_path = "..." |
| 253 | + // [[admin.roles]] id = "provisioner" allowed_endpoints = "^/kbs/v0/provisioner/.*$" |
| 254 | + Ok(true) |
| 255 | + } |
| 256 | + |
| 257 | + async fn encrypted( |
| 258 | + &self, |
| 259 | + _body: &[u8], |
| 260 | + _query: &HashMap<String, String>, |
| 261 | + _path: &[&str], |
| 262 | + _method: &Method, |
| 263 | + ) -> Result<bool> { |
| 264 | + // Responses don't need TEE encryption (caller is infrastructure, not a TEE). |
| 265 | + Ok(false) |
| 266 | + } |
| 267 | +} |
0 commit comments