1use std::collections::HashSet;
2use std::env;
3use std::io::{self, Write};
4use std::path::PathBuf;
5use std::thread;
6use std::time::Duration;
7
8use crate::config::ConfigManager;
9use crate::engine::{dedup, matcher, msfrpc, parser};
10use crate::error::{AppError, Result};
11use crate::models::{DedupStats, ModuleSuggestion, PayloadRecipe};
12use crate::nvd::{EnrichmentStats, NVDClient};
13use crate::recipe;
14use crate::report;
15use crate::share;
16
17pub fn main() {
18 if let Err(err) = run() {
19 eprintln!("[!] {}", err);
20 std::process::exit(1);
21 }
22}
23
24pub fn run() -> Result<()> {
25 let mut config_mgr = ConfigManager::new();
26 let config_loaded = config_mgr.load();
27
28 let args = env::args().skip(1).collect::<Vec<_>>();
29 if args.is_empty() {
30 print_banner();
31 return Ok(());
32 }
33
34 match args[0].as_str() {
35 "process" => {
36 cmd_process(&args[1..], &mut config_mgr, config_loaded)?;
37 }
38 "share" => {
39 cmd_share(&args[1..])?;
40 }
41 "reset-config" => {
42 cmd_reset_config(&mut config_mgr)?;
43 }
44 "setup" => {
45 cmd_setup(&mut config_mgr)?;
46 }
47 "-h" | "--help" => {
48 print_banner();
49 }
50 other => {
51 eprintln!("[!] Unknown command: {}", other);
52 print_banner();
53 }
54 }
55
56 Ok(())
57}
58
59fn cmd_setup(config_mgr: &mut ConfigManager) -> Result<()> {
60 println!("PloitMalper Configuration Setup");
61 println!();
62 println!("--- MSF-RPC Configuration ---");
63 println!("Enter your Metasploit RPC server details.");
64 let current = config_mgr.get_msfrpc_config().clone();
65
66 let host = prompt_text("MSF-RPC Host", ¤t.host)?;
67 let port = prompt_u16("MSF-RPC Port", current.port)?;
68 let username = prompt_text("MSF-RPC Username", ¤t.username)?;
69 let password = prompt_text("MSF-RPC Password", ¤t.password)?;
70 let ssl = prompt_bool("Use SSL?", current.ssl)?;
71 let workspace = prompt_text("Workspace", ¤t.workspace)?;
72
73 config_mgr.config.msfrpc.host = host;
74 config_mgr.config.msfrpc.port = port;
75 config_mgr.config.msfrpc.username = username;
76 config_mgr.config.msfrpc.password = password;
77 config_mgr.config.msfrpc.ssl = ssl;
78 config_mgr.config.msfrpc.workspace = workspace;
79
80 println!();
81 println!("--- NVD API Configuration ---");
82 println!("Enter your NVD API key for CVE enrichment (optional but recommended).");
83 println!("Get one at: https://nvd.nist.gov/developers/request-an-api-key");
84 let current_nvd = config_mgr.get_nvd_config().clone();
85 let nvd_key = prompt_text("NVD API Key", ¤t_nvd.api_key)?;
86 config_mgr.config.nvd.api_key = nvd_key;
87
88 config_mgr.save()?;
89 println!();
90 println!(
91 "[+] Configuration saved to {}",
92 crate::config::config_file().display()
93 );
94 Ok(())
95}
96
97fn cmd_process(args: &[String], config_mgr: &mut ConfigManager, config_loaded: bool) -> Result<()> {
98 let input_file = match args.first() {
99 Some(path) => path,
100 None => {
101 eprintln!("[!] No input file specified. Use: ploit-malper process <scan.json>");
102 return Ok(());
103 }
104 };
105
106 let input_path = PathBuf::from(input_file);
107 if !input_path.exists() {
108 eprintln!("[!] File not found: {}", input_path.display());
109 return Ok(());
110 }
111
112 println!("[+] Loading scan results from: {}", input_path.display());
113 let raw_json = std::fs::read_to_string(&input_path)?;
114
115 println!("[+] Parsing with Rust engine...");
116 let parsed = parser::parse_vulnmalper_json(&raw_json)?;
117 println!("[+] Found {} raw findings. Deduplicating...", parsed.len());
118
119 let dedup_result = dedup::deduplicate_records(parsed);
120 let mut records = dedup_result.records;
121 let dedup_stats = DedupStats {
122 total: records.len() + dedup_result.removed_count,
123 unique: dedup_result.unique_count,
124 removed: dedup_result.removed_count,
125 };
126
127 println!(
128 "[+] Deduplication complete: {} unique, {} removed",
129 dedup_stats.unique, dedup_stats.removed
130 );
131 println!();
132
133 if config_mgr.is_nvd_configured() {
134 let nvd_cfg = config_mgr.get_nvd_config().clone();
135 let mut nvd_client = NVDClient::new(&nvd_cfg.api_key);
136 println!("[+] Enriching CVEs via NVD API...");
137 let stats: EnrichmentStats = nvd_client.enrich_records(&mut records);
138 println!(
139 "[+] NVD enrichment complete: {} fetched, {} from cache, {} not found",
140 stats.fetched, stats.cache_hits, stats.not_found
141 );
142 println!();
143 }
144
145 println!("{}", report::render_findings_table(&records));
146
147 let mut all_suggestions = Vec::<ModuleSuggestion>::new();
148 let mut seen_suggestions = HashSet::<(String, String)>::new();
149
150 println!();
151 println!("[+] Analyzing service banners and titles for module suggestions...");
152 for record in &records {
153 if let Some(service) = record.service.as_deref() {
154 for suggestion in matcher::suggest_modules(service) {
155 push_unique_suggestion(&mut all_suggestions, &mut seen_suggestions, suggestion);
156 }
157 }
158 if !record.title.is_empty() {
159 for suggestion in matcher::suggest_from_title(&record.title, "") {
160 push_unique_suggestion(&mut all_suggestions, &mut seen_suggestions, suggestion);
161 }
162 }
163 }
164
165 if all_suggestions.is_empty() {
166 println!("[?] No module suggestions for detected services.");
167 } else {
168 println!("{}", report::render_module_table(&all_suggestions));
169 }
170
171 let mut msf_connected = false;
172 let mut msf_client = None;
173 if !config_loaded || !config_mgr.is_configured() {
174 println!("[?] No MSF-RPC configuration found.");
175 if prompt_bool_with_default("Configure MSF-RPC and NVD API now?", true)? {
176 cmd_setup(config_mgr)?;
177 } else {
178 println!("[?] Continuing without MSF-RPC integration.");
179 println!();
180 }
181 }
182
183 if config_mgr.is_configured() {
184 let msf_cfg = config_mgr.get_msfrpc_config().clone();
185 println!();
186 println!("[+] Connecting to MSF-RPC for workspace verification...");
187 let mut client = msfrpc::MsfRpcClient::new(
188 &msf_cfg.host,
189 msf_cfg.port,
190 &msf_cfg.username,
191 &msf_cfg.password,
192 msf_cfg.ssl,
193 );
194
195 let login_result = client.login()?;
196 if login_result.success {
197 msf_connected = true;
198 println!(
199 "[+] Authenticated to MSF-RPC at {}:{}",
200 msf_cfg.host, msf_cfg.port
201 );
202
203 let ws_result = client.get_workspaces()?;
204 if !ws_result.workspaces.is_empty() {
205 println!();
206 println!("MSF Workspaces");
207 println!("{:<24} {:<16} {:>8}", "Name", "Scope", "Hosts");
208 println!("{}", "-".repeat(52));
209 for workspace in &ws_result.workspaces {
210 println!(
211 "{:<24} {:<16} {:>8}",
212 truncate(&workspace.name, 24),
213 truncate(&workspace.scope, 16),
214 workspace.host_count
215 );
216 }
217 }
218
219 for record in records.iter().take(5) {
220 if let Some(target) = record.target.as_str().split_whitespace().next() {
221 let check_result =
222 client.check_host_exists(target, Some(&msf_cfg.workspace))?;
223 if check_result.exists {
224 println!(
225 "[?] Host {} already exists in workspace '{}'",
226 target, msf_cfg.workspace
227 );
228 }
229 }
230 }
231 } else {
232 println!(
233 "[!] Remote MSF-RPC unreachable. Switched entirely to offline matching matrix."
234 );
235 println!(" Error: {}", login_result.error);
236 }
237
238 msf_client = Some(client);
239 }
240
241 let mut recipes: Vec<PayloadRecipe> = Vec::new();
242 if prompt_bool_with_default("\nGenerate msfvenom payload recipes?", false)? {
243 println!();
244 println!("Payload Recipe Builder");
245 let platforms = recipe::get_available_platforms();
246 println!("Available platforms: {}", platforms.join(", "));
247 let platform = prompt_choice("Platform", &platforms, "windows")?;
248 let arches = recipe::get_available_arches(&platform);
249 println!("Available architectures: {}", arches.join(", "));
250 let arch = prompt_choice("Architecture", &arches, "x64")?;
251 let lhost = prompt_text("LHOST", "10.0.0.1")?;
252 let lport = prompt_u16("LPORT", 4444)?;
253 let output = prompt_text("Output path", "/tmp/payload")?;
254
255 let recipe = recipe::build_recipe(&platform, &arch, &lhost, lport, &output, None, None);
256 println!();
257 println!("Generated recipe:");
258 println!("{}", recipe.command);
259 recipes.push(recipe);
260 }
261
262 if prompt_bool_with_default("\nWrite findings to Markdown report (report.md)?", true)? {
263 let output_path = report::generate_markdown_report(
264 &records,
265 &all_suggestions,
266 &recipes,
267 &dedup_stats,
268 "report.md",
269 )?;
270 println!();
271 println!("[+] Report written to: {}", output_path.display());
272 }
273
274 if msf_connected {
275 if let Some(mut client) = msf_client {
276 client.logout();
277 }
278 }
279
280 config_mgr.config.last_scan_file = Some(input_path.to_string_lossy().to_string());
281 config_mgr.save()?;
282 Ok(())
283}
284
285fn cmd_share(args: &[String]) -> Result<()> {
286 let mut directory = PathBuf::from(".");
287 let mut port = 8888u16;
288
289 let mut index = 0usize;
290 while index < args.len() {
291 match args[index].as_str() {
292 "--directory" | "-d" => {
293 if let Some(value) = args.get(index + 1) {
294 directory = PathBuf::from(value);
295 index += 2;
296 continue;
297 }
298 }
299 "--port" | "-p" => {
300 if let Some(value) = args.get(index + 1) {
301 port = value
302 .parse::<u16>()
303 .map_err(|_| AppError::Message(format!("Invalid port value: {}", value)))?;
304 index += 2;
305 continue;
306 }
307 }
308 _ => {}
309 }
310 index += 1;
311 }
312
313 println!("[+] Starting file server in: {}", directory.display());
314 println!("[+] Port: {}", port);
315 println!();
316
317 let (server, actual_port) = share::start_file_server(directory, port)?;
318 println!(
319 "File server running at http://0.0.0.0:{} (press Ctrl+C to stop)",
320 actual_port
321 );
322
323 let _server = server;
324 loop {
325 thread::sleep(Duration::from_secs(1));
326 }
327}
328
329fn cmd_reset_config(config_mgr: &mut ConfigManager) -> Result<()> {
330 println!("[?] Resetting all stored configuration...");
331 config_mgr.reset()?;
332 println!("[+] Configuration reset. Run ploit-malper to set up credentials.");
333 Ok(())
334}
335
336fn push_unique_suggestion(
337 suggestions: &mut Vec<ModuleSuggestion>,
338 seen: &mut HashSet<(String, String)>,
339 suggestion: ModuleSuggestion,
340) {
341 let key = (
342 suggestion.service_banner.clone(),
343 suggestion.suggested_module.clone(),
344 );
345 if seen.insert(key) {
346 suggestions.push(suggestion);
347 }
348}
349
350fn prompt_text(prompt: &str, default: &str) -> Result<String> {
351 print!(" {} [{}]: ", prompt, default);
352 io::stdout().flush()?;
353 let mut buffer = String::new();
354 io::stdin().read_line(&mut buffer)?;
355 let value = buffer.trim();
356 Ok(if value.is_empty() {
357 default.to_string()
358 } else {
359 value.to_string()
360 })
361}
362
363fn prompt_u16(prompt: &str, default: u16) -> Result<u16> {
364 loop {
365 let value = prompt_text(prompt, &default.to_string())?;
366 if value.is_empty() {
367 return Ok(default);
368 }
369 match value.parse::<u16>() {
370 Ok(parsed) => return Ok(parsed),
371 Err(_) => println!(" Please enter a valid number."),
372 }
373 }
374}
375
376fn prompt_bool(prompt: &str, default: bool) -> Result<bool> {
377 prompt_bool_with_default(prompt, default)
378}
379
380fn prompt_bool_with_default(prompt: &str, default: bool) -> Result<bool> {
381 let suffix = if default { "[Y/n]" } else { "[y/N]" };
382 loop {
383 print!(" {} {}: ", prompt, suffix);
384 io::stdout().flush()?;
385 let mut buffer = String::new();
386 io::stdin().read_line(&mut buffer)?;
387 let value = buffer.trim().to_lowercase();
388 if value.is_empty() {
389 return Ok(default);
390 }
391 match value.as_str() {
392 "y" | "yes" | "true" => return Ok(true),
393 "n" | "no" | "false" => return Ok(false),
394 _ => println!(" Please answer yes or no."),
395 }
396 }
397}
398
399fn prompt_choice(prompt: &str, choices: &[String], default: &str) -> Result<String> {
400 loop {
401 print!(" {} [{}]: ", prompt, default);
402 io::stdout().flush()?;
403 let mut buffer = String::new();
404 io::stdin().read_line(&mut buffer)?;
405 let value = buffer.trim();
406 if value.is_empty() {
407 return Ok(default.to_string());
408 }
409 if choices.iter().any(|choice| choice == value) {
410 return Ok(value.to_string());
411 }
412 println!(" Please choose one of: {}", choices.join(", "));
413 }
414}
415
416fn truncate(value: &str, width: usize) -> String {
417 let count = value.chars().count();
418 if count <= width {
419 return value.to_string();
420 }
421 if width <= 1 {
422 return "…".to_string();
423 }
424 let mut truncated = value.chars().take(width - 1).collect::<String>();
425 truncated.push('…');
426 truncated
427}
428
429fn print_banner() {
430 println!("PloitMalper v{}", env!("CARGO_PKG_VERSION"));
431 println!("Vulnerability Post-Processing and Analysis Toolkit");
432 println!();
433 println!("Commands:");
434 println!(" process <file> Process and deduplicate scan results");
435 println!(" share Start temporary file server");
436 println!(" setup Configure MSF-RPC and NVD API credentials");
437 println!(" reset-config Reset stored configuration");
438}