Merge pull request #8964 from dotCooCoo/feat/plugin-manifest-section

Plug-ins: read the manifest from a custom section before running any code
This commit is contained in:
BFlat
2026-11-24 16:03:53 +07:00
committed by GitHub
36 changed files with 561 additions and 42 deletions
+5 -1
View File
@@ -10,6 +10,9 @@ use crate::{Error, Result};
/// Longest manifest the host reads.
pub const MAX_MANIFEST_BYTES: usize = 64 * 1024;
/// The name of the custom section a module may carry its manifest in, so the host reads it
/// without running any of the module's code.
pub const MANIFEST_SECTION: &str = "vc_manifest";
/// Most parameters a plug-in may declare.
pub const MAX_PARAMS: usize = 256;
/// Most parameters outside groups (`group`): a dialog of more is sorted into sections.
@@ -299,7 +302,8 @@ impl ParamSpec {
}
}
/// The manifest a plug-in returns from `vc_manifest` (UTF-8 JSON).
/// The manifest a plug-in carries in its [`MANIFEST_SECTION`] custom section or returns from
/// `vc_manifest` (UTF-8 JSON).
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Manifest {
+134 -26
View File
@@ -1,13 +1,13 @@
//! The wasmi host: loading, instantiating and calling a plug-in under resource limits.
use wasmi::{
Config, CustomFuelCosts, EnforcedLimits, Engine, Instance, Memory, Module, Store, StoreLimitsBuilder, TypedFunc, TypedResumableCall, Val,
WasmParams, WasmResults,
Config, CustomFuelCosts, EnforcedLimits, Engine, ExternType, Instance, Memory, Module, Store, StoreLimitsBuilder, TypedFunc, TypedResumableCall,
Val, ValType, WasmParams, WasmResults,
};
use wasmparser::{Validator, WasmFeatures};
use crate::host::{self, Bridge, Deadline, Host, Report, Run};
use crate::manifest::{MAX_MANIFEST_BYTES, Manifest};
use crate::manifest::{MANIFEST_SECTION, MAX_MANIFEST_BYTES, Manifest};
use crate::permissions::Permission;
use crate::{Error, Kind, Result};
@@ -219,10 +219,96 @@ fn wasm_err(e: wasmi::Error) -> Error {
/// `vc_run(input_ptr, input_len, params_ptr, params_len) -> len << 32 | ptr` (negative: error).
type RunArgs = (i32, i32, i32, i32);
/// The manifest in the module's [`MANIFEST_SECTION`] custom section, or `None` when it has none.
/// A module with more than one is refused, and so is a section longer than [`MAX_MANIFEST_BYTES`],
/// which [`Manifest::parse`] checks before it decodes the bytes. The manifest in the section must
/// give the ABI version as `abi`, in place of the `vc_abi_version` export.
fn section_manifest(module: &Module) -> Result<Option<Manifest>> {
let mut sections = module.custom_sections().filter(|s| s.name() == MANIFEST_SECTION);
let Some(section) = sections.next() else {
return Ok(None);
};
if sections.next().is_some() {
return Err(Error::Manifest(format!("the module has more than one `{MANIFEST_SECTION}` custom section")));
}
let manifest = Manifest::parse(section.data())?;
// `Manifest::parse` has checked that the section is UTF-8 JSON of at most `MAX_MANIFEST_BYTES`.
let abi = serde_json::from_slice::<serde_json::Value>(section.data()).ok().and_then(|v| v.get("abi").and_then(serde_json::Value::as_i64));
if abi != Some(i64::from(ABI_VERSION)) {
return Err(Error::Abi(format!(
"the manifest in the `{MANIFEST_SECTION}` custom section must give `abi` as {ABI_VERSION}, the ABI version this host implements"
)));
}
Ok(Some(manifest))
}
/// Most tables a module may define: the store an instance runs in holds no more.
const MAX_TABLES: u64 = 4;
/// Most elements a table may hold: the store an instance runs in holds no more.
const MAX_TABLE_ELEMENTS: u64 = 100_000;
/// The number of tables the module in `bytes` defines and the largest initial size among them,
/// from its table section, or `None` when its sections can't be read. `bytes` is a module
/// [`check_features`] has validated.
fn table_sizes(bytes: &[u8]) -> Option<(u64, u64)> {
for payload in wasmparser::Parser::new(0).parse_all(bytes) {
if let wasmparser::Payload::TableSection(reader) = payload.ok()? {
let count = u64::from(reader.count());
let mut largest = 0;
for table in reader {
largest = largest.max(table.ok()?.ty.initial);
}
return Some((count, largest));
}
}
Some((0, 0))
}
/// Checks the tables the module in `bytes` defines against the store's limits ([`MAX_TABLES`]
/// tables of at most [`MAX_TABLE_ELEMENTS`] elements), which instantiating it checks. The host
/// offers no tables to import, so the module defines every table it has.
fn check_tables(bytes: &[u8]) -> Result<()> {
let Some((count, largest)) = table_sizes(bytes) else {
return Err(Error::Module("the module's table section could not be read".into()));
};
if count > MAX_TABLES || largest > MAX_TABLE_ELEMENTS {
return Err(Error::Limit(format!(
"table budget (the module defines {count} tables, the largest with {largest} elements; limit {MAX_TABLES} tables of {MAX_TABLE_ELEMENTS} elements)"
)));
}
Ok(())
}
/// Checks the exports a run needs without instantiating `module`: its memory as `memory`, whose
/// initial size fits in `max_memory_bytes`, and `vc_alloc` and `vc_run` with the ABI's types.
fn check_exports(module: &Module, max_memory_bytes: usize) -> Result<()> {
use ValType::{I32, I64};
let export = |name: &str| module.exports().find(|e| e.name() == name).map(|e| e.ty().clone());
let Some(ExternType::Memory(memory)) = export("memory") else {
return Err(Error::Abi("the module must export its linear memory as `memory`".into()));
};
// Pages are 64 KiB: the engine's configuration leaves custom page sizes off.
let initial = memory.minimum().saturating_mul(1 << 16);
if initial > max_memory_bytes as u64 {
return Err(Error::Limit(format!("memory budget (the module's initial memory is {initial} bytes, limit {max_memory_bytes})")));
}
let wanted: [(&str, &[ValType], &[ValType], &str); 2] =
[("vc_alloc", &[I32], &[I32], "(param i32) (result i32)"), ("vc_run", &[I32, I32, I32, I32], &[I64], "(param i32 i32 i32 i32) (result i64)")];
for (name, params, results, signature) in wanted {
if !matches!(export(name), Some(ExternType::Func(f)) if f.params() == params && f.results() == results) {
return Err(Error::Abi(format!("the module must export `{name}` with the type {signature}")));
}
}
Ok(())
}
impl Plugin {
/// Validates and loads a module: checks the ABI version, the exports and reads the manifest, and
/// checks that each host import it asks for is one the host offers ([`crate::host::IMPORTS`])
/// and its manifest allows. In Safe Mode nothing is loaded ([`Error::SafeMode`]).
/// Validates and loads a module: reads the manifest, checks that each host import it asks for
/// is one the host offers ([`crate::host::IMPORTS`]) and its manifest allows, and checks the
/// exports. A module that carries its manifest in a [`MANIFEST_SECTION`] custom section is
/// checked without being instantiated, so none of its code runs; one without that section is
/// instantiated to call `vc_abi_version` and `vc_manifest`. In Safe Mode nothing is loaded
/// ([`Error::SafeMode`]).
pub fn load(bytes: &[u8], limits: Limits) -> Result<Plugin> {
crate::safe_mode::check()?;
if bytes.len() > limits.max_module_bytes {
@@ -243,22 +329,31 @@ impl Plugin {
let imports = host::check_imports(&module)?;
let hash = crate::permissions::sha256_hex(bytes);
let mut p = Plugin { manifest: Manifest::placeholder(), engine, module, limits, size: bytes.len(), hash, source: None, serial: 0 };
let deadline = Deadline::new(p.limits.wall_time_ms);
// The manifest isn't read yet: every host import is linked, what it reports is dropped and
// there is no storage to reach.
let mut live = p.instantiate(Run::new("", false, false, deadline), &crate::permissions::ALL, &mut Report::default())?;
let version: TypedFunc<(), i32> = live.func("vc_abi_version")?;
let v = p.call(&mut live, &version, (), p.limits.fuel_base, &deadline)?;
if v != ABI_VERSION {
return Err(Error::Abi(format!("vc_abi_version returned {v}; this host implements version {ABI_VERSION}")));
}
let manifest: TypedFunc<(), i64> = live.func("vc_manifest")?;
let packed = p.call(&mut live, &manifest, (), p.limits.fuel_base, &deadline)?;
let text = live.read_packed(packed, "vc_manifest", MAX_MANIFEST_BYTES).map_err(|e| match e {
Error::Limit(_) => Error::Manifest(format!("manifest is too long (limit {MAX_MANIFEST_BYTES} bytes)")),
e => e,
})?;
p.manifest = Manifest::parse(&text)?;
let live = match section_manifest(&p.module)? {
Some(manifest) => {
p.manifest = manifest;
None
}
None => {
let deadline = Deadline::new(p.limits.wall_time_ms);
// The manifest isn't read yet: every host import is linked, what it reports is
// dropped and there is no storage to reach.
let mut live = p.instantiate(Run::new("", false, false, deadline), &crate::permissions::ALL, &mut Report::default())?;
let version: TypedFunc<(), i32> = live.func("vc_abi_version")?;
let v = p.call(&mut live, &version, (), p.limits.fuel_base, &deadline)?;
if v != ABI_VERSION {
return Err(Error::Abi(format!("vc_abi_version returned {v}; this host implements version {ABI_VERSION}")));
}
let manifest: TypedFunc<(), i64> = live.func("vc_manifest")?;
let packed = p.call(&mut live, &manifest, (), p.limits.fuel_base, &deadline)?;
let text = live.read_packed(packed, "vc_manifest", MAX_MANIFEST_BYTES).map_err(|e| match e {
Error::Limit(_) => Error::Manifest(format!("manifest is too long (limit {MAX_MANIFEST_BYTES} bytes)")),
e => e,
})?;
p.manifest = Manifest::parse(&text)?;
Some(live)
}
};
host::check_granted(&p.manifest, &imports)?;
// A heavy filter's runs get the larger budget the host allows for one, which the host
// lets the user allow or refuse before installing it.
@@ -267,8 +362,16 @@ impl Plugin {
p.limits.wall_time_ms = p.limits.wall_time_ms.max(p.limits.heavy_wall_time_ms);
}
// The other exports must exist with the right types.
live.func::<i32, i32>("vc_alloc")?;
live.func::<RunArgs, i64>("vc_run")?;
match live {
Some(live) => {
live.func::<i32, i32>("vc_alloc")?;
live.func::<RunArgs, i64>("vc_run")?;
}
None => {
check_exports(&p.module, p.limits.max_memory_bytes)?;
check_tables(bytes)?;
}
}
Ok(p)
}
@@ -315,8 +418,13 @@ impl Plugin {
/// A new instance for `run`, with the host imports of the permissions `granted` linked. When the
/// module's start function fails, what it reported through the host imports goes to `report`.
fn instantiate(&self, run: Run, granted: &[Permission], report: &mut Report) -> Result<Live> {
let limits =
StoreLimitsBuilder::new().memory_size(self.limits.max_memory_bytes).memories(1).tables(4).table_elements(100_000).instances(1).build();
let limits = StoreLimitsBuilder::new()
.memory_size(self.limits.max_memory_bytes)
.memories(1)
.tables(MAX_TABLES as usize)
.table_elements(MAX_TABLE_ELEMENTS as usize)
.instances(1)
.build();
let mut store = Store::new(&self.engine, Host { limits, run });
store.limiter(|h| &mut h.limits);
// The start function (if any) runs on one slice of fuel: it runs before `call` can check
+54 -6
View File
@@ -7,12 +7,26 @@ const OUTPUT_AT: usize = 0x1_0000;
/// `s` as the body of a WAT string literal (every byte that isn't a letter, digit or space
/// escaped).
pub fn string(s: &str) -> String {
s.bytes().map(|b| if b.is_ascii_alphanumeric() || b == b' ' { char::from(b).to_string() } else { format!("\\{b:02x}") }).collect()
bytes(s.as_bytes())
}
/// `data` as the body of a WAT string literal, every byte that isn't an ASCII letter, digit or
/// space escaped (so it may hold any bytes, UTF-8 or not).
pub fn bytes(data: &[u8]) -> String {
data.iter().map(|&b| if b.is_ascii_alphanumeric() || b == b' ' { char::from(b).to_string() } else { format!("\\{b:02x}") }).collect()
}
/// `vc_alloc`, which grows memory by whole pages, so its blocks never overlap data segments.
const ALLOC: &str = r#"(func (export "vc_alloc") (param $n i32) (result i32) (local $old i32)
(local.set $old (memory.grow (i32.shr_u (i32.add (local.get $n) (i32.const 65535)) (i32.const 16))))
(if (result i32) (i32.eq (local.get $old) (i32.const -1)) (then (i32.const 0)) (else (i32.mul (local.get $old) (i32.const 65536)))))"#;
/// A plug-in module: `manifest` (JSON), a `vc_run` whose body is `run` (parameters `$in $il $pp
/// $pl`, result i64), extra module fields `extra` and `pages` of initial memory. `vc_alloc` grows
/// memory by whole pages, so its blocks never overlap data segments.
/// $pl`, result i64), extra module fields `extra` and `pages` of initial memory (at least 1: with
/// none, the first `vc_alloc` block would start at 0, which the host refuses). `vc_alloc` grows
/// memory by whole pages, so its blocks never overlap data segments. The manifest comes from the
/// `vc_manifest` export, which the host calls when it loads the module ([`sectioned`] carries it in
/// a custom section instead).
pub fn module(manifest: &str, run: &str, extra: &str, pages: u32) -> String {
format!(
r#"(module
@@ -21,16 +35,50 @@ pub fn module(manifest: &str, run: &str, extra: &str, pages: u32) -> String {
(data (i32.const 16) "{data}")
(func (export "vc_abi_version") (result i32) (i32.const 1))
(func (export "vc_manifest") (result i64) (i64.or (i64.shl (i64.const {len}) (i64.const 32)) (i64.const 16)))
(func (export "vc_alloc") (param $n i32) (result i32) (local $old i32)
(local.set $old (memory.grow (i32.shr_u (i32.add (local.get $n) (i32.const 65535)) (i32.const 16))))
(if (result i32) (i32.eq (local.get $old) (i32.const -1)) (then (i32.const 0)) (else (i32.mul (local.get $old) (i32.const 65536)))))
{ALLOC}
(func (export "vc_run") (param $in i32) (param $il i32) (param $pp i32) (param $pl i32) (result i64)
{run}))"#,
pages = pages.max(1),
data = string(manifest),
len = manifest.len(),
)
}
/// A custom section named `name` holding `data`, as a module field.
pub fn custom_section(name: &str, data: &[u8]) -> String {
format!(r#"(@custom "{}" "{}")"#, string(name), bytes(data))
}
/// A plug-in module like [`module`] that carries `manifest` in its `vc_manifest` custom section
/// ([`crate::manifest::MANIFEST_SECTION`]) and exports only `memory`, `vc_alloc` and `vc_run`: the
/// host reads the manifest without running any of its code. The host loads it only when `manifest`
/// gives `"abi": 1`. It has `pages` of initial memory, at least 1, as [`module`] has.
pub fn sectioned(manifest: &str, run: &str, extra: &str, pages: u32) -> String {
format!(
r#"(module
{section}
{extra}
(memory (export "memory") {pages})
{ALLOC}
(func (export "vc_run") (param $in i32) (param $il i32) (param $pp i32) (param $pl i32) (result i64)
{run}))"#,
section = custom_section(crate::manifest::MANIFEST_SECTION, manifest.as_bytes()),
pages = pages.max(1),
)
}
/// `module` (a module in WebAssembly text that starts with `(module`, after any white space) with
/// the module field `field` added first, after the module's `$name` when it has one, such as a
/// [`custom_section`]; `None` when `module` does not start with `(module`.
pub fn with_field(module: &str, field: &str) -> Option<String> {
let rest = module.trim_start().strip_prefix("(module")?;
let Some(id) = rest.trim_start().strip_prefix('$') else {
return Some(format!("(module\n {field}{rest}"));
};
let (name, rest) = id.split_at(id.find(|c: char| c.is_whitespace() || c == '(' || c == ')').unwrap_or(id.len()));
Some(format!("(module ${name}\n {field}{rest}"))
}
/// A `vc_run` body returning the input unchanged.
pub const ECHO: &str = "(i64.or (i64.shl (i64.extend_i32_u (local.get $il)) (i64.const 32)) (i64.extend_i32_u (local.get $in)))";