detonate 0.1.5

Prove an injected web payload actually EXECUTES (alert(1) fires), not just reflects: a shared XSS-execution oracle over a jsdet sandbox.
Documentation
//! `detonate` CLI (prove a reflected HTTP response executes injected JS).
//!
//! Reads an HTML response body (from `--body-file` or stdin), runs the
//! JavaScript it would execute through the jsdet sandbox, and prints an
//! [`detonate::ExecutionProof`] as JSON. Designed to be invoked out-of-process
//! by other tools (e.g. `wafrift --prove-execution`) so they need not link the
//! heavy jsdet / wasmtime dependency.
//!
//! Usage:
//!   detonate --url <URL> [--body-file <FILE>] [--expect <ARG>]
//!   cat response.html | detonate --url https://target/reflect
//!
//! Exit codes: `0` = a dialog sink fired (execution proven); `0` with
//! `--expect <ARG>` requires the sink's message to equal `<ARG>` (e.g. `1` for
//! `alert(1)`); `3` = ran but nothing executed; `2` = usage/IO error.

use std::io::Read;
use std::process::ExitCode;

fn main() -> ExitCode {
    let mut args = std::env::args().skip(1).peekable();

    // `detonate vectors [--marker M]`: emit the self-validated
    // execution-preserving XSS vector library (one per line) for the evasion
    // search (`wafrift exploit`) to consume. Every vector printed here is
    // guaranteed by detonate's own tests to actually fire a dialog sink.
    if args.peek().map(String::as_str) == Some("vectors") {
        args.next();
        let mut marker = "1".to_string();
        let mut catalog = "exec";
        while let Some(a) = args.next() {
            match a.as_str() {
                "--marker" => {
                    if let Some(m) = args.next() {
                        marker = m;
                    }
                }
                // Emit the browser-only mutation-XSS catalog instead of the
                // jsdet-validated execution-preserving vectors. These fire only
                // through a real browser's DOM-sink re-serialization, so the
                // consumer must detonate them with `--engine chrome`.
                "--mutation" | "--mxss" => catalog = "mutation",
                // Emit the context-breakout catalog: payloads that escape a
                // quoted attribute / JS-string / javascript:-URI reflection
                // context (the non-body contexts a real app exposes).
                "--breakout" => catalog = "breakout",
                _ => {}
            }
        }
        let vectors = match catalog {
            "mutation" => detonate::mutation::mutation_vectors(&marker),
            "breakout" => detonate::breakout::breakout_vectors(&marker),
            _ => detonate::exec_preserving_vectors(&marker),
        };
        for v in vectors {
            println!("{v}");
        }
        return ExitCode::SUCCESS;
    }

    let mut url: Option<String> = None;
    let mut body_file: Option<String> = None;
    let mut expect: Option<String> = None;
    let mut engine = detonate::Engine::default();

    // Consume the value that must follow a value-taking flag, rejecting a
    // missing value or one that is itself a flag. Without this, `--url` with no
    // following token silently stayed None (and fell through to stdin), and
    // `--url --engine chrome` silently consumed `--engine` as the URL.
    fn take_value(
        args: &mut impl Iterator<Item = String>,
        flag: &str,
    ) -> Result<String, ExitCode> {
        match args.next() {
            Some(v) if !v.starts_with('-') => Ok(v),
            Some(v) => {
                eprintln!("detonate: {flag} requires a value but got the flag {v:?}");
                Err(ExitCode::from(2))
            }
            None => {
                eprintln!("detonate: {flag} requires a value");
                Err(ExitCode::from(2))
            }
        }
    }

    while let Some(a) = args.next() {
        match a.as_str() {
            "--url" => {
                url = Some(match take_value(&mut args, "--url") {
                    Ok(v) => v,
                    Err(code) => return code,
                });
            }
            "--body-file" => {
                body_file = Some(match take_value(&mut args, "--body-file") {
                    Ok(v) => v,
                    Err(code) => return code,
                });
            }
            "--expect" => {
                expect = Some(match take_value(&mut args, "--expect") {
                    Ok(v) => v,
                    Err(code) => return code,
                });
            }
            "--engine" => {
                let Some(name) = args.next() else {
                    eprintln!("detonate: --engine requires a value (jsdet|chrome)");
                    return ExitCode::from(2);
                };
                match detonate::Engine::parse(&name) {
                    Some(e) => engine = e,
                    None => {
                        eprintln!("detonate: unknown engine {name:?} (expected jsdet|chrome)");
                        return ExitCode::from(2);
                    }
                }
            }
            "-h" | "--help" => {
                eprintln!(
                    "detonate --url <URL> [--body-file <FILE>] [--expect <ARG>] [--engine jsdet|chrome]\n\
                     Reads the HTML response body from --body-file or stdin and proves\n\
                     whether its injected JavaScript executes (a dialog sink fires).\n\
                     --engine jsdet (default): QuickJS sandbox, fast, JS-execution proof.\n\
                     --engine chrome: real headless Chrome, also catches mutation-XSS and\n\
                       browser-only handlers jsdet cannot (needs Chrome; $WAFRIFT_CHROME_BIN).\n\
                     Prints ExecutionProof JSON. Exit 0 = executed, 3 = did not, 2 = usage.\n\
                     \n\
                     detonate vectors [--marker M] [--mutation|--breakout]\n\
                       Emit a self-validated XSS vector catalog (one per line) for the\n\
                       evasion search to consume. Default: execution-preserving vectors.\n\
                       --mutation: browser-only mutation-XSS (needs --engine chrome).\n\
                       --breakout: context-breakout vectors (quoted attribute, JS string,\n\
                       javascript: URI) (escape the non-body contexts a real app exposes)."
                );
                return ExitCode::from(2);
            }
            other => {
                eprintln!("detonate: unexpected argument {other:?} (try --help)");
                return ExitCode::from(2);
            }
        }
    }

    // Requesting the chrome engine where no browser exists is an operator
    // error worth surfacing (the call still answers via jsdet fallback).
    if engine == detonate::Engine::Chrome && !detonate::chrome::available() {
        eprintln!(
            "detonate: --engine chrome requested but no Chrome/Chromium found \
             (set $WAFRIFT_CHROME_BIN); falling back to jsdet"
        );
    }

    let Some(url) = url else {
        eprintln!("detonate: --url is required (the page URL the body was served from)");
        return ExitCode::from(2);
    };

    let body = match read_body(body_file.as_deref()) {        Ok(b) => b,
        Err(e) => {
            eprintln!("detonate: cannot read body: {e}");
            return ExitCode::from(2);
        }
    };

    let proof = detonate::detonate_html_with(engine, &body, &url);
    // Machine-readable result on stdout for the calling tool.
    match serde_json::to_string(&proof) {
        Ok(j) => println!("{j}"),
        Err(e) => {
            eprintln!("detonate: serialize proof: {e}");
            return ExitCode::from(2);
        }
    }

    if proof.failed_to_run() {
        if let Some(ref err) = proof.error {
            eprintln!("detonate: detonation failed to run: {err}");
        }
        return ExitCode::from(2);
    }

    let proven = match expect {
        Some(ref arg) => proof.proves(arg),
        None => proof.executed,
    };
    if proven { ExitCode::SUCCESS } else { ExitCode::from(3) }
}

/// Read the response body from `--body-file`, or from stdin when absent.
///
/// The body is attacker-influenced data (an HTTP response from a scan
/// target), so the read is capped at [`MAX_BODY_BYTES`]: an unbounded
/// `read_to_string` lets a hostile or broken peer OOM the detonation host
/// with a multi-gigabyte response.
fn read_body(path: Option<&str>) -> std::io::Result<String> {
    /// Largest response body the CLI will detonate. A real reflected
    /// response is kilobytes; 64 MiB leaves generous headroom while keeping
    /// memory bounded.
    const MAX_BODY_BYTES: u64 = 64 * 1024 * 1024;
    read_body_limited(path, MAX_BODY_BYTES)
}

/// [`read_body`] with the byte cap as a parameter so tests can exercise the
/// limit without writing 64 MiB fixtures.
fn read_body_limited(path: Option<&str>, max_bytes: u64) -> std::io::Result<String> {
    let reader: Box<dyn std::io::Read> = match path {
        Some(p) => Box::new(std::fs::File::open(p)?),
        None => Box::new(std::io::stdin()),
    };
    let mut limited = reader.take(max_bytes + 1);
    let mut s = String::new();
    limited.read_to_string(&mut s)?;
    if s.len() as u64 > max_bytes {
        return Err(std::io::Error::new(
            std::io::ErrorKind::InvalidData,
            format!(
                "response body exceeds the {max_bytes}-byte limit; truncate the capture or raise the limit in read_body"
            ),
        ));
    }
    Ok(s)
}

#[cfg(test)]
mod tests {
    use super::read_body_limited;

    /// Regression: the CLI read the response body (attacker-influenced bytes
    /// from a scan target) with an unbounded `read_to_string`. A hostile or
    /// broken peer could OOM the detonation host. The read is now capped;
    /// this pins both sides of the boundary: exactly-at-limit succeeds, one
    /// byte over fails with a clear error.
    #[test]
    fn read_body_enforces_byte_cap() {
        let dir = std::env::temp_dir();
        let path = dir.join(format!("detonate-read-body-test-{}", std::process::id()));
        std::fs::write(&path, vec![b'a'; 1025]).expect("write fixture");

        let at_limit = read_body_limited(Some(path.to_str().expect("utf8 path")), 1024);
        // 1025 bytes present, cap 1024: must fail.
        assert!(at_limit.is_err(), "one byte over the cap must error");
        let over_err = at_limit.err().expect("checked above");
        assert!(
            over_err.to_string().contains("1024-byte limit"),
            "error must name the limit: {over_err}"
        );

        let exact = read_body_limited(Some(path.to_str().expect("utf8 path")), 1025);
        assert_eq!(
            exact.expect("at-cap body must succeed").len(),
            1025,
            "exactly-at-limit body must be returned whole"
        );
        let _ = std::fs::remove_file(&path);
    }
}