use std::borrow::Cow;
use crate::model::confidence::Confidence;
use crate::model::finding::{DetectionClass, Reference, Severity};
use crate::model::host::OsSource;
use crate::model::host::{Filtering, HostStatus, IpProtocolState, NetworkRole, StatusProtocol};
use crate::model::port::discovery::ScanResponse;
use crate::model::port::{PortSet, PortState, Protocol};
use crate::protocols::tcp;
use crate::report::ScannerKind;
use crate::report::{AttachmentSource, PortScope, ScanKind, StopReason};
const CUSTOM: &str = "custom:";
pub fn host_status_name(status: HostStatus) -> &'static str {
match status {
HostStatus::Unknown => "unknown",
HostStatus::Down => "down",
HostStatus::Filtered => "filtered",
HostStatus::Up => "up",
}
}
pub fn host_status(name: &str) -> Option<HostStatus> {
Some(match name {
"unknown" => HostStatus::Unknown,
"down" => HostStatus::Down,
"filtered" => HostStatus::Filtered,
"up" => HostStatus::Up,
_ => return None,
})
}
pub fn port_state_name(state: PortState) -> &'static str {
match state {
PortState::Unasked => "unasked",
PortState::ClosedFiltered => "closed_filtered",
PortState::Filtered => "filtered",
PortState::Unfiltered => "unfiltered",
PortState::Closed => "closed",
PortState::OpenFiltered => "open_filtered",
PortState::Open => "open",
}
}
pub fn port_state(name: &str) -> Option<PortState> {
Some(match name {
"unasked" => PortState::Unasked,
"closed_filtered" => PortState::ClosedFiltered,
"filtered" => PortState::Filtered,
"unfiltered" => PortState::Unfiltered,
"closed" => PortState::Closed,
"open_filtered" => PortState::OpenFiltered,
"open" => PortState::Open,
_ => return None,
})
}
pub fn ip_protocol_state_name(state: IpProtocolState) -> &'static str {
match state {
IpProtocolState::Unasked => "unasked",
IpProtocolState::OpenFiltered => "open_filtered",
IpProtocolState::Filtered => "filtered",
IpProtocolState::Closed => "closed",
IpProtocolState::Open => "open",
}
}
pub fn ip_protocol_state(name: &str) -> Option<IpProtocolState> {
Some(match name {
"unasked" => IpProtocolState::Unasked,
"open_filtered" => IpProtocolState::OpenFiltered,
"filtered" => IpProtocolState::Filtered,
"closed" => IpProtocolState::Closed,
"open" => IpProtocolState::Open,
_ => return None,
})
}
pub fn protocol_name(protocol: Protocol) -> &'static str {
match protocol {
Protocol::Tcp => "tcp",
Protocol::Udp => "udp",
Protocol::Sctp => "sctp",
}
}
pub fn protocol(name: &str) -> Option<Protocol> {
Some(match name {
"tcp" => Protocol::Tcp,
"udp" => Protocol::Udp,
"sctp" => Protocol::Sctp,
_ => return None,
})
}
pub fn network_role_name(role: NetworkRole) -> &'static str {
match role {
NetworkRole::Router => "router",
NetworkRole::DnsServer => "dns",
NetworkRole::DhcpServer => "dhcp",
NetworkRole::NtpServer => "ntp",
NetworkRole::SnmpAgent => "snmp",
NetworkRole::DomainController => "domain-controller",
NetworkRole::Switch => "switch",
NetworkRole::Origin => "origin",
NetworkRole::Tarpit => "tarpit",
NetworkRole::Truncated => "truncated",
}
}
pub fn network_role(name: &str) -> Option<NetworkRole> {
Some(match name {
"router" => NetworkRole::Router,
"dns" => NetworkRole::DnsServer,
"dhcp" => NetworkRole::DhcpServer,
"ntp" => NetworkRole::NtpServer,
"snmp" => NetworkRole::SnmpAgent,
"domain-controller" => NetworkRole::DomainController,
"switch" => NetworkRole::Switch,
"origin" => NetworkRole::Origin,
"tarpit" => NetworkRole::Tarpit,
"truncated" => NetworkRole::Truncated,
_ => return None,
})
}
pub fn filtering_name(filtering: Filtering) -> &'static str {
match filtering {
Filtering::InlineMiddlebox => "inline_middlebox",
Filtering::StatefulFilter => "stateful_filter",
Filtering::PortTrustingAcl => "port_trusting_acl",
Filtering::StatelessFilter => "stateless_filter",
}
}
pub fn filtering(name: &str) -> Option<Filtering> {
Some(match name {
"inline_middlebox" => Filtering::InlineMiddlebox,
"stateful_filter" => Filtering::StatefulFilter,
"port_trusting_acl" => Filtering::PortTrustingAcl,
"stateless_filter" => Filtering::StatelessFilter,
_ => return None,
})
}
pub fn severity_name(severity: Severity) -> &'static str {
match severity {
Severity::Info => "info",
Severity::Low => "low",
Severity::Medium => "medium",
Severity::High => "high",
Severity::Critical => "critical",
}
}
pub fn severity(name: &str) -> Option<Severity> {
Some(match name {
"info" => Severity::Info,
"low" => Severity::Low,
"medium" => Severity::Medium,
"high" => Severity::High,
"critical" => Severity::Critical,
_ => return None,
})
}
pub fn detection_class_name(class: DetectionClass) -> &'static str {
match class {
DetectionClass::Passive => "passive",
DetectionClass::ActiveBenign => "active_benign",
DetectionClass::ActiveMutating => "active_mutating",
DetectionClass::Exploit => "exploit",
DetectionClass::Dos => "dos",
}
}
pub fn detection_ceiling_name(ceiling: Option<DetectionClass>) -> &'static str {
match ceiling {
Some(class) => detection_class_name(class),
None => "off",
}
}
pub fn detection_class(name: &str) -> Option<DetectionClass> {
Some(match name {
"passive" => DetectionClass::Passive,
"active_benign" => DetectionClass::ActiveBenign,
"active_mutating" => DetectionClass::ActiveMutating,
"exploit" => DetectionClass::Exploit,
"dos" => DetectionClass::Dos,
_ => return None,
})
}
pub fn confidence_name(confidence: Confidence) -> &'static str {
match confidence {
Confidence::Heuristic => "heuristic",
Confidence::Weak => "weak",
Confidence::Probable => "probable",
Confidence::Strong => "strong",
Confidence::Certain => "certain",
}
}
pub fn confidence(name: &str) -> Option<Confidence> {
Some(match name {
"heuristic" => Confidence::Heuristic,
"weak" => Confidence::Weak,
"probable" => Confidence::Probable,
"strong" => Confidence::Strong,
"certain" => Confidence::Certain,
_ => return None,
})
}
pub fn reference_kind_name(reference: &Reference) -> &'static str {
match reference {
Reference::Cve(_) => "cve",
Reference::Cwe(_) => "cwe",
Reference::Url(_) => "url",
}
}
pub fn reference(kind: &str, value: &str) -> Option<Reference> {
Some(match kind {
"cve" => Reference::cve(value)?,
"cwe" => Reference::cwe(value.parse().ok()?),
"url" => Reference::url(value),
_ => return None,
})
}
pub fn tcp_flags_name(byte: u8) -> String {
[
(tcp::flags::URG, "urg"),
(tcp::flags::ACK, "ack"),
(tcp::flags::PSH, "psh"),
(tcp::flags::RST, "rst"),
(tcp::flags::SYN, "syn"),
(tcp::flags::FIN, "fin"),
]
.into_iter()
.filter(|(bit, _)| byte & bit != 0)
.map(|(_, name)| name)
.collect::<Vec<_>>()
.join("|")
}
pub fn tcp_flags(name: &str) -> u8 {
tcp_flags_fold(name).0
}
pub fn tcp_flags_checked(name: &str) -> Option<u8> {
match tcp_flags_fold(name) {
(mask, true) => Some(mask),
(_, false) => None,
}
}
fn tcp_flags_fold(name: &str) -> (u8, bool) {
name.split('|')
.fold((0, true), |(mask, known), part| match part.trim() {
"fin" => (mask | tcp::flags::FIN, known),
"syn" => (mask | tcp::flags::SYN, known),
"rst" => (mask | tcp::flags::RST, known),
"psh" => (mask | tcp::flags::PSH, known),
"ack" => (mask | tcp::flags::ACK, known),
"urg" => (mask | tcp::flags::URG, known),
_ => (mask, false),
})
}
pub fn status_protocol_name(protocol: &StatusProtocol) -> Cow<'_, str> {
match protocol {
StatusProtocol::Arp => Cow::Borrowed("arp"),
StatusProtocol::Ndp => Cow::Borrowed("ndp"),
StatusProtocol::IcmpEcho => Cow::Borrowed("icmp_echo"),
StatusProtocol::IcmpTimestamp => Cow::Borrowed("icmp_timestamp"),
StatusProtocol::IcmpUnreachable => Cow::Borrowed("icmp_unreachable"),
StatusProtocol::TcpSyn => Cow::Borrowed("tcp_syn"),
StatusProtocol::Tcp => Cow::Borrowed("tcp"),
StatusProtocol::Dhcp => Cow::Borrowed("dhcp"),
StatusProtocol::Udp => Cow::Borrowed("udp"),
StatusProtocol::Sctp => Cow::Borrowed("sctp"),
StatusProtocol::Custom(name) => Cow::Owned(format!("{CUSTOM}{name}")),
}
}
pub fn status_protocol(name: &str) -> Option<StatusProtocol> {
if let Some(custom) = name.strip_prefix(CUSTOM) {
return (!custom.is_empty()).then(|| StatusProtocol::Custom(custom.into()));
}
Some(match name {
"icmp_timestamp" => StatusProtocol::IcmpTimestamp,
"arp" => StatusProtocol::Arp,
"ndp" => StatusProtocol::Ndp,
"icmp_echo" => StatusProtocol::IcmpEcho,
"icmp_unreachable" => StatusProtocol::IcmpUnreachable,
"tcp_syn" => StatusProtocol::TcpSyn,
"tcp" => StatusProtocol::Tcp,
"dhcp" => StatusProtocol::Dhcp,
"udp" => StatusProtocol::Udp,
"sctp" => StatusProtocol::Sctp,
_ => return None,
})
}
pub fn scan_response_name(response: &ScanResponse) -> Cow<'_, str> {
match response {
ScanResponse::TcpSynAck => Cow::Borrowed("tcp_syn_ack"),
ScanResponse::OverheardSynAck => Cow::Borrowed("overheard_syn_ack"),
ScanResponse::TcpRst => Cow::Borrowed("tcp_rst"),
ScanResponse::UdpResponse => Cow::Borrowed("udp_response"),
ScanResponse::SctpInitAck => Cow::Borrowed("sctp_init_ack"),
ScanResponse::SctpAbort => Cow::Borrowed("sctp_abort"),
ScanResponse::NoResponse => Cow::Borrowed("no_response"),
ScanResponse::IcmpUnreachable => Cow::Borrowed("icmp_unreachable"),
ScanResponse::IcmpProhibited => Cow::Borrowed("icmp_prohibited"),
ScanResponse::Custom(name) => Cow::Owned(format!("{CUSTOM}{name}")),
}
}
pub fn scan_response(name: &str) -> Option<ScanResponse> {
if let Some(custom) = name.strip_prefix(CUSTOM) {
return (!custom.is_empty()).then(|| ScanResponse::Custom(custom.to_string()));
}
Some(match name {
"tcp_syn_ack" => ScanResponse::TcpSynAck,
"overheard_syn_ack" => ScanResponse::OverheardSynAck,
"tcp_rst" => ScanResponse::TcpRst,
"udp_response" => ScanResponse::UdpResponse,
"sctp_init_ack" => ScanResponse::SctpInitAck,
"sctp_abort" => ScanResponse::SctpAbort,
"no_response" => ScanResponse::NoResponse,
"icmp_unreachable" => ScanResponse::IcmpUnreachable,
"icmp_prohibited" => ScanResponse::IcmpProhibited,
_ => return None,
})
}
pub fn os_source_name(source: OsSource) -> &'static str {
match source {
OsSource::TcpStack => "tcp_stack",
OsSource::HardwareVendor => "hardware_vendor",
OsSource::ServiceBanner => "service_banner",
OsSource::SnmpAgent => "snmp_agent",
OsSource::MdnsResponder => "mdns_responder",
OsSource::Hostname => "hostname",
}
}
pub fn os_source(name: &str) -> Option<OsSource> {
Some(match name {
"tcp_stack" => OsSource::TcpStack,
"hardware_vendor" => OsSource::HardwareVendor,
"service_banner" => OsSource::ServiceBanner,
"snmp_agent" => OsSource::SnmpAgent,
"mdns_responder" => OsSource::MdnsResponder,
"hostname" => OsSource::Hostname,
_ => return None,
})
}
pub fn attachment_source_name(source: AttachmentSource) -> &'static str {
match source {
AttachmentSource::Lldp => "lldp",
AttachmentSource::Cdp => "cdp",
}
}
pub fn attachment_source(name: &str) -> Option<AttachmentSource> {
Some(match name {
"lldp" => AttachmentSource::Lldp,
"cdp" => AttachmentSource::Cdp,
_ => return None,
})
}
pub fn scan_kind_name(kind: ScanKind) -> &'static str {
match kind {
ScanKind::Discovery => "discovery",
ScanKind::PortScan => "port_scan",
ScanKind::Listen => "listen",
}
}
pub fn scan_kind(name: &str) -> Option<ScanKind> {
Some(match name {
"discovery" => ScanKind::Discovery,
"port_scan" => ScanKind::PortScan,
"listen" => ScanKind::Listen,
_ => return None,
})
}
pub fn scanner_kind_name(kind: ScannerKind) -> &'static str {
match kind {
ScannerKind::Local => "local",
ScannerKind::Passive => "passive",
ScannerKind::Routed => "routed",
ScannerKind::RoutedSctp => "routed_sctp",
ScannerKind::SynPort => "syn_port",
ScannerKind::TcpPort => "tcp_port",
ScannerKind::Connect => "connect",
ScannerKind::ConnectUdp => "connect_udp",
ScannerKind::UdpPort => "udp_port",
ScannerKind::SctpPort => "sctp_port",
ScannerKind::OsEcho => "os_echo",
ScannerKind::OsSeries => "os_series",
ScannerKind::OsSnmp => "os_snmp",
ScannerKind::Idle => "idle",
ScannerKind::Composite => "composite",
ScannerKind::Service => "service",
ScannerKind::Detection => "detection",
ScannerKind::Journal => "journal",
}
}
pub fn scanner_kind(name: &str) -> Option<ScannerKind> {
Some(match name {
"local" => ScannerKind::Local,
"passive" => ScannerKind::Passive,
"routed" => ScannerKind::Routed,
"routed_sctp" => ScannerKind::RoutedSctp,
"syn_port" => ScannerKind::SynPort,
"tcp_port" => ScannerKind::TcpPort,
"connect" => ScannerKind::Connect,
"connect_udp" => ScannerKind::ConnectUdp,
"udp_port" => ScannerKind::UdpPort,
"sctp_port" => ScannerKind::SctpPort,
"os_echo" => ScannerKind::OsEcho,
"os_series" => ScannerKind::OsSeries,
"os_snmp" => ScannerKind::OsSnmp,
"idle" => ScannerKind::Idle,
"composite" => ScannerKind::Composite,
"service" => ScannerKind::Service,
"detection" => ScannerKind::Detection,
"journal" => ScannerKind::Journal,
_ => return None,
})
}
pub fn stop_reason_name(reason: StopReason) -> &'static str {
match reason {
StopReason::Aborted => "aborted",
StopReason::AllResponded => "all_responded",
StopReason::AttemptsSpent => "attempts_spent",
StopReason::DeadlineExpired => "deadline_expired",
StopReason::TimedOut => "timed_out",
StopReason::StreamClosed => "stream_closed",
}
}
pub fn stop_reason(name: &str) -> Option<StopReason> {
Some(match name {
"aborted" => StopReason::Aborted,
"all_responded" => StopReason::AllResponded,
"attempts_spent" => StopReason::AttemptsSpent,
"deadline_expired" => StopReason::DeadlineExpired,
"timed_out" => StopReason::TimedOut,
"stream_closed" => StopReason::StreamClosed,
_ => return None,
})
}
pub fn port_scope_name(scope: &PortScope) -> &'static str {
match scope {
PortScope::Unstated => "unstated",
PortScope::NoPorts => "none",
PortScope::Every(_) => "every",
PortScope::Mixed(_) => "mixed",
}
}
pub fn port_scope(name: &str, ports: Option<PortSet>) -> Option<PortScope> {
Some(match (name, ports) {
("unstated", _) => PortScope::Unstated,
("none", _) => PortScope::NoPorts,
("every", Some(ports)) => PortScope::Every(ports),
("mixed", Some(ports)) => PortScope::Mixed(ports),
("every" | "mixed", None) => PortScope::Unstated,
_ => return None,
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn every_name_parses_back() {
for value in HostStatus::ALL {
assert_eq!(host_status(host_status_name(value)), Some(value));
}
for value in PortState::ALL {
assert_eq!(port_state(port_state_name(value)), Some(value));
}
for value in ScanKind::ALL {
assert_eq!(scan_kind(scan_kind_name(value)), Some(value));
}
for value in IpProtocolState::ALL {
assert_eq!(
ip_protocol_state(ip_protocol_state_name(value)),
Some(value)
);
}
for value in Filtering::ALL {
assert_eq!(filtering(filtering_name(value)), Some(value));
}
for value in AttachmentSource::ALL {
assert_eq!(
attachment_source(attachment_source_name(value)),
Some(value)
);
}
for value in ScannerKind::ALL {
assert_eq!(scanner_kind(scanner_kind_name(value)), Some(value));
}
for value in StopReason::ALL {
assert_eq!(stop_reason(stop_reason_name(value)), Some(value));
}
for value in Protocol::ALL {
assert_eq!(protocol(protocol_name(value)), Some(value));
}
for value in NetworkRole::ALL {
assert_eq!(network_role(network_role_name(value)), Some(value));
}
for value in Severity::ALL {
assert_eq!(severity(severity_name(value)), Some(value));
}
for value in DetectionClass::ALL {
assert_eq!(detection_class(detection_class_name(value)), Some(value));
}
for value in Confidence::ALL {
assert_eq!(confidence(confidence_name(value)), Some(value));
}
for value in [
Reference::Cve("CVE-2021-44228".to_string()),
Reference::Cwe(79),
Reference::url("https://example.test/advisory"),
] {
let kind = reference_kind_name(&value);
let carried = match &value {
Reference::Cve(s) | Reference::Url(s) => s.clone(),
Reference::Cwe(n) => n.to_string(),
};
assert_eq!(reference(kind, &carried), Some(value));
}
for value in [
OsSource::TcpStack,
OsSource::HardwareVendor,
OsSource::ServiceBanner,
OsSource::SnmpAgent,
OsSource::MdnsResponder,
OsSource::Hostname,
] {
assert_eq!(os_source(os_source_name(value)), Some(value));
}
for value in StatusProtocol::ALL
.iter()
.cloned()
.chain([StatusProtocol::Custom("a-strategy".into())])
{
let name = status_protocol_name(&value);
assert_eq!(status_protocol(&name), Some(value.clone()), "{name}");
}
for value in [
ScanResponse::TcpSynAck,
ScanResponse::OverheardSynAck,
ScanResponse::TcpRst,
ScanResponse::UdpResponse,
ScanResponse::NoResponse,
ScanResponse::IcmpUnreachable,
ScanResponse::IcmpProhibited,
ScanResponse::Custom("a-strategy".to_string()),
] {
let name = scan_response_name(&value);
assert_eq!(scan_response(&name), Some(value.clone()), "{name}");
}
}
#[test]
fn every_built_in_protocol_is_named_everywhere() {
const SCHEMA: &str = include_str!("../../assets/schema/zond-report-v1.schema.json");
let described = SCHEMA
.find("The protocol event that produced the evidence")
.expect("the schema describes the evidence protocol");
let names = &SCHEMA[described..];
let names = &names[..names.find(']').expect("the enum closes")];
assert!(
!names.contains("\"router\""),
"the search caught the network-role enum instead"
);
for protocol in StatusProtocol::ALL {
match protocol {
StatusProtocol::Arp
| StatusProtocol::Ndp
| StatusProtocol::IcmpEcho
| StatusProtocol::IcmpTimestamp
| StatusProtocol::IcmpUnreachable
| StatusProtocol::TcpSyn
| StatusProtocol::Tcp
| StatusProtocol::Dhcp
| StatusProtocol::Udp
| StatusProtocol::Sctp => {}
StatusProtocol::Custom(_) => {
unreachable!("`ALL` holds no strategy-supplied names")
}
}
let name = status_protocol_name(protocol);
assert_eq!(status_protocol(&name), Some(protocol.clone()));
assert!(
names.contains(&format!("\"{name}\"")),
"the report schema does not name '{name}'"
);
}
}
#[test]
fn every_port_scope_parses_back() {
let ports = || PortSet::try_from("80,443").expect("a port set");
for scope in [
PortScope::Unstated,
PortScope::NoPorts,
PortScope::Every(ports()),
PortScope::Mixed(ports()),
] {
let name = port_scope_name(&scope);
assert_eq!(
port_scope(name, scope.ports().cloned()),
Some(scope.clone()),
"{name}"
);
}
assert_eq!(port_scope("every", None), Some(PortScope::Unstated));
assert_eq!(port_scope("mixed", None), Some(PortScope::Unstated));
assert_eq!(port_scope("thorough", Some(ports())), None);
}
#[test]
fn an_unknown_name_is_refused() {
assert_eq!(host_status("perhaps"), None);
assert_eq!(port_state("ajar"), None);
assert_eq!(protocol("dccp"), None);
assert_eq!(network_role("gateway"), None);
assert_eq!(os_source("astrology"), None);
assert_eq!(status_protocol("igmp"), None);
assert_eq!(scan_response("tcp_fin_ack"), None);
assert_eq!(scan_kind("enrichment"), None);
assert_eq!(scanner_kind("telepathy"), None);
assert_eq!(stop_reason("bored"), None);
assert_eq!(severity("catastrophic"), None);
assert_eq!(detection_class("nosy"), None);
assert_eq!(confidence("absolute"), None);
assert_eq!(reference("mystery", "x"), None);
}
#[test]
fn an_empty_custom_name_is_refused() {
assert_eq!(status_protocol(CUSTOM), None);
assert_eq!(scan_response(CUSTOM), None);
}
}