Source code for sigma.processing.transformations.values

from collections import defaultdict
from sigma.conditions import ConditionAND, ConditionOR
from typing import (
    Any,
    ClassVar,
    Literal,
    Optional,
    Tuple,
    TYPE_CHECKING,
    Union,
    cast,
)
from dataclasses import InitVar, dataclass, field
import re
from sigma.processing.transformations.base import (
    DetectionItemTransformation,
    StringValueTransformation,
    ValueTransformation,
)
from sigma.rule import SigmaDetection, SigmaDetectionItem
from sigma.exceptions import (
    SigmaRegularExpressionError,
    SigmaValueError,
    SigmaConfigurationError,
)
from sigma.policy.regex_engine import RegexPattern
from sigma.types import (
    Placeholder,
    SigmaBool,
    SigmaExpansion,
    SigmaNull,
    SigmaNumber,
    SigmaRegularExpression,
    SigmaRegularExpressionFlag,
    SigmaString,
    SigmaStringPartType,
    SigmaType,
    SpecialChars,
)

if TYPE_CHECKING:
    from sigma.policy.regex_engine import RegexEngine


[docs] @dataclass class HashesFieldsDetectionItemTransformation(DetectionItemTransformation): """ Transforms the 'Hashes' field in Sigma rules by creating separate detection items for each hash type. This transformation replaces the generic 'Hashes' field with specific fields for each hash algorithm, optionally prefixing the field names. It supports various hash formats and can auto-detect hash types based on their length. Attributes: valid_hash_algos (list[str]): List of supported hash algorithms. field_prefix (str): Prefix to add to the new field names. drop_algo_prefix (bool): If True, omits the algorithm name from the new field name. field_to_parse (list[str]): List of field names to parse for hash values. Defaults to ["Hashes", "Hash"]. hash_lengths (dict[int, str]): Mapping of hash lengths to their corresponding algorithms. Example: Input: Hashes: - 'SHA1=5F1CBC3D99558307BC1250D084FA968521482025' - 'MD5=987B65CD9B9F4E9A1AFD8F8B48CF64A7' Output: FileSHA1: '5F1CBC3D99558307BC1250D084FA968521482025' FileMD5: '987B65CD9B9F4E9A1AFD8F8B48CF64A7' """ valid_hash_algos: list[str] field_prefix: str = "" drop_algo_prefix: bool = False field_to_parse: list[str] = field(default_factory=lambda: ["Hashes", "Hash"]) hash_lengths: ClassVar[dict[int, str]] = {32: "MD5", 40: "SHA1", 64: "SHA256", 128: "SHA512"}
[docs] def apply_detection_item( self, detection_item: SigmaDetectionItem ) -> (SigmaDetection | SigmaDetectionItem) | None: """ Applies the transformation to a single detection item. Args: detection_item (SigmaDetectionItem): The detection item to transform. Returns: (SigmaDetection | SigmaDetectionItem) | None: A new SigmaDetection object containing the transformed detection items, or None if no valid hashes were found. Raises: Exception: If no valid hash algorithms were found in the detection item. """ if detection_item.field not in self.field_to_parse: return None if ( isinstance(detection_item.value, SigmaString) or isinstance(detection_item.value, list) and all(isinstance(v, SigmaString) for v in detection_item.value) ): values = detection_item.value if not isinstance(values, list): values = [values] algo_dict = self._parse_hash_values(cast(list[SigmaString], values)) if not algo_dict: raise SigmaValueError( f"No valid hash algorithm found in Hashes field. Please use one of the following: {', '.join(self.valid_hash_algos)}" ) return self._create_new_detection_items(algo_dict) else: return None
def _parse_hash_values(self, values: list[SigmaString]) -> dict[str, list[str]]: """ Parses the hash values from the detection item. Args: values (SigmaString | list[SigmaString]): The hash values to parse. Returns: dict[str, list[str]]: A dictionary mapping field names to lists of hash values. """ algo_dict = defaultdict(list) for value in values: hash_algo, hash_value = self._extract_hash_algo_and_value(value.to_plain()) if hash_algo: field_name = self._get_field_name(hash_algo) algo_dict[field_name].append(hash_value) return algo_dict def _extract_hash_algo_and_value(self, value: str) -> tuple[str, str]: """ Extracts the hash algorithm and value from a string. Args: value (str): The string containing the hash algorithm and value. Returns: tuple[str, str]: A tuple containing the hash algorithm and value. """ parts = value.split("|") if "|" in value else value.split("=") if len(parts) == 2: hash_algo, hash_value = parts hash_algo = hash_algo.lstrip("*").upper() hash_value = hash_value.strip("*?") else: hash_value = parts[0].strip("*?") hash_algo = self._determine_hash_algo_by_length(hash_value) return (hash_algo, hash_value) if hash_algo in self.valid_hash_algos else ("", hash_value) def _determine_hash_algo_by_length(self, hash_value: str) -> str: """ Determines the hash algorithm based on the length of the hash value. Args: hash_value (str): The hash value to analyze. Returns: str: The determined hash algorithm, or an empty string if not recognized. """ return self.hash_lengths.get(len(hash_value), "") def _get_field_name(self, hash_algo: str) -> str: """ Generates the field name for a given hash algorithm. Args: hash_algo (str): The hash algorithm. Returns: str: The generated field name. """ return f"{self.field_prefix}{'' if self.drop_algo_prefix else hash_algo}" def _create_new_detection_items(self, algo_dict: dict[str, list[str]]) -> SigmaDetection: """ Creates new detection items based on the parsed hash values. Args: algo_dict (dict[str, list[str]]): A dictionary mapping field names to lists of hash values. Returns: SigmaDetection: A new SigmaDetection object containing the created detection items. """ return SigmaDetection( detection_items=[ SigmaDetectionItem( field=k if k != "keyword" else None, modifiers=[], value=[SigmaString(x) for x in v], ) for k, v in algo_dict.items() if k ], item_linking=ConditionOR, )
[docs] @dataclass class ReplaceStringTransformation(StringValueTransformation): """ Replace string part matched by regular expresssion with replacement string that can reference capture groups. Normally, the replacement operates on the plain string representation of the SigmaString. This allows also to include special characters and placeholders in the replacement. By enabling the skip_special parameter, the replacement is only applied to the plain string parts of a SigmaString and special characters and placeholders are left untouched. The interpret_special option determines for skip_special if special characters and placeholders are interpreted in the replacement result or not. The replacement is implemented with re.sub() and can use all features available there. """ regex: str replacement: str skip_special: bool = False interpret_special: bool = False def __post_init__(self) -> None: super().__post_init__() engine = self.resolve_regex_engine() try: self.compile_regex(self.regex) except engine.error as e: raise SigmaRegularExpressionError( f"Regular expression '{self.regex}' is invalid: {str(e)}" ) from e
[docs] def apply_value( self, field: str | None, val: SigmaType ) -> (SigmaType | list[SigmaType]) | None: if isinstance(val, SigmaNumber): return self.apply_string_value(field, SigmaString(str(val))) return super().apply_value(field, val)
[docs] def apply_string_value(self, field: str | None, val: SigmaString) -> SigmaString: if isinstance(val, SigmaString): if self.skip_special: return val.map_parts( lambda s: self.regex_sub( self.regex, self.replacement, cast(str, s) ), # filter function in second parameter ensures str type. lambda p: isinstance(p, str), self.interpret_special, ) else: return self._replace_plain(val)
def _parse_plain(self, plain: str, placeholders: bool) -> list[SigmaStringPartType]: """ Parse a fragment of the plain string representation that was produced by the replacement. Backslashes are literal unless they escape a wildcard character. """ s = SigmaString(re.sub(r"\\(?![*?])", r"\\\\", plain)) if placeholders: # Preserve placeholders s = s.insert_placeholders() return s.s def _replace_plain(self, val: SigmaString) -> SigmaString: """ Apply the replacement to the plain string representation of val. The plain representation is ambiguous: a literal backslash followed by a wildcard (e.g. C:\\Windows\\*) is rendered like an escaped wildcard character. Therefore only the replaced text is parsed from the plain representation, while all text not matched by the regular expression is taken over from the original parts of val. """ # Plain representation of val and the plain text span of each original part. plain = "" spans: list[tuple[int, int, SigmaStringPartType]] = [] for part in val.s: if isinstance(part, str): for c in part: text = "\\" + c if c in ("*", "?") else c spans.append((len(plain), len(plain) + len(text), c)) plain += text else: part_string = SigmaString() part_string.s = [part] text = part_string.to_plain() spans.append((len(plain), len(plain) + len(text), part)) plain += text placeholders = val.contains_placeholder() result: list[SigmaStringPartType] = [] pending = "" # replaced plain text that still has to be parsed def flush_pending() -> None: nonlocal pending if pending: result.extend(self._parse_plain(pending, placeholders)) pending = "" def keep_original(start: int, end: int) -> None: """Take over the original parts between the plain string positions start and end.""" nonlocal pending for span_start, span_end, part in spans: if span_end <= start or span_start >= end: continue if span_start >= start and span_end <= end: flush_pending() result.append(part) else: # part only partially outside of a match: parse with the replaced text pending += plain[max(span_start, start) : min(span_end, end)] pos = 0 for match in self.regex_finditer(self.regex, plain): keep_original(pos, match.start()) pending += match.expand(self.replacement) pos = match.end() keep_original(pos, len(plain)) flush_pending() replaced = SigmaString() replaced.s = result return replaced._merge_strs()
[docs] @dataclass class MapStringTransformation(StringValueTransformation): """ Map static string value to one or multiple other strings. """ mapping: dict[str, str | list[str]]
[docs] def apply_string_value( self, field: str | None, val: SigmaString ) -> (SigmaType | list[SigmaType]) | None: mapped = self.mapping.get(str(val), None) if isinstance(mapped, str): return SigmaString(mapped) elif isinstance(mapped, list): return [SigmaString(item) for item in mapped] else: return None
[docs] @dataclass class RegexTransformation(StringValueTransformation): """ Transform a string value to a case insensitive regular expression. The following methods are available and can be selected with the method parameter: * plain: Convert the string to a regular expression without any change to its case. In most cases this should result in a case-sensitive match of the string. * case_insensitive_flag: Add the case insensitive flag to the regular expression. * case_insensitive_brackets (default): Wrap each character in a bracket expression like [aA] to match both case variants. This transformation is intended to be used to emulate case insensitive matching in backends that don't support it natively. """ method: Literal["plain", "ignore_case_flag", "ignore_case_brackets"] = "ignore_case_brackets" def __post_init__(self) -> None: if self.method not in type(self).__annotations__["method"].__args__: raise SigmaConfigurationError( f"Invalid method '{self.method}' for CaseInsensitiveRegexTransformation." ) return super().__post_init__()
[docs] def apply_string_value(self, field: str | None, val: SigmaString) -> SigmaType | None: regex = "" # empty string can not be convert into a simple regex if val == "": return val for sc in val.s: # iterate over all SigmaString components (strings and special chars) if isinstance(sc, str): # if component is a string if ( self.method == "ignore_case_brackets" ): # wrap each character in a bracket expression regex += "".join( f"[{c.lower()}{c.upper()}]" if c.isalpha() else re.escape(c) for c in sc ) else: regex += re.escape(sc) elif ( sc == SpecialChars.WILDCARD_MULTI ): # if component is a wildcard, add it as regex .* regex += ".*" elif ( sc == SpecialChars.WILDCARD_SINGLE ): # if component is a single wildcard, add it as regex . regex += "." elif isinstance(sc, Placeholder): # Placeholders are not allowed in regex raise SigmaConfigurationError( f"Placeholder '{sc.name}' can't be converted to a regular expression. Please use a placeholder resolution transformation before." ) if self.method == "ignore_case_flag": return SigmaRegularExpression(regex, {SigmaRegularExpressionFlag.IGNORECASE}) else: return SigmaRegularExpression(regex)
[docs] @dataclass class SetValueTransformation(ValueTransformation): """ Set value to a fixed value. The type of the value can be enforced to `str` or `num` with the force_type parameter. """ value: InitVar[(str | int | float | bool) | None] force_type: Literal["str", "num"] | None = None sigma_value: SigmaType = field(init=False) def __post_init__(self, value: (str | int | float | bool) | None) -> None: if self.force_type is None: # no type forced, use type of value if isinstance(value, str): self.sigma_value = SigmaString(value) elif isinstance(value, bool): self.sigma_value = SigmaBool(value) elif isinstance(value, (int, float)): self.sigma_value = SigmaNumber(value) elif value is None: self.sigma_value = SigmaNull() else: raise SigmaConfigurationError( f"Unsupported value type '{type(value)}' for SetValueTransformation" ) else: # forced type if not isinstance(value, (str, int, float)): # only allowed for certain types raise SigmaConfigurationError( f"force_type '{self.force_type}' is only allowed for string and numeric values" ) if self.force_type == "str": self.sigma_value = SigmaString(str(value)) elif self.force_type == "num": try: self.sigma_value = SigmaNumber(value) except SigmaValueError: raise SigmaConfigurationError( f"Value '{value}' can't be converted to number while initializing SimgaValueTransformation" ) else: raise SigmaConfigurationError( f"Invalid force_type '{self.force_type}' in SigmaValueTransformation" ) super().__post_init__()
[docs] def apply_value(self, field: str | None, val: SigmaType) -> SigmaType: return self.sigma_value
[docs] @dataclass class ConvertTypeTransformation(ValueTransformation): """ Convert type of value. The conversion into strings and numbers is currently supported. """ target_type: Literal["str", "num"]
[docs] def apply_value( self, field: str | None, val: SigmaType ) -> (SigmaString | SigmaNumber | SigmaExpansion) | None: if self.target_type == "str": # Only convert SigmaNumber to SigmaString if isinstance(val, SigmaNumber): return SigmaString(str(val)) if isinstance(val, SigmaExpansion): for i, entry in enumerate(val.values): # Only convert SigmaNumber entries to SigmaString if isinstance(entry, SigmaNumber): val.values[i] = SigmaString(str(entry)) return val # Return None for other types - no conversion return None elif self.target_type == "num": # Only convert SigmaString to SigmaNumber if isinstance(val, SigmaString): try: return SigmaNumber(str(val)) except SigmaValueError: raise SigmaValueError( f"Value '{val}' can't be converted to number for {str(self)}" ) if isinstance(val, SigmaExpansion): for i, entry in enumerate(val.values): # Only convert SigmaString entries to SigmaNumber if isinstance(entry, SigmaString): try: val.values[i] = SigmaNumber(str(entry)) except SigmaValueError: raise SigmaValueError( f"Value '{entry}' can't be converted to number for {str(self)}" ) return val # Return None for other types - no conversion return None
[docs] @dataclass class CaseTransformation(StringValueTransformation): """ Transform a string value to a lower or upper or snake case. """ method: Literal["lower", "upper", "snake_case"] = "lower" def __post_init__(self) -> None: if self.method not in type(self).__annotations__["method"].__args__: raise SigmaConfigurationError(f"Invalid method '{self.method}' for CaseTransformation.") return super().__post_init__()
[docs] def apply_string_value(self, field: str | None, val: SigmaString) -> SigmaString | None: if self.method == "snake_case": return val.snake_case() elif self.method == "lower": return val.lower() else: return val.upper()
[docs] @dataclass class ExtractFieldsTransformation(DetectionItemTransformation): """ Transforms values matching a regex pattern with named groups into separate detection items. Extracts named capture groups from a regex match and creates one detection item per group. Each item uses the field prefix followed by the group name: - {field_prefix}.{group_name}: captured value Example: regex = r"(?P<type>[A-Za-z]+):(?P<valeur>[0-9]+)" field_prefix = "reg" Input: reg: "Dword:00001" Output: reg.type: "Dword", reg.valeur: "00001" Multiple values are each transformed independently. Each value's extracted fields are AND-linked within a nested SigmaDetection, and the outer linking follows the detection item's value_linking (default OR). The regex pattern must contain at least one named group. Groups without names are ignored. Type conversion for captured values: - "null", "none", or empty string -> SigmaNull - Integer strings (without leading zeros, except "0") -> SigmaNumber(int) - Float strings (without leading zeros) -> SigmaNumber(float) - All other strings -> SigmaString Strings with leading zeros (e.g., "00001", "03.14") are preserved as SigmaString to avoid losing the leading zero information. To restrict this transformation to specific fields, use the :class:`~sigma.processing.conditions.IncludeFieldCondition` in the processing item's field_name_conditions instead of a field list attribute on the transformation. Attributes: regex (str): Regex pattern with named groups (e.g., (?P<name>pattern)). field_prefix (str | None): Prefix for field names. Used as {field_prefix}.{group_name}. If None, only the group name is used as the field name. preserve_unmatched (bool): If True, values that don't match the regex are preserved as-is in the original field. If False (default), non-matching values are dropped. """ regex: str field_prefix: str | None = None preserve_unmatched: bool = False def __post_init__(self) -> None: if hasattr(super(), "__post_init__"): super().__post_init__() # type: ignore[misc] engine = self.resolve_regex_engine() try: compiled = self.compile_regex(self.regex) except engine.error as e: raise SigmaRegularExpressionError( f"Regular expression '{self.regex}' is invalid: {str(e)}" ) from e if not compiled.groupindex: raise SigmaRegularExpressionError( f"Regular expression '{self.regex}' must contain at least one named group" ) import re as _re group_names = _re.findall(r"\(\?P<([^>]+)>", self.regex) if len(group_names) != len(set(group_names)): raise SigmaRegularExpressionError( f"Regular expression '{self.regex}' is invalid: contains duplicate named groups" ) def _convert_value(self, value: str) -> SigmaType: if value.lower() in ("null", "none", ""): return SigmaNull() if value != "0" and value.startswith("0"): return SigmaString(value) try: return SigmaNumber(int(value)) except ValueError: try: return SigmaNumber(float(value)) except ValueError: return SigmaString(value)
[docs] def apply_detection_item(self, detection_item: SigmaDetectionItem) -> SigmaDetection | None: if not isinstance(detection_item.value, list) or not all( isinstance(v, SigmaString) for v in detection_item.value ): return None value_detections: list[SigmaDetectionItem | SigmaDetection] = [] for val in detection_item.value: plain = val.to_plain() match = self.regex_match(self.regex, plain) if not match: # Value doesn't match - handle based on preserve_unmatched setting if self.preserve_unmatched: # Preserve the original value as-is value_detections.append( SigmaDetectionItem( field=detection_item.field, modifiers=[], value=[val], ) ) # Otherwise, skip this value (dropped from results) continue items: list[SigmaDetectionItem | SigmaDetection] = [] for group_name, group_value in match.groupdict().items(): if group_value is None or group_value == "": continue field_name = ( f"{self.field_prefix}.{group_name}" if self.field_prefix else group_name ) items.append( SigmaDetectionItem( field=field_name, modifiers=[], value=[self._convert_value(group_value)], ) ) if items: value_detections.append( SigmaDetection(detection_items=items, item_linking=ConditionAND) ) if not value_detections: return None if len(value_detections) == 1: return cast(SigmaDetection, value_detections[0]) return SigmaDetection( detection_items=value_detections, item_linking=detection_item.value_linking, )