from __future__ import annotations
from abc import ABC, abstractmethod
import re
import types
from typing import (
Any,
ClassVar,
Generator,
Iterator,
Union,
Type,
cast,
get_origin,
get_args,
get_type_hints,
Generic,
TypeVar,
TYPE_CHECKING,
)
from collections.abc import Sequence as SequenceABC
from base64 import b64encode
from sigma.types import (
CompareOperators,
Placeholder,
SigmaBool,
SigmaCasedString,
SigmaExists,
SigmaExpansion,
SigmaFieldReference,
SigmaRegularExpressionFlag,
SigmaType,
SigmaString,
SigmaNumber,
SpecialChars,
SigmaRegularExpression,
SigmaCompareExpression,
SigmaCIDRExpression,
SigmaTimestampPart,
TimestampPart,
SigmaStringPartType,
)
from sigma.exceptions import SigmaModifiedError, SigmaRuleLocation, SigmaTypeError, SigmaValueError
if TYPE_CHECKING:
from .rule import SigmaDetectionItem
T = TypeVar("T", bound=SigmaType | list[SigmaType])
R = TypeVar("R", bound=SigmaType | list[SigmaType])
### Base Classes ###
[docs]
class SigmaModifier(ABC, Generic[T, R]):
"""Base class for all Sigma modifiers"""
detection_item: "SigmaDetectionItem"
applied_modifiers: list[Type["SigmaModifier[T, R]"]]
[docs]
def __init__(
self,
detection_item: "SigmaDetectionItem",
applied_modifiers: list[Type["SigmaModifier[T, R]"]],
source: SigmaRuleLocation | None = None,
):
self.detection_item = detection_item
self.applied_modifiers = applied_modifiers
self.source = source
# Cache for type hints resolved from modify() method, keyed by class
_type_hint_cache: ClassVar[dict[type, Any]] = {}
def _get_modify_type_hint(self) -> Any:
"""Get the type hint for the 'val' parameter of the modify method, with caching per class."""
cls = type(self)
try:
return SigmaModifier._type_hint_cache[cls]
except KeyError:
th = get_type_hints(self.modify)["val"]
SigmaModifier._type_hint_cache[cls] = th
return th
[docs]
def type_check(self, val: Any, explicit_type: Type[Any] | None = None) -> bool:
th = (
explicit_type or self._get_modify_type_hint()
) # get type annotation from val parameter of apply method or explicit_type parameter
if th is Any:
return True
to = get_origin(th) # get possible generic type of type hint
if to is None: # Plain type in annotation
return isinstance(val, th)
elif (
to is Union or to is types.UnionType
): # type hint is Union of multiple types, check if val is one of them
for t in get_args(th):
if isinstance(val, t):
return True
return False
elif to is list and isinstance(val, list): # type hint is sequence
inner_type = get_args(th)[0]
return all([self.type_check(item, explicit_type=inner_type) for item in val])
return False
[docs]
@abstractmethod
def modify(self, val: T) -> R:
"""This method should be overridden with the modifier implementation."""
[docs]
def apply(self, val: T) -> list[T]:
"""
Modifier entry point containing the default operations:
* Type checking
* Ensure returned value is a list
* Handle values of SigmaExpansion objects separately.
"""
if isinstance(val, SigmaExpansion): # Handle each SigmaExpansion item separately
return [
cast(
T,
SigmaExpansion(
[cast(SigmaType, va) for v in val.values for va in self.apply(cast(T, v))]
),
)
]
else:
if not self.type_check(val):
raise SigmaTypeError(
f"Modifier {self.__class__.__name__} incompatible to value type of '{ val }'",
source=self.source,
)
r = self.modify(val)
if isinstance(r, list):
return [cast(T, item) for item in r]
else:
return [cast(T, r)]
[docs]
class SigmaValueModifier(SigmaModifier[T, R]):
"""Base class for all modifiers that handle each value for the modifier scope separately"""
[docs]
@abstractmethod
def modify(self, val: T) -> R:
"""This method should be overridden with the modifier implementation."""
[docs]
class SigmaListModifier(SigmaModifier[T, R]):
"""Base class for all modifiers that handle all values for the modifier scope as a whole."""
[docs]
@abstractmethod
def modify(self, val: T) -> R:
"""This method should be overridden with the modifier implementation."""
### Helpers for regular expression modifiers ###
def _regex_has_toplevel_alternation(regexp: str) -> bool:
"""Check if a regular expression contains a | outside of groups and character classes."""
depth = 0
in_class = False
i = 0
while i < len(regexp):
c = regexp[i]
if c == "\\": # skip escaped character
i += 2
continue
if in_class:
if c == "]":
in_class = False
elif c == "[":
in_class = True
if regexp[i + 1 : i + 2] == "^": # negated character class
i += 1
if regexp[i + 1 : i + 2] == "]": # ] directly after [ or [^ is a literal
i += 1
elif c == "(":
depth += 1
elif c == ")":
depth -= 1
elif c == "|" and depth == 0:
return True
i += 1
return False
def _regex_ends_with_unescaped(regexp: str, suffix: str) -> bool:
"""Check if a regular expression ends with suffix that is not escaped by a backslash."""
if not regexp.endswith(suffix):
return False
head = regexp[: len(regexp) - len(suffix)]
return (len(head) - len(head.rstrip("\\"))) % 2 == 0
def _regex_is_open_ended(regexp: str) -> bool:
"""Check if a regular expression neither ends with a .* wildcard nor with an end anchor."""
return not _regex_ends_with_unescaped(regexp, ".*") and not _regex_ends_with_unescaped(
regexp, "$"
)
def _group_regex_alternation(val: SigmaRegularExpression) -> str:
"""
Wrap a regular expression with a top-level alternation into a non-capturing group, so that
wildcards prepended or appended by the contains/startswith/endswith modifiers apply to all
alternatives. Returns the resulting regular expression string.
"""
regexp_str = str(val.regexp)
if _regex_has_toplevel_alternation(regexp_str):
val.regexp = SigmaString("(?:", escape=False) + val.regexp + SigmaString(")")
regexp_str = str(val.regexp)
return regexp_str
### Modifier Implementations ###
[docs]
class SigmaContainsModifier(
SigmaValueModifier[
SigmaString | SigmaRegularExpression | SigmaFieldReference,
SigmaString | SigmaRegularExpression | SigmaFieldReference,
]
):
"""Puts wildcards around a string to match it somewhere inside another string instead of as a whole."""
[docs]
def modify(
self, val: SigmaString | SigmaRegularExpression | SigmaFieldReference
) -> SigmaString | SigmaRegularExpression | SigmaFieldReference:
if isinstance(val, SigmaString):
if not val.startswith(SpecialChars.WILDCARD_MULTI):
val = SpecialChars.WILDCARD_MULTI + val
if not val.endswith(SpecialChars.WILDCARD_MULTI):
val += SpecialChars.WILDCARD_MULTI
elif isinstance(val, SigmaRegularExpression):
regexp_str = _group_regex_alternation(val)
if not regexp_str.startswith((".*", "^")):
val.regexp = SigmaString(".") + SpecialChars.WILDCARD_MULTI + val.regexp
if _regex_is_open_ended(regexp_str):
val.regexp += SigmaString(".") + SpecialChars.WILDCARD_MULTI
val.compile()
elif isinstance(val, SigmaFieldReference):
val.starts_with = True
val.ends_with = True
return val
[docs]
class SigmaStartswithModifier(
SigmaValueModifier[
SigmaString | SigmaRegularExpression | SigmaFieldReference,
SigmaString | SigmaRegularExpression | SigmaFieldReference,
]
):
"""Puts a wildcard at the end of a string to match arbitrary values after the given prefix."""
[docs]
def modify(
self, val: SigmaString | SigmaRegularExpression | SigmaFieldReference
) -> SigmaString | SigmaRegularExpression | SigmaFieldReference:
if isinstance(val, SigmaString):
if not val.endswith(SpecialChars.WILDCARD_MULTI):
val += SpecialChars.WILDCARD_MULTI
elif isinstance(val, SigmaRegularExpression):
regexp_str = _group_regex_alternation(val)
if _regex_is_open_ended(regexp_str):
val.regexp += SigmaString(".") + SpecialChars.WILDCARD_MULTI
val.compile()
elif isinstance(val, SigmaFieldReference):
val.starts_with = True
return val
[docs]
class SigmaEndswithModifier(
SigmaValueModifier[
SigmaString | SigmaRegularExpression | SigmaFieldReference,
SigmaString | SigmaRegularExpression | SigmaFieldReference,
]
):
"""Puts a wildcard before a string to match arbitrary values before it."""
[docs]
def modify(
self, val: SigmaString | SigmaRegularExpression | SigmaFieldReference
) -> SigmaString | SigmaRegularExpression | SigmaFieldReference:
if isinstance(val, SigmaString):
if not val.startswith(SpecialChars.WILDCARD_MULTI):
val = SpecialChars.WILDCARD_MULTI + val
elif isinstance(val, SigmaRegularExpression):
regexp_str = _group_regex_alternation(val)
if not regexp_str.startswith((".*", "^")):
val.regexp = SigmaString(".") + SpecialChars.WILDCARD_MULTI + val.regexp
val.compile()
elif isinstance(val, SigmaFieldReference):
val.ends_with = True
return val
def _base64_input_bytes(val: SigmaString, applied_modifiers: SequenceABC[type]) -> bytes:
"""
Byte sequence that is encoded by the base64 modifiers. The utf16 modifier prepends the byte
order mark as character U+FEFF, whose UTF-8 encoding is EF BB BF. After the utf16 modifier it
must be encoded as the UTF-16LE byte order mark FF FE instead.
"""
data = bytes(val)
utf8_bom = "\ufeff".encode("utf-8")
if SigmaUTF16Modifier in applied_modifiers and data.startswith(utf8_bom):
data = b"\xff\xfe" + data[len(utf8_bom) :]
return data
[docs]
class SigmaBase64Modifier(SigmaValueModifier[SigmaString, SigmaString]):
"""Encode string as Base64 value."""
[docs]
def modify(self, val: SigmaString) -> SigmaString:
if val.contains_special():
raise SigmaValueError(
"Base64 encoding of strings with wildcards is not allowed",
source=self.source,
)
return SigmaString(b64encode(_base64_input_bytes(val, self.applied_modifiers)).decode())
[docs]
class SigmaBase64OffsetModifier(SigmaValueModifier[SigmaString, SigmaExpansion]):
"""
Encode string as Base64 value with different offsets to match it at different locations in
encoded form.
"""
start_offsets = (0, 2, 3)
end_offsets = (None, -3, -2)
[docs]
def modify(self, val: SigmaString) -> SigmaExpansion:
if val.contains_special():
raise SigmaValueError(
"Base64 encoding of strings with wildcards is not allowed",
source=self.source,
)
data = _base64_input_bytes(val, self.applied_modifiers)
return SigmaExpansion(
[
SigmaString(
b64encode(i * b" " + data)[
# the cut depends on the encoded byte length, not the character count
self.start_offsets[i] : self.end_offsets[(len(data) + i) % 3]
].decode()
)
for i in range(3)
]
)
[docs]
class SigmaWideModifier(SigmaValueModifier[SigmaString, SigmaString]):
"""Encode string as wide string (UTF-16LE)."""
[docs]
def modify(self, val: SigmaString) -> SigmaString:
r: list[SigmaStringPartType] = list()
for item in val.s:
if isinstance(
item, str
): # put 0x00 after each character by encoding it to utf-16le and decoding it as utf-8
try:
r.append(item.encode("utf-16le").decode("utf-8"))
except UnicodeDecodeError: # this method only works for ascii characters
raise SigmaValueError(
f"Wide modifier only allowed for ascii strings, input string '{str(val)}' isn't one",
source=self.source,
)
else: # just append special characters without further handling
r.append(item)
s = SigmaString()
s.s = r
return s
[docs]
class SigmaUTF16BEModifier(SigmaValueModifier[SigmaString, SigmaString]):
"""Encode string as wide string (UTF-16BE)."""
[docs]
def modify(self, val: SigmaString) -> SigmaString:
r: list[SigmaStringPartType] = list()
for item in val.s:
if isinstance(item, str):
try:
r.append(item.encode("utf-16be").decode("utf-8"))
except UnicodeDecodeError:
raise SigmaValueError(
f"UTF-16BE modifier only allowed for valid Unicode strings, input string '{str(val)}' isn't one",
source=self.source,
)
else:
r.append(item)
s = SigmaString()
s.s = r
return s
[docs]
class SigmaUTF16Modifier(SigmaValueModifier[SigmaString, SigmaString]):
"""Encode string as wide string with BOM (UTF-16LE with BOM prefix)."""
[docs]
def modify(self, val: SigmaString) -> SigmaString:
r: list[SigmaStringPartType] = list()
r.append("\ufeff") # BOM
for item in val.s:
if isinstance(item, str):
try:
r.append(item.encode("utf-16le").decode("utf-8"))
except UnicodeDecodeError:
raise SigmaValueError(
f"UTF-16 modifier only allowed for valid Unicode strings, input string '{str(val)}' isn't one",
source=self.source,
)
else:
r.append(item)
s = SigmaString()
s.s = r
return s
[docs]
class SigmaWindowsDashModifier(SigmaValueModifier[SigmaString, SigmaExpansion]):
"""
Expand parameter characters / and - that are often interchangeable in Windows into the other
form if it appears between word boundaries. E.g. in -param-name the first dash will be expanded
into /param-name while the second dash is left untouched.
"""
en_dash = chr(int("2013", 16))
em_dash = chr(int("2014", 16))
horizontal_bar = chr(int("2015", 16))
max_expanded_dashes = 3
[docs]
def modify(self, val: SigmaString) -> SigmaExpansion:
def callback(p: Placeholder) -> Iterator[str | Placeholder]:
if p.name == "_windash":
yield from ("-", "/", self.en_dash, self.em_dash, self.horizontal_bar)
else:
yield p
with_placeholders = val.replace_with_placeholder(re.compile("\\B[-/]\\b"), "_windash")
expanded_dashes = sum(
1
for part in with_placeholders.s
if isinstance(part, Placeholder) and part.name == "_windash"
)
if expanded_dashes > self.max_expanded_dashes:
raise SigmaModifiedError(
"windash modifier expands at most three dash occurrences in one value; "
"split multiple dash expansions into separate ORed string match conditions "
"with one dash expanded",
source=self.source,
)
return SigmaExpansion(
cast(
list[SigmaType],
with_placeholders.replace_placeholders(callback),
)
)
[docs]
class SigmaRegularExpressionModifier(SigmaValueModifier[SigmaString, SigmaRegularExpression]):
"""Treats string value as (case-sensitive) regular expression."""
[docs]
def modify(self, val: SigmaString) -> SigmaRegularExpression:
if len(self.applied_modifiers) > 0:
raise SigmaValueError(
"Regular expression modifier only applicable to unmodified values",
source=self.source,
)
return SigmaRegularExpression(val.original, policy=self.detection_item.policy)
[docs]
class SigmaRegularExpressionFlagModifier(
SigmaValueModifier[SigmaRegularExpression, SigmaRegularExpression]
):
"""Generic base class for setting a regular expression flag including checks"""
flag: ClassVar[SigmaRegularExpressionFlag]
[docs]
def modify(self, val: SigmaRegularExpression) -> SigmaRegularExpression:
val.add_flag(self.flag)
return val
[docs]
class SigmaRegularExpressionIgnoreCaseFlagModifier(SigmaRegularExpressionFlagModifier):
"""Match regular expression case-insensitive."""
flag: ClassVar[SigmaRegularExpressionFlag] = SigmaRegularExpressionFlag.IGNORECASE
[docs]
class SigmaRegularExpressionMultilineFlagModifier(SigmaRegularExpressionFlagModifier):
"""Match regular expression across multiple lines."""
flag: ClassVar[SigmaRegularExpressionFlag] = SigmaRegularExpressionFlag.MULTILINE
[docs]
class SigmaRegularExpressionDotAllFlagModifier(SigmaRegularExpressionFlagModifier):
"""Regular expression dot matches all characters."""
flag: ClassVar[SigmaRegularExpressionFlag] = SigmaRegularExpressionFlag.DOTALL
[docs]
class SigmaCaseSensitiveModifier(SigmaValueModifier[SigmaString, SigmaCasedString]):
[docs]
def modify(self, val: SigmaString) -> SigmaCasedString:
return SigmaCasedString.from_sigma_string(val)
[docs]
class SigmaCIDRModifier(SigmaValueModifier[SigmaString, SigmaCIDRExpression]):
"""Treat value as IP (v4 or v6) CIDR network."""
[docs]
def modify(self, val: SigmaString) -> SigmaCIDRExpression:
if len(self.applied_modifiers) > 0:
raise SigmaValueError(
"CIDR expression modifier only applicable to unmodified values",
source=self.source,
)
return SigmaCIDRExpression(str(val), source=self.source)
[docs]
class SigmaAllModifier(SigmaListModifier[Any, Any]):
"""Match all values of a list instead of any pf them."""
[docs]
def modify(self, val: Any) -> Any:
from sigma.conditions import ConditionAND
self.detection_item.value_linking = ConditionAND
return val
[docs]
class SigmaNegateModifier(SigmaListModifier[Any, Any]):
"""Negate the match - turns the detection item into a NOT match."""
[docs]
def modify(self, val: Any) -> Any:
self.detection_item.negated = True
return val
[docs]
class SigmaCompareModifier(SigmaValueModifier[SigmaNumber, SigmaCompareExpression]):
"""Base class for numeric comparison operator modifiers."""
op: ClassVar[CompareOperators]
[docs]
def modify(self, val: SigmaNumber) -> SigmaCompareExpression:
return SigmaCompareExpression(val, self.op, self.source)
[docs]
class SigmaLessThanModifier(SigmaCompareModifier):
"""Numeric less than (<) matching."""
op: ClassVar[CompareOperators] = CompareOperators.LT
[docs]
class SigmaLessThanEqualModifier(SigmaCompareModifier):
"""Numeric less than or equal (<=) matching."""
op: ClassVar[CompareOperators] = CompareOperators.LTE
[docs]
class SigmaGreaterThanModifier(SigmaCompareModifier):
"""Numeric greater than (>) matching."""
op: ClassVar[CompareOperators] = CompareOperators.GT
[docs]
class SigmaGreaterThanEqualModifier(SigmaCompareModifier):
"""Numeric greater than or equal (>=) matching."""
op: ClassVar[CompareOperators] = CompareOperators.GTE
[docs]
class SigmaNotEqualModifier(SigmaCompareModifier):
"""Numeric not equal (!=) matching."""
op: ClassVar[CompareOperators] = CompareOperators.NEQ
[docs]
class SigmaFieldReferenceModifier(SigmaValueModifier[SigmaString, SigmaFieldReference]):
"""Modifiers a plain string into the field reference type."""
[docs]
def modify(self, val: SigmaString) -> SigmaFieldReference:
if val.contains_special():
raise SigmaValueError("Field references must not contain wildcards", source=self.source)
return SigmaFieldReference(val.to_plain())
[docs]
class SigmaExistsModifier(SigmaValueModifier[SigmaBool, SigmaExists]):
"""Modifies to check if the field name provided as value exists in the matched event."""
[docs]
def modify(self, val: SigmaBool) -> SigmaExists:
if self.detection_item.field is None:
raise SigmaValueError("Exists modifier must be applied to field", source=self.source)
if len(self.applied_modifiers) > 0:
raise SigmaValueError(
"Exists modifier only applicable to unmodified boolean values",
source=self.source,
)
return SigmaExists(val.boolean)
[docs]
class SigmaExpandModifier(
SigmaValueModifier[SigmaString | SigmaRegularExpression, SigmaString | SigmaRegularExpression]
):
"""
Modifier for expansion of placeholders in values. It replaces placeholder strings (%something%)
with stub objects that are later expanded to one or multiple strings or replaced with some SIEM
specific list item or lookup by the processing pipeline.
"""
[docs]
def modify(
self, val: SigmaString | SigmaRegularExpression
) -> SigmaString | SigmaRegularExpression:
return val.insert_placeholders()
[docs]
class SigmaTimestampModifier(SigmaValueModifier[SigmaNumber, SigmaTimestampPart]):
"""
Base class for timestamp modifiers that parse the field as a datetime/timestamp and transform it to a specific part.
"""
time_part_unit: ClassVar[TimestampPart]
[docs]
def modify(self, val: SigmaNumber) -> SigmaTimestampPart:
return SigmaTimestampPart(self.time_part_unit, int(val.number))
[docs]
class SigmaTimestampMinuteModifier(SigmaTimestampModifier):
"""
Modifier that parses the field as a datetime/timestamp and transforms it to the minute number. Between 0 and 59.
"""
time_part_unit: ClassVar[TimestampPart] = TimestampPart.MINUTE
[docs]
class SigmaTimestampHourModifier(SigmaTimestampModifier):
"""
Modifier that parses the field as a datetime/timestamp and transforms it to the hour number. Between 0 and 23.
"""
time_part_unit: ClassVar[TimestampPart] = TimestampPart.HOUR
[docs]
class SigmaTimestampDayModifier(SigmaTimestampModifier):
"""
Modifier that parses the field as a datetime/timestamp and transforms it to the day of the month number. Between 1 and 31.
"""
time_part_unit: ClassVar[TimestampPart] = TimestampPart.DAY
[docs]
class SigmaTimestampWeekModifier(SigmaTimestampModifier):
"""
Modifier that parses the field as a datetime/timestamp and transforms it to the week of the year number. Between 1 and 52.
"""
time_part_unit: ClassVar[TimestampPart] = TimestampPart.WEEK
[docs]
class SigmaTimestampMonthModifier(SigmaTimestampModifier):
"""
Modifier that parses the field as a datetime/timestamp and transforms it to the month of the year number. Between 1 and 12.
"""
time_part_unit: ClassVar[TimestampPart] = TimestampPart.MONTH
[docs]
class SigmaTimestampYearModifier(SigmaTimestampModifier):
"""
Modifier that parses the field as a datetime/timestamp and transforms it to the year number.
"""
time_part_unit: ClassVar[TimestampPart] = TimestampPart.YEAR
# Mapping from modifier identifier strings to modifier classes
modifier_mapping: dict[str, Type[SigmaModifier[Any, Any]]] = {
"all": SigmaAllModifier,
"neq": SigmaNegateModifier,
"base64": SigmaBase64Modifier,
"base64offset": SigmaBase64OffsetModifier,
"cased": SigmaCaseSensitiveModifier,
"cidr": SigmaCIDRModifier,
"contains": SigmaContainsModifier,
"day": SigmaTimestampDayModifier,
"dotall": SigmaRegularExpressionDotAllFlagModifier,
"endswith": SigmaEndswithModifier,
"exists": SigmaExistsModifier,
"expand": SigmaExpandModifier,
"fieldref": SigmaFieldReferenceModifier,
"gt": SigmaGreaterThanModifier,
"gte": SigmaGreaterThanEqualModifier,
"hour": SigmaTimestampHourModifier,
"i": SigmaRegularExpressionIgnoreCaseFlagModifier,
"ignorecase": SigmaRegularExpressionIgnoreCaseFlagModifier,
"lt": SigmaLessThanModifier,
"lte": SigmaLessThanEqualModifier,
"m": SigmaRegularExpressionMultilineFlagModifier,
"minute": SigmaTimestampMinuteModifier,
"month": SigmaTimestampMonthModifier,
"multiline": SigmaRegularExpressionMultilineFlagModifier,
"re": SigmaRegularExpressionModifier,
"utf16": SigmaUTF16Modifier,
"utf16be": SigmaUTF16BEModifier,
"s": SigmaRegularExpressionDotAllFlagModifier,
"startswith": SigmaStartswithModifier,
"week": SigmaTimestampWeekModifier,
"wide": SigmaWideModifier,
"windash": SigmaWindowsDashModifier,
"year": SigmaTimestampYearModifier,
}
# Mapping from modifier class to identifier
reverse_modifier_mapping: dict[str, str] = {
modifier_class.__name__: identifier for identifier, modifier_class in modifier_mapping.items()
}