Skip to content

Building 70 Projects ranging from beginner to advanced so anyone can — learn from, build upon, use as a reference, or even copy directly. Owned by my cybersecurity company 👇

11.7 KB
Raw Blame
// ©AngelaMos | 2026
// console.rs

use std::io::{BufRead, BufReader, Read, Write};
use std::net::{SocketAddr, TcpStream};
use std::path::PathBuf;

use lisdex_core::campaign::{Campaign, CampaignStatus, TreeProvenance};
use lisdex_core::crash::Crash;
use lisdex_core::store::Store;
use lisdex_dashboard::{SNAPSHOT_ROUTE, loopback, router};
use lisdex_monitor::snapshot::Source;

const REAL_PLOT: &str = include_str!("../../lisdex-fuzz/tests/fixtures/plot_data.txt");
const REAL_UNSYMBOLIZED: &str = include_str!("../../lisdex-triage/tests/fixtures/heapw.txt");

const KEYED_WRITE_REPORT: &str = "\
=================================================================
==53767==ERROR: AddressSanitizer: heap-buffer-overflow on address 0x7bd6bfde0020 at pc 0x558474e40fd9
WRITE of size 32 at 0x7bd6bfde0020 thread T0
    #0 0x558474e40fd8 in png_handle_PLTE /src/libpng/pngrutil.c:992:4
    #1 0x558474e41111 in png_read_info /src/libpng/pngread.c:160:10
SUMMARY: AddressSanitizer: heap-buffer-overflow (/out/harness+0xcdfd8) in png_handle_PLTE
";

const KEYED_READ_REPORT: &str = "\
=================================================================
==53768==ERROR: AddressSanitizer: heap-buffer-overflow on address 0x7bc207fe0020 at pc 0x55afa18b1a77
READ of size 1 at 0x7bc207fe0020 thread T0
    #0 0x55afa18b1a76 in png_handle_tRNS /src/libpng/pngrutil.c:1470:9
    #1 0x55afa18b2200 in png_read_info /src/libpng/pngread.c:171:10
SUMMARY: AddressSanitizer: heap-buffer-overflow (/out/harness+0x114a76) in png_handle_tRNS
";

const MAIN_STATS: &str = "\
start_time        : 1784982517
last_update       : 1784983139
run_time          : 600
fuzzer_pid        : 2790
cycles_done       : 64
execs_done        : 34283406
execs_per_sec     : 71170.98
corpus_count      : 1413
bitmap_cvg        : 19.74%
saved_crashes     : 80
saved_hangs       : 0
edges_found       : 13647
total_edges       : 69140
afl_banner        : lisdex_libpng_read
afl_version       : ++5.02c
target_mode       : persistent shmem_testcase deferred
";

struct Lab {
    root: PathBuf,
}

impl Lab {
    fn new(name: &str) -> Lab {
        let root = lisdex_core::scratch::unclaimed_path(&format!(
            "console-{name}-{:?}",
            std::thread::current().id()
        ));
        let _ = std::fs::remove_dir_all(&root);
        let dir = root.join("findings").join("main");
        std::fs::create_dir_all(&dir).unwrap();
        std::fs::write(dir.join("fuzzer_stats"), MAIN_STATS).unwrap();
        std::fs::write(dir.join("plot_data"), REAL_PLOT).unwrap();

        let store = Store::open(root.join("lisdex.sqlite")).unwrap();
        let mut campaign = Campaign::new("lisdex_libpng_read", TreeProvenance::Field);
        let id = store.insert_campaign(&campaign).unwrap();
        campaign.advance(CampaignStatus::Building).unwrap();
        campaign.advance(CampaignStatus::Fuzzing).unwrap();
        store
            .update_campaign_status(id, CampaignStatus::Fuzzing)
            .unwrap();
        for (index, report) in [KEYED_WRITE_REPORT, KEYED_WRITE_REPORT, KEYED_READ_REPORT]
            .iter()
            .enumerate()
        {
            store
                .insert_crash(&Crash::from_report(
                    id,
                    format!("input-{index}").into_bytes(),
                    *report,
                ))
                .unwrap();
        }
        Lab { root }
    }

    fn source(&self) -> Source {
        Source {
            db: self.root.join("lisdex.sqlite"),
            findings: self.root.join("findings"),
            campaign: None,
        }
    }

    fn add_crash(&self, report: &str) {
        let store = Store::open(self.root.join("lisdex.sqlite")).unwrap();
        let (id, _) = store.list_campaigns().unwrap().pop().unwrap();
        store
            .insert_crash(&Crash::from_report(id, b"unsymbolized".to_vec(), report))
            .unwrap();
    }
}

impl Drop for Lab {
    fn drop(&mut self) {
        let _ = std::fs::remove_dir_all(&self.root);
    }
}

struct Server {
    addr: SocketAddr,
}

impl Server {
    fn start(source: Source) -> Server {
        let runtime = tokio::runtime::Builder::new_current_thread()
            .enable_all()
            .build()
            .unwrap();
        let listener = runtime
            .block_on(async { tokio::net::TcpListener::bind(loopback(0)).await })
            .unwrap();
        let addr = listener.local_addr().unwrap();
        let app = router(source);
        std::thread::spawn(move || {
            runtime.block_on(async move {
                let _ = axum::serve(listener, app).await;
            });
        });
        Server { addr }
    }

    fn get(&self, path: &str) -> (String, String) {
        let mut attempt = 0;
        let mut stream = loop {
            match TcpStream::connect(self.addr) {
                Ok(stream) => break stream,
                Err(err) if attempt < 50 => {
                    attempt += 1;
                    std::thread::sleep(std::time::Duration::from_millis(20));
                    let _ = err;
                }
                Err(err) => panic!("console never accepted a connection: {err}"),
            }
        };
        write!(
            stream,
            "GET {path} HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"
        )
        .unwrap();
        stream.flush().unwrap();

        let mut reader = BufReader::new(stream);
        let mut status = String::new();
        reader.read_line(&mut status).unwrap();
        let mut headers = String::new();
        loop {
            let mut line = String::new();
            reader.read_line(&mut line).unwrap();
            if line == "\r\n" || line.is_empty() {
                break;
            }
            headers.push_str(&line);
        }
        let mut body = String::new();
        reader.read_to_string(&mut body).unwrap();
        (format!("{status}{headers}"), body)
    }
}

fn console(lab: &Lab) -> (Server, serde_json::Value) {
    let server = Server::start(lab.source());
    let (head, body) = server.get(SNAPSHOT_ROUTE);
    assert!(
        head.starts_with("HTTP/1.1 200"),
        "unexpected status: {head}"
    );
    let json = serde_json::from_str(&body).expect("the console must answer with valid JSON");
    (server, json)
}

#[test]
fn the_console_serves_a_self_contained_page() {
    let lab = Lab::new("page");
    let server = Server::start(lab.source());
    let (head, body) = server.get("/");
    assert!(head.starts_with("HTTP/1.1 200"));
    assert!(head.contains("text/html"));
    assert!(body.contains("<title>lisdex console</title>"));
    for loader in [
        "src=\"http",
        "src=\"//",
        "href=\"http",
        "href=\"//",
        "@import",
    ] {
        assert!(
            !body.contains(loader),
            "a keyless local tool must not fetch its own console assets from the internet"
        );
    }
}

#[test]
fn the_snapshot_endpoint_reports_the_campaign_on_disk() {
    let lab = Lab::new("snapshot");
    let (_server, json) = console(&lab);
    assert_eq!(json["campaign"]["target"], "lisdex_libpng_read");
    assert_eq!(json["campaign"]["phase"], "FUZZING");
    assert_eq!(json["summary"]["live"], true);
    assert_eq!(json["summary"]["total_crashes"], 3);
    assert_eq!(json["summary"]["distinct_bugs"], 2);
    assert_eq!(json["summary"]["peak_edges"], 13647);
    assert_eq!(json["summary"]["elapsed_secs"], 600);
}

#[test]
fn the_console_reports_the_same_coverage_the_stats_file_holds() {
    let lab = Lab::new("totals");
    let (_server, json) = console(&lab);
    assert_eq!(json["totals"]["edges_found"], 13647);
    assert_eq!(json["totals"]["total_edges"], 69140);
    assert_eq!(json["totals"]["execs_done"], 34_283_406_u64);
    assert_eq!(json["totals"]["afl_version"], "++5.02c");
    let ratio = json["totals"]["edge_ratio"].as_f64().unwrap();
    assert!((ratio - 13_647.0 / 69_140.0).abs() < 1e-9);
    assert!((0.0..=1.0).contains(&ratio));
}

#[test]
fn the_console_serves_the_curve_a_real_campaign_wrote() {
    let lab = Lab::new("curve");
    let (_server, json) = console(&lab);
    let curve = json["curve"].as_array().unwrap();
    assert!(
        curve.len() > 100,
        "the 600s magma capture has over a hundred samples; a truncated curve would still draw a plausible chart"
    );
    assert_eq!(curve.last().unwrap()["secs"], 600);
    assert_eq!(curve.last().unwrap()["edges"], 13647);
    assert_eq!(json["summary"]["curve_instance"], "main");
}

#[test]
fn the_console_ranks_findings_the_way_the_model_did() {
    let lab = Lab::new("findings");
    let (_server, json) = console(&lab);
    let findings = json["findings"].as_array().unwrap();
    assert_eq!(findings.len(), 2);
    assert_eq!(findings[0]["severity"], "EXPLOITABLE");
    assert_eq!(findings[0]["crash_site"], "png_handle_PLTE");
    assert_eq!(findings[0]["crash_count"], 2);
    assert_eq!(findings[1]["severity"], "NOT_EXPLOITABLE");
    assert!(
        findings[0]["sanitizer_report"]
            .as_str()
            .unwrap()
            .contains("AddressSanitizer"),
        "the raw report an advisory would quote must reach the console"
    );
}

#[test]
fn a_crash_that_could_not_be_keyed_is_served_as_a_finding_but_not_as_a_bug() {
    let lab = Lab::new("unkeyed");
    lab.add_crash(REAL_UNSYMBOLIZED);
    let (_server, json) = console(&lab);
    let summary = &json["summary"];
    let findings = json["findings"].as_array().unwrap();

    assert_eq!(summary["total_crashes"], 4);
    assert_eq!(summary["unkeyed_crashes"], 1);
    assert_eq!(
        findings.len(),
        3,
        "the unkeyed crash is its own finding, because two crashes that cannot be keyed must never be merged with each other"
    );
    assert_eq!(
        summary["distinct_bugs"], 2,
        "distinct_bugs counts the crashes that really keyed; serving findings.len() here would report a refusal as a third bug"
    );
    assert_ne!(
        summary["distinct_bugs"].as_u64().unwrap(),
        findings.len() as u64,
        "if these are equal the assertion above cannot tell the two quantities apart, and this test proves nothing"
    );

    let unkeyed: Vec<&serde_json::Value> =
        findings.iter().filter(|f| f["keyed"] == false).collect();
    assert_eq!(unkeyed.len(), 1);
    assert_eq!(unkeyed[0]["short_key"], "unkeyed");
    assert!(
        unkeyed[0]["key_status"]
            .as_str()
            .unwrap()
            .contains("no symbolized frames"),
        "the console must serve the reason a crash was refused, not an empty field"
    );
    assert_eq!(
        unkeyed[0]["severity"], "EXPLOITABLE",
        "refusing to key a crash must not discard the severity the classifier did decide"
    );
}

#[test]
fn a_console_pointed_at_nothing_answers_rather_than_failing() {
    let empty = lisdex_core::scratch::path("console-empty");
    std::fs::create_dir_all(&empty).unwrap();
    let server = Server::start(Source {
        db: empty.join("missing.sqlite"),
        findings: empty.clone(),
        campaign: None,
    });
    let (head, body) = server.get(SNAPSHOT_ROUTE);
    assert!(head.starts_with("HTTP/1.1 200"));
    let json: serde_json::Value = serde_json::from_str(&body).unwrap();
    assert!(json["campaign"].is_null());
    assert!(
        json["notices"]
            .as_array()
            .unwrap()
            .iter()
            .any(|notice| notice.as_str().unwrap().contains("no campaign")),
        "an empty console must say why it is empty rather than render zeroes that look real"
    );
    let _ = std::fs::remove_dir_all(&empty);
}

#[test]
fn an_unknown_route_is_not_answered_with_the_console() {
    let lab = Lab::new("unknown");
    let server = Server::start(lab.source());
    let (head, _) = server.get("/api/../etc/passwd");
    assert!(
        !head.starts_with("HTTP/1.1 200"),
        "the console serves two routes; anything else must not resolve"
    );
}