const BROWSER_HEADER_BYTES: usize = 3;
const BROWSER_SVR_RESP: u8 = 0x05;
const MEMCACHED_FRAME_BYTES: usize = 8;
#[must_use]
pub(super) fn sql_server_browser(datagram: &[u8]) -> Option<&str> {
if *datagram.first()? != BROWSER_SVR_RESP {
return None;
}
let stated = u16::from_le_bytes([*datagram.get(1)?, *datagram.get(2)?]) as usize;
let body = datagram.get(BROWSER_HEADER_BYTES..)?;
let body = body.get(..stated.min(body.len()))?;
std::str::from_utf8(body).ok().map(str::trim_end)
}
#[must_use]
pub(super) fn memcached_udp(datagram: &[u8]) -> Option<&str> {
let body = datagram.get(MEMCACHED_FRAME_BYTES..)?;
let body = std::str::from_utf8(body).ok()?.trim();
(!body.is_empty()).then_some(body)
}
#[must_use]
pub(super) fn xdmcp_willing(datagram: &[u8]) -> Option<String> {
const OPCODE_WILLING: u16 = 5;
let opcode = u16::from_be_bytes([*datagram.get(2)?, *datagram.get(3)?]);
if opcode != OPCODE_WILLING {
return None;
}
let mut at = 6;
let mut fields = Vec::with_capacity(3);
for _ in 0..3 {
let len = u16::from_be_bytes([*datagram.get(at)?, *datagram.get(at + 1)?]) as usize;
let value = datagram.get(at + 2..at + 2 + len)?;
fields.push(String::from_utf8_lossy(value).trim().to_string());
at += 2 + len;
}
let (host, status) = (&fields[1], &fields[2]);
match (host.is_empty(), status.is_empty()) {
(true, true) => None,
(true, false) => Some(status.clone()),
(false, true) => Some(host.clone()),
(false, false) => Some(format!("{host}: {status}")),
}
}
#[must_use]
pub(super) fn source_engine(datagram: &[u8]) -> Option<String> {
const HEADER: &[u8] = &[0xFF, 0xFF, 0xFF, 0xFF];
const INFO: u8 = b'I';
const CHALLENGE: u8 = b'A';
if !datagram.starts_with(HEADER) {
return None;
}
match *datagram.get(4)? {
CHALLENGE => Some("challenge".to_string()),
INFO => {
let mut rest = datagram.get(6..)?;
let mut fields = Vec::with_capacity(4);
for _ in 0..4 {
let end = rest.iter().position(|byte| *byte == 0)?;
fields.push(String::from_utf8_lossy(&rest[..end]).to_string());
rest = rest.get(end + 1..)?;
}
Some(fields.join(";"))
}
_ => None,
}
}
#[must_use]
pub(super) fn raknet_pong(datagram: &[u8]) -> Option<&str> {
const UNCONNECTED_PONG: u8 = 0x1C;
const MAGIC: &[u8] = &[
0x00, 0xFF, 0xFF, 0x00, 0xFE, 0xFE, 0xFE, 0xFE, 0xFD, 0xFD, 0xFD, 0xFD, 0x12, 0x34, 0x56,
0x78,
];
if *datagram.first()? != UNCONNECTED_PONG {
return None;
}
if datagram.get(17..33)? != MAGIC {
return None;
}
let len = u16::from_be_bytes([*datagram.get(33)?, *datagram.get(34)?]) as usize;
let status = datagram.get(35..35 + len)?;
std::str::from_utf8(status).ok().map(str::trim)
}
#[must_use]
pub(super) fn coap_payload(datagram: &[u8]) -> Option<&str> {
const PAYLOAD_MARKER: u8 = 0xFF;
const VERSION_1: u8 = 0b0100_0000;
let first = *datagram.first()?;
if first & 0b1100_0000 != VERSION_1 {
return None;
}
let mut at = 4 + (first & 0x0F) as usize;
while let Some(byte) = datagram.get(at) {
if *byte == PAYLOAD_MARKER {
let payload = datagram.get(at + 1..)?;
let text = std::str::from_utf8(payload).ok()?.trim();
return (!text.is_empty()).then_some(text);
}
at += 1;
let mut length = (*byte & 0x0F) as usize;
for nibble in [*byte >> 4, *byte & 0x0F] {
at += match nibble {
13 => 1,
14 => 2,
15 => return None,
_ => 0,
};
}
if length == 13 {
length = *datagram.get(at - 1)? as usize + 13;
} else if length == 14 {
length =
u16::from_be_bytes([*datagram.get(at - 2)?, *datagram.get(at - 1)?]) as usize + 269;
}
at += length;
}
None
}
#[must_use]
pub(super) fn rpc_program_dump(datagram: &[u8]) -> Option<String> {
const NAMED: &[(u32, &str)] = &[
(100000, "portmapper"),
(100003, "nfs"),
(100005, "mountd"),
(100021, "nlockmgr"),
(100024, "status"),
(100227, "nfs_acl"),
(100011, "rquotad"),
(100002, "rusersd"),
];
let body = accepted_rpc_reply(datagram)?;
let word = |at: usize| -> Option<u32> {
body.get(at..at + 4)
.map(|bytes| u32::from_be_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]))
};
let mut at = 0;
let mut entries = Vec::new();
while word(at)? == 1 {
let (program, version, protocol, port) =
(word(at + 4)?, word(at + 8)?, word(at + 12)?, word(at + 16)?);
at += 20;
let name = NAMED
.iter()
.find(|(number, _)| *number == program)
.map_or_else(|| program.to_string(), |(_, name)| (*name).to_string());
let transport = match protocol {
6 => "tcp",
17 => "udp",
other => return Some(format!("{name} {version} proto{other} {port}")),
};
entries.push(format!("{name} {version} {transport} {port}"));
if entries.len() >= 64 {
break;
}
}
(!entries.is_empty()).then(|| entries.join(", "))
}
#[must_use]
pub(super) fn rpc_version_range(datagram: &[u8]) -> Option<String> {
const PROG_MISMATCH: u32 = 2;
let (status, body) = rpc_reply_status(datagram)?;
if status != PROG_MISMATCH {
return None;
}
let word = |at: usize| -> Option<u32> {
body.get(at..at + 4)
.map(|bytes| u32::from_be_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]))
};
let (low, high) = (word(0)?, word(4)?);
(low <= high && high < 100).then(|| format!("versions {low}-{high}"))
}
fn accepted_rpc_reply(datagram: &[u8]) -> Option<&[u8]> {
match rpc_reply_status(datagram)? {
(0, body) => Some(body),
_ => None,
}
}
fn rpc_reply_status(datagram: &[u8]) -> Option<(u32, &[u8])> {
const MSG_TYPE_REPLY: u32 = 1;
const MSG_ACCEPTED: u32 = 0;
let word = |at: usize| -> Option<u32> {
datagram
.get(at..at + 4)
.map(|bytes| u32::from_be_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]))
};
if word(4)? != MSG_TYPE_REPLY || word(8)? != MSG_ACCEPTED {
return None;
}
let verifier = word(16)? as usize;
let at = 20 + verifier.next_multiple_of(4);
Some((word(at)?, datagram.get(at + 4..)?))
}
#[must_use]
pub(super) fn ipmi_auth_capabilities(datagram: &[u8]) -> Option<String> {
const CLASS_IPMI: u8 = 0x07;
const DATA_AT: usize = 4 + 9 + 1 + 7;
if *datagram.first()? != 0x06 || *datagram.get(3)? != CLASS_IPMI {
return None;
}
if *datagram.get(DATA_AT - 1)? != 0x00 {
return None;
}
let support = *datagram.get(DATA_AT + 1)?;
let status = *datagram.get(DATA_AT + 2)?;
let mut said = Vec::new();
said.push(match support & 0b1000_0000 != 0 {
true => "IPMI-2.0",
false => "IPMI-1.5",
});
if status & 0b0000_0001 != 0 {
said.push("anonymous-login");
}
if status & 0b0000_0010 != 0 {
said.push("null-user");
}
Some(said.join(" "))
}
#[must_use]
pub(super) fn ntp_control_variables(datagram: &[u8]) -> Option<String> {
const RESPONSE: u8 = 0b1000_0000;
const OPCODE: u8 = 0b0001_1111;
const READVAR: u8 = 2;
const HEADER_BYTES: usize = 12;
let mode = *datagram.first()? & 0b0000_0111;
if mode != 6 {
return None;
}
let second = *datagram.get(1)?;
if second & RESPONSE == 0 || second & OPCODE != READVAR {
return None;
}
let count = u16::from_be_bytes([*datagram.get(10)?, *datagram.get(11)?]) as usize;
let data = datagram.get(HEADER_BYTES..HEADER_BYTES + count)?;
let text = std::str::from_utf8(data).ok()?;
let mut folded = String::with_capacity(text.len());
let mut breaking = false;
for character in text.chars() {
match character {
'\r' | '\n' => breaking = true,
_ => {
if breaking {
folded.push(' ');
breaking = false;
}
folded.push(character);
}
}
}
let folded = folded.trim().to_string();
(!folded.is_empty()).then_some(folded)
}
#[must_use]
pub(super) fn stun_binding(datagram: &[u8]) -> Option<String> {
const MAGIC_COOKIE: u32 = 0x2112_A442;
const BINDING_SUCCESS: u16 = 0x0101;
const SOFTWARE: u16 = 0x8022;
const HEADER_BYTES: usize = 20;
let kind = u16::from_be_bytes([*datagram.first()?, *datagram.get(1)?]);
let cookie = u32::from_be_bytes([
*datagram.get(4)?,
*datagram.get(5)?,
*datagram.get(6)?,
*datagram.get(7)?,
]);
if cookie != MAGIC_COOKIE || kind != BINDING_SUCCESS {
return None;
}
let mut at = HEADER_BYTES;
while at + 4 <= datagram.len() {
let attribute = u16::from_be_bytes([datagram[at], datagram[at + 1]]);
let length = u16::from_be_bytes([datagram[at + 2], datagram[at + 3]]) as usize;
let value = datagram.get(at + 4..at + 4 + length)?;
if attribute == SOFTWARE
&& let Ok(name) = std::str::from_utf8(value)
&& let name = name.trim().trim_end_matches('\0')
&& !name.is_empty()
{
return Some(name.to_string());
}
at += 4 + length.next_multiple_of(4);
}
Some("stun".to_string())
}
#[must_use]
pub(super) fn ike_response(datagram: &[u8]) -> Option<String> {
const HEADER_BYTES: usize = 28;
const PAYLOAD_VENDOR_ID: u8 = 13;
const PAYLOAD_NOTIFY: u8 = 11;
const PAYLOAD_HEADER_BYTES: usize = 4;
if datagram.len() < HEADER_BYTES {
return None;
}
if datagram.get(8..16)? == [0u8; 8] {
return None;
}
let mut next = *datagram.get(16)?;
let mut at = HEADER_BYTES;
let mut vendor_ids = Vec::new();
let mut notified = false;
while next != 0 && at + PAYLOAD_HEADER_BYTES <= datagram.len() {
let length = u16::from_be_bytes([datagram[at + 2], datagram[at + 3]]) as usize;
if length < PAYLOAD_HEADER_BYTES {
return None;
}
let body = datagram.get(at + PAYLOAD_HEADER_BYTES..at + length)?;
match next {
PAYLOAD_VENDOR_ID => vendor_ids.push(
body.iter()
.map(|byte| format!("{byte:02x}"))
.collect::<String>(),
),
PAYLOAD_NOTIFY => notified = true,
_ => {}
}
next = datagram[at];
at += length;
if vendor_ids.len() >= 16 {
break;
}
}
match (vendor_ids.is_empty(), notified) {
(false, _) => Some(vendor_ids.join(" ")),
(true, true) => Some("notify".to_string()),
(true, false) => Some("isakmp".to_string()),
}
}
const PROBE_REALM: &str = "ZOND-SCAN";
#[must_use]
pub(super) fn kerberos_error(datagram: &[u8]) -> Option<String> {
const KRB_ERROR: u8 = 0x7E;
if *datagram.first()? != KRB_ERROR {
return None;
}
let body = der_value(datagram)?;
let fields = der_value(body)?;
let mut code = None;
let mut realm = None;
let mut text = None;
let mut at = 0;
while at < fields.len() {
let (tag, value, next) = der_element(&fields[at..])?;
match tag {
0xA6 => code = der_value(value).map(der_unsigned),
0xA9 => realm = der_value(value).and_then(|v| std::str::from_utf8(v).ok()),
0xAB => text = der_value(value).and_then(|v| std::str::from_utf8(v).ok()),
_ => {}
}
at += next;
}
let code = code?;
let mut said = format!("krb-error {code}");
if let Some(realm) = realm.filter(|realm| *realm != PROBE_REALM) {
said.push_str(&format!(" realm={realm}"));
}
if let Some(text) = text.filter(|text| !text.is_empty()) {
said.push(' ');
said.push_str(text);
}
Some(said)
}
fn der_value(bytes: &[u8]) -> Option<&[u8]> {
der_element(bytes).map(|(_, value, _)| value)
}
fn der_element(bytes: &[u8]) -> Option<(u8, &[u8], usize)> {
let tag = *bytes.first()?;
let first = *bytes.get(1)? as usize;
let (length, header) = if first & 0x80 == 0 {
(first, 2)
} else {
let count = first & 0x7F;
if count == 0 || count > 4 {
return None;
}
let mut length = 0usize;
for index in 0..count {
length = (length << 8) | *bytes.get(2 + index)? as usize;
}
(length, 2 + count)
};
let value = bytes.get(header..header + length)?;
Some((tag, value, header + length))
}
fn der_unsigned(bytes: &[u8]) -> u32 {
bytes
.iter()
.take(4)
.fold(0u32, |value, byte| (value << 8) | u32::from(*byte))
}
#[must_use]
pub(super) fn l2tp_control(datagram: &[u8]) -> Option<String> {
const CONTROL: u8 = 0b1100_0000;
const HEADER_BYTES: usize = 12;
const ATTRIBUTE_HEADER_BYTES: usize = 6;
const VENDOR_NAME: u16 = 8;
const HOST_NAME: u16 = 7;
if *datagram.first()? & CONTROL != CONTROL {
return None;
}
if *datagram.get(1)? & 0x0F != 2 {
return None;
}
let mut at = HEADER_BYTES;
let mut vendor = None;
let mut host = None;
let mut attributes = 0usize;
while at + ATTRIBUTE_HEADER_BYTES <= datagram.len() {
attributes += 1;
let length = (u16::from_be_bytes([datagram[at], datagram[at + 1]]) & 0x03FF) as usize;
if length < ATTRIBUTE_HEADER_BYTES {
return None;
}
let attribute = u16::from_be_bytes([datagram[at + 4], datagram[at + 5]]);
let value = datagram.get(at + ATTRIBUTE_HEADER_BYTES..at + length)?;
let text = |value: &[u8]| {
std::str::from_utf8(value)
.ok()
.map(|text| text.trim().to_string())
.filter(|text| !text.is_empty())
};
match attribute {
VENDOR_NAME => vendor = text(value),
HOST_NAME => host = text(value),
_ => {}
}
at += length;
}
if attributes == 0 {
return None;
}
let mut said = Vec::new();
if let Some(vendor) = vendor {
said.push(format!("vendor={vendor}"));
}
if let Some(host) = host {
said.push(format!("host={host}"));
}
match said.is_empty() {
true => Some("l2tp".to_string()),
false => Some(said.join(" ")),
}
}
#[must_use]
pub(super) fn smb_session_setup(stream: &[u8]) -> Vec<String> {
const SESSION_SETUP: u8 = 0x73;
const UNICODE: u16 = 0x8000;
const NBSS_HEADER_BYTES: usize = 4;
const SMB_HEADER_BYTES: usize = 32;
let mut at = 0;
while at + NBSS_HEADER_BYTES <= stream.len() {
let length =
u32::from_be_bytes([0, stream[at + 1], stream[at + 2], stream[at + 3]]) as usize;
let Some(message) = stream.get(at + NBSS_HEADER_BYTES..at + NBSS_HEADER_BYTES + length)
else {
break;
};
at += NBSS_HEADER_BYTES + length;
if !message.starts_with(b"\xffSMB") || message.get(4) != Some(&SESSION_SETUP) {
continue;
}
if message.len() < SMB_HEADER_BYTES + 3 {
continue;
}
if u32::from_le_bytes([message[5], message[6], message[7], message[8]]) != 0 {
continue;
}
let unicode = u16::from_le_bytes([message[10], message[11]]) & UNICODE != 0;
let words = message[SMB_HEADER_BYTES] as usize;
let bytes_at = SMB_HEADER_BYTES + 1 + words * 2;
let (Some(low), Some(high)) = (message.get(bytes_at), message.get(bytes_at + 1)) else {
continue;
};
let count = u16::from_le_bytes([*low, *high]) as usize;
let Some(field) = message.get(bytes_at + 2..bytes_at + 2 + count) else {
continue;
};
let names = match unicode {
true => utf16_strings(field),
false => field
.split(|byte| *byte == 0)
.map(|part| String::from_utf8_lossy(part).trim().to_string())
.filter(|part| !part.is_empty())
.collect(),
};
if !names.is_empty() {
return names;
}
}
Vec::new()
}
fn utf16_strings(field: &[u8]) -> Vec<String> {
let field = match field.first() {
Some(0) if field.len() % 2 == 1 => &field[1..],
_ => field,
};
let units: Vec<u16> = field
.as_chunks::<2>()
.0
.iter()
.map(|pair| u16::from_le_bytes(*pair))
.collect();
units
.split(|unit| *unit == 0)
.filter(|part| !part.is_empty())
.map(|part| String::from_utf16_lossy(part).trim().to_string())
.filter(|part| !part.is_empty())
.collect()
}
#[must_use]
pub(super) fn rtsp_server(stream: &[u8]) -> Option<String> {
let text = std::str::from_utf8(stream).ok()?;
if !text.starts_with("RTSP/") {
return None;
}
text.lines()
.skip(1)
.take_while(|line| !line.trim().is_empty())
.find_map(|line| {
let (name, value) = line.split_once(':')?;
name.trim()
.eq_ignore_ascii_case("server")
.then(|| value.trim().to_string())
})
.filter(|value| !value.is_empty())
}
#[must_use]
pub(super) fn wsd_types(datagram: &[u8]) -> Option<String> {
let text = std::str::from_utf8(datagram).ok()?;
let inner = element_text(text, "Types")?;
let types: Vec<&str> = inner
.split_whitespace()
.map(|name| name.rsplit(':').next().unwrap_or(name))
.filter(|name| !name.is_empty())
.collect();
(!types.is_empty()).then(|| types.join(" "))
}
fn element_text<'a>(xml: &'a str, name: &str) -> Option<&'a str> {
let mut search = xml;
loop {
let at = search.find('<')?;
let rest = &search[at + 1..];
let close = rest.find('>')?;
let tag = &rest[..close];
let bare = tag.rsplit(':').next().unwrap_or(tag);
if bare.trim_end_matches('/') == name && !tag.starts_with('/') {
let body = &rest[close + 1..];
let end = body.find('<')?;
let text = body[..end].trim();
return (!text.is_empty()).then_some(text);
}
search = &rest[close..];
}
}
#[cfg(test)]
mod tests {
use super::*;
fn browser(body: &str) -> Vec<u8> {
let mut out = vec![BROWSER_SVR_RESP];
out.extend_from_slice(&(body.len() as u16).to_le_bytes());
out.extend_from_slice(body.as_bytes());
out
}
const INSTANCES: &str = "ServerName;WIN-DB01;InstanceName;SQLEXPRESS;IsClustered;No;\
Version;15.0.2000.5;tcp;1433;;";
#[test]
fn a_browser_response_yields_its_instance_list() {
assert_eq!(sql_server_browser(&browser(INSTANCES)), Some(INSTANCES));
}
#[test]
fn a_length_past_the_datagram_reads_what_arrived() {
let mut short = browser(INSTANCES);
short.truncate(3 + 20);
assert_eq!(sql_server_browser(&short), Some("ServerName;WIN-DB01;"));
}
#[test]
fn anything_that_is_not_a_browser_response_yields_nothing() {
assert!(sql_server_browser(b"").is_none());
assert!(sql_server_browser(b"\x02").is_none());
assert!(sql_server_browser(b"\x05\x10").is_none());
assert!(sql_server_browser(&[0x05, 0x02, 0x00, 0xff, 0xfe]).is_none());
}
#[test]
fn a_memcached_frame_yields_the_line_inside_it() {
let packet = b"\x00\x01\x00\x00\x00\x01\x00\x00VERSION 1.6.21\r\n";
assert_eq!(memcached_udp(packet), Some("VERSION 1.6.21"));
}
#[test]
fn a_datagram_shorter_than_the_frame_yields_nothing() {
assert!(memcached_udp(b"\x00\x01\x00\x00").is_none());
assert!(memcached_udp(b"\x00\x01\x00\x00\x00\x01\x00\x00").is_none());
}
#[test]
fn a_probe_match_yields_its_types_without_prefixes() {
let reply = r#"<?xml version="1.0"?><s:Envelope><s:Body><d:ProbeMatches>
<d:ProbeMatch><a:EndpointReference/><d:Types>wsdp:Device pub:Computer</d:Types>
</d:ProbeMatch></d:ProbeMatches></s:Body></s:Envelope>"#;
assert_eq!(
wsd_types(reply.as_bytes()).as_deref(),
Some("Device Computer")
);
}
#[test]
fn a_printer_answers_with_its_own_type() {
let reply = "<d:ProbeMatches><d:Types>print:PrintDeviceType</d:Types></d:ProbeMatches>";
assert_eq!(
wsd_types(reply.as_bytes()).as_deref(),
Some("PrintDeviceType")
);
}
#[test]
fn a_reply_naming_no_types_yields_nothing() {
assert!(wsd_types(b"<d:ProbeMatches></d:ProbeMatches>").is_none());
assert!(wsd_types(b"not xml at all").is_none());
assert!(wsd_types(b"").is_none());
assert!(wsd_types(b"<d:Types></d:Types>").is_none());
}
fn willing(auth: &str, host: &str, status: &str) -> Vec<u8> {
let mut out = vec![0x00, 0x01, 0x00, 0x05, 0x00, 0x00];
for field in [auth, host, status] {
out.extend_from_slice(&(field.len() as u16).to_be_bytes());
out.extend_from_slice(field.as_bytes());
}
out
}
#[test]
fn a_willing_response_names_the_host_and_the_manager() {
let reply = willing("", "workstation", "Linux 6.1 gdm");
assert_eq!(
xdmcp_willing(&reply).as_deref(),
Some("workstation: Linux 6.1 gdm")
);
}
#[test]
fn a_willing_response_missing_a_field_yields_what_it_has() {
assert_eq!(
xdmcp_willing(&willing("", "", "gdm")).as_deref(),
Some("gdm")
);
assert_eq!(
xdmcp_willing(&willing("", "kiosk", "")).as_deref(),
Some("kiosk")
);
assert!(xdmcp_willing(&willing("", "", "")).is_none());
}
#[test]
fn anything_that_is_not_a_willing_response_yields_nothing() {
assert!(xdmcp_willing(b"\x00\x01\x00\x02\x00\x01\x00").is_none());
assert!(xdmcp_willing(b"").is_none());
let mut lying = willing("", "host", "status");
lying[6] = 0xff;
assert!(xdmcp_willing(&lying).is_none());
}
#[test]
fn a_source_info_reply_yields_the_server_and_its_game() {
let mut reply = vec![0xFF, 0xFF, 0xFF, 0xFF, b'I', 17];
for field in ["Zond Test Server", "de_dust2", "csgo", "Counter-Strike"] {
reply.extend_from_slice(field.as_bytes());
reply.push(0);
}
reply.extend_from_slice(&[0x00, 0x01, 0x02]);
assert_eq!(
source_engine(&reply).as_deref(),
Some("Zond Test Server;de_dust2;csgo;Counter-Strike")
);
}
#[test]
fn a_source_challenge_is_recognised_as_one() {
let reply = [0xFF, 0xFF, 0xFF, 0xFF, b'A', 0x11, 0x22, 0x33, 0x44];
assert_eq!(source_engine(&reply).as_deref(), Some("challenge"));
}
#[test]
fn a_datagram_with_the_wrong_header_is_not_a_source_reply() {
assert!(source_engine(b"\xff\xff\xff\xffZ").is_none());
assert!(source_engine(b"\x00\x00\x00\x00I").is_none());
assert!(source_engine(b"\xff\xff\xff\xffItruncated").is_none());
assert!(source_engine(b"").is_none());
}
fn pong(status: &str) -> Vec<u8> {
let mut out = vec![0x1C];
out.extend_from_slice(&[0u8; 8]);
out.extend_from_slice(&[0u8; 8]);
out.extend_from_slice(&[
0x00, 0xFF, 0xFF, 0x00, 0xFE, 0xFE, 0xFE, 0xFE, 0xFD, 0xFD, 0xFD, 0xFD, 0x12, 0x34,
0x56, 0x78,
]);
out.extend_from_slice(&(status.len() as u16).to_be_bytes());
out.extend_from_slice(status.as_bytes());
out
}
const MOTD: &str = "MCPE;Dedicated Server;390;1.14.60;0;10;13253860892328930865;Bedrock level";
#[test]
fn a_pong_yields_the_status_line() {
assert_eq!(raknet_pong(&pong(MOTD)), Some(MOTD));
}
#[test]
fn a_datagram_without_the_magic_is_not_a_pong() {
let mut wrong = pong(MOTD);
wrong[18] = 0x00; assert!(raknet_pong(&wrong).is_none());
assert!(raknet_pong(b"\x1c").is_none());
assert!(raknet_pong(b"").is_none());
}
#[test]
fn a_coap_reply_yields_its_link_format_payload() {
let mut reply = vec![0x60, 0x45, 0x7a, 0x6e, 0xC1, 0x28, 0xFF];
reply.extend_from_slice(br#"</sensors/temp>;rt="temperature""#);
assert_eq!(
coap_payload(&reply),
Some(r#"</sensors/temp>;rt="temperature""#)
);
}
#[test]
fn a_coap_reply_without_a_payload_yields_nothing() {
assert!(coap_payload(&[0x60, 0x45, 0x7a, 0x6e, 0xC1, 0x28]).is_none());
assert!(coap_payload(&[0x60, 0x45, 0x7a, 0x6e, 0xFF]).is_none());
assert!(coap_payload(b"\x00\x01\x02\x03").is_none());
assert!(coap_payload(b"").is_none());
}
fn rpc_reply(accept_status: u32, body: &[u8]) -> Vec<u8> {
let mut out = Vec::new();
out.extend_from_slice(&0x7a6f6e64u32.to_be_bytes()); out.extend_from_slice(&1u32.to_be_bytes()); out.extend_from_slice(&0u32.to_be_bytes()); out.extend_from_slice(&0u32.to_be_bytes()); out.extend_from_slice(&0u32.to_be_bytes()); out.extend_from_slice(&accept_status.to_be_bytes());
out.extend_from_slice(body);
out
}
#[test]
fn a_program_dump_names_the_services_and_their_ports() {
let mut body = Vec::new();
for (program, version, protocol, port) in [
(100000u32, 2u32, 17u32, 111u32),
(100003, 3, 6, 2049),
(100005, 3, 17, 20048),
] {
body.extend_from_slice(&1u32.to_be_bytes());
for field in [program, version, protocol, port] {
body.extend_from_slice(&field.to_be_bytes());
}
}
body.extend_from_slice(&0u32.to_be_bytes());
assert_eq!(
rpc_program_dump(&rpc_reply(0, &body)).as_deref(),
Some("portmapper 2 udp 111, nfs 3 tcp 2049, mountd 3 udp 20048")
);
}
#[test]
fn an_unnamed_program_keeps_its_number() {
let mut body = 1u32.to_be_bytes().to_vec();
for field in [391_002u32, 2, 6, 39_845] {
body.extend_from_slice(&field.to_be_bytes());
}
body.extend_from_slice(&0u32.to_be_bytes());
assert_eq!(
rpc_program_dump(&rpc_reply(0, &body)).as_deref(),
Some("391002 2 tcp 39845")
);
}
#[test]
fn a_version_mismatch_yields_the_range_the_server_supports() {
let mut body = 3u32.to_be_bytes().to_vec();
body.extend_from_slice(&4u32.to_be_bytes());
assert_eq!(
rpc_version_range(&rpc_reply(2, &body)).as_deref(),
Some("versions 3-4")
);
}
#[test]
fn anything_but_a_mismatch_yields_no_range() {
assert!(rpc_version_range(&rpc_reply(0, &[])).is_none());
assert!(rpc_version_range(&rpc_reply(1, &[])).is_none());
assert!(rpc_version_range(b"").is_none());
assert!(rpc_program_dump(&rpc_reply(1, &[])).is_none());
}
#[test]
fn an_rpc_call_is_not_read_as_a_reply() {
let mut call = 0x7a6f6e64u32.to_be_bytes().to_vec();
call.extend_from_slice(&0u32.to_be_bytes()); call.extend_from_slice(&[0u8; 32]);
assert!(rpc_program_dump(&call).is_none());
let mut truncated = rpc_reply(0, &1u32.to_be_bytes());
truncated.truncate(truncated.len() - 1);
assert!(rpc_program_dump(&truncated).is_none());
}
fn ipmi(support: u8, status: u8) -> Vec<u8> {
let mut out = vec![0x06, 0x00, 0xFF, 0x07];
out.extend_from_slice(&[0u8; 9]); out.push(8); out.extend_from_slice(&[0x81, 0x1C, 0x00, 0x20, 0x00, 0x38]); out.push(0x00); out.push(0x01); out.push(support);
out.push(status);
out
}
#[test]
fn a_bmc_states_its_version_and_how_it_may_be_logged_into() {
assert_eq!(
ipmi_auth_capabilities(&ipmi(0b0000_0000, 0b0000_0011)).as_deref(),
Some("IPMI-1.5 anonymous-login null-user")
);
assert_eq!(
ipmi_auth_capabilities(&ipmi(0b1000_0000, 0b0000_0010)).as_deref(),
Some("IPMI-2.0 null-user")
);
}
#[test]
fn a_bmc_that_requires_a_real_user_says_only_what_it_speaks() {
assert_eq!(
ipmi_auth_capabilities(&ipmi(0b1000_0000, 0b0000_0100)).as_deref(),
Some("IPMI-2.0")
);
}
#[test]
fn a_refused_ipmi_command_yields_nothing() {
let mut refused = ipmi(0b1000_0000, 0b0000_0001);
refused[20] = 0xC1; assert!(ipmi_auth_capabilities(&refused).is_none());
let mut wrong_class = ipmi(0b1000_0000, 0b0000_0001);
wrong_class[3] = 0x06; assert!(ipmi_auth_capabilities(&wrong_class).is_none());
assert!(ipmi_auth_capabilities(b"").is_none());
}
fn control_response(data: &str) -> Vec<u8> {
let mut out = vec![0x16, 0x82]; out.extend_from_slice(&1u16.to_be_bytes()); out.extend_from_slice(&0u16.to_be_bytes()); out.extend_from_slice(&0u16.to_be_bytes()); out.extend_from_slice(&0u16.to_be_bytes()); out.extend_from_slice(&(data.len() as u16).to_be_bytes());
out.extend_from_slice(data.as_bytes());
out
}
#[test]
fn a_control_response_yields_the_variables_a_daemon_reports() {
const VARS: &str =
r#"version="ntpd 4.2.8p15@1.3728-o", processor="x86_64", system="Linux/6.1.0""#;
assert_eq!(
ntp_control_variables(&control_response(VARS)).as_deref(),
Some(VARS)
);
}
#[test]
fn line_breaks_are_folded_and_nothing_else_is_touched() {
let wrapped =
"version=\"ntpd 4.2.8p15\",\r\nprocessor=\"x86_64\",\r\nsystem=\"Linux/6.1.0\"";
assert_eq!(
ntp_control_variables(&control_response(wrapped)).as_deref(),
Some("version=\"ntpd 4.2.8p15\", processor=\"x86_64\", system=\"Linux/6.1.0\"")
);
}
#[test]
fn a_client_mode_reply_is_not_a_control_response() {
let mut client = vec![0x24];
client.extend_from_slice(&[0u8; 47]);
assert!(ntp_control_variables(&client).is_none());
assert!(ntp_control_variables(&[0x16, 0x02, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0]).is_none());
assert!(ntp_control_variables(b"").is_none());
}
fn binding_response(attributes: &[u8]) -> Vec<u8> {
let mut out = 0x0101u16.to_be_bytes().to_vec();
out.extend_from_slice(&(attributes.len() as u16).to_be_bytes());
out.extend_from_slice(&0x2112_A442u32.to_be_bytes());
out.extend_from_slice(b"zond-scan-01");
out.extend_from_slice(attributes);
out
}
#[test]
fn a_binding_response_yields_the_software_that_sent_it() {
let name = b"Coturn-4.5.2";
let mut attributes = 0x8022u16.to_be_bytes().to_vec();
attributes.extend_from_slice(&(name.len() as u16).to_be_bytes());
attributes.extend_from_slice(name);
assert_eq!(
stun_binding(&binding_response(&attributes)).as_deref(),
Some("Coturn-4.5.2")
);
}
#[test]
fn a_binding_response_without_software_is_still_stun() {
let mut attributes = 0x0020u16.to_be_bytes().to_vec();
attributes.extend_from_slice(&8u16.to_be_bytes());
attributes.extend_from_slice(&[0x00, 0x01, 0x2B, 0x3C, 0x5E, 0x12, 0xA4, 0x43]);
assert_eq!(
stun_binding(&binding_response(&attributes)).as_deref(),
Some("stun")
);
}
#[test]
fn a_datagram_without_the_magic_cookie_is_not_stun() {
let mut wrong = binding_response(&[]);
wrong[4] = 0x00;
assert!(stun_binding(&wrong).is_none());
assert!(stun_binding(b"").is_none());
}
fn isakmp(payloads: &[(u8, Vec<u8>)]) -> Vec<u8> {
let mut out = b"initiator".to_vec();
out.truncate(8);
out.extend_from_slice(b"responder"); out.truncate(16);
out.push(payloads.first().map_or(0, |(kind, _)| *kind));
out.extend_from_slice(&[0x10, 0x02, 0x00]); out.extend_from_slice(&0u32.to_be_bytes()); out.extend_from_slice(&0u32.to_be_bytes());
for (index, (_, body)) in payloads.iter().enumerate() {
let next = payloads.get(index + 1).map_or(0, |(kind, _)| *kind);
out.push(next);
out.push(0);
out.extend_from_slice(&((4 + body.len()) as u16).to_be_bytes());
out.extend_from_slice(body);
}
out
}
#[test]
fn a_gateway_is_named_by_the_vendor_ids_it_announces() {
let reply = isakmp(&[
(1, vec![0u8; 8]), (13, vec![0x4a, 0x13, 0x1c, 0x81, 0x07, 0x03, 0x58, 0x45]),
(13, vec![0xaf, 0xca, 0xd7, 0x13]),
]);
assert_eq!(
ike_response(&reply).as_deref(),
Some("4a131c8107035845 afcad713")
);
}
#[test]
fn a_notify_is_a_reply_rather_than_a_refusal_to_answer() {
assert_eq!(
ike_response(&isakmp(&[(11, vec![0u8; 12])])).as_deref(),
Some("notify")
);
}
#[test]
fn a_request_echoed_back_is_not_a_response() {
let mut echoed = isakmp(&[(13, vec![0xaa; 8])]);
echoed[8..16].fill(0);
assert!(ike_response(&echoed).is_none());
assert!(ike_response(b"too short").is_none());
}
#[test]
fn a_zero_length_body_is_an_acknowledgement_and_not_an_answer() {
let zlb = [0xC8u8, 0x02, 0x00, 0x0C, 0x7A, 0x6F, 0, 0, 0, 0, 0, 1];
assert!(l2tp_control(&zlb).is_none());
}
#[test]
fn a_control_message_naming_nothing_is_still_l2tp() {
let mut message = vec![0xC8u8, 0x02, 0x00, 0x14, 0x7A, 0x6F, 0, 0, 0, 0, 0, 1];
message.extend_from_slice(&[0x80, 0x08, 0, 0, 0, 0, 0, 4]);
assert_eq!(l2tp_control(&message).as_deref(), Some("l2tp"));
}
#[test]
fn arbitrary_bytes_are_refused_rather_than_read() {
for bytes in [
&b""[..],
&[0xff; 64][..],
&[0x05, 0xff, 0xff][..],
&[0x3c; 200][..],
] {
let _ = sql_server_browser(bytes);
let _ = memcached_udp(bytes);
let _ = wsd_types(bytes);
let _ = xdmcp_willing(bytes);
let _ = source_engine(bytes);
let _ = raknet_pong(bytes);
let _ = coap_payload(bytes);
let _ = rpc_program_dump(bytes);
let _ = rpc_version_range(bytes);
let _ = ipmi_auth_capabilities(bytes);
let _ = ntp_control_variables(bytes);
let _ = stun_binding(bytes);
let _ = ike_response(bytes);
let _ = kerberos_error(bytes);
let _ = l2tp_control(bytes);
}
}
}