cipherrun 0.3.0

A fast, modular, and scalable TLS/SSL security scanner written in Rust
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
// Anycast Detection Module
// Resolves all A/AAAA records and scans each IP individually
// Detects Anycast deployments by comparing certificates and behaviors

use crate::Args;
use crate::Result;
use crate::error::TlsError;
use crate::scanner::ScanResults;
use crate::utils::network::Target;
use serde::{Deserialize, Serialize};
use std::collections::{HashMap, HashSet};
use std::net::IpAddr;
use hickory_resolver::TokioAsyncResolver;
use hickory_resolver::config::*;

/// Anycast scanner for testing all IPs of a hostname
pub struct AnycastScanner {
    hostname: String,
    port: u16,
    args: Args,
}

impl AnycastScanner {
    /// Create new anycast scanner
    pub fn new(hostname: String, port: u16, args: Args) -> Self {
        Self {
            hostname,
            port,
            args,
        }
    }

    /// Scan all IPs resolved for the hostname
    pub async fn scan_all_ips(&self) -> Result<AnycastScanResults> {
        // 1. Resolve hostname to all IPs (A + AAAA records)
        let ip_addresses = self.resolve_all_ips().await?;

        if ip_addresses.is_empty() {
            return Err(TlsError::DnsResolutionFailed {
                hostname: self.hostname.clone(),
                source: std::io::Error::new(
                    std::io::ErrorKind::NotFound,
                    "No IP addresses resolved",
                ),
            });
        }

        println!(
            "  Resolved {} IP address(es) for {}",
            ip_addresses.len(),
            self.hostname
        );

        // 2. Scan each IP individually
        let mut ip_results = Vec::new();
        for (index, ip) in ip_addresses.iter().enumerate() {
            println!(
                "  [{}/{}] Scanning IP: {}",
                index + 1,
                ip_addresses.len(),
                ip
            );

            match self.scan_single_ip(ip).await {
                Ok(scan_result) => {
                    ip_results.push(IpScanResult {
                        ip: *ip,
                        results: scan_result,
                        error: None,
                    });
                }
                Err(e) => {
                    println!("    Warning: Scan failed for {}: {}", ip, e);
                    ip_results.push(IpScanResult {
                        ip: *ip,
                        results: ScanResults::default(),
                        error: Some(e.to_string()),
                    });
                }
            }
        }

        // 3. Detect Anycast deployment
        let anycast_detection = Self::detect_anycast(&ip_results);

        Ok(AnycastScanResults {
            hostname: self.hostname.clone(),
            port: self.port,
            total_ips: ip_addresses.len(),
            successful_scans: ip_results.iter().filter(|r| r.error.is_none()).count(),
            ip_results,
            anycast_detection,
        })
    }

    /// Resolve all A and AAAA records for hostname
    async fn resolve_all_ips(&self) -> Result<Vec<IpAddr>> {
        let resolver =
            TokioAsyncResolver::tokio(ResolverConfig::default(), ResolverOpts::default());

        let mut ips = Vec::new();

        // Query A records (IPv4)
        if !self.args.network.ipv6_only {
            match resolver.ipv4_lookup(&self.hostname).await {
                Ok(lookup) => {
                    for ipv4 in lookup.iter() {
                        ips.push(IpAddr::V4(ipv4.0));
                    }
                }
                Err(_) => {
                    // A records not found, continue
                }
            }
        }

        // Query AAAA records (IPv6)
        if !self.args.network.ipv4_only {
            match resolver.ipv6_lookup(&self.hostname).await {
                Ok(lookup) => {
                    for ipv6 in lookup.iter() {
                        ips.push(IpAddr::V6(ipv6.0));
                    }
                }
                Err(_) => {
                    // AAAA records not found, continue
                }
            }
        }

        Ok(ips)
    }

    /// Scan a single IP address with SNI=hostname
    async fn scan_single_ip(&self, ip: &IpAddr) -> Result<ScanResults> {
        // Create target with specific IP (unused but kept for potential future use)
        let _target = Target::with_ips(self.hostname.clone(), self.port, vec![*ip])?;

        // Create scanner with modified args (use IP directly)
        let mut scanner_args = self.args.clone();
        scanner_args.target = Some(format!("{}:{}", ip, self.port));

        // Override SNI to use original hostname
        if scanner_args.tls.sni_name.is_none() {
            scanner_args.tls.sni_name = Some(self.hostname.clone());
        }

        // Create and run scanner
        let scanner = crate::scanner::Scanner::new(scanner_args)?;
        scanner.run().await
    }

    /// Detect Anycast deployment by comparing scan results
    fn detect_anycast(results: &[IpScanResult]) -> AnycastDetection {
        let successful_results: Vec<_> = results.iter().filter(|r| r.error.is_none()).collect();

        if successful_results.len() < 2 {
            return AnycastDetection {
                is_anycast: false,
                confidence: 0.0,
                reasons: vec!["Insufficient successful scans to determine Anycast".to_string()],
                certificate_fingerprints: HashSet::new(),
                cipher_preferences: HashMap::new(),
                protocol_support: HashMap::new(),
            };
        }

        let mut is_anycast = false;
        let mut reasons = Vec::new();
        let mut certificate_fingerprints = HashSet::new();
        let mut cipher_preferences: HashMap<IpAddr, String> = HashMap::new();
        let mut protocol_support: HashMap<IpAddr, Vec<String>> = HashMap::new();

        // Compare certificate fingerprints
        for result in &successful_results {
            if let Some(cert) = &result.results.certificate_chain
                && let Some(fingerprint) =
                    &cert.chain.leaf().and_then(|c| c.fingerprint_sha256.clone())
            {
                certificate_fingerprints.insert(fingerprint.clone());
            }

            // Extract cipher preferences
            if let Some(first_protocol) = result.results.ciphers.values().next()
                && let Some(preferred_cipher) = &first_protocol.preferred_cipher
            {
                cipher_preferences.insert(result.ip, preferred_cipher.openssl_name.clone());
            }

            // Extract protocol support
            let protocols: Vec<String> = result
                .results
                .protocols
                .iter()
                .filter(|p| p.supported)
                .map(|p| p.protocol.to_string())
                .collect();
            protocol_support.insert(result.ip, protocols);
        }

        // Check for different certificates (strong Anycast indicator)
        if certificate_fingerprints.len() > 1 {
            is_anycast = true;
            reasons.push(format!(
                "Different certificates detected ({} unique fingerprints)",
                certificate_fingerprints.len()
            ));
        }

        // Check for different cipher preferences
        let unique_ciphers: HashSet<_> = cipher_preferences.values().cloned().collect();
        if unique_ciphers.len() > 1 {
            is_anycast = true;
            reasons.push(format!(
                "Different cipher preferences detected ({} unique)",
                unique_ciphers.len()
            ));
        }

        // Check for different protocol support
        let protocol_sets: Vec<HashSet<String>> = protocol_support
            .values()
            .map(|v| v.iter().cloned().collect())
            .collect();

        if protocol_sets.len() >= 2 {
            let first_set = &protocol_sets[0];
            if protocol_sets.iter().any(|set| set != first_set) {
                is_anycast = true;
                reasons.push("Different protocol support detected".to_string());
            }
        }

        // Calculate confidence score
        let confidence = if is_anycast {
            let mut score: f32 = 0.0;

            // Certificate differences = high confidence
            if certificate_fingerprints.len() > 1 {
                score += 0.7;
            }

            // Cipher differences = medium confidence
            if unique_ciphers.len() > 1 {
                score += 0.2;
            }

            // Protocol differences = low confidence
            if protocol_sets.len() >= 2 && protocol_sets.iter().any(|s| s != &protocol_sets[0]) {
                score += 0.1;
            }

            score.min(1.0)
        } else if certificate_fingerprints.len() == 1
            && unique_ciphers.len() == 1
            && protocol_sets.iter().all(|s| s == &protocol_sets[0])
        {
            0.0 // Not Anycast
        } else {
            0.5 // Uncertain
        };

        if !is_anycast && certificate_fingerprints.len() == 1 {
            reasons.push("All IPs return identical certificates".to_string());
            reasons.push("All IPs have matching cipher preferences".to_string());
            reasons.push("All IPs have identical protocol support".to_string());
        }

        AnycastDetection {
            is_anycast,
            confidence: confidence as f64,
            reasons,
            certificate_fingerprints,
            cipher_preferences,
            protocol_support,
        }
    }
}

/// Result of scanning a single IP
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct IpScanResult {
    pub ip: IpAddr,
    pub results: ScanResults,
    pub error: Option<String>,
}

/// Complete Anycast scan results
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AnycastScanResults {
    pub hostname: String,
    pub port: u16,
    pub total_ips: usize,
    pub successful_scans: usize,
    pub ip_results: Vec<IpScanResult>,
    pub anycast_detection: AnycastDetection,
}

/// Anycast detection result
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AnycastDetection {
    pub is_anycast: bool,
    pub confidence: f64,
    pub reasons: Vec<String>,
    pub certificate_fingerprints: HashSet<String>,
    pub cipher_preferences: HashMap<IpAddr, String>,
    pub protocol_support: HashMap<IpAddr, Vec<String>>,
}

impl AnycastScanResults {
    /// Display results summary
    pub fn display_summary(&self) {
        use colored::*;

        println!("\n{}", "=".repeat(60).cyan());
        println!("{}", "Anycast Scan Results".cyan().bold());
        println!("{}", "=".repeat(60).cyan());

        println!("Hostname:         {}", self.hostname.green());
        println!("Port:             {}", self.port);
        println!("Total IPs:        {}", self.total_ips);
        println!(
            "Successful Scans: {}/{}",
            self.successful_scans, self.total_ips
        );

        println!("\n{}", "Per-IP Results:".cyan().bold());
        for result in &self.ip_results {
            if let Some(error) = &result.error {
                println!("  {} {} - {}", "".red(), result.ip, error.red());
            } else {
                let cert_status = if let Some(cert) = &result.results.certificate_chain {
                    if cert.validation.valid {
                        "Valid Cert".green()
                    } else {
                        "Invalid Cert".red()
                    }
                } else {
                    "No Cert".yellow()
                };

                let protocol_count = result
                    .results
                    .protocols
                    .iter()
                    .filter(|p| p.supported)
                    .count();

                println!(
                    "  {} {} - {} - {} protocols",
                    "".green(),
                    result.ip,
                    cert_status,
                    protocol_count
                );
            }
        }

        println!("\n{}", "Anycast Detection:".cyan().bold());
        let detection_status = if self.anycast_detection.is_anycast {
            format!(
                "YES (confidence: {:.0}%)",
                self.anycast_detection.confidence * 100.0
            )
            .red()
            .bold()
        } else {
            "NO".green().bold()
        };
        println!("  Anycast Detected: {}", detection_status);

        if !self.anycast_detection.reasons.is_empty() {
            println!("\n  Reasons:");
            for reason in &self.anycast_detection.reasons {
                println!("    - {}", reason);
            }
        }

        if self.anycast_detection.certificate_fingerprints.len() > 1 {
            println!(
                "\n  Unique Certificates: {}",
                self.anycast_detection.certificate_fingerprints.len()
            );
        }

        println!("{}", "=".repeat(60).cyan());
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_anycast_detection_different_certs() {
        let results = vec![
            IpScanResult {
                ip: "1.1.1.1".parse().unwrap(),
                results: ScanResults::default(),
                error: None,
            },
            IpScanResult {
                ip: "2.2.2.2".parse().unwrap(),
                results: ScanResults::default(),
                error: None,
            },
        ];

        // Simulate different certificate fingerprints
        // (In real code, this would come from actual certificate data)

        let detection = AnycastScanner::detect_anycast(&results);

        // With default ScanResults, we don't have cert data, so it should be uncertain
        assert!(detection.confidence >= 0.0);
    }
}