rustnet-core 0.6.0

Network analysis library: packet parsing, protocol types, deep packet inspection, link-layer parsers, connection merging, and DNS/GeoIP/OUI lookups: the reusable core of rustnet
Documentation
use crate::network::types::{ApplicationProtocol, QuicInfo};
use log::{debug, warn};

mod bittorrent;
mod cipher_suites;
#[cfg(test)]
mod database_tests;
mod dhcp;
mod dns;
mod ftp;
mod http;
mod https;
mod llmnr;
mod mdns;
mod mqtt;
mod mysql;
mod netbios;
mod ntp;
mod openvpn;
mod postgres;
mod quic;
mod redis;
mod snmp;
mod ssdp;
mod ssh;
mod stun;
mod tls_common;
mod wireguard;

pub(crate) use cipher_suites::{format_cipher_suite, is_secure_cipher_suite};
pub(crate) use quic::try_extract_tls_from_reassembler;
pub(crate) use tls_common::is_partial_sni;
#[cfg(test)]
pub(crate) use tls_common::test_fixtures;

// Well-known port numbers used for DPI protocol detection.
const PORT_SSH: u16 = 22;
const PORT_DNS: u16 = 53;
const PORT_FTP: u16 = 21;
const PORT_DHCP_SERVER: u16 = 67;
const PORT_DHCP_CLIENT: u16 = 68;
const PORT_NTP: u16 = 123;
const PORT_NETBIOS_NS: u16 = 137;
const PORT_NETBIOS_DGM: u16 = 138;
const PORT_SNMP: u16 = 161;
const PORT_SNMP_TRAP: u16 = 162;
const PORT_HTTPS: u16 = 443;
const PORT_MQTT: u16 = 1883;
const PORT_SSDP: u16 = 1900;
const PORT_MDNS: u16 = 5353;
const PORT_STUN: u16 = 3478;
const PORT_STUN_TLS: u16 = 5349;
const PORT_LLMNR: u16 = 5355;
const PORT_OPENVPN: u16 = 1194;

/// Result of DPI analysis
#[derive(Debug, Clone)]
pub struct DpiResult {
    pub application: ApplicationProtocol,
}

/// Analyze a TCP packet payload
pub(crate) fn analyze_tcp_packet(
    payload: &[u8],
    local_port: u16,
    remote_port: u16,
    _is_outgoing: bool,
) -> Option<DpiResult> {
    if payload.is_empty() {
        return None;
    }

    let source_port = if _is_outgoing {
        local_port
    } else {
        remote_port
    };
    let destination_port = if _is_outgoing {
        remote_port
    } else {
        local_port
    };
    // Both binary decoders cap message lengths at 16 KiB. Check the zero
    // high bytes here before calling them on unrelated TCP payloads.
    if matches!(payload, [_, _, 0, ..])
        && let Some(info) = mysql::analyze_mysql(payload, destination_port == 3306)
    {
        return Some(DpiResult {
            application: ApplicationProtocol::MySql(info),
        });
    }
    if payload.starts_with(&[0, 0])
        && let Some(info) = postgres::analyze_postgres(payload)
    {
        return Some(DpiResult {
            application: ApplicationProtocol::PostgreSql(info),
        });
    }
    // RESP replies can also be arrays of bulk strings. On the standard port,
    // only inspect traffic toward the server so result values cannot become
    // command metadata.
    if payload[0] == b'*'
        && source_port != 6379
        && let Some(info) = redis::analyze_redis(payload, destination_port == 6379)
    {
        return Some(DpiResult {
            application: ApplicationProtocol::Redis(info),
        });
    }

    // Try protocols in order of likelihood/speed

    // 1. Check for HTTP (fast string matching)
    if let Some(http_result) = http::analyze_http(payload) {
        return Some(DpiResult {
            application: ApplicationProtocol::Http(http_result),
        });
    }

    // 2. Check for TLS/HTTPS (port 443 or TLS handshake)
    if (local_port == PORT_HTTPS || remote_port == PORT_HTTPS || https::is_tls_handshake(payload))
        && let Some(tls_result) = https::analyze_https(payload)
    {
        return Some(DpiResult {
            application: ApplicationProtocol::Https(tls_result),
        });
    }

    // 3. Check for BitTorrent (handshake signature \x13BitTorrent protocol)
    if bittorrent::is_bittorrent_handshake(payload)
        && let Some(bt_result) = bittorrent::analyze_bittorrent(payload)
    {
        return Some(DpiResult {
            application: ApplicationProtocol::BitTorrent(bt_result),
        });
    }

    // 4. Check for MQTT (port 1883 or MQTT signature)
    if (local_port == PORT_MQTT || remote_port == PORT_MQTT || mqtt::is_mqtt_packet(payload))
        && let Some(mqtt_result) = mqtt::analyze_mqtt(payload)
    {
        return Some(DpiResult {
            application: ApplicationProtocol::Mqtt(mqtt_result),
        });
    }

    // 5. Check for SSH (port 22 or SSH banner)
    if (local_port == PORT_SSH || remote_port == PORT_SSH || ssh::is_likely_ssh(payload))
        && let Some(ssh_result) = ssh::analyze_ssh(payload, _is_outgoing)
    {
        return Some(DpiResult {
            application: ApplicationProtocol::Ssh(ssh_result),
        });
    }

    // 6. Check for FTP control channel (port 21 plaintext / AUTH TLS upgrade,
    //    or signature). Off port 21 only distinctively-FTP commands count as
    //    a signature; 3-digit reply lines are shared with SMTP/POP3/NNTP and
    //    are only classified on port 21.
    //
    //    Implicit FTPS on port 990 is intentionally NOT routed here: that
    //    flow is TLS from the very first byte and falls through to the
    //    HTTPS/TLS branch. AUTH TLS on port 21 is captured via the `AUTH`
    //    command in the plaintext control channel before the upgrade.
    if (local_port == PORT_FTP || remote_port == PORT_FTP || ftp::is_ftp(payload))
        && let Some(ftp_result) = ftp::analyze_ftp(payload)
    {
        return Some(DpiResult {
            application: ApplicationProtocol::Ftp(ftp_result),
        });
    }

    // 7. OpenVPN over TCP uses a two-byte length prefix. On its registered
    // port we accept all current packet opcodes; elsewhere the analyzer only
    // accepts a distinctive hard-reset exchange.
    if let Some(openvpn_result) = openvpn::analyze_openvpn_tcp(
        payload,
        local_port == PORT_OPENVPN || remote_port == PORT_OPENVPN,
    ) {
        return Some(DpiResult {
            application: ApplicationProtocol::OpenVpn(openvpn_result),
        });
    }

    // More protocols here...

    None
}

/// Analyze a UDP packet payload
pub(crate) fn analyze_udp_packet(
    payload: &[u8],
    local_port: u16,
    remote_port: u16,
    _is_outgoing: bool,
) -> Option<DpiResult> {
    if payload.is_empty() {
        return None;
    }

    // 1. DNS (port 53)
    if (local_port == PORT_DNS || remote_port == PORT_DNS)
        && let Some(dns_result) = dns::analyze_dns(payload)
    {
        return Some(DpiResult {
            application: ApplicationProtocol::Dns(dns_result),
        });
    }

    // 2. QUIC/HTTP3 (port 443)
    if (local_port == PORT_HTTPS || remote_port == PORT_HTTPS) && quic::is_quic_packet(payload) {
        let quic_info = quic::parse_quic_packet(payload);
        if let Some(quic_info) = quic_info {
            debug!("QUIC packet detected: {:?}", quic_info);
            return Some(DpiResult {
                application: ApplicationProtocol::Quic(Box::new(quic_info)),
            });
        } else {
            warn!("Failed to parse QUIC packet");
            let empty_quic_info = QuicInfo::new(0);

            return Some(DpiResult {
                application: ApplicationProtocol::Quic(Box::new(empty_quic_info)),
            });
        }
    }

    // 3. mDNS (port 5353)
    if (local_port == PORT_MDNS || remote_port == PORT_MDNS)
        && let Some(mdns_result) = mdns::analyze_mdns(payload)
    {
        return Some(DpiResult {
            application: ApplicationProtocol::Mdns(mdns_result),
        });
    }

    // 4. DHCP (ports 67-68)
    if matches!(
        (local_port, remote_port),
        (PORT_DHCP_SERVER, _)
            | (PORT_DHCP_CLIENT, _)
            | (_, PORT_DHCP_SERVER)
            | (_, PORT_DHCP_CLIENT)
    ) && let Some(dhcp_result) = dhcp::analyze_dhcp(payload)
    {
        return Some(DpiResult {
            application: ApplicationProtocol::Dhcp(dhcp_result),
        });
    }

    // 5. NTP (port 123)
    if (local_port == PORT_NTP || remote_port == PORT_NTP)
        && let Some(ntp_result) = ntp::analyze_ntp(payload)
    {
        return Some(DpiResult {
            application: ApplicationProtocol::Ntp(ntp_result),
        });
    }

    // 6. LLMNR (port 5355)
    if (local_port == PORT_LLMNR || remote_port == PORT_LLMNR)
        && let Some(llmnr_result) = llmnr::analyze_llmnr(payload)
    {
        return Some(DpiResult {
            application: ApplicationProtocol::Llmnr(llmnr_result),
        });
    }

    // 7. SSDP (port 1900)
    if (local_port == PORT_SSDP || remote_port == PORT_SSDP)
        && let Some(ssdp_result) = ssdp::analyze_ssdp(payload)
    {
        return Some(DpiResult {
            application: ApplicationProtocol::Ssdp(ssdp_result),
        });
    }

    // 8. NetBIOS-NS (port 137)
    if (local_port == PORT_NETBIOS_NS || remote_port == PORT_NETBIOS_NS)
        && let Some(netbios_result) = netbios::analyze_netbios_ns(payload)
    {
        return Some(DpiResult {
            application: ApplicationProtocol::NetBios(netbios_result),
        });
    }

    // 9. NetBIOS-DGM (port 138)
    if (local_port == PORT_NETBIOS_DGM || remote_port == PORT_NETBIOS_DGM)
        && let Some(netbios_result) = netbios::analyze_netbios_dgm(payload)
    {
        return Some(DpiResult {
            application: ApplicationProtocol::NetBios(netbios_result),
        });
    }

    // 10. SNMP (ports 161-162)
    if matches!(
        (local_port, remote_port),
        (PORT_SNMP, _) | (PORT_SNMP_TRAP, _) | (_, PORT_SNMP) | (_, PORT_SNMP_TRAP)
    ) && let Some(snmp_result) = snmp::analyze_snmp(payload)
    {
        return Some(DpiResult {
            application: ApplicationProtocol::Snmp(snmp_result),
        });
    }

    // 11. STUN (port 3478/5349 or magic cookie detection for non-standard ports)
    if (local_port == PORT_STUN
        || remote_port == PORT_STUN
        || local_port == PORT_STUN_TLS
        || remote_port == PORT_STUN_TLS
        || stun::is_likely_stun(payload))
        && let Some(stun_result) = stun::analyze_stun(payload)
    {
        return Some(DpiResult {
            application: ApplicationProtocol::Stun(stun_result),
        });
    }

    // 12. WireGuard (fixed message types, reserved bytes, and lengths)
    if let Some(wireguard_result) = wireguard::analyze_wireguard(payload) {
        return Some(DpiResult {
            application: ApplicationProtocol::WireGuard(wireguard_result),
        });
    }

    // 13. OpenVPN. The registered port permits all structurally plausible
    // opcodes; alternate ports require a distinctive hard-reset exchange.
    if let Some(openvpn_result) = openvpn::analyze_openvpn_udp(
        payload,
        local_port == PORT_OPENVPN || remote_port == PORT_OPENVPN,
    ) {
        return Some(DpiResult {
            application: ApplicationProtocol::OpenVpn(openvpn_result),
        });
    }

    // 14. BitTorrent DHT / uTP (no port gating, signature-based)
    if let Some(bt_result) = bittorrent::analyze_udp_bittorrent(payload) {
        return Some(DpiResult {
            application: ApplicationProtocol::BitTorrent(bt_result),
        });
    }

    None
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::network::types::{OpenVpnPacketType, WireGuardPacketType};

    #[test]
    fn dispatches_wireguard_before_bittorrent() {
        let mut payload = vec![0x5a; 148];
        payload[..4].copy_from_slice(&[1, 0, 0, 0]);

        let result = analyze_udp_packet(&payload, 50_000, 51_820, true).unwrap();
        let ApplicationProtocol::WireGuard(info) = result.application else {
            panic!("expected WireGuard classification");
        };
        assert_eq!(info.packet_type, WireGuardPacketType::HandshakeInitiation);
    }

    #[test]
    fn dispatches_openvpn_udp_on_registered_port() {
        let mut payload = vec![0x5a; 20];
        payload[0] = 9 << 3;

        let result = analyze_udp_packet(&payload, 50_000, PORT_OPENVPN, true).unwrap();
        let ApplicationProtocol::OpenVpn(info) = result.application else {
            panic!("expected OpenVPN classification");
        };
        assert_eq!(info.packet_type, OpenVpnPacketType::DataV2);
    }

    #[test]
    fn dispatches_openvpn_tcp_frame() {
        let mut packet = vec![0x5a; 14];
        packet[0] = 7 << 3;
        packet[9..].fill(0);
        let mut frame = Vec::with_capacity(16);
        frame.extend_from_slice(&14u16.to_be_bytes());
        frame.extend_from_slice(&packet);

        let result = analyze_tcp_packet(&frame, 50_000, PORT_OPENVPN, true).unwrap();
        assert!(matches!(
            result.application,
            ApplicationProtocol::OpenVpn(_)
        ));
    }

    #[test]
    fn registered_port_alone_does_not_classify_random_udp() {
        assert!(analyze_udp_packet(b"not an OpenVPN packet", 50_000, PORT_OPENVPN, true).is_none());
    }
}