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,
ChallengeAck,
}
#[non_exhaustive]
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum TcpScanTechnique {
#[default]
Syn,
Fin,
Null,
Xmas,
Maimon,
Ack,
}
impl TcpScanTechnique {
pub const ALL: [Self; 6] = [
Self::Syn,
Self::Fin,
Self::Null,
Self::Xmas,
Self::Maimon,
Self::Ack,
];
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",
}
}
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",
}
}
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),
_ => None,
}
}
pub const fn silence_means(self) -> PortState {
match self {
Self::Syn | Self::Ack => PortState::Filtered,
Self::Fin | Self::Null | Self::Xmas | Self::Maimon => PortState::OpenFiltered,
}
}
pub const fn finds_open_ports(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)]
#[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
.into_iter()
.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::*;
assert_eq!(Syn.verdict(TcpReply::Rst), Some(PortState::Closed));
assert_eq!(Fin.verdict(TcpReply::Rst), Some(PortState::Closed));
assert_eq!(Ack.verdict(TcpReply::Rst), Some(PortState::Unfiltered));
}
#[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.finds_open_ports(),
"{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);
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
);
}
}
}