Files
harpia/crates/xexeu-cli/tests/fingerprint_e2e.rs
T

220 lines
7.2 KiB
Rust

use std::fs;
use std::io::{BufRead, BufReader, Read, Write};
use std::net::{TcpListener, TcpStream};
use std::process::{Command, Stdio};
use std::time::{Duration, Instant};
use tempfile::TempDir;
use xexeu_core::batch::SweepBatch;
use xexeu_core::vuln::feeds::{Cpe, CpeMatchCriteria, CveRecord, VulnDatabase};
struct ChildGuard(std::process::Child);
impl Drop for ChildGuard {
fn drop(&mut self) {
let _ = self.0.kill();
let _ = self.0.wait();
}
}
fn http_get(addr: &str, path: &str) -> (u16, String) {
let mut stream = TcpStream::connect(addr).expect("connect to server");
stream
.set_read_timeout(Some(Duration::from_secs(3)))
.expect("set read timeout");
let request = format!("GET {path} HTTP/1.1\r\nHost: {addr}\r\nConnection: close\r\n\r\n");
stream.write_all(request.as_bytes()).expect("write request");
let mut response = String::new();
stream.read_to_string(&mut response).expect("read response");
let status_line = response.lines().next().unwrap_or("");
let code: u16 = status_line
.split_whitespace()
.nth(1)
.unwrap_or("0")
.parse()
.unwrap_or(0);
let body = response.split("\r\n\r\n").nth(1).unwrap_or("").to_string();
(code, body)
}
#[test]
fn fingerprint_and_vuln_matching_e2e() {
// 1. Mock HTTP service returning Apache 2.4.49 Server header
let target_listener = TcpListener::bind("127.0.0.1:0").expect("bind target listener");
let target_port = target_listener.local_addr().expect("target address").port();
std::thread::spawn(move || {
for stream in target_listener.incoming() {
let mut stream = match stream {
Ok(s) => s,
Err(_) => break,
};
let mut buf = [0u8; 1024];
let _ = stream.read(&mut buf);
let resp = "HTTP/1.1 200 OK\r\nServer: Apache/2.4.49 (Unix)\r\nContent-Length: 2\r\nConnection: close\r\n\r\nOK";
let _ = stream.write_all(resp.as_bytes());
}
});
// 2. Setup workspace, config, and fixture vuln_db.json
let workspace = TempDir::new().expect("temporary directory");
let config_path = workspace.path().join("xexeu.toml");
let sweeps_dir = workspace.path().join("sweeps");
let data_dir = workspace.path().join("data");
fs::create_dir_all(&data_dir).expect("create data dir");
fs::write(
&config_path,
format!(
r#"
[escopo]
autorizado = ["127.0.0.1/32"]
responsavel = "teste"
[padrao]
cron = "@daily"
hosts_simultaneos = 2
[perfis.padrao]
tcp = "{target_port}"
[[grupo]]
nome = "local"
alvos = ["127.0.0.1/32"]
"#
),
)
.expect("write configuration");
let mut db = VulnDatabase::default();
db.kev.cve_ids.insert("CVE-2021-41773".to_string());
db.nvd.records.insert(
"CVE-2021-41773".to_string(),
CveRecord {
id: "CVE-2021-41773".to_string(),
description: "Path traversal and file disclosure in Apache HTTP Server 2.4.49"
.to_string(),
cvss_score: Some(7.5),
cvss_vector: None,
cpe_matches: vec![CpeMatchCriteria {
criteria: "cpe:2.3:a:apache:http_server:2.4.49:*:*:*:*:*:*:*".to_string(),
cpe: Cpe::parse("cpe:2.3:a:apache:http_server:2.4.49:*:*:*:*:*:*:*").unwrap(),
version_start_including: None,
version_start_excluding: None,
version_end_including: None,
version_end_excluding: None,
}],
},
);
db.save_to_file(&data_dir.join("vuln_db.json"))
.expect("save fixture vuln_db.json");
// 3. Run scan --once with --data-dir pointing to our fixture database
let scan_output = Command::new(env!("CARGO_BIN_EXE_xexeu"))
.args([
"scan",
"--group",
"local",
"--once",
"--config",
config_path.to_str().expect("config path"),
"--out",
sweeps_dir.to_str().expect("sweeps path"),
"--data-dir",
data_dir.to_str().expect("data dir"),
])
.output()
.expect("run xexeu scan");
assert!(
scan_output.status.success(),
"scan failed: {}",
String::from_utf8_lossy(&scan_output.stderr)
);
// 4. Validate generated Parquet batch
let group_dir = sweeps_dir.join("local");
let sweep_dir = fs::read_dir(&group_dir)
.expect("group directory")
.next()
.expect("one sweep")
.expect("sweep entry")
.path();
let batch = SweepBatch::read(&sweep_dir).expect("read batch");
assert_eq!(batch.services.len(), 1, "expected 1 service observation");
let service = &batch.services[0];
assert_eq!(service.port, target_port);
assert_eq!(service.product.as_deref(), Some("Apache HTTP Server"));
assert_eq!(service.version.as_deref(), Some("2.4.49"));
assert!(
service
.cpe
.as_ref()
.map(|s| s.contains("http_server"))
.unwrap_or(false),
"cpe should contain http_server: {:?}",
service.cpe
);
assert_eq!(service.findings.len(), 1, "expected 1 finding on service");
let finding = &service.findings[0];
assert_eq!(finding.id, "CVE-2021-41773");
assert!(finding.kev);
assert_eq!(finding.cvss, Some(7.5));
// 5. Run serve and verify /api/hosts
let mut child = Command::new(env!("CARGO_BIN_EXE_xexeu"))
.args([
"serve",
"--bind",
"127.0.0.1:0",
"--config",
config_path.to_str().expect("config path"),
"--sweeps",
sweeps_dir.to_str().expect("sweeps path"),
"--data-dir",
data_dir.to_str().expect("data dir"),
])
.stdout(Stdio::piped())
.stderr(Stdio::inherit())
.spawn()
.expect("spawn xexeu serve");
let stdout = child.stdout.take().expect("take stdout");
let mut reader = BufReader::new(stdout);
let mut server_addr = None;
let deadline = Instant::now() + Duration::from_secs(5);
while Instant::now() < deadline {
let mut line = String::new();
if reader.read_line(&mut line).unwrap_or(0) > 0 {
if let Some(pos) = line.find("http://") {
let rest = &line[pos + "http://".len()..];
let addr = rest.split_whitespace().next().unwrap_or("").trim();
server_addr = Some(addr.to_string());
break;
}
}
}
let _guard = ChildGuard(child);
let server_addr = server_addr.expect("server failed to output listening address");
// Poll /api/hosts until the sweep is ingested and host has findings
let poll_deadline = Instant::now() + Duration::from_secs(6);
let mut finding_found = false;
while Instant::now() < poll_deadline {
let (status, body) = http_get(&server_addr, "/api/hosts");
if status == 200 && body.contains("CVE-2021-41773") && body.contains("Apache HTTP Server") {
finding_found = true;
break;
}
std::thread::sleep(Duration::from_millis(300));
}
assert!(
finding_found,
"expected /api/hosts to return Apache HTTP Server and CVE-2021-41773"
);
}