from __future__ import annotations
import re
from abc import ABC, abstractmethod
from dataclasses import InitVar, dataclass, field
from enum import Enum, auto
from ipaddress import IPv4Network, IPv6Address, IPv6Network, ip_network
from itertools import product
from math import inf, isfinite
from typing import (
ClassVar,
Type,
Union,
Optional,
Any,
Iterable,
Callable,
Iterator,
TYPE_CHECKING,
cast,
)
if TYPE_CHECKING:
from sigma.policy import SigmaPolicy
from sigma.exceptions import (
SigmaPlaceholderError,
SigmaRuleLocation,
SigmaValueError,
SigmaRegularExpressionError,
SigmaTypeError,
)
[docs]
class SpecialChars(Enum):
"""Enumeration of supported special characters"""
WILDCARD_MULTI = auto()
WILDCARD_SINGLE = auto()
[docs]
class TimestampPart(Enum):
"""Enumeration of supported datetime parts for a SigmaTimestamp object"""
MINUTE = auto()
HOUR = auto()
DAY = auto()
WEEK = auto()
MONTH = auto()
YEAR = auto()
@dataclass
class Placeholder:
"""
Placeholder class used as stub in a SigmaString to be later replaced by a value contained in a string or
receives some configuration-specific special treatment, e.g. replacement with a SIEM specific list item.
"""
name: str
escape_char = "\\"
char_mapping = {
"*": SpecialChars.WILDCARD_MULTI,
"?": SpecialChars.WILDCARD_SINGLE,
}
special_char_mapping = {v: k for k, v in char_mapping.items()}
[docs]
class SigmaType(ABC):
"""Base class for Sigma value types"""
[docs]
def __init__(self, dummy: Any) -> None:
pass
def __eq__(self, other: Any) -> bool:
return False
[docs]
def to_plain(self) -> Any:
"""
Return plain Python value (str, int etc.) from SigmaType instance for usage in conversion of
Sigma rules back to dicts. Uses the first annotated member as return value.
"""
return self.__getattribute__(list(type(self).__annotations__.keys())[0])
class NoPlainConversionMixin:
"""Mixin for declaring a SigmaType as non-convertible into a plain representation."""
def to_plain(self) -> None:
raise SigmaValueError(
f"Sigma type '{ self.__class__.__name__ }' can't be converted into a plain representation."
)
[docs]
class SigmaNull(SigmaType):
"""Empty/none/null value"""
null: ClassVar[None] = None
[docs]
def __init__(self, dummy: Any | None = None):
pass
def __eq__(self, other: Any) -> bool:
return isinstance(other, self.__class__)
[docs]
@dataclass
class SigmaExists(SigmaType):
"""Field existence check."""
exists: bool
def __bool__(self) -> bool:
return self.exists
SigmaStringPartType = str | SpecialChars | Placeholder
[docs]
class SigmaString(SigmaType):
"""
Strings in Sigma detection values containing wildcards.
"""
original: str # the original string, untouched
s: list[
SigmaStringPartType
] # the string is represented as sequence of strings and characters with special meaning
max_placeholder_expansions: ClassVar[int] = 200
[docs]
def __init__(self, s: str | None = None, escape: bool = True):
"""
Initializes SigmaString instance from raw string by parsing it:
* characters from char_mapping are interpreted as special characters and interrupt the plain string in the resulting sequence
* escape_char disables special character mapping in the next character
* if escaping character is followed by a character without special meaning the escaping character is used as plain character
:param s: string to be parsed
:type s: str
:param escape: whether to enable escaping of special characters
:type escape: bool
"""
if s is None:
s = ""
self.original = s
r: list[str | SpecialChars | Placeholder] = list()
acc = [] # list accumulation until special character appears
escaped = False # escape mode flag: characters in this mode are always accumulated
for c in s:
if escaped: # escaping mode?
if (
c in char_mapping or c == escape_char
): # accumulate if character is special or escaping character
acc.append(c)
else: # accumulate escaping and current character (this allows to use plain backslashes in values)
acc.append(escape_char)
acc.append(c)
escaped = False
elif (
c == escape_char and escape
): # escaping character? enable escaped mode for next character
escaped = True
else: # "normal" string parsing
if c in char_mapping: # character is special character?
if acc:
r.append(
"".join(acc)
) # append accumulated string to parsed result if there was something
r.append(char_mapping[c]) # append special character to parsed result
acc = [] # accumulation reset
else: # characters without special meaning aren't accumulated
acc.append(c)
if escaped: # String ended in escaping mode: accumulate escaping character
acc.append(escape_char)
if acc: # append accumulated remainder
r.append("".join(acc))
self.s = r
[docs]
@classmethod
def from_str(cls, s: str) -> "SigmaString":
sigma_string = SigmaString()
sigma_string.s = [s]
sigma_string.original = s
return sigma_string
def __getitem__(self, idx: int | slice) -> "SigmaString":
"""
Index SigmaString parts with transparent handling of special characters.
:param key: Integer index or slice.
:type key: int | slice
:return: SigmaString containing only the specified part.
:rtype: SigmaString
"""
# Set start and end indices from given index
length = len(self)
if isinstance(idx, int):
start = idx
end = None
elif isinstance(idx, slice):
if idx.step is not None:
raise IndexError("SigmaString slice index with step is not allowed")
start = idx.start or 0
end = idx.stop if idx.stop is not None else inf
else:
raise TypeError("SigmaString indices must be integers or slices")
# Handling of negative indices and deferred setting of end index if only character index was set
if start < 0:
start = length + start
if end is None:
end = start + 1
elif end < 0:
end = length + end
# Range checks
if start > end or start >= length:
return self.__class__("")
if start < 0 or end < 0 or (end != inf and end > length):
raise IndexError("SigmaString index out of range")
i = 0 # Pointer to SigmaString element
result: list[str | SpecialChars | Placeholder] = [] # Result: indexed string part
# Find start. The variables start and end now contain the remaining characters until the
# indexed part begins/ends relative to the current element.
while start > 0 and i < len(self.s):
e = self.s[i]
if isinstance(e, str): # Current SigmaString part is string
e_len = len(e)
# if e_len <= start:
if e_len > start:
# else:
if end < e_len: # end lies within this string part
s = self.__class__()
s.s = [
e[start : cast(int, end)]
] # don't re-parse the cut-out substring: plain wildcard characters from escaped sequences would be interpreted as special characters again
return s
else: # end lies behind the current string part
result.append(e[start:])
# end -= start
# start = 0
start -= e_len
end -= e_len
else: # Current SigmaString part is a special character or placeholder
start -= 1
end -= 1
i += 1
# Append until end of string or indexed part is reached.
while end > 0 and i < len(self.s):
e = self.s[i]
if isinstance(e, str): # Current SigmaString part is string
e_len = len(e)
if end < e_len: # end lies within this string part
result.append(e[: cast(int, end)])
else:
result.append(e)
end -= e_len
else: # Current SigmaString part is a special character or placeholder
result.append(e)
end -= 1
i += 1
if len(result) == 0: # Special case: start begins after string - return empty string
return self.__class__("")
else: # Return calculated result
s = self.__class__()
s.s = result
return s
[docs]
def insert_placeholders(self) -> "SigmaString":
"""
Replace %something% placeholders with Placeholder stub objects that can be later handled by the processing
pipeline. This implements the expand modifier.
Iterates over the parts in self.s. For plain string parts, scans for %name% patterns and
replaces them with Placeholder objects. Backslashes are treated as ordinary literal characters
— a backslash immediately before %name% is emitted as a literal backslash followed by the
placeholder. The placeholder name must be non-empty and must not contain backslashes or
percent signs; otherwise the opening % is treated as a literal character.
Non-string parts (special characters, existing placeholders) are preserved unchanged.
"""
res: list[str | SpecialChars | Placeholder] = []
for part in self.s:
if not isinstance(part, str):
res.append(part)
continue
acc: list[str] = []
i = 0
while i < len(part):
c = part[i]
if c == "%":
end = part.find("%", i + 1)
if end != -1 and end > i + 1:
name = part[i + 1 : end]
# Accept only non-empty names without backslashes
if "\\" not in name:
if acc:
res.append("".join(acc))
acc = []
res.append(Placeholder(name))
i = end + 1
continue
# lone %, empty name, or name containing backslash: treat % as literal
acc.append(c)
else:
acc.append(c)
i += 1
if acc:
res.append("".join(acc))
self.s = res
return self
[docs]
def replace_with_placeholder(
self, regex: re.Pattern[str], placeholder_name: str
) -> "SigmaString":
"""
Replace all occurrences of string part matching regular expression with placeholder.
:param regex: regular expression that should be matched.
:type regex: Pattern
:param placeholder_name: name of placeholder that should be inserted.
:type placeholder_name: str
:return: Returns a string with the replacement placeholders.
:rtype: SigmaString
"""
result: list[str | SpecialChars | Placeholder] = []
for e in self.s:
if isinstance(e, str):
matched = False
i = 0
for m in regex.finditer(e):
matched = True
s = e[i : m.start()]
if s != "":
result.append(s)
result.append(Placeholder(placeholder_name))
i = m.end()
if matched: # if matched, append remainder of string
s = e[i:]
if s != "":
result.append(s)
else: # no matches: append original string
result.append(e)
else:
result.append(e)
sigma_string = self.__class__()
sigma_string.s = result
return sigma_string
def _merge_strs(self) -> "SigmaString":
"""Merge consecutive plain strings in self.s."""
if not self.s:
return self
res: list[SigmaStringPartType] = [self.s[0]]
for item in self.s[1:]:
if isinstance(res[-1], str) and isinstance(item, str):
res[-1] += item
else:
res.append(item)
self.s = res
return self
def __add__(self, other: "SigmaString" | str | SpecialChars | Placeholder) -> "SigmaString":
s = self.__class__()
if isinstance(other, self.__class__):
s.s = self.s + other.s
elif isinstance(other, (str, SpecialChars, Placeholder)):
s.s = self.s + [other]
else:
return NotImplemented
return s._merge_strs()
def __radd__(self, other: str | SpecialChars | Placeholder) -> "SigmaString":
if isinstance(other, (str, SpecialChars, Placeholder)):
s = self.__class__()
s.s = [other] + self.s
return s._merge_strs()
else:
return NotImplemented
def __eq__(self, other: object) -> bool:
if isinstance(other, str):
return self == self.__class__(other)
elif isinstance(other, self.__class__):
return self.s == other.s
else:
raise NotImplementedError(
"SigmaString can only be compared with a string or another SigmaString"
)
def __str__(self) -> str:
return self.to_plain()
[docs]
def to_plain(self, regex: bool = False, escape_backslash: bool = False) -> str:
"""
Generate string representation of SigmaString with or without regex escaping.
If escape_backslash is set, backslashes that would be interpreted as escaping character
when the result is parsed again (a backslash followed by a wildcard or another backslash)
are escaped, so that parsing the result yields the same SigmaString.
"""
rs = ""
for i, s in enumerate(self.s):
if isinstance(s, str):
if regex:
rs += s
else:
if escape_backslash:
s = self._escape_backslashes(
s, self.s[i + 1] if i + 1 < len(self.s) else None
)
rs += s.replace("*", "\\*").replace("?", "\\?")
elif isinstance(s, SpecialChars):
rs += special_char_mapping[s]
elif isinstance(s, Placeholder):
rs += f"%{s.name}%"
else:
raise TypeError(
"SigmaString can only consist of plain strings and instances of SpecialChars or Placeholder objects."
)
return rs
@staticmethod
def _escape_backslashes(s: str, next_part: SigmaStringPartType | None) -> str:
"""
Escape each backslash in the plain string part s that is followed by a character that
would turn it into an escaping character: a wildcard character (escaped or special) or
another backslash. next_part is the SigmaString part following s.
"""
escaping_follower = (*char_mapping, escape_char)
r = ""
for j, c in enumerate(s):
if c == escape_char:
if j + 1 < len(s):
followed = s[j + 1] in escaping_follower
else:
followed = isinstance(next_part, SpecialChars) or (
isinstance(next_part, str) and next_part[:1] in escaping_follower
)
if followed:
r += escape_char
r += c
return r
def __repr__(self) -> str:
return str(f"SigmaString({self.s})")
[docs]
def to_plain_regex(self) -> str:
"""Return plain string representation of SigmaString with reduced escaping."""
return self.to_plain(regex=True)
def __bytes__(self) -> bytes:
# Plain parts are encoded as they are: the escaping of literal wildcard characters done by
# to_plain() is not part of the value.
return self.to_plain(regex=True).encode()
def __len__(self) -> int:
return sum(
(
(
len(e)
if isinstance(e, str) # count string parts with number of characters
else 1
) # everything else is counted as single character
for e in self.s
)
)
[docs]
def startswith(self, val: SigmaStringPartType) -> bool:
"""Check if string starts with a given string or special character."""
if len(self.s) == 0:
return False
c = self.s[0]
if not isinstance(val, type(c)): # can't match if types differ
return False
elif isinstance(c, str): # pass startswith invocation to string objects
return c.startswith(cast(str, val))
else: # direct comparison of SpecialChars
return c == val
[docs]
def endswith(self, val: SigmaStringPartType) -> bool:
"""Check if string ends with a given string or special character."""
if len(self.s) == 0:
return False
c = self.s[-1]
if not isinstance(val, type(c)): # can't match if types differ
return False
elif isinstance(c, str): # pass endswith invocation to string objects
return c.endswith(cast(str, val))
else: # direct comparison of SpecialChars
return c == val
[docs]
def contains_special(self) -> bool:
"""Check if string contains special characters."""
return any(isinstance(item, SpecialChars) for item in self.s)
[docs]
def contains_placeholder(
self, include: list[str] | None = None, exclude: list[str] | None = None
) -> bool:
"""
Check if string contains placeholders and if any placeholder name is
* contained on the include list (if there is one)
* not contained on the include list (if there is one)
It is sufficient that one placeholder matches these conditions. The purpose of this method is to
determine if there are placeholders for further processing.
"""
return any(
(
isinstance(item, Placeholder)
and (include is None or item.name in include)
and (exclude is None or item.name not in exclude)
for item in self.s
)
)
[docs]
def replace_placeholders(
self,
callback: Callable[
[Placeholder], Iterator[str | SpecialChars | Placeholder | "SigmaString"]
],
) -> list["SigmaString"]:
"""
Iterate over all placeholders and call the callback for each one. The callback is called with the placeholder instance
as argument and yields replacement values (plain strings or SpecialChars instances). Each yielded replacement value
is concatenated to the SigmaString prefix before the placeholder and the method is called recursively with the suffix
after the placeholder. All placeholder replacements are combined with all returned SigmaString suffixes. Therefore,
the callback could be called multiple times with the same placeholder instance and should return the same results to ensure
a consistent result.
The callback can return a plain string, a SpecialChars instance (for insertion of wildcards) or a Placeholder (e.g. to keep
the placeholder for later processing pipeline items).
The total number of expanded strings is limited to max_placeholder_expansions.
"""
if (
not self.contains_placeholder()
): # return unchanged string in a list if it doesn't contain placeholders
return [self]
s = self.s
for i in range(len(s)):
if isinstance(s[i], Placeholder): # Placeholder instance at index, do replacement
prefix = SigmaString()
prefix.s = s[:i]
placeholder = s[i]
suffix = SigmaString()
suffix.s = s[i + 1 :]
results: list[SigmaString] = []
for replacement in callback(
cast(Placeholder, placeholder)
): # iterate over all callback result values
for result_suffix in suffix.replace_placeholders(
callback
): # iterate over all result values of calling this method with the SigmaString remainder
results.append(prefix + replacement + result_suffix)
if len(results) > self.max_placeholder_expansions:
raise SigmaValueError(
"Placeholder expansion exceeds maximum of "
f"{self.max_placeholder_expansions} items"
)
return results
return [self]
def __iter__(self) -> Iterable[SigmaStringPartType]:
for item in self.s:
if isinstance(item, str): # yield single characters of string parts
for char in item:
yield char
else:
yield item
[docs]
def iter_parts(self) -> Iterable[SigmaStringPartType]:
for item in self.s:
yield item
[docs]
def map_parts(
self,
func: Callable[[SigmaStringPartType], SigmaStringPartType | None],
filter_func: Callable[[SigmaStringPartType], bool] = lambda x: True,
interpret_special: bool = False,
) -> "SigmaString":
s = self.__class__()
parts = []
for item in self.iter_parts():
if filter_func(item):
result = func(item)
if result is not None:
if interpret_special:
if isinstance(result, str):
parts.extend(SigmaString(result).s)
else:
parts.append(result)
else:
parts.append(result)
else:
parts.append(item)
s.s = parts
return s
[docs]
def map_str_parts(self, func: Callable[[str], str | None]) -> "SigmaString":
return self.map_parts(func, lambda x: isinstance(x, str)) # type: ignore
[docs]
def convert(
self,
escape_char: str | None = "\\",
wildcard_multi: str | None = "*",
wildcard_single: str | None = "?",
add_escaped: str = "",
filter_chars: str = "",
) -> str:
"""
Convert SigmaString into a query string or pattern. The following parameters allow to change the behavior:
* escape_char: the character used to escape special characters. By default these are only the wildcard characters.
* wildcard_multi and wildcard_single: strings that should be output as wildcards for multiple and single characters.
* add_escaped: characters which are escaped in addition to the wildcards
* filter_chars: characters that are filtered out.
Setting one of the wildcard or multiple parameters to None indicates that this feature is not supported. Appearance
of these characters in a string will raise a SigmaValueError.
"""
result = []
escaped_chars = frozenset((wildcard_multi or "") + (wildcard_single or "") + add_escaped)
filter_set = frozenset(filter_chars)
for part in self.s:
if isinstance(part, str): # part is a plain string segment
if not filter_set and not escaped_chars:
# Fast path: no escaping or filtering needed
result.append(part)
elif not filter_set and escaped_chars:
# Only escaping needed, process character-by-character only if necessary
if any(c in escaped_chars for c in part):
for c in part:
if c in escaped_chars and escape_char is not None:
result.append(escape_char)
result.append(c)
else:
result.append(part)
else:
# Both filtering and escaping
for c in part:
if c in filter_set:
continue
if c in escaped_chars and escape_char is not None:
result.append(escape_char)
result.append(c)
elif isinstance(part, SpecialChars): # special handling for special characters
if part == SpecialChars.WILDCARD_MULTI:
if wildcard_multi is not None:
result.append(wildcard_multi)
else:
raise SigmaValueError(
"Multi-character wildcard not specified for conversion"
)
elif part == SpecialChars.WILDCARD_SINGLE:
if wildcard_single is not None:
result.append(wildcard_single)
else:
raise SigmaValueError(
"Single-character wildcard not specified for conversion"
)
elif isinstance(part, Placeholder):
raise SigmaPlaceholderError(
f"Attempt to convert unhandled placeholder '{part.name}' into query."
)
else:
raise SigmaValueError(
f"Trying to convert SigmaString containing part of type '{type(part).__name__}'"
)
return "".join(result)
[docs]
def to_regex(self, custom_escaped: str = "") -> "SigmaRegularExpression":
"""Convert SigmaString into a regular expression."""
return SigmaRegularExpression(
self.convert(
escape_char="\\",
wildcard_multi=".*",
wildcard_single=".",
add_escaped=".*+?^$[](){}\\|" + custom_escaped,
)
)
[docs]
def upper(self) -> "SigmaString":
return self.map_str_parts(str.upper)
[docs]
def lower(self) -> "SigmaString":
return self.map_str_parts(str.lower)
[docs]
def snake_case(self) -> "SigmaString":
return self.map_parts(
lambda x: re.sub(
r"(?<!^)(?=[A-Z])",
"_",
cast(
str, x
), # str type ensured by filtering for str in next parameter of map_parts
).lower(),
lambda x: isinstance(x, str),
)
[docs]
class SigmaCasedString(SigmaString):
"""Case-sensitive string matching."""
[docs]
@classmethod
def from_sigma_string(cls, s: SigmaString) -> "SigmaCasedString":
cs = cls(s.original)
cs.s = s.s
return cs
[docs]
@dataclass
class SigmaNumber(SigmaType):
"""Numeric value type"""
number: int | float = field(init=False, repr=True)
init_number: InitVar[Any]
def __post_init__(self, init_number: Any) -> None:
try: # Only use float number if it can't be represented as int.
f = float(init_number)
if not isfinite(f):
raise ValueError("Invalid number")
i = int(init_number)
if i == f:
self.number = i
else:
self.number = f
except (ValueError, OverflowError) as e:
raise SigmaValueError("Invalid number") from e
def __str__(self) -> str:
return str(self.number)
def __eq__(self, other: object) -> bool:
if isinstance(other, (int, float)):
return self.number == other
elif isinstance(other, SigmaNumber):
return bool(self.number == other.number)
else:
raise NotImplementedError(
"SigmaNumber can only be compared with a number or another SigmaNumber"
)
[docs]
class SigmaTimestampPart(SigmaNumber):
timestamp_part: TimestampPart
[docs]
def __init__(self, timestamp_part: TimestampPart, number: int):
self.timestamp_part = timestamp_part
super().__init__(number)
[docs]
@dataclass
class SigmaBool(SigmaType):
"""Boolean value type"""
boolean: bool
def __post_init__(self) -> None:
if not isinstance(self.boolean, bool):
raise SigmaTypeError("SigmaBool must be a boolean")
def __str__(self) -> str:
return str(self.boolean)
def __bool__(self) -> bool:
return self.boolean
def __eq__(self, other: object) -> bool:
if isinstance(other, bool):
return self.boolean == other
elif isinstance(other, self.__class__):
return self.boolean == other.boolean
else:
raise NotImplementedError(
"SigmaBool can only be compared with a boolean or another SigmaBool"
)
[docs]
class SigmaRegularExpressionFlag(Enum):
IGNORECASE = auto()
MULTILINE = auto()
DOTALL = auto()
[docs]
@dataclass
class SigmaRegularExpression(SigmaType):
"""Regular expression type"""
regexp: SigmaString = field(init=False)
regexp_init: InitVar[SigmaString | str]
flags: set[SigmaRegularExpressionFlag] = field(default_factory=set)
policy: SigmaPolicy | None = field(default=None, compare=False)
sigma_to_python_flags: ClassVar[dict[SigmaRegularExpressionFlag, re.RegexFlag]] = {
SigmaRegularExpressionFlag.IGNORECASE: re.IGNORECASE,
SigmaRegularExpressionFlag.MULTILINE: re.MULTILINE,
SigmaRegularExpressionFlag.DOTALL: re.DOTALL,
}
sigma_to_re_flag: ClassVar[dict[SigmaRegularExpressionFlag, str]] = {
SigmaRegularExpressionFlag.IGNORECASE: "i",
SigmaRegularExpressionFlag.MULTILINE: "m",
SigmaRegularExpressionFlag.DOTALL: "s",
}
def __post_init__(
self,
regexp_init: str | SigmaString,
) -> None:
if isinstance(regexp_init, str):
regexp_init = SigmaString(regexp_init, escape=False)
self.regexp = regexp_init
self.compile()
[docs]
def add_flag(self, flag: SigmaRegularExpressionFlag) -> None:
self.flags.add(flag)
[docs]
def compile(self) -> None:
"""Verify if regular expression is valid by compiling it"""
from sigma.policy import default_policy
engine = (self.policy or default_policy).regex_engine
try:
flags = 0
for flag in self.flags:
flags |= self.sigma_to_python_flags[flag]
engine.compile(str(self.regexp), flags)
except engine.error as e:
raise SigmaRegularExpressionError(
f"Regular expression '{str(self.regexp)}' is invalid: {str(e)}"
) from e
[docs]
def to_plain(self) -> str:
return self.regexp.to_plain()
[docs]
def escape(
self,
escaped: list[str] = cast(list[str], ()),
escape_char: str = "\\",
escape_escape_char: bool = True,
flag_prefix: bool = True,
) -> str:
"""Escape strings from escaped tuple as well as escape_char itself (can be disabled with
escape_escape_char) with escape_char. Prepends a (?...) expression with set flags (i, m and
s) if flag_prefix is set."""
r = "|".join(
[ # Generate regular expressions from sequences that should be escaped and the escape char itself
re.escape(e)
for e in [*escaped, escape_char if escape_escape_char else None]
if e is not None
]
)
regexp_str = str(self.regexp)
pos = (
[ # determine positions of matches in regular expression
m.start() for m in re.finditer(r, regexp_str)
]
if r != ""
else []
)
ranges = list(
zip([None, *pos], [*pos, None])
) # string chunk ranges with escapes in between
if flag_prefix and self.flags:
prefix = (
"(?" + "".join(sorted((self.sigma_to_re_flag[flag] for flag in self.flags))) + ")"
)
else:
prefix = ""
return prefix + escape_char.join([regexp_str[i:j] for i, j in ranges])
[docs]
def contains_placeholder(
self, include: list[str] | None = None, exclude: list[str] | None = None
) -> bool:
return self.regexp.contains_placeholder(include, exclude)
[docs]
def insert_placeholders(self) -> "SigmaRegularExpression":
"""
Replace %something% placeholders with Placeholder stub objects that can be later handled by the processing
pipeline. This implements the expand modifier.
"""
self.regexp = self.regexp.insert_placeholders()
self.compile() # recompile after inserting placeholders
return self
[docs]
def replace_placeholders(
self,
callback: Callable[
[Placeholder], Iterator[str | SpecialChars | Placeholder | "SigmaString"]
],
) -> list["SigmaRegularExpression"]:
"""
Replace all occurrences of string part matching regular expression with placeholder.
"""
return [
SigmaRegularExpression(str(sigmastr), self.flags)
for sigmastr in self.regexp.replace_placeholders(callback)
]
[docs]
@dataclass
class SigmaCIDRExpression(NoPlainConversionMixin, SigmaType):
"""CIDR IP address range expression type"""
cidr: str
source: SigmaRuleLocation | None = None
network: IPv4Network | IPv6Network = field(init=False, compare=False)
def __post_init__(self) -> None:
"""Verify if cidr is valid by re"""
try:
self.network = ip_network(self.cidr)
except ValueError as e:
raise SigmaTypeError("Invalid CIDR expression: " + str(e), source=self.source)
def __str__(self) -> str:
return self.cidr
[docs]
def expand(
self,
wildcard: str = "*",
) -> list[str]:
"""
Convert CIDR range into a list of wildcard patterns or plain CIDR notation. The following parameters allow to change the behavior:
* wildcard: string that should be output as wildcard. Usually not required because this is
passed to SigmaString that generates a wildcard pecial character from '*' that is
converted into possible individual wildcard characters.
Setting wildcard to None indicates that this feature is not need and the query language handles CIDR notation properly.
"""
if (
wildcard is None
): # The query language handles CIDR notation properly: return the network itself in CIDR notation
return [str(self.network)]
patterns = []
if isinstance(
self.network, IPv4Network
): # IPv4, algorithm: each group of an IPv4 address represents 8 bit. Therefore, we align to 8 bit boundaries, iterate over the remaining bits and put a wildcard at the end (if not /32)
prefix_rem8 = (
self.network.prefixlen % 8
) # This variable stores the number of bits exceeding the previous 8 bit boundary
prefix_diff = (
8 - prefix_rem8
) % 8 # We want the next 8 bit boundary to expand into smaller subnets, therefore the other side of the remainder is used.
for subnet in self.network.subnets(
prefix_diff
): # Generate all the subnetworks where the prefix ends at the next 8 bit boundary
wildcard_group = (
subnet.prefixlen // 8
) # Determine group that has to be replaced with wildcard: 8 bit boundary before prefix
subnet_groups = str(subnet.network_address).split(".")
if wildcard_group == 0: # Not all groups are static, add wildcard
patterns.append(wildcard)
elif wildcard_group < 4: # Not all groups are static, add wildcard
patterns.append(".".join(subnet_groups[:wildcard_group]) + "." + wildcard)
else: # /32 - no wildcard is set
patterns.append(
str(subnet.network_address)
) # Return single address subnet without wildcard
else: # IPv6, algorithm: each hex digit of an IPv6 address represents 4 bit. Therefore, we align to 4 bit boundaries and iterate over the remaining bits.
prefix_rem4 = (
self.network.prefixlen % 4
) # This variable stores the number of bits exceeding the previous 4 bit boundary
prefix_diff = (
4 - prefix_rem4
) % 4 # We want the next 4 bit boundary to expand into smaller subnets, therefore the other side of the remainder is used.
for subnet_v6 in self.network.subnets(
prefix_diff
): # Generate all the subnetworks where the prefix ends at the next 4 bit boundary
for pattern in self._expand_ipv6_subnet(subnet_v6, wildcard):
if pattern not in patterns:
patterns.append(pattern)
# Remove patterns that are covered by another pattern ending with a wildcard.
patterns = [
pattern
for pattern in patterns
if not any(
other != pattern
and other.endswith(wildcard)
and pattern.startswith(other[: -len(wildcard)])
for other in patterns
)
]
# Some log sources, e.g. Sysmon network events, write IPv6 addresses uncompressed.
# Add patterns for this representation that are not already covered by the RFC 5952
# patterns above.
uncompressed: list[str] = []
for subnet_v6 in self.network.subnets(prefix_diff):
for pattern in self._expand_ipv6_subnet_uncompressed(subnet_v6, wildcard):
if pattern not in uncompressed:
uncompressed.append(pattern)
patterns += [
pattern
for pattern in uncompressed
if pattern not in patterns
and not any(
other != pattern
and other.endswith(wildcard)
and pattern.startswith(other[: -len(wildcard)])
for other in patterns + uncompressed
)
]
return patterns
@staticmethod
def _ipv6_groups(address: IPv6Address) -> list[str]:
"""
Return the eight groups of an IPv6 address as four-digit hexadecimal strings.
IPv6Address.exploded can't be used for this, because current Python versions write the
last 32 bits of IPv4-mapped addresses in dotted notation.
"""
digits = format(int(address), "032x")
return [digits[i : i + 4] for i in range(0, 32, 4)]
@staticmethod
def _expand_ipv6_subnet_uncompressed(subnet: IPv6Network, wildcard: str) -> list[str]:
"""
Generate wildcard patterns that match the uncompressed textual representation written
by some log sources, e.g. Sysmon network events (all eight groups, lower case, no
leading zeros, no :: compression, e.g. 0:0:0:0:0:0:0:1 for ::1), of all addresses of an
IPv6 network whose prefix length is a multiple of 4. Groups are handled like in
_expand_ipv6_subnet.
"""
fixed_groups, rem = divmod(subnet.prefixlen, 16)
fixed_nibbles = rem // 4
exploded = SigmaCIDRExpression._ipv6_groups(subnet.network_address)
fixed = [format(int(group, 16), "x") for group in exploded[:fixed_groups]]
if fixed_groups == 8: # single address
return [":".join(fixed)]
if fixed_nibbles == 0: # first group not covered by prefix
partial = [wildcard]
else: # group partially covered by prefix
nibbles = exploded[fixed_groups][:fixed_nibbles]
free_digits = 4 - fixed_nibbles
if int(nibbles, 16) != 0:
partial = [nibbles.lstrip("0") + "?" * free_digits]
else:
partial = ["?" * n for n in range(1, free_digits + 1)]
# Everything after the first group not covered completely by the prefix is a wildcard.
rest = [wildcard] if fixed_nibbles > 0 and fixed_groups < 7 else []
return [":".join(fixed + [group] + rest) for group in partial]
@staticmethod
def _expand_ipv6_subnet(subnet: IPv6Network, wildcard: str) -> list[str]:
"""
Generate wildcard patterns that match the textual representation (RFC 5952: lower case,
no leading zeros, the longest run of at least two zero groups compressed to ::) of all
addresses of an IPv6 network whose prefix length is a multiple of 4.
The textual representation depends on which groups are zero, because of the :: compression.
Therefore, all possible combinations of zero and non-zero groups are enumerated and the
resulting pattern is generated for each of them. Groups covered completely by the prefix
are emitted as they are, a group covered partially by the prefix is emitted as fixed digits
followed by single-character wildcards for the remaining digits, and groups not covered by
the prefix are emitted as wildcard.
Wildcards can't express the number of groups compressed by :: and single-character
wildcards also match a colon. Therefore, the patterns still match some addresses outside
of the network, e.g. if the :: of a pattern must cover more than two zero groups. Backends
should prefer native CIDR matching where available.
"""
if subnet.prefixlen == 128: # single address
return [str(subnet.network_address)]
fixed_groups, rem = divmod(subnet.prefixlen, 16)
fixed_nibbles = rem // 4
exploded = SigmaCIDRExpression._ipv6_groups(subnet.network_address)
# For each group: list of possible textual representations if the group is not part of
# the compressed zero run and whether the group can be zero / non-zero.
group_texts: list[list[str]] = []
can_be_zero: list[bool] = []
can_be_nonzero: list[bool] = []
for i, group in enumerate(exploded):
if i < fixed_groups: # group is completely covered by the prefix
value = int(group, 16)
group_texts.append([format(value, "x")])
can_be_zero.append(value == 0)
can_be_nonzero.append(value != 0)
elif i == fixed_groups and fixed_nibbles > 0: # group is partially covered by prefix
nibbles = group[:fixed_nibbles]
free_digits = 4 - fixed_nibbles
# Fixed digits are non-zero: the digit count is fixed, but leading zeros are
# omitted (e.g. fixed "0a" with two free digits is written as "a??")
if int(nibbles, 16) != 0:
group_texts.append([nibbles.lstrip("0") + "?" * free_digits])
can_be_zero.append(False)
else: # group value is below 16**free_digits: 1 up to free_digits digits
group_texts.append(["?" * n for n in range(1, free_digits + 1)])
can_be_zero.append(True)
can_be_nonzero.append(True)
else: # group not covered by prefix
group_texts.append([wildcard])
can_be_zero.append(True)
can_be_nonzero.append(True)
patterns: dict[str, None] = {} # insertion-ordered de-duplication
for zero_groups in product(*([False, True] for _ in range(8))):
if any(
(is_zero and not can_be_zero[i]) or (not is_zero and not can_be_nonzero[i])
for i, is_zero in enumerate(zero_groups)
):
continue
# Determine the zero run that is compressed to :: (longest, first one on ties, at least
# two groups).
run_start, run_len = 0, 0
i = 0
while i < 8:
if zero_groups[i]:
j = i
while j < 8 and zero_groups[j]:
j += 1
if j - i > run_len:
run_start, run_len = i, j - i
i = j
else:
i += 1
for texts in product(*group_texts):
if run_len >= 2:
pattern = (
":".join(texts[:run_start]) + "::" + ":".join(texts[run_start + run_len :])
)
else:
pattern = ":".join(texts)
# Everything after a wildcard that is not preceded by :: is covered by the wildcard.
wildcard_pos = pattern.find(wildcard)
if wildcard_pos >= 0 and "::" not in pattern[:wildcard_pos]:
pattern = pattern[: wildcard_pos + len(wildcard)]
patterns[pattern] = None
return list(patterns)
[docs]
class CompareOperators(Enum):
LT = auto() # <
LTE = auto() # <=
GT = auto() # >
GTE = auto() # >=
NEQ = auto() # !=
[docs]
@dataclass
class SigmaCompareExpression(NoPlainConversionMixin, SigmaType):
"""Type for numeric comparison."""
number: SigmaNumber
op: CompareOperators
source: SigmaRuleLocation | None = None
CompareOperators: ClassVar[Type["CompareOperators"]] = CompareOperators
def __post_init__(self) -> None:
if not isinstance(self.number, SigmaNumber):
raise SigmaTypeError("Compare operator expects number", source=self.source)
[docs]
@dataclass
class SigmaFieldReference(NoPlainConversionMixin, SigmaType):
"""Type for referencing to other fields for comparison between them."""
field: str
starts_with: bool = False
ends_with: bool = False
[docs]
@dataclass
class SigmaQueryExpression(NoPlainConversionMixin, SigmaType):
"""
Special purpose type for passing a query part (e.g. list lookups in placeholders) directly into the generated
query. The query string may contain a {field} placeholder, which is replaced with the field name contained in
the detection item containing the query expression. This is done by the finalize method.
Because this is very specific to the target language, it has to be used in late stages of the conversion
process by backend-specific processing pipelines or the backend itself.
"""
expr: str
id: str
def __post_init__(self) -> None:
if not isinstance(self.expr, str):
raise SigmaTypeError("SigmaQueryExpression expression must be a string")
if not isinstance(self.id, str):
raise SigmaTypeError("SigmaQueryExpression placeholder identifier must be a string")
def __str__(self) -> str:
return self.expr
[docs]
def has_field_placeholder(self) -> bool:
return "{field}" in self.expr
[docs]
def finalize(self, field: str | None = None) -> str:
if field is None and self.has_field_placeholder():
raise SigmaValueError(
f"Query expression '{ self.expr }' has a field placeholder but no field was given in finalization"
)
return self.expr.format(field=field, id=self.id)
[docs]
@dataclass
class SigmaExpansion(NoPlainConversionMixin, SigmaType):
"""
Special purpose type for correct logic linking of values expanded by modifiers. In the usual
cases the writer of a Sigma rule expects the values expanded by modifiers like base64offset or
windash are OR-linked, even if the value list containing the original values is linked with AND
by modifying it with 'all'. A SigmaExpansion is emitted by such modifiers, contains the
expanded values and is converted as follows:
1. the whole expansion is handled as group which is enclosed in parentheses.
2. the values contained in the expansion are linked with OR, independent from the linking of the
context that encloses the expansion.
"""
values: list[SigmaType]
type_map: dict[type, Type[SigmaType]] = {
bool: SigmaBool,
int: SigmaNumber,
float: SigmaNumber,
str: SigmaString,
type(None): SigmaNull,
}
[docs]
def sigma_type(v: (int | float | str | bool) | None) -> SigmaType:
"""Return Sigma type from Python value"""
# Check bool before int since bool is a subclass of int in Python
if isinstance(v, bool):
return SigmaBool(v)
matched = type_map.get(type(v))
if matched is not None:
return matched(v)
# Fallback to isinstance checks for subclasses
for t, st in type_map.items():
if isinstance(v, t):
return st(v)
raise SigmaTypeError(f"Unsupported type: {type(v)}")