gossan-portscan 0.3.3

TCP port scanner with TLS inspection and banner grabbing for gossan, part of the security research ecosystem
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
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
use super::*;
use gossan_core::NetworkTarget;
use std::net::IpAddr;
use std::time::Duration;
use tokio::net::TcpListener;

fn service(port: u16, banner: Option<&str>) -> ServiceTarget {
    ServiceTarget {
        host: HostTarget {
            ip: IpAddr::from([127, 0, 0, 1]),
            domain: Some("example.com".into()),
        },
        port,
        protocol: Protocol::Tcp,
        banner: banner.map(str::to_string),
        tls: matches!(port, 443 | 465 | 636 | 993 | 8443),
    }
}

#[test]
fn scanner_accepts_domains_hosts_and_networks() {
    let scanner = PortScanner;
    assert!(scanner.accepts(&Target::Domain(DomainTarget {
        domain: "example.com".into(),
        source: DiscoverySource::Seed,
    })));
    assert!(scanner.accepts(&Target::Host(HostTarget {
        ip: IpAddr::from([127, 0, 0, 1]),
        domain: None,
    })));
    assert!(scanner.accepts(&Target::Network(NetworkTarget {
        cidr: "1.2.3.0/24".into(),
        source: DiscoverySource::Asn,
    })));
    assert!(!scanner.accepts(&Target::Service(service(443, None))));
}

#[test]
fn risky_ports_list_contains_high_value_targets() {
    for port in [23, 2375, 6379, 9200, 10250, 30303] {
        assert!(
            rules::risky_services().iter().any(|r| r.port == port),
            "missing risky port {port}"
        );
    }
}

#[test]
fn identify_banner_detects_old_ssh_versions_as_high() {
    let finding = identify_banner_or_probe(
        "SSH-2.0-OpenSSH_7.2p1 Ubuntu-4ubuntu2.10",
        &[], // probe_matches: tests exercise the banner path only
        &service(22, None),
        22,
    )
    .unwrap();

    assert_eq!(finding.severity(), Severity::High);
    assert!(finding.title().contains("SSH version disclosed"));
    assert!(finding.tags().iter().any(|t| t.as_ref() == "ssh"));
}

#[test]
fn identify_banner_detects_modern_ssh_versions_as_info() {
    let finding =
        identify_banner_or_probe("SSH-2.0-OpenSSH_9.7", &[], &service(22, None), 22).unwrap();

    assert_eq!(finding.severity(), Severity::Info);
}

#[test]
fn identify_banner_detects_ftp_banner() {
    let finding =
        identify_banner_or_probe("220 ProFTPD 1.3.5 Server", &[], &service(21, None), 21).unwrap();
    assert!(finding.title().contains("FTP banner"));
    assert!(finding.tags().iter().any(|t| t.as_ref() == "ftp"));
}

#[test]
fn identify_banner_detects_smtp_banner() {
    let finding = identify_banner_or_probe(
        "220 mx.example.com ESMTP Postfix",
        &[],
        &service(25, None),
        25,
    )
    .unwrap();
    assert!(finding.title().contains("SMTP banner"));
    assert!(finding.tags().iter().any(|t| t.as_ref() == "smtp"));
}

#[test]
fn identify_banner_extracts_http_server_header() {
    let banner = "HTTP/1.1 200 OK\r\nServer: nginx/1.18.0\r\n\r\n";
    let finding = identify_banner_or_probe(banner, &[], &service(80, None), 80).unwrap();
    assert!(finding.title().contains("HTTP server header"));
    assert!(finding.detail().contains("discloses"));
}

#[test]
fn identify_banner_detects_redis_no_auth() {
    let finding = identify_banner_or_probe("+PONG", &[], &service(6379, None), 6379).unwrap();
    assert_eq!(finding.severity(), Severity::Critical);
    assert!(finding
        .title()
        .contains("Redis responds without authentication"));
}

#[test]
fn identify_banner_detects_mongodb_no_auth() {
    let finding =
        identify_banner_or_probe("ismaster MongoDB", &[], &service(27017, None), 27017).unwrap();
    assert_eq!(finding.severity(), Severity::Critical);
    assert!(finding.tags().iter().any(|t| t.as_ref() == "mongodb"));
}

#[test]
fn identify_banner_detects_telnet_response() {
    let finding = identify_banner_or_probe("Welcome", &[], &service(23, None), 23).unwrap();
    assert_eq!(finding.severity(), Severity::Critical);
    assert!(finding.tags().iter().any(|t| t.as_ref() == "telnet"));
}

#[test]
fn identify_banner_returns_none_for_unrecognized_banner() {
    assert!(
        identify_banner_or_probe("some random banner", &[], &service(1234, None), 1234).is_none()
    );
}

#[test]
fn port_mode_custom_can_represent_explicit_ranges() {
    let mode = PortMode::Custom(vec![1, 80, 443, 65535]);
    let PortMode::Custom(ports) = mode else {
        panic!("expected custom mode");
    };
    assert_eq!(ports, vec![1, 80, 443, 65535]);
}

#[test]
fn top_ports_tables_are_nonempty_and_unique() {
    use std::collections::HashSet;

    assert!(!rules::top_100().is_empty());
    assert!(!rules::top_1000().is_empty());
    assert_eq!(
        rules::top_100().iter().collect::<HashSet<_>>().len(),
        rules::top_100().len()
    );
    assert_eq!(
        rules::top_1000().iter().collect::<HashSet<_>>().len(),
        rules::top_1000().len()
    );
}

#[test]
fn default_portset_includes_common_web_and_database_ports() {
    let ports = rules::default_ports();
    for port in [80, 443, 5432, 6379, 8080] {
        assert!(ports.contains(&port), "missing default port {port}");
    }
}

// ============================================================================
// Edge case tests for port scanning
// ============================================================================

/// Port 0 is technically valid but may behave differently across platforms.
/// This test verifies our scanner handles it without panicking.
#[tokio::test]
async fn port_zero_is_handled_gracefully() {
    let scanner = PortScanner::new();
    // Port 0 typically results in a dynamic port assignment when binding,
    // but when scanning it should simply fail to connect (nothing listening)
    // without causing a panic or error.
    assert!(scanner.accepts(&Target::Domain(DomainTarget {
        domain: "localhost".into(),
        source: DiscoverySource::Seed,
    })));
}

/// Port 65535 is the maximum valid port number.
/// Ensure we handle it correctly in our port lists and scanning.
#[test]
fn port_maximum_valid_u16() {
    // Port 65535 is valid (u16::MAX)
    let max_port: u16 = 65535;
    assert_eq!(max_port, u16::MAX);

    // Verify it can be represented in custom port mode
    let mode = PortMode::Custom(vec![65535]);
    match mode {
        PortMode::Custom(ports) => {
            assert_eq!(ports, vec![65535]);
        }
        _ => panic!("expected custom mode"),
    }
}

/// Test that connection timeout is respected and returns gracefully.
#[tokio::test]
async fn connection_timeout_respected() {
    // Use a reserved documentation/test IP that should never respond
    // 192.0.2.0/24 is TEST-NET-1, guaranteed non-routable
    let start = std::time::Instant::now();
    let timeout_duration = Duration::from_millis(100);

    // Attempt connection with short timeout
    let _result = tokio::time::timeout(
        timeout_duration * 2,
        gossan_core::net::connect_tcp("192.0.2.1", 9999, None),
    )
    .await;

    let elapsed = start.elapsed();

    // Should complete (either timeout or fail) within reasonable time
    // Allow some buffer for the timeout
    assert!(
        elapsed < Duration::from_secs(5),
        "Connection attempt took too long: {:?}",
        elapsed
    );
}

/// Test that banner grab times out gracefully when server is silent.
#[tokio::test]
async fn banner_grab_times_out_on_silent_server() {
    // Bind to a local port but never send data
    let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
    let local_addr = listener.local_addr().unwrap();

    let server_task = tokio::spawn(async move {
        // Accept connection but never send data
        let (socket, _) = listener.accept().await.unwrap();
        // Hold the connection open but silent
        tokio::time::sleep(Duration::from_secs(10)).await;
        drop(socket);
    });

    // Connect to the silent server
    let stream = tokio::net::TcpStream::connect(local_addr).await.unwrap();

    // Banner grab should timeout (uses 800ms internally)
    let start = std::time::Instant::now();
    let banner = grab_banner(stream, Duration::from_millis(500)).await;
    let elapsed = start.elapsed();

    // Should return None (timeout)
    assert!(banner.is_none(), "Expected None for silent server");

    // Should have timed out around 800ms, definitely under 2 seconds
    assert!(
        elapsed < Duration::from_secs(2),
        "Banner grab took too long to timeout: {:?}",
        elapsed
    );

    // Clean up
    server_task.abort();
}

/// Test that port scanning handles empty port lists gracefully.
#[test]
fn empty_port_list_handled() {
    let mode = PortMode::Custom(vec![]);
    match mode {
        PortMode::Custom(ports) => {
            assert!(ports.is_empty());
        }
        _ => panic!("expected custom mode"),
    }
}

/// Test full port range generation (1-65535) doesn't panic.
#[test]
fn full_port_range_generation() {
    // Simulating PortMode::Full behavior
    let full_range: Vec<u16> = (1u16..=65535).collect();
    assert_eq!(full_range.len(), 65535);
    assert_eq!(full_range[0], 1);
    assert_eq!(full_range[65534], 65535);
}

/// Test that banner processing handles oversized data correctly.
#[test]
fn banner_processing_handles_large_input() {
    let svc = service(22, None);

    // Create a banner larger than the 512-byte buffer
    let large_banner = "A".repeat(2000);
    // This shouldn't match SSH patterns but also shouldn't panic
    let finding = identify_banner_or_probe(&large_banner, &[], &svc, 22);

    // Should return None since it doesn't match any pattern
    assert!(finding.is_none());
}

/// Test that binary/non-UTF8 data in banners is sanitized.
#[test]
fn banner_sanitizes_binary_data() {
    // Simulate binary data that might come from a service
    let binary_data: Vec<u8> = vec![
        0x00, 0x01, 0x02, 0x03, // Non-printable (4 bytes)
        0x20, 0x21, 0x22, // Printable: space, !, " (3 bytes)
        0x7f, 0x80, 0xff, // Edge (DEL) and non-ASCII (3 bytes)
    ];

    // The sanitize logic replaces non-printable with '.'
    // Range (0x20..0x7f) = 0x20 to 0x7e inclusive
    let sanitized: String = binary_data
        .iter()
        .map(|&b| {
            if (0x20..0x7f).contains(&b) {
                b as char
            } else {
                '.'
            }
        })
        .collect();

    // Verify sanitization: 4 dots + space + ! + " + 3 dots
    assert_eq!(sanitized, ".... !\"...");
}

/// Test edge case port numbers in various contexts.
#[test]
fn edge_case_port_numbers() {
    // Test that common edge ports are handled
    let edge_ports = [1, 1024, 1025, 65534, 65535];

    for port in edge_ports {
        let svc = service(port, None);
        assert_eq!(svc.port, port);
    }
}

/// Verify finding builder works with edge case inputs.
#[test]
fn finding_builder_edge_cases() {
    let target = Target::Domain(DomainTarget {
        domain: "test.example.com".into(),
        source: DiscoverySource::Seed,
    });

    // Note: Empty title may fail validation - use minimal valid content
    let finding = finding_builder(&target, Severity::Info, "test", "test detail").build();
    assert!(finding.is_ok());

    // Very long strings
    let long_string = "x".repeat(10000);
    let finding = finding_builder(&target, Severity::High, &long_string, &long_string).build();
    assert!(finding.is_ok());

    // Unicode content
    let unicode = "ๆต‹่ฏ• ๐ŸŽ‰ รฉmoji ๆ—ฅๆœฌ่ชž";
    let finding = finding_builder(&target, Severity::Medium, unicode, unicode).build();
    assert!(finding.is_ok());
}

/// Test CVE correlation with edge case patterns.
#[test]
fn cve_correlation_edge_cases() {
    use crate::cve::correlate;

    let svc = service(80, None);

    // Empty banner
    let findings = correlate("", &svc);
    assert!(findings.is_empty());

    // Very long banner
    let long_banner = format!("Server: Apache/2.4.49 {}", "x".repeat(10000));
    let findings = correlate(&long_banner, &svc);
    // Should still match the pattern
    assert!(findings
        .iter()
        .any(|f| f.title().contains("CVE-2021-41773")));

    // Case insensitivity check
    let findings = correlate("SERVER: APACHE/2.4.49", &svc);
    assert!(findings
        .iter()
        .any(|f| f.title().contains("CVE-2021-41773")));
}

/// Test TLS info display formatting.
#[test]
fn tls_cert_info_display() {
    use crate::tls::{days_until_expiry, LegacyTlsResult, TlsCertInfo};

    let info = TlsCertInfo {
        subject: "CN=test.com".into(),
        issuer: "CN=Test CA".into(),
        sans: vec!["test.com".into(), "www.test.com".into()],
        not_after_unix: 1893456000,
        is_self_signed: false,
        cipher_suite: "TLS13_AES_256_GCM_SHA384".into(),
        protocol_version: "TLS1.3".into(),
    };

    let display = format!("{}", info);
    assert!(display.contains("TlsCertInfo"));
    assert!(display.contains("test.com"));
    assert!(display.contains("self-signed: false"));

    // Test LegacyTlsResult display
    let legacy = LegacyTlsResult {
        supports_tls10: true,
        supports_tls11: false,
    };
    let display = format!("{}", legacy);
    assert!(display.contains("VULNERABLE"));

    let legacy_clean = LegacyTlsResult {
        supports_tls10: false,
        supports_tls11: false,
    };
    let display = format!("{}", legacy_clean);
    assert!(display.contains("no legacy protocols"));

    // Test days_until_expiry edge cases
    let now = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap()
        .as_secs() as i64;

    // Exactly now
    assert_eq!(days_until_expiry(now), 0);

    // Far future
    assert!(days_until_expiry(now + 365 * 86400) > 364);

    // Far past
    assert!(days_until_expiry(now - 365 * 86400) < -364);
}

#[test]
fn test_scan_target_key_serialization_and_legacy_migration() {
    use std::collections::HashSet;
    use std::net::IpAddr;

    // Test 1: Serialize and Deserialize ScanTargetKey
    let mut completed = HashSet::new();
    completed.insert(ScanTargetKey {
        target: "alpha.com".to_string(),
        port: 80,
    });
    completed.insert(ScanTargetKey {
        target: "127.0.0.1".to_string(),
        port: 443,
    });

    let keys: Vec<&ScanTargetKey> = completed.iter().collect();
    let json = serde_json::to_string(&keys).unwrap();

    // Deserialize new format
    let parsed: Vec<ScanTargetKey> = serde_json::from_str(&json).unwrap();
    assert_eq!(parsed.len(), 2);
    assert!(parsed
        .iter()
        .any(|k| k.target == "alpha.com" && k.port == 80));
    assert!(parsed
        .iter()
        .any(|k| k.target == "127.0.0.1" && k.port == 443));

    // Test 2: Parse legacy format Vec<(IpAddr, u16)> and migrate
    let old_data: Vec<(IpAddr, u16)> = vec![
        (IpAddr::from([1, 1, 1, 1]), 80),
        (IpAddr::from([8, 8, 8, 8]), 53),
    ];
    let old_json = serde_json::to_string(&old_data).unwrap();

    // Ensure it might parse directly due to Serde's flexibility with sequence deserialization.
    // If it succeeds, verify the output; otherwise, we explicitly test the migration fallback path.
    let parsed_new_attempt = serde_json::from_str::<Vec<ScanTargetKey>>(&old_json);
    if let Ok(ref migrated) = parsed_new_attempt {
        assert_eq!(migrated.len(), 2);
        assert!(migrated
            .iter()
            .any(|k| k.target == "1.1.1.1" && k.port == 80));
    }

    // Migrate old format successfully
    let old_ports: Vec<(IpAddr, u16)> = serde_json::from_str(&old_json).unwrap();
    let migrated_keys: Vec<ScanTargetKey> = old_ports
        .into_iter()
        .map(|(ip, port)| ScanTargetKey {
            target: ip.to_string(),
            port,
        })
        .collect();

    assert_eq!(migrated_keys.len(), 2);
    assert!(migrated_keys
        .iter()
        .any(|k| k.target == "1.1.1.1" && k.port == 80));
    assert!(migrated_keys
        .iter()
        .any(|k| k.target == "8.8.8.8" && k.port == 53));
}

#[test]
fn large_ipv6_network_does_not_panic_on_host_count() {
    // Adversarial: ::/0 has 2^128 hosts; calling hosts().count()
    // directly can overflow usize and panic in debug builds.
    // Our fix caps the enumeration at max_hosts + 1.
    let net: ipnet::IpNet = "::/0".parse().unwrap();
    let max_hosts: usize = 256;
    let total_hosts = net.hosts().take(max_hosts + 1).count();
    assert_eq!(total_hosts, max_hosts + 1);
}

/// Anti-rig: pin TLS_PORTS against the literal set documented in the module.
/// If someone adds a port to one but not the other, this test breaks rather
/// than silently diverging (ยง12 TESTING).
#[test]
fn tls_ports_well_known_set_pinned() {
    // These are the historically expected TLS-by-default ports.
    // Changing TLS_PORTS without updating this test is intentional, the
    // test is the change-detector, not a hard veto.
    let expected: std::collections::HashSet<u16> = [443, 8443, 465, 993, 636, 995, 587]
        .iter()
        .copied()
        .collect();
    let actual: std::collections::HashSet<u16> = TLS_PORTS.iter().copied().collect();
    assert_eq!(
        expected, actual,
        "TLS_PORTS diverged from the pinned set, update this test intentionally"
    );
}

/// Anti-rig: ephemeral port constants must stay inside the IANA range.
#[test]
fn ephemeral_port_constants_in_valid_range() {
    assert!(EPHEMERAL_PORT_START >= 49152, "start below IANA minimum");
    assert!(
        (EPHEMERAL_PORT_START as u32) + (EPHEMERAL_PORT_COUNT as u32) <= 65535,
        "start+count overflows u16 port space"
    );
}

/// Anti-rig: retry parameters must be sane.
#[test]
fn probe_retry_constants_sane() {
    assert!(PROBE_MAX_RETRIES > 0, "zero retries means we never probe");
    assert!(
        PROBE_MAX_RETRIES <= 10,
        "excessive retries inflate scan time"
    );
    assert!(BACKOFF_TIMEOUT_BASE_MS > 0, "zero base delay causes spin");
    assert!(
        BACKOFF_TIMEOUT_BASE_MS <= 5_000,
        "base delay > 5 s is too slow"
    );
}

#[test]
fn probe_retry_backoff_uses_canonical_timeout_schedule() {
    let backoff = probe_retry_backoff();
    assert_eq!(backoff.max_retries(), PROBE_MAX_RETRIES);
    assert_eq!(
        backoff.delay(BackoffKind::Timeout, 0),
        Duration::from_millis(200)
    );
    assert_eq!(
        backoff.delay(BackoffKind::Timeout, 1),
        Duration::from_millis(400)
    );
    assert!(!backoff.should_retry_after(PROBE_MAX_RETRIES - 1));
}