Skip to main content

ruso_runtime/runtime/
executor.rs

1use std::collections::HashMap;
2use std::sync::Arc;
3use std::time::{Duration, Instant};
4
5use regex::Regex;
6use reqwest::Client;
7
8use crate::contract::{EvidenceKind, ExtractSource};
9use crate::runtime::binary;
10use crate::runtime::bytecode::{BytecodeProgram, Instr};
11use crate::runtime::context::{Context, LoopFrame, LoopState, VariableValue};
12use crate::runtime::dns::{resolve_host, run_dns_probe};
13use crate::runtime::duration::parse_duration;
14use crate::runtime::error::RuntimeError;
15use crate::runtime::http::{build_client, execute_http};
16use crate::runtime::interpolate::interpolate;
17use crate::runtime::matcher::{CompiledMatcherRegex, evaluate, evaluate_all, evaluate_any};
18use crate::runtime::port_cache::{PortCache, PortCheck, scan_target_host_port};
19use crate::runtime::report::Report;
20use crate::runtime::response::ProbeResponse;
21use crate::runtime::response::SocketResponse;
22use crate::runtime::session::{
23    ProbeSession, open_tcp_session, open_udp_session, read_opts_from_spec,
24};
25use crate::runtime::socket::{
26    exchange_tcp, exchange_udp, tcp_session_exchange, udp_session_exchange,
27};
28use crate::runtime::spec::ProbeKind;
29use crate::runtime::spec::SocketProbeSpec;
30
31/// Runtime configuration for an [`Executor`]: the target base URL plus the
32/// network, TLS, and safety knobs. Use [`ExecutorConfig::default`] and override
33/// the fields you care about.
34#[derive(Debug, Clone)]
35pub struct ExecutorConfig {
36    /// Base URL HTTP probe `path`s are joined onto, and the source of the
37    /// `scan_host` / `scan_port` / `scan_url` variables (the CLI `--target`).
38    pub base_url: String,
39    /// Connect timeout for HTTP requests and TCP/UDP/DNS probes.
40    pub default_timeout: Duration,
41    /// Per-read I/O timeout for socket probes (TCP/UDP/DNS). Falls back to
42    /// `default_timeout` if not explicitly tuned.
43    pub read_timeout: Duration,
44    /// Maximum HTTP response body size in bytes. Larger responses are
45    /// truncated at this boundary to bound memory use against malicious
46    /// or misconfigured targets.
47    pub max_response_bytes: usize,
48    /// Follow HTTP redirects (per-probe `follow_redirect` overrides this).
49    pub follow_redirect: bool,
50    /// Verify TLS server certificates. Default is `true`; set to `false`
51    /// (CLI `--insecure`) only for explicitly trusted scan environments —
52    /// otherwise the scanner is exposed to MITM that can plant findings
53    /// or read in-flight credentials.
54    pub verify_ssl: bool,
55    /// Optional proxy URL for HTTP probes (e.g. `http://127.0.0.1:8080`).
56    pub proxy: Option<String>,
57    /// Wall-clock budget for a single script execution. `None` disables.
58    /// Defaults to 5 minutes so a hostile/buggy bytecode (deep loops, long
59    /// `sleep`s, etc.) cannot pin a tokio worker.
60    pub max_script_duration: Option<Duration>,
61    /// How many times to retry an HTTP probe that fails with a *transient*
62    /// transport error (connection reset, connect/read timeout) before giving
63    /// up. `0` disables. A probe driven by the script's own `retry` directive
64    /// is exempt — the author controls retries there. Defaults to `2`.
65    pub http_retries: u32,
66}
67
68impl Default for ExecutorConfig {
69    fn default() -> Self {
70        Self {
71            base_url: String::new(),
72            default_timeout: Duration::from_secs(30),
73            read_timeout: Duration::from_secs(10),
74            max_response_bytes: 10 * 1024 * 1024, // 10 MiB
75            follow_redirect: true,
76            verify_ssl: true,
77            proxy: None,
78            max_script_duration: Some(Duration::from_secs(300)),
79            http_retries: 2,
80        }
81    }
82}
83
84/// Executes a compiled program against a target. Construct one with
85/// [`from_bytes`](Executor::from_bytes), [`from_bytecode`](Executor::from_bytecode),
86/// or [`from_program`](Executor::from_program), then call
87/// [`run`](Executor::run).
88pub struct Executor {
89    config: ExecutorConfig,
90    /// Program shared via `Arc` so the same compiled script can run against
91    /// many targets without cloning the bytecode (string pool, payload pool,
92    /// matcher pool, etc.) for each.
93    program: Arc<BytecodeProgram>,
94    client: Client,
95    /// Pre-compiled regexes aligned by index with `program.matchers`. Built
96    /// once at executor construction so per-run / per-loop-iteration matcher
97    /// dispatch never pays the regex compile cost again.
98    compiled_matcher_regex: Arc<[CompiledMatcherRegex]>,
99    /// Pre-compiled regexes for evidence rules that carry a regex, aligned with
100    /// `program.evidence`. `None` for non-regex evidence kinds.
101    compiled_evidence_regex: Arc<[Option<Regex>]>,
102    /// Pre-compiled regexes for `ExtractSource::Body { regex: Some(...) }`,
103    /// aligned with `program.extracts`.
104    compiled_extract_regex: Arc<[Option<Regex>]>,
105}
106
107/// The outcome of one [`Executor::run`]: whether a finding was produced, plus
108/// the report, port-check details, and final variable state.
109#[derive(Debug, Clone)]
110pub struct ExecutionResult {
111    /// The script ran to completion without an aborting error.
112    pub success: bool,
113    /// True when `finalize_finding()` produced a finding (metadata + matchers passed).
114    pub detected: bool,
115    /// Check did not run because a required socket port was closed (see `skip_reason`).
116    pub skipped: bool,
117    /// Human-readable reason the check was skipped, if `skipped`.
118    pub skip_reason: Option<String>,
119    /// Port probes performed before execution (empty for HTTP-only checks).
120    pub port_checks: Vec<PortCheck>,
121    /// The findings report (empty unless `detected`).
122    pub report: Report,
123    /// Final value of every variable set during the run.
124    pub variables: HashMap<String, VariableValue>,
125    /// The check's metadata, echoed for convenience.
126    pub metadata: crate::runtime::spec::CheckMetadata,
127}
128
129impl Executor {
130    /// Decode a raw `.rbc` byte buffer and build an executor from it.
131    /// Fails with [`RuntimeError::Bytecode`] if the bytes are not a valid
132    /// program for this runtime version.
133    pub fn from_bytes(config: ExecutorConfig, bytes: &[u8]) -> Result<Self, RuntimeError> {
134        let program = binary::decode(bytes).map_err(RuntimeError::Bytecode)?;
135        Self::from_bytecode(config, program)
136    }
137
138    /// Build an executor from an already-decoded [`BytecodeProgram`]. Prefer
139    /// [`from_program`](Executor::from_program) when running one program
140    /// against many targets.
141    pub fn from_bytecode(
142        config: ExecutorConfig,
143        program: BytecodeProgram,
144    ) -> Result<Self, RuntimeError> {
145        Self::from_program(config, Arc::new(program))
146    }
147
148    /// Construct an executor sharing a pre-built `Arc<BytecodeProgram>`.
149    ///
150    /// Prefer this over [`Executor::from_bytecode`] when a single compiled
151    /// script is run against many targets: the program (and the regex caches
152    /// derived from it) are cloned via `Arc` rather than deep-copied.
153    pub fn from_program(
154        config: ExecutorConfig,
155        program: Arc<BytecodeProgram>,
156    ) -> Result<Self, RuntimeError> {
157        let client = build_client(
158            Some(config.default_timeout),
159            config.follow_redirect,
160            config.verify_ssl,
161            config.proxy.as_deref(),
162        )?;
163        let compiled_matcher_regex: Arc<[CompiledMatcherRegex]> = program
164            .matchers
165            .iter()
166            .map(CompiledMatcherRegex::compile)
167            .collect::<Result<Vec<_>, _>>()?
168            .into();
169        let compiled_evidence_regex: Arc<[Option<Regex>]> = program
170            .evidence
171            .iter()
172            .map(|kind| match kind {
173                EvidenceKind::Body { pattern, .. }
174                | EvidenceKind::Response { pattern, .. }
175                | EvidenceKind::Header { pattern, .. } => match pattern {
176                    Some(p) => Regex::new(p).map(Some),
177                    None => Ok(None),
178                },
179            })
180            .collect::<Result<Vec<_>, regex::Error>>()?
181            .into();
182        let compiled_extract_regex: Arc<[Option<Regex>]> = program
183            .extracts
184            .iter()
185            .map(|src| match src {
186                ExtractSource::Body {
187                    regex: Some(pattern),
188                    ..
189                } => Regex::new(pattern).map(Some),
190                _ => Ok(None),
191            })
192            .collect::<Result<Vec<_>, regex::Error>>()?
193            .into();
194        Ok(Self {
195            config,
196            program,
197            client,
198            compiled_matcher_regex,
199            compiled_evidence_regex,
200            compiled_extract_regex,
201        })
202    }
203
204    /// The program this executor will run, as decoded.
205    pub fn bytecode(&self) -> &BytecodeProgram {
206        &self.program
207    }
208
209    /// Execute the program against the configured target and return the
210    /// [`ExecutionResult`]. Probes that must reach a closed port short-circuit
211    /// to a `skipped` result; an `assert`/`fail` or transport error returns
212    /// `Err`.
213    pub async fn run(&self) -> Result<ExecutionResult, RuntimeError> {
214        self.run_bytecode().await
215    }
216
217    fn client_for_http(
218        &self,
219        spec: &crate::runtime::spec::HttpRequestSpec,
220    ) -> Result<Client, RuntimeError> {
221        let verify_ssl = spec.verify_ssl.unwrap_or(self.config.verify_ssl);
222        let follow_redirect = spec.follow_redirect.unwrap_or(self.config.follow_redirect);
223        if verify_ssl == self.config.verify_ssl && follow_redirect == self.config.follow_redirect {
224            return Ok(self.client.clone());
225        }
226        build_client(
227            Some(self.config.default_timeout),
228            follow_redirect,
229            verify_ssl,
230            self.config.proxy.as_deref(),
231        )
232    }
233
234    async fn run_bytecode(&self) -> Result<ExecutionResult, RuntimeError> {
235        let cache = PortCache::global();
236        let (port_checks, closed) = cache
237            .check_for_run(&self.program.spec, &self.config.base_url)
238            .await;
239        if let Some((host, port)) = closed {
240            return Ok(ExecutionResult {
241                success: true,
242                detected: false,
243                skipped: true,
244                skip_reason: Some(format!("port {host}:{port} closed")),
245                port_checks,
246                report: Report::default(),
247                variables: HashMap::new(),
248                metadata: self.program.spec.metadata.clone(),
249            });
250        }
251
252        let mut context = Context::from_spec(&self.program.spec);
253        inject_scan_target_variables(&mut context, &self.config.base_url);
254        let mut pc: usize = 0;
255        let started_at = Instant::now();
256        let budget = self.config.max_script_duration;
257
258        while pc < self.program.code.len() {
259            if let Some(limit) = budget
260                && started_at.elapsed() > limit
261            {
262                return Err(RuntimeError::Other(format!(
263                    "script execution exceeded budget of {:?}",
264                    limit
265                )));
266            }
267            match &self.program.code[pc] {
268                Instr::Set { name, value } => {
269                    let name = &self.program.strings[*name as usize];
270                    let value = &self.program.strings[*value as usize];
271                    context.set_variable(name.clone(), interpolate(value, &context.variables)?);
272                    pc += 1;
273                }
274                Instr::SetList { name, start, len } => {
275                    let name = &self.program.strings[*name as usize];
276                    let values = self.program.strings
277                        [*start as usize..(*start + *len as u32) as usize]
278                        .iter()
279                        .map(|value| interpolate(value, &context.variables))
280                        .collect::<Result<Vec<_>, _>>()?;
281                    context.set_list_variable(name.clone(), values);
282                    pc += 1;
283                }
284                Instr::Send { probe, payload } => {
285                    let name = &self.program.strings[*probe as usize];
286                    let payload_override =
287                        payload.map(|id| self.program.payloads[id as usize].clone());
288                    tracing::trace!(probe = %name, "send");
289                    self.send_probe(
290                        name,
291                        payload_override,
292                        self.config.http_retries,
293                        &mut context,
294                    )
295                    .await?;
296                    pc += 1;
297                }
298                Instr::Match(matcher) => {
299                    self.apply_match(*matcher as usize, &mut context)?;
300                    pc += 1;
301                }
302                Instr::MatchAll { start, len } => {
303                    self.apply_match_all(*start as usize, *len as usize, &mut context)?;
304                    pc += 1;
305                }
306                Instr::MatchAny { start, len } => {
307                    self.apply_match_any(*start as usize, *len as usize, &mut context)?;
308                    pc += 1;
309                }
310                Instr::Assert(matcher) => {
311                    self.require_assert(*matcher as usize, &context)?;
312                    pc += 1;
313                }
314                Instr::Extract { name, source } => {
315                    if context.matched {
316                        let name = &self.program.strings[*name as usize];
317                        let source_idx = *source as usize;
318                        let source = &self.program.extracts[source_idx];
319                        self.extract(name, source, source_idx, &mut context)?;
320                    }
321                    pc += 1;
322                }
323                Instr::IfMatch { matcher, else_pc } => {
324                    if !context.matched || !self.matches_idx(*matcher as usize, &context)? {
325                        pc = *else_pc as usize;
326                    } else {
327                        pc += 1;
328                    }
329                }
330                Instr::ForList {
331                    item,
332                    start,
333                    len,
334                    end_pc,
335                } => {
336                    let item = self.program.strings[*item as usize].clone();
337                    let values = self.program.strings
338                        [*start as usize..(*start + *len as u32) as usize]
339                        .iter()
340                        .map(|value| interpolate(value, &context.variables))
341                        .collect::<Result<Vec<_>, _>>()?;
342                    pc = self.enter_foreach(&mut context, item, values, pc, *end_pc as usize);
343                }
344                Instr::ForVar { item, list, end_pc } => {
345                    let item = self.program.strings[*item as usize].clone();
346                    let list_name = &self.program.strings[*list as usize];
347                    let values = match context.variables.get(list_name) {
348                        Some(VariableValue::List(values)) => values.clone(),
349                        Some(VariableValue::String(_)) => {
350                            return Err(RuntimeError::Other(format!(
351                                "variable {list_name} is not a list"
352                            )));
353                        }
354                        None => Vec::new(),
355                    };
356                    pc = self.enter_foreach(&mut context, item, values, pc, *end_pc as usize);
357                }
358                Instr::LoopBack => pc = self.step_loop_back(&mut context)?,
359                Instr::Break => pc = self.step_break(&mut context)?,
360                Instr::Save { from, to } => {
361                    let from = &self.program.strings[*from as usize];
362                    let to = &self.program.strings[*to as usize];
363                    context.alias_response(from, to);
364                    pc += 1;
365                }
366                Instr::Evidence(kind) => {
367                    if !context.matched {
368                        pc += 1;
369                        continue;
370                    }
371                    let kind_idx = *kind as usize;
372                    let kind = &self.program.evidence[kind_idx];
373                    let text = self.collect_evidence(kind, kind_idx, &context)?;
374                    context.evidence.push(text);
375                    pc += 1;
376                }
377                Instr::Retry { probe, count } => {
378                    let name = &self.program.strings[*probe as usize];
379                    self.retry_send(name, *count, &mut context).await?;
380                    pc += 1;
381                }
382                Instr::RetryDelay(value) => {
383                    let value = &self.program.strings[*value as usize];
384                    context.retry_delay = Some(parse_duration(value)?);
385                    pc += 1;
386                }
387                Instr::Sleep(value) => {
388                    let value = &self.program.strings[*value as usize];
389                    tokio::time::sleep(parse_duration(value)?).await;
390                    pc += 1;
391                }
392                Instr::Stop => {
393                    tracing::warn!("stop");
394                    context.emit_finding = false;
395                    break;
396                }
397                Instr::Exit => {
398                    tracing::info!("exit");
399                    break;
400                }
401                Instr::Fail => {
402                    tracing::error!("fail");
403                    context.failed = true;
404                    return Err(RuntimeError::Flow("fail".into()));
405                }
406                Instr::Continue => pc = self.step_continue(&context)?,
407            }
408        }
409
410        context.close_sessions();
411        context.finalize_finding();
412
413        Ok(ExecutionResult {
414            success: !context.failed,
415            detected: !context.report.findings.is_empty(),
416            skipped: false,
417            skip_reason: None,
418            port_checks,
419            report: context.report,
420            variables: context.variables,
421            metadata: context.metadata,
422        })
423    }
424
425    /// Enter a `for` loop: bind `item` to the first value and push a loop
426    /// frame, or skip the body entirely when the list is empty. Returns the
427    /// next program counter — the loop body (`pc + 1`) or `end_pc`.
428    fn enter_foreach(
429        &self,
430        context: &mut Context,
431        item: String,
432        values: Vec<String>,
433        pc: usize,
434        end_pc: usize,
435    ) -> usize {
436        if values.is_empty() {
437            return end_pc;
438        }
439        let previous = context.variables.get(&item).cloned();
440        context.set_variable(item.clone(), values[0].clone());
441        context.loop_stack.push(LoopFrame {
442            state: LoopState::ForEach {
443                item,
444                values,
445                index: 0,
446                previous,
447            },
448            head_pc: pc + 1,
449            continue_pc: end_pc.saturating_sub(1),
450            end_pc,
451        });
452        pc + 1
453    }
454
455    /// Advance the innermost loop on `loop_back`: bind the next item and jump
456    /// to the loop head, or — when exhausted — pop the frame, restore the
457    /// shadowed variable, and continue past the loop. Returns the next pc.
458    fn step_loop_back(&self, context: &mut Context) -> Result<usize, RuntimeError> {
459        // Decide the action while borrowing the frame, then mutate `context`
460        // after that borrow ends (the two can't overlap).
461        enum Next {
462            Jump {
463                item: String,
464                value: String,
465                head_pc: usize,
466            },
467            End {
468                item: String,
469                previous: Option<VariableValue>,
470                end_pc: usize,
471            },
472        }
473        let next = {
474            let frame = context
475                .loop_stack
476                .last_mut()
477                .ok_or_else(|| RuntimeError::Other("loop_back outside loop".into()))?;
478            let LoopState::ForEach {
479                item,
480                values,
481                index,
482                previous,
483            } = &mut frame.state;
484            if *index + 1 < values.len() {
485                *index += 1;
486                Next::Jump {
487                    item: item.clone(),
488                    value: values[*index].clone(),
489                    head_pc: frame.head_pc,
490                }
491            } else {
492                Next::End {
493                    item: item.clone(),
494                    previous: previous.clone(),
495                    end_pc: frame.end_pc,
496                }
497            }
498        };
499        Ok(match next {
500            Next::Jump {
501                item,
502                value,
503                head_pc,
504            } => {
505                context.set_variable(item, value);
506                head_pc
507            }
508            Next::End {
509                item,
510                previous,
511                end_pc,
512            } => {
513                context.loop_stack.pop();
514                context.restore_or_remove_variable(item, previous);
515                end_pc
516            }
517        })
518    }
519
520    /// `break`: pop the innermost loop frame, restore its shadowed variable,
521    /// and return the program counter just past the loop (`end_pc`).
522    fn step_break(&self, context: &mut Context) -> Result<usize, RuntimeError> {
523        let frame = context
524            .loop_stack
525            .pop()
526            .ok_or_else(|| RuntimeError::Other("break outside loop".into()))?;
527        let LoopState::ForEach { item, previous, .. } = frame.state;
528        context.restore_or_remove_variable(item, previous);
529        Ok(frame.end_pc)
530    }
531
532    /// `continue`: jump to the innermost loop's `loop_back` (its `continue_pc`).
533    fn step_continue(&self, context: &Context) -> Result<usize, RuntimeError> {
534        Ok(context
535            .loop_stack
536            .last()
537            .ok_or_else(|| RuntimeError::Other("continue outside loop".into()))?
538            .continue_pc)
539    }
540
541    fn interpolate_socket_spec(
542        &self,
543        spec: &SocketProbeSpec,
544        context: &Context,
545    ) -> Result<SocketProbeSpec, RuntimeError> {
546        let payload = spec
547            .payload
548            .as_ref()
549            .map(|bytes| {
550                if let Ok(text) = std::str::from_utf8(bytes) {
551                    interpolate(text, &context.variables).map(|value| value.into_bytes())
552                } else {
553                    Ok(bytes.clone())
554                }
555            })
556            .transpose()?;
557
558        Ok(SocketProbeSpec {
559            host: interpolate(&spec.host, &context.variables)?,
560            port: spec.port,
561            payload,
562            tls: spec.tls,
563            session: spec.session,
564            read_max: spec.read_max,
565            read_idle_ms: spec.read_idle_ms,
566        })
567    }
568
569    #[tracing::instrument(level = "trace", skip(self, context), fields(probe = name))]
570    async fn send_probe(
571        &self,
572        name: &str,
573        payload_override: Option<Vec<u8>>,
574        retries: u32,
575        context: &mut Context,
576    ) -> Result<(), RuntimeError> {
577        let probe = self
578            .program
579            .spec
580            .probes
581            .get(name)
582            .ok_or_else(|| RuntimeError::UnknownTarget(name.to_string()))?
583            .clone();
584
585        // `retry_delay` is the wait *between* retry attempts (used only in
586        // `retry_send` below). Earlier revisions piped it in here as the
587        // connect timeout, which made a `retry_delay 1s` directive silently
588        // shrink every subsequent probe's connect timeout to 1s.
589        let timeout = self.config.default_timeout;
590
591        let response = match probe {
592            ProbeKind::Http(spec) => {
593                let client = self.client_for_http(&spec)?;
594                let http = execute_http(
595                    &client,
596                    &self.config.base_url,
597                    &spec,
598                    &context.variables,
599                    self.config.max_response_bytes,
600                    retries,
601                )
602                .await?;
603                ProbeResponse::Http(http)
604            }
605            ProbeKind::Dns(spec) => {
606                let mut spec = self.interpolate_socket_spec(&spec, context)?;
607                if let Some(p) = payload_override {
608                    spec.payload = Some(p);
609                }
610                if spec.is_dns_resolver_mode() {
611                    ProbeResponse::DnsResolve(resolve_host(&spec.host).await?)
612                } else {
613                    ProbeResponse::Socket(
614                        run_dns_probe(&spec, timeout, self.config.read_timeout).await?,
615                    )
616                }
617            }
618            ProbeKind::Tcp(spec) => {
619                let spec = self.interpolate_socket_spec(&spec, context)?;
620                let port = spec
621                    .port
622                    .ok_or_else(|| RuntimeError::Other("tcp probe requires port".to_string()))?;
623                let payload = payload_override.or_else(|| spec.payload.clone());
624                ProbeResponse::Socket(
625                    self.exchange_tcp_probe(
626                        name,
627                        &spec,
628                        port,
629                        payload.as_deref(),
630                        timeout,
631                        context,
632                    )
633                    .await?,
634                )
635            }
636            ProbeKind::Udp(spec) => {
637                let spec = self.interpolate_socket_spec(&spec, context)?;
638                let port = spec
639                    .port
640                    .ok_or_else(|| RuntimeError::Other("udp probe requires port".to_string()))?;
641                let payload = payload_override.or_else(|| spec.payload.clone());
642                ProbeResponse::Socket(
643                    self.exchange_udp_probe(
644                        name,
645                        &spec,
646                        port,
647                        payload.as_deref(),
648                        timeout,
649                        context,
650                    )
651                    .await?,
652                )
653            }
654        };
655
656        log_probe_response(name, &response);
657
658        let append_session = probe_session_enabled(name, &self.program.spec);
659        if append_session
660            && let (ProbeResponse::Socket(chunk), Some(ProbeResponse::Socket(existing))) =
661                (&response, context.responses.get(name))
662        {
663            let mut merged = existing.clone();
664            merged.data.extend_from_slice(&chunk.data);
665            context.store_response(name, ProbeResponse::Socket(merged));
666            return Ok(());
667        }
668        context.store_response(name, response);
669        Ok(())
670    }
671
672    async fn exchange_tcp_probe(
673        &self,
674        name: &str,
675        spec: &SocketProbeSpec,
676        port: u16,
677        payload: Option<&[u8]>,
678        timeout: Duration,
679        context: &mut Context,
680    ) -> Result<SocketResponse, RuntimeError> {
681        let read = read_opts_from_spec(spec);
682        let io_timeout = self.config.read_timeout;
683
684        if spec.session {
685            if let Some(ProbeSession::Tcp(session)) = context.sessions.get_mut(name) {
686                let data = tcp_session_exchange(session, payload, &read, io_timeout).await?;
687                return Ok(SocketResponse {
688                    host: spec.host.clone(),
689                    port,
690                    data,
691                });
692            }
693            let mut session =
694                open_tcp_session(&spec.host, port, spec.tls, self.config.verify_ssl, timeout)
695                    .await?;
696            let data = tcp_session_exchange(&mut session, payload, &read, io_timeout).await?;
697            context
698                .sessions
699                .insert(name.to_string(), ProbeSession::Tcp(session));
700            return Ok(SocketResponse {
701                host: spec.host.clone(),
702                port,
703                data,
704            });
705        }
706
707        let mut send_spec = spec.clone();
708        send_spec.payload = payload.map(|p| p.to_vec());
709        exchange_tcp(
710            &send_spec.host,
711            port,
712            &send_spec,
713            self.config.verify_ssl,
714            timeout,
715            io_timeout,
716        )
717        .await
718    }
719
720    async fn exchange_udp_probe(
721        &self,
722        name: &str,
723        spec: &SocketProbeSpec,
724        port: u16,
725        payload: Option<&[u8]>,
726        timeout: Duration,
727        context: &mut Context,
728    ) -> Result<SocketResponse, RuntimeError> {
729        let read = read_opts_from_spec(spec);
730        let io_timeout = self.config.read_timeout;
731
732        if spec.tls {
733            return Err(RuntimeError::Other("tls is not supported for udp".into()));
734        }
735
736        if spec.session {
737            if let Some(ProbeSession::Udp(socket)) = context.sessions.get(name) {
738                let data = udp_session_exchange(socket, payload, &read, io_timeout).await?;
739                return Ok(SocketResponse {
740                    host: spec.host.clone(),
741                    port,
742                    data,
743                });
744            }
745            let socket = open_udp_session(&spec.host, port, timeout).await?;
746            let data = udp_session_exchange(&socket, payload, &read, io_timeout).await?;
747            context
748                .sessions
749                .insert(name.to_string(), ProbeSession::Udp(socket));
750            return Ok(SocketResponse {
751                host: spec.host.clone(),
752                port,
753                data,
754            });
755        }
756
757        exchange_udp(&spec.host, port, payload, spec, timeout, io_timeout).await
758    }
759
760    async fn retry_send(
761        &self,
762        name: &str,
763        count: u32,
764        context: &mut Context,
765    ) -> Result<(), RuntimeError> {
766        let delay = context.retry_delay.unwrap_or(Duration::from_secs(1));
767        let mut last_error = None;
768
769        for attempt in 0..count {
770            if attempt > 0 {
771                tokio::time::sleep(delay).await;
772            }
773            // 0 auto-retries: the script's own `retry` directive controls
774            // re-sends here, so the transport layer must not multiply attempts
775            // underneath it.
776            match self.send_probe(name, None, 0, context).await {
777                Ok(()) => return Ok(()),
778                Err(err) => last_error = Some(err),
779            }
780        }
781
782        Err(last_error
783            .unwrap_or_else(|| RuntimeError::Other(format!("retry send failed for {name}"))))
784    }
785
786    fn apply_match(&self, matcher_idx: usize, context: &mut Context) -> Result<(), RuntimeError> {
787        if !context.matched {
788            return Ok(());
789        }
790        let matcher = &self.program.matchers[matcher_idx];
791        if !self.matches_idx(matcher_idx, context)? {
792            tracing::trace!(target = %matcher.field.target, ?matcher.predicate, "match failed");
793            context.matched = false;
794        } else {
795            tracing::trace!(target = %matcher.field.target, ?matcher.predicate, "match ok");
796        }
797        Ok(())
798    }
799
800    fn apply_match_all(
801        &self,
802        start: usize,
803        len: usize,
804        context: &mut Context,
805    ) -> Result<(), RuntimeError> {
806        if !context.matched {
807            return Ok(());
808        }
809        let matchers = &self.program.matchers[start..start + len];
810        let compiled = &self.compiled_matcher_regex[start..start + len];
811        if !evaluate_all(matchers, compiled, &context.responses)? {
812            tracing::trace!(count = len, "match all failed");
813            context.matched = false;
814        } else {
815            tracing::trace!(count = len, "match all ok");
816        }
817        Ok(())
818    }
819
820    fn apply_match_any(
821        &self,
822        start: usize,
823        len: usize,
824        context: &mut Context,
825    ) -> Result<(), RuntimeError> {
826        if !context.matched {
827            return Ok(());
828        }
829        let matchers = &self.program.matchers[start..start + len];
830        let compiled = &self.compiled_matcher_regex[start..start + len];
831        if !evaluate_any(matchers, compiled, &context.responses)? {
832            tracing::trace!(count = len, "match any failed");
833            context.matched = false;
834        } else {
835            tracing::trace!(count = len, "match any ok");
836        }
837        Ok(())
838    }
839
840    fn require_assert(&self, matcher_idx: usize, context: &Context) -> Result<(), RuntimeError> {
841        if !context.matched {
842            return Ok(());
843        }
844        if self.matches_idx(matcher_idx, context)? {
845            return Ok(());
846        }
847        let matcher = &self.program.matchers[matcher_idx];
848        let detail = format!("target {}", matcher.field.target);
849        Err(RuntimeError::assert_failed(matcher, detail))
850    }
851
852    fn matches_idx(&self, matcher_idx: usize, context: &Context) -> Result<bool, RuntimeError> {
853        let matcher = &self.program.matchers[matcher_idx];
854        let response = context
855            .response(&matcher.field.target)
856            .ok_or_else(|| RuntimeError::UnknownTarget(matcher.field.target.clone()))?;
857        evaluate(matcher, response, &self.compiled_matcher_regex[matcher_idx])
858    }
859
860    fn extract(
861        &self,
862        name: &str,
863        source: &ExtractSource,
864        source_idx: usize,
865        context: &mut Context,
866    ) -> Result<(), RuntimeError> {
867        let value = match source {
868            ExtractSource::Body { target, regex } => {
869                let response = context
870                    .response(target)
871                    .ok_or_else(|| RuntimeError::UnknownTarget(target.clone()))?;
872                let http = response
873                    .as_http()
874                    .map_err(|_| RuntimeError::WrongProbeKind {
875                        name: target.clone(),
876                    })?;
877                match regex {
878                    Some(_) => {
879                        let compiled = self.compiled_extract_regex[source_idx]
880                            .as_ref()
881                            .ok_or_else(|| {
882                                RuntimeError::Other(
883                                    "extract regex missing pre-compiled entry".into(),
884                                )
885                            })?;
886                        extract_with_compiled(&http.body, compiled)?
887                    }
888                    None => http.body.clone(),
889                }
890            }
891            ExtractSource::Header {
892                target,
893                name: header,
894            } => {
895                let response = context
896                    .response(target)
897                    .ok_or_else(|| RuntimeError::UnknownTarget(target.clone()))?;
898                let http = response
899                    .as_http()
900                    .map_err(|_| RuntimeError::WrongProbeKind {
901                        name: target.clone(),
902                    })?;
903                // Empty-string and missing-header used to collapse into the
904                // same "empty result" error. Distinguish them: a present but
905                // empty header is a legitimate value to capture; only an
906                // absent header is an extraction failure.
907                match http
908                    .headers
909                    .iter()
910                    .find(|(key, _)| key.eq_ignore_ascii_case(header))
911                {
912                    Some((_, value)) => value.clone(),
913                    None => {
914                        return Err(RuntimeError::ExtractFailed {
915                            name: name.to_string(),
916                            reason: format!("header `{header}` not present"),
917                        });
918                    }
919                }
920            }
921        };
922
923        // Body extracts: an empty extract is still a failure (the regex
924        // matched zero characters). Header extracts that resolved to an
925        // empty value have already returned above; that path is preserved.
926        if matches!(source, ExtractSource::Body { .. }) && value.is_empty() {
927            return Err(RuntimeError::ExtractFailed {
928                name: name.to_string(),
929                reason: "empty result".into(),
930            });
931        }
932
933        tracing::trace!(variable = %name, "extracted");
934        context.set_variable(name, value);
935        Ok(())
936    }
937
938    fn collect_evidence(
939        &self,
940        kind: &EvidenceKind,
941        kind_idx: usize,
942        context: &Context,
943    ) -> Result<String, RuntimeError> {
944        // Resolve the explicit source to its raw string, plus the optional
945        // regex and a label for error messages.
946        let (raw, pattern, label, target): (String, &Option<String>, String, &str) = match kind {
947            EvidenceKind::Body { target, pattern } => {
948                let response = context
949                    .response(target)
950                    .ok_or_else(|| RuntimeError::UnknownTarget(target.clone()))?;
951                let http = response.as_http().map_err(|_| {
952                    RuntimeError::Other(format!(
953                        "evidence {target}.body requires an http probe; use {target}.response for socket/dns"
954                    ))
955                })?;
956                (http.body.clone(), pattern, format!("{target}.body"), target)
957            }
958            EvidenceKind::Response { target, pattern } => {
959                let response = context
960                    .response(target)
961                    .ok_or_else(|| RuntimeError::UnknownTarget(target.clone()))?;
962                (
963                    evidence_haystack(response),
964                    pattern,
965                    format!("{target}.response"),
966                    target,
967                )
968            }
969            EvidenceKind::Header {
970                target,
971                name,
972                pattern,
973            } => {
974                let response = context
975                    .response(target)
976                    .ok_or_else(|| RuntimeError::UnknownTarget(target.clone()))?;
977                let http = response.as_http().map_err(|_| {
978                    RuntimeError::Other(format!("evidence {target}.header requires an http probe"))
979                })?;
980                let value = http
981                    .headers
982                    .iter()
983                    .find(|(key, _)| key.eq_ignore_ascii_case(name))
984                    .map(|(_, value)| value.clone())
985                    .ok_or_else(|| {
986                        RuntimeError::Other(format!(
987                            "evidence header `{name}` on {target} not present"
988                        ))
989                    })?;
990                (
991                    value,
992                    pattern,
993                    format!("{target}.header \"{name}\""),
994                    target,
995                )
996            }
997        };
998        let _ = target;
999        match pattern {
1000            None => Ok(crate::util::truncate_str(&raw, 500)),
1001            Some(p) => {
1002                let compiled =
1003                    self.compiled_evidence_regex[kind_idx]
1004                        .as_ref()
1005                        .ok_or_else(|| {
1006                            RuntimeError::Other("evidence regex missing pre-compiled entry".into())
1007                        })?;
1008                extract_with_compiled(&raw, compiled).map_err(|_| {
1009                    RuntimeError::Other(format!("evidence regex on {label} did not match: {p}"))
1010                })
1011            }
1012        }
1013    }
1014}
1015
1016fn inject_scan_target_variables(context: &mut Context, base_url: &str) {
1017    if let Some((host, port)) = scan_target_host_port(base_url) {
1018        context.set_variable("scan_host", host);
1019        context.set_variable("scan_port", port.to_string());
1020    }
1021    if !base_url.is_empty() {
1022        context.set_variable("scan_url", base_url.to_string());
1023    }
1024}
1025
1026fn evidence_haystack(response: &ProbeResponse) -> String {
1027    match response {
1028        ProbeResponse::Http(http) => http.body.clone(),
1029        ProbeResponse::DnsResolve(dns) => dns.answers.join(" "),
1030        // Socket data is bytes; evidence is human-facing, so a lossy decode is
1031        // intentional here. Matching elsewhere still operates on raw bytes.
1032        ProbeResponse::Socket(sock) => sock.data_lossy().into_owned(),
1033    }
1034}
1035
1036fn probe_session_enabled(name: &str, spec: &crate::runtime::spec::ProgramSpec) -> bool {
1037    spec.probes.get(name).is_some_and(|kind| match kind {
1038        ProbeKind::Tcp(s) | ProbeKind::Udp(s) | ProbeKind::Dns(s) => s.session,
1039        ProbeKind::Http(_) => false,
1040    })
1041}
1042
1043/// Run a pre-compiled regex against `body`, returning the first capture group
1044/// (or the full match if there is no capture). Compiled once at executor init
1045/// rather than on every call site.
1046fn extract_with_compiled(body: &str, regex: &Regex) -> Result<String, RuntimeError> {
1047    let captures = regex
1048        .captures(body)
1049        .ok_or_else(|| RuntimeError::ExtractFailed {
1050            name: "regex".into(),
1051            reason: format!("pattern not found: {}", regex.as_str()),
1052        })?;
1053    let matched = captures
1054        .get(1)
1055        .or_else(|| captures.get(0))
1056        .map(|value| value.as_str().to_string())
1057        .unwrap_or_default();
1058    if matched.is_empty() {
1059        return Err(RuntimeError::ExtractFailed {
1060            name: "regex".into(),
1061            reason: format!("empty capture for: {}", regex.as_str()),
1062        });
1063    }
1064    Ok(matched)
1065}
1066
1067fn log_probe_response(name: &str, response: &ProbeResponse) {
1068    match response {
1069        ProbeResponse::Http(http) => {
1070            tracing::trace!(
1071                probe = name,
1072                status = http.status,
1073                elapsed_ms = http.elapsed.as_millis() as u64,
1074                body_bytes = http.body.len(),
1075                "http response"
1076            );
1077        }
1078        ProbeResponse::DnsResolve(dns) => {
1079            tracing::trace!(
1080                probe = name,
1081                host = %dns.host,
1082                answers = dns.answers.len(),
1083                "dns resolve"
1084            );
1085        }
1086        ProbeResponse::Socket(sock) => {
1087            tracing::trace!(
1088                probe = name,
1089                host = %sock.host,
1090                port = sock.port,
1091                data_bytes = sock.data.len(),
1092                "socket response"
1093            );
1094        }
1095    }
1096}
1097
1098#[cfg(test)]
1099mod tests {
1100    use super::*;
1101    use crate::contract::{
1102        CmpOp, CmpValue, FieldKind, MatchPredicate, QualifiedField, QualifiedMatch, Severity,
1103    };
1104    use crate::runtime::bytecode::BytecodeProgram;
1105    use crate::runtime::spec::{CheckMetadata, ProgramSpec};
1106
1107    fn metadata_only_bytecode() -> BytecodeProgram {
1108        BytecodeProgram {
1109            spec: ProgramSpec {
1110                probes: Default::default(),
1111                metadata: CheckMetadata {
1112                    name: Some("Metadata only".into()),
1113                    severity: Some(Severity::Low),
1114                    ..CheckMetadata::default()
1115                },
1116            },
1117            code: vec![],
1118            strings: vec![],
1119            payloads: vec![],
1120            matchers: vec![],
1121            extracts: vec![],
1122            evidence: vec![],
1123        }
1124    }
1125
1126    #[tokio::test]
1127    async fn run_fail_opcode_returns_error() {
1128        let bytecode = BytecodeProgram {
1129            spec: ProgramSpec {
1130                probes: Default::default(),
1131                metadata: CheckMetadata::default(),
1132            },
1133            code: vec![Instr::Fail],
1134            strings: vec![],
1135            payloads: vec![],
1136            matchers: vec![],
1137            extracts: vec![],
1138            evidence: vec![],
1139        };
1140        let config = ExecutorConfig {
1141            base_url: "http://127.0.0.1".into(),
1142            ..ExecutorConfig::default()
1143        };
1144        let executor = Executor::from_bytecode(config, bytecode).unwrap();
1145        assert!(executor.run().await.is_err());
1146    }
1147
1148    #[tokio::test]
1149    async fn match_without_send_returns_unknown_target() {
1150        let bytecode = BytecodeProgram {
1151            spec: ProgramSpec {
1152                probes: Default::default(),
1153                metadata: CheckMetadata::default(),
1154            },
1155            code: vec![Instr::Match(0)],
1156            strings: vec![],
1157            payloads: vec![],
1158            matchers: vec![QualifiedMatch {
1159                field: QualifiedField {
1160                    target: "home".into(),
1161                    kind: FieldKind::Status,
1162                },
1163                predicate: MatchPredicate::Compare {
1164                    op: CmpOp::Eq,
1165                    value: CmpValue::Number(200),
1166                },
1167            }],
1168            extracts: vec![],
1169            evidence: vec![],
1170        };
1171        let config = ExecutorConfig {
1172            base_url: "http://127.0.0.1".into(),
1173            ..ExecutorConfig::default()
1174        };
1175        let executor = Executor::from_bytecode(config, bytecode).unwrap();
1176        let err = executor.run().await.expect_err("match without prior send");
1177        assert!(matches!(err, RuntimeError::UnknownTarget(_)));
1178    }
1179
1180    #[tokio::test]
1181    async fn metadata_only_can_emit_finding_without_network() {
1182        let config = ExecutorConfig {
1183            base_url: "http://127.0.0.1".into(),
1184            ..ExecutorConfig::default()
1185        };
1186        let executor = Executor::from_bytecode(config, metadata_only_bytecode()).unwrap();
1187        assert!(executor.bytecode().code.is_empty());
1188        let result = executor.run().await.expect("metadata run");
1189        assert!(result.detected);
1190        assert_eq!(result.report.findings[0].name, "Metadata only");
1191    }
1192
1193    /// The wall-clock budget is checked at instruction boundaries, so a script
1194    /// with many steps must abort once it runs past the budget rather than
1195    /// executing them all. (A long sequence of short sleeps stands in for any
1196    /// long-running script now that the unbounded `repeat` loop is gone.)
1197    #[tokio::test]
1198    async fn script_budget_aborts_a_long_run() {
1199        let bytecode = BytecodeProgram {
1200            spec: ProgramSpec {
1201                probes: Default::default(),
1202                metadata: CheckMetadata::default(),
1203            },
1204            // strings[0] = "10ms" per sleep; 200 of them (~2s) far exceed the
1205            // 50ms budget, so the boundary check fires after a handful.
1206            code: vec![Instr::Sleep(0); 200],
1207            strings: vec!["10ms".into()],
1208            payloads: vec![],
1209            matchers: vec![],
1210            extracts: vec![],
1211            evidence: vec![],
1212        };
1213        let config = ExecutorConfig {
1214            base_url: "http://127.0.0.1".into(),
1215            // Tight budget so the test finishes quickly.
1216            max_script_duration: Some(Duration::from_millis(50)),
1217            ..ExecutorConfig::default()
1218        };
1219        let executor = Executor::from_bytecode(config, bytecode).unwrap();
1220        let err = executor.run().await.expect_err("budget should fire");
1221        let msg = err.to_string();
1222        assert!(msg.contains("budget"), "expected budget error, got: {msg}");
1223    }
1224
1225    /// Build a `for x in ["a", "b", "c"] { <body> }` program. `body` is the
1226    /// instructions between the `ForList` header and the trailing `LoopBack`;
1227    /// a `Stop` is appended just past the loop so control flow has a clean
1228    /// landing point. `end_pc` (one past `LoopBack`) is wired automatically.
1229    fn foreach_program(body: Vec<Instr>) -> BytecodeProgram {
1230        // Layout: [ForList][..body..][LoopBack][Stop]
1231        let loop_back_pc = 1 + body.len();
1232        let end_pc = loop_back_pc + 1; // one past LoopBack — where the loop exits to
1233        let mut code = vec![Instr::ForList {
1234            item: 0,
1235            start: 1,
1236            len: 3,
1237            end_pc: end_pc as u32,
1238        }];
1239        code.extend(body);
1240        code.push(Instr::LoopBack);
1241        code.push(Instr::Stop);
1242        BytecodeProgram {
1243            spec: ProgramSpec {
1244                probes: Default::default(),
1245                metadata: CheckMetadata {
1246                    name: Some("loop test".into()),
1247                    ..CheckMetadata::default()
1248                },
1249            },
1250            code,
1251            strings: vec!["x".into(), "a".into(), "b".into(), "c".into()],
1252            payloads: vec![],
1253            matchers: vec![],
1254            extracts: vec![],
1255            evidence: vec![],
1256        }
1257    }
1258
1259    async fn run_offline(bytecode: BytecodeProgram) -> Result<(), RuntimeError> {
1260        let config = ExecutorConfig {
1261            base_url: "http://127.0.0.1".into(),
1262            ..ExecutorConfig::default()
1263        };
1264        let executor = Executor::from_bytecode(config, bytecode).unwrap();
1265        executor.run().await.map(|_| ())
1266    }
1267
1268    // The next three tests pin down loop *execution* (ForList/LoopBack/Break/
1269    // Continue) — the opcodes extracted into `enter_foreach`/`step_loop_back`/
1270    // `step_break`/`step_continue`. They use `Instr::Fail` as a tripwire: any
1271    // instruction the control flow should have skipped turns a pass into an
1272    // error, so a regression can't slip through as a silent no-op.
1273
1274    #[tokio::test]
1275    async fn foreach_iterates_every_value_and_exits() {
1276        // Empty body: enter, three loop-backs, exhaust, fall through to Stop.
1277        // A broken index/jump would panic (out-of-bounds) or hang (budget),
1278        // so reaching a clean `Ok` proves all three iterations ran and the
1279        // frame was popped exactly once.
1280        run_offline(foreach_program(vec![]))
1281            .await
1282            .expect("foreach should iterate and exit cleanly");
1283    }
1284
1285    #[tokio::test]
1286    async fn foreach_break_skips_rest_of_body_and_loop() {
1287        // `break` must jump past the `Fail` and out of the loop to `Stop`.
1288        let body = vec![Instr::Break, Instr::Fail];
1289        run_offline(foreach_program(body))
1290            .await
1291            .expect("break should exit before reaching Fail");
1292    }
1293
1294    #[tokio::test]
1295    async fn foreach_continue_skips_to_loop_back() {
1296        // `continue` must jump to `LoopBack` (continue_pc), skipping the `Fail`,
1297        // on every iteration — then the loop exhausts and exits to `Stop`.
1298        let body = vec![Instr::Continue, Instr::Fail];
1299        run_offline(foreach_program(body))
1300            .await
1301            .expect("continue should skip Fail on every iteration");
1302    }
1303
1304    #[tokio::test]
1305    async fn default_config_verifies_tls() {
1306        // C3 regression: ExecutorConfig::default() must verify TLS so a
1307        // freshly-constructed runtime cannot silently fall back to
1308        // accept-invalid-certs.
1309        let cfg = ExecutorConfig::default();
1310        assert!(cfg.verify_ssl);
1311        assert!(cfg.max_script_duration.is_some());
1312    }
1313}