summaryrefslogtreecommitdiffstats
path: root/rust/src/dns
diff options
context:
space:
mode:
authorDaniel Baumann <daniel.baumann@progress-linux.org>2024-04-19 17:39:49 +0000
committerDaniel Baumann <daniel.baumann@progress-linux.org>2024-04-19 17:39:49 +0000
commita0aa2307322cd47bbf416810ac0292925e03be87 (patch)
tree37076262a026c4b48c8a0e84f44ff9187556ca35 /rust/src/dns
parentInitial commit. (diff)
downloadsuricata-a0aa2307322cd47bbf416810ac0292925e03be87.tar.xz
suricata-a0aa2307322cd47bbf416810ac0292925e03be87.zip
Adding upstream version 1:7.0.3.upstream/1%7.0.3
Signed-off-by: Daniel Baumann <daniel.baumann@progress-linux.org>
Diffstat (limited to 'rust/src/dns')
-rw-r--r--rust/src/dns/detect.rs199
-rw-r--r--rust/src/dns/dns.rs1526
-rw-r--r--rust/src/dns/log.rs671
-rw-r--r--rust/src/dns/lua.rs234
-rw-r--r--rust/src/dns/mod.rs26
-rw-r--r--rust/src/dns/parser.rs851
6 files changed, 3507 insertions, 0 deletions
diff --git a/rust/src/dns/detect.rs b/rust/src/dns/detect.rs
new file mode 100644
index 0000000..268a409
--- /dev/null
+++ b/rust/src/dns/detect.rs
@@ -0,0 +1,199 @@
+/* Copyright (C) 2019 Open Information Security Foundation
+ *
+ * You can copy, redistribute or modify this Program under the terms of
+ * the GNU General Public License version 2 as published by the Free
+ * Software Foundation.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * version 2 along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301, USA.
+ */
+
+use super::dns::DNSTransaction;
+use crate::core::*;
+use std::ffi::CStr;
+use std::os::raw::{c_char, c_void};
+
+#[derive(Debug, PartialEq, Eq)]
+pub struct DetectDnsOpcode {
+ negate: bool,
+ opcode: u8,
+}
+
+/// Parse a DNS opcode argument returning the code and if it is to be
+/// negated or not.
+///
+/// For now only an indication that an error occurred is returned, not
+/// the details of the error.
+fn parse_opcode(opcode: &str) -> Result<DetectDnsOpcode, ()> {
+ let mut negated = false;
+ for (i, c) in opcode.chars().enumerate() {
+ match c {
+ ' ' | '\t' => {
+ continue;
+ }
+ '!' => {
+ negated = true;
+ }
+ _ => {
+ let code: u8 = opcode[i..].parse().map_err(|_| ())?;
+ return Ok(DetectDnsOpcode {
+ negate: negated,
+ opcode: code,
+ });
+ }
+ }
+ }
+ Err(())
+}
+
+/// Perform the DNS opcode match.
+///
+/// 1 will be returned on match, otherwise 0 will be returned.
+#[no_mangle]
+pub extern "C" fn rs_dns_opcode_match(
+ tx: &mut DNSTransaction, detect: &mut DetectDnsOpcode, flags: u8,
+) -> u8 {
+ let header_flags = if flags & Direction::ToServer as u8 != 0 {
+ if let Some(request) = &tx.request {
+ request.header.flags
+ } else {
+ return 0;
+ }
+ } else if flags & Direction::ToClient as u8 != 0 {
+ if let Some(response) = &tx.response {
+ response.header.flags
+ } else {
+ return 0;
+ }
+ } else {
+ // Not to server or to client??
+ return 0;
+ };
+
+ match_opcode(detect, header_flags).into()
+}
+
+fn match_opcode(detect: &DetectDnsOpcode, flags: u16) -> bool {
+ let opcode = ((flags >> 11) & 0xf) as u8;
+ if detect.negate {
+ detect.opcode != opcode
+ } else {
+ detect.opcode == opcode
+ }
+}
+
+#[no_mangle]
+pub unsafe extern "C" fn rs_detect_dns_opcode_parse(carg: *const c_char) -> *mut c_void {
+ if carg.is_null() {
+ return std::ptr::null_mut();
+ }
+ let arg = match CStr::from_ptr(carg).to_str() {
+ Ok(arg) => arg,
+ _ => {
+ return std::ptr::null_mut();
+ }
+ };
+
+ match parse_opcode(arg) {
+ Ok(detect) => Box::into_raw(Box::new(detect)) as *mut _,
+ Err(_) => std::ptr::null_mut(),
+ }
+}
+
+#[no_mangle]
+pub unsafe extern "C" fn rs_dns_detect_opcode_free(ptr: *mut c_void) {
+ if !ptr.is_null() {
+ std::mem::drop(Box::from_raw(ptr as *mut DetectDnsOpcode));
+ }
+}
+
+#[cfg(test)]
+mod test {
+ use super::*;
+
+ #[test]
+ fn parse_opcode_good() {
+ assert_eq!(
+ parse_opcode("1"),
+ Ok(DetectDnsOpcode {
+ negate: false,
+ opcode: 1
+ })
+ );
+ assert_eq!(
+ parse_opcode("123"),
+ Ok(DetectDnsOpcode {
+ negate: false,
+ opcode: 123
+ })
+ );
+ assert_eq!(
+ parse_opcode("!123"),
+ Ok(DetectDnsOpcode {
+ negate: true,
+ opcode: 123
+ })
+ );
+ assert_eq!(
+ parse_opcode("!123"),
+ Ok(DetectDnsOpcode {
+ negate: true,
+ opcode: 123
+ })
+ );
+ assert_eq!(parse_opcode(""), Err(()));
+ assert_eq!(parse_opcode("!"), Err(()));
+ assert_eq!(parse_opcode("! "), Err(()));
+ assert_eq!(parse_opcode("!asdf"), Err(()));
+ }
+
+ #[test]
+ fn test_match_opcode() {
+ assert!(
+ match_opcode(
+ &DetectDnsOpcode {
+ negate: false,
+ opcode: 0,
+ },
+ 0b0000_0000_0000_0000,
+ )
+ );
+
+ assert!(
+ !match_opcode(
+ &DetectDnsOpcode {
+ negate: true,
+ opcode: 0,
+ },
+ 0b0000_0000_0000_0000,
+ )
+ );
+
+ assert!(
+ match_opcode(
+ &DetectDnsOpcode {
+ negate: false,
+ opcode: 4,
+ },
+ 0b0010_0000_0000_0000,
+ )
+ );
+
+ assert!(
+ !match_opcode(
+ &DetectDnsOpcode {
+ negate: true,
+ opcode: 4,
+ },
+ 0b0010_0000_0000_0000,
+ )
+ );
+ }
+}
diff --git a/rust/src/dns/dns.rs b/rust/src/dns/dns.rs
new file mode 100644
index 0000000..382c76a
--- /dev/null
+++ b/rust/src/dns/dns.rs
@@ -0,0 +1,1526 @@
+/* Copyright (C) 2017-2022 Open Information Security Foundation
+ *
+ * You can copy, redistribute or modify this Program under the terms of
+ * the GNU General Public License version 2 as published by the Free
+ * Software Foundation.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * version 2 along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301, USA.
+ */
+
+use std;
+use std::collections::HashMap;
+use std::collections::VecDeque;
+use std::ffi::CString;
+
+use crate::applayer::*;
+use crate::core::{self, *};
+use crate::dns::parser;
+use crate::frames::Frame;
+
+use nom7::number::streaming::be_u16;
+use nom7::{Err, IResult};
+
+/// DNS record types.
+pub const DNS_RECORD_TYPE_A: u16 = 1;
+pub const DNS_RECORD_TYPE_NS: u16 = 2;
+pub const DNS_RECORD_TYPE_MD: u16 = 3; // Obsolete
+pub const DNS_RECORD_TYPE_MF: u16 = 4; // Obsolete
+pub const DNS_RECORD_TYPE_CNAME: u16 = 5;
+pub const DNS_RECORD_TYPE_SOA: u16 = 6;
+pub const DNS_RECORD_TYPE_MB: u16 = 7; // Experimental
+pub const DNS_RECORD_TYPE_MG: u16 = 8; // Experimental
+pub const DNS_RECORD_TYPE_MR: u16 = 9; // Experimental
+pub const DNS_RECORD_TYPE_NULL: u16 = 10; // Experimental
+pub const DNS_RECORD_TYPE_WKS: u16 = 11;
+pub const DNS_RECORD_TYPE_PTR: u16 = 12;
+pub const DNS_RECORD_TYPE_HINFO: u16 = 13;
+pub const DNS_RECORD_TYPE_MINFO: u16 = 14;
+pub const DNS_RECORD_TYPE_MX: u16 = 15;
+pub const DNS_RECORD_TYPE_TXT: u16 = 16;
+pub const DNS_RECORD_TYPE_RP: u16 = 17;
+pub const DNS_RECORD_TYPE_AFSDB: u16 = 18;
+pub const DNS_RECORD_TYPE_X25: u16 = 19;
+pub const DNS_RECORD_TYPE_ISDN: u16 = 20;
+pub const DNS_RECORD_TYPE_RT: u16 = 21;
+pub const DNS_RECORD_TYPE_NSAP: u16 = 22;
+pub const DNS_RECORD_TYPE_NSAPPTR: u16 = 23;
+pub const DNS_RECORD_TYPE_SIG: u16 = 24;
+pub const DNS_RECORD_TYPE_KEY: u16 = 25;
+pub const DNS_RECORD_TYPE_PX: u16 = 26;
+pub const DNS_RECORD_TYPE_GPOS: u16 = 27;
+pub const DNS_RECORD_TYPE_AAAA: u16 = 28;
+pub const DNS_RECORD_TYPE_LOC: u16 = 29;
+pub const DNS_RECORD_TYPE_NXT: u16 = 30; // Obsolete
+pub const DNS_RECORD_TYPE_SRV: u16 = 33;
+pub const DNS_RECORD_TYPE_ATMA: u16 = 34;
+pub const DNS_RECORD_TYPE_NAPTR: u16 = 35;
+pub const DNS_RECORD_TYPE_KX: u16 = 36;
+pub const DNS_RECORD_TYPE_CERT: u16 = 37;
+pub const DNS_RECORD_TYPE_A6: u16 = 38; // Obsolete
+pub const DNS_RECORD_TYPE_DNAME: u16 = 39;
+pub const DNS_RECORD_TYPE_OPT: u16 = 41;
+pub const DNS_RECORD_TYPE_APL: u16 = 42;
+pub const DNS_RECORD_TYPE_DS: u16 = 43;
+pub const DNS_RECORD_TYPE_SSHFP: u16 = 44;
+pub const DNS_RECORD_TYPE_IPSECKEY: u16 = 45;
+pub const DNS_RECORD_TYPE_RRSIG: u16 = 46;
+pub const DNS_RECORD_TYPE_NSEC: u16 = 47;
+pub const DNS_RECORD_TYPE_DNSKEY: u16 = 48;
+pub const DNS_RECORD_TYPE_DHCID: u16 = 49;
+pub const DNS_RECORD_TYPE_NSEC3: u16 = 50;
+pub const DNS_RECORD_TYPE_NSEC3PARAM: u16 = 51;
+pub const DNS_RECORD_TYPE_TLSA: u16 = 52;
+pub const DNS_RECORD_TYPE_HIP: u16 = 55;
+pub const DNS_RECORD_TYPE_CDS: u16 = 59;
+pub const DNS_RECORD_TYPE_CDNSKEY: u16 = 60;
+pub const DNS_RECORD_TYPE_HTTPS: u16 = 65;
+pub const DNS_RECORD_TYPE_SPF: u16 = 99; // Obsolete
+pub const DNS_RECORD_TYPE_TKEY: u16 = 249;
+pub const DNS_RECORD_TYPE_TSIG: u16 = 250;
+pub const DNS_RECORD_TYPE_MAILA: u16 = 254; // Obsolete
+pub const DNS_RECORD_TYPE_ANY: u16 = 255;
+pub const DNS_RECORD_TYPE_URI: u16 = 256;
+
+/// DNS error codes.
+pub const DNS_RCODE_NOERROR: u16 = 0;
+pub const DNS_RCODE_FORMERR: u16 = 1;
+pub const DNS_RCODE_SERVFAIL: u16 = 2;
+pub const DNS_RCODE_NXDOMAIN: u16 = 3;
+pub const DNS_RCODE_NOTIMP: u16 = 4;
+pub const DNS_RCODE_REFUSED: u16 = 5;
+pub const DNS_RCODE_YXDOMAIN: u16 = 6;
+pub const DNS_RCODE_YXRRSET: u16 = 7;
+pub const DNS_RCODE_NXRRSET: u16 = 8;
+pub const DNS_RCODE_NOTAUTH: u16 = 9;
+pub const DNS_RCODE_NOTZONE: u16 = 10;
+// Support for OPT RR from RFC6891 will be needed to
+// parse RCODE values over 15
+pub const DNS_RCODE_BADVERS: u16 = 16;
+//also pub const DNS_RCODE_BADSIG: u16 = 16;
+pub const DNS_RCODE_BADKEY: u16 = 17;
+pub const DNS_RCODE_BADTIME: u16 = 18;
+pub const DNS_RCODE_BADMODE: u16 = 19;
+pub const DNS_RCODE_BADNAME: u16 = 20;
+pub const DNS_RCODE_BADALG: u16 = 21;
+pub const DNS_RCODE_BADTRUNC: u16 = 22;
+
+static mut ALPROTO_DNS: AppProto = ALPROTO_UNKNOWN;
+
+#[derive(AppLayerFrameType)]
+pub enum DnsFrameType {
+ /// DNS PDU frame. For UDP DNS this is the complete UDP payload, for TCP
+ /// this is the DNS payload not including the leading length field allowing
+ /// this frame to be used for UDP and TCP DNS.
+ Pdu,
+}
+
+#[derive(Debug, PartialEq, Eq, AppLayerEvent)]
+pub enum DNSEvent {
+ MalformedData,
+ NotRequest,
+ NotResponse,
+ ZFlagSet,
+ InvalidOpcode,
+}
+
+#[derive(Debug, PartialEq, Eq)]
+#[repr(C)]
+pub struct DNSHeader {
+ pub tx_id: u16,
+ pub flags: u16,
+ pub questions: u16,
+ pub answer_rr: u16,
+ pub authority_rr: u16,
+ pub additional_rr: u16,
+}
+
+#[derive(Debug)]
+pub struct DNSQueryEntry {
+ pub name: Vec<u8>,
+ pub rrtype: u16,
+ pub rrclass: u16,
+}
+
+#[derive(Debug, PartialEq, Eq)]
+pub struct DNSRDataSOA {
+ /// Primary name server for this zone
+ pub mname: Vec<u8>,
+ /// Authority's mailbox
+ pub rname: Vec<u8>,
+ /// Serial version number
+ pub serial: u32,
+ /// Refresh interval (seconds)
+ pub refresh: u32,
+ /// Retry interval (seconds)
+ pub retry: u32,
+ /// Upper time limit until zone is no longer authoritative (seconds)
+ pub expire: u32,
+ /// Minimum ttl for records in this zone (seconds)
+ pub minimum: u32,
+}
+
+#[derive(Debug, PartialEq, Eq)]
+pub struct DNSRDataSSHFP {
+ /// Algorithm number
+ pub algo: u8,
+ /// Fingerprint type
+ pub fp_type: u8,
+ /// Fingerprint
+ pub fingerprint: Vec<u8>,
+}
+
+#[derive(Debug, PartialEq, Eq)]
+pub struct DNSRDataSRV {
+ /// Priority
+ pub priority: u16,
+ /// Weight
+ pub weight: u16,
+ /// Port
+ pub port: u16,
+ /// Target
+ pub target: Vec<u8>,
+}
+
+/// Represents RData of various formats
+#[derive(Debug, PartialEq, Eq)]
+pub enum DNSRData {
+ // RData is an address
+ A(Vec<u8>),
+ AAAA(Vec<u8>),
+ // RData is a domain name
+ CNAME(Vec<u8>),
+ PTR(Vec<u8>),
+ MX(Vec<u8>),
+ NS(Vec<u8>),
+ // RData is text
+ TXT(Vec<u8>),
+ NULL(Vec<u8>),
+ // RData has several fields
+ SOA(DNSRDataSOA),
+ SRV(DNSRDataSRV),
+ SSHFP(DNSRDataSSHFP),
+ // RData for remaining types is sometimes ignored
+ Unknown(Vec<u8>),
+}
+
+#[derive(Debug, PartialEq, Eq)]
+pub struct DNSAnswerEntry {
+ pub name: Vec<u8>,
+ pub rrtype: u16,
+ pub rrclass: u16,
+ pub ttl: u32,
+ pub data: DNSRData,
+}
+
+#[derive(Debug)]
+pub struct DNSRequest {
+ pub header: DNSHeader,
+ pub queries: Vec<DNSQueryEntry>,
+}
+
+#[derive(Debug)]
+pub struct DNSResponse {
+ pub header: DNSHeader,
+ pub queries: Vec<DNSQueryEntry>,
+ pub answers: Vec<DNSAnswerEntry>,
+ pub authorities: Vec<DNSAnswerEntry>,
+}
+
+#[derive(Debug, Default)]
+pub struct DNSTransaction {
+ pub id: u64,
+ pub request: Option<DNSRequest>,
+ pub response: Option<DNSResponse>,
+ pub tx_data: AppLayerTxData,
+}
+
+impl Transaction for DNSTransaction {
+ fn id(&self) -> u64 {
+ self.id
+ }
+}
+
+impl DNSTransaction {
+ pub fn new(direction: Direction) -> Self {
+ Self {
+ tx_data: AppLayerTxData::for_direction(direction),
+ ..Default::default()
+ }
+ }
+
+ /// Get the DNS transactions ID (not the internal tracking ID).
+ pub fn tx_id(&self) -> u16 {
+ if let Some(request) = &self.request {
+ return request.header.tx_id;
+ }
+ if let Some(response) = &self.response {
+ return response.header.tx_id;
+ }
+
+ // Shouldn't happen.
+ return 0;
+ }
+
+ /// Get the reply code of the transaction. Note that this will
+ /// also return 0 if there is no reply.
+ pub fn rcode(&self) -> u16 {
+ if let Some(response) = &self.response {
+ return response.header.flags & 0x000f;
+ }
+ return 0;
+ }
+}
+
+struct ConfigTracker {
+ map: HashMap<u16, AppLayerTxConfig>,
+ queue: VecDeque<u16>,
+}
+
+impl ConfigTracker {
+ fn new() -> ConfigTracker {
+ ConfigTracker {
+ map: HashMap::new(),
+ queue: VecDeque::new(),
+ }
+ }
+
+ fn add(&mut self, id: u16, config: AppLayerTxConfig) {
+ // If at size limit, remove the oldest entry.
+ if self.queue.len() > 499 {
+ if let Some(id) = self.queue.pop_front() {
+ self.map.remove(&id);
+ }
+ }
+
+ self.map.insert(id, config);
+ self.queue.push_back(id);
+ }
+
+ fn remove(&mut self, id: &u16) -> Option<AppLayerTxConfig> {
+ self.map.remove(id)
+ }
+}
+
+#[derive(Default)]
+pub struct DNSState {
+ state_data: AppLayerStateData,
+
+ // Internal transaction ID.
+ pub tx_id: u64,
+
+ // Transactions.
+ pub transactions: VecDeque<DNSTransaction>,
+
+ config: Option<ConfigTracker>,
+
+ gap: bool,
+}
+
+impl State<DNSTransaction> for DNSState {
+ fn get_transaction_count(&self) -> usize {
+ self.transactions.len()
+ }
+
+ fn get_transaction_by_index(&self, index: usize) -> Option<&DNSTransaction> {
+ self.transactions.get(index)
+ }
+}
+
+impl DNSState {
+ pub fn new() -> Self {
+ Default::default()
+ }
+
+ pub fn new_tx(&mut self, direction: Direction) -> DNSTransaction {
+ let mut tx = DNSTransaction::new(direction);
+ self.tx_id += 1;
+ tx.id = self.tx_id;
+ return tx;
+ }
+
+ pub fn free_tx(&mut self, tx_id: u64) {
+ let len = self.transactions.len();
+ let mut found = false;
+ let mut index = 0;
+ for i in 0..len {
+ let tx = &self.transactions[i];
+ if tx.id == tx_id + 1 {
+ found = true;
+ index = i;
+ break;
+ }
+ }
+ if found {
+ self.transactions.remove(index);
+ }
+ }
+
+ pub fn get_tx(&mut self, tx_id: u64) -> Option<&DNSTransaction> {
+ SCLogDebug!("get_tx: tx_id={}", tx_id);
+ for tx in &mut self.transactions {
+ if tx.id == tx_id + 1 {
+ SCLogDebug!("Found DNS TX with ID {}", tx_id);
+ return Some(tx);
+ }
+ }
+ SCLogDebug!("Failed to find DNS TX with ID {}", tx_id);
+ return None;
+ }
+
+ /// Set an event. The event is set on the most recent transaction.
+ pub fn set_event(&mut self, event: DNSEvent) {
+ let len = self.transactions.len();
+ if len == 0 {
+ return;
+ }
+
+ let tx = &mut self.transactions[len - 1];
+ tx.tx_data.set_event(event as u8);
+ }
+
+ fn validate_header<'a>(&self, input: &'a [u8]) -> Option<(&'a [u8], DNSHeader)> {
+ if let Ok((body, header)) = parser::dns_parse_header(input) {
+ if probe_header_validity(&header, input.len()).0 {
+ return Some((body, header));
+ }
+ }
+ None
+ }
+
+ fn parse_request(&mut self, input: &[u8], is_tcp: bool) -> bool {
+ let (body, header) = if let Some((body, header)) = self.validate_header(input) {
+ (body, header)
+ } else {
+ return !is_tcp;
+ };
+
+ match parser::dns_parse_request_body(body, input, header) {
+ Ok((_, request)) => {
+ if request.header.flags & 0x8000 != 0 {
+ SCLogDebug!("DNS message is not a request");
+ self.set_event(DNSEvent::NotRequest);
+ return false;
+ }
+
+ let z_flag = request.header.flags & 0x0040 != 0;
+ let opcode = ((request.header.flags >> 11) & 0xf) as u8;
+
+ let mut tx = self.new_tx(Direction::ToServer);
+ tx.request = Some(request);
+ self.transactions.push_back(tx);
+
+ if z_flag {
+ SCLogDebug!("Z-flag set on DNS response");
+ self.set_event(DNSEvent::ZFlagSet);
+ }
+
+ if opcode >= 7 {
+ self.set_event(DNSEvent::InvalidOpcode);
+ }
+
+ return true;
+ }
+ Err(Err::Incomplete(_)) => {
+ // Insufficient data.
+ SCLogDebug!("Insufficient data while parsing DNS request");
+ self.set_event(DNSEvent::MalformedData);
+ return false;
+ }
+ Err(_) => {
+ // Error, probably malformed data.
+ SCLogDebug!("An error occurred while parsing DNS request");
+ self.set_event(DNSEvent::MalformedData);
+ return false;
+ }
+ }
+ }
+
+ fn parse_request_udp(&mut self, flow: *const core::Flow, stream_slice: StreamSlice) -> bool {
+ let input = stream_slice.as_slice();
+ let _pdu = Frame::new(
+ flow,
+ &stream_slice,
+ input,
+ input.len() as i64,
+ DnsFrameType::Pdu as u8,
+ );
+ self.parse_request(input, false)
+ }
+
+ fn parse_response_udp(&mut self, flow: *const core::Flow, stream_slice: StreamSlice) -> bool {
+ let input = stream_slice.as_slice();
+ let _pdu = Frame::new(
+ flow,
+ &stream_slice,
+ input,
+ input.len() as i64,
+ DnsFrameType::Pdu as u8,
+ );
+ self.parse_response(input, false)
+ }
+
+ pub fn parse_response(&mut self, input: &[u8], is_tcp: bool) -> bool {
+ let (body, header) = if let Some((body, header)) = self.validate_header(input) {
+ (body, header)
+ } else {
+ return !is_tcp;
+ };
+
+ match parser::dns_parse_response_body(body, input, header) {
+ Ok((_, response)) => {
+ SCLogDebug!("Response header flags: {}", response.header.flags);
+
+ if response.header.flags & 0x8000 == 0 {
+ SCLogDebug!("DNS message is not a response");
+ self.set_event(DNSEvent::NotResponse);
+ }
+
+ let z_flag = response.header.flags & 0x0040 != 0;
+ let opcode = ((response.header.flags >> 11) & 0xf) as u8;
+
+ let mut tx = self.new_tx(Direction::ToClient);
+ if let Some(ref mut config) = &mut self.config {
+ if let Some(config) = config.remove(&response.header.tx_id) {
+ tx.tx_data.config = config;
+ }
+ }
+ tx.response = Some(response);
+ self.transactions.push_back(tx);
+
+ if z_flag {
+ SCLogDebug!("Z-flag set on DNS response");
+ self.set_event(DNSEvent::ZFlagSet);
+ }
+
+ if opcode >= 7 {
+ self.set_event(DNSEvent::InvalidOpcode);
+ }
+
+ return true;
+ }
+ Err(Err::Incomplete(_)) => {
+ // Insufficient data.
+ SCLogDebug!("Insufficient data while parsing DNS response");
+ self.set_event(DNSEvent::MalformedData);
+ return false;
+ }
+ Err(_) => {
+ // Error, probably malformed data.
+ SCLogDebug!("An error occurred while parsing DNS response");
+ self.set_event(DNSEvent::MalformedData);
+ return false;
+ }
+ }
+ }
+
+ /// TCP variation of response request parser to handle the length
+ /// prefix.
+ ///
+ /// Returns the number of messages parsed.
+ pub fn parse_request_tcp(
+ &mut self, flow: *const core::Flow, stream_slice: StreamSlice,
+ ) -> AppLayerResult {
+ let input = stream_slice.as_slice();
+ if self.gap {
+ let (is_dns, _, is_incomplete) = probe_tcp(input);
+ if is_dns || is_incomplete {
+ self.gap = false;
+ } else {
+ AppLayerResult::ok();
+ }
+ }
+
+ let mut cur_i = input;
+ let mut consumed = 0;
+ while !cur_i.is_empty() {
+ if cur_i.len() == 1 {
+ return AppLayerResult::incomplete(consumed as u32, 2_u32);
+ }
+ let size = match be_u16(cur_i) as IResult<&[u8], u16> {
+ Ok((_, len)) => len,
+ _ => 0,
+ } as usize;
+ SCLogDebug!(
+ "[request] Have {} bytes, need {} to parse",
+ cur_i.len(),
+ size + 2
+ );
+ if size > 0 && cur_i.len() >= size + 2 {
+ let msg = &cur_i[2..(size + 2)];
+ let _pdu = Frame::new(
+ flow,
+ &stream_slice,
+ msg,
+ msg.len() as i64,
+ DnsFrameType::Pdu as u8,
+ );
+ if self.parse_request(msg, true) {
+ cur_i = &cur_i[(size + 2)..];
+ consumed += size + 2;
+ } else {
+ return AppLayerResult::err();
+ }
+ } else if size == 0 {
+ cur_i = &cur_i[2..];
+ consumed += 2;
+ } else {
+ SCLogDebug!(
+ "[request]Not enough DNS traffic to parse. Returning {}/{}",
+ consumed as u32,
+ (size + 2) as u32
+ );
+ return AppLayerResult::incomplete(consumed as u32, (size + 2) as u32);
+ }
+ }
+ AppLayerResult::ok()
+ }
+
+ /// TCP variation of the response parser to handle the length
+ /// prefix.
+ ///
+ /// Returns the number of messages parsed.
+ pub fn parse_response_tcp(
+ &mut self, flow: *const core::Flow, stream_slice: StreamSlice,
+ ) -> AppLayerResult {
+ let input = stream_slice.as_slice();
+ if self.gap {
+ let (is_dns, _, is_incomplete) = probe_tcp(input);
+ if is_dns || is_incomplete {
+ self.gap = false;
+ } else {
+ return AppLayerResult::ok();
+ }
+ }
+
+ let mut cur_i = input;
+ let mut consumed = 0;
+ while !cur_i.is_empty() {
+ if cur_i.len() == 1 {
+ return AppLayerResult::incomplete(consumed as u32, 2_u32);
+ }
+ let size = match be_u16(cur_i) as IResult<&[u8], u16> {
+ Ok((_, len)) => len,
+ _ => 0,
+ } as usize;
+ SCLogDebug!(
+ "[response] Have {} bytes, need {} to parse",
+ cur_i.len(),
+ size + 2
+ );
+ if size > 0 && cur_i.len() >= size + 2 {
+ let msg = &cur_i[2..(size + 2)];
+ let _pdu = Frame::new(
+ flow,
+ &stream_slice,
+ msg,
+ msg.len() as i64,
+ DnsFrameType::Pdu as u8,
+ );
+ if self.parse_response(msg, true) {
+ cur_i = &cur_i[(size + 2)..];
+ consumed += size + 2;
+ } else {
+ return AppLayerResult::err();
+ }
+ } else if size == 0 {
+ cur_i = &cur_i[2..];
+ consumed += 2;
+ } else {
+ SCLogDebug!(
+ "[response]Not enough DNS traffic to parse. Returning {}/{}",
+ consumed as u32,
+ (cur_i.len() - consumed) as u32
+ );
+ return AppLayerResult::incomplete(consumed as u32, (size + 2) as u32);
+ }
+ }
+ AppLayerResult::ok()
+ }
+
+ /// A gap has been seen in the request direction. Set the gap flag.
+ pub fn request_gap(&mut self, gap: u32) {
+ if gap > 0 {
+ self.gap = true;
+ }
+ }
+
+ /// A gap has been seen in the response direction. Set the gap
+ /// flag.
+ pub fn response_gap(&mut self, gap: u32) {
+ if gap > 0 {
+ self.gap = true;
+ }
+ }
+}
+
+const DNS_HEADER_SIZE: usize = 12;
+
+fn probe_header_validity(header: &DNSHeader, rlen: usize) -> (bool, bool, bool) {
+ let min_msg_size = 2
+ * (header.additional_rr as usize
+ + header.answer_rr as usize
+ + header.authority_rr as usize
+ + header.questions as usize)
+ + DNS_HEADER_SIZE;
+
+ if min_msg_size > rlen {
+ // Not enough data for records defined in the header, or
+ // impossibly large.
+ return (false, false, false);
+ }
+
+ let is_request = header.flags & 0x8000 == 0;
+ return (true, is_request, false);
+}
+
+/// Probe input to see if it looks like DNS.
+///
+/// Returns a tuple of booleans: (is_dns, is_request, incomplete)
+fn probe(input: &[u8], dlen: usize) -> (bool, bool, bool) {
+ // Trim input to dlen if larger.
+ let input = if input.len() <= dlen {
+ input
+ } else {
+ &input[..dlen]
+ };
+
+ // If input is less than dlen then we know we don't have enough data to
+ // parse a complete message, so perform header validation only.
+ if input.len() < dlen {
+ if let Ok((_, header)) = parser::dns_parse_header(input) {
+ return probe_header_validity(&header, dlen);
+ } else {
+ return (false, false, false);
+ }
+ }
+
+ match parser::dns_parse_request(input) {
+ Ok((_, request)) => {
+ return probe_header_validity(&request.header, dlen);
+ }
+ Err(Err::Incomplete(_)) => match parser::dns_parse_header(input) {
+ Ok((_, header)) => {
+ return probe_header_validity(&header, dlen);
+ }
+ Err(Err::Incomplete(_)) => (false, false, true),
+ Err(_) => (false, false, false),
+ },
+ Err(_) => (false, false, false),
+ }
+}
+
+/// Probe TCP input to see if it looks like DNS.
+pub fn probe_tcp(input: &[u8]) -> (bool, bool, bool) {
+ match be_u16(input) as IResult<&[u8], u16> {
+ Ok((rem, dlen)) => {
+ return probe(rem, dlen as usize);
+ }
+ Err(Err::Incomplete(_)) => {
+ return (false, false, true);
+ }
+ _ => {}
+ }
+ return (false, false, false);
+}
+
+/// Returns *mut DNSState
+#[no_mangle]
+pub extern "C" fn rs_dns_state_new(
+ _orig_state: *mut std::os::raw::c_void, _orig_proto: AppProto,
+) -> *mut std::os::raw::c_void {
+ let state = DNSState::new();
+ let boxed = Box::new(state);
+ return Box::into_raw(boxed) as *mut _;
+}
+
+/// Returns *mut DNSState
+#[no_mangle]
+pub extern "C" fn rs_dns_state_tcp_new() -> *mut std::os::raw::c_void {
+ let state = DNSState::new();
+ let boxed = Box::new(state);
+ return Box::into_raw(boxed) as *mut _;
+}
+
+/// Params:
+/// - state: *mut DNSState as void pointer
+#[no_mangle]
+pub extern "C" fn rs_dns_state_free(state: *mut std::os::raw::c_void) {
+ // Just unbox...
+ std::mem::drop(unsafe { Box::from_raw(state as *mut DNSState) });
+}
+
+#[no_mangle]
+pub unsafe extern "C" fn rs_dns_state_tx_free(state: *mut std::os::raw::c_void, tx_id: u64) {
+ let state = cast_pointer!(state, DNSState);
+ state.free_tx(tx_id);
+}
+
+/// C binding parse a DNS request. Returns 1 on success, -1 on failure.
+#[no_mangle]
+pub unsafe extern "C" fn rs_dns_parse_request(
+ flow: *const core::Flow, state: *mut std::os::raw::c_void, _pstate: *mut std::os::raw::c_void,
+ stream_slice: StreamSlice, _data: *const std::os::raw::c_void,
+) -> AppLayerResult {
+ let state = cast_pointer!(state, DNSState);
+ state.parse_request_udp(flow, stream_slice);
+ AppLayerResult::ok()
+}
+
+#[no_mangle]
+pub unsafe extern "C" fn rs_dns_parse_response(
+ flow: *const core::Flow, state: *mut std::os::raw::c_void, _pstate: *mut std::os::raw::c_void,
+ stream_slice: StreamSlice, _data: *const std::os::raw::c_void,
+) -> AppLayerResult {
+ let state = cast_pointer!(state, DNSState);
+ state.parse_response_udp(flow, stream_slice);
+ AppLayerResult::ok()
+}
+
+/// C binding parse a DNS request. Returns 1 on success, -1 on failure.
+#[no_mangle]
+pub unsafe extern "C" fn rs_dns_parse_request_tcp(
+ flow: *const core::Flow, state: *mut std::os::raw::c_void, _pstate: *mut std::os::raw::c_void,
+ stream_slice: StreamSlice, _data: *const std::os::raw::c_void,
+) -> AppLayerResult {
+ let state = cast_pointer!(state, DNSState);
+ if stream_slice.is_gap() {
+ state.request_gap(stream_slice.gap_size());
+ } else if !stream_slice.is_empty() {
+ return state.parse_request_tcp(flow, stream_slice);
+ }
+ AppLayerResult::ok()
+}
+
+#[no_mangle]
+pub unsafe extern "C" fn rs_dns_parse_response_tcp(
+ flow: *const core::Flow, state: *mut std::os::raw::c_void, _pstate: *mut std::os::raw::c_void,
+ stream_slice: StreamSlice, _data: *const std::os::raw::c_void,
+) -> AppLayerResult {
+ let state = cast_pointer!(state, DNSState);
+ if stream_slice.is_gap() {
+ state.response_gap(stream_slice.gap_size());
+ } else if !stream_slice.is_empty() {
+ return state.parse_response_tcp(flow, stream_slice);
+ }
+ AppLayerResult::ok()
+}
+
+#[no_mangle]
+pub extern "C" fn rs_dns_tx_get_alstate_progress(
+ _tx: *mut std::os::raw::c_void, _direction: u8,
+) -> std::os::raw::c_int {
+ // This is a stateless parser, just the existence of a transaction
+ // means its complete.
+ SCLogDebug!("rs_dns_tx_get_alstate_progress");
+ return 1;
+}
+
+#[no_mangle]
+pub unsafe extern "C" fn rs_dns_state_get_tx_count(state: *mut std::os::raw::c_void) -> u64 {
+ let state = cast_pointer!(state, DNSState);
+ SCLogDebug!("rs_dns_state_get_tx_count: returning {}", state.tx_id);
+ return state.tx_id;
+}
+
+#[no_mangle]
+pub unsafe extern "C" fn rs_dns_state_get_tx(
+ state: *mut std::os::raw::c_void, tx_id: u64,
+) -> *mut std::os::raw::c_void {
+ let state = cast_pointer!(state, DNSState);
+ match state.get_tx(tx_id) {
+ Some(tx) => {
+ return tx as *const _ as *mut _;
+ }
+ None => {
+ return std::ptr::null_mut();
+ }
+ }
+}
+
+#[no_mangle]
+pub extern "C" fn rs_dns_tx_is_request(tx: &mut DNSTransaction) -> bool {
+ tx.request.is_some()
+}
+
+#[no_mangle]
+pub extern "C" fn rs_dns_tx_is_response(tx: &mut DNSTransaction) -> bool {
+ tx.response.is_some()
+}
+
+pub unsafe extern "C" fn rs_dns_state_get_tx_data(
+ tx: *mut std::os::raw::c_void,
+) -> *mut AppLayerTxData {
+ let tx = cast_pointer!(tx, DNSTransaction);
+ return &mut tx.tx_data;
+}
+
+export_state_data_get!(rs_dns_get_state_data, DNSState);
+
+#[no_mangle]
+pub unsafe extern "C" fn rs_dns_tx_get_query_name(
+ tx: &mut DNSTransaction, i: u32, buf: *mut *const u8, len: *mut u32,
+) -> u8 {
+ if let Some(request) = &tx.request {
+ if (i as usize) < request.queries.len() {
+ let query = &request.queries[i as usize];
+ if !query.name.is_empty() {
+ *len = query.name.len() as u32;
+ *buf = query.name.as_ptr();
+ return 1;
+ }
+ }
+ }
+ return 0;
+}
+
+/// Get the DNS transaction ID of a transaction.
+//
+/// extern uint16_t rs_dns_tx_get_tx_id(RSDNSTransaction *);
+#[no_mangle]
+pub extern "C" fn rs_dns_tx_get_tx_id(tx: &mut DNSTransaction) -> u16 {
+ return tx.tx_id();
+}
+
+/// Get the DNS response flags for a transaction.
+///
+/// extern uint16_t rs_dns_tx_get_response_flags(RSDNSTransaction *);
+#[no_mangle]
+pub extern "C" fn rs_dns_tx_get_response_flags(tx: &mut DNSTransaction) -> u16 {
+ return tx.rcode();
+}
+
+#[no_mangle]
+pub unsafe extern "C" fn rs_dns_tx_get_query_rrtype(
+ tx: &mut DNSTransaction, i: u16, rrtype: *mut u16,
+) -> u8 {
+ if let Some(request) = &tx.request {
+ if (i as usize) < request.queries.len() {
+ let query = &request.queries[i as usize];
+ if !query.name.is_empty() {
+ *rrtype = query.rrtype;
+ return 1;
+ }
+ }
+ }
+ return 0;
+}
+
+#[no_mangle]
+pub unsafe extern "C" fn rs_dns_probe(
+ _flow: *const core::Flow, _dir: u8, input: *const u8, len: u32, rdir: *mut u8,
+) -> AppProto {
+ if len == 0 || len < std::mem::size_of::<DNSHeader>() as u32 {
+ return core::ALPROTO_UNKNOWN;
+ }
+ let slice: &[u8] = std::slice::from_raw_parts(input as *mut u8, len as usize);
+ let (is_dns, is_request, _) = probe(slice, slice.len());
+ if is_dns {
+ let dir = if is_request {
+ Direction::ToServer
+ } else {
+ Direction::ToClient
+ };
+ *rdir = dir as u8;
+ return ALPROTO_DNS;
+ }
+ return 0;
+}
+
+#[no_mangle]
+pub unsafe extern "C" fn rs_dns_probe_tcp(
+ _flow: *const core::Flow, direction: u8, input: *const u8, len: u32, rdir: *mut u8,
+) -> AppProto {
+ if len == 0 || len < std::mem::size_of::<DNSHeader>() as u32 + 2 {
+ return core::ALPROTO_UNKNOWN;
+ }
+ let slice: &[u8] = std::slice::from_raw_parts(input as *mut u8, len as usize);
+ //is_incomplete is checked by caller
+ let (is_dns, is_request, _) = probe_tcp(slice);
+ if is_dns {
+ let dir = if is_request {
+ Direction::ToServer
+ } else {
+ Direction::ToClient
+ };
+ if (direction & DIR_BOTH) != dir.into() {
+ *rdir = dir as u8;
+ }
+ return ALPROTO_DNS;
+ }
+ return 0;
+}
+
+#[no_mangle]
+pub unsafe extern "C" fn rs_dns_apply_tx_config(
+ _state: *mut std::os::raw::c_void, _tx: *mut std::os::raw::c_void, _mode: std::os::raw::c_int,
+ config: AppLayerTxConfig,
+) {
+ let tx = cast_pointer!(_tx, DNSTransaction);
+ let state = cast_pointer!(_state, DNSState);
+ if let Some(request) = &tx.request {
+ if state.config.is_none() {
+ state.config = Some(ConfigTracker::new());
+ }
+ if let Some(ref mut tracker) = &mut state.config {
+ tracker.add(request.header.tx_id, config);
+ }
+ }
+}
+
+#[no_mangle]
+pub unsafe extern "C" fn rs_dns_udp_register_parser() {
+ let default_port = std::ffi::CString::new("[53]").unwrap();
+ let parser = RustParser {
+ name: b"dns\0".as_ptr() as *const std::os::raw::c_char,
+ default_port: default_port.as_ptr(),
+ ipproto: IPPROTO_UDP,
+ probe_ts: Some(rs_dns_probe),
+ probe_tc: Some(rs_dns_probe),
+ min_depth: 0,
+ max_depth: std::mem::size_of::<DNSHeader>() as u16,
+ state_new: rs_dns_state_new,
+ state_free: rs_dns_state_free,
+ tx_free: rs_dns_state_tx_free,
+ parse_ts: rs_dns_parse_request,
+ parse_tc: rs_dns_parse_response,
+ get_tx_count: rs_dns_state_get_tx_count,
+ get_tx: rs_dns_state_get_tx,
+ tx_comp_st_ts: 1,
+ tx_comp_st_tc: 1,
+ tx_get_progress: rs_dns_tx_get_alstate_progress,
+ get_eventinfo: Some(DNSEvent::get_event_info),
+ get_eventinfo_byid: Some(DNSEvent::get_event_info_by_id),
+ localstorage_new: None,
+ localstorage_free: None,
+ get_tx_files: None,
+ get_tx_iterator: Some(crate::applayer::state_get_tx_iterator::<DNSState, DNSTransaction>),
+ get_tx_data: rs_dns_state_get_tx_data,
+ get_state_data: rs_dns_get_state_data,
+ apply_tx_config: Some(rs_dns_apply_tx_config),
+ flags: 0,
+ truncate: None,
+ get_frame_id_by_name: Some(DnsFrameType::ffi_id_from_name),
+ get_frame_name_by_id: Some(DnsFrameType::ffi_name_from_id),
+ };
+
+ let ip_proto_str = CString::new("udp").unwrap();
+ if AppLayerProtoDetectConfProtoDetectionEnabled(ip_proto_str.as_ptr(), parser.name) != 0 {
+ let alproto = AppLayerRegisterProtocolDetection(&parser, 1);
+ ALPROTO_DNS = alproto;
+ if AppLayerParserConfParserEnabled(ip_proto_str.as_ptr(), parser.name) != 0 {
+ let _ = AppLayerRegisterParser(&parser, alproto);
+ }
+ }
+}
+
+#[no_mangle]
+pub unsafe extern "C" fn rs_dns_tcp_register_parser() {
+ let default_port = std::ffi::CString::new("53").unwrap();
+ let parser = RustParser {
+ name: b"dns\0".as_ptr() as *const std::os::raw::c_char,
+ default_port: default_port.as_ptr(),
+ ipproto: IPPROTO_TCP,
+ probe_ts: Some(rs_dns_probe_tcp),
+ probe_tc: Some(rs_dns_probe_tcp),
+ min_depth: 0,
+ max_depth: std::mem::size_of::<DNSHeader>() as u16 + 2,
+ state_new: rs_dns_state_new,
+ state_free: rs_dns_state_free,
+ tx_free: rs_dns_state_tx_free,
+ parse_ts: rs_dns_parse_request_tcp,
+ parse_tc: rs_dns_parse_response_tcp,
+ get_tx_count: rs_dns_state_get_tx_count,
+ get_tx: rs_dns_state_get_tx,
+ tx_comp_st_ts: 1,
+ tx_comp_st_tc: 1,
+ tx_get_progress: rs_dns_tx_get_alstate_progress,
+ get_eventinfo: Some(DNSEvent::get_event_info),
+ get_eventinfo_byid: Some(DNSEvent::get_event_info_by_id),
+ localstorage_new: None,
+ localstorage_free: None,
+ get_tx_files: None,
+ get_tx_iterator: Some(crate::applayer::state_get_tx_iterator::<DNSState, DNSTransaction>),
+ get_tx_data: rs_dns_state_get_tx_data,
+ get_state_data: rs_dns_get_state_data,
+ apply_tx_config: Some(rs_dns_apply_tx_config),
+ flags: APP_LAYER_PARSER_OPT_ACCEPT_GAPS,
+ truncate: None,
+ get_frame_id_by_name: Some(DnsFrameType::ffi_id_from_name),
+ get_frame_name_by_id: Some(DnsFrameType::ffi_name_from_id),
+ };
+
+ let ip_proto_str = CString::new("tcp").unwrap();
+ if AppLayerProtoDetectConfProtoDetectionEnabled(ip_proto_str.as_ptr(), parser.name) != 0 {
+ let alproto = AppLayerRegisterProtocolDetection(&parser, 1);
+ ALPROTO_DNS = alproto;
+ if AppLayerParserConfParserEnabled(ip_proto_str.as_ptr(), parser.name) != 0 {
+ let _ = AppLayerRegisterParser(&parser, alproto);
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+
+ use super::*;
+
+ #[test]
+ fn test_dns_parse_request_tcp_valid() {
+ // A UDP DNS request with the DNS payload starting at byte 42.
+ // From pcap: https://github.com/jasonish/suricata-verify/blob/7cc0e1bd0a5249b52e6e87d82d57c0b6aaf75fce/dns-udp-dig-a-www-suricata-ids-org/dig-a-www.suricata-ids.org.pcap
+ #[rustfmt::skip]
+ let buf: &[u8] = &[
+ 0x00, 0x15, 0x17, 0x0d, 0x06, 0xf7, 0xd8, 0xcb, /* ........ */
+ 0x8a, 0xed, 0xa1, 0x46, 0x08, 0x00, 0x45, 0x00, /* ...F..E. */
+ 0x00, 0x4d, 0x23, 0x11, 0x00, 0x00, 0x40, 0x11, /* .M#...@. */
+ 0x41, 0x64, 0x0a, 0x10, 0x01, 0x0b, 0x0a, 0x10, /* Ad...... */
+ 0x01, 0x01, 0xa3, 0x4d, 0x00, 0x35, 0x00, 0x39, /* ...M.5.9 */
+ 0xb2, 0xb3, 0x8d, 0x32, 0x01, 0x20, 0x00, 0x01, /* ...2. .. */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x03, 0x77, /* .......w */
+ 0x77, 0x77, 0x0c, 0x73, 0x75, 0x72, 0x69, 0x63, /* ww.suric */
+ 0x61, 0x74, 0x61, 0x2d, 0x69, 0x64, 0x73, 0x03, /* ata-ids. */
+ 0x6f, 0x72, 0x67, 0x00, 0x00, 0x01, 0x00, 0x01, /* org..... */
+ 0x00, 0x00, 0x29, 0x10, 0x00, 0x00, 0x00, 0x00, /* ..)..... */
+ 0x00, 0x00, 0x00 /* ... */
+ ];
+
+ // The DNS payload starts at offset 42.
+ let dns_payload = &buf[42..];
+
+ // Make a TCP DNS request payload.
+ let mut request = Vec::new();
+ request.push(((dns_payload.len() as u16) >> 8) as u8);
+ request.push(((dns_payload.len() as u16) & 0xff) as u8);
+ request.extend(dns_payload);
+
+ let mut state = DNSState::new();
+ assert_eq!(
+ AppLayerResult::ok(),
+ state.parse_request_tcp(
+ std::ptr::null(),
+ StreamSlice::from_slice(&request, STREAM_TOSERVER, 0)
+ )
+ );
+ }
+
+ #[test]
+ fn test_dns_parse_request_tcp_short_payload() {
+ // A UDP DNS request with the DNS payload starting at byte 42.
+ // From pcap: https://github.com/jasonish/suricata-verify/blob/7cc0e1bd0a5249b52e6e87d82d57c0b6aaf75fce/dns-udp-dig-a-www-suricata-ids-org/dig-a-www.suricata-ids.org.pcap
+ #[rustfmt::skip]
+ let buf: &[u8] = &[
+ 0x00, 0x15, 0x17, 0x0d, 0x06, 0xf7, 0xd8, 0xcb, /* ........ */
+ 0x8a, 0xed, 0xa1, 0x46, 0x08, 0x00, 0x45, 0x00, /* ...F..E. */
+ 0x00, 0x4d, 0x23, 0x11, 0x00, 0x00, 0x40, 0x11, /* .M#...@. */
+ 0x41, 0x64, 0x0a, 0x10, 0x01, 0x0b, 0x0a, 0x10, /* Ad...... */
+ 0x01, 0x01, 0xa3, 0x4d, 0x00, 0x35, 0x00, 0x39, /* ...M.5.9 */
+ 0xb2, 0xb3, 0x8d, 0x32, 0x01, 0x20, 0x00, 0x01, /* ...2. .. */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x03, 0x77, /* .......w */
+ 0x77, 0x77, 0x0c, 0x73, 0x75, 0x72, 0x69, 0x63, /* ww.suric */
+ 0x61, 0x74, 0x61, 0x2d, 0x69, 0x64, 0x73, 0x03, /* ata-ids. */
+ 0x6f, 0x72, 0x67, 0x00, 0x00, 0x01, 0x00, 0x01, /* org..... */
+ 0x00, 0x00, 0x29, 0x10, 0x00, 0x00, 0x00, 0x00, /* ..)..... */
+ 0x00, 0x00, 0x00 /* ... */
+ ];
+
+ // The DNS payload starts at offset 42.
+ let dns_payload = &buf[42..];
+
+ // Make a TCP DNS request payload but with the length 1 larger
+ // than the available data.
+ let mut request = Vec::new();
+ request.push(((dns_payload.len() as u16) >> 8) as u8);
+ request.push(((dns_payload.len() as u16) & 0xff) as u8 + 1);
+ request.extend(dns_payload);
+
+ let mut state = DNSState::new();
+ assert_eq!(
+ AppLayerResult::incomplete(0, 52),
+ state.parse_request_tcp(
+ std::ptr::null(),
+ StreamSlice::from_slice(&request, STREAM_TOSERVER, 0)
+ )
+ );
+ }
+
+ #[test]
+ fn test_dns_parse_response_tcp_valid() {
+ // A UDP DNS response with the DNS payload starting at byte 42.
+ // From pcap: https://github.com/jasonish/suricata-verify/blob/7cc0e1bd0a5249b52e6e87d82d57c0b6aaf75fce/dns-udp-dig-a-www-suricata-ids-org/dig-a-www.suricata-ids.org.pcap
+ #[rustfmt::skip]
+ let buf: &[u8] = &[
+ 0xd8, 0xcb, 0x8a, 0xed, 0xa1, 0x46, 0x00, 0x15, /* .....F.. */
+ 0x17, 0x0d, 0x06, 0xf7, 0x08, 0x00, 0x45, 0x00, /* ......E. */
+ 0x00, 0x80, 0x65, 0x4e, 0x40, 0x00, 0x40, 0x11, /* ..eN@.@. */
+ 0xbe, 0xf3, 0x0a, 0x10, 0x01, 0x01, 0x0a, 0x10, /* ........ */
+ 0x01, 0x0b, 0x00, 0x35, 0xa3, 0x4d, 0x00, 0x6c, /* ...5.M.l */
+ 0x8d, 0x8c, 0x8d, 0x32, 0x81, 0xa0, 0x00, 0x01, /* ...2.... */
+ 0x00, 0x03, 0x00, 0x00, 0x00, 0x00, 0x03, 0x77, /* .......w */
+ 0x77, 0x77, 0x0c, 0x73, 0x75, 0x72, 0x69, 0x63, /* ww.suric */
+ 0x61, 0x74, 0x61, 0x2d, 0x69, 0x64, 0x73, 0x03, /* ata-ids. */
+ 0x6f, 0x72, 0x67, 0x00, 0x00, 0x01, 0x00, 0x01, /* org..... */
+ 0xc0, 0x0c, 0x00, 0x05, 0x00, 0x01, 0x00, 0x00, /* ........ */
+ 0x0d, 0xd8, 0x00, 0x12, 0x0c, 0x73, 0x75, 0x72, /* .....sur */
+ 0x69, 0x63, 0x61, 0x74, 0x61, 0x2d, 0x69, 0x64, /* icata-id */
+ 0x73, 0x03, 0x6f, 0x72, 0x67, 0x00, 0xc0, 0x32, /* s.org..2 */
+ 0x00, 0x01, 0x00, 0x01, 0x00, 0x00, 0x00, 0xf4, /* ........ */
+ 0x00, 0x04, 0xc0, 0x00, 0x4e, 0x18, 0xc0, 0x32, /* ....N..2 */
+ 0x00, 0x01, 0x00, 0x01, 0x00, 0x00, 0x00, 0xf4, /* ........ */
+ 0x00, 0x04, 0xc0, 0x00, 0x4e, 0x19 /* ....N. */
+ ];
+
+ // The DNS payload starts at offset 42.
+ let dns_payload = &buf[42..];
+
+ // Make a TCP DNS response payload.
+ let mut request = Vec::new();
+ request.push(((dns_payload.len() as u16) >> 8) as u8);
+ request.push(((dns_payload.len() as u16) & 0xff) as u8);
+ request.extend(dns_payload);
+
+ let mut state = DNSState::new();
+ assert_eq!(
+ AppLayerResult::ok(),
+ state.parse_response_tcp(
+ std::ptr::null(),
+ StreamSlice::from_slice(&request, STREAM_TOCLIENT, 0)
+ )
+ );
+ }
+
+ // Test that a TCP DNS payload won't be parsed if there is not
+ // enough data.
+ #[test]
+ fn test_dns_parse_response_tcp_short_payload() {
+ // A UDP DNS response with the DNS payload starting at byte 42.
+ // From pcap: https://github.com/jasonish/suricata-verify/blob/7cc0e1bd0a5249b52e6e87d82d57c0b6aaf75fce/dns-udp-dig-a-www-suricata-ids-org/dig-a-www.suricata-ids.org.pcap
+ #[rustfmt::skip]
+ let buf: &[u8] = &[
+ 0xd8, 0xcb, 0x8a, 0xed, 0xa1, 0x46, 0x00, 0x15, /* .....F.. */
+ 0x17, 0x0d, 0x06, 0xf7, 0x08, 0x00, 0x45, 0x00, /* ......E. */
+ 0x00, 0x80, 0x65, 0x4e, 0x40, 0x00, 0x40, 0x11, /* ..eN@.@. */
+ 0xbe, 0xf3, 0x0a, 0x10, 0x01, 0x01, 0x0a, 0x10, /* ........ */
+ 0x01, 0x0b, 0x00, 0x35, 0xa3, 0x4d, 0x00, 0x6c, /* ...5.M.l */
+ 0x8d, 0x8c, 0x8d, 0x32, 0x81, 0xa0, 0x00, 0x01, /* ...2.... */
+ 0x00, 0x03, 0x00, 0x00, 0x00, 0x00, 0x03, 0x77, /* .......w */
+ 0x77, 0x77, 0x0c, 0x73, 0x75, 0x72, 0x69, 0x63, /* ww.suric */
+ 0x61, 0x74, 0x61, 0x2d, 0x69, 0x64, 0x73, 0x03, /* ata-ids. */
+ 0x6f, 0x72, 0x67, 0x00, 0x00, 0x01, 0x00, 0x01, /* org..... */
+ 0xc0, 0x0c, 0x00, 0x05, 0x00, 0x01, 0x00, 0x00, /* ........ */
+ 0x0d, 0xd8, 0x00, 0x12, 0x0c, 0x73, 0x75, 0x72, /* .....sur */
+ 0x69, 0x63, 0x61, 0x74, 0x61, 0x2d, 0x69, 0x64, /* icata-id */
+ 0x73, 0x03, 0x6f, 0x72, 0x67, 0x00, 0xc0, 0x32, /* s.org..2 */
+ 0x00, 0x01, 0x00, 0x01, 0x00, 0x00, 0x00, 0xf4, /* ........ */
+ 0x00, 0x04, 0xc0, 0x00, 0x4e, 0x18, 0xc0, 0x32, /* ....N..2 */
+ 0x00, 0x01, 0x00, 0x01, 0x00, 0x00, 0x00, 0xf4, /* ........ */
+ 0x00, 0x04, 0xc0, 0x00, 0x4e, 0x19 /* ....N. */
+ ];
+
+ // The DNS payload starts at offset 42.
+ let dns_payload = &buf[42..];
+
+ // Make a TCP DNS response payload, but make the length 1 byte
+ // larger than the actual size.
+ let mut request = Vec::new();
+ request.push(((dns_payload.len() as u16) >> 8) as u8);
+ request.push((((dns_payload.len() as u16) & 0xff) + 1) as u8);
+ request.extend(dns_payload);
+
+ let mut state = DNSState::new();
+ assert_eq!(
+ AppLayerResult::incomplete(0, 103),
+ state.parse_response_tcp(
+ std::ptr::null(),
+ StreamSlice::from_slice(&request, STREAM_TOCLIENT, 0)
+ )
+ );
+ }
+
+ // Port of the C RustDNSUDPParserTest02 unit test.
+ #[test]
+ fn test_dns_udp_parser_test_01() {
+ /* query: abcdefghijk.com
+ * TTL: 86400
+ * serial 20130422 refresh 28800 retry 7200 exp 604800 min ttl 86400
+ * ns, hostmaster */
+ #[rustfmt::skip]
+ let buf: &[u8] = &[
+ 0x00, 0x3c, 0x85, 0x00, 0x00, 0x01, 0x00, 0x00,
+ 0x00, 0x01, 0x00, 0x00, 0x0b, 0x61, 0x62, 0x63,
+ 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x6b,
+ 0x03, 0x63, 0x6f, 0x6d, 0x00, 0x00, 0x0f, 0x00,
+ 0x01, 0x00, 0x00, 0x06, 0x00, 0x01, 0x00, 0x01,
+ 0x51, 0x80, 0x00, 0x25, 0x02, 0x6e, 0x73, 0x00,
+ 0x0a, 0x68, 0x6f, 0x73, 0x74, 0x6d, 0x61, 0x73,
+ 0x74, 0x65, 0x72, 0xc0, 0x2f, 0x01, 0x33, 0x2a,
+ 0x76, 0x00, 0x00, 0x70, 0x80, 0x00, 0x00, 0x1c,
+ 0x20, 0x00, 0x09, 0x3a, 0x80, 0x00, 0x01, 0x51,
+ 0x80,
+ ];
+ let mut state = DNSState::new();
+ assert!(state.parse_response(buf, false));
+ }
+
+ // Port of the C RustDNSUDPParserTest02 unit test.
+ #[test]
+ fn test_dns_udp_parser_test_02() {
+ #[rustfmt::skip]
+ let buf: &[u8] = &[
+ 0x6D,0x08,0x84,0x80,0x00,0x01,0x00,0x08,0x00,0x00,0x00,0x01,0x03,0x57,0x57,0x57,
+ 0x04,0x54,0x54,0x54,0x54,0x03,0x56,0x56,0x56,0x03,0x63,0x6F,0x6D,0x02,0x79,0x79,
+ 0x00,0x00,0x01,0x00,0x01,0xC0,0x0C,0x00,0x05,0x00,0x01,0x00,0x00,0x0E,0x10,0x00,
+ 0x02,0xC0,0x0C,0xC0,0x31,0x00,0x05,0x00,0x01,0x00,0x00,0x0E,0x10,0x00,0x02,0xC0,
+ 0x31,0xC0,0x3F,0x00,0x05,0x00,0x01,0x00,0x00,0x0E,0x10,0x00,0x02,0xC0,0x3F,0xC0,
+ 0x4D,0x00,0x05,0x00,0x01,0x00,0x00,0x0E,0x10,0x00,0x02,0xC0,0x4D,0xC0,0x5B,0x00,
+ 0x05,0x00,0x01,0x00,0x00,0x0E,0x10,0x00,0x02,0xC0,0x5B,0xC0,0x69,0x00,0x05,0x00,
+ 0x01,0x00,0x00,0x0E,0x10,0x00,0x02,0xC0,0x69,0xC0,0x77,0x00,0x05,0x00,0x01,0x00,
+ 0x00,0x0E,0x10,0x00,0x02,0xC0,0x77,0xC0,0x85,0x00,0x05,0x00,0x01,0x00,0x00,0x0E,
+ 0x10,0x00,0x02,0xC0,0x85,0x00,0x00,0x29,0x05,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+ ];
+ let mut state = DNSState::new();
+ assert!(state.parse_response(buf, false));
+ }
+
+ // Port of the C RustDNSUDPParserTest03 unit test.
+ #[test]
+ fn test_dns_udp_parser_test_03() {
+ #[rustfmt::skip]
+ let buf: &[u8] = &[
+ 0x6F,0xB4,0x84,0x80,0x00,0x01,0x00,0x02,0x00,0x02,0x00,0x03,0x03,0x57,0x57,0x77,
+ 0x0B,0x56,0x56,0x56,0x56,0x56,0x56,0x56,0x56,0x56,0x56,0x56,0x03,0x55,0x55,0x55,
+ 0x02,0x79,0x79,0x00,0x00,0x01,0x00,0x01,0xC0,0x0C,0x00,0x05,0x00,0x01,0x00,0x00,
+ 0x0E,0x10,0x00,0x02,0xC0,0x10,0xC0,0x34,0x00,0x01,0x00,0x01,0x00,0x00,0x0E,0x10,
+ 0x00,0x04,0xC3,0xEA,0x04,0x19,0xC0,0x34,0x00,0x02,0x00,0x01,0x00,0x00,0x0E,0x10,
+ 0x00,0x0A,0x03,0x6E,0x73,0x31,0x03,0x61,0x67,0x62,0xC0,0x20,0xC0,0x46,0x00,0x02,
+ 0x00,0x01,0x00,0x00,0x0E,0x10,0x00,0x06,0x03,0x6E,0x73,0x32,0xC0,0x56,0xC0,0x52,
+ 0x00,0x01,0x00,0x01,0x00,0x00,0x0E,0x10,0x00,0x04,0xC3,0xEA,0x04,0x0A,0xC0,0x68,
+ 0x00,0x01,0x00,0x01,0x00,0x00,0x0E,0x10,0x00,0x04,0xC3,0xEA,0x05,0x14,0x00,0x00,
+ 0x29,0x05,0x00,0x00,0x00,0x00,0x00,0x00,0x00
+ ];
+ let mut state = DNSState::new();
+ assert!(state.parse_response(buf, false));
+ }
+
+ // Port of the C RustDNSUDPParserTest04 unit test.
+ //
+ // Test the TXT records in an answer.
+ #[test]
+ fn test_dns_udp_parser_test_04() {
+ #[rustfmt::skip]
+ let buf: &[u8] = &[
+ 0xc2,0x2f,0x81,0x80,0x00,0x01,0x00,0x01,0x00,0x01,0x00,0x01,0x0a,0x41,0x41,0x41,
+ 0x41,0x41,0x4f,0x31,0x6b,0x51,0x41,0x05,0x3d,0x61,0x75,0x74,0x68,0x03,0x73,0x72,
+ 0x76,0x06,0x74,0x75,0x6e,0x6e,0x65,0x6c,0x03,0x63,0x6f,0x6d,0x00,0x00,0x10,0x00,
+ 0x01,
+ /* answer record start */
+ 0xc0,0x0c,0x00,0x10,0x00,0x01,0x00,0x00,0x00,0x03,0x00,0x22,
+ /* txt record starts: */
+ 0x20, /* <txt len 32 */ 0x41,0x68,0x76,0x4d,0x41,0x41,0x4f,0x31,0x6b,0x41,0x46,
+ 0x45,0x35,0x54,0x45,0x39,0x51,0x54,0x6a,0x46,0x46,0x4e,0x30,0x39,0x52,0x4e,0x31,
+ 0x6c,0x59,0x53,0x44,0x6b,0x00, /* <txt len 0 */ 0xc0,0x1d,0x00,0x02,0x00,0x01,
+ 0x00,0x09,0x3a,0x80,0x00,0x09,0x06,0x69,0x6f,0x64,0x69,0x6e,0x65,0xc0,0x21,0xc0,
+ 0x6b,0x00,0x01,0x00,0x01,0x00,0x09,0x3a,0x80,0x00,0x04,0x0a,0x1e,0x1c,0x5f
+ ];
+ let mut state = DNSState::new();
+ assert!(state.parse_response(buf, false));
+ }
+
+ // Port of the C RustDNSUDPParserTest05 unit test.
+ //
+ // Test TXT records in answer with a bad length.
+ #[test]
+ fn test_dns_udp_parser_test_05() {
+ #[rustfmt::skip]
+ let buf: &[u8] = &[
+ 0xc2,0x2f,0x81,0x80,0x00,0x01,0x00,0x01,0x00,0x01,0x00,0x01,0x0a,0x41,0x41,0x41,
+ 0x41,0x41,0x4f,0x31,0x6b,0x51,0x41,0x05,0x3d,0x61,0x75,0x74,0x68,0x03,0x73,0x72,
+ 0x76,0x06,0x74,0x75,0x6e,0x6e,0x65,0x6c,0x03,0x63,0x6f,0x6d,0x00,0x00,0x10,0x00,
+ 0x01,
+ /* answer record start */
+ 0xc0,0x0c,0x00,0x10,0x00,0x01,0x00,0x00,0x00,0x03,0x00,0x22,
+ /* txt record starts: */
+ 0x40, /* <txt len 64 */ 0x41,0x68,0x76,0x4d,0x41,0x41,0x4f,0x31,0x6b,0x41,0x46,
+ 0x45,0x35,0x54,0x45,0x39,0x51,0x54,0x6a,0x46,0x46,0x4e,0x30,0x39,0x52,0x4e,0x31,
+ 0x6c,0x59,0x53,0x44,0x6b,0x00, /* <txt len 0 */ 0xc0,0x1d,0x00,0x02,0x00,0x01,
+ 0x00,0x09,0x3a,0x80,0x00,0x09,0x06,0x69,0x6f,0x64,0x69,0x6e,0x65,0xc0,0x21,0xc0,
+ 0x6b,0x00,0x01,0x00,0x01,0x00,0x09,0x3a,0x80,0x00,0x04,0x0a,0x1e,0x1c,0x5f
+ ];
+ let mut state = DNSState::new();
+ assert!(!state.parse_response(buf, false));
+ }
+
+ // Port of the C RustDNSTCPParserTestMultiRecord unit test.
+ #[test]
+ fn test_dns_tcp_parser_multi_record() {
+ #[rustfmt::skip]
+ let buf: &[u8] = &[
+ 0x00, 0x1e, 0x00, 0x00, 0x01, 0x00, 0x00, 0x01,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x30,
+ 0x06, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x03,
+ 0x63, 0x6f, 0x6d, 0x00, 0x00, 0x01, 0x00, 0x01,
+ 0x00, 0x1e, 0x00, 0x01, 0x01, 0x00, 0x00, 0x01,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x31,
+ 0x06, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x03,
+ 0x63, 0x6f, 0x6d, 0x00, 0x00, 0x01, 0x00, 0x01,
+ 0x00, 0x1e, 0x00, 0x02, 0x01, 0x00, 0x00, 0x01,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x32,
+ 0x06, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x03,
+ 0x63, 0x6f, 0x6d, 0x00, 0x00, 0x01, 0x00, 0x01,
+ 0x00, 0x1e, 0x00, 0x03, 0x01, 0x00, 0x00, 0x01,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x33,
+ 0x06, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x03,
+ 0x63, 0x6f, 0x6d, 0x00, 0x00, 0x01, 0x00, 0x01,
+ 0x00, 0x1e, 0x00, 0x04, 0x01, 0x00, 0x00, 0x01,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x34,
+ 0x06, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x03,
+ 0x63, 0x6f, 0x6d, 0x00, 0x00, 0x01, 0x00, 0x01,
+ 0x00, 0x1e, 0x00, 0x05, 0x01, 0x00, 0x00, 0x01,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x35,
+ 0x06, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x03,
+ 0x63, 0x6f, 0x6d, 0x00, 0x00, 0x01, 0x00, 0x01,
+ 0x00, 0x1e, 0x00, 0x06, 0x01, 0x00, 0x00, 0x01,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x36,
+ 0x06, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x03,
+ 0x63, 0x6f, 0x6d, 0x00, 0x00, 0x01, 0x00, 0x01,
+ 0x00, 0x1e, 0x00, 0x07, 0x01, 0x00, 0x00, 0x01,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x37,
+ 0x06, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x03,
+ 0x63, 0x6f, 0x6d, 0x00, 0x00, 0x01, 0x00, 0x01,
+ 0x00, 0x1e, 0x00, 0x08, 0x01, 0x00, 0x00, 0x01,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x38,
+ 0x06, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x03,
+ 0x63, 0x6f, 0x6d, 0x00, 0x00, 0x01, 0x00, 0x01,
+ 0x00, 0x1e, 0x00, 0x09, 0x01, 0x00, 0x00, 0x01,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x39,
+ 0x06, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x03,
+ 0x63, 0x6f, 0x6d, 0x00, 0x00, 0x01, 0x00, 0x01,
+ 0x00, 0x1f, 0x00, 0x0a, 0x01, 0x00, 0x00, 0x01,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x31,
+ 0x30, 0x06, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65,
+ 0x03, 0x63, 0x6f, 0x6d, 0x00, 0x00, 0x01, 0x00,
+ 0x01, 0x00, 0x1f, 0x00, 0x0b, 0x01, 0x00, 0x00,
+ 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02,
+ 0x31, 0x31, 0x06, 0x67, 0x6f, 0x6f, 0x67, 0x6c,
+ 0x65, 0x03, 0x63, 0x6f, 0x6d, 0x00, 0x00, 0x01,
+ 0x00, 0x01, 0x00, 0x1f, 0x00, 0x0c, 0x01, 0x00,
+ 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x02, 0x31, 0x32, 0x06, 0x67, 0x6f, 0x6f, 0x67,
+ 0x6c, 0x65, 0x03, 0x63, 0x6f, 0x6d, 0x00, 0x00,
+ 0x01, 0x00, 0x01, 0x00, 0x1f, 0x00, 0x0d, 0x01,
+ 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x02, 0x31, 0x33, 0x06, 0x67, 0x6f, 0x6f,
+ 0x67, 0x6c, 0x65, 0x03, 0x63, 0x6f, 0x6d, 0x00,
+ 0x00, 0x01, 0x00, 0x01, 0x00, 0x1f, 0x00, 0x0e,
+ 0x01, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x02, 0x31, 0x34, 0x06, 0x67, 0x6f,
+ 0x6f, 0x67, 0x6c, 0x65, 0x03, 0x63, 0x6f, 0x6d,
+ 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x1f, 0x00,
+ 0x0f, 0x01, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x02, 0x31, 0x35, 0x06, 0x67,
+ 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x03, 0x63, 0x6f,
+ 0x6d, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x1f,
+ 0x00, 0x10, 0x01, 0x00, 0x00, 0x01, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x02, 0x31, 0x36, 0x06,
+ 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x03, 0x63,
+ 0x6f, 0x6d, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00,
+ 0x1f, 0x00, 0x11, 0x01, 0x00, 0x00, 0x01, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x31, 0x37,
+ 0x06, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x03,
+ 0x63, 0x6f, 0x6d, 0x00, 0x00, 0x01, 0x00, 0x01,
+ 0x00, 0x1f, 0x00, 0x12, 0x01, 0x00, 0x00, 0x01,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x31,
+ 0x38, 0x06, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65,
+ 0x03, 0x63, 0x6f, 0x6d, 0x00, 0x00, 0x01, 0x00,
+ 0x01, 0x00, 0x1f, 0x00, 0x13, 0x01, 0x00, 0x00,
+ 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02,
+ 0x31, 0x39, 0x06, 0x67, 0x6f, 0x6f, 0x67, 0x6c,
+ 0x65, 0x03, 0x63, 0x6f, 0x6d, 0x00, 0x00, 0x01,
+ 0x00, 0x01
+ ];
+
+ // A NULL flow.
+ let flow = std::ptr::null();
+
+ let mut state = DNSState::new();
+ assert_eq!(
+ AppLayerResult::ok(),
+ state.parse_request_tcp(flow, StreamSlice::from_slice(buf, STREAM_TOSERVER, 0))
+ );
+ }
+
+ #[test]
+ fn test_dns_tcp_parser_split_payload() {
+ // A NULL flow.
+ let flow = std::ptr::null();
+
+ /* incomplete payload */
+ #[rustfmt::skip]
+ let buf1: &[u8] = &[
+ 0x00, 0x1c, 0x10, 0x32, 0x01, 0x00, 0x00, 0x01,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
+ ];
+ /* complete payload plus the start of a new payload */
+ #[rustfmt::skip]
+ let buf2: &[u8] = &[
+ 0x00, 0x1c, 0x10, 0x32, 0x01, 0x00, 0x00, 0x01,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x06, 0x67, 0x6F, 0x6F, 0x67, 0x6C, 0x65, 0x03,
+ 0x63, 0x6F, 0x6D, 0x00, 0x00, 0x10, 0x00, 0x01,
+
+ // next.
+ 0x00, 0x1c, 0x10, 0x32, 0x01, 0x00, 0x00, 0x01,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ ];
+
+ /* and the complete payload again with no trailing data. */
+ #[rustfmt::skip]
+ let buf3: &[u8] = &[
+ 0x00, 0x1c, 0x10, 0x32, 0x01, 0x00, 0x00, 0x01,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x06, 0x67, 0x6F, 0x6F, 0x67, 0x6C, 0x65, 0x03,
+ 0x63, 0x6F, 0x6D, 0x00, 0x00, 0x10, 0x00, 0x01,
+ ];
+
+ let mut state = DNSState::new();
+ assert_eq!(
+ AppLayerResult::incomplete(0, 30),
+ state.parse_request_tcp(flow, StreamSlice::from_slice(buf1, STREAM_TOSERVER, 0))
+ );
+ assert_eq!(
+ AppLayerResult::incomplete(30, 30),
+ state.parse_request_tcp(flow, StreamSlice::from_slice(buf2, STREAM_TOSERVER, 0))
+ );
+ assert_eq!(
+ AppLayerResult::ok(),
+ state.parse_request_tcp(flow, StreamSlice::from_slice(buf3, STREAM_TOSERVER, 0))
+ );
+ }
+
+ #[test]
+ fn test_dns_event_from_id() {
+ assert_eq!(DNSEvent::from_id(0), Some(DNSEvent::MalformedData));
+ assert_eq!(DNSEvent::from_id(3), Some(DNSEvent::ZFlagSet));
+ assert_eq!(DNSEvent::from_id(9), None);
+ }
+
+ #[test]
+ fn test_dns_event_to_cstring() {
+ assert_eq!(DNSEvent::MalformedData.to_cstring(), "malformed_data\0");
+ }
+
+ #[test]
+ fn test_dns_event_from_string() {
+ let name = "malformed_data";
+ let event = DNSEvent::from_string(name).unwrap();
+ assert_eq!(event, DNSEvent::MalformedData);
+ assert_eq!(event.to_cstring(), format!("{}\0", name));
+ }
+}
diff --git a/rust/src/dns/log.rs b/rust/src/dns/log.rs
new file mode 100644
index 0000000..5212b1a
--- /dev/null
+++ b/rust/src/dns/log.rs
@@ -0,0 +1,671 @@
+/* Copyright (C) 2017 Open Information Security Foundation
+ *
+ * You can copy, redistribute or modify this Program under the terms of
+ * the GNU General Public License version 2 as published by the Free
+ * Software Foundation.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * version 2 along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301, USA.
+ */
+
+use std;
+use std::collections::HashMap;
+use std::string::String;
+
+use crate::dns::dns::*;
+use crate::jsonbuilder::{JsonBuilder, JsonError};
+
+pub const LOG_A: u64 = BIT_U64!(2);
+pub const LOG_NS: u64 = BIT_U64!(3);
+pub const LOG_MD: u64 = BIT_U64!(4);
+pub const LOG_MF: u64 = BIT_U64!(5);
+pub const LOG_CNAME: u64 = BIT_U64!(6);
+pub const LOG_SOA: u64 = BIT_U64!(7);
+pub const LOG_MB: u64 = BIT_U64!(8);
+pub const LOG_MG: u64 = BIT_U64!(9);
+pub const LOG_MR: u64 = BIT_U64!(10);
+pub const LOG_NULL: u64 = BIT_U64!(11);
+pub const LOG_WKS: u64 = BIT_U64!(12);
+pub const LOG_PTR: u64 = BIT_U64!(13);
+pub const LOG_HINFO: u64 = BIT_U64!(14);
+pub const LOG_MINFO: u64 = BIT_U64!(15);
+pub const LOG_MX: u64 = BIT_U64!(16);
+pub const LOG_TXT: u64 = BIT_U64!(17);
+pub const LOG_RP: u64 = BIT_U64!(18);
+pub const LOG_AFSDB: u64 = BIT_U64!(19);
+pub const LOG_X25: u64 = BIT_U64!(20);
+pub const LOG_ISDN: u64 = BIT_U64!(21);
+pub const LOG_RT: u64 = BIT_U64!(22);
+pub const LOG_NSAP: u64 = BIT_U64!(23);
+pub const LOG_NSAPPTR: u64 = BIT_U64!(24);
+pub const LOG_SIG: u64 = BIT_U64!(25);
+pub const LOG_KEY: u64 = BIT_U64!(26);
+pub const LOG_PX: u64 = BIT_U64!(27);
+pub const LOG_GPOS: u64 = BIT_U64!(28);
+pub const LOG_AAAA: u64 = BIT_U64!(29);
+pub const LOG_LOC: u64 = BIT_U64!(30);
+pub const LOG_NXT: u64 = BIT_U64!(31);
+pub const LOG_SRV: u64 = BIT_U64!(32);
+pub const LOG_ATMA: u64 = BIT_U64!(33);
+pub const LOG_NAPTR: u64 = BIT_U64!(34);
+pub const LOG_KX: u64 = BIT_U64!(35);
+pub const LOG_CERT: u64 = BIT_U64!(36);
+pub const LOG_A6: u64 = BIT_U64!(37);
+pub const LOG_DNAME: u64 = BIT_U64!(38);
+pub const LOG_OPT: u64 = BIT_U64!(39);
+pub const LOG_APL: u64 = BIT_U64!(40);
+pub const LOG_DS: u64 = BIT_U64!(41);
+pub const LOG_SSHFP: u64 = BIT_U64!(42);
+pub const LOG_IPSECKEY: u64 = BIT_U64!(43);
+pub const LOG_RRSIG: u64 = BIT_U64!(44);
+pub const LOG_NSEC: u64 = BIT_U64!(45);
+pub const LOG_DNSKEY: u64 = BIT_U64!(46);
+pub const LOG_DHCID: u64 = BIT_U64!(47);
+pub const LOG_NSEC3: u64 = BIT_U64!(48);
+pub const LOG_NSEC3PARAM: u64 = BIT_U64!(49);
+pub const LOG_TLSA: u64 = BIT_U64!(50);
+pub const LOG_HIP: u64 = BIT_U64!(51);
+pub const LOG_CDS: u64 = BIT_U64!(52);
+pub const LOG_CDNSKEY: u64 = BIT_U64!(53);
+pub const LOG_SPF: u64 = BIT_U64!(54);
+pub const LOG_TKEY: u64 = BIT_U64!(55);
+pub const LOG_TSIG: u64 = BIT_U64!(56);
+pub const LOG_MAILA: u64 = BIT_U64!(57);
+pub const LOG_ANY: u64 = BIT_U64!(58);
+pub const LOG_URI: u64 = BIT_U64!(59);
+
+pub const LOG_FORMAT_GROUPED: u64 = BIT_U64!(60);
+pub const LOG_FORMAT_DETAILED: u64 = BIT_U64!(61);
+pub const LOG_HTTPS: u64 = BIT_U64!(62);
+
+fn dns_log_rrtype_enabled(rtype: u16, flags: u64) -> bool {
+ if flags == !0 {
+ return true;
+ }
+
+ match rtype {
+ DNS_RECORD_TYPE_A => {
+ return flags & LOG_A != 0;
+ }
+ DNS_RECORD_TYPE_NS => {
+ return flags & LOG_NS != 0;
+ }
+ DNS_RECORD_TYPE_MD => {
+ return flags & LOG_MD != 0;
+ }
+ DNS_RECORD_TYPE_MF => {
+ return flags & LOG_MF != 0;
+ }
+ DNS_RECORD_TYPE_CNAME => {
+ return flags & LOG_CNAME != 0;
+ }
+ DNS_RECORD_TYPE_SOA => {
+ return flags & LOG_SOA != 0;
+ }
+ DNS_RECORD_TYPE_MB => {
+ return flags & LOG_MB != 0;
+ }
+ DNS_RECORD_TYPE_MG => {
+ return flags & LOG_MG != 0;
+ }
+ DNS_RECORD_TYPE_MR => {
+ return flags & LOG_MR != 0;
+ }
+ DNS_RECORD_TYPE_NULL => {
+ return flags & LOG_NULL != 0;
+ }
+ DNS_RECORD_TYPE_WKS => {
+ return flags & LOG_WKS != 0;
+ }
+ DNS_RECORD_TYPE_PTR => {
+ return flags & LOG_PTR != 0;
+ }
+ DNS_RECORD_TYPE_HINFO => {
+ return flags & LOG_HINFO != 0;
+ }
+ DNS_RECORD_TYPE_MINFO => {
+ return flags & LOG_MINFO != 0;
+ }
+ DNS_RECORD_TYPE_MX => {
+ return flags & LOG_MX != 0;
+ }
+ DNS_RECORD_TYPE_TXT => {
+ return flags & LOG_TXT != 0;
+ }
+ DNS_RECORD_TYPE_RP => {
+ return flags & LOG_RP != 0;
+ }
+ DNS_RECORD_TYPE_AFSDB => {
+ return flags & LOG_AFSDB != 0;
+ }
+ DNS_RECORD_TYPE_X25 => {
+ return flags & LOG_X25 != 0;
+ }
+ DNS_RECORD_TYPE_ISDN => {
+ return flags & LOG_ISDN != 0;
+ }
+ DNS_RECORD_TYPE_RT => {
+ return flags & LOG_RT != 0;
+ }
+ DNS_RECORD_TYPE_NSAP => {
+ return flags & LOG_NSAP != 0;
+ }
+ DNS_RECORD_TYPE_NSAPPTR => {
+ return flags & LOG_NSAPPTR != 0;
+ }
+ DNS_RECORD_TYPE_SIG => {
+ return flags & LOG_SIG != 0;
+ }
+ DNS_RECORD_TYPE_KEY => {
+ return flags & LOG_KEY != 0;
+ }
+ DNS_RECORD_TYPE_PX => {
+ return flags & LOG_PX != 0;
+ }
+ DNS_RECORD_TYPE_GPOS => {
+ return flags & LOG_GPOS != 0;
+ }
+ DNS_RECORD_TYPE_AAAA => {
+ return flags & LOG_AAAA != 0;
+ }
+ DNS_RECORD_TYPE_LOC => {
+ return flags & LOG_LOC != 0;
+ }
+ DNS_RECORD_TYPE_NXT => {
+ return flags & LOG_NXT != 0;
+ }
+ DNS_RECORD_TYPE_SRV => {
+ return flags & LOG_SRV != 0;
+ }
+ DNS_RECORD_TYPE_ATMA => {
+ return flags & LOG_ATMA != 0;
+ }
+ DNS_RECORD_TYPE_NAPTR => {
+ return flags & LOG_NAPTR != 0;
+ }
+ DNS_RECORD_TYPE_KX => {
+ return flags & LOG_KX != 0;
+ }
+ DNS_RECORD_TYPE_CERT => {
+ return flags & LOG_CERT != 0;
+ }
+ DNS_RECORD_TYPE_A6 => {
+ return flags & LOG_A6 != 0;
+ }
+ DNS_RECORD_TYPE_DNAME => {
+ return flags & LOG_DNAME != 0;
+ }
+ DNS_RECORD_TYPE_OPT => {
+ return flags & LOG_OPT != 0;
+ }
+ DNS_RECORD_TYPE_APL => {
+ return flags & LOG_APL != 0;
+ }
+ DNS_RECORD_TYPE_DS => {
+ return flags & LOG_DS != 0;
+ }
+ DNS_RECORD_TYPE_SSHFP => {
+ return flags & LOG_SSHFP != 0;
+ }
+ DNS_RECORD_TYPE_IPSECKEY => {
+ return flags & LOG_IPSECKEY != 0;
+ }
+ DNS_RECORD_TYPE_RRSIG => {
+ return flags & LOG_RRSIG != 0;
+ }
+ DNS_RECORD_TYPE_NSEC => {
+ return flags & LOG_NSEC != 0;
+ }
+ DNS_RECORD_TYPE_DNSKEY => {
+ return flags & LOG_DNSKEY != 0;
+ }
+ DNS_RECORD_TYPE_DHCID => {
+ return flags & LOG_DHCID != 0;
+ }
+ DNS_RECORD_TYPE_NSEC3 => return flags & LOG_NSEC3 != 0,
+ DNS_RECORD_TYPE_NSEC3PARAM => {
+ return flags & LOG_NSEC3PARAM != 0;
+ }
+ DNS_RECORD_TYPE_TLSA => {
+ return flags & LOG_TLSA != 0;
+ }
+ DNS_RECORD_TYPE_HIP => {
+ return flags & LOG_HIP != 0;
+ }
+ DNS_RECORD_TYPE_CDS => {
+ return flags & LOG_CDS != 0;
+ }
+ DNS_RECORD_TYPE_CDNSKEY => {
+ return flags & LOG_CDNSKEY != 0;
+ }
+ DNS_RECORD_TYPE_HTTPS => {
+ return flags & LOG_HTTPS != 0;
+ }
+ DNS_RECORD_TYPE_SPF => {
+ return flags & LOG_SPF != 0;
+ }
+ DNS_RECORD_TYPE_TKEY => {
+ return flags & LOG_TKEY != 0;
+ }
+ DNS_RECORD_TYPE_TSIG => {
+ return flags & LOG_TSIG != 0;
+ }
+ DNS_RECORD_TYPE_MAILA => {
+ return flags & LOG_MAILA != 0;
+ }
+ DNS_RECORD_TYPE_ANY => {
+ return flags & LOG_ANY != 0;
+ }
+ DNS_RECORD_TYPE_URI => {
+ return flags & LOG_URI != 0;
+ }
+ _ => {
+ return false;
+ }
+ }
+}
+
+pub fn dns_rrtype_string(rrtype: u16) -> String {
+ match rrtype {
+ DNS_RECORD_TYPE_A => "A",
+ DNS_RECORD_TYPE_NS => "NS",
+ DNS_RECORD_TYPE_AAAA => "AAAA",
+ DNS_RECORD_TYPE_CNAME => "CNAME",
+ DNS_RECORD_TYPE_TXT => "TXT",
+ DNS_RECORD_TYPE_MX => "MX",
+ DNS_RECORD_TYPE_SOA => "SOA",
+ DNS_RECORD_TYPE_PTR => "PTR",
+ DNS_RECORD_TYPE_SIG => "SIG",
+ DNS_RECORD_TYPE_KEY => "KEY",
+ DNS_RECORD_TYPE_WKS => "WKS",
+ DNS_RECORD_TYPE_TKEY => "TKEY",
+ DNS_RECORD_TYPE_TSIG => "TSIG",
+ DNS_RECORD_TYPE_ANY => "ANY",
+ DNS_RECORD_TYPE_RRSIG => "RRSIG",
+ DNS_RECORD_TYPE_NSEC => "NSEC",
+ DNS_RECORD_TYPE_DNSKEY => "DNSKEY",
+ DNS_RECORD_TYPE_HINFO => "HINFO",
+ DNS_RECORD_TYPE_MINFO => "MINFO",
+ DNS_RECORD_TYPE_RP => "RP",
+ DNS_RECORD_TYPE_AFSDB => "AFSDB",
+ DNS_RECORD_TYPE_X25 => "X25",
+ DNS_RECORD_TYPE_ISDN => "ISDN",
+ DNS_RECORD_TYPE_RT => "RT",
+ DNS_RECORD_TYPE_NSAP => "NSAP",
+ DNS_RECORD_TYPE_NSAPPTR => "NSAPPT",
+ DNS_RECORD_TYPE_PX => "PX",
+ DNS_RECORD_TYPE_GPOS => "GPOS",
+ DNS_RECORD_TYPE_LOC => "LOC",
+ DNS_RECORD_TYPE_SRV => "SRV",
+ DNS_RECORD_TYPE_ATMA => "ATMA",
+ DNS_RECORD_TYPE_NAPTR => "NAPTR",
+ DNS_RECORD_TYPE_KX => "KX",
+ DNS_RECORD_TYPE_CERT => "CERT",
+ DNS_RECORD_TYPE_A6 => "A6",
+ DNS_RECORD_TYPE_DNAME => "DNAME",
+ DNS_RECORD_TYPE_OPT => "OPT",
+ DNS_RECORD_TYPE_APL => "APL",
+ DNS_RECORD_TYPE_DS => "DS",
+ DNS_RECORD_TYPE_SSHFP => "SSHFP",
+ DNS_RECORD_TYPE_IPSECKEY => "IPSECKEY",
+ DNS_RECORD_TYPE_DHCID => "DHCID",
+ DNS_RECORD_TYPE_NSEC3 => "NSEC3",
+ DNS_RECORD_TYPE_NSEC3PARAM => "NSEC3PARAM",
+ DNS_RECORD_TYPE_TLSA => "TLSA",
+ DNS_RECORD_TYPE_HIP => "HIP",
+ DNS_RECORD_TYPE_CDS => "CDS",
+ DNS_RECORD_TYPE_CDNSKEY => "CDSNKEY",
+ DNS_RECORD_TYPE_HTTPS => "HTTPS",
+ DNS_RECORD_TYPE_MAILA => "MAILA",
+ DNS_RECORD_TYPE_URI => "URI",
+ DNS_RECORD_TYPE_MB => "MB",
+ DNS_RECORD_TYPE_MG => "MG",
+ DNS_RECORD_TYPE_MR => "MR",
+ DNS_RECORD_TYPE_NULL => "NULL",
+ DNS_RECORD_TYPE_SPF => "SPF",
+ DNS_RECORD_TYPE_NXT => "NXT",
+ DNS_RECORD_TYPE_MD => "ND",
+ DNS_RECORD_TYPE_MF => "MF",
+ _ => {
+ return rrtype.to_string();
+ }
+ }
+ .to_string()
+}
+
+pub fn dns_rcode_string(flags: u16) -> String {
+ match flags & 0x000f {
+ DNS_RCODE_NOERROR => "NOERROR",
+ DNS_RCODE_FORMERR => "FORMERR",
+ DNS_RCODE_SERVFAIL => "SERVFAIL",
+ DNS_RCODE_NXDOMAIN => "NXDOMAIN",
+ DNS_RCODE_NOTIMP => "NOTIMP",
+ DNS_RCODE_REFUSED => "REFUSED",
+ DNS_RCODE_YXDOMAIN => "YXDOMAIN",
+ DNS_RCODE_YXRRSET => "YXRRSET",
+ DNS_RCODE_NXRRSET => "NXRRSET",
+ DNS_RCODE_NOTAUTH => "NOTAUTH",
+ DNS_RCODE_NOTZONE => "NOTZONE",
+ DNS_RCODE_BADVERS => "BADVERS/BADSIG",
+ DNS_RCODE_BADKEY => "BADKEY",
+ DNS_RCODE_BADTIME => "BADTIME",
+ DNS_RCODE_BADMODE => "BADMODE",
+ DNS_RCODE_BADNAME => "BADNAME",
+ DNS_RCODE_BADALG => "BADALG",
+ DNS_RCODE_BADTRUNC => "BADTRUNC",
+ _ => {
+ return (flags & 0x000f).to_string();
+ }
+ }
+ .to_string()
+}
+
+/// Format bytes as an IP address string.
+pub fn dns_print_addr(addr: &Vec<u8>) -> std::string::String {
+ if addr.len() == 4 {
+ return format!("{}.{}.{}.{}", addr[0], addr[1], addr[2], addr[3]);
+ } else if addr.len() == 16 {
+ return format!("{:02x}{:02x}:{:02x}{:02x}:{:02x}{:02x}:{:02x}{:02x}:{:02x}{:02x}:{:02x}{:02x}:{:02x}{:02x}:{:02x}{:02x}",
+ addr[0],
+ addr[1],
+ addr[2],
+ addr[3],
+ addr[4],
+ addr[5],
+ addr[6],
+ addr[7],
+ addr[8],
+ addr[9],
+ addr[10],
+ addr[11],
+ addr[12],
+ addr[13],
+ addr[14],
+ addr[15]);
+ } else {
+ return "".to_string();
+ }
+}
+
+/// Log SOA section fields.
+fn dns_log_soa(soa: &DNSRDataSOA) -> Result<JsonBuilder, JsonError> {
+ let mut js = JsonBuilder::try_new_object()?;
+
+ js.set_string_from_bytes("mname", &soa.mname)?;
+ js.set_string_from_bytes("rname", &soa.rname)?;
+ js.set_uint("serial", soa.serial as u64)?;
+ js.set_uint("refresh", soa.refresh as u64)?;
+ js.set_uint("retry", soa.retry as u64)?;
+ js.set_uint("expire", soa.expire as u64)?;
+ js.set_uint("minimum", soa.minimum as u64)?;
+
+ js.close()?;
+ return Ok(js);
+}
+
+/// Log SSHFP section fields.
+fn dns_log_sshfp(sshfp: &DNSRDataSSHFP) -> Result<JsonBuilder, JsonError> {
+ let mut js = JsonBuilder::try_new_object()?;
+
+ let mut hex = Vec::new();
+ for byte in &sshfp.fingerprint {
+ hex.push(format!("{:02x}", byte));
+ }
+
+ js.set_string("fingerprint", &hex.join(":"))?;
+ js.set_uint("algo", sshfp.algo as u64)?;
+ js.set_uint("type", sshfp.fp_type as u64)?;
+
+ js.close()?;
+ return Ok(js);
+}
+
+/// Log SRV section fields.
+fn dns_log_srv(srv: &DNSRDataSRV) -> Result<JsonBuilder, JsonError> {
+ let mut js = JsonBuilder::try_new_object()?;
+
+ js.set_uint("priority", srv.priority as u64)?;
+ js.set_uint("weight", srv.weight as u64)?;
+ js.set_uint("port", srv.port as u64)?;
+ js.set_string_from_bytes("name", &srv.target)?;
+
+ js.close()?;
+ return Ok(js);
+}
+
+fn dns_log_json_answer_detail(answer: &DNSAnswerEntry) -> Result<JsonBuilder, JsonError> {
+ let mut jsa = JsonBuilder::try_new_object()?;
+
+ jsa.set_string_from_bytes("rrname", &answer.name)?;
+ jsa.set_string("rrtype", &dns_rrtype_string(answer.rrtype))?;
+ jsa.set_uint("ttl", answer.ttl as u64)?;
+
+ match &answer.data {
+ DNSRData::A(addr) | DNSRData::AAAA(addr) => {
+ jsa.set_string("rdata", &dns_print_addr(addr))?;
+ }
+ DNSRData::CNAME(bytes)
+ | DNSRData::MX(bytes)
+ | DNSRData::NS(bytes)
+ | DNSRData::TXT(bytes)
+ | DNSRData::NULL(bytes)
+ | DNSRData::PTR(bytes) => {
+ jsa.set_string_from_bytes("rdata", bytes)?;
+ }
+ DNSRData::SOA(soa) => {
+ jsa.set_object("soa", &dns_log_soa(soa)?)?;
+ }
+ DNSRData::SSHFP(sshfp) => {
+ jsa.set_object("sshfp", &dns_log_sshfp(sshfp)?)?;
+ }
+ DNSRData::SRV(srv) => {
+ jsa.set_object("srv", &dns_log_srv(srv)?)?;
+ }
+ _ => {}
+ }
+
+ jsa.close()?;
+ return Ok(jsa);
+}
+
+fn dns_log_json_answer(
+ js: &mut JsonBuilder, response: &DNSResponse, flags: u64,
+) -> Result<(), JsonError> {
+ let header = &response.header;
+
+ js.set_uint("version", 2)?;
+ js.set_string("type", "answer")?;
+ js.set_uint("id", header.tx_id as u64)?;
+ js.set_string("flags", format!("{:x}", header.flags).as_str())?;
+ if header.flags & 0x8000 != 0 {
+ js.set_bool("qr", true)?;
+ }
+ if header.flags & 0x0400 != 0 {
+ js.set_bool("aa", true)?;
+ }
+ if header.flags & 0x0200 != 0 {
+ js.set_bool("tc", true)?;
+ }
+ if header.flags & 0x0100 != 0 {
+ js.set_bool("rd", true)?;
+ }
+ if header.flags & 0x0080 != 0 {
+ js.set_bool("ra", true)?;
+ }
+ if header.flags & 0x0040 != 0 {
+ js.set_bool("z", true)?;
+ }
+
+ let opcode = ((header.flags >> 11) & 0xf) as u8;
+ js.set_uint("opcode", opcode as u64)?;
+
+ if let Some(query) = response.queries.first() {
+ js.set_string_from_bytes("rrname", &query.name)?;
+ js.set_string("rrtype", &dns_rrtype_string(query.rrtype))?;
+ }
+ js.set_string("rcode", &dns_rcode_string(header.flags))?;
+
+ if !response.answers.is_empty() {
+ let mut js_answers = JsonBuilder::try_new_array()?;
+
+ // For grouped answers we use a HashMap keyed by the rrtype.
+ let mut answer_types = HashMap::new();
+
+ for answer in &response.answers {
+ if flags & LOG_FORMAT_GROUPED != 0 {
+ let type_string = dns_rrtype_string(answer.rrtype);
+ match &answer.data {
+ DNSRData::A(addr) | DNSRData::AAAA(addr) => {
+ if !answer_types.contains_key(&type_string) {
+ answer_types.insert(type_string.to_string(), JsonBuilder::try_new_array()?);
+ }
+ if let Some(a) = answer_types.get_mut(&type_string) {
+ a.append_string(&dns_print_addr(addr))?;
+ }
+ }
+ DNSRData::CNAME(bytes)
+ | DNSRData::MX(bytes)
+ | DNSRData::NS(bytes)
+ | DNSRData::TXT(bytes)
+ | DNSRData::NULL(bytes)
+ | DNSRData::PTR(bytes) => {
+ if !answer_types.contains_key(&type_string) {
+ answer_types.insert(type_string.to_string(), JsonBuilder::try_new_array()?);
+ }
+ if let Some(a) = answer_types.get_mut(&type_string) {
+ a.append_string_from_bytes(bytes)?;
+ }
+ }
+ DNSRData::SOA(soa) => {
+ if !answer_types.contains_key(&type_string) {
+ answer_types.insert(type_string.to_string(), JsonBuilder::try_new_array()?);
+ }
+ if let Some(a) = answer_types.get_mut(&type_string) {
+ a.append_object(&dns_log_soa(soa)?)?;
+ }
+ }
+ DNSRData::SSHFP(sshfp) => {
+ if !answer_types.contains_key(&type_string) {
+ answer_types.insert(type_string.to_string(), JsonBuilder::try_new_array()?);
+ }
+ if let Some(a) = answer_types.get_mut(&type_string) {
+ a.append_object(&dns_log_sshfp(sshfp)?)?;
+ }
+ }
+ DNSRData::SRV(srv) => {
+ if !answer_types.contains_key(&type_string) {
+ answer_types.insert(type_string.to_string(), JsonBuilder::try_new_array()?);
+ }
+ if let Some(a) = answer_types.get_mut(&type_string) {
+ a.append_object(&dns_log_srv(srv)?)?;
+ }
+ }
+ _ => {}
+ }
+ }
+
+ if flags & LOG_FORMAT_DETAILED != 0 {
+ js_answers.append_object(&dns_log_json_answer_detail(answer)?)?;
+ }
+ }
+
+ js_answers.close()?;
+
+ if flags & LOG_FORMAT_DETAILED != 0 {
+ js.set_object("answers", &js_answers)?;
+ }
+
+ if flags & LOG_FORMAT_GROUPED != 0 {
+ js.open_object("grouped")?;
+ for (k, mut v) in answer_types.drain() {
+ v.close()?;
+ js.set_object(&k, &v)?;
+ }
+ js.close()?;
+ }
+ }
+
+ if !response.authorities.is_empty() {
+ js.open_array("authorities")?;
+ for auth in &response.authorities {
+ let auth_detail = dns_log_json_answer_detail(auth)?;
+ js.append_object(&auth_detail)?;
+ }
+ js.close()?;
+ }
+
+ Ok(())
+}
+
+fn dns_log_query(
+ tx: &mut DNSTransaction, i: u16, flags: u64, jb: &mut JsonBuilder,
+) -> Result<bool, JsonError> {
+ let index = i as usize;
+ if let Some(request) = &tx.request {
+ if index < request.queries.len() {
+ let query = &request.queries[index];
+ if dns_log_rrtype_enabled(query.rrtype, flags) {
+ jb.set_string("type", "query")?;
+ jb.set_uint("id", request.header.tx_id as u64)?;
+ jb.set_string_from_bytes("rrname", &query.name)?;
+ jb.set_string("rrtype", &dns_rrtype_string(query.rrtype))?;
+ jb.set_uint("tx_id", tx.id - 1)?;
+ if request.header.flags & 0x0040 != 0 {
+ jb.set_bool("z", true)?;
+ }
+ let opcode = ((request.header.flags >> 11) & 0xf) as u8;
+ jb.set_uint("opcode", opcode as u64)?;
+ return Ok(true);
+ }
+ }
+ }
+
+ return Ok(false);
+}
+
+#[no_mangle]
+pub extern "C" fn rs_dns_log_json_query(
+ tx: &mut DNSTransaction, i: u16, flags: u64, jb: &mut JsonBuilder,
+) -> bool {
+ match dns_log_query(tx, i, flags, jb) {
+ Ok(false) | Err(_) => {
+ return false;
+ }
+ Ok(true) => {
+ return true;
+ }
+ }
+}
+
+#[no_mangle]
+pub extern "C" fn rs_dns_log_json_answer(
+ tx: &mut DNSTransaction, flags: u64, js: &mut JsonBuilder,
+) -> bool {
+ if let Some(response) = &tx.response {
+ for query in &response.queries {
+ if dns_log_rrtype_enabled(query.rrtype, flags) {
+ return dns_log_json_answer(js, response, flags).is_ok();
+ }
+ }
+ }
+ return false;
+}
+
+#[no_mangle]
+pub extern "C" fn rs_dns_do_log_answer(tx: &mut DNSTransaction, flags: u64) -> bool {
+ if let Some(response) = &tx.response {
+ for query in &response.queries {
+ if dns_log_rrtype_enabled(query.rrtype, flags) {
+ return true;
+ }
+ }
+ }
+ return false;
+}
diff --git a/rust/src/dns/lua.rs b/rust/src/dns/lua.rs
new file mode 100644
index 0000000..b9935f8
--- /dev/null
+++ b/rust/src/dns/lua.rs
@@ -0,0 +1,234 @@
+/* Copyright (C) 2017 Open Information Security Foundation
+ *
+ * You can copy, redistribute or modify this Program under the terms of
+ * the GNU General Public License version 2 as published by the Free
+ * Software Foundation.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * version 2 along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301, USA.
+ */
+
+use std::os::raw::c_int;
+
+use crate::dns::dns::*;
+use crate::dns::log::*;
+use crate::lua::*;
+
+#[no_mangle]
+pub extern "C" fn rs_dns_lua_get_tx_id(clua: &mut CLuaState, tx: &mut DNSTransaction) {
+ let lua = LuaState { lua: clua };
+
+ lua.pushinteger(tx.tx_id() as i64);
+}
+
+#[no_mangle]
+pub extern "C" fn rs_dns_lua_get_rrname(clua: &mut CLuaState, tx: &mut DNSTransaction) -> c_int {
+ let lua = LuaState { lua: clua };
+
+ if let Some(request) = &tx.request {
+ if let Some(query) = request.queries.first() {
+ lua.pushstring(&String::from_utf8_lossy(&query.name));
+ return 1;
+ }
+ } else if let Some(response) = &tx.response {
+ if let Some(query) = response.queries.first() {
+ lua.pushstring(&String::from_utf8_lossy(&query.name));
+ return 1;
+ }
+ }
+
+ return 0;
+}
+
+#[no_mangle]
+pub extern "C" fn rs_dns_lua_get_rcode(clua: &mut CLuaState, tx: &mut DNSTransaction) -> c_int {
+ let lua = LuaState { lua: clua };
+
+ let rcode = tx.rcode();
+ if rcode > 0 {
+ lua.pushstring(&dns_rcode_string(rcode));
+ return 1;
+ }
+
+ return 0;
+}
+
+#[no_mangle]
+pub extern "C" fn rs_dns_lua_get_query_table(
+ clua: &mut CLuaState, tx: &mut DNSTransaction,
+) -> c_int {
+ let lua = LuaState { lua: clua };
+
+ let mut i: i64 = 0;
+
+ // Create table now to be consistent with C that always returns
+ // table even in the absence of any authorities.
+ lua.newtable();
+
+ // We first look in the request for queries. However, if there is
+ // no request, check the response for queries.
+ if let Some(request) = &tx.request {
+ for query in &request.queries {
+ lua.pushinteger(i);
+ i += 1;
+
+ lua.newtable();
+
+ lua.pushstring("type");
+ lua.pushstring(&dns_rrtype_string(query.rrtype));
+ lua.settable(-3);
+
+ lua.pushstring("rrname");
+ lua.pushstring(&String::from_utf8_lossy(&query.name));
+ lua.settable(-3);
+
+ lua.settable(-3);
+ }
+ } else if let Some(response) = &tx.response {
+ for query in &response.queries {
+ lua.pushinteger(i);
+ i += 1;
+
+ lua.newtable();
+
+ lua.pushstring("type");
+ lua.pushstring(&dns_rrtype_string(query.rrtype));
+ lua.settable(-3);
+
+ lua.pushstring("rrname");
+ lua.pushstring(&String::from_utf8_lossy(&query.name));
+ lua.settable(-3);
+
+ lua.settable(-3);
+ }
+ }
+
+ // Again, always return 1 to be consistent with C, even if the
+ // table is empty.
+ return 1;
+}
+
+#[no_mangle]
+pub extern "C" fn rs_dns_lua_get_answer_table(
+ clua: &mut CLuaState, tx: &mut DNSTransaction,
+) -> c_int {
+ let lua = LuaState { lua: clua };
+
+ let mut i: i64 = 0;
+
+ // Create table now to be consistent with C that always returns
+ // table even in the absence of any authorities.
+ lua.newtable();
+
+ if let Some(response) = &tx.response {
+ for answer in &response.answers {
+ lua.pushinteger(i);
+ i += 1;
+
+ lua.newtable();
+ lua.pushstring("type");
+ lua.pushstring(&dns_rrtype_string(answer.rrtype));
+ lua.settable(-3);
+
+ lua.pushstring("ttl");
+ lua.pushinteger(answer.ttl as i64);
+ lua.settable(-3);
+
+ lua.pushstring("rrname");
+ lua.pushstring(&String::from_utf8_lossy(&answer.name));
+ lua.settable(-3);
+
+ // All rdata types are pushed to "addr" for backwards compatibility
+ match answer.data {
+ DNSRData::A(ref bytes) | DNSRData::AAAA(ref bytes) => {
+ if !bytes.is_empty() {
+ lua.pushstring("addr");
+ lua.pushstring(&dns_print_addr(bytes));
+ lua.settable(-3);
+ }
+ }
+ DNSRData::CNAME(ref bytes)
+ | DNSRData::MX(ref bytes)
+ | DNSRData::NS(ref bytes)
+ | DNSRData::TXT(ref bytes)
+ | DNSRData::NULL(ref bytes)
+ | DNSRData::PTR(ref bytes)
+ | DNSRData::Unknown(ref bytes) => {
+ if !bytes.is_empty() {
+ lua.pushstring("addr");
+ lua.pushstring(&String::from_utf8_lossy(bytes));
+ lua.settable(-3);
+ }
+ }
+ DNSRData::SOA(ref soa) => {
+ if !soa.mname.is_empty() {
+ lua.pushstring("addr");
+ lua.pushstring(&String::from_utf8_lossy(&soa.mname));
+ lua.settable(-3);
+ }
+ }
+ DNSRData::SSHFP(ref sshfp) => {
+ lua.pushstring("addr");
+ lua.pushstring(&String::from_utf8_lossy(&sshfp.fingerprint));
+ lua.settable(-3);
+ }
+ DNSRData::SRV(ref srv) => {
+ lua.pushstring("addr");
+ lua.pushstring(&String::from_utf8_lossy(&srv.target));
+ lua.settable(-3);
+ }
+ }
+ lua.settable(-3);
+ }
+ }
+
+ // Again, always return 1 to be consistent with C, even if the
+ // table is empty.
+ return 1;
+}
+
+#[no_mangle]
+pub extern "C" fn rs_dns_lua_get_authority_table(
+ clua: &mut CLuaState, tx: &mut DNSTransaction,
+) -> c_int {
+ let lua = LuaState { lua: clua };
+
+ let mut i: i64 = 0;
+
+ // Create table now to be consistent with C that always returns
+ // table even in the absence of any authorities.
+ lua.newtable();
+
+ if let Some(response) = &tx.response {
+ for answer in &response.authorities {
+ lua.pushinteger(i);
+ i += 1;
+
+ lua.newtable();
+ lua.pushstring("type");
+ lua.pushstring(&dns_rrtype_string(answer.rrtype));
+ lua.settable(-3);
+
+ lua.pushstring("ttl");
+ lua.pushinteger(answer.ttl as i64);
+ lua.settable(-3);
+
+ lua.pushstring("rrname");
+ lua.pushstring(&String::from_utf8_lossy(&answer.name));
+ lua.settable(-3);
+
+ lua.settable(-3);
+ }
+ }
+
+ // Again, always return 1 to be consistent with C, even if the
+ // table is empty.
+ return 1;
+}
diff --git a/rust/src/dns/mod.rs b/rust/src/dns/mod.rs
new file mode 100644
index 0000000..b0ca00f
--- /dev/null
+++ b/rust/src/dns/mod.rs
@@ -0,0 +1,26 @@
+/* Copyright (C) 2017 Open Information Security Foundation
+ *
+ * You can copy, redistribute or modify this Program under the terms of
+ * the GNU General Public License version 2 as published by the Free
+ * Software Foundation.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * version 2 along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301, USA.
+ */
+
+//! DNS parser, detection, logger and application layer module.
+
+pub mod detect;
+pub mod dns;
+pub mod log;
+pub mod parser;
+
+#[cfg(feature = "lua")]
+pub mod lua;
diff --git a/rust/src/dns/parser.rs b/rust/src/dns/parser.rs
new file mode 100644
index 0000000..a1d97a5
--- /dev/null
+++ b/rust/src/dns/parser.rs
@@ -0,0 +1,851 @@
+/* Copyright (C) 2017 Open Information Security Foundation
+ *
+ * You can copy, redistribute or modify this Program under the terms of
+ * the GNU General Public License version 2 as published by the Free
+ * Software Foundation.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * version 2 along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301, USA.
+ */
+
+//! Nom parsers for DNS.
+
+use crate::dns::dns::*;
+use nom7::combinator::{complete, rest};
+use nom7::error::ErrorKind;
+use nom7::multi::{count, length_data, many_m_n};
+use nom7::number::streaming::{be_u16, be_u32, be_u8};
+use nom7::{error_position, Err, IResult};
+
+// Parse a DNS header.
+pub fn dns_parse_header(i: &[u8]) -> IResult<&[u8], DNSHeader> {
+ let (i, tx_id) = be_u16(i)?;
+ let (i, flags) = be_u16(i)?;
+ let (i, questions) = be_u16(i)?;
+ let (i, answer_rr) = be_u16(i)?;
+ let (i, authority_rr) = be_u16(i)?;
+ let (i, additional_rr) = be_u16(i)?;
+ Ok((
+ i,
+ DNSHeader {
+ tx_id,
+ flags,
+ questions,
+ answer_rr,
+ authority_rr,
+ additional_rr,
+ },
+ ))
+}
+
+/// Parse a DNS name.
+///
+/// Parameters:
+/// start: the start of the name
+/// message: the complete message that start is a part of with the DNS header
+pub fn dns_parse_name<'b>(start: &'b [u8], message: &'b [u8]) -> IResult<&'b [u8], Vec<u8>> {
+ let mut pos = start;
+ let mut pivot = start;
+ let mut name: Vec<u8> = Vec::with_capacity(32);
+ let mut count = 0;
+
+ loop {
+ if pos.is_empty() {
+ break;
+ }
+
+ let len = pos[0];
+
+ if len == 0x00 {
+ pos = &pos[1..];
+ break;
+ } else if len & 0b1100_0000 == 0 {
+ let (rem, label) = length_data(be_u8)(pos)?;
+ if !name.is_empty() {
+ name.push(b'.');
+ }
+ name.extend(label);
+ pos = rem;
+ } else if len & 0b1100_0000 == 0b1100_0000 {
+ let (rem, leader) = be_u16(pos)?;
+ let offset = usize::from(leader) & 0x3fff;
+ if offset > message.len() {
+ return Err(Err::Error(error_position!(pos, ErrorKind::OctDigit)));
+ }
+ pos = &message[offset..];
+ if pivot == start {
+ pivot = rem;
+ }
+ } else {
+ return Err(Err::Error(error_position!(pos, ErrorKind::OctDigit)));
+ }
+
+ // Return error if we've looped a certain number of times.
+ count += 1;
+ if count > 255 {
+ return Err(Err::Error(error_position!(pos, ErrorKind::OctDigit)));
+ }
+ }
+
+ // If we followed a pointer we return the position after the first
+ // pointer followed. Is there a better way to see if these slices
+ // diverged from each other? A straight up comparison would
+ // actually check the contents.
+ if pivot.len() != start.len() {
+ return Ok((pivot, name));
+ }
+ return Ok((pos, name));
+}
+
+/// Parse answer entries.
+///
+/// In keeping with the C implementation, answer values that can
+/// contain multiple answers get expanded into their own answer
+/// records. An example of this is a TXT record with multiple strings
+/// in it - each string will be expanded to its own answer record.
+///
+/// This function could be a made a whole lot simpler if we logged a
+/// multi-string TXT entry as a single quote string, similar to the
+/// output of dig. Something to consider for a future version.
+fn dns_parse_answer<'a>(
+ slice: &'a [u8], message: &'a [u8], count: usize,
+) -> IResult<&'a [u8], Vec<DNSAnswerEntry>> {
+ let mut answers = Vec::new();
+ let mut input = slice;
+
+ struct Answer<'a> {
+ name: Vec<u8>,
+ rrtype: u16,
+ rrclass: u16,
+ ttl: u32,
+ data: &'a [u8],
+ }
+
+ fn subparser<'a>(i: &'a [u8], message: &'a [u8]) -> IResult<&'a [u8], Answer<'a>> {
+ let (i, name) = dns_parse_name(i, message)?;
+ let (i, rrtype) = be_u16(i)?;
+ let (i, rrclass) = be_u16(i)?;
+ let (i, ttl) = be_u32(i)?;
+ let (i, data) = length_data(be_u16)(i)?;
+ let answer = Answer {
+ name,
+ rrtype,
+ rrclass,
+ ttl,
+ data,
+ };
+ Ok((i, answer))
+ }
+
+ for _ in 0..count {
+ match subparser(input, message) {
+ Ok((rem, val)) => {
+ let n = match val.rrtype {
+ DNS_RECORD_TYPE_TXT => {
+ // For TXT records we need to run the parser
+ // multiple times. Set n high, to the maximum
+ // value based on a max txt side of 65535, but
+ // taking into considering that strings need
+ // to be quoted, so half that.
+ 32767
+ }
+ _ => {
+ // For all other types we only want to run the
+ // parser once, so set n to 1.
+ 1
+ }
+ };
+ let result: IResult<&'a [u8], Vec<DNSRData>> =
+ many_m_n(1, n, complete(|b| dns_parse_rdata(b, message, val.rrtype)))(val.data);
+ match result {
+ Ok((_, rdatas)) => {
+ for rdata in rdatas {
+ answers.push(DNSAnswerEntry {
+ name: val.name.clone(),
+ rrtype: val.rrtype,
+ rrclass: val.rrclass,
+ ttl: val.ttl,
+ data: rdata,
+ });
+ }
+ }
+ Err(e) => {
+ return Err(e);
+ }
+ }
+ input = rem;
+ }
+ Err(e) => {
+ return Err(e);
+ }
+ }
+ }
+
+ return Ok((input, answers));
+}
+
+pub fn dns_parse_response_body<'a>(
+ i: &'a [u8], message: &'a [u8], header: DNSHeader,
+) -> IResult<&'a [u8], DNSResponse> {
+ let (i, queries) = count(|b| dns_parse_query(b, message), header.questions as usize)(i)?;
+ let (i, answers) = dns_parse_answer(i, message, header.answer_rr as usize)?;
+ let (i, authorities) = dns_parse_answer(i, message, header.authority_rr as usize)?;
+ Ok((
+ i,
+ DNSResponse {
+ header,
+ queries,
+ answers,
+ authorities,
+ },
+ ))
+}
+
+/// Parse a single DNS query.
+///
+/// Arguments are suitable for using with call!:
+///
+/// call!(complete_dns_message_buffer)
+pub fn dns_parse_query<'a>(input: &'a [u8], message: &'a [u8]) -> IResult<&'a [u8], DNSQueryEntry> {
+ let i = input;
+ let (i, name) = dns_parse_name(i, message)?;
+ let (i, rrtype) = be_u16(i)?;
+ let (i, rrclass) = be_u16(i)?;
+ Ok((
+ i,
+ DNSQueryEntry {
+ name,
+ rrtype,
+ rrclass,
+ },
+ ))
+}
+
+fn dns_parse_rdata_a(input: &[u8]) -> IResult<&[u8], DNSRData> {
+ rest(input).map(|(input, data)| (input, DNSRData::A(data.to_vec())))
+}
+
+fn dns_parse_rdata_aaaa(input: &[u8]) -> IResult<&[u8], DNSRData> {
+ rest(input).map(|(input, data)| (input, DNSRData::AAAA(data.to_vec())))
+}
+
+fn dns_parse_rdata_cname<'a>(input: &'a [u8], message: &'a [u8]) -> IResult<&'a [u8], DNSRData> {
+ dns_parse_name(input, message).map(|(input, name)| (input, DNSRData::CNAME(name)))
+}
+
+fn dns_parse_rdata_ns<'a>(input: &'a [u8], message: &'a [u8]) -> IResult<&'a [u8], DNSRData> {
+ dns_parse_name(input, message).map(|(input, name)| (input, DNSRData::NS(name)))
+}
+
+fn dns_parse_rdata_ptr<'a>(input: &'a [u8], message: &'a [u8]) -> IResult<&'a [u8], DNSRData> {
+ dns_parse_name(input, message).map(|(input, name)| (input, DNSRData::PTR(name)))
+}
+
+fn dns_parse_rdata_soa<'a>(input: &'a [u8], message: &'a [u8]) -> IResult<&'a [u8], DNSRData> {
+ let i = input;
+ let (i, mname) = dns_parse_name(i, message)?;
+ let (i, rname) = dns_parse_name(i, message)?;
+ let (i, serial) = be_u32(i)?;
+ let (i, refresh) = be_u32(i)?;
+ let (i, retry) = be_u32(i)?;
+ let (i, expire) = be_u32(i)?;
+ let (i, minimum) = be_u32(i)?;
+ Ok((
+ i,
+ DNSRData::SOA(DNSRDataSOA {
+ mname,
+ rname,
+ serial,
+ refresh,
+ retry,
+ expire,
+ minimum,
+ }),
+ ))
+}
+
+fn dns_parse_rdata_mx<'a>(input: &'a [u8], message: &'a [u8]) -> IResult<&'a [u8], DNSRData> {
+ // For MX we skip over the preference field before
+ // parsing out the name.
+ let (i, _) = be_u16(input)?;
+ let (i, name) = dns_parse_name(i, message)?;
+ Ok((i, DNSRData::MX(name)))
+}
+
+fn dns_parse_rdata_srv<'a>(input: &'a [u8], message: &'a [u8]) -> IResult<&'a [u8], DNSRData> {
+ let i = input;
+ let (i, priority) = be_u16(i)?;
+ let (i, weight) = be_u16(i)?;
+ let (i, port) = be_u16(i)?;
+ let (i, target) = dns_parse_name(i, message)?;
+ Ok((
+ i,
+ DNSRData::SRV(DNSRDataSRV {
+ priority,
+ weight,
+ port,
+ target,
+ }),
+ ))
+}
+
+fn dns_parse_rdata_txt(input: &[u8]) -> IResult<&[u8], DNSRData> {
+ let (i, txt) = length_data(be_u8)(input)?;
+ Ok((i, DNSRData::TXT(txt.to_vec())))
+}
+
+fn dns_parse_rdata_null(input: &[u8]) -> IResult<&[u8], DNSRData> {
+ rest(input).map(|(input, data)| (input, DNSRData::NULL(data.to_vec())))
+}
+
+fn dns_parse_rdata_sshfp(input: &[u8]) -> IResult<&[u8], DNSRData> {
+ let i = input;
+ let (i, algo) = be_u8(i)?;
+ let (i, fp_type) = be_u8(i)?;
+ let fingerprint = i;
+ Ok((
+ &[],
+ DNSRData::SSHFP(DNSRDataSSHFP {
+ algo,
+ fp_type,
+ fingerprint: fingerprint.to_vec(),
+ }),
+ ))
+}
+
+fn dns_parse_rdata_unknown(input: &[u8]) -> IResult<&[u8], DNSRData> {
+ rest(input).map(|(input, data)| (input, DNSRData::Unknown(data.to_vec())))
+}
+
+pub fn dns_parse_rdata<'a>(
+ input: &'a [u8], message: &'a [u8], rrtype: u16,
+) -> IResult<&'a [u8], DNSRData> {
+ match rrtype {
+ DNS_RECORD_TYPE_A => dns_parse_rdata_a(input),
+ DNS_RECORD_TYPE_AAAA => dns_parse_rdata_aaaa(input),
+ DNS_RECORD_TYPE_CNAME => dns_parse_rdata_cname(input, message),
+ DNS_RECORD_TYPE_PTR => dns_parse_rdata_ptr(input, message),
+ DNS_RECORD_TYPE_SOA => dns_parse_rdata_soa(input, message),
+ DNS_RECORD_TYPE_MX => dns_parse_rdata_mx(input, message),
+ DNS_RECORD_TYPE_NS => dns_parse_rdata_ns(input, message),
+ DNS_RECORD_TYPE_TXT => dns_parse_rdata_txt(input),
+ DNS_RECORD_TYPE_NULL => dns_parse_rdata_null(input),
+ DNS_RECORD_TYPE_SSHFP => dns_parse_rdata_sshfp(input),
+ DNS_RECORD_TYPE_SRV => dns_parse_rdata_srv(input, message),
+ _ => dns_parse_rdata_unknown(input),
+ }
+}
+
+/// Parse a DNS request.
+pub fn dns_parse_request(input: &[u8]) -> IResult<&[u8], DNSRequest> {
+ let i = input;
+ let (i, header) = dns_parse_header(i)?;
+ dns_parse_request_body(i, input, header)
+}
+
+pub fn dns_parse_request_body<'a>(
+ input: &'a [u8], message: &'a [u8], header: DNSHeader,
+) -> IResult<&'a [u8], DNSRequest> {
+ let i = input;
+ let (i, queries) = count(|b| dns_parse_query(b, message), header.questions as usize)(i)?;
+ Ok((i, DNSRequest { header, queries }))
+}
+
+#[cfg(test)]
+mod tests {
+
+ use crate::dns::dns::{DNSAnswerEntry, DNSHeader};
+ use crate::dns::parser::*;
+
+ /// Parse a simple name with no pointers.
+ #[test]
+ fn test_dns_parse_name() {
+ let buf: &[u8] = &[
+ 0x09, 0x63, /* .......c */
+ 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x2d, 0x63, 0x66, /* lient-cf */
+ 0x07, 0x64, 0x72, 0x6f, 0x70, 0x62, 0x6f, 0x78, /* .dropbox */
+ 0x03, 0x63, 0x6f, 0x6d, 0x00, 0x00, 0x01, 0x00, /* .com.... */
+ ];
+ let expected_remainder: &[u8] = &[0x00, 0x01, 0x00];
+ let (remainder, name) = dns_parse_name(buf, buf).unwrap();
+ assert_eq!("client-cf.dropbox.com".as_bytes(), &name[..]);
+ assert_eq!(remainder, expected_remainder);
+ }
+
+ /// Test parsing a name with pointers.
+ #[test]
+ fn test_dns_parse_name_with_pointer() {
+ let buf: &[u8] = &[
+ 0xd8, 0xcb, 0x8a, 0xed, 0xa1, 0x46, 0x00, 0x15, /* 0 - .....F.. */
+ 0x17, 0x0d, 0x06, 0xf7, 0x08, 0x00, 0x45, 0x00, /* 8 - ......E. */
+ 0x00, 0x7b, 0x71, 0x6e, 0x00, 0x00, 0x39, 0x11, /* 16 - .{qn..9. */
+ 0xf4, 0xd9, 0x08, 0x08, 0x08, 0x08, 0x0a, 0x10, /* 24 - ........ */
+ 0x01, 0x0b, 0x00, 0x35, 0xe1, 0x8e, 0x00, 0x67, /* 32 - ...5...g */
+ 0x60, 0x00, 0xef, 0x08, 0x81, 0x80, 0x00, 0x01, /* 40 - `....... */
+ 0x00, 0x03, 0x00, 0x00, 0x00, 0x01, 0x03, 0x77, /* 48 - .......w */
+ 0x77, 0x77, 0x0c, 0x73, 0x75, 0x72, 0x69, 0x63, /* 56 - ww.suric */
+ 0x61, 0x74, 0x61, 0x2d, 0x69, 0x64, 0x73, 0x03, /* 64 - ata-ids. */
+ 0x6f, 0x72, 0x67, 0x00, 0x00, 0x01, 0x00, 0x01, /* 72 - org..... */
+ 0xc0, 0x0c, 0x00, 0x05, 0x00, 0x01, 0x00, 0x00, /* 80 - ........ */
+ 0x0e, 0x0f, 0x00, 0x02, 0xc0, 0x10, 0xc0, 0x10, /* 88 - ........ */
+ 0x00, 0x01, 0x00, 0x01, 0x00, 0x00, 0x01, 0x2b, /* 96 - .......+ */
+ 0x00, 0x04, 0xc0, 0x00, 0x4e, 0x19, 0xc0, 0x10, /* 104 - ....N... */
+ 0x00, 0x01, 0x00, 0x01, 0x00, 0x00, 0x01, 0x2b, /* 112 - .......+ */
+ 0x00, 0x04, 0xc0, 0x00, 0x4e, 0x18, 0x00, 0x00, /* 120 - ....N... */
+ 0x29, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 128 - )....... */
+ 0x00, /* 136 - . */
+ ];
+
+ // The DNS payload starts at offset 42.
+ let message = &buf[42..];
+
+ // The name at offset 54 is the complete name.
+ let start1 = &buf[54..];
+ let res1 = dns_parse_name(start1, message);
+ assert_eq!(
+ res1,
+ Ok((&start1[22..], "www.suricata-ids.org".as_bytes().to_vec()))
+ );
+
+ // The second name starts at offset 80, but is just a pointer
+ // to the first.
+ let start2 = &buf[80..];
+ let res2 = dns_parse_name(start2, message);
+ assert_eq!(
+ res2,
+ Ok((&start2[2..], "www.suricata-ids.org".as_bytes().to_vec()))
+ );
+
+ // The third name starts at offset 94, but is a pointer to a
+ // portion of the first.
+ let start3 = &buf[94..];
+ let res3 = dns_parse_name(start3, message);
+ assert_eq!(
+ res3,
+ Ok((&start3[2..], "suricata-ids.org".as_bytes().to_vec()))
+ );
+
+ // The fourth name starts at offset 110, but is a pointer to a
+ // portion of the first.
+ let start4 = &buf[110..];
+ let res4 = dns_parse_name(start4, message);
+ assert_eq!(
+ res4,
+ Ok((&start4[2..], "suricata-ids.org".as_bytes().to_vec()))
+ );
+ }
+
+ #[test]
+ fn test_dns_parse_name_double_pointer() {
+ let buf: &[u8] = &[
+ 0xd8, 0xcb, 0x8a, 0xed, 0xa1, 0x46, 0x00, 0x15, /* 0: .....F.. */
+ 0x17, 0x0d, 0x06, 0xf7, 0x08, 0x00, 0x45, 0x00, /* 8: ......E. */
+ 0x00, 0x66, 0x5e, 0x20, 0x40, 0x00, 0x40, 0x11, /* 16: .f^ @.@. */
+ 0xc6, 0x3b, 0x0a, 0x10, 0x01, 0x01, 0x0a, 0x10, /* 24: .;...... */
+ 0x01, 0x0b, 0x00, 0x35, 0xc2, 0x21, 0x00, 0x52, /* 32: ...5.!.R */
+ 0x35, 0xc5, 0x0d, 0x4f, 0x81, 0x80, 0x00, 0x01, /* 40: 5..O.... */
+ 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x05, 0x62, /* 48: .......b */
+ 0x6c, 0x6f, 0x63, 0x6b, 0x07, 0x64, 0x72, 0x6f, /* 56: lock.dro */
+ 0x70, 0x62, 0x6f, 0x78, 0x03, 0x63, 0x6f, 0x6d, /* 64: pbox.com */
+ 0x00, 0x00, 0x01, 0x00, 0x01, 0xc0, 0x0c, 0x00, /* 72: ........ */
+ 0x05, 0x00, 0x01, 0x00, 0x00, 0x00, 0x09, 0x00, /* 80: ........ */
+ 0x0b, 0x05, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x02, /* 88: ..block. */
+ 0x67, 0x31, 0xc0, 0x12, 0xc0, 0x2f, 0x00, 0x01, /* 96: g1.../.. */
+ 0x00, 0x01, 0x00, 0x00, 0x00, 0x08, 0x00, 0x04, /* 104: ........ */
+ 0x2d, 0x3a, 0x46, 0x21, /* 112: -:F! */
+ ];
+
+ // The start of the DNS message in the above packet.
+ let message: &[u8] = &buf[42..];
+
+ // The start of the name we want to parse, 0xc0 0x2f, a
+ // pointer to offset 47 in the message (or 89 in the full
+ // packet).
+ let start: &[u8] = &buf[100..];
+
+ let res = dns_parse_name(start, message);
+ assert_eq!(
+ res,
+ Ok((&start[2..], "block.g1.dropbox.com".as_bytes().to_vec()))
+ );
+ }
+
+ #[test]
+ fn test_dns_parse_request() {
+ // DNS request from dig-a-www.suricata-ids.org.pcap.
+ let pkt: &[u8] = &[
+ 0x8d, 0x32, 0x01, 0x20, 0x00, 0x01, /* ...2. .. */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x03, 0x77, /* .......w */
+ 0x77, 0x77, 0x0c, 0x73, 0x75, 0x72, 0x69, 0x63, /* ww.suric */
+ 0x61, 0x74, 0x61, 0x2d, 0x69, 0x64, 0x73, 0x03, /* ata-ids. */
+ 0x6f, 0x72, 0x67, 0x00, 0x00, 0x01, 0x00, 0x01, /* org..... */
+ 0x00, 0x00, 0x29, 0x10, 0x00, 0x00, 0x00, 0x00, /* ..)..... */
+ 0x00, 0x00, 0x00, /* ... */
+ ];
+
+ let res = dns_parse_request(pkt);
+ match res {
+ Ok((rem, request)) => {
+ // For now we have some remainder data as there is an
+ // additional record type we don't parse yet.
+ assert!(!rem.is_empty());
+
+ assert_eq!(
+ request.header,
+ DNSHeader {
+ tx_id: 0x8d32,
+ flags: 0x0120,
+ questions: 1,
+ answer_rr: 0,
+ authority_rr: 0,
+ additional_rr: 1,
+ }
+ );
+
+ assert_eq!(request.queries.len(), 1);
+
+ let query = &request.queries[0];
+ assert_eq!(query.name, "www.suricata-ids.org".as_bytes().to_vec());
+ assert_eq!(query.rrtype, 1);
+ assert_eq!(query.rrclass, 1);
+ }
+ _ => {
+ assert!(false);
+ }
+ }
+ }
+
+ /// Parse a DNS response.
+ fn dns_parse_response(message: &[u8]) -> IResult<&[u8], DNSResponse> {
+ let i = message;
+ let (i, header) = dns_parse_header(i)?;
+ dns_parse_response_body(i, message, header)
+ }
+
+ #[test]
+ fn test_dns_parse_response() {
+ // DNS response from dig-a-www.suricata-ids.org.pcap.
+ let pkt: &[u8] = &[
+ 0x8d, 0x32, 0x81, 0xa0, 0x00, 0x01, /* ...2.... */
+ 0x00, 0x03, 0x00, 0x00, 0x00, 0x00, 0x03, 0x77, /* .......w */
+ 0x77, 0x77, 0x0c, 0x73, 0x75, 0x72, 0x69, 0x63, /* ww.suric */
+ 0x61, 0x74, 0x61, 0x2d, 0x69, 0x64, 0x73, 0x03, /* ata-ids. */
+ 0x6f, 0x72, 0x67, 0x00, 0x00, 0x01, 0x00, 0x01, /* org..... */
+ 0xc0, 0x0c, 0x00, 0x05, 0x00, 0x01, 0x00, 0x00, /* ........ */
+ 0x0d, 0xd8, 0x00, 0x12, 0x0c, 0x73, 0x75, 0x72, /* .....sur */
+ 0x69, 0x63, 0x61, 0x74, 0x61, 0x2d, 0x69, 0x64, /* icata-id */
+ 0x73, 0x03, 0x6f, 0x72, 0x67, 0x00, 0xc0, 0x32, /* s.org..2 */
+ 0x00, 0x01, 0x00, 0x01, 0x00, 0x00, 0x00, 0xf4, /* ........ */
+ 0x00, 0x04, 0xc0, 0x00, 0x4e, 0x18, 0xc0, 0x32, /* ....N..2 */
+ 0x00, 0x01, 0x00, 0x01, 0x00, 0x00, 0x00, 0xf4, /* ........ */
+ 0x00, 0x04, 0xc0, 0x00, 0x4e, 0x19, /* ....N. */
+ ];
+
+ let res = dns_parse_response(pkt);
+ match res {
+ Ok((rem, response)) => {
+ // The response should be full parsed.
+ assert_eq!(rem.len(), 0);
+
+ assert_eq!(
+ response.header,
+ DNSHeader {
+ tx_id: 0x8d32,
+ flags: 0x81a0,
+ questions: 1,
+ answer_rr: 3,
+ authority_rr: 0,
+ additional_rr: 0,
+ }
+ );
+
+ assert_eq!(response.answers.len(), 3);
+
+ let answer1 = &response.answers[0];
+ assert_eq!(answer1.name, "www.suricata-ids.org".as_bytes().to_vec());
+ assert_eq!(answer1.rrtype, 5);
+ assert_eq!(answer1.rrclass, 1);
+ assert_eq!(answer1.ttl, 3544);
+ assert_eq!(
+ answer1.data,
+ DNSRData::CNAME("suricata-ids.org".as_bytes().to_vec())
+ );
+
+ let answer2 = &response.answers[1];
+ assert_eq!(
+ answer2,
+ &DNSAnswerEntry {
+ name: "suricata-ids.org".as_bytes().to_vec(),
+ rrtype: 1,
+ rrclass: 1,
+ ttl: 244,
+ data: DNSRData::A([192, 0, 78, 24].to_vec()),
+ }
+ );
+
+ let answer3 = &response.answers[2];
+ assert_eq!(
+ answer3,
+ &DNSAnswerEntry {
+ name: "suricata-ids.org".as_bytes().to_vec(),
+ rrtype: 1,
+ rrclass: 1,
+ ttl: 244,
+ data: DNSRData::A([192, 0, 78, 25].to_vec()),
+ }
+ )
+ }
+ _ => {
+ assert!(false);
+ }
+ }
+ }
+
+ #[test]
+ fn test_dns_parse_response_nxdomain_soa() {
+ // DNS response with an SOA authority record from
+ // dns-udp-nxdomain-soa.pcap.
+ let pkt: &[u8] = &[
+ 0x82, 0x95, 0x81, 0x83, 0x00, 0x01, /* j....... */
+ 0x00, 0x00, 0x00, 0x01, 0x00, 0x01, 0x03, 0x64, /* .......d */
+ 0x6e, 0x65, 0x04, 0x6f, 0x69, 0x73, 0x66, 0x03, /* ne.oisf. */
+ 0x6e, 0x65, 0x74, 0x00, 0x00, 0x01, 0x00, 0x01, /* net..... */
+ 0xc0, 0x10, 0x00, 0x06, 0x00, 0x01, 0x00, 0x00, /* ........ */
+ 0x03, 0x83, 0x00, 0x45, 0x06, 0x6e, 0x73, 0x2d, /* ...E.ns- */
+ 0x31, 0x31, 0x30, 0x09, 0x61, 0x77, 0x73, 0x64, /* 110.awsd */
+ 0x6e, 0x73, 0x2d, 0x31, 0x33, 0x03, 0x63, 0x6f, /* ns-13.co */
+ 0x6d, 0x00, 0x11, 0x61, 0x77, 0x73, 0x64, 0x6e, /* m..awsdn */
+ 0x73, 0x2d, 0x68, 0x6f, 0x73, 0x74, 0x6d, 0x61, /* s-hostma */
+ 0x73, 0x74, 0x65, 0x72, 0x06, 0x61, 0x6d, 0x61, /* ster.ama */
+ 0x7a, 0x6f, 0x6e, 0xc0, 0x3b, 0x00, 0x00, 0x00, /* zon.;... */
+ 0x01, 0x00, 0x00, 0x1c, 0x20, 0x00, 0x00, 0x03, /* .... ... */
+ 0x84, 0x00, 0x12, 0x75, 0x00, 0x00, 0x01, 0x51, /* ...u...Q */
+ 0x80, 0x00, 0x00, 0x29, 0x02, 0x00, 0x00, 0x00, /* ...).... */
+ 0x00, 0x00, 0x00, 0x00, /* .... */
+ ];
+
+ let res = dns_parse_response(pkt);
+ match res {
+ Ok((rem, response)) => {
+ // For now we have some remainder data as there is an
+ // additional record type we don't parse yet.
+ assert!(!rem.is_empty());
+
+ assert_eq!(
+ response.header,
+ DNSHeader {
+ tx_id: 0x8295,
+ flags: 0x8183,
+ questions: 1,
+ answer_rr: 0,
+ authority_rr: 1,
+ additional_rr: 1,
+ }
+ );
+
+ assert_eq!(response.authorities.len(), 1);
+
+ let authority = &response.authorities[0];
+ assert_eq!(authority.name, "oisf.net".as_bytes().to_vec());
+ assert_eq!(authority.rrtype, 6);
+ assert_eq!(authority.rrclass, 1);
+ assert_eq!(authority.ttl, 899);
+ assert_eq!(
+ authority.data,
+ DNSRData::SOA(DNSRDataSOA {
+ mname: "ns-110.awsdns-13.com".as_bytes().to_vec(),
+ rname: "awsdns-hostmaster.amazon.com".as_bytes().to_vec(),
+ serial: 1,
+ refresh: 7200,
+ retry: 900,
+ expire: 1209600,
+ minimum: 86400,
+ })
+ );
+ }
+ _ => {
+ assert!(false);
+ }
+ }
+ }
+
+ #[test]
+ fn test_dns_parse_response_null() {
+ // DNS response with a NULL record from
+ // https://redmine.openinfosecfoundation.org/attachments/2062
+
+ let pkt: &[u8] = &[
+ 0x12, 0xb0, 0x84, 0x00, 0x00, 0x01, 0x00, 0x01, /* ........ */
+ 0x00, 0x00, 0x00, 0x00, 0x0b, 0x76, 0x61, 0x61, /* .....vaa */
+ 0x61, 0x61, 0x6b, 0x61, 0x72, 0x64, 0x6c, 0x69, /* aakardli */
+ 0x06, 0x70, 0x69, 0x72, 0x61, 0x74, 0x65, 0x03, /* .pirate. */
+ 0x73, 0x65, 0x61, 0x00, 0x00, 0x0a, 0x00, 0x01, /* sea..... */
+ 0xc0, 0x0c, 0x00, 0x0a, 0x00, 0x01, 0x00, 0x00, /* ........ */
+ 0x00, 0x00, 0x00, 0x09, 0x56, 0x41, 0x43, 0x4b, /* ....VACK */
+ 0x44, 0x03, 0xc5, 0xe9, 0x01, /* D.... */
+ ];
+
+ let res = dns_parse_response(pkt);
+ match res {
+ Ok((rem, response)) => {
+ // The response should be fully parsed.
+ assert_eq!(rem.len(), 0);
+
+ assert_eq!(
+ response.header,
+ DNSHeader {
+ tx_id: 0x12b0,
+ flags: 0x8400,
+ questions: 1,
+ answer_rr: 1,
+ authority_rr: 0,
+ additional_rr: 0,
+ }
+ );
+
+ assert_eq!(response.queries.len(), 1);
+ let query = &response.queries[0];
+ assert_eq!(query.name, "vaaaakardli.pirate.sea".as_bytes().to_vec());
+ assert_eq!(query.rrtype, DNS_RECORD_TYPE_NULL);
+ assert_eq!(query.rrclass, 1);
+
+ assert_eq!(response.answers.len(), 1);
+
+ let answer = &response.answers[0];
+ assert_eq!(answer.name, "vaaaakardli.pirate.sea".as_bytes().to_vec());
+ assert_eq!(answer.rrtype, DNS_RECORD_TYPE_NULL);
+ assert_eq!(answer.rrclass, 1);
+ assert_eq!(answer.ttl, 0);
+ assert_eq!(
+ answer.data,
+ DNSRData::NULL(vec![
+ 0x56, 0x41, 0x43, 0x4b, /* VACK */
+ 0x44, 0x03, 0xc5, 0xe9, 0x01, /* D.... */
+ ])
+ );
+ }
+ _ => {
+ assert!(false);
+ }
+ }
+ }
+
+ #[test]
+ fn test_dns_parse_rdata_sshfp() {
+ // Dummy data since we don't have a pcap sample.
+ let data: &[u8] = &[
+ // algo: DSS
+ 0x02, // fp_type: SHA-1
+ 0x01, // fingerprint: 123456789abcdef67890123456789abcdef67890
+ 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf6, 0x78, 0x90, 0x12, 0x34, 0x56, 0x78,
+ 0x9a, 0xbc, 0xde, 0xf6, 0x78, 0x90,
+ ];
+
+ let res = dns_parse_rdata_sshfp(data);
+ match res {
+ Ok((rem, rdata)) => {
+ // The data should be fully parsed.
+ assert_eq!(rem.len(), 0);
+
+ match rdata {
+ DNSRData::SSHFP(sshfp) => {
+ assert_eq!(sshfp.algo, 2);
+ assert_eq!(sshfp.fp_type, 1);
+ assert_eq!(sshfp.fingerprint, &data[2..]);
+ }
+ _ => {
+ assert!(false);
+ }
+ }
+ }
+ _ => {
+ assert!(false);
+ }
+ }
+ }
+
+ #[test]
+ fn test_dns_parse_rdata_srv() {
+ /* ; <<>> DiG 9.11.5-P4-5.1+deb10u2-Debian <<>> _sip._udp.sip.voice.google.com SRV
+ ;; global options: +cmd
+ ;; Got answer:
+ ;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 1524
+ ;; flags: qr rd ra; QUERY: 1, ANSWER: 2, AUTHORITY: 0, ADDITIONAL: 3
+
+ [...]
+
+ ;; ANSWER SECTION:
+ _sip._udp.sip.voice.google.com. 300 IN SRV 10 1 5060 sip-anycast-1.voice.google.com.
+ _sip._udp.sip.voice.google.com. 300 IN SRV 20 1 5060 sip-anycast-2.voice.google.com.
+
+ [...]
+
+ ;; Query time: 72 msec
+ ;; MSG SIZE rcvd: 191 */
+
+ let pkt: &[u8] = &[
+ 0xeb, 0x56, 0x81, 0x80, 0x00, 0x01, 0x00, 0x02, 0x00, 0x00, 0x00, 0x01, 0x04, 0x5f,
+ 0x73, 0x69, 0x70, 0x04, 0x5f, 0x75, 0x64, 0x70, 0x03, 0x73, 0x69, 0x70, 0x05, 0x76,
+ 0x6f, 0x69, 0x63, 0x65, 0x06, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x03, 0x63, 0x6f,
+ 0x6d, 0x00, 0x00, 0x21, 0x00, 0x01, 0xc0, 0x0c, 0x00, 0x21, 0x00, 0x01, 0x00, 0x00,
+ 0x01, 0x13, 0x00, 0x26, 0x00, 0x14, 0x00, 0x01, 0x13, 0xc4, 0x0d, 0x73, 0x69, 0x70,
+ 0x2d, 0x61, 0x6e, 0x79, 0x63, 0x61, 0x73, 0x74, 0x2d, 0x32, 0x05, 0x76, 0x6f, 0x69,
+ 0x63, 0x65, 0x06, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x03, 0x63, 0x6f, 0x6d, 0x00,
+ 0xc0, 0x0c, 0x00, 0x21, 0x00, 0x01, 0x00, 0x00, 0x01, 0x13, 0x00, 0x26, 0x00, 0x0a,
+ 0x00, 0x01, 0x13, 0xc4, 0x0d, 0x73, 0x69, 0x70, 0x2d, 0x61, 0x6e, 0x79, 0x63, 0x61,
+ 0x73, 0x74, 0x2d, 0x31, 0x05, 0x76, 0x6f, 0x69, 0x63, 0x65, 0x06, 0x67, 0x6f, 0x6f,
+ 0x67, 0x6c, 0x65, 0x03, 0x63, 0x6f, 0x6d, 0x00,
+ ];
+
+ let res = dns_parse_response(pkt);
+ match res {
+ Ok((rem, response)) => {
+ // The data should be fully parsed.
+ assert_eq!(rem.len(), 0);
+
+ assert_eq!(response.answers.len(), 2);
+
+ let answer1 = &response.answers[0];
+ match &answer1.data {
+ DNSRData::SRV(srv) => {
+ assert_eq!(srv.priority, 20);
+ assert_eq!(srv.weight, 1);
+ assert_eq!(srv.port, 5060);
+ assert_eq!(
+ srv.target,
+ "sip-anycast-2.voice.google.com".as_bytes().to_vec()
+ );
+ }
+ _ => {
+ assert!(false);
+ }
+ }
+ let answer2 = &response.answers[1];
+ match &answer2.data {
+ DNSRData::SRV(srv) => {
+ assert_eq!(srv.priority, 10);
+ assert_eq!(srv.weight, 1);
+ assert_eq!(srv.port, 5060);
+ assert_eq!(
+ srv.target,
+ "sip-anycast-1.voice.google.com".as_bytes().to_vec()
+ );
+ }
+ _ => {
+ assert!(false);
+ }
+ }
+ }
+ _ => {
+ assert!(false);
+ }
+ }
+ }
+}