|
| 1 | +"""Extract field names from Sigma rules.""" |
| 2 | +from __future__ import annotations |
| 3 | + |
| 4 | +from operator import add |
| 5 | +from typing import List, Set, Tuple |
| 6 | +from sigma.rule import SigmaRule, SigmaDetection, SigmaDetectionItem |
| 7 | +from sigma.collection import SigmaCollection |
| 8 | +from sigma.correlations import SigmaCorrelationRule |
| 9 | +from sigma.exceptions import SigmaError, SigmaPlaceholderError |
| 10 | +from sigma.modifiers import SigmaExpandModifier |
| 11 | +from sigma.types import SigmaString |
| 12 | +from sigma.processing.pipeline import ProcessingPipeline |
| 13 | + |
| 14 | + |
| 15 | +def get_fields( |
| 16 | + backend, |
| 17 | + rule: SigmaRule | SigmaCorrelationRule, |
| 18 | + collect_errors: bool = True, |
| 19 | +) -> Tuple[List[str], List[SigmaError]]: |
| 20 | + """Extract field names from a Sigma rule. |
| 21 | + |
| 22 | + Args: |
| 23 | + backend: A Backend instance used to escape and quote field names |
| 24 | + rule: A SigmaRule or SigmaCorrelationRule to extract fields from |
| 25 | + collect_errors: Whether to collect errors. Defaults to True. |
| 26 | + |
| 27 | + Returns: |
| 28 | + Tuple[List[str], List[SigmaError]]: A list of fields and any errors found |
| 29 | + """ |
| 30 | + fields: List[str] = [] |
| 31 | + errors: List[SigmaError] = [] |
| 32 | + |
| 33 | + def noop(field: str) -> str: |
| 34 | + """A no-op function that returns the field as-is.""" |
| 35 | + return field |
| 36 | + |
| 37 | + # Get the field escaper from the backend |
| 38 | + escape_and_quote_field = getattr(backend, "escape_and_quote_field", lambda x: x) |
| 39 | + if not callable(escape_and_quote_field): |
| 40 | + escape_and_quote_field = noop |
| 41 | + |
| 42 | + if isinstance(rule, SigmaRule): |
| 43 | + if not rule.detection: |
| 44 | + return fields, errors |
| 45 | + |
| 46 | + # Extract fields from each detection |
| 47 | + for key in frozenset(rule.detection.detections.keys()): |
| 48 | + _fields, _errors = _get_fields_from_detection_items( |
| 49 | + backend, |
| 50 | + rule.detection.detections[key].detection_items, |
| 51 | + collect_errors, |
| 52 | + ) |
| 53 | + fields.extend(_fields) |
| 54 | + errors.extend(_errors) |
| 55 | + |
| 56 | + elif isinstance(rule, SigmaCorrelationRule): |
| 57 | + # Handle correlation rules |
| 58 | + if rule.group_by: |
| 59 | + fields.extend([escape_and_quote_field(field) for field in rule.group_by]) |
| 60 | + |
| 61 | + # Handle aliases |
| 62 | + if rule.aliases: |
| 63 | + aliases_to_remove = set() |
| 64 | + for field_alias in rule.aliases: |
| 65 | + esc_field_alias = escape_and_quote_field(field_alias.alias) |
| 66 | + if esc_field_alias in fields: |
| 67 | + aliases_to_remove.add(esc_field_alias) |
| 68 | + fields.extend([ |
| 69 | + escape_and_quote_field(field) |
| 70 | + for field in field_alias.mapping.values() |
| 71 | + ]) |
| 72 | + fields = [f for f in fields if f not in aliases_to_remove] |
| 73 | + |
| 74 | + return fields, errors |
| 75 | + |
| 76 | + |
| 77 | +def _get_fields_from_detection_items( |
| 78 | + backend, |
| 79 | + detection_items: List[SigmaDetectionItem | SigmaDetection], |
| 80 | + collect_errors: bool = True, |
| 81 | +) -> Tuple[List[str], List[SigmaError]]: |
| 82 | + """Extract fields from detection items recursively. |
| 83 | + |
| 84 | + Args: |
| 85 | + backend: A Backend instance used to escape and quote field names |
| 86 | + detection_items: A list of SigmaDetectionItem or SigmaDetection |
| 87 | + collect_errors: Whether to collect errors. Defaults to True. |
| 88 | + |
| 89 | + Returns: |
| 90 | + Tuple[List[str], List[SigmaError]]: A list of fields and any errors found |
| 91 | + """ |
| 92 | + fields: List[str] = [] |
| 93 | + errors: List[SigmaError] = [] |
| 94 | + |
| 95 | + def noop(field: str) -> str: |
| 96 | + """A no-op function that returns the field as-is.""" |
| 97 | + return field |
| 98 | + |
| 99 | + escape_and_quote_field = getattr(backend, "escape_and_quote_field", lambda x: x) |
| 100 | + if not callable(escape_and_quote_field): |
| 101 | + escape_and_quote_field = noop |
| 102 | + |
| 103 | + for di in detection_items: |
| 104 | + if isinstance(di, SigmaDetectionItem) and hasattr(di, "field") and di.field: |
| 105 | + if collect_errors: |
| 106 | + # Check for unexpanded placeholders |
| 107 | + has_placeholder_modifier = any( |
| 108 | + [ |
| 109 | + is_sem |
| 110 | + for mod in di.modifiers |
| 111 | + if (is_sem := issubclass(mod, SigmaExpandModifier)) |
| 112 | + ] |
| 113 | + ) |
| 114 | + has_placeholder_value = any( |
| 115 | + [ |
| 116 | + is_placeholder |
| 117 | + for val in di.value |
| 118 | + if ( |
| 119 | + is_placeholder := isinstance(val, SigmaString) |
| 120 | + and ( |
| 121 | + hasattr(val, "contains_placeholder") |
| 122 | + and val.contains_placeholder() |
| 123 | + ) |
| 124 | + ) |
| 125 | + ] |
| 126 | + ) |
| 127 | + if all([has_placeholder_modifier, has_placeholder_value]): |
| 128 | + errors.append( |
| 129 | + SigmaPlaceholderError( |
| 130 | + "Cannot extract fields from Sigma rule with unexpanded placeholders." |
| 131 | + ) |
| 132 | + ) |
| 133 | + fields.append(escape_and_quote_field(di.field)) |
| 134 | + elif isinstance(di, SigmaDetection): |
| 135 | + # Recursively extract fields from nested detections |
| 136 | + _fields, _errors = _get_fields_from_detection_items( |
| 137 | + backend, di.detection_items, collect_errors |
| 138 | + ) |
| 139 | + fields.extend(_fields) |
| 140 | + errors.extend(_errors) |
| 141 | + |
| 142 | + return fields, errors |
| 143 | + |
| 144 | + |
| 145 | +def extract_fields_from_collection( |
| 146 | + collection: SigmaCollection, |
| 147 | + backend, |
| 148 | + collect_errors: bool = True, |
| 149 | +) -> Tuple[Set[str], List[SigmaError]]: |
| 150 | + """Extract all unique field names from a Sigma collection. |
| 151 | + |
| 152 | + Args: |
| 153 | + collection: A SigmaCollection to extract fields from |
| 154 | + backend: A Backend instance used to escape and quote field names |
| 155 | + collect_errors: Whether to collect errors. Defaults to True. |
| 156 | + |
| 157 | + Returns: |
| 158 | + Tuple[Set[str], List[SigmaError]]: A set of unique field names and any errors found |
| 159 | + """ |
| 160 | + all_fields: Set[str] = set() |
| 161 | + all_errors: List[SigmaError] = [] |
| 162 | + |
| 163 | + for rule in collection: |
| 164 | + # Try to apply any processing pipelines if available |
| 165 | + last_processing_pipeline = getattr(rule, "last_processing_pipeline", None) |
| 166 | + if not last_processing_pipeline: |
| 167 | + backend_processing_pipeline = ( |
| 168 | + getattr(backend, "backend_processing_pipeline", None) or None |
| 169 | + ) |
| 170 | + processing_pipeline = getattr(backend, "processing_pipeline", None) or None |
| 171 | + output_format_processing_pipeline = ( |
| 172 | + getattr(backend, "output_format_processing_pipeline", None) or None |
| 173 | + ) |
| 174 | + |
| 175 | + if output_format_processing_pipeline and isinstance(output_format_processing_pipeline, dict): |
| 176 | + output_format_processing_pipeline = ( |
| 177 | + output_format_processing_pipeline.get( |
| 178 | + getattr(backend, "format", "default") |
| 179 | + ) |
| 180 | + ) |
| 181 | + |
| 182 | + if backend_processing_pipeline is None: |
| 183 | + backend_processing_pipeline = ProcessingPipeline() |
| 184 | + if processing_pipeline is None: |
| 185 | + processing_pipeline = ProcessingPipeline() |
| 186 | + if output_format_processing_pipeline is None: |
| 187 | + output_format_processing_pipeline = ProcessingPipeline() |
| 188 | + |
| 189 | + last_processing_pipeline = add( |
| 190 | + backend_processing_pipeline, |
| 191 | + add(processing_pipeline, output_format_processing_pipeline), |
| 192 | + ) |
| 193 | + |
| 194 | + # Apply the processing pipeline to the rule |
| 195 | + try: |
| 196 | + rule = last_processing_pipeline.apply(rule) |
| 197 | + except Exception: |
| 198 | + # If pipeline application fails, continue with the rule as-is |
| 199 | + pass |
| 200 | + |
| 201 | + # Extract fields from the rule |
| 202 | + fields, errors = get_fields(backend, rule, collect_errors) |
| 203 | + all_fields.update(fields) |
| 204 | + all_errors.extend(errors) |
| 205 | + |
| 206 | + return all_fields, all_errors |
| 207 | + |
0 commit comments