Skip to main content

shadow_network_sim/
lib.rs

1//! # Network Simulation
2//!
3//! Adversary modelling, censorship simulation, correlation attacks,
4//! and statistical traffic analysis:
5//! - **Adversary Models**: Passive observer, active attacker, global observer, compromised relays
6//! - **Censorship Simulation**: IP/port blocking, DPI, throttling, TCP reset
7//! - **Correlation Analysis**: Timing & size correlation between traffic flows
8//! - **Statistical Analysis**: Entropy, chi-squared, pattern detection, timing regularity
9//!
10//! ```rust
11//! use shadow_network_sim::{CensorshipSimulator, CorrelationAnalyzer, StatisticalAnalyzer};
12//! let censor = CensorshipSimulator::with_standard_rules();
13//! let analyzer = CorrelationAnalyzer::new();
14//! let stats = StatisticalAnalyzer::new();
15//! ```
16
17pub mod adversary;
18pub mod analysis;
19pub mod censorship;
20pub mod correlation;
21
22pub use adversary::{
23    AdversaryCapabilities, AdversaryModel, AdversaryType, ObservedFlow,
24};
25pub use analysis::{AnalysisResult, StatisticalAnalyzer};
26pub use censorship::{
27    BlockingRule, CensorResult, CensorStats, CensorshipMethod, CensorshipSimulator,
28    SimulatedPacket,
29};
30pub use correlation::{CorrelationAnalyzer, CorrelationResult, FlowRecord};
31
32/// Verify the full network simulation system.
33/// Returns (adversary_ok, censorship_ok, correlation_ok, analysis_ok).
34pub fn verify_network_simulation() -> (bool, bool, bool, bool) {
35    // 1. Adversary modeling
36    let adversary_ok = {
37        let model = AdversaryModel::new(AdversaryType::PassiveObserver);
38        model.capabilities.can_observe_metadata
39            && !model.capabilities.can_inject
40            && model.capabilities.threat_level() > 0.0
41    };
42
43    // 2. Censorship simulation
44    let censorship_ok = {
45        let mut sim = CensorshipSimulator::with_standard_rules();
46        let blocked = SimulatedPacket {
47            source_ip: "10.0.0.1".into(),
48            dest_ip: "1.2.3.4".into(),
49            source_port: 12345,
50            dest_port: 9001,
51            payload: vec![0u8; 64],
52            protocol: "TCP".into(),
53        };
54        let allowed = SimulatedPacket {
55            dest_port: 80,
56            ..blocked.clone()
57        };
58        matches!(sim.check_packet(&blocked), CensorResult::Blocked(_))
59            && sim.check_packet(&allowed) == CensorResult::Allowed
60    };
61
62    // 3. Correlation analysis
63    let correlation_ok = {
64        let analyzer = CorrelationAnalyzer::new();
65        let mut a = FlowRecord::new("a");
66        let mut b = FlowRecord::new("b");
67        // Use varying delays so timing correlation is meaningful
68        let timestamps_a = [0u64, 1000, 2500, 4500, 7000];
69        let timestamps_b = [50u64, 1050, 2550, 4550, 7050];
70        let sizes = [100, 200, 150, 300, 250];
71        for i in 0..5 {
72            a.add_packet(sizes[i], timestamps_a[i], true);
73            b.add_packet(sizes[i], timestamps_b[i], true);
74        }
75        let result = analyzer.correlate(&a, &b);
76        result.combined_score > 0.5
77    };
78
79    // 4. Statistical analysis
80    let analysis_ok = {
81        let analyzer = StatisticalAnalyzer::new();
82        // Generate pseudo-random data via hashing
83        let mut data = Vec::new();
84        for i in 0u32..100 {
85            let hash = crypto::hash_data(&i.to_le_bytes());
86            data.extend_from_slice(hash.as_bytes());
87        }
88        let entropy = analyzer.byte_entropy(&data);
89        entropy > 7.0
90    };
91
92    (adversary_ok, censorship_ok, correlation_ok, analysis_ok)
93}
94
95#[cfg(test)]
96mod tests {
97    use super::*;
98
99    #[test]
100    fn test_verify_all() {
101        let (adv, censor, corr, analysis) = verify_network_simulation();
102        assert!(adv, "Adversary check failed");
103        assert!(censor, "Censorship check failed");
104        assert!(corr, "Correlation check failed");
105        assert!(analysis, "Analysis check failed");
106    }
107
108    #[test]
109    fn test_end_to_end_scenario() {
110        // Simulate: generate traffic, apply censorship, check correlation resistance
111        let mut censor = CensorshipSimulator::new();
112        censor.add_rule(BlockingRule::dpi_rule("PLAINTEXT_SIG"));
113
114        // Encrypted packet evades DPI
115        let encrypted_pkt = SimulatedPacket {
116            source_ip: "10.0.0.1".into(),
117            dest_ip: "10.0.0.2".into(),
118            source_port: 443,
119            dest_port: 443,
120            payload: vec![0xAB; 128], // encrypted-looking
121            protocol: "TLS".into(),
122        };
123        assert_eq!(censor.check_packet(&encrypted_pkt), CensorResult::Allowed);
124
125        // Analyze the encrypted payload
126        let analyzer = StatisticalAnalyzer::new();
127        let entropy = analyzer.byte_entropy(&encrypted_pkt.payload);
128        // Single byte repeated = 0 entropy, but it's "encrypted-looking" for the censor
129        // Real encrypted data would have high entropy
130        assert!(entropy >= 0.0);
131    }
132}