mirror of
https://github.com/Dasemu/Synapse.git
synced 2026-11-26 15:26:17 +00:00
fix(modules): meter host calls, cap tables, storage quotas, separate key wrapping from sealing, no lock-order deadlock, unique macro names
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
0faff9ae96
commit
fcdfeb216a
6 files changed
+417
-18
No files matched your search
@@ -12,12 +12,20 @@ use zeroize::Zeroizing;
|
||||
pub const KEY_LEN: usize = 32;
|
||||
pub const NONCE_LEN: usize = 24;
|
||||
/// Upper bounds for Argon2id parameters a module may ask for (memory in KiB).
|
||||
pub const MAX_KDF_MEMORY_KIB: u32 = 256 * 1024;
|
||||
pub const MAX_KDF_MEMORY_KIB: u32 = 128 * 1024;
|
||||
pub const MAX_KDF_ITERATIONS: u32 = 10;
|
||||
pub const MAX_KDF_LANES: u32 = 4;
|
||||
/// Largest plaintext or ciphertext handled in one call.
|
||||
pub const MAX_CRYPTO_INPUT: usize = 1 << 20;
|
||||
const MAX_KEYS: usize = 64;
|
||||
/// Associated data prefix reserved for key wrapping, so data sealed with [`Keyring::seal`]
|
||||
/// can never be unwrapped as a key (importing a key the module knows) and a wrapped key can
|
||||
/// never be opened as data (exporting it).
|
||||
const WRAP_AAD: &[u8] = b"synapse.wrap\0";
|
||||
|
||||
fn wrap_aad(aad: &[u8]) -> Vec<u8> {
|
||||
[WRAP_AAD, aad].concat()
|
||||
}
|
||||
|
||||
type Key = Zeroizing<[u8; KEY_LEN]>;
|
||||
|
||||
@@ -89,6 +97,13 @@ impl Keyring {
|
||||
|
||||
/// Encrypts with a fresh random nonce; returns `nonce || ciphertext`.
|
||||
pub fn seal(&self, key: u32, plaintext: &[u8], aad: &[u8]) -> Result<Vec<u8>> {
|
||||
if aad.starts_with(WRAP_AAD) {
|
||||
return Err(Error::Invalid("reserved associated data".into()));
|
||||
}
|
||||
self.seal_raw(key, plaintext, aad)
|
||||
}
|
||||
|
||||
fn seal_raw(&self, key: u32, plaintext: &[u8], aad: &[u8]) -> Result<Vec<u8>> {
|
||||
if plaintext.len() > MAX_CRYPTO_INPUT {
|
||||
return Err(Error::Invalid("plaintext too large".into()));
|
||||
}
|
||||
@@ -111,6 +126,13 @@ impl Keyring {
|
||||
|
||||
/// Decrypts `nonce || ciphertext`; fails when the key, data or associated data is wrong.
|
||||
pub fn open(&self, key: u32, data: &[u8], aad: &[u8]) -> Result<Zeroizing<Vec<u8>>> {
|
||||
if aad.starts_with(WRAP_AAD) {
|
||||
return Err(Error::Invalid("reserved associated data".into()));
|
||||
}
|
||||
self.open_raw(key, data, aad)
|
||||
}
|
||||
|
||||
fn open_raw(&self, key: u32, data: &[u8], aad: &[u8]) -> Result<Zeroizing<Vec<u8>>> {
|
||||
if data.len() < NONCE_LEN || data.len() > MAX_CRYPTO_INPUT + NONCE_LEN + 16 {
|
||||
return Err(Error::Decrypt);
|
||||
}
|
||||
@@ -129,12 +151,12 @@ impl Keyring {
|
||||
/// Encrypts key `target` with key `kek` (key wrapping).
|
||||
pub fn wrap(&self, kek: u32, target: u32, aad: &[u8]) -> Result<Vec<u8>> {
|
||||
let t = self.get(target)?.clone();
|
||||
self.seal(kek, t.as_ref(), aad)
|
||||
self.seal_raw(kek, t.as_ref(), &wrap_aad(aad))
|
||||
}
|
||||
|
||||
/// Decrypts a wrapped key and returns a handle to it.
|
||||
pub fn unwrap_key(&mut self, kek: u32, data: &[u8], aad: &[u8]) -> Result<u32> {
|
||||
let plain = self.open(kek, data, aad)?;
|
||||
let plain = self.open_raw(kek, data, &wrap_aad(aad))?;
|
||||
let bytes: [u8; KEY_LEN] = plain.as_slice().try_into().map_err(|_| Error::Decrypt)?;
|
||||
self.insert(Zeroizing::new(bytes))
|
||||
}
|
||||
@@ -185,6 +207,12 @@ mod tests {
|
||||
// Fresh nonce each time.
|
||||
assert_ne!(ct, k.seal(dek, b"hunter2", b"entry/1").unwrap());
|
||||
|
||||
// Wrapped keys and sealed data cannot be confused.
|
||||
assert!(k.open(same, &wrapped, b"vault").is_err());
|
||||
let sealed_key = k.seal(kek, &[7u8; KEY_LEN], b"vault").unwrap();
|
||||
assert!(k.unwrap_key(same, &sealed_key, b"vault").is_err());
|
||||
assert!(k.seal(kek, b"x", b"synapse.wrap\0vault").is_err());
|
||||
|
||||
k.forget(dek2);
|
||||
assert!(k.open(dek2, &ct, b"entry/1").is_err());
|
||||
}
|
||||
|
||||
@@ -32,6 +32,20 @@ pub const FUEL_PER_REQUEST: u64 = 1_000_000_000;
|
||||
pub const MAX_MEMORY: usize = 64 << 20;
|
||||
/// Largest request, response or host-call payload.
|
||||
pub const MAX_MESSAGE: usize = 4 << 20;
|
||||
/// Host calls are not free: each costs this much fuel plus [`FUEL_PER_BYTE`] per byte in and
|
||||
/// out, so a loop of host calls runs out of fuel like any other loop.
|
||||
pub const FUEL_PER_HOST_CALL: u64 = 200_000;
|
||||
pub const FUEL_PER_BYTE: u64 = 20;
|
||||
/// Hard caps per request, whatever the fuel: host calls, bytes written to storage and key
|
||||
/// derivations (Argon2 is memory-hard and slow on purpose).
|
||||
pub const MAX_HOST_CALLS: u32 = 5_000;
|
||||
pub const MAX_WRITE_BYTES: usize = 16 << 20;
|
||||
pub const MAX_DERIVES: u32 = 3;
|
||||
/// Storage quota per module (all its live entries).
|
||||
pub const MAX_STORAGE_BYTES: u64 = 64 << 20;
|
||||
pub const MAX_STORAGE_ENTRIES: u64 = 50_000;
|
||||
/// Table elements per instance (tables live outside linear memory).
|
||||
pub const MAX_TABLE_ELEMENTS: usize = 10_000;
|
||||
|
||||
pub(crate) struct HostState {
|
||||
manifest: Manifest,
|
||||
@@ -41,6 +55,10 @@ pub(crate) struct HostState {
|
||||
response: Option<Vec<u8>>,
|
||||
limits: StoreLimits,
|
||||
log: Vec<String>,
|
||||
/// Usage in the current request (reset by [`Running::request`]).
|
||||
calls: u32,
|
||||
written: usize,
|
||||
derives: u32,
|
||||
}
|
||||
|
||||
pub(crate) fn engine() -> Engine {
|
||||
@@ -68,6 +86,16 @@ fn memory_of(caller: &Caller<'_, HostState>) -> Result<Memory, wasmi::Error> {
|
||||
.ok_or_else(|| wasmi::Error::new("module exports no memory"))
|
||||
}
|
||||
|
||||
/// Takes the cost of a host call (and its payload) out of the request's fuel.
|
||||
fn charge(caller: &mut Caller<'_, HostState>, bytes: usize) -> Result<(), wasmi::Error> {
|
||||
let cost = FUEL_PER_HOST_CALL + FUEL_PER_BYTE * bytes as u64;
|
||||
let fuel = caller.get_fuel()?;
|
||||
if fuel < cost {
|
||||
return Err(wasmi::Error::new("out of fuel"));
|
||||
}
|
||||
caller.set_fuel(fuel - cost)
|
||||
}
|
||||
|
||||
fn read_bytes(caller: &Caller<'_, HostState>, ptr: i32, len: i32) -> Result<Vec<u8>, wasmi::Error> {
|
||||
let len = usize::try_from(len).map_err(|_| wasmi::Error::new("negative length"))?;
|
||||
if len > MAX_MESSAGE {
|
||||
@@ -98,8 +126,13 @@ impl Running {
|
||||
.instances(1)
|
||||
.memories(1)
|
||||
.tables(4)
|
||||
.table_elements(MAX_TABLE_ELEMENTS)
|
||||
.trap_on_grow_failure(true)
|
||||
.build(),
|
||||
log: Vec::new(),
|
||||
calls: 0,
|
||||
written: 0,
|
||||
derives: 0,
|
||||
};
|
||||
let mut store = Store::new(engine, state);
|
||||
store.limiter(|s| &mut s.limits);
|
||||
@@ -113,6 +146,12 @@ impl Running {
|
||||
len: i32|
|
||||
-> Result<i32, wasmi::Error> {
|
||||
let req = read_bytes(&caller, ptr, len)?;
|
||||
let state = caller.data_mut();
|
||||
state.calls += 1;
|
||||
if state.calls > MAX_HOST_CALLS {
|
||||
return Err(wasmi::Error::new("too many host calls in one request"));
|
||||
}
|
||||
charge(&mut caller, req.len())?;
|
||||
let reply = match dispatch(caller.data_mut(), &req) {
|
||||
Ok(v) => json!({ "ok": v }),
|
||||
Err(e) => json!({ "error": e.to_string() }),
|
||||
@@ -122,6 +161,7 @@ impl Running {
|
||||
if bytes.len() > MAX_MESSAGE {
|
||||
return Err(wasmi::Error::new("host reply too large"));
|
||||
}
|
||||
charge(&mut caller, bytes.len())?;
|
||||
let n = bytes.len() as i32;
|
||||
caller.data_mut().pending = bytes;
|
||||
Ok(n)
|
||||
@@ -187,7 +227,12 @@ impl Running {
|
||||
self.store
|
||||
.set_fuel(FUEL_PER_REQUEST)
|
||||
.map_err(|e| Error::Host(e.to_string()))?;
|
||||
self.store.data_mut().response = None;
|
||||
let state = self.store.data_mut();
|
||||
state.response = None;
|
||||
state.pending.clear();
|
||||
state.calls = 0;
|
||||
state.written = 0;
|
||||
state.derives = 0;
|
||||
let ptr = self
|
||||
.alloc
|
||||
.call(&mut self.store, bytes.len() as i32)
|
||||
@@ -301,21 +346,52 @@ fn dispatch(state: &mut HostState, req: &[u8]) -> Result<Value> {
|
||||
Some(Value::String(s)) => Some(s.as_str()),
|
||||
Some(_) => return Err(Error::Invalid("value must be a string or null".into())),
|
||||
};
|
||||
graph(state).set_module_data(&id, key, value)?;
|
||||
let size = key.len() + value.map_or(0, str::len);
|
||||
if state.written + size > MAX_WRITE_BYTES {
|
||||
return Err(Error::Invalid(
|
||||
"too much data written in one request".into(),
|
||||
));
|
||||
}
|
||||
state.written += size;
|
||||
let g = graph(state);
|
||||
if let Some(v) = value {
|
||||
let (count, bytes) = g.module_data_usage(&id)?;
|
||||
let old = g.module_data(&id, key)?;
|
||||
let new_count = count + u64::from(old.is_none());
|
||||
let new_bytes = bytes - old.map_or(0, |o| (key.len() + o.len()) as u64)
|
||||
+ (key.len() + v.len()) as u64;
|
||||
if new_count > MAX_STORAGE_ENTRIES || new_bytes > MAX_STORAGE_BYTES {
|
||||
return Err(Error::Invalid("the module's storage quota is full".into()));
|
||||
}
|
||||
}
|
||||
g.set_module_data(&id, key, value)?;
|
||||
Ok(Value::Null)
|
||||
}
|
||||
"kv.list" => {
|
||||
need(state, Permission::Storage)?;
|
||||
let prefix = args.get("prefix").and_then(Value::as_str).unwrap_or("");
|
||||
let rows = graph(state).module_data_list(&id, prefix)?;
|
||||
Ok(Value::Array(
|
||||
rows.into_iter()
|
||||
.map(|(k, v)| json!({ "key": k, "value": v }))
|
||||
.collect(),
|
||||
))
|
||||
let mut total = 0;
|
||||
let mut out = Vec::with_capacity(rows.len());
|
||||
for (k, v) in rows {
|
||||
total += k.len() + v.len() + 32;
|
||||
if total > MAX_MESSAGE - 1024 {
|
||||
return Err(Error::Invalid(
|
||||
"too much data to list at once; use a narrower prefix".into(),
|
||||
));
|
||||
}
|
||||
out.push(json!({ "key": k, "value": v }));
|
||||
}
|
||||
Ok(Value::Array(out))
|
||||
}
|
||||
"crypto.derive" => {
|
||||
need(state, Permission::Crypto)?;
|
||||
state.derives += 1;
|
||||
if state.derives > MAX_DERIVES {
|
||||
return Err(Error::Invalid(
|
||||
"too many key derivations in one request".into(),
|
||||
));
|
||||
}
|
||||
let h = state.keys.derive(
|
||||
arg_str(&args, "password")?,
|
||||
&arg_b64(&args, "salt")?,
|
||||
|
||||
@@ -11,7 +11,11 @@ mod host;
|
||||
pub mod manifest;
|
||||
mod registry;
|
||||
|
||||
pub use host::{FUEL_PER_REQUEST, MAX_MEMORY, MAX_MESSAGE, Running};
|
||||
pub use host::{
|
||||
FUEL_PER_BYTE, FUEL_PER_HOST_CALL, FUEL_PER_REQUEST, MAX_DERIVES, MAX_HOST_CALLS, MAX_MEMORY,
|
||||
MAX_MESSAGE, MAX_STORAGE_BYTES, MAX_STORAGE_ENTRIES, MAX_TABLE_ELEMENTS, MAX_WRITE_BYTES,
|
||||
Running,
|
||||
};
|
||||
pub use manifest::{API_VERSION, MANIFEST_SECTION, Manifest, Permission, ViewDecl};
|
||||
pub use registry::{ModuleInfo, Registry};
|
||||
|
||||
|
||||
@@ -108,6 +108,23 @@ impl Registry {
|
||||
)));
|
||||
}
|
||||
let mut state = self.lock_state();
|
||||
// A block macro belongs to one module: another installed module claiming the same
|
||||
// name would silently receive (and could spoof) its blocks.
|
||||
for other in self.list_locked(&state) {
|
||||
if other.manifest.id == manifest.id {
|
||||
continue;
|
||||
}
|
||||
if let Some(m) = manifest
|
||||
.macros
|
||||
.iter()
|
||||
.find(|m| other.manifest.macros.contains(m))
|
||||
{
|
||||
return Err(Error::Invalid(format!(
|
||||
"the macro {{{{{m}}}}} is already used by the module {}",
|
||||
other.manifest.name
|
||||
)));
|
||||
}
|
||||
}
|
||||
std::fs::create_dir_all(&self.dir)?;
|
||||
let path = self.wasm_path(&manifest.id);
|
||||
let tmp = path.with_extension("wasm.tmp");
|
||||
@@ -122,6 +139,9 @@ impl Registry {
|
||||
},
|
||||
);
|
||||
self.save(&state)?;
|
||||
// Never wait for a module slot while holding the state lock: `call` takes them in
|
||||
// the opposite order.
|
||||
drop(state);
|
||||
// Drop a running older version.
|
||||
*self
|
||||
.slot(&manifest.id)
|
||||
@@ -137,12 +157,23 @@ impl Registry {
|
||||
/// Installed modules, by name. A module whose file is missing or broken is skipped.
|
||||
pub fn list(&self) -> Vec<ModuleInfo> {
|
||||
let state = self.lock_state().clone();
|
||||
self.list_locked(&state)
|
||||
}
|
||||
|
||||
/// Whether the graph already holds data for module `id` (synced from another device or
|
||||
/// left by an earlier install): a module installed under that id can read it.
|
||||
pub fn has_data(&self, id: &str) -> Result<bool> {
|
||||
let g = self.graph.lock().unwrap_or_else(|p| p.into_inner());
|
||||
Ok(g.module_data_usage(id)?.0 > 0)
|
||||
}
|
||||
|
||||
fn list_locked(&self, state: &BTreeMap<String, Entry>) -> Vec<ModuleInfo> {
|
||||
let mut out: Vec<ModuleInfo> = state
|
||||
.into_iter()
|
||||
.iter()
|
||||
.filter_map(|(id, e)| {
|
||||
let bytes = std::fs::read(self.wasm_path(&id)).ok()?;
|
||||
let bytes = std::fs::read(self.wasm_path(id)).ok()?;
|
||||
let manifest = Manifest::from_wasm(&bytes).ok()?;
|
||||
(manifest.id == id).then_some(ModuleInfo {
|
||||
(&manifest.id == id).then_some(ModuleInfo {
|
||||
manifest,
|
||||
enabled: e.enabled,
|
||||
size: bytes.len() as u64,
|
||||
@@ -160,6 +191,7 @@ impl Registry {
|
||||
.ok_or_else(|| Error::NotFound(id.to_string()))?;
|
||||
e.enabled = enabled;
|
||||
self.save(&state)?;
|
||||
drop(state);
|
||||
if !enabled {
|
||||
self.stop(id);
|
||||
}
|
||||
@@ -174,6 +206,7 @@ impl Registry {
|
||||
return Err(Error::NotFound(id.to_string()));
|
||||
}
|
||||
self.save(&state)?;
|
||||
drop(state);
|
||||
self.stop(id);
|
||||
let _ = std::fs::remove_file(self.wasm_path(id));
|
||||
if delete_data {
|
||||
@@ -187,12 +220,14 @@ impl Registry {
|
||||
|
||||
/// Drops the running instance (its in-memory state, such as unlocked keys, is lost).
|
||||
pub fn stop(&self, id: &str) {
|
||||
if let Some(slot) = self
|
||||
// Release the map before waiting for a busy module, so other modules keep working.
|
||||
let slot = self
|
||||
.loaded
|
||||
.lock()
|
||||
.unwrap_or_else(|p| p.into_inner())
|
||||
.get(id)
|
||||
{
|
||||
.cloned();
|
||||
if let Some(slot) = slot {
|
||||
*slot.lock().unwrap_or_else(|p| p.into_inner()) = None;
|
||||
}
|
||||
}
|
||||
@@ -224,6 +259,14 @@ impl Registry {
|
||||
}
|
||||
let slot = self.slot(id);
|
||||
let mut guard = slot.lock().unwrap_or_else(|p| p.into_inner());
|
||||
// Disabled or removed while we waited for the slot: do not start it again.
|
||||
let entry = match self.lock_state().get(id) {
|
||||
Some(e) if e.enabled => e.clone(),
|
||||
_ => {
|
||||
*guard = None;
|
||||
return Err(Error::Invalid(format!("module {id} is disabled")));
|
||||
}
|
||||
};
|
||||
if guard.is_none() {
|
||||
let bytes = std::fs::read(self.wasm_path(id))?;
|
||||
let manifest = Manifest::from_wasm(&bytes)?;
|
||||
|
||||
Reference in new issue
Block a user