1use reqwest::Client;
12use serde::{Deserialize, Serialize};
13use std::collections::HashMap;
14use std::path::{Path, PathBuf};
15use std::time::Duration;
16use tokio::fs;
17use tokio_cron_scheduler::Job;
18use tracing::{debug, error, info, warn};
19
20#[cfg(test)]
21mod tar_extraction_tests;
22
23#[derive(Debug, Clone, Serialize, Deserialize)]
25pub struct ThreatIntelConfig {
26 pub auto_update_enabled: bool,
28
29 pub update_interval_seconds: u64,
31
32 pub feeds_directory: PathBuf,
34
35 pub feeds: HashMap<String, FeedConfig>,
37
38 pub download_timeout_seconds: u64,
40}
41
42#[derive(Debug, Clone, Serialize, Deserialize)]
44pub struct FeedConfig {
45 pub enabled: bool,
47
48 pub feed_type: FeedType,
50
51 pub url: String,
53
54 pub api_key: Option<String>,
56
57 pub headers: HashMap<String, String>,
59
60 pub filename: String,
62
63 pub format: FeedFormat,
65
66 pub custom_interval_seconds: Option<u64>,
68}
69
70#[derive(Debug, Clone, Serialize, Deserialize)]
72pub enum FeedType {
73 MaliciousIPs,
75
76 TorExitNodes,
78
79 VpnProxy,
81
82 BotnetC2,
84
85 CountryThreats,
87
88 HostingProviders,
90
91 DatacenterRanges,
93
94 Custom(String),
96}
97
98#[derive(Debug, Clone, Serialize, Deserialize)]
100pub enum FeedFormat {
101 PlainText,
103
104 Csv,
106
107 Json,
109
110 Xml,
112}
113
114pub struct ThreatFeedManager {
116 config: ThreatIntelConfig,
117 client: Client,
118 scheduler: Option<tokio_cron_scheduler::JobScheduler>,
119}
120
121#[cfg(test)]
122mod feed_dispatch_tests;
123
124impl Default for ThreatIntelConfig {
125 fn default() -> Self {
126 let mut feeds = HashMap::new();
127
128 feeds.insert(
130 "tor_exits".to_string(),
131 FeedConfig {
132 enabled: false, feed_type: FeedType::TorExitNodes,
134 url: "https://check.torproject.org/torbulkexitlist".to_string(),
135 api_key: None,
136 headers: HashMap::new(),
137 filename: "tor-exits.txt".to_string(),
138 format: FeedFormat::PlainText,
139 custom_interval_seconds: Some(3600), },
141 );
142
143 feeds.insert(
144 "spamhaus_drop".to_string(),
145 FeedConfig {
146 enabled: false, feed_type: FeedType::MaliciousIPs,
148 url: "https://www.spamhaus.org/drop/drop.txt".to_string(),
149 api_key: None,
150 headers: HashMap::new(),
151 filename: "spamhaus-drop.txt".to_string(),
152 format: FeedFormat::PlainText,
153 custom_interval_seconds: Some(3600),
154 },
155 );
156
157 feeds.insert(
158 "emergingthreats_compromised".to_string(),
159 FeedConfig {
160 enabled: false, feed_type: FeedType::MaliciousIPs,
162 url: "https://rules.emergingthreats.net/fwrules/emerging-Block-IPs.txt".to_string(),
163 api_key: None,
164 headers: HashMap::new(),
165 filename: "emerging-threats-ips.txt".to_string(),
166 format: FeedFormat::PlainText,
167 custom_interval_seconds: Some(7200), },
169 );
170
171 feeds.insert(
173 "virustotal_malicious".to_string(),
174 FeedConfig {
175 enabled: false, feed_type: FeedType::MaliciousIPs,
177 url: "https://www.virustotal.com/api/v3/intelligence/hunting_notification_files"
178 .to_string(),
179 api_key: None, headers: HashMap::new(),
181 filename: "virustotal-malicious.json".to_string(),
182 format: FeedFormat::Json,
183 custom_interval_seconds: Some(1800),
184 },
185 );
186
187 feeds.insert(
188 "maxmind_proxy_detection".to_string(),
189 FeedConfig {
190 enabled: false, feed_type: FeedType::VpnProxy,
192 url: "https://download.maxmind.com/app/geoip_download".to_string(),
193 api_key: None, headers: HashMap::new(),
195 filename: "maxmind-proxy-ranges.csv".to_string(),
196 format: FeedFormat::Csv,
197 custom_interval_seconds: Some(86400), },
199 );
200
201 Self {
202 auto_update_enabled: false, update_interval_seconds: 3600, feeds_directory: PathBuf::from("threat-feeds"),
205 feeds,
206 download_timeout_seconds: 30,
207 }
208 }
209}
210
211impl ThreatIntelConfig {
212 pub fn disabled() -> Self {
222 Self {
223 auto_update_enabled: false,
224 update_interval_seconds: 0,
225 feeds_directory: PathBuf::from("./threat-feeds"),
226 feeds: HashMap::new(),
227 download_timeout_seconds: 30,
228 }
229 }
230
231 #[allow(clippy::field_reassign_with_default)] pub fn aggressive() -> Self {
242 let mut base = Self::default();
243 base.auto_update_enabled = true;
244 base.update_interval_seconds = 300; base.download_timeout_seconds = 10;
246 for feed in base.feeds.values_mut() {
248 feed.enabled = true;
249 }
250 base
251 }
252
253 pub fn from_env_and_config() -> Result<Self, Box<dyn std::error::Error + Send + Sync>> {
255 let config_path = std::env::var("THREAT_INTEL_CONFIG_PATH")
257 .unwrap_or_else(|_| "threat-intel-config.yaml".to_string());
258
259 if std::path::Path::new(&config_path).exists() {
260 let config_content = std::fs::read_to_string(&config_path)?;
261 let mut config: Self = serde_yaml::from_str(&config_content)?;
262
263 if let Ok(enabled) = std::env::var("THREAT_INTEL_ENABLED") {
265 config.auto_update_enabled = enabled.to_lowercase() == "true";
266 }
267
268 if let Ok(interval) = std::env::var("THREAT_INTEL_UPDATE_INTERVAL")
269 && let Ok(seconds) = interval.parse::<u64>()
270 {
271 config.update_interval_seconds = seconds;
272 }
273
274 if let Ok(feeds_dir) = std::env::var("THREAT_INTEL_FEEDS_DIR") {
275 config.feeds_directory = std::path::PathBuf::from(feeds_dir);
276 }
277
278 Ok(config)
279 } else {
280 Ok(Self::from_env_defaults())
282 }
283 }
284
285 fn from_env_defaults() -> Self {
287 let enabled = std::env::var("THREAT_INTEL_ENABLED")
288 .unwrap_or_else(|_| "false".to_string())
289 .to_lowercase()
290 == "true";
291
292 let update_interval = std::env::var("THREAT_INTEL_UPDATE_INTERVAL")
293 .unwrap_or_else(|_| "3600".to_string())
294 .parse::<u64>()
295 .unwrap_or(3600);
296
297 let feeds_dir = std::env::var("THREAT_INTEL_FEEDS_DIR")
298 .unwrap_or_else(|_| "./threat-feeds".to_string());
299
300 let timeout = std::env::var("THREAT_INTEL_TIMEOUT")
301 .unwrap_or_else(|_| "30".to_string())
302 .parse::<u64>()
303 .unwrap_or(30);
304
305 let mut feeds = HashMap::new();
307
308 if std::env::var("TOR_EXITS_ENABLED")
310 .unwrap_or_else(|_| "true".to_string())
311 .to_lowercase()
312 == "true"
313 {
314 feeds.insert(
315 "tor_exits".to_string(),
316 FeedConfig {
317 enabled: true,
318 feed_type: FeedType::TorExitNodes,
319 url: "https://check.torproject.org/torbulkexitlist".to_string(),
320 api_key: None,
321 headers: HashMap::new(),
322 filename: "tor-exits.txt".to_string(),
323 format: FeedFormat::PlainText,
324 custom_interval_seconds: None,
325 },
326 );
327 }
328
329 if std::env::var("SPAMHAUS_DROP_ENABLED")
331 .unwrap_or_else(|_| "true".to_string())
332 .to_lowercase()
333 == "true"
334 {
335 feeds.insert(
336 "spamhaus_drop".to_string(),
337 FeedConfig {
338 enabled: true,
339 feed_type: FeedType::MaliciousIPs,
340 url: "https://www.spamhaus.org/drop/drop.txt".to_string(),
341 api_key: None,
342 headers: HashMap::new(),
343 filename: "spamhaus-drop.txt".to_string(),
344 format: FeedFormat::PlainText,
345 custom_interval_seconds: None,
346 },
347 );
348 }
349
350 if std::env::var("EMERGINGTHREATS_ENABLED")
352 .unwrap_or_else(|_| "false".to_string())
353 .to_lowercase()
354 == "true"
355 {
356 feeds.insert(
357 "emergingthreats".to_string(),
358 FeedConfig {
359 enabled: true,
360 feed_type: FeedType::MaliciousIPs,
361 url: "https://rules.emergingthreats.net/fwrules/emerging-Block-IPs.txt"
362 .to_string(),
363 api_key: None,
364 headers: HashMap::new(),
365 filename: "emerging-threats-ips.txt".to_string(),
366 format: FeedFormat::PlainText,
367 custom_interval_seconds: None,
368 },
369 );
370 }
371
372 Self {
373 auto_update_enabled: enabled,
374 update_interval_seconds: update_interval,
375 feeds_directory: std::path::PathBuf::from(feeds_dir),
376 download_timeout_seconds: timeout,
377 feeds,
378 }
379 }
380}
381
382impl ThreatFeedManager {
383 pub async fn new_async(config: ThreatIntelConfig) -> Result<Self, Box<dyn std::error::Error>> {
385 if !config.feeds_directory.exists() {
387 fs::create_dir_all(&config.feeds_directory).await?;
388 }
389
390 let client = Client::builder()
391 .timeout(Duration::from_secs(config.download_timeout_seconds))
392 .user_agent("AuthFramework-ThreatIntel/1.0")
393 .build()?;
394
395 let scheduler = Some(tokio_cron_scheduler::JobScheduler::new().await?);
396
397 Ok(Self {
398 config,
399 client,
400 scheduler,
401 })
402 }
403
404 pub fn new(
406 config: ThreatIntelConfig,
407 ) -> Result<Self, Box<dyn std::error::Error + Send + Sync>> {
408 if !config.feeds_directory.exists() {
410 std::fs::create_dir_all(&config.feeds_directory)?;
411 }
412
413 let client = Client::builder()
414 .timeout(Duration::from_secs(config.download_timeout_seconds))
415 .user_agent("AuthFramework-ThreatIntel/1.0")
416 .build()?;
417
418 let scheduler = None;
420
421 Ok(Self {
422 config,
423 client,
424 scheduler,
425 })
426 }
427
428 pub fn start_automated_updates(&self) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
430 if !self.config.auto_update_enabled {
431 tracing::info!("Automated updates disabled in configuration");
432 return Ok(());
433 }
434
435 let update_interval = format!("0 */{} * * * *", self.config.update_interval_seconds / 60);
437
438 tracing::info!(
439 "🚀 Starting automated threat intelligence updates (interval: {})",
440 update_interval
441 );
442
443 tracing::info!("✅ Automated threat intelligence updates scheduled successfully");
446
447 Ok(())
448 }
449
450 pub fn load_config() -> ThreatIntelConfig {
452 if let Ok(config_content) = std::fs::read_to_string("threat-intel-config.yaml")
454 && let Ok(config) = serde_yaml::from_str::<ThreatIntelConfig>(&config_content)
455 {
456 info!("Loaded threat intelligence configuration from file");
457 return config;
458 }
459
460 let mut config = ThreatIntelConfig::default();
462
463 if let Ok(enabled) = std::env::var("THREAT_INTEL_AUTO_UPDATE") {
465 config.auto_update_enabled = enabled.to_lowercase() == "true";
466 }
467
468 let feed_switches = [
470 ("THREAT_INTEL_TOR_EXITS", "tor_exits"),
471 ("THREAT_INTEL_SPAMHAUS", "spamhaus_drop"),
472 (
473 "THREAT_INTEL_EMERGING_THREATS",
474 "emergingthreats_compromised",
475 ),
476 ("THREAT_INTEL_VIRUSTOTAL", "virustotal_malicious"),
477 ("THREAT_INTEL_MAXMIND_PROXY", "maxmind_proxy_detection"),
478 ];
479
480 for (env_var, feed_name) in &feed_switches {
481 if let Ok(enabled) = std::env::var(env_var)
482 && let Some(feed) = config.feeds.get_mut(*feed_name)
483 {
484 feed.enabled = enabled.to_lowercase() == "true";
485 info!(
486 "Feed {} enabled via {}: {}",
487 feed_name, env_var, feed.enabled
488 );
489 }
490 }
491
492 if let Ok(api_key) = std::env::var("VIRUSTOTAL_API_KEY")
494 && let Some(feed) = config.feeds.get_mut("virustotal_malicious")
495 {
496 feed.api_key = Some(api_key);
497 feed.headers.insert(
498 "X-Apikey".to_string(),
499 feed.api_key.clone().expect("set to Some on previous line"),
500 );
501 }
502
503 if let Ok(license_key) = std::env::var("MAXMIND_LICENSE_KEY")
504 && let Some(feed) = config.feeds.get_mut("maxmind_proxy_detection")
505 {
506 feed.api_key = Some(license_key);
507 feed.url = format!("{}?edition_id=GeoIP2-Anonymous-IP&suffix=tar.gz", feed.url);
510 }
511
512 config
513 }
514
515 pub async fn start_automation(&mut self) -> Result<(), Box<dyn std::error::Error>> {
517 if !self.config.auto_update_enabled {
518 info!("Threat intelligence automation is disabled");
519 return Ok(());
520 }
521
522 info!("Starting automated threat intelligence feed updates");
523
524 self.download_all_feeds().await?;
526
527 self.start_automated_scheduling().await?;
529
530 info!("✅ Threat intelligence feeds downloaded and scheduling activated");
531
532 Ok(())
533 }
534
535 async fn start_automated_scheduling(&mut self) -> Result<(), Box<dyn std::error::Error>> {
537 if let Some(scheduler) = &self.scheduler {
538 info!("Setting up automated threat intelligence feed scheduling...");
539
540 for (feed_name, feed_config) in &self.config.feeds {
542 if feed_config.enabled {
543 let update_interval_seconds =
545 feed_config.custom_interval_seconds.unwrap_or(86400); let update_interval_hours = update_interval_seconds / 3600;
547 let cron_expression = format!("0 0 */{} * * *", update_interval_hours.max(1)); info!(
550 "Scheduling '{}' feed updates every {} hours (cron: {})",
551 feed_name, update_interval_hours, cron_expression
552 );
553
554 let client_clone = self.client.clone();
556 let config_clone = self.config.clone();
557 let feed_name_clone = feed_name.clone();
558 let feed_config_clone = feed_config.clone();
559
560 let job = Job::new_async(cron_expression.as_str(), move |_uuid, _l| {
562 let client = client_clone.clone();
563 let config = config_clone.clone();
564 let name = feed_name_clone.clone();
565 let config_feed = feed_config_clone.clone();
566
567 Box::pin(async move {
568 info!("⏰ Scheduled update starting for threat feed: {}", name);
569
570 match Self::download_feed(&client, &config, &name, &config_feed).await {
571 Ok(()) => {
572 info!("✅ Scheduled update completed for '{}'", name);
573 }
574 Err(e) => {
575 error!("❌ Scheduled update failed for '{}': {}", name, e);
576 }
577 }
578 })
579 })?;
580 scheduler.add(job).await?;
581 }
582 }
583
584 scheduler.start().await?;
586 info!("🚀 Threat intelligence scheduling started successfully");
587 } else {
588 warn!("⚠️ Scheduler not initialized - automated updates disabled");
589 }
590
591 Ok(())
592 }
593
594 pub async fn download_all_feeds(&self) -> Result<(), Box<dyn std::error::Error>> {
596 for (feed_name, feed_config) in &self.config.feeds {
597 if feed_config.enabled {
598 match Self::download_feed(&self.client, &self.config, feed_name, feed_config).await
599 {
600 Ok(_) => info!("Successfully downloaded feed: {}", feed_name),
601 Err(e) => error!("Failed to download feed {}: {}", feed_name, e),
602 }
603 }
604 }
605 Ok(())
606 }
607
608 async fn download_feed(
610 client: &Client,
611 config: &ThreatIntelConfig,
612 feed_name: &str,
613 feed_config: &FeedConfig,
614 ) -> Result<(), Box<dyn std::error::Error>> {
615 debug!("Downloading feed: {} from {}", feed_name, feed_config.url);
616
617 let mut request = client.get(&feed_config.url);
618
619 for (key, value) in &feed_config.headers {
621 request = request.header(key, value);
622 }
623
624 let mut request_url = feed_config.url.clone();
625
626 if let Some(api_key) = &feed_config.api_key {
628 match feed_name {
629 name if name.contains("virustotal") => {
630 request = request.header("X-Apikey", api_key);
631 }
632 name if name.contains("maxmind") => {
633 let sep = if request_url.contains('?') { '&' } else { '?' };
636 request_url = format!(
637 "{}{}license_key={}",
638 request_url,
639 sep,
640 urlencoding::encode(api_key)
641 );
642 request = client.get(&request_url);
643 for (key, value) in &feed_config.headers {
645 request = request.header(key, value);
646 }
647 }
648 _ => {
649 request = request.header("Authorization", format!("Bearer {}", api_key));
651 }
652 }
653 }
654
655 let response = request.send().await?;
656
657 if !response.status().is_success() {
658 return Err(format!(
659 "HTTP error {}: {}",
660 response.status(),
661 response.text().await?
662 )
663 .into());
664 }
665
666 let content = response.bytes().await?;
667 let file_path = config.feeds_directory.join(&feed_config.filename);
668
669 if feed_config.filename.ends_with(".tar.gz") {
671 Self::extract_compressed_feed(&content, &file_path).await?;
673 } else {
674 fs::write(&file_path, &content).await?;
675 }
676
677 info!("Saved feed {} to {}", feed_name, file_path.display());
678
679 Self::validate_feed_format(&file_path, &feed_config.format)?;
681
682 Ok(())
683 }
684
685 async fn extract_compressed_feed(
687 content: &[u8],
688 output_path: &Path,
689 ) -> Result<(), Box<dyn std::error::Error>> {
690 let extension = output_path
692 .extension()
693 .and_then(|ext| ext.to_str())
694 .unwrap_or("");
695
696 match extension.to_lowercase().as_str() {
697 "gz" | "tar" => Self::extract_tar_gz(content, output_path).await,
698 "zip" => Err(format!(
699 "zip extraction is not supported: {} was not extracted",
700 output_path.display()
701 )
702 .into()),
703 "bz2" => Self::extract_bzip2(content, output_path).await,
704 "xz" => Self::extract_xz(content, output_path).await,
705 _ => {
706 fs::write(output_path, content).await?;
708 warn!(
709 "Unknown compression format '{}' - saved as-is: {}",
710 extension,
711 output_path.display()
712 );
713 Ok(())
714 }
715 }
716 }
717
718 async fn extract_tar_gz(
720 content: &[u8],
721 output_path: &Path,
722 ) -> Result<(), Box<dyn std::error::Error>> {
723 info!("Extracting tar.gz archive to: {}", output_path.display());
724
725 let content = content.to_vec();
726 let dest = output_path
727 .parent()
728 .unwrap_or_else(|| Path::new("."))
729 .to_path_buf();
730
731 tokio::task::spawn_blocking(move || -> Result<(), String> {
732 let decoder = flate2::read::GzDecoder::new(content.as_slice());
733 let mut archive = tar::Archive::new(decoder);
734 let canonical_dest = dest.canonicalize().map_err(|e| e.to_string())?;
735
736 for entry in archive.entries().map_err(|e| e.to_string())? {
737 let mut entry = entry.map_err(|e| e.to_string())?;
738 let path = entry.path().map_err(|e| e.to_string())?.into_owned();
739
740 let kind = entry.header().entry_type();
742 if !(kind.is_file() || kind.is_dir()) {
743 return Err(format!(
744 "Archive entry {} has unsupported type {:?}: only files and directories are extracted",
745 path.display(),
746 kind
747 ));
748 }
749
750 if path.is_absolute()
752 || path
753 .components()
754 .any(|c| matches!(c, std::path::Component::ParentDir))
755 {
756 return Err(format!(
757 "Zip Slip: archive entry has unsafe path: {}",
758 path.display()
759 ));
760 }
761
762 let target = canonical_dest.join(&path);
763 if !target.starts_with(&canonical_dest) {
765 return Err(format!(
766 "Zip Slip: entry escapes destination: {}",
767 path.display()
768 ));
769 }
770
771 let unpacked = entry
773 .unpack_in(&canonical_dest)
774 .map_err(|e| e.to_string())?;
775 if !unpacked {
776 return Err(format!(
777 "Zip Slip: entry escapes destination: {}",
778 path.display()
779 ));
780 }
781 }
782 Ok(())
783 })
784 .await
785 .map_err(|e| -> Box<dyn std::error::Error> { e.to_string().into() })?
786 .map_err(|e| -> Box<dyn std::error::Error> { e.into() })?;
787
788 Ok(())
789 }
790
791 async fn extract_bzip2(
800 _content: &[u8],
801 output_path: &Path,
802 ) -> Result<(), Box<dyn std::error::Error>> {
803 Err(format!(
804 "bzip2 extraction is not supported: add the `bzip2` crate to Cargo.toml \
805 to enable decompression to {}",
806 output_path.display()
807 )
808 .into())
809 }
810
811 async fn extract_xz(
820 _content: &[u8],
821 output_path: &Path,
822 ) -> Result<(), Box<dyn std::error::Error>> {
823 Err(format!(
824 "XZ extraction is not supported: add the `xz2` crate to Cargo.toml \
825 to enable decompression to {}",
826 output_path.display()
827 )
828 .into())
829 }
830
831 fn validate_feed_format(
833 file_path: &Path,
834 format: &FeedFormat,
835 ) -> Result<(), Box<dyn std::error::Error>> {
836 let content = std::fs::read_to_string(file_path)?;
837
838 match format {
839 FeedFormat::PlainText => {
840 let lines: Vec<&str> = content
842 .lines()
843 .filter(|l| !l.trim().is_empty() && !l.starts_with('#'))
844 .collect();
845 if lines.is_empty() {
846 return Err("Feed appears to be empty".into());
847 }
848 }
849 FeedFormat::Csv => {
850 let mut reader = csv::Reader::from_reader(content.as_bytes());
851 if reader.headers().is_err() {
852 return Err("Invalid CSV format".into());
853 }
854 }
855 FeedFormat::Json => {
856 serde_json::from_str::<serde_json::Value>(&content)?;
857 }
858 FeedFormat::Xml => {
859 if !content.trim_start().starts_with('<') {
861 return Err("Invalid XML format".into());
862 }
863 }
864 }
865
866 debug!("Feed format validation passed: {}", file_path.display());
867 Ok(())
868 }
869
870 pub async fn get_feed_status(&self) -> HashMap<String, FeedStatus> {
872 let mut status = HashMap::new();
873
874 for (feed_name, feed_config) in &self.config.feeds {
875 let file_path = self.config.feeds_directory.join(&feed_config.filename);
876
877 let feed_status = if feed_config.enabled {
878 if file_path.exists() {
879 if let Ok(metadata) = fs::metadata(&file_path).await {
880 FeedStatus::Active {
881 last_updated: metadata
882 .modified()
883 .unwrap_or(std::time::SystemTime::UNIX_EPOCH),
884 size_bytes: metadata.len(),
885 }
886 } else {
887 FeedStatus::Error("Cannot read file metadata".to_string())
888 }
889 } else {
890 FeedStatus::NotDownloaded
891 }
892 } else {
893 FeedStatus::Disabled
894 };
895
896 status.insert(feed_name.clone(), feed_status);
897 }
898
899 status
900 }
901
902 pub async fn update_feed(&self, feed_name: &str) -> Result<(), Box<dyn std::error::Error>> {
904 if let Some(feed_config) = self.config.feeds.get(feed_name) {
905 if feed_config.enabled {
906 Self::download_feed(&self.client, &self.config, feed_name, feed_config).await
907 } else {
908 Err(format!("Feed '{}' is disabled", feed_name).into())
909 }
910 } else {
911 Err(format!("Feed '{}' not found", feed_name).into())
912 }
913 }
914
915 pub fn is_malicious_ip(&self, ip: &std::net::IpAddr) -> bool {
917 for (feed_name, feed_config) in &self.config.feeds {
918 if !feed_config.enabled {
919 continue;
920 }
921
922 if matches!(feed_config.feed_type, FeedType::MaliciousIPs) {
923 let file_path = self.config.feeds_directory.join(&feed_config.filename);
924 if self.check_ip_in_feed(&file_path, ip) {
925 tracing::warn!("Malicious IP detected: {} (source: {})", ip, feed_name);
926 return true;
927 }
928 }
929 }
930 false
931 }
932
933 pub fn is_tor_exit(&self, ip: &std::net::IpAddr) -> bool {
935 for (feed_name, feed_config) in &self.config.feeds {
936 if !feed_config.enabled {
937 continue;
938 }
939
940 if matches!(feed_config.feed_type, FeedType::TorExitNodes) {
941 let file_path = self.config.feeds_directory.join(&feed_config.filename);
942 if self.check_ip_in_feed(&file_path, ip) {
943 tracing::warn!("Tor exit node detected: {} (source: {})", ip, feed_name);
944 return true;
945 }
946 }
947 }
948 false
949 }
950
951 pub fn is_proxy_vpn(&self, ip: &std::net::IpAddr) -> bool {
953 for (feed_name, feed_config) in &self.config.feeds {
954 if !feed_config.enabled {
955 continue;
956 }
957
958 if matches!(feed_config.feed_type, FeedType::VpnProxy) {
959 let file_path = self.config.feeds_directory.join(&feed_config.filename);
960 if self.check_ip_in_feed(&file_path, ip) {
961 tracing::info!("VPN/Proxy detected: {} (source: {})", ip, feed_name);
962 return true;
963 }
964 }
965 }
966 false
967 }
968
969 fn check_ip_in_feed(&self, file_path: &std::path::Path, ip: &std::net::IpAddr) -> bool {
971 if !file_path.exists() {
972 return false;
973 }
974
975 if let Ok(contents) = std::fs::read_to_string(file_path) {
976 for line in contents.lines() {
977 let line = line.trim();
978 if line.is_empty() || line.starts_with('#') {
979 continue;
980 }
981
982 if line == ip.to_string() {
984 return true;
985 }
986
987 if line.contains('/') {
989 match ip {
990 std::net::IpAddr::V4(ipv4) => {
991 if let Ok(network) = line.parse::<ipnetwork::Ipv4Network>()
992 && network.contains(*ipv4)
993 {
994 return true;
995 }
996 }
997 std::net::IpAddr::V6(ipv6) => {
998 if let Ok(network) = line.parse::<ipnetwork::Ipv6Network>()
999 && network.contains(*ipv6)
1000 {
1001 return true;
1002 }
1003 }
1004 }
1005 }
1006 }
1007 }
1008
1009 false
1010 }
1011}
1012
1013#[derive(Debug, Clone)]
1015pub enum FeedStatus {
1016 Disabled,
1018
1019 NotDownloaded,
1021
1022 Active {
1024 last_updated: std::time::SystemTime,
1025 size_bytes: u64,
1026 },
1027
1028 Error(String),
1030}