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

detect: add vlan.id keyword - v9 #12360

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
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
1 change: 1 addition & 0 deletions doc/userguide/rules/index.rst
Original file line number Diff line number Diff line change
Expand Up @@ -49,3 +49,4 @@ Suricata Rules
differences-from-snort
multi-buffer-matching
tag
vlan-keywords
125 changes: 125 additions & 0 deletions doc/userguide/rules/vlan-keywords.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
VLAN Keywords
=============

.. role:: example-rule-action
.. role:: example-rule-header
.. role:: example-rule-options
.. role:: example-rule-emphasis

vlan.id
-------

Suricata has a ``vlan.id`` keyword that can be used in signatures to identify
and filter network packets based on Virtual Local Area Network IDs. By default,
it matches all layers if a packet contains multiple VLAN layers. However, if a
specific layer is defined, it will only match that layer.

Syntax::

vlan.id: [op]id[,layer];

The id can be matched exactly, or compared using the ``op`` setting::

vlan.id:300 # exactly 300
vlan.id:<300,0 # smaller than 300 at layer 0
vlan.id:>=200,1 # greater or equal than 200 at layer 1

vlan.id uses :ref:`unsigned 16-bit integer <rules-integer-keywords>`.

The valid range for VLAN id values is ``1 - 4094``.

This keyword also supports ``all`` and ``any`` as arguments for ``layer``.
``all`` matches only if all VLAN layers match and ``any`` matches with any layer.

.. table:: **Layer values for vlan.id keyword**

=============== ================================================
Value Description
=============== ================================================
[default] Match with any layer
0 - 2 Match specific layer
``-3`` - ``-1`` Match specific layer with back to front indexing
all Match only if all layers match
any Match with any layer
=============== ================================================

This small illustration shows how indexing works for vlan.id::

[ethernet]
[vlan 666 (index 0 and -2)]
[vlan 123 (index 1 and -1)]
[ipv4]
[udp]

Examples
^^^^^^^^

Example of a signature that would alert if any of the VLAN IDs is equal to 300:

.. container:: example-rule

alert ip any any -> any any (msg:"Vlan ID is equal to 300"; :example-rule-emphasis:`vlan.id:300;` sid:1;)

Example of a signature that would alert if the VLAN ID at layer 1 is equal to 300:

.. container:: example-rule

alert ip any any -> any any (msg:"Vlan ID is equal to 300 at layer 1"; :example-rule-emphasis:`vlan.id:300,1;` sid:1;)

Example of a signature that would alert if the VLAN ID at the last layer is equal to 400:

.. container:: example-rule

alert ip any any -> any any (msg:"Vlan ID is equal to 400 at the last layer"; :example-rule-emphasis:`vlan.id:400,-1;` sid:1;)

Example of a signature that would alert only if all the VLAN IDs are greater than 100:

.. container:: example-rule

alert ip any any -> any any (msg:"All Vlan IDs are greater than 100"; :example-rule-emphasis:`vlan.id:>100,all;` sid:1;)

It is also possible to use the vlan.id content as a fast_pattern by using the ``prefilter`` keyword, as shown in the following example.

.. container:: example-rule

alert ip any any -> any any (msg:"Vlan ID is equal to 200 at layer 1"; :example-rule-emphasis:`vlan.id:200,1; prefilter;` sid:1;)

vlan.layers
-----------

Matches based on the number of layers.

Syntax::

vlan.id: [op]number;
AkakiAlice marked this conversation as resolved.
Show resolved Hide resolved

It can be matched exactly, or compared using the ``op`` setting::

vlan.layer:3 # exactly 3 vlan layers
AkakiAlice marked this conversation as resolved.
Show resolved Hide resolved
vlan.layer:<3 # less than 3 vlan layers
vlan.layer:>=2 # more or equal to 2 vlan layers

vlan.layer uses :ref:`unsigned 8-bit integer <rules-integer-keywords>`.

The minimum and maximum values that vlan.layers can be are ``0`` and ``3``.

Examples
^^^^^^^^

Example of a signature that would alert if a packet has 0 VLAN layers:

.. container:: example-rule

alert ip any any -> any any (msg:"Packet has 0 vlan layers"; :example-rule-emphasis:`vlan.id:0;` sid:1;)
AkakiAlice marked this conversation as resolved.
Show resolved Hide resolved

Example of a signature that would alert if a packet has more than 1 VLAN layers:

.. container:: example-rule

alert ip any any -> any any (msg:"Packet more than 1 vlan layer"; :example-rule-emphasis:`vlan.id:>1;` sid:1;)

It is also possible to use the vlan.layer content as a fast_pattern by using the ``prefilter`` keyword, as shown in the following example.

.. container:: example-rule

alert ip any any -> any any (msg:"Packet has 2 vlan layers"; :example-rule-emphasis:`vlan.id:2; prefilter;` sid:1;)
27 changes: 15 additions & 12 deletions rust/src/detect/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,11 +24,12 @@ pub mod iprep;
pub mod parser;
pub mod requires;
pub mod stream_size;
pub mod tojson;
pub mod transform_base64;
pub mod transforms;
pub mod uint;
pub mod uri;
pub mod tojson;
pub mod vlan;

use crate::core::AppProto;
use std::os::raw::{c_int, c_void};
Expand All @@ -37,7 +38,9 @@ use std::os::raw::{c_int, c_void};
/// derive StringEnum.
pub trait EnumString<T> {
/// Return the enum variant of the given numeric value.
fn from_u(v: T) -> Option<Self> where Self: Sized;
fn from_u(v: T) -> Option<Self>
Copy link
Contributor

Choose a reason for hiding this comment

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

Maybe we should rustfmt this file into its own commit

where
Self: Sized;

/// Convert the enum variant to the numeric value.
fn into_u(self) -> T;
Expand All @@ -46,7 +49,9 @@ pub trait EnumString<T> {
fn to_str(&self) -> &'static str;

/// Get an enum variant from parsing a string.
fn from_str(s: &str) -> Option<Self> where Self: Sized;
fn from_str(s: &str) -> Option<Self>
where
Self: Sized;
}

#[repr(C)]
Expand Down Expand Up @@ -80,7 +85,7 @@ pub(crate) const SIGMATCH_QUOTES_MANDATORY: u16 = 0x40; // BIT_U16(6) in detect.
pub(crate) const SIGMATCH_INFO_STICKY_BUFFER: u16 = 0x200; // BIT_U16(9)

/// cbindgen:ignore
extern {
extern "C" {
pub fn DetectBufferSetActiveList(de: *mut c_void, s: *mut c_void, bufid: c_int) -> c_int;
pub fn DetectHelperGetData(
de: *mut c_void, transforms: *const c_void, flow: *const c_void, flow_flags: u8,
Expand Down Expand Up @@ -109,13 +114,8 @@ extern {
) -> *mut c_void;
// in detect-engine-helper.h
pub fn DetectHelperGetMultiData(
de: *mut c_void,
transforms: *const c_void,
flow: *const c_void,
flow_flags: u8,
tx: *const c_void,
list_id: c_int,
local_id: u32,
de: *mut c_void, transforms: *const c_void, flow: *const c_void, flow_flags: u8,
tx: *const c_void, list_id: c_int, local_id: u32,
get_buf: unsafe extern "C" fn(*const c_void, u8, u32, *mut *const u8, *mut u32) -> bool,
) -> *mut c_void;
pub fn DetectHelperMultiBufferMpmRegister(
Expand Down Expand Up @@ -194,6 +194,9 @@ mod test {
assert_eq!(TestEnum::BestValueEver.to_str(), "best_value_ever");
assert_eq!(TestEnum::from_str("zero"), Some(TestEnum::Zero));
assert_eq!(TestEnum::from_str("nope"), None);
assert_eq!(TestEnum::from_str("best_value_ever"), Some(TestEnum::BestValueEver));
assert_eq!(
TestEnum::from_str("best_value_ever"),
Some(TestEnum::BestValueEver)
);
}
}
195 changes: 195 additions & 0 deletions rust/src/detect/vlan.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,195 @@
/* 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.
*/

use super::uint::{detect_parse_uint, DetectUintData};
use std::ffi::CStr;
use std::str::FromStr;

pub const DETECT_VLAN_ID_ANY: i8 = i8::MIN;
pub const DETECT_VLAN_ID_ALL: i8 = i8::MAX;
pub static VLAN_MAX_LAYERS: u16 = 3;
AkakiAlice marked this conversation as resolved.
Show resolved Hide resolved
pub static VLAN_MAX_LAYER_IDX: i8 = 2;

#[repr(C)]
#[derive(Debug, PartialEq)]
pub struct DetectVlanIdData {
pub du16: DetectUintData<u16>, // vlan id
pub layer: i8, // vlan layer
Copy link
Contributor

Choose a reason for hiding this comment

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

I think Victor wants more a comment explaining, that this can be DETECT_VLAN_ID_ANY or DETECT_VLAN_ID_ALL or negative index to match from the end...

}

pub fn detect_parse_vlan_id(s: &str) -> Option<DetectVlanIdData> {
let parts: Vec<&str> = s.split(',').collect();
let du16 = detect_parse_uint(parts[0]).ok()?.1;
if parts.len() > 2 {
return None;
}
if du16.arg1 >= 0xFFF || du16.arg2 >= 0xFFF {
// vlan id is encoded on 12 bits
return None;
}
let layer = if parts.len() == 2 {
if parts[1] == "all" {
DETECT_VLAN_ID_ALL
} else if parts[1] == "any" {
DETECT_VLAN_ID_ANY
} else {
let u8_layer = i8::from_str(parts[1]).ok()?;
if !(-3..=VLAN_MAX_LAYER_IDX).contains(&u8_layer) {
Copy link
Contributor

Choose a reason for hiding this comment

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

Can we say !(-VLAN_MAX_LAYERS..= VLAN_MAX_LAYERS-1).contains(&u8_layer)

return None;
}
u8_layer
}
} else {
DETECT_VLAN_ID_ANY
};
return Some(DetectVlanIdData { du16, layer });
}

#[no_mangle]
pub unsafe extern "C" fn rs_detect_vlan_id_parse(
ustr: *const std::os::raw::c_char,
) -> *mut DetectVlanIdData {
let ft_name: &CStr = CStr::from_ptr(ustr); //unsafe
if let Ok(s) = ft_name.to_str() {
if let Some(ctx) = detect_parse_vlan_id(s) {
let boxed = Box::new(ctx);
return Box::into_raw(boxed) as *mut _;
}
}
return std::ptr::null_mut();
}

#[no_mangle]
pub unsafe extern "C" fn rs_detect_vlan_id_free(ctx: &mut DetectVlanIdData) {
// Just unbox...
std::mem::drop(Box::from_raw(ctx));
}

#[cfg(test)]
mod test {
use super::*;
use crate::detect::uint::DetectUintMode;

#[test]
fn test_detect_parse_vlan_id() {
assert_eq!(
detect_parse_vlan_id("300").unwrap(),
DetectVlanIdData {
du16: DetectUintData {
arg1: 300,
arg2: 0,
mode: DetectUintMode::DetectUintModeEqual,
},
layer: DETECT_VLAN_ID_ANY
}
);
assert_eq!(
detect_parse_vlan_id("300,any").unwrap(),
DetectVlanIdData {
du16: DetectUintData {
arg1: 300,
arg2: 0,
mode: DetectUintMode::DetectUintModeEqual,
},
layer: DETECT_VLAN_ID_ANY
}
);
assert_eq!(
detect_parse_vlan_id("300,all").unwrap(),
DetectVlanIdData {
du16: DetectUintData {
arg1: 300,
arg2: 0,
mode: DetectUintMode::DetectUintModeEqual,
},
layer: DETECT_VLAN_ID_ALL
}
);
assert_eq!(
detect_parse_vlan_id("200,1").unwrap(),
DetectVlanIdData {
du16: DetectUintData {
arg1: 200,
arg2: 0,
mode: DetectUintMode::DetectUintModeEqual,
},
layer: 1
}
);
assert_eq!(
detect_parse_vlan_id("200,-1").unwrap(),
DetectVlanIdData {
du16: DetectUintData {
arg1: 200,
arg2: 0,
mode: DetectUintMode::DetectUintModeEqual,
},
layer: -1
}
);
assert_eq!(
detect_parse_vlan_id("!200,2").unwrap(),
DetectVlanIdData {
du16: DetectUintData {
arg1: 200,
arg2: 0,
mode: DetectUintMode::DetectUintModeNe,
},
layer: 2
}
);
assert_eq!(
detect_parse_vlan_id(">200,2").unwrap(),
DetectVlanIdData {
du16: DetectUintData {
arg1: 200,
arg2: 0,
mode: DetectUintMode::DetectUintModeGt,
},
layer: 2
}
);
assert_eq!(
detect_parse_vlan_id("200-300,0").unwrap(),
DetectVlanIdData {
du16: DetectUintData {
arg1: 200,
arg2: 300,
mode: DetectUintMode::DetectUintModeRange,
},
layer: 0
}
);
assert_eq!(
detect_parse_vlan_id("0xC8,2").unwrap(),
DetectVlanIdData {
du16: DetectUintData {
arg1: 200,
arg2: 0,
mode: DetectUintMode::DetectUintModeEqual,
},
layer: 2
}
);
assert!(detect_parse_vlan_id("200abc").is_none());
assert!(detect_parse_vlan_id("4096").is_none());
assert!(detect_parse_vlan_id("600,abc").is_none());
assert!(detect_parse_vlan_id("600,100").is_none());
assert!(detect_parse_vlan_id("123,-4").is_none());
assert!(detect_parse_vlan_id("1,2,3").is_none());
}
}
Loading
Loading