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
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
// CipherRun - Multi-IP Terminal Output Module
// Copyright (C) 2024 Marc Rivero López
// Licensed under GPL-3.0

//! Terminal output formatting for multi-IP scan reports
//!
//! This module provides formatted terminal output for multi-IP scanning,
//! including per-IP breakdowns, inconsistency detection, and aggregated results.

use crate::scanner::aggregation::AggregatedScanResult;
use crate::scanner::inconsistency::{
    Inconsistency, InconsistencyDetails, InconsistencyType, SingleIpScanResult,
};
use crate::scanner::multi_ip::MultiIpScanReport;
use colored::*;
use std::fmt;

/// Display implementation for MultiIpScanReport
impl fmt::Display for MultiIpScanReport {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        // Header
        writeln!(
            f,
            "\n╔═══════════════════════════════════════════════════════════╗"
        )?;
        writeln!(
            f,
            "║              MULTI-IP SCAN REPORT                         ║"
        )?;
        writeln!(
            f,
            "╚═══════════════════════════════════════════════════════════╝\n"
        )?;

        writeln!(
            f,
            "Target: {}:{}",
            self.target.hostname.green().bold(),
            self.target.port
        )?;
        writeln!(
            f,
            "IPs Scanned: {}/{} successful",
            self.successful_scans.to_string().green(),
            self.total_ips
        )?;
        writeln!(
            f,
            "Total Duration: {:.2}s\n",
            self.total_duration_ms as f64 / 1000.0
        )?;

        // Inconsistency warning if present
        if !self.inconsistencies.is_empty() {
            writeln!(
                f,
                "{}",
                "⚠ LOAD BALANCER INCONSISTENCIES DETECTED".yellow().bold()
            )?;
            writeln!(
                f,
                "  {} configuration difference{} found across backends\n",
                self.inconsistencies.len(),
                if self.inconsistencies.len() == 1 {
                    ""
                } else {
                    "s"
                }
            )?;
        }

        // Per-IP Results Section
        writeln!(f, "{}", "Per-IP Results:".cyan().bold())?;
        writeln!(f, "{}", "".repeat(60))?;
        writeln!(f)?;

        // Sort IPs for consistent display
        let mut ips: Vec<_> = self.per_ip_results.keys().collect();
        ips.sort();

        for ip in ips {
            if let Some(result) = self.per_ip_results.get(ip) {
                self.display_single_ip_result(f, result)?;
            }
        }

        // Inconsistencies Section
        if !self.inconsistencies.is_empty() {
            writeln!(f, "\n{}", "Inconsistencies Detected:".yellow().bold())?;
            writeln!(f, "{}", "".repeat(60))?;
            writeln!(f)?;

            for inconsistency in &self.inconsistencies {
                self.display_inconsistency(f, inconsistency)?;
            }
        }

        // Aggregated Results Section
        writeln!(
            f,
            "\n{}",
            "Aggregated Results (Conservative):".cyan().bold()
        )?;
        writeln!(f, "{}", "".repeat(60))?;
        writeln!(f)?;

        self.display_aggregated_results(f, &self.aggregated)?;

        // Recommendations Section
        if !self.inconsistencies.is_empty() {
            writeln!(f, "\n{}", "Recommendations:".green().bold())?;
            writeln!(f, "{}", "".repeat(60))?;
            writeln!(f)?;
            self.display_recommendations(f)?;
        }

        Ok(())
    }
}

impl MultiIpScanReport {
    /// Display a single IP's scan result
    fn display_single_ip_result(
        &self,
        f: &mut fmt::Formatter<'_>,
        result: &SingleIpScanResult,
    ) -> fmt::Result {
        if let Some(ref error) = result.error {
            writeln!(
                f,
                "  {} {} - {}",
                "".red(),
                result.ip.to_string().yellow(),
                "FAILED".red().bold()
            )?;
            writeln!(f, "    Error: {}", error.red())?;
            writeln!(f, "    Scan Time: {}ms\n", result.scan_duration_ms)?;
        } else {
            writeln!(f, "  {} {}", "".green(), result.ip.to_string().yellow())?;

            // Display grade if available
            if let Some(rating) = result.scan_result.ssl_rating() {
                let grade_str = format!("{}", rating.grade);
                let grade_colored = Self::color_grade(&grade_str, rating.score);
                writeln!(f, "    Grade: {} ({}/100)", grade_colored, rating.score)?;
            }

            // Display protocol support
            let tls13 = result
                .scan_result
                .protocols
                .iter()
                .any(|p| p.protocol == crate::protocols::Protocol::TLS13 && p.supported);
            let tls12 = result
                .scan_result
                .protocols
                .iter()
                .any(|p| p.protocol == crate::protocols::Protocol::TLS12 && p.supported);

            writeln!(
                f,
                "    TLS 1.3: {}",
                if tls13 { "".green() } else { "".red() }
            )?;
            writeln!(
                f,
                "    TLS 1.2: {}",
                if tls12 { "".green() } else { "".red() }
            )?;

            // Display cipher count
            let cipher_count: usize = result
                .scan_result
                .ciphers
                .values()
                .map(|s| s.supported_ciphers.len())
                .sum();
            if cipher_count > 0 {
                writeln!(f, "    Cipher Suites: {} total", cipher_count)?;
            }

            // Display certificate info
            if let Some(ref cert_chain) = result.scan_result.certificate_chain {
                let cert_status = if cert_chain.validation.valid {
                    "Valid".green()
                } else {
                    "Invalid".red()
                };
                writeln!(f, "    Certificate: {}", cert_status)?;
            }

            writeln!(f, "    Scan Time: {}ms\n", result.scan_duration_ms)?;
        }

        Ok(())
    }

    /// Display a detected inconsistency
    fn display_inconsistency(
        &self,
        f: &mut fmt::Formatter<'_>,
        inconsistency: &Inconsistency,
    ) -> fmt::Result {
        let severity_colored = match inconsistency.severity {
            crate::vulnerabilities::Severity::Critical => "CRITICAL".red().bold(),
            crate::vulnerabilities::Severity::High => "HIGH".red(),
            crate::vulnerabilities::Severity::Medium => "MEDIUM".yellow(),
            crate::vulnerabilities::Severity::Low => "LOW".normal(),
            crate::vulnerabilities::Severity::Info => "INFO".cyan(),
        };

        writeln!(
            f,
            "{} {} - {}",
            "".yellow(),
            inconsistency.inconsistency_type,
            severity_colored
        )?;
        writeln!(f, "  {}", inconsistency.description)?;

        // Display specific details based on type
        match &inconsistency.details {
            InconsistencyDetails::Protocols {
                protocol,
                ips_with_support,
                ips_without_support,
            } => {
                writeln!(
                    f,
                    "  IPs WITH {}: {}",
                    protocol.name(),
                    ips_with_support
                        .iter()
                        .map(|ip| ip.to_string())
                        .collect::<Vec<_>>()
                        .join(", ")
                        .green()
                )?;
                writeln!(
                    f,
                    "  IPs WITHOUT {}: {}",
                    protocol.name(),
                    ips_without_support
                        .iter()
                        .map(|ip| ip.to_string())
                        .collect::<Vec<_>>()
                        .join(", ")
                        .red()
                )?;
            }
            InconsistencyDetails::Certificates { fingerprints } => {
                writeln!(f, "  Different certificates detected:")?;
                for (ip, fingerprint) in fingerprints {
                    writeln!(
                        f,
                        "    {} -> {}",
                        ip.to_string().yellow(),
                        fingerprint[..16].to_string().dimmed()
                    )?;
                }
            }
            InconsistencyDetails::Grades { grades } => {
                writeln!(f, "  Grade distribution:")?;
                for (ip, (grade, score)) in grades {
                    let grade_colored = Self::color_grade(grade, *score);
                    writeln!(
                        f,
                        "    {} -> {} ({}/100)",
                        ip.to_string().yellow(),
                        grade_colored,
                        score
                    )?;
                }
            }
            InconsistencyDetails::CipherSuites { differences } => {
                writeln!(
                    f,
                    "  {} unique cipher configurations detected",
                    differences.len()
                )?;
            }
            InconsistencyDetails::SessionResumption {
                ips_with_caching,
                ips_with_tickets,
                ips_without,
            } => {
                if !ips_with_caching.is_empty() {
                    writeln!(
                        f,
                        "  With Caching: {}",
                        ips_with_caching
                            .iter()
                            .map(|ip| ip.to_string())
                            .collect::<Vec<_>>()
                            .join(", ")
                    )?;
                }
                if !ips_with_tickets.is_empty() {
                    writeln!(
                        f,
                        "  With Tickets: {}",
                        ips_with_tickets
                            .iter()
                            .map(|ip| ip.to_string())
                            .collect::<Vec<_>>()
                            .join(", ")
                    )?;
                }
                if !ips_without.is_empty() {
                    writeln!(
                        f,
                        "  Without Resumption: {}",
                        ips_without
                            .iter()
                            .map(|ip| ip.to_string())
                            .collect::<Vec<_>>()
                            .join(", ")
                            .red()
                    )?;
                }
            }
            InconsistencyDetails::Alpn { protocols_by_ip } => {
                writeln!(f, "  ALPN protocols by IP:")?;
                for (ip, protocols) in protocols_by_ip {
                    writeln!(
                        f,
                        "    {} -> {}",
                        ip.to_string().yellow(),
                        protocols.join(", ")
                    )?;
                }
            }
        }

        writeln!(f)?;
        Ok(())
    }

    /// Display aggregated results
    fn display_aggregated_results(
        &self,
        f: &mut fmt::Formatter<'_>,
        aggregated: &AggregatedScanResult,
    ) -> fmt::Result {
        let grade_colored = Self::color_grade(&aggregated.grade.0, aggregated.grade.1);
        writeln!(
            f,
            "  Overall Grade: {} ({}/100)",
            grade_colored, aggregated.grade.1
        )?;
        writeln!(f, "  {} Based on WORST backend performance\n", "".cyan())?;

        writeln!(f, "  Protocols (supported by ALL backends):")?;
        for protocol_result in &aggregated.protocols {
            if protocol_result.supported {
                writeln!(f, "    {} {}", "".green(), protocol_result.protocol.name())?;
            }
        }

        if !aggregated.certificate_consistent {
            writeln!(
                f,
                "\n  {} Multiple different certificates detected across backends",
                "".yellow()
            )?;
        }

        if !aggregated.alpn_protocols.is_empty() {
            writeln!(f, "\n  ALPN Protocols (supported by all):")?;
            writeln!(f, "    {}", aggregated.alpn_protocols.join(", ").cyan())?;
        }

        writeln!(f, "\n  Session Resumption:")?;
        writeln!(
            f,
            "    Caching: {}",
            if aggregated.session_resumption_caching {
                "✓ All backends".green()
            } else {
                "✗ Not all backends".red()
            }
        )?;
        writeln!(
            f,
            "    Tickets: {}",
            if aggregated.session_resumption_tickets {
                "✓ All backends".green()
            } else {
                "✗ Not all backends".red()
            }
        )?;

        Ok(())
    }

    /// Display recommendations based on detected inconsistencies
    fn display_recommendations(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let has_protocol_inconsistency = self
            .inconsistencies
            .iter()
            .any(|i| i.inconsistency_type == InconsistencyType::ProtocolSupport);
        let has_cert_inconsistency = self
            .inconsistencies
            .iter()
            .any(|i| i.inconsistency_type == InconsistencyType::Certificates);
        let has_cipher_inconsistency = self
            .inconsistencies
            .iter()
            .any(|i| i.inconsistency_type == InconsistencyType::CipherSuites);

        if has_protocol_inconsistency {
            writeln!(
                f,
                "  {} Standardize TLS protocol support across all backend servers",
                "".yellow()
            )?;
            writeln!(
                f,
                "     Enable TLS 1.3 on all backends for consistent security posture"
            )?;
        }

        if has_cert_inconsistency {
            writeln!(
                f,
                "  {} Ensure all backend servers use the same certificate",
                "".yellow()
            )?;
            writeln!(
                f,
                "     Different certificates can cause browser warnings and trust issues"
            )?;
        }

        if has_cipher_inconsistency {
            writeln!(
                f,
                "  {} Align cipher suite configurations across all backends",
                "".yellow()
            )?;
            writeln!(
                f,
                "     Use the same cipher suite list and preferences on all servers"
            )?;
        }

        writeln!(
            f,
            "\n  {} Configuration inconsistencies can lead to:",
            "".cyan()
        )?;
        writeln!(f, "     - Unpredictable behavior for end users")?;
        writeln!(f, "     - Security vulnerabilities if weak backends exist")?;
        writeln!(f, "     - Difficult troubleshooting and maintenance")?;

        Ok(())
    }

    /// Helper to color grade strings
    fn color_grade(grade: &str, score: u8) -> colored::ColoredString {
        use crate::rating::Grade;

        // Parse the grade based on score
        let grade_enum = Grade::from_score(score);
        let grade_str = grade.to_string();

        match grade_enum {
            Grade::APlus | Grade::A => grade_str.green().bold(),
            Grade::AMinus | Grade::B => grade_str.blue().bold(),
            Grade::C => grade_str.yellow(),
            Grade::D | Grade::E | Grade::F => grade_str.red(),
            Grade::T | Grade::M => grade_str.red().bold(),
        }
    }
}