use std::net::{IpAddr, Ipv4Addr};
use std::sync::Arc;
use std::time::{Duration, SystemTime};
use crate::config::{IdleScan, ZondConfig};
use crate::evasion::EvasionProfile;
use crate::model::capture::CaptureCounts;
use crate::model::confidence::Confidence;
use crate::model::exclusion::Exclusions;
use crate::model::finding::{
DetectionClass, DetectionId, Excerpt, Finding, Reference, Severity, Version,
};
use crate::model::host::{
Filtering, Hop, Host, HostStatus, IpProtocolState, NetworkRole, OsFingerprint, StatusProtocol,
StatusReason,
};
use crate::model::ip::scoped::Zone;
use crate::model::ip::set::IpSet;
use crate::model::mac::MacAddr;
use crate::model::port::{
CertificateInfo, Discovery, Port, PortState, Protocol, ScanResponse, Security, Service,
};
use crate::model::tls::{CipherSuite, TlsSupport, TlsVersion, VersionSupport};
use crate::protocols::tcp::flags;
use crate::report::ScannerKind;
use crate::report::WindowSummary;
use crate::report::{
Attachment, AttachmentSource, BUCKET_BOUNDS_MS, ProbeStats, ScanKind, ScanReport, StopReason,
TargetScope,
};
use crate::scanner::recorder::PhaseRecorder;
use crate::scanner::session::ScanSession;
use crate::system::privilege::Privilege;
fn ip(last: u8) -> IpAddr {
IpAddr::V4(Ipv4Addr::new(192, 168, 0, last))
}
fn router() -> Host {
let mut host = Host::new(ip(1));
host.set_hostname(Some("router.local".to_string()));
host.set_status(HostStatus::Up);
host.add_reason(StatusReason::new(StatusProtocol::Arp, "reply from gateway"));
host.record_mac(MacAddr::new(0x2c, 0xcf, 0x67, 0xf2, 0x51, 0xe3));
let mut os = OsFingerprint::new("Linux", 95)
.with_family("Unix-like")
.with_device("Printer")
.with_generation("5.15.0")
.with_evidence("syn-ack hops>=64 opts=M,S,T,N,W win=65160=45x1448 ws=7 mss=1460");
os.add_cpe("cpe:/o:linux:linux_kernel:5.15.0");
host.set_os(os);
host.add_rtt(Duration::from_micros(1_200));
host.add_rtt(Duration::from_micros(1_800));
host.add_rtt(Duration::from_micros(3_000));
host.record_hop(Hop::answered(
3,
IpAddr::V4(Ipv4Addr::new(198, 51, 100, 1)),
Some(Duration::from_micros(4_100)),
));
host.record_hop(Hop::silent(2));
host.record_hop(
Hop::answered(1, IpAddr::V4(Ipv4Addr::new(192, 168, 0, 254)), None).as_inferred(),
);
host.add_port(https_port());
host.add_port(ssh_port());
host.add_port(Port::new(80, Protocol::Tcp, PortState::Open));
host.add_filtering(Filtering::InlineMiddlebox);
host.add_filtering(Filtering::StatefulFilter);
host.add_filtering(Filtering::PortTrustingAcl);
host.add_filtering(Filtering::StatelessFilter);
host.record_ip_protocol(1, IpProtocolState::Open);
host.record_ip_protocol(47, IpProtocolState::Closed);
host.record_ip_protocol(50, IpProtocolState::Filtered);
host.record_ip_protocol(89, IpProtocolState::OpenFiltered);
host.record_ip_protocol(103, IpProtocolState::Unasked);
host
}
fn ssh_port() -> Port {
let service = Service::new("ssh", 100)
.with_product("OpenSSH")
.with_vendor("OpenBSD")
.with_version("8.9p1")
.with_cpe("cpe:/a:openbsd:openssh:8.9p1");
let discovery = Discovery::new(ScanResponse::TcpSynAck)
.with_rtt(Duration::from_micros(1_450))
.with_ttl(64)
.with_source_ip(ip(50));
Port::new(22, Protocol::Tcp, PortState::Open)
.with_service(service)
.with_discovery(discovery)
}
fn https_port() -> Port {
let certificate = CertificateInfo::new(
"router.local",
"Local CA",
std::time::UNIX_EPOCH + Duration::from_secs(1_767_225_600),
std::time::UNIX_EPOCH + Duration::from_secs(1_798_761_600),
"9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08",
)
.with_sans([Arc::from("www.router.local")])
.with_public_key("ECDSA", 256);
let security = Security::new()
.with_tls_version("TLSv1.3")
.with_cipher_suite("TLS_AES_256_GCM_SHA384")
.with_alpn("h2")
.with_alpn("http/1.1")
.with_certificate(certificate)
.with_support(accepted());
Port::new(443, Protocol::Tcp, PortState::Open).with_security(security)
}
fn accepted() -> TlsSupport {
let suite = |code: u16| CipherSuite::from_code(code).expect("a suite in the registry");
TlsSupport::new()
.accepting(VersionSupport::new(
TlsVersion::Tls10,
vec![suite(0x000A), suite(0x002F)],
Vec::new(),
))
.accepting(VersionSupport::new(
TlsVersion::Tls12,
vec![suite(0xC030), suite(0x009C)],
vec![0xFF01],
))
.accepting(VersionSupport::new(
TlsVersion::Tls13,
vec![suite(0x1302)],
Vec::new(),
))
}
fn filtered_host() -> Host {
let mut host = Host::new(ip(2));
host.set_status(HostStatus::Filtered);
host.add_reason(StatusReason::basic(StatusProtocol::TcpSyn));
host.add_port(Port::new(445, Protocol::Tcp, PortState::Filtered));
host
}
fn bare_host() -> Host {
let mut host = Host::new(ip(9));
host.set_status(HostStatus::Down);
host
}
fn probe_stats() -> ProbeStats {
let mut found_at = [0u64; BUCKET_BOUNDS_MS.len() + 1];
found_at[0] = 4;
found_at[3] = 3;
found_at[BUCKET_BOUNDS_MS.len()] = 2;
ProbeStats {
window: Some(WindowSummary {
capacity: 48,
peak: 256,
reductions: 2,
adaptive: true,
at_floor: false,
}),
scanner: ScannerKind::Routed,
targets: 256,
stop_reason: StopReason::DeadlineExpired,
elapsed: Duration::from_millis(412),
sends_attempted: 512,
sends_failed: 0,
sends_witnessed: 0,
segments_seen: 271,
segments_off_target: 3,
replies_without_rtt: 2,
hosts_found: 9,
answered_on: [7, 2, 0, 0, 0, 0],
answered_unattributed: 0,
first_reply: Some(Duration::from_micros(900)),
last_reply: Some(Duration::from_millis(405)),
found_at,
capture: Some(CaptureCounts {
received: 271,
dropped: 0,
if_dropped: 0,
stopped_early: 0,
}),
}
}
pub(crate) fn report() -> ScanReport {
let (_session, ctx) = ScanSession::builder()
.host_timeout(Some(Duration::ZERO))
.build();
let mut targets = IpSet::new();
targets.insert_range("192.168.0.0/24".parse().expect("a valid range"));
let mut excluded = IpSet::new();
excluded.insert_range("192.168.0.128/25".parse().expect("a valid range"));
let config = ZondConfig {
evasion: EvasionProfile::default()
.with_source_port(53)
.with_ttl(40)
.with_padding(24)
.with_bad_tcp_checksum(true)
.with_spoof_mac(MacAddr::new(0xDE, 0xAD, 0xBE, 0xEF, 0x00, 0x01))
.with_fragment(28)
.with_decoys(vec![
"192.0.2.61".parse().expect("a valid decoy address"),
"192.0.2.62".parse().expect("a valid decoy address"),
])
.with_flags(flags::SYN | flags::FIN),
idle_scan: Some(IdleScan {
zombie: "192.0.2.9".parse().expect("a valid zombie address"),
zombie_port: Some(113),
}),
host_timeout: Some(Duration::from_secs(300)),
scan_timeout: Some(Duration::from_secs(3600)),
sctp_technique: crate::model::technique::SctpScanTechnique::CookieEcho,
..Default::default()
};
let recorder = PhaseRecorder::start(
ScanKind::Discovery,
Privilege::Raw,
TargetScope::from_ip_set(&mut targets, &Exclusions::new(excluded)),
&config,
);
ctx.record_failure(ScannerKind::Local, "raw socket unavailable".to_string());
ctx.record_probe_stats(probe_stats());
ctx.record_sweep(Zone::new(3, "en0"));
ctx.record_attachment(
Attachment::new(
Zone::new(3, "en0"),
AttachmentSource::Lldp,
SystemTime::UNIX_EPOCH + Duration::from_secs(1_772_000_000),
)
.with_device_mac(MacAddr::new(0x00, 0x1B, 0x2C, 0x3D, 0x4E, 0x5F))
.with_device_name("core-sw-02")
.with_port("GigabitEthernet1/0/14")
.with_native_vlan(40)
.with_management_address(IpAddr::V4(Ipv4Addr::new(10, 0, 0, 2))),
);
assert!(
ctx.host_expired(ip(9)),
"the fixture's budget is spent before it is asked"
);
for host in [router(), filtered_host(), bare_host()] {
ctx.store.insert(host.scoped_ip(), host);
}
for mut entry in ctx.store.iter_mut() {
crate::cve::correlate(entry.value_mut());
}
recorder.finish(&ctx)
}
const BASELINE_AT: Duration = Duration::from_secs(1_780_000_000);
const DAY: Duration = Duration::from_secs(86_400);
const COMPARED_PORTS: &str = "22,80,443,8080,8443";
pub(crate) fn compared() -> (ScanReport, ScanReport) {
(
compared_phase(0, before_hosts()),
compared_phase(35, after_hosts()),
)
}
fn compared_phase(days: u64, hosts: Vec<Host>) -> ScanReport {
use crate::model::port::PortSet;
use crate::model::target::{TargetMap, TargetSet};
use crate::report::{PhaseParts, ScanPhase, ScanSettings};
let mut targets = TargetMap::new();
let mut addresses = IpSet::new();
addresses.insert_range("192.168.0.0/25".parse().expect("a valid range"));
targets.add_unit(TargetSet::new(
addresses,
PortSet::try_from(COMPARED_PORTS).expect("a valid port set"),
));
let phase = ScanPhase::from_parts(PhaseParts {
attachments: Vec::new(),
kind: ScanKind::PortScan,
started_at: std::time::UNIX_EPOCH + BASELINE_AT + DAY * days as u32,
elapsed: Duration::from_secs(12),
privilege: Some(Privilege::Raw),
targets: TargetScope::from_target_map(&mut targets, &Exclusions::none()),
settings: ScanSettings::from(&ZondConfig::default()),
failures: Vec::new(),
refusals: Vec::new(),
unroutable: Vec::new(),
timed_out: Vec::new(),
probes: Vec::new(),
origin: None,
});
ScanReport::recorded(crate::report::ENGINE_VERSION, vec![phase], hosts)
}
fn certificate(fingerprint: &str, issuer: &str, ends: Duration) -> Security {
Security::new()
.with_tls_version("TLSv1.3")
.with_cipher_suite("TLS_AES_256_GCM_SHA384")
.with_certificate(CertificateInfo::new(
"www.example.test",
issuer,
std::time::UNIX_EPOCH + BASELINE_AT - DAY * 90,
std::time::UNIX_EPOCH + ends,
fingerprint,
))
}
fn compared_router(later: bool) -> Host {
let mut host = Host::new(ip(1));
host.set_status(HostStatus::Up);
host.add_reason(StatusReason::new(StatusProtocol::Arp, "reply from gateway"));
host.record_mac(MacAddr::new(0x2c, 0xcf, 0x67, 0xf2, 0x51, 0xe3));
host.set_hostname(Some(
if later {
"gateway.local"
} else {
"router.local"
}
.to_string(),
));
host.set_os(
OsFingerprint::new("Linux", 95)
.with_family("Unix-like")
.with_generation(if later { "6.1.0" } else { "5.15.0" }),
);
if later {
host.add_finding(
Finding::new(
DetectionId::new("kev", Version::new(1, 0, 0), "seed")
.expect("a valid detection id"),
"Known exploited vulnerability in the management interface",
Severity::High,
Confidence::Strong,
DetectionClass::Passive,
)
.expect("a titled finding"),
);
}
host.add_finding(
Finding::new(
DetectionId::new("tls-audit", Version::new(1, 0, 0), "seed")
.expect("a valid detection id"),
"Management interface accepts a deprecated TLS version",
if later {
Severity::High
} else {
Severity::Medium
},
Confidence::Strong,
DetectionClass::Passive,
)
.expect("a titled finding"),
);
host.add_port(
Port::new(22, Protocol::Tcp, PortState::Open).with_service(
Service::new("ssh", 100)
.with_product("OpenSSH")
.with_version(if later { "9.6p1" } else { "8.9p1" }),
),
);
host.add_port(Port::new(
80,
Protocol::Tcp,
if later {
PortState::Closed
} else {
PortState::Open
},
));
host.add_port(
Port::new(443, Protocol::Tcp, PortState::Open).with_security(if later {
certificate(
"bbbb2b0b822cd15d6c15b0f00a089f86d081884c7d659a2feaa0c55ad015",
"Public CA",
BASELINE_AT + DAY * 400,
)
} else {
certificate(
"aaaa884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08",
"Local CA",
BASELINE_AT + DAY * 200,
)
}),
);
if later {
host.add_port(
Port::new(8080, Protocol::Tcp, PortState::Open).with_service(
Service::new("http-alt", 90)
.with_product("Caddy")
.with_version("2.7.6"),
),
);
}
host
}
fn compared_expiring() -> Host {
let mut host = Host::new(ip(4));
host.set_status(HostStatus::Up);
host.add_port(
Port::new(8443, Protocol::Tcp, PortState::Open)
.with_security(certificate(
"cccc7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08",
"Local CA",
BASELINE_AT + DAY * 60,
)),
);
host
}
fn before_hosts() -> Vec<Host> {
let mut gone = Host::new(ip(9));
gone.set_status(HostStatus::Up);
vec![compared_router(false), compared_expiring(), gone]
}
fn after_hosts() -> Vec<Host> {
let mut arrived = Host::new(ip(7));
arrived.set_status(HostStatus::Up);
arrived.add_reason(StatusReason::new(StatusProtocol::IcmpEcho, "echo reply"));
arrived.add_port(Port::new(22, Protocol::Tcp, PortState::Open));
vec![compared_router(true), compared_expiring(), arrived]
}
pub(crate) const HOSTILE: &str = "=<script>alert(\"x\")</script>&'\u{202e}";
fn hostile_finding() -> Finding {
Finding::new(
DetectionId::new(HOSTILE, Version::new(1, 0, 0), HOSTILE).unwrap(),
HOSTILE,
Severity::Critical,
Confidence::Certain,
DetectionClass::Exploit,
)
.unwrap()
.with_excerpt(Excerpt::new(HOSTILE))
.with_reference(Reference::url(HOSTILE))
.with_remediation(HOSTILE)
}
fn hostile_host() -> Host {
let mut host = Host::new(ip(3));
host.set_hostname(Some(HOSTILE.to_string()));
host.set_status(HostStatus::Up);
host.add_reason(StatusReason::new(StatusProtocol::Arp, HOSTILE));
host.record_mac(MacAddr::new(0xde, 0xad, 0xbe, 0xef, 0x00, 0x01));
host.add_network_role(NetworkRole::Tarpit);
let mut os = OsFingerprint::new(HOSTILE, 90)
.with_family(HOSTILE)
.with_device(HOSTILE)
.with_generation(HOSTILE)
.with_evidence(HOSTILE);
os.add_cpe(HOSTILE);
host.set_os(os);
host.add_rtt(Duration::from_micros(1_000));
host.add_finding(hostile_finding());
host.add_port(hostile_port());
host
}
fn hostile_port() -> Port {
let service = Service::new(HOSTILE, 100)
.with_product(HOSTILE)
.with_vendor(HOSTILE)
.with_version(HOSTILE)
.with_cpe(HOSTILE);
let certificate = CertificateInfo::new(
HOSTILE,
HOSTILE,
std::time::UNIX_EPOCH + Duration::from_secs(1_767_225_600),
std::time::UNIX_EPOCH + Duration::from_secs(1_798_761_600),
HOSTILE,
)
.with_sans([Arc::from(HOSTILE)])
.with_public_key(HOSTILE, 256);
let security = Security::new()
.with_tls_version(HOSTILE)
.with_cipher_suite(HOSTILE)
.with_alpn(HOSTILE)
.with_certificate(certificate);
let mut port = Port::new(8443, Protocol::Tcp, PortState::Open)
.with_service(service)
.with_security(security)
.with_discovery(Discovery::new(ScanResponse::TcpSynAck).with_source_ip(ip(50)));
port.add_finding(hostile_finding());
port
}
pub(crate) fn hostile() -> ScanReport {
let (_session, ctx) = ScanSession::new();
let mut targets = IpSet::new();
targets.insert_range("192.168.0.0/24".parse().expect("a valid range"));
let recorder = PhaseRecorder::start(
ScanKind::Discovery,
Privilege::Raw,
TargetScope::from_ip_set(&mut targets, &Exclusions::none()),
&ZondConfig::default(),
);
ctx.record_failure(ScannerKind::Local, HOSTILE.to_string());
ctx.record_probe_stats(probe_stats());
ctx.store.insert(
crate::model::ip::scoped::ScopedIp::unscoped(ip(3)),
hostile_host(),
);
recorder.finish(&ctx)
}