Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

dns: add dns.rcode keyword v3 #10126

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
165 changes: 165 additions & 0 deletions rust/src/dns/detect.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,12 @@ pub struct DetectDnsOpcode {
opcode: u8,
}

#[derive(Debug, PartialEq, Eq)]
pub struct DetectDnsRcode {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We should reuse DetectUintData<u8> cf #10087 (comment)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It was suggested here #10087 (comment) that I can use simple u8 till the code is in working condition. I can change it to DetectUintData<u8> in the next PR I create.

negate: bool,
rcode: u8,
}

/// Parse a DNS opcode argument returning the code and if it is to be
/// negated or not.
///
Expand Down Expand Up @@ -53,6 +59,33 @@ fn parse_opcode(opcode: &str) -> Result<DetectDnsOpcode, ()> {
Err(())
}

/// Parse a DNS rcode 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_rcode(rcode: &str) -> Result<DetectDnsRcode, ()> {
let mut negated = false;
for (i, c) in rcode.chars().enumerate() {
match c {
' ' | '\t' => {
continue;
}
'!' => {
negated = true;
}
_ => {
let code: u8 = rcode[i..].parse().map_err(|_| ())?;
return Ok(DetectDnsRcode {
negate: negated,
rcode: code,
});
}
}
}
Err(())
}

/// Perform the DNS opcode match.
///
/// 1 will be returned on match, otherwise 0 will be returned.
Expand Down Expand Up @@ -80,6 +113,33 @@ pub extern "C" fn rs_dns_opcode_match(
match_opcode(detect, header_flags).into()
}

/// Perform the DNS rcode match.
///
/// 1 will be returned on match, otherwise 0 will be returned.
#[no_mangle]
pub extern "C" fn rs_dns_rcode_match(
tx: &mut DNSTransaction, detect: &mut DetectDnsRcode, 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_rcode(detect, header_flags).into()
}

fn match_opcode(detect: &DetectDnsOpcode, flags: u16) -> bool {
let opcode = ((flags >> 11) & 0xf) as u8;
if detect.negate {
Expand All @@ -89,6 +149,15 @@ fn match_opcode(detect: &DetectDnsOpcode, flags: u16) -> bool {
}
}

fn match_rcode(detect: &DetectDnsRcode, flags: u16) -> bool {
let rcode = (flags & 0xf) as u8;
if detect.negate {
detect.rcode != rcode
} else {
detect.rcode == rcode
}
}

#[no_mangle]
pub unsafe extern "C" fn rs_detect_dns_opcode_parse(carg: *const c_char) -> *mut c_void {
if carg.is_null() {
Expand All @@ -107,13 +176,38 @@ pub unsafe extern "C" fn rs_detect_dns_opcode_parse(carg: *const c_char) -> *mut
}
}

#[no_mangle]
pub unsafe extern "C" fn rs_detect_dns_rcode_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_rcode(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));
}
}

#[no_mangle]
pub unsafe extern "C" fn rs_dns_detect_rcode_free(ptr: *mut c_void) {
if !ptr.is_null() {
std::mem::drop(Box::from_raw(ptr as *mut DetectDnsRcode));
}
}

#[cfg(test)]
mod test {
use super::*;
Expand Down Expand Up @@ -154,6 +248,42 @@ mod test {
assert_eq!(parse_opcode("!asdf"), Err(()));
}

#[test]
fn parse_rcode_good() {
assert_eq!(
parse_rcode("1"),
Ok(DetectDnsRcode {
negate: false,
rcode: 1
})
);
assert_eq!(
parse_rcode("123"),
Ok(DetectDnsRcode {
negate: false,
rcode: 123
})
);
assert_eq!(
parse_rcode("!123"),
Ok(DetectDnsRcode {
negate: true,
rcode: 123
})
);
assert_eq!(
parse_rcode("!123"),
Ok(DetectDnsRcode {
negate: true,
rcode: 123
})
);
assert_eq!(parse_rcode(""), Err(()));
assert_eq!(parse_rcode("!"), Err(()));
assert_eq!(parse_rcode("! "), Err(()));
assert_eq!(parse_rcode("!asdf"), Err(()));
}

#[test]
fn test_match_opcode() {
assert!(match_opcode(
Expand Down Expand Up @@ -188,4 +318,39 @@ mod test {
0b0010_0000_0000_0000,
));
}

#[test]
fn test_match_rcode() {
assert!(match_rcode(
&DetectDnsRcode {
negate: false,
rcode: 0,
},
0b0000_0000_0000_0000,
));

assert!(!match_rcode(
&DetectDnsRcode {
negate: true,
rcode: 0,
},
0b0000_0000_0000_0000,
));

assert!(match_rcode(
&DetectDnsRcode {
negate: false,
rcode: 4,
},
0b0000_0000_0000_0100,
));

assert!(!match_rcode(
&DetectDnsRcode {
negate: true,
rcode: 4,
},
0b0000_0000_0000_0100,
));
}
}
2 changes: 2 additions & 0 deletions src/Makefile.am
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,7 @@ noinst_HEADERS = \
detect-dnp3.h \
detect-dns-answer-name.h \
detect-dns-opcode.h \
detect-dns-rcode.h \
detect-dns-query.h \
detect-dns-query-name.h \
detect-dsize.h \
Expand Down Expand Up @@ -739,6 +740,7 @@ libsuricata_c_a_SOURCES = \
detect-dnp3.c \
detect-dns-answer-name.c \
detect-dns-opcode.c \
detect-dns-rcode.c \
detect-dns-query.c \
detect-dns-query-name.c \
detect-dsize.c \
Expand Down
87 changes: 87 additions & 0 deletions src/detect-dns-rcode.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
/* Copyright (C) 2024 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.
*/

#include "suricata-common.h"

#include "detect-parse.h"
#include "detect-engine.h"
#include "detect-dns-rcode.h"
#include "rust.h"

static int dns_rcode_list_id = 0;

static void DetectDnsRcodeFree(DetectEngineCtx *, void *ptr);

static int DetectDnsRcodeSetup(DetectEngineCtx *de_ctx, Signature *s, const char *str)
{
SCEnter();

if (DetectSignatureSetAppProto(s, ALPROTO_DNS) != 0) {
return -1;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: SCReturnInt(-1);

currently use of the macro is inconsistent in this function

}

void *detect = rs_detect_dns_rcode_parse(str);
if (detect == NULL) {
SCLogError("failed to parse dns.rcode: %s", str);
return -1;
}

if (SigMatchAppendSMToList(
de_ctx, s, DETECT_AL_DNS_RCODE, (SigMatchCtx *)detect, dns_rcode_list_id) == NULL) {
goto error;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

minor: since we have only one error path after detect was allocated, we can call DetectDnsRcodeFree and return here, instead of using a goto.

}

SCReturnInt(0);

error:
DetectDnsRcodeFree(de_ctx, detect);
SCReturnInt(-1);
}

static void DetectDnsRcodeFree(DetectEngineCtx *de_ctx, void *ptr)
{
SCEnter();
if (ptr != NULL) {
rs_dns_detect_rcode_free(ptr);
}
SCReturn;
}

static int DetectDnsRcodeMatch(DetectEngineThreadCtx *det_ctx, Flow *f, uint8_t flags, void *state,
void *txv, const Signature *s, const SigMatchCtx *ctx)
{
return rs_dns_rcode_match(txv, (void *)ctx, flags);
}

void DetectDnsRcodeRegister(void)
{
sigmatch_table[DETECT_AL_DNS_RCODE].name = "dns.rcode";
sigmatch_table[DETECT_AL_DNS_RCODE].desc = "Match the DNS header rcode flag.";
sigmatch_table[DETECT_AL_DNS_RCODE].url = "/rules/dns-keywords.html#dns-rcode";
sigmatch_table[DETECT_AL_DNS_RCODE].Setup = DetectDnsRcodeSetup;
sigmatch_table[DETECT_AL_DNS_RCODE].Free = DetectDnsRcodeFree;
sigmatch_table[DETECT_AL_DNS_RCODE].Match = NULL;
sigmatch_table[DETECT_AL_DNS_RCODE].AppLayerTxMatch = DetectDnsRcodeMatch;

DetectAppLayerInspectEngineRegister(
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should remove this line with SIG_FLAG_TOSERVER because dns.rcode is only to client

Copy link
Contributor Author

@hadiqaalamdar hadiqaalamdar Jan 9, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

will do, thanks!

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'd keep it. While answers should only be seen in the to client direction as well, we do allow detection on them in the to server direction as they are allowed by the message format.

Likewise, the rcode field is also there in the to server direction, and at some point may be of interest to detect on in that direction.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Likewise, the rcode field is also there in the to server direction

Wireshark does not show it :-/

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not in the break down, no, but the bits are still there. I agree its somewhat non-sensical, but Suricata is here to find the non-sensical.

Note: The major DNS servers don't seem to care if an rcode is set on a request.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Makes sense.

By the way, the pcap in SV test seems to have an extended rcode cf dns.resp.ext_rcode == 0x00 Wireshark filter

"dns.rcode", ALPROTO_DNS, SIG_FLAG_TOSERVER, 0, DetectEngineInspectGenericList, NULL);

DetectAppLayerInspectEngineRegister(
"dns.rcode", ALPROTO_DNS, SIG_FLAG_TOCLIENT, 0, DetectEngineInspectGenericList, NULL);

dns_rcode_list_id = DetectBufferTypeGetByName("dns.rcode");
}
23 changes: 23 additions & 0 deletions src/detect-dns-rcode.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
/* Copyright (C) 2024 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.
*/

#ifndef __DETECT_DNS_RCODE_H__
#define __DETECT_DNS_RCODE_H__

void DetectDnsRcodeRegister(void);

#endif /* __DETECT_DNS_RCODE_H__ */
2 changes: 2 additions & 0 deletions src/detect-engine-register.c
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@
#include "detect-engine-payload.h"
#include "detect-engine-dcepayload.h"
#include "detect-dns-opcode.h"
#include "detect-dns-rcode.h"
#include "detect-dns-query.h"
#include "detect-dns-answer-name.h"
#include "detect-dns-query-name.h"
Expand Down Expand Up @@ -520,6 +521,7 @@ void SigTableSetup(void)

DetectDnsQueryRegister();
DetectDnsOpcodeRegister();
DetectDnsRcodeRegister();
DetectDnsAnswerNameRegister();
DetectDnsQueryNameRegister();
DetectModbusRegister();
Expand Down
1 change: 1 addition & 0 deletions src/detect-engine-register.h
Original file line number Diff line number Diff line change
Expand Up @@ -229,6 +229,7 @@ enum DetectKeywordId {

DETECT_AL_DNS_QUERY,
DETECT_AL_DNS_OPCODE,
DETECT_AL_DNS_RCODE,
DETECT_AL_DNS_ANSWER_NAME,
DETECT_AL_DNS_QUERY_NAME,
DETECT_AL_TLS_SNI,
Expand Down
Loading