use std::cell::{Cell, RefCell};
use std::ptr::NonNull;
use std::sync::Arc;
use std::time::Instant;
use ::rhai::{
AST, Array, Blob, Dynamic, Engine, EvalAltResult, ImmutableString, Map, NativeCallContext,
Position, Scope,
};
use crate::fingerprint::PortContext;
use crate::model::confidence::Confidence;
use crate::model::finding::{Excerpt, Finding, Reference};
use crate::record::wire;
use super::budget::{BudgetTrap, Denial, ModuleFault, RunOutcome};
use super::capability::{CapError, Capabilities, Capability, Grant};
use super::guest_patterns::guest_regex;
use super::runtime::{ComputeRuntime, LoadError, ModuleBody};
const MAX_CALL_LEVELS: usize = 32;
const PROGRESS_STRIDE: u64 = 8192;
const MAX_PARSE_DEPTH: usize = 64;
thread_local! {
static ACTIVE_CAPS: Cell<Option<NonNull<dyn Capabilities>>> = const { Cell::new(None) };
static ABORT: RefCell<Option<RunOutcome>> = const { RefCell::new(None) };
static RUN_DEADLINE: Cell<Option<Instant>> = const { Cell::new(None) };
}
struct ActiveRun {
previous_caps: Option<NonNull<dyn Capabilities>>,
previous_abort: Option<RunOutcome>,
previous_deadline: Option<Instant>,
}
impl ActiveRun {
fn new(caps: *mut dyn Capabilities, deadline: Instant) -> Option<Self> {
if ACTIVE_CAPS.with(|cell| cell.get().is_some()) {
return None;
}
let previous_caps = ACTIVE_CAPS.with(|cell| cell.replace(NonNull::new(caps)));
let previous_abort = ABORT.with(|cell| cell.borrow_mut().take());
let previous_deadline = RUN_DEADLINE.with(|cell| cell.replace(Some(deadline)));
Some(Self {
previous_caps,
previous_abort,
previous_deadline,
})
}
fn taken_abort(&self) -> Option<RunOutcome> {
ABORT.with(|cell| cell.borrow_mut().take())
}
}
impl Drop for ActiveRun {
fn drop(&mut self) {
ACTIVE_CAPS.with(|cell| cell.set(self.previous_caps));
ABORT.with(|cell| *cell.borrow_mut() = self.previous_abort.take());
RUN_DEADLINE.with(|cell| cell.set(self.previous_deadline));
}
}
fn with_capabilities<R>(f: impl FnOnce(&mut dyn Capabilities) -> R) -> Option<R> {
ACTIVE_CAPS.with(|cell| {
let mut caps = cell.get()?;
Some(f(unsafe { caps.as_mut() }))
})
}
pub struct RhaiModule {
ast: Arc<AST>,
}
pub struct RhaiInstance {
engine: Engine,
ast: Arc<AST>,
grant: Grant,
}
pub struct RhaiRuntime {
compiler: Engine,
}
impl RhaiRuntime {
pub fn new() -> Self {
let mut compiler = Engine::new();
compiler.set_max_expr_depths(MAX_PARSE_DEPTH, MAX_PARSE_DEPTH);
harden(&mut compiler);
Self { compiler }
}
}
impl Default for RhaiRuntime {
fn default() -> Self {
Self::new()
}
}
impl ComputeRuntime for RhaiRuntime {
type Module = RhaiModule;
type Instance = RhaiInstance;
fn load(&self, body: &ModuleBody) -> Result<Self::Module, LoadError> {
let ModuleBody::Rhai(source) = body;
let ast = self
.compiler
.compile(source)
.map_err(|error| LoadError::Compile(error.to_string()))?;
let has_entry = ast
.iter_functions()
.any(|function| function.name == "analyze" && function.params.len() == 2);
if !has_entry {
return Err(LoadError::Compile(
"the module must define `fn analyze(ctx, responses)`".to_string(),
));
}
Ok(RhaiModule { ast: Arc::new(ast) })
}
fn instantiate(
&self,
module: &Self::Module,
grant: &Grant,
) -> Result<Self::Instance, LoadError> {
let mut engine = Engine::new();
engine.on_print(|_| {});
engine.on_debug(|_, _, _| {});
engine.set_max_operations(grant.budget.fuel);
engine.set_max_string_size(grant.budget.max_memory);
engine.set_max_array_size(grant.budget.max_memory);
engine.set_max_map_size(grant.budget.max_memory);
engine.set_max_call_levels(MAX_CALL_LEVELS);
harden(&mut engine);
engine.on_progress(|operations| {
if operations % PROGRESS_STRIDE == 0
&& RUN_DEADLINE
.with(|cell| cell.get())
.is_some_and(|deadline| Instant::now() >= deadline)
{
Some(Dynamic::UNIT)
} else {
None
}
});
register_helpers(&mut engine);
engine.register_fn("now", capability_now);
if grant.speak {
engine.register_fn("speak", capability_speak);
}
if grant.resolve {
engine.register_fn("resolve", capability_resolve);
}
Ok(RhaiInstance {
engine,
ast: module.ast.clone(),
grant: grant.clone(),
})
}
fn run(
&self,
instance: &mut Self::Instance,
ctx: &PortContext,
responses: &[&[u8]],
caps: &mut dyn Capabilities,
) -> Result<Vec<Finding>, RunOutcome> {
let caps: *mut (dyn Capabilities + '_) = caps;
let caps: *mut (dyn Capabilities + 'static) = unsafe { std::mem::transmute(caps) };
let deadline = Instant::now() + instance.grant.budget.deadline;
let Some(active) = ActiveRun::new(caps, deadline) else {
return Err(RunOutcome::HostReentered);
};
let context = build_context(ctx);
let responses = build_responses(responses);
let mut scope = Scope::new();
let result = instance.engine.call_fn::<Dynamic>(
&mut scope,
&instance.ast,
"analyze",
(context, responses),
);
match result {
Ok(value) => collect_findings(value, &instance.grant),
Err(error) => match active.taken_abort() {
Some(outcome) => Err(outcome),
None => Err(classify(&error)),
},
}
}
}
fn register_helpers(engine: &mut Engine) {
engine.register_fn("text", |bytes: Blob| -> String {
bytes.iter().map(|&byte| byte as char).collect()
});
engine.register_fn("bytes", |string: ImmutableString| -> Blob {
string.chars().map(|c| c as u8).collect()
});
engine.register_fn("hex_encode", |bytes: Blob| -> String {
data_encoding::HEXLOWER.encode(&bytes)
});
engine.register_fn("hex_decode", |string: ImmutableString| -> Blob {
data_encoding::HEXLOWER_PERMISSIVE
.decode(string.as_bytes())
.unwrap_or_default()
});
engine.register_fn("b64_encode", |bytes: Blob| -> String {
data_encoding::BASE64.encode(&bytes)
});
engine.register_fn("b64_decode", |string: ImmutableString| -> Blob {
data_encoding::BASE64
.decode(string.as_bytes())
.unwrap_or_default()
});
engine.register_fn(
"json",
|ctx: NativeCallContext, source: ImmutableString| -> Dynamic {
let wrapped = format!("{{\"_\":{source}}}");
match ctx.engine().parse_json(&wrapped, false) {
Ok(mut map) => map.remove("_").unwrap_or(Dynamic::UNIT),
Err(_) => Dynamic::UNIT,
}
},
);
engine.register_fn(
"re_is_match",
|pattern: ImmutableString, text: ImmutableString| -> bool {
guest_regex(&pattern).is_some_and(|re| re.is_match(&text))
},
);
engine.register_fn(
"re_find",
|pattern: ImmutableString, text: ImmutableString| -> String {
guest_regex(&pattern)
.and_then(|re| re.find(&text).map(|m| m.as_str().to_string()))
.unwrap_or_default()
},
);
engine.register_fn(
"re_capture",
|pattern: ImmutableString, text: ImmutableString| -> String {
let Some(re) = guest_regex(&pattern) else {
return String::new();
};
re.captures(&text)
.and_then(|caps| caps.get(1).or_else(|| caps.get(0)))
.map_or(String::new(), |m| m.as_str().to_string())
},
);
engine.register_fn("http_response", |raw: Blob| -> Dynamic {
let Some(response) = super::http::parse_response(&raw) else {
return Dynamic::UNIT;
};
let mut map = Map::new();
map.insert("version".into(), response.version.into());
map.insert("status".into(), (i64::from(response.status)).into());
map.insert("reason".into(), response.reason.into());
let mut folded: Vec<(String, String)> = Vec::new();
for (name, value) in response.headers {
match folded.iter_mut().find(|(existing, _)| *existing == name) {
Some((_, current)) => {
current.push_str(", ");
current.push_str(&value);
}
None => folded.push((name, value)),
}
}
let mut headers = Map::new();
for (name, value) in folded {
headers.insert(name.into(), value.into());
}
map.insert("headers".into(), Dynamic::from(headers));
let body: String = response.body.iter().map(|&byte| byte as char).collect();
map.insert("body".into(), body.into());
Dynamic::from(map)
});
engine.register_fn("http_request", |spec: Map| -> Blob {
let string_field = |key: &str, default: &str| -> String {
spec.get(key)
.and_then(|value| value.clone().into_string().ok())
.unwrap_or_else(|| default.to_string())
};
let method = string_field("method", "GET");
let path = string_field("path", "/");
let host = string_field("host", "");
let headers: Vec<(String, String)> = spec
.get("headers")
.and_then(|value| value.clone().try_cast::<Map>())
.map(|map| {
map.into_iter()
.map(|(name, value)| {
(name.to_string(), value.into_string().unwrap_or_default())
})
.collect()
})
.unwrap_or_default();
let body: Vec<u8> = match spec.get("body") {
None => Vec::new(),
Some(value) => value.clone().try_cast::<Blob>().unwrap_or_else(|| {
value
.clone()
.into_string()
.map(String::into_bytes)
.unwrap_or_default()
}),
};
super::http::build_request(&method, &path, &host, &headers, &body)
});
}
fn harden(engine: &mut Engine) {
engine.disable_symbol("eval");
engine.set_module_resolver(::rhai::module_resolvers::DummyModuleResolver::new());
engine.register_fn("sleep", |_seconds: i64| -> Result<(), Box<EvalAltResult>> {
Err(disabled_symbol("sleep"))
});
engine.register_fn("sleep", |_seconds: f64| -> Result<(), Box<EvalAltResult>> {
Err(disabled_symbol("sleep"))
});
engine.register_fn("timestamp", || -> Result<Dynamic, Box<EvalAltResult>> {
Err(disabled_symbol("timestamp"))
});
}
fn disabled_symbol(name: &str) -> Box<EvalAltResult> {
Box::new(EvalAltResult::ErrorRuntime(
format!("`{name}` is not available to a detection module").into(),
Position::NONE,
))
}
fn capability_speak(bytes: Blob) -> Result<Blob, Box<EvalAltResult>> {
match with_capabilities(|caps| caps.speak(&bytes)) {
None => Err(runtime_error("a capability was called outside a run")),
Some(Ok(reply)) => Ok(reply),
Some(Err(error)) if error.is_fatal() => {
record_abort(outcome_for(&error, Capability::Speak));
Err(terminated())
}
Some(Err(error)) => Err(runtime_error(&error.to_string())),
}
}
fn capability_resolve(name: ImmutableString) -> Result<Array, Box<EvalAltResult>> {
match with_capabilities(|caps| caps.resolve(name.as_str())) {
None => Err(runtime_error("a capability was called outside a run")),
Some(Ok(addresses)) => Ok(addresses
.into_iter()
.map(|address| Dynamic::from(address.to_string()))
.collect()),
Some(Err(error)) if error.is_fatal() => {
record_abort(outcome_for(&error, Capability::Resolve));
Err(terminated())
}
Some(Err(error)) => Err(runtime_error(&error.to_string())),
}
}
fn capability_now() -> i64 {
with_capabilities(|caps| caps.now().millis() as i64).unwrap_or(0)
}
fn outcome_for(error: &CapError, capability: Capability) -> RunOutcome {
match error {
CapError::ByteBudgetExhausted => RunOutcome::BudgetExceeded(BudgetTrap::Bytes),
CapError::ConnectionBudgetExhausted => RunOutcome::BudgetExceeded(BudgetTrap::Connections),
CapError::Denied(reason) => RunOutcome::Denied(Denial {
capability,
reason: reason.clone(),
}),
CapError::OutOfDescriptors => RunOutcome::OutOfDescriptors,
other => RunOutcome::Faulted(ModuleFault::Runtime(other.to_string())),
}
}
fn record_abort(outcome: RunOutcome) {
ABORT.with(|cell| *cell.borrow_mut() = Some(outcome));
}
fn terminated() -> Box<EvalAltResult> {
Box::new(EvalAltResult::ErrorTerminated(
Dynamic::UNIT,
Position::NONE,
))
}
fn runtime_error(message: &str) -> Box<EvalAltResult> {
Box::new(EvalAltResult::ErrorRuntime(message.into(), Position::NONE))
}
fn classify(error: &EvalAltResult) -> RunOutcome {
match error {
EvalAltResult::ErrorTooManyOperations(_) => RunOutcome::BudgetExceeded(BudgetTrap::Fuel),
EvalAltResult::ErrorTerminated(_, _) => RunOutcome::BudgetExceeded(BudgetTrap::Deadline),
EvalAltResult::ErrorDataTooLarge(_, _) => RunOutcome::BudgetExceeded(BudgetTrap::Memory),
EvalAltResult::ErrorFunctionNotFound(name, _) if names_capability(name) => {
RunOutcome::Faulted(ModuleFault::Runtime(format!(
"the module named an ungranted capability: {name}"
)))
}
other => RunOutcome::Faulted(ModuleFault::Runtime(other.to_string())),
}
}
fn names_capability(signature: &str) -> bool {
signature.starts_with("speak")
|| signature.starts_with("resolve")
|| signature.starts_with("now")
}
fn build_context(ctx: &PortContext) -> Map {
let mut map = Map::new();
map.insert("port".into(), (i64::from(ctx.port)).into());
map.insert("protocol".into(), wire::protocol_name(ctx.protocol).into());
let addr = match ctx.addr {
Some(addr) => addr.ip().to_string().into(),
None => Dynamic::UNIT,
};
map.insert("addr".into(), addr);
let hostname = match &ctx.host_name {
Some(name) => name.as_str().into(),
None => Dynamic::UNIT,
};
map.insert("hostname".into(), hostname);
map
}
fn build_responses(responses: &[&[u8]]) -> Array {
responses
.iter()
.map(|payload| Dynamic::from_blob(payload.to_vec()))
.collect()
}
fn collect_findings(value: Dynamic, grant: &Grant) -> Result<Vec<Finding>, RunOutcome> {
if value.is_unit() {
return Ok(Vec::new());
}
if let Some(array) = value.clone().try_cast::<Array>() {
let mut findings = Vec::with_capacity(array.len());
for element in array {
let map = element
.try_cast::<Map>()
.ok_or_else(|| bad_output("each finding must be a map"))?;
findings.push(finding_from_map(&map, grant)?);
}
return Ok(findings);
}
if let Some(map) = value.try_cast::<Map>() {
return Ok(vec![finding_from_map(&map, grant)?]);
}
Err(bad_output(
"analyze must return a finding, an array of findings, or nothing",
))
}
fn finding_from_map(map: &Map, grant: &Grant) -> Result<Finding, RunOutcome> {
let severity = map_str(map, "severity")
.as_deref()
.and_then(wire::severity)
.ok_or_else(|| {
bad_output("a finding needs a severity: info, low, medium, high, or critical")
})?;
let summary = map_str(map, "summary")
.filter(|summary| !summary.trim().is_empty())
.ok_or_else(|| bad_output("a finding needs a non-empty summary"))?;
let title = map_str(map, "title")
.filter(|title| !title.trim().is_empty())
.unwrap_or_else(|| summary.clone());
let confidence = map_str(map, "confidence")
.as_deref()
.and_then(wire::confidence)
.unwrap_or(Confidence::Certain);
let mut finding = Finding::new(
grant.detection.clone(),
title,
severity,
confidence,
grant.class,
)
.map_err(|error| bad_output(&error.to_string()))?;
if let Some(text) = map_str(map, "excerpt").or_else(|| map_str(map, "detail")) {
finding = finding.with_excerpt(Excerpt::new(text));
}
if let Some(references) = map
.get("references")
.and_then(|d| d.clone().try_cast::<Array>())
{
for element in references {
if let Some(reference) = element
.try_cast::<Map>()
.and_then(|m| reference_from_map(&m))
{
finding = finding.with_reference(reference);
}
}
}
if let Some(remediation) =
map_str(map, "remediation").filter(|remediation| !remediation.trim().is_empty())
{
finding = finding.with_remediation(remediation);
}
Ok(finding)
}
fn reference_from_map(map: &Map) -> Option<Reference> {
if let Some(cve) = map_str(map, "cve") {
return Reference::cve(cve);
}
if let Some(cwe) = map_int(map, "cwe").filter(|cwe| (0..=i64::from(u32::MAX)).contains(cwe)) {
return Some(Reference::cwe(cwe as u32));
}
map_str(map, "url").map(Reference::url)
}
fn map_str(map: &Map, key: &str) -> Option<String> {
map.get(key)
.and_then(|value| value.clone().into_string().ok())
}
fn map_int(map: &Map, key: &str) -> Option<i64> {
map.get(key).and_then(|value| value.as_int().ok())
}
fn bad_output(message: &str) -> RunOutcome {
RunOutcome::Faulted(ModuleFault::BadOutput(message.to_string()))
}
#[cfg(test)]
mod tests {
use super::*;
use crate::detect::compute::{Budget, ScanInstant};
use crate::model::finding::{DetectionClass, DetectionId, Severity, Version};
use crate::model::port::Protocol;
use std::collections::VecDeque;
use std::net::IpAddr;
use std::time::Duration;
#[test]
fn a_second_run_on_one_thread_is_refused_before_it_can_alias() {
let mut caps = RecordedCaps::new(Vec::new());
let pointer: *mut dyn Capabilities = &mut caps;
let deadline = Instant::now() + Duration::from_secs(1);
let outer = ActiveRun::new(pointer, deadline);
assert!(outer.is_some(), "the first run installs");
assert!(
ActiveRun::new(pointer, deadline).is_none(),
"a second run on one thread would alias the first's borrow"
);
drop(outer);
assert!(
ActiveRun::new(pointer, deadline).is_some(),
"and the refusal lifts once the first run is over"
);
}
struct RecordedCaps {
replies: VecDeque<Result<Vec<u8>, CapError>>,
sent: Vec<Vec<u8>>,
clock: u64,
}
impl RecordedCaps {
fn new(replies: Vec<Result<Vec<u8>, CapError>>) -> Self {
Self {
replies: replies.into(),
sent: Vec::new(),
clock: 0,
}
}
}
impl Capabilities for RecordedCaps {
fn speak(&mut self, bytes: &[u8]) -> Result<Vec<u8>, CapError> {
self.sent.push(bytes.to_vec());
self.replies.pop_front().unwrap_or(Ok(Vec::new()))
}
fn resolve(&mut self, _name: &str) -> Result<Vec<IpAddr>, CapError> {
Ok(Vec::new())
}
fn now(&mut self) -> ScanInstant {
let millis = self.clock;
self.clock += 1;
ScanInstant::from_millis(millis)
}
}
fn budget() -> Budget {
Budget {
fuel: 1_000_000,
deadline: Duration::from_secs(2),
max_memory: 65_536,
max_bytes: 8_192,
max_connections: 4,
}
}
fn grant(class: DetectionClass, speak: bool) -> Grant {
Grant {
detection: DetectionId::new("test-detection", Version::new(1, 0, 0), "hash").unwrap(),
class,
budget: budget(),
speak,
resolve: false,
}
}
fn ctx(port: u16) -> PortContext {
PortContext {
port,
protocol: Protocol::Tcp,
addr: None,
tunnel: None,
speaks_http: false,
detection: crate::config::ServiceDetection::default(),
host_name: None,
}
}
fn run(
source: &str,
grant: Grant,
caps: &mut RecordedCaps,
) -> Result<Vec<Finding>, RunOutcome> {
let runtime = RhaiRuntime::new();
let module = runtime
.load(&ModuleBody::Rhai(source.to_string()))
.expect("the module compiles");
let mut instance = runtime
.instantiate(&module, &grant)
.expect("the module instantiates");
runtime.run(&mut instance, &ctx(6379), &[], caps)
}
#[test]
fn a_module_reads_the_host_name_a_target_named() {
let source = r#"
fn analyze(ctx, responses) {
let name = if ctx.hostname == () { "none" } else { ctx.hostname };
[ #{ severity: "info", summary: "asked for " + name } ]
}
"#;
let runtime = RhaiRuntime::new();
let module = runtime
.load(&ModuleBody::Rhai(source.to_string()))
.expect("the module compiles");
let summary = |ctx: &PortContext| {
let mut instance = runtime
.instantiate(&module, &grant(DetectionClass::Passive, false))
.expect("the module instantiates");
let findings = runtime
.run(&mut instance, ctx, &[], &mut RecordedCaps::new(Vec::new()))
.expect("a clean run");
findings[0].title().to_string()
};
let mut named = ctx(443);
named.host_name = Some("box.example".to_string());
assert_eq!(summary(&named), "asked for box.example");
assert_eq!(summary(&ctx(443)), "asked for none");
}
#[test]
fn a_module_speaks_reads_the_reply_and_returns_a_finding() {
let source = r#"
fn analyze(ctx, responses) {
let reply = speak(blob());
if reply.len() > 0 {
[ #{
severity: "high",
summary: "port " + ctx.port + " answered",
confidence: "probable",
references: [ #{ cwe: 306 } ],
} ]
} else {
[]
}
}
"#;
let mut caps = RecordedCaps::new(vec![Ok(b"# Server\r\n".to_vec())]);
let findings =
run(source, grant(DetectionClass::ActiveBenign, true), &mut caps).expect("a clean run");
assert_eq!(findings.len(), 1);
let finding = &findings[0];
assert_eq!(finding.severity(), Severity::High);
assert_eq!(finding.confidence(), Confidence::Probable);
assert_eq!(finding.title(), "port 6379 answered");
assert_eq!(finding.detection().id(), "test-detection");
assert_eq!(finding.detection().content_hash(), "hash");
assert!(
finding
.references()
.any(|r| matches!(r, Reference::Cwe(306)))
);
assert_eq!(caps.sent, vec![Vec::<u8>::new()]);
}
#[test]
fn the_pure_helpers_encode_and_decode_without_a_grant() {
let source = r#"
fn analyze(ctx, responses) {
let raw = b64_decode("aGk="); // "hi"
let as_hex = hex_encode(raw); // "6869"
let round = text(hex_decode(as_hex)); // "hi"
let built = bytes("AB"); // blob [0x41, 0x42]
[ #{
severity: "info",
summary: as_hex + " " + round + " " + b64_encode(built),
} ]
}
"#;
let mut caps = RecordedCaps::new(Vec::new());
let findings =
run(source, grant(DetectionClass::Passive, false), &mut caps).expect("a clean run");
assert_eq!(findings.len(), 1);
assert_eq!(findings[0].title(), "6869 hi QUI=");
}
#[test]
fn json_parses_an_object_an_array_and_reports_bad_input_as_unit() {
let source = r#"
fn analyze(ctx, responses) {
let obj = json("{\"version\":\"7.2.4\",\"tags\":[\"a\",\"b\"]}");
let arr = json("[10, 20, 30]");
let bad = json("<html>not json</html>");
[ #{
severity: "info",
summary: obj.version + " " + obj.tags[1] + " " + arr[2] + " " + (bad == ()),
} ]
}
"#;
let mut caps = RecordedCaps::new(Vec::new());
let findings =
run(source, grant(DetectionClass::Passive, false), &mut caps).expect("a clean run");
assert_eq!(findings[0].title(), "7.2.4 b 30 true");
}
#[test]
fn the_regex_helpers_test_find_and_capture() {
let source = r#"
fn analyze(ctx, responses) {
let body = "Server: nginx/1.25.3";
let ok = re_is_match("nginx", body);
let whole = re_find("nginx/[0-9.]+", body);
let ver = re_capture("nginx/([0-9.]+)", body);
let none = re_capture("apache/([0-9.]+)", body);
[ #{
severity: "info",
summary: "" + ok + " " + whole + " " + ver + " '" + none + "'",
} ]
}
"#;
let mut caps = RecordedCaps::new(Vec::new());
let findings =
run(source, grant(DetectionClass::Passive, false), &mut caps).expect("a clean run");
assert_eq!(findings[0].title(), "true nginx/1.25.3 1.25.3 ''");
}
#[test]
fn a_module_builds_a_request_and_reads_a_response_through_the_http_helpers() {
let source = r#"
fn analyze(ctx, responses) {
let request = http_request(#{
method: "GET",
path: "/",
host: "" + ctx.port,
headers: #{ "User-Agent": "zond" },
});
let reply = http_response(speak(request));
if reply == () { return []; }
if reply.status == 200 && reply.headers["server"] != () {
[ #{
severity: "info",
summary: "server is " + reply.headers.server + " body " + reply.body,
} ]
} else {
[]
}
}
"#;
let reply = b"HTTP/1.1 200 OK\r\nServer: Caddy\r\nContent-Length: 2\r\n\r\nhi".to_vec();
let mut caps = RecordedCaps::new(vec![Ok(reply)]);
let findings =
run(source, grant(DetectionClass::ActiveBenign, true), &mut caps).expect("a clean run");
assert_eq!(findings.len(), 1);
assert_eq!(findings[0].title(), "server is Caddy body hi");
let sent = String::from_utf8_lossy(&caps.sent[0]);
assert!(
sent.starts_with("GET / HTTP/1.1\r\n"),
"request line: {sent:?}"
);
assert!(
sent.contains("Host: 6379"),
"the seeded host reached the wire: {sent:?}"
);
assert!(
sent.contains("User-Agent: zond"),
"the header reached the wire: {sent:?}"
);
}
#[test]
fn an_uncompilable_pattern_matches_nothing_rather_than_faulting() {
let source = r#"
fn analyze(ctx, responses) {
let broken = re_is_match("(unclosed", "anything");
[ #{ severity: "info", summary: "" + broken } ]
}
"#;
let mut caps = RecordedCaps::new(Vec::new());
let findings =
run(source, grant(DetectionClass::Passive, false), &mut caps).expect("a clean run");
assert_eq!(findings[0].title(), "false");
}
#[test]
fn a_malformed_decode_is_an_empty_blob_not_a_fault() {
let source = r#"
fn analyze(ctx, responses) {
let decoded = b64_decode("not valid base64!!");
[ #{ severity: "info", summary: "len " + decoded.len() } ]
}
"#;
let mut caps = RecordedCaps::new(Vec::new());
let findings =
run(source, grant(DetectionClass::Passive, false), &mut caps).expect("a clean run");
assert_eq!(findings[0].title(), "len 0");
}
#[test]
fn a_module_that_computes_without_end_is_trapped_at_its_fuel_bound() {
let source = r#"
fn analyze(ctx, responses) {
let n = 0;
while true { n += 1; }
n
}
"#;
let mut grant = grant(DetectionClass::ActiveBenign, true);
grant.budget.fuel = 10_000;
let mut caps = RecordedCaps::new(vec![]);
let outcome = run(source, grant, &mut caps).expect_err("the loop is trapped");
assert_eq!(outcome, RunOutcome::BudgetExceeded(BudgetTrap::Fuel));
}
#[test]
fn a_passive_module_cannot_reach_the_network_because_speak_is_absent() {
let source = r#"
fn analyze(ctx, responses) {
speak(blob());
[]
}
"#;
let mut caps = RecordedCaps::new(vec![Ok(b"should never be reached".to_vec())]);
let outcome = run(source, grant(DetectionClass::Passive, false), &mut caps)
.expect_err("naming an ungranted capability faults");
assert!(matches!(
outcome,
RunOutcome::Faulted(ModuleFault::Runtime(_))
));
assert!(caps.sent.is_empty(), "a passive module reached the network");
}
#[test]
fn a_byte_budget_refusal_ends_the_run_and_the_module_cannot_catch_it() {
let source = r#"
fn analyze(ctx, responses) {
try { speak(blob()); } catch (err) { }
[ #{ severity: "low", summary: "the catch swallowed the trap" } ]
}
"#;
let mut caps = RecordedCaps::new(vec![Err(CapError::ByteBudgetExhausted)]);
let outcome = run(source, grant(DetectionClass::ActiveBenign, true), &mut caps)
.expect_err("a budget end is not catchable");
assert_eq!(outcome, RunOutcome::BudgetExceeded(BudgetTrap::Bytes));
}
#[test]
fn the_same_recorded_inputs_yield_identical_findings() {
let source = r#"
fn analyze(ctx, responses) {
let reply = speak(blob());
[ #{ severity: "medium", summary: "answered at " + now(), detail: reply } ]
}
"#;
let mut first_caps = RecordedCaps::new(vec![Ok(b"banner".to_vec())]);
let first = run(
source,
grant(DetectionClass::ActiveBenign, true),
&mut first_caps,
)
.expect("a clean run");
let mut second_caps = RecordedCaps::new(vec![Ok(b"banner".to_vec())]);
let second = run(
source,
grant(DetectionClass::ActiveBenign, true),
&mut second_caps,
)
.expect("a clean run");
assert_eq!(
first, second,
"a pure function of its inputs did not replay"
);
}
#[test]
fn eval_is_refused_at_load() {
let runtime = RhaiRuntime::new();
let source = "fn analyze(ctx, responses) { let x = eval(\"1\"); [] }".to_string();
assert!(
matches!(
runtime.load(&ModuleBody::Rhai(source)),
Err(LoadError::Compile(_))
),
"a module naming `eval` was not refused at load"
);
}
#[test]
fn a_module_cannot_import_a_file_that_exists() {
let dir = std::env::temp_dir().join(format!("zond-rhai-import-{}", std::process::id()));
std::fs::create_dir_all(&dir).expect("a scratch directory");
let smuggled = dir.join("smuggled.rhai");
std::fs::write(&smuggled, "fn smuggled_value() { 4242 }\n").expect("a module on disk");
let path = dir.join("smuggled").to_string_lossy().replace('\\', "/");
let source = format!(
r#"
import "{path}" as m;
fn analyze(ctx, responses) {{
[ #{{ severity: "high", summary: "value " + m::smuggled_value(),
confidence: "probable" }} ]
}}
"#
);
let mut caps = RecordedCaps::new(Vec::new());
let outcome = run(&source, grant(DetectionClass::Passive, false), &mut caps);
let _ = std::fs::remove_dir_all(&dir);
assert!(
matches!(outcome, Err(RunOutcome::Faulted(ModuleFault::Runtime(_)))),
"a module imported a file that exists on disk: {outcome:?}"
);
}
#[test]
fn sleep_and_timestamp_fault_rather_than_parking_or_reading_the_clock() {
for call in ["sleep(1);", "sleep(1.5);", "let t = timestamp();"] {
let source = format!("fn analyze(ctx, responses) {{ {call} [] }}");
let mut caps = RecordedCaps::new(Vec::new());
let outcome = run(&source, grant(DetectionClass::Passive, false), &mut caps);
assert!(
matches!(outcome, Err(RunOutcome::Faulted(ModuleFault::Runtime(_)))),
"`{call}` was not faulted: {outcome:?}"
);
}
}
#[test]
fn a_passive_module_that_runs_without_end_is_bounded_by_its_wall_clock() {
let source = r#"
fn analyze(ctx, responses) {
let n = 0;
loop { n += 1; }
[]
}
"#;
let mut grant = grant(DetectionClass::Passive, false);
grant.budget.fuel = u64::MAX; grant.budget.deadline = Duration::from_millis(50);
let started = std::time::Instant::now();
let mut caps = RecordedCaps::new(Vec::new());
let outcome = run(source, grant, &mut caps);
assert_eq!(
outcome,
Err(RunOutcome::BudgetExceeded(BudgetTrap::Deadline)),
"a passive run past its deadline was not trapped as a deadline"
);
assert!(
started.elapsed() < Duration::from_secs(5),
"the deadline did not stop the run promptly: {:?}",
started.elapsed()
);
}
#[test]
fn a_run_is_not_reachable_from_another_thread() {
let mut caps = RecordedCaps::new(Vec::new());
let pointer: *mut dyn Capabilities = &mut caps;
let deadline = Instant::now() + Duration::from_secs(1);
let guard = ActiveRun::new(pointer, deadline).expect("the first run installs");
assert!(
!std::thread::spawn(|| ACTIVE_CAPS.with(|cell| cell.get().is_some()))
.join()
.expect("the thread ran"),
"another thread could see this run's capabilities"
);
assert!(
std::thread::spawn(|| {
let mut other = RecordedCaps::new(Vec::new());
let other_pointer: *mut dyn Capabilities = &mut other;
ActiveRun::new(other_pointer, Instant::now() + Duration::from_secs(1)).is_some()
})
.join()
.expect("the thread ran"),
"a thread with its own borrow must not be refused"
);
drop(guard);
}
#[test]
fn a_panicking_run_restores_every_thread_local() {
let outcome = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
let mut caps = RecordedCaps::new(Vec::new());
let pointer: *mut dyn Capabilities = &mut caps;
let _guard =
ActiveRun::new(pointer, Instant::now() + Duration::from_secs(1)).expect("installs");
ABORT.with(|cell| *cell.borrow_mut() = Some(RunOutcome::HostReentered));
panic!("the guest exploded");
}));
assert!(
outcome.is_err(),
"the panic has to reach here to prove anything"
);
assert!(ACTIVE_CAPS.with(|cell| cell.get().is_none()));
assert!(ABORT.with(|cell| cell.borrow().is_none()));
assert!(RUN_DEADLINE.with(|cell| cell.get().is_none()));
}
}