use colored::Colorize;
use indicatif::{MultiProgress, ProgressBar, ProgressStyle};
use reqwest::Client;
use std::collections::HashMap;
use std::fs;
use std::path::Path;
use std::sync::Arc;
use std::time::Duration;
use tokio::sync::{Mutex, Semaphore};
use url::Url;
#[derive(Debug, Clone)]
pub struct FuzzResult {
pub url: String,
pub status_code: u16,
pub content_length: Option<u64>,
pub content_type: Option<String>,
pub source: FuzzSource,
}
#[derive(Debug, Clone, PartialEq)]
pub enum FuzzSource {
Initial, Database, Discovered, }
pub struct FuzzOptions {
pub base_urls: Vec<String>,
pub wordlist: Vec<String>,
pub threads: usize,
pub show_progress_bars: bool,
pub use_head_requests: bool,
pub timeout_secs: u64,
pub db_path: Option<std::path::PathBuf>,
}
pub async fn execute_fuzz(options: FuzzOptions) -> Result<Vec<FuzzResult>, String> {
let FuzzOptions {
base_urls,
wordlist,
threads,
show_progress_bars,
use_head_requests,
timeout_secs,
db_path,
} = options;
if base_urls.is_empty() {
return Err("No base URLs provided".to_string());
}
if wordlist.is_empty() {
return Err("Wordlist is empty".to_string());
}
let mut db_endpoints = Vec::new();
if let Some(ref db_path) = db_path {
if let Ok(db_urls) = query_database_endpoints(db_path, &base_urls) {
db_endpoints = db_urls;
if !db_endpoints.is_empty() {
println!(
"✓ Found {} endpoints from previous crawls in database",
db_endpoints.len()
);
}
}
}
let mut base_urls_with_source = Vec::new();
for url in &db_endpoints {
base_urls_with_source.push((url.clone(), FuzzSource::Database));
}
for url in &base_urls {
base_urls_with_source.push((url.clone(), FuzzSource::Initial));
}
let mut urls_to_test = Vec::new();
for (base_url, source) in &base_urls_with_source {
for word in &wordlist {
let test_url = build_test_url(base_url, word)?;
urls_to_test.push((test_url, source.clone()));
}
}
let initial_count = urls_to_test.len();
println!(
"Testing {} initial URLs with {} workers",
initial_count, threads
);
if !db_endpoints.is_empty() {
println!(
" {} from command line, {} from database",
base_urls.len() * wordlist.len(),
db_endpoints.len() * wordlist.len()
);
}
println!();
let m = if show_progress_bars {
Some(Arc::new(MultiProgress::new()))
} else {
None
};
let results: Arc<Mutex<Vec<FuzzResult>>> = Arc::new(Mutex::new(Vec::new()));
let hits_display: Arc<Mutex<Vec<String>>> = Arc::new(Mutex::new(Vec::new()));
let work_queue: Arc<Mutex<Vec<(String, FuzzSource)>>> = Arc::new(Mutex::new(urls_to_test));
let tested_urls: Arc<Mutex<std::collections::HashSet<String>>> =
Arc::new(Mutex::new(std::collections::HashSet::new()));
let wordlist_arc = Arc::new(wordlist);
let hits_pb = if show_progress_bars && let Some(ref multi_progress) = m {
let pb = multi_progress.add(ProgressBar::new(0));
pb.set_style(ProgressStyle::default_bar().template("{msg}").unwrap());
pb.set_message("Hits: 0".to_string());
Some(Arc::new(pb))
} else {
None
};
let client = Arc::new(
Client::builder()
.timeout(Duration::from_secs(timeout_secs))
.connect_timeout(Duration::from_secs(timeout_secs / 2))
.pool_max_idle_per_host(threads) .pool_idle_timeout(Duration::from_secs(90))
.http2_adaptive_window(true) .tcp_keepalive(Duration::from_secs(60))
.redirect(reqwest::redirect::Policy::limited(3))
.user_agent("Rinzler/0.1 (https://github.com/trapdoorsec/rinzler)")
.build()
.map_err(|e| format!("Failed to create HTTP client: {}", e))?,
);
let semaphore = Arc::new(Semaphore::new(threads));
let mut worker_tasks = Vec::new();
for worker_id in 0..threads {
let pb = if show_progress_bars && let Some(ref multi_progress) = m {
let progress_bar = multi_progress.add(ProgressBar::new(initial_count as u64));
progress_bar.set_style(
ProgressStyle::default_bar()
.template("[{bar:40.cyan/blue}] Worker {msg}")
.unwrap()
.progress_chars("=>-"),
);
progress_bar.set_message(format!("{} idle", worker_id));
Some(progress_bar)
} else {
None
};
let client_clone = client.clone();
let results_clone = results.clone();
let hits_display_clone = hits_display.clone();
let hits_pb_clone = hits_pb.clone();
let semaphore_clone = semaphore.clone();
let work_queue_clone = work_queue.clone();
let tested_urls_clone = tested_urls.clone();
let wordlist_clone = wordlist_arc.clone();
let task = tokio::spawn(async move {
let mut processed = 0;
loop {
let work_item = {
let mut queue = work_queue_clone.lock().await;
queue.pop()
};
let Some((url, source)) = work_item else {
break; };
let url_path = extract_path(&url);
if let Some(ref pb) = pb {
processed += 1;
let msg = format!(
"{} {} {}",
worker_id,
processed,
format!("[{}]", url_path).truecolor(255, 165, 0) );
pb.set_message(msg);
}
let _permit = semaphore_clone.acquire().await.unwrap();
if let Ok(mut result) =
make_fuzz_request(&client_clone, &url, use_head_requests).await
{
result.source = source.clone();
if result.status_code < 500 {
results_clone.lock().await.push(result.clone());
}
if (200..400).contains(&result.status_code) {
let hit_display = format_hit(&result);
hits_display_clone.lock().await.push(hit_display);
if let Some(ref hits_pb) = hits_pb_clone {
let hits = hits_display_clone.lock().await;
let formatted = format_hits_display(&hits);
hits_pb.set_message(formatted);
}
if let Ok(base_url) = extract_base_url(&result.url) {
let mut tested = tested_urls_clone.lock().await;
if !tested.contains(&base_url) {
tested.insert(base_url.clone());
let mut queue = work_queue_clone.lock().await;
for word in wordlist_clone.iter() {
if let Ok(new_url) = build_test_url(&base_url, word) {
queue.push((new_url, FuzzSource::Discovered));
}
}
}
}
}
}
if let Some(ref pb) = pb {
pb.inc(1);
}
}
if let Some(ref pb) = pb {
pb.finish_with_message(format!("{}: done", worker_id));
}
});
worker_tasks.push(task);
}
for task in worker_tasks {
task.await
.map_err(|e| format!("Worker task failed: {}", e))?;
}
if let Some(ref hits_pb) = hits_pb {
hits_pb.finish();
}
let final_results = results.lock().await.clone();
Ok(final_results)
}
fn extract_path(url: &str) -> String {
if let Ok(parsed) = Url::parse(url) {
let path = parsed.path();
if path.len() > 40 {
format!("...{}", &path[path.len() - 37..])
} else {
path.to_string()
}
} else {
url.to_string()
}
}
fn format_hit(result: &FuzzResult) -> String {
let path = extract_path(&result.url);
let status_colored = colorize_status_code(result.status_code);
format!("{} {}", path, status_colored)
}
fn colorize_status_code(status: u16) -> String {
let status_str = format!("[{}]", status);
match status {
200..=299 => status_str.green().to_string(),
300..=399 => status_str.yellow().to_string(),
400..=499 => status_str.red().to_string(),
_ => status_str.white().to_string(),
}
}
fn format_hits_display(hits: &[String]) -> String {
if hits.is_empty() {
return "Hits: 0".to_string();
}
let total_hits = hits.len();
let max_per_column = 10;
if total_hits <= max_per_column {
let mut display = format!("Hits: {}\n", total_hits);
for hit in hits {
display.push_str(&format!(" {}\n", hit));
}
display
} else {
let num_columns = (total_hits + max_per_column - 1) / max_per_column;
let mut display = format!(
"Hits: {} (showing in {} columns)\n",
total_hits, num_columns
);
let mut columns: Vec<Vec<&str>> = vec![Vec::new(); num_columns];
for (idx, hit) in hits.iter().enumerate() {
let col = idx / max_per_column;
if col < num_columns {
columns[col].push(hit);
}
}
let max_rows = columns.iter().map(|c| c.len()).max().unwrap_or(0);
for row in 0..max_rows {
for (col_idx, column) in columns.iter().enumerate() {
if let Some(hit) = column.get(row) {
display.push_str(&format!(" {:50}", hit));
} else {
display.push_str(&format!("{:52}", ""));
}
if col_idx < columns.len() - 1 {
display.push_str(" ");
}
}
display.push('\n');
}
display
}
}
async fn make_fuzz_request(
client: &Client,
url: &str,
use_head: bool,
) -> Result<FuzzResult, String> {
let response = if use_head {
client
.head(url)
.send()
.await
.map_err(|e| format!("Request failed: {}", e))?
} else {
client
.get(url)
.send()
.await
.map_err(|e| format!("Request failed: {}", e))?
};
let status_code = response.status().as_u16();
let content_length = response.content_length();
let content_type = response
.headers()
.get("content-type")
.and_then(|v| v.to_str().ok())
.map(String::from);
Ok(FuzzResult {
url: url.to_string(),
status_code,
content_length,
content_type,
source: FuzzSource::Initial, })
}
fn extract_base_url(url: &str) -> Result<String, String> {
let parsed = Url::parse(url).map_err(|e| format!("Invalid URL: {}", e))?;
let mut base = parsed.clone();
base.set_query(None);
base.set_fragment(None);
Ok(base.to_string())
}
fn query_database_endpoints(
db_path: &std::path::Path,
target_urls: &[String],
) -> Result<Vec<String>, String> {
use crate::data::Database;
let db = Database::new(db_path).map_err(|e| format!("Failed to open database: {}", e))?;
let mut endpoints = Vec::new();
let mut target_domains = Vec::new();
for url in target_urls {
if let Ok(parsed) = Url::parse(url) {
if let Some(host) = parsed.host_str() {
target_domains.push(host.to_string());
}
}
}
for domain in &target_domains {
let query = "SELECT url FROM nodes WHERE domain = ?";
if let Ok(mut stmt) = db.get_connection().prepare(query) {
if let Ok(rows) = stmt.query_map([domain], |row| row.get::<_, String>(0)) {
for url_result in rows.flatten() {
if let Ok(parsed) = Url::parse(&url_result) {
if let Some(host) = parsed.host_str() {
if host == domain || host.ends_with(&format!(".{}", domain)) {
endpoints.push(url_result);
}
}
}
}
}
}
}
Ok(endpoints)
}
fn build_test_url(base_url: &str, word: &str) -> Result<String, String> {
let mut url =
Url::parse(base_url).map_err(|e| format!("Invalid base URL '{}': {}", base_url, e))?;
let current_path = url.path().to_string();
let path_base = if current_path.ends_with('/') {
current_path
} else {
format!("{}/", current_path)
};
let new_path = format!("{}{}", path_base, word.trim_start_matches('/'));
url.set_path(&new_path);
Ok(url.to_string())
}
pub fn load_wordlist(path: &Path) -> Result<Vec<String>, String> {
let content = fs::read_to_string(path)
.map_err(|e| format!("Failed to read wordlist {}: {}", path.display(), e))?;
let words: Vec<String> = content
.lines()
.filter(|line| !line.trim().is_empty())
.filter(|line| !line.trim().starts_with('#'))
.map(|line| line.trim().to_string())
.collect();
if words.is_empty() {
return Err(format!(
"Wordlist {} is empty or contains only comments",
path.display()
));
}
Ok(words)
}
pub fn generate_fuzz_report(results: &[FuzzResult]) -> String {
let mut report = String::new();
let initial_count = results
.iter()
.filter(|r| r.source == FuzzSource::Initial)
.count();
let db_count = results
.iter()
.filter(|r| r.source == FuzzSource::Database)
.count();
let discovered_count = results
.iter()
.filter(|r| r.source == FuzzSource::Discovered)
.count();
let mut by_status: HashMap<u16, Vec<&FuzzResult>> = HashMap::new();
for result in results {
by_status
.entry(result.status_code)
.or_default()
.push(result);
}
let mut status_codes: Vec<u16> = by_status.keys().copied().collect();
status_codes.sort();
report.push_str(
"\n═══════════════════════════════════════════════════════════════════════════════\n",
);
report.push_str(" FUZZ RESULTS\n");
report.push_str(
"═══════════════════════════════════════════════════════════════════════════════\n\n",
);
report.push_str(&format!("Total findings: {}\n", results.len()));
if db_count > 0 || discovered_count > 0 {
report.push_str(&format!(" {} from initial targets\n", initial_count));
if db_count > 0 {
report.push_str(&format!(" {} from database endpoints\n", db_count));
}
if discovered_count > 0 {
report.push_str(&format!(
" {} from discovered endpoints\n",
discovered_count
));
}
}
report.push('\n');
for status_code in status_codes {
if let Some(status_results) = by_status.get(&status_code) {
let status_label = match status_code {
200..=299 => format!("[{}] Success", status_code),
300..=399 => format!("[{}] Redirect", status_code),
400..=499 => format!("[{}] Client Error", status_code),
_ => format!("[{}]", status_code),
};
report.push_str(&format!(
"{} ({} findings)\n",
status_label,
status_results.len()
));
report.push_str(
"───────────────────────────────────────────────────────────────────────────────\n",
);
for result in status_results {
let source_marker = match result.source {
FuzzSource::Initial => "",
FuzzSource::Database => " [DB]",
FuzzSource::Discovered => " [DISC]",
};
report.push_str(&format!(" {}{}", result.url, source_marker));
if let Some(length) = result.content_length {
report.push_str(&format!(" ({} bytes)", length));
}
if let Some(ref ct) = result.content_type {
let short_ct = ct.split(';').next().unwrap_or(ct);
report.push_str(&format!(" [{}]", short_ct));
}
report.push('\n');
}
report.push('\n');
}
}
report.push_str(
"═══════════════════════════════════════════════════════════════════════════════\n",
);
if discovered_count > 0 {
report.push_str(" [DB] = From database [DISC] = Discovered during fuzzing\n");
report.push_str(
"═══════════════════════════════════════════════════════════════════════════════\n",
);
}
report.push_str(" End of Report\n");
report.push_str(
"═══════════════════════════════════════════════════════════════════════════════\n",
);
report
}