use std::fmt;
use std::str::FromStr;
use crate::model::port::PortState;
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TcpReply {
SynAck,
Rst {
window: u16,
},
ChallengeAck,
}
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SctpReply {
InitAck,
Abort,
}
#[non_exhaustive]
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum SctpScanTechnique {
#[default]
Init,
CookieEcho,
}
impl SctpScanTechnique {
pub const ALL: &'static [Self] = &[Self::Init, Self::CookieEcho];
pub const fn name(self) -> &'static str {
match self {
Self::Init => "init",
Self::CookieEcho => "cookie-echo",
}
}
pub const fn summary(self) -> &'static str {
match self {
Self::Init => "association attempt; the only one that confirms a listener",
Self::CookieEcho => "unminted cookie; a closed port answers, an open one stays silent",
}
}
pub const fn verdict(self, reply: SctpReply) -> Option<PortState> {
match (self, reply) {
(Self::Init, SctpReply::InitAck) => Some(PortState::Open),
(Self::Init | Self::CookieEcho, SctpReply::Abort) => Some(PortState::Closed),
(Self::CookieEcho, SctpReply::InitAck) => None,
}
}
pub const fn silence_means(self) -> PortState {
match self {
Self::Init => PortState::Filtered,
Self::CookieEcho => PortState::OpenFiltered,
}
}
pub const fn finds_open_ports(self) -> bool {
matches!(self, Self::Init)
}
pub const fn silence_label(self) -> &'static str {
match self {
Self::Init => "filtered",
Self::CookieEcho => "open-filtered",
}
}
}
impl fmt::Display for SctpScanTechnique {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.name())
}
}
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
#[error(
"unknown SCTP scan technique '{input}', expected one of: {}",
Self::expected()
)]
pub struct UnknownSctpTechnique {
pub input: String,
}
impl UnknownSctpTechnique {
fn expected() -> String {
SctpScanTechnique::ALL
.iter()
.map(|technique| technique.name())
.collect::<Vec<_>>()
.join(", ")
}
}
impl FromStr for SctpScanTechnique {
type Err = UnknownSctpTechnique;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let name = s.trim().to_ascii_lowercase();
Self::ALL
.iter()
.copied()
.find(|technique| technique.name() == name)
.ok_or_else(|| UnknownSctpTechnique {
input: s.to_string(),
})
}
}
#[non_exhaustive]
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum TcpScanTechnique {
#[default]
Syn,
Fin,
Null,
Xmas,
Maimon,
Ack,
Window,
}
impl TcpScanTechnique {
pub const ALL: &'static [Self] = &[
Self::Syn,
Self::Fin,
Self::Null,
Self::Xmas,
Self::Maimon,
Self::Ack,
Self::Window,
];
pub const fn name(self) -> &'static str {
match self {
Self::Syn => "syn",
Self::Fin => "fin",
Self::Null => "null",
Self::Xmas => "xmas",
Self::Maimon => "maimon",
Self::Ack => "ack",
Self::Window => "window",
}
}
pub const fn summary(self) -> &'static str {
match self {
Self::Syn => "half-open connection attempt; the only one that confirms a listener",
Self::Fin => "bare FIN; a closed port answers, an open one stays silent",
Self::Null => "no flags set; like FIN, but unlike any real connection",
Self::Xmas => "FIN, PSH and URG at once; the most unusual segment of the three",
Self::Maimon => {
"FIN with ACK; only meaningful against BSD-derived stacks, misleading elsewhere"
}
Self::Ack => "bare ACK; maps the firewall rather than the ports behind it",
Self::Window => {
"bare ACK read for the reset's window; tells open from closed where a stack leaks it"
}
}
}
pub const fn verdict(self, reply: TcpReply) -> Option<PortState> {
match (self, reply) {
(Self::Syn, TcpReply::SynAck) => Some(PortState::Open),
(Self::Syn, TcpReply::Rst { .. }) => Some(PortState::Closed),
(Self::Syn, TcpReply::ChallengeAck) => Some(PortState::Open),
(Self::Fin | Self::Null | Self::Xmas | Self::Maimon, TcpReply::Rst { .. }) => {
Some(PortState::Closed)
}
(Self::Ack, TcpReply::Rst { .. }) => Some(PortState::Unfiltered),
(Self::Window, TcpReply::Rst { window }) => Some(if window == 0 {
PortState::Closed
} else {
PortState::Open
}),
_ => None,
}
}
pub const fn silence_means(self) -> PortState {
match self {
Self::Syn | Self::Ack | Self::Window => PortState::Filtered,
Self::Fin | Self::Null | Self::Xmas | Self::Maimon => PortState::OpenFiltered,
}
}
pub const fn finds_open_ports(self) -> bool {
matches!(self, Self::Syn | Self::Window)
}
pub const fn has_connect_fallback(self) -> bool {
matches!(self, Self::Syn)
}
pub const fn reads_icmp_errors(self) -> bool {
!matches!(self, Self::Syn)
}
}
impl fmt::Display for TcpScanTechnique {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.name())
}
}
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
#[error(
"unknown TCP scan technique '{input}', expected one of: {}",
Self::expected()
)]
pub struct UnknownTechnique {
pub input: String,
}
impl UnknownTechnique {
fn expected() -> String {
TcpScanTechnique::ALL
.iter()
.map(|technique| technique.name())
.collect::<Vec<_>>()
.join(", ")
}
}
impl FromStr for TcpScanTechnique {
type Err = UnknownTechnique;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let name = s.trim().to_ascii_lowercase();
Self::ALL
.iter()
.copied()
.find(|technique| technique.name() == name)
.ok_or_else(|| UnknownTechnique {
input: s.to_string(),
})
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn every_technique_parses_back_from_the_name_it_prints() {
for &technique in TcpScanTechnique::ALL {
assert_eq!(technique.to_string().parse(), Ok(technique));
}
}
#[test]
fn parsing_ignores_case_and_surrounding_space() {
assert_eq!(" MAIMON ".parse(), Ok(TcpScanTechnique::Maimon));
}
#[test]
fn an_unknown_name_is_rejected_with_the_ones_that_would_work() {
let error = "stealth"
.parse::<TcpScanTechnique>()
.unwrap_err()
.to_string();
assert!(error.contains("stealth"));
for &technique in TcpScanTechnique::ALL {
assert!(
error.contains(technique.name()),
"{technique} is missing: {error}"
);
}
}
#[test]
fn a_rst_means_something_different_per_technique() {
use TcpScanTechnique::*;
let rst = TcpReply::Rst { window: 8192 };
assert_eq!(Syn.verdict(rst), Some(PortState::Closed));
assert_eq!(Fin.verdict(rst), Some(PortState::Closed));
assert_eq!(Ack.verdict(rst), Some(PortState::Unfiltered));
assert_eq!(Window.verdict(rst), Some(PortState::Open));
}
#[test]
fn a_window_scan_reads_the_reset_the_ack_scan_only_counts() {
use TcpScanTechnique::*;
assert_eq!(
Window.verdict(TcpReply::Rst { window: 0 }),
Some(PortState::Closed)
);
assert_eq!(
Window.verdict(TcpReply::Rst { window: 1 }),
Some(PortState::Open)
);
assert_eq!(
Ack.verdict(TcpReply::Rst { window: 0 }),
Ack.verdict(TcpReply::Rst { window: 1 }),
"an ack scan reads the window it has no use for"
);
}
#[test]
fn only_a_syn_scan_falls_back_to_connect() {
for &technique in TcpScanTechnique::ALL {
assert_eq!(
technique.has_connect_fallback(),
technique == TcpScanTechnique::Syn,
"{technique} would have been answered by a connect scan"
);
}
assert!(TcpScanTechnique::Window.finds_open_ports());
assert!(!TcpScanTechnique::Window.has_connect_fallback());
}
#[test]
fn only_a_syn_scan_reads_a_syn_ack() {
for &technique in TcpScanTechnique::ALL {
let verdict = technique.verdict(TcpReply::SynAck);
assert_eq!(
verdict.is_some(),
technique == TcpScanTechnique::Syn,
"{technique} read a SYN+ACK it could not have provoked"
);
}
}
#[test]
fn silence_is_open_filtered_exactly_for_the_flag_probes() {
use TcpScanTechnique::*;
assert_eq!(Syn.silence_means(), PortState::Filtered);
assert_eq!(Ack.silence_means(), PortState::Filtered);
assert_eq!(Window.silence_means(), PortState::Filtered);
for technique in [Fin, Null, Xmas, Maimon] {
assert_eq!(technique.silence_means(), PortState::OpenFiltered);
}
}
#[test]
fn only_a_syn_scan_declines_icmp_errors() {
for &technique in TcpScanTechnique::ALL {
assert_eq!(
technique.reads_icmp_errors(),
technique != TcpScanTechnique::Syn
);
}
}
#[test]
fn every_sctp_technique_parses_back_from_the_name_it_prints() {
for &technique in SctpScanTechnique::ALL {
assert_eq!(technique.to_string().parse(), Ok(technique));
}
}
#[test]
fn an_unknown_sctp_name_is_rejected_with_the_ones_that_would_work() {
let error = "cookie".parse::<SctpScanTechnique>().expect_err("refused");
let message = error.to_string();
for &technique in SctpScanTechnique::ALL {
assert!(
message.contains(technique.name()),
"the error should name {}",
technique.name()
);
}
}
#[test]
fn an_abort_closes_a_port_for_both_and_an_init_ack_only_for_one() {
assert_eq!(
SctpScanTechnique::Init.verdict(SctpReply::Abort),
Some(PortState::Closed)
);
assert_eq!(
SctpScanTechnique::CookieEcho.verdict(SctpReply::Abort),
Some(PortState::Closed)
);
assert_eq!(
SctpScanTechnique::Init.verdict(SctpReply::InitAck),
Some(PortState::Open)
);
assert_eq!(
SctpScanTechnique::CookieEcho.verdict(SctpReply::InitAck),
None
);
}
#[test]
fn only_an_init_scan_names_an_open_sctp_port() {
assert!(SctpScanTechnique::Init.finds_open_ports());
assert!(!SctpScanTechnique::CookieEcho.finds_open_ports());
assert_eq!(SctpScanTechnique::Init.silence_means(), PortState::Filtered);
assert_eq!(
SctpScanTechnique::CookieEcho.silence_means(),
PortState::OpenFiltered
);
}
#[test]
fn the_silence_label_names_the_state_silence_produces() {
assert_eq!(SctpScanTechnique::Init.silence_label(), "filtered");
assert_eq!(
SctpScanTechnique::CookieEcho.silence_label(),
"open-filtered"
);
}
}