Source code for sigma.processing.finalization

from __future__ import annotations

from abc import abstractmethod
from dataclasses import dataclass, field
import json
from typing import Any, Type, TYPE_CHECKING

import yaml
from sigma.exceptions import SigmaConfigurationError, SigmaTransformationError

from sigma.processing.templates import TemplateBase

if TYPE_CHECKING:
    from sigma.processing.pipeline import ProcessingPipeline
    from sigma.policy import SigmaPolicy


[docs] @dataclass class Finalizer: """Conversion output transformation base class.""" _pipeline: "ProcessingPipeline" | None = field(init=False, compare=False, default=None)
[docs] @classmethod def from_dict(cls, d: dict[str, Any]) -> "Finalizer": try: return cls(**d) except TypeError as e: raise SigmaConfigurationError("Error in instantiation of finalizer: " + str(e))
[docs] def set_pipeline(self, pipeline: "ProcessingPipeline") -> None: if self._pipeline is None: self._pipeline = pipeline else: raise SigmaTransformationError("Pipeline for finalizer was already set.")
[docs] @abstractmethod def apply(self, queries: list[Any]) -> Any: """Finalize output by applying a transformation to the list of generated and postprocessed queries. :param queries: List of converted and postprocessed queries that should be finalized. :type queries: list[Any] :return: Output that can be used in further processing of the conversion result. :rtype: Any """
[docs] @dataclass class ConcatenateQueriesFinalizer(Finalizer): """Concatenate queries with a given separator and embed result within a prefix or suffix string.""" separator: str = "\n" prefix: str = "" suffix: str = ""
[docs] def apply(self, queries: list[str]) -> str: return self.prefix + self.separator.join(queries) + self.suffix
[docs] @dataclass class JSONFinalizer(Finalizer): indent: int | None = None
[docs] def apply(self, queries: list[Any]) -> str: return json.dumps(queries, indent=self.indent)
[docs] @dataclass class YAMLFinalizer(Finalizer): indent: int | None = None
[docs] def apply(self, queries: list[Any]) -> str: return yaml.safe_dump(queries, indent=self.indent)
[docs] @dataclass class TemplateFinalizer(Finalizer, TemplateBase): """Apply Jinja2 template provided as template object variable to the queries. The following variables are available in the context: * queries: all post-processed queries generated by the backend. * pipeline: the Sigma processing pipeline where this transformation is applied including all current state information in pipeline.state. if *path* is given, *template* is considered as a relative path to a template file below the specified path. If it is not provided, the template is specified as plain string. *autoescape* controls the Jinja2 HTML/XML auto-escaping. if *vars* is given, it should point to a Python file containing helper functions and variables to be made available in the Jinja2 template context. See TemplateBase for details on the format. """
[docs] def apply(self, queries: list[Any]) -> str: return self.j2template.render(queries=queries, pipeline=self._pipeline)
[docs] @dataclass class NestedFinalizer(Finalizer): """Apply a list of finalizers to the queries in a nested fashion.""" finalizers: list[Finalizer] _nested_pipeline: "ProcessingPipeline" = field(init=False, compare=False) def __post_init__(self) -> None: from sigma.processing.pipeline import ( ProcessingPipeline, ) # TODO: move to top after restructuring code. self._nested_pipeline = ProcessingPipeline(finalizers=self.finalizers)
[docs] @classmethod def from_dict( cls, d: dict[str, Any], policy: "SigmaPolicy | None" = None, ) -> "NestedFinalizer": if "finalizers" not in d: raise SigmaConfigurationError("Nested finalizer requires a 'finalizers' key.") fs: list[Finalizer] = [] for finalizer in d["finalizers"]: finalizer = finalizer.copy() finalizer.pop("allow_template_vars", None) # Strip untrusted YAML value finalizer.pop("vars_allowed_paths", None) # Strip untrusted YAML value finalizer.pop("allow_external_sources", None) # Strip untrusted YAML value finalizer.pop("restrict_template_path", None) # Strip untrusted YAML value finalizer.pop("policy", None) # Strip untrusted YAML value try: finalizer_type = finalizer.pop("type") except KeyError: raise SigmaConfigurationError("Finalizer type not specified for: " + str(finalizer)) finalizer_cls = finalizers[finalizer_type] import sigma as _sigma effective_policy = policy or _sigma.policy.default_policy if issubclass(finalizer_cls, TemplateBase): finalizer["policy"] = policy finalizer["restrict_template_path"] = not effective_policy.allow_external_sources fs.append(finalizer_cls.from_dict(finalizer)) elif finalizer_cls is cls: fs.append( cls.from_dict( finalizer, policy=policy, ) ) else: fs.append(finalizer_cls.from_dict(finalizer)) return cls(finalizers=fs)
[docs] def apply(self, queries: list[Any]) -> Any: return self._nested_pipeline.finalize(queries)
finalizers: dict[str, Type[Finalizer]] = { "concat": ConcatenateQueriesFinalizer, "json": JSONFinalizer, "yaml": YAMLFinalizer, "template": TemplateFinalizer, "nested": NestedFinalizer, }