detection-graph 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,10 @@
1
+ """Top-level package for detection_graph.
2
+
3
+ Expose `DetectionGraph` and provider constructors as a convenient API.
4
+ """
5
+ from .graph import DetectionGraph
6
+ from .providers import sentinel, defender
7
+
8
+ __all__ = ["DetectionGraph", "sentinel", "defender"]
9
+
10
+ __version__ = "0.1.0"
@@ -0,0 +1,3 @@
1
+ from .coverage import coverage_by_technique, find_unmapped_rules, find_orphan_techniques
2
+
3
+ __all__ = ["coverage_by_technique", "find_unmapped_rules", "find_orphan_techniques"]
@@ -0,0 +1,51 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import Dict, Set
4
+ import pandas as pd
5
+ import networkx as nx
6
+
7
+
8
+ def coverage_by_technique(graph: nx.DiGraph) -> pd.DataFrame:
9
+ """Return a DataFrame with technique id and unique-rule coverage counts."""
10
+ rows = []
11
+ for n, d in graph.nodes(data=True):
12
+ if d.get("node_type") == "technique":
13
+ # find rules that map to this technique
14
+ preds = [p for p in graph.predecessors(n) if graph.nodes[p].get("node_type") == "rule"]
15
+ unique_rules = set(preds)
16
+ rows.append({"technique": n, "technique_name": d.get("name"), "coverage_count": len(unique_rules), "rules": list(unique_rules)})
17
+
18
+ df = pd.DataFrame(rows)
19
+ return df.sort_values("coverage_count", ascending=False)
20
+
21
+
22
+ def find_unmapped_rules(graph: nx.DiGraph) -> Set[str]:
23
+ """Return rule node ids that have no tactic and no technique mapping."""
24
+ unmapped = set()
25
+ for n, d in graph.nodes(data=True):
26
+ if d.get("node_type") == "rule":
27
+ has_tactic = any(graph.edges[n, v].get("relation") == "mapped_to_tactic" for v in graph.successors(n) if graph.nodes[v].get("node_type") == "tactic")
28
+ has_tech = any(graph.edges[n, v].get("relation") == "mapped_to_technique" for v in graph.successors(n) if graph.nodes[v].get("node_type") == "technique")
29
+ if not has_tactic and not has_tech:
30
+ unmapped.add(n)
31
+ return unmapped
32
+
33
+
34
+ def find_orphan_techniques(graph: nx.DiGraph, attack_reference=None) -> Set[str]:
35
+ """Return techniques that exist in the graph or ATT&CK reference but have zero mapped rules."""
36
+ orphans = set()
37
+ # techniques present in graph
38
+ for n, d in graph.nodes(data=True):
39
+ if d.get("node_type") == "technique":
40
+ preds = [p for p in graph.predecessors(n) if graph.nodes[p].get("node_type") == "rule"]
41
+ if not preds:
42
+ orphans.add(n)
43
+
44
+ # optionally include techniques from attack_reference that are not in graph or have no rules
45
+ if attack_reference is not None:
46
+ for tech_id in attack_reference.techniques.keys():
47
+ node_id = f"technique:{tech_id}"
48
+ if node_id not in graph.nodes:
49
+ orphans.add(node_id)
50
+
51
+ return orphans
@@ -0,0 +1,3 @@
1
+ from .graph_builder import GraphBuilder
2
+
3
+ __all__ = ["GraphBuilder"]
@@ -0,0 +1,80 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import Iterable
4
+ import networkx as nx
5
+
6
+ from detection_graph.models.detection import DetectionRule
7
+ from detection_graph.models.attack import AttackReference
8
+
9
+
10
+ class GraphBuilder:
11
+ """Builds a NetworkX directed graph from detection rules and ATT&CK data.
12
+
13
+ Nodes use collision-resistant ids with prefixes:
14
+ - `tactic:<id>`
15
+ - `technique:<id>`
16
+ - `rule:<provider>:<id>`
17
+ - `product:<normalized-name>`
18
+
19
+ Edges include explicit `relation` attributes such as `mapped_to_tactic`,
20
+ `mapped_to_technique`, `provided_by`, and `contains_technique`.
21
+ """
22
+
23
+ def __init__(self, attack: AttackReference | None = None):
24
+ self.attack = attack
25
+
26
+ @staticmethod
27
+ def _tactic_node_id(tactic_id: str) -> str:
28
+ return f"tactic:{tactic_id}"
29
+
30
+ @staticmethod
31
+ def _technique_node_id(tech_id: str) -> str:
32
+ return f"technique:{tech_id}"
33
+
34
+ @staticmethod
35
+ def _rule_node_id(rule: DetectionRule) -> str:
36
+ # DetectionRule.id already includes provider prefix in our providers
37
+ return f"rule:{rule.id}"
38
+
39
+ @staticmethod
40
+ def _product_node_id(product_name: str) -> str:
41
+ return f"product:{product_name.lower().replace(' ', '-') }"
42
+
43
+ def build(self, rules: Iterable[DetectionRule]) -> nx.DiGraph:
44
+ g = nx.DiGraph()
45
+
46
+ for rule in rules:
47
+ rid = self._rule_node_id(rule)
48
+ g.add_node(rid, node_type="rule", name=rule.name, severity=rule.severity, source_product=rule.source_product)
49
+
50
+ # product node
51
+ prod_id = self._product_node_id(rule.source_product)
52
+ if not g.has_node(prod_id):
53
+ g.add_node(prod_id, node_type="product", name=rule.source_product)
54
+ g.add_edge(rid, prod_id, relation="provided_by")
55
+
56
+ # rule -> tactics
57
+ for t in rule.tactics:
58
+ t_id = self._tactic_node_id(t)
59
+ if not g.has_node(t_id):
60
+ g.add_node(t_id, node_type="tactic", name=t)
61
+ g.add_edge(rid, t_id, relation="mapped_to_tactic")
62
+
63
+ # rule -> techniques
64
+ for tech in rule.techniques:
65
+ tech_id = self._technique_node_id(tech)
66
+ if not g.has_node(tech_id):
67
+ g.add_node(tech_id, node_type="technique", name=tech)
68
+ g.add_edge(rid, tech_id, relation="mapped_to_technique")
69
+
70
+ # Optionally add tactic->technique relationships when supported by ATT&CK data
71
+ if self.attack is not None:
72
+ for tech_id, tech in self.attack.techniques.items():
73
+ tech_node = self._technique_node_id(tech_id)
74
+ for tac in tech.tactics:
75
+ tac_node = self._tactic_node_id(tac)
76
+ # Only add if both nodes exist in the graph
77
+ if g.has_node(tac_node) and g.has_node(tech_node):
78
+ g.add_edge(tac_node, tech_node, relation="contains_technique")
79
+
80
+ return g
detection_graph/cli.py ADDED
@@ -0,0 +1,68 @@
1
+ from __future__ import annotations
2
+
3
+ import argparse
4
+ from pathlib import Path
5
+
6
+ from detection_graph.providers.sentinel import SentinelProvider
7
+ from detection_graph.providers.defender import DefenderProvider
8
+ from detection_graph.graph import DetectionGraph
9
+
10
+
11
+ def main():
12
+ parser = argparse.ArgumentParser(prog="detection-graph")
13
+ sub = parser.add_subparsers(dest="cmd", required=True)
14
+
15
+ build_p = sub.add_parser("build")
16
+ build_p.add_argument("--provider", required=True)
17
+ build_p.add_argument("--input-path", required=True)
18
+ build_p.add_argument("--attack-path", required=True)
19
+ build_p.add_argument("--output", required=True)
20
+ build_p.add_argument("--renderer", required=False, choices=["sigma", "pyvis"], default="sigma")
21
+ build_p.add_argument("--seed", required=False, type=int, default=42)
22
+ build_p.add_argument("--bundle", required=False, choices=["cdn", "local", "embed"], default="cdn")
23
+
24
+ analyze_p = sub.add_parser("analyze")
25
+ analyze_p.add_argument("--provider", required=True)
26
+ analyze_p.add_argument("--input-path", required=True)
27
+ analyze_p.add_argument("--attack-path", required=True)
28
+
29
+ args = parser.parse_args()
30
+
31
+ if args.cmd == "build":
32
+ provider = args.provider.lower()
33
+ if provider == "sentinel":
34
+ p = SentinelProvider.from_json(args.input_path)
35
+ elif provider == "defender":
36
+ p = DefenderProvider.from_json(args.input_path)
37
+ else:
38
+ print(f"Unsupported provider: {provider}")
39
+ return 2
40
+
41
+ rules = p.get_rules()
42
+ dg = DetectionGraph.from_attack_json(args.attack_path)
43
+ dg.add_rules(rules)
44
+ Path(args.output).parent.mkdir(parents=True, exist_ok=True)
45
+ dg.export_html(args.output, hierarchical=False, renderer=args.renderer, seed=args.seed, bundle=args.bundle)
46
+ print(f"Wrote {args.output}")
47
+ return 0
48
+
49
+ if args.cmd == "analyze":
50
+ provider = args.provider.lower()
51
+ if provider == "sentinel":
52
+ p = SentinelProvider.from_json(args.input_path)
53
+ elif provider == "defender":
54
+ p = DefenderProvider.from_json(args.input_path)
55
+ else:
56
+ print(f"Unsupported provider: {provider}")
57
+ return 2
58
+
59
+ rules = p.get_rules()
60
+ dg = DetectionGraph.from_attack_json(args.attack_path)
61
+ dg.add_rules(rules)
62
+ df = dg.analytics.coverage_by_technique()
63
+ print(df.to_string(index=False))
64
+ return 0
65
+
66
+
67
+ if __name__ == "__main__":
68
+ raise SystemExit(main())
@@ -0,0 +1,5 @@
1
+ from .json import export_json
2
+ from .graphml import export_graphml
3
+ from .html import export_html
4
+
5
+ __all__ = ["export_json", "export_graphml", "export_html"]
@@ -0,0 +1,7 @@
1
+ from __future__ import annotations
2
+
3
+ import networkx as nx
4
+
5
+
6
+ def export_graphml(graph: nx.DiGraph, path: str) -> None:
7
+ nx.write_graphml(graph, path)
@@ -0,0 +1,30 @@
1
+ from __future__ import annotations
2
+
3
+ from detection_graph.visualizers.sigma_renderer import SigmaRenderer
4
+ import networkx as nx
5
+
6
+
7
+ def export_html(graph: nx.DiGraph, path: str, hierarchical: bool = False, renderer: str | None = None, seed: int = 42, bundle: str = "cdn") -> None:
8
+ """Export the graph to HTML.
9
+
10
+ renderer: optional selector: 'sigma' (default) or 'pyvis'.
11
+ """
12
+ if renderer is None or renderer == "sigma":
13
+ try:
14
+ sr = SigmaRenderer()
15
+ sr.render(graph, path, hierarchical=hierarchical, seed=seed, bundle=bundle)
16
+ return
17
+ except Exception:
18
+ # fall through to pyvis fallback
19
+ pass
20
+
21
+ # fallback to PyVis renderer for environments where Sigma/Graphology
22
+ # is not desired or testing requires the older renderer. Import lazily
23
+ # so pyvis is not required when using the Sigma renderer.
24
+ try:
25
+ from detection_graph.visualizers.pyvis_renderer import PyVisRenderer
26
+ except Exception as e:
27
+ raise RuntimeError("PyVis fallback requested but pyvis is not installed") from e
28
+
29
+ pr = PyVisRenderer()
30
+ pr.render(graph, path, hierarchical=hierarchical)
@@ -0,0 +1,11 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ from networkx.readwrite import json_graph
5
+ import networkx as nx
6
+
7
+
8
+ def export_json(graph: nx.DiGraph, path: str) -> None:
9
+ data = json_graph.node_link_data(graph)
10
+ with open(path, "w", encoding="utf-8") as fh:
11
+ json.dump(data, fh, indent=2)
@@ -0,0 +1,54 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import Iterable
4
+ import networkx as nx
5
+
6
+ from detection_graph.builders.graph_builder import GraphBuilder
7
+ from detection_graph.models.attack import AttackReference
8
+ from detection_graph.analytics import coverage as analytics_module
9
+ from detection_graph.exporters import json as json_exporter
10
+ from detection_graph.exporters import graphml as graphml_exporter
11
+ from detection_graph.exporters import html as html_exporter
12
+
13
+
14
+ class DetectionGraph:
15
+ def __init__(self, attack: AttackReference | None = None):
16
+ self._attack = attack
17
+ self._graph = nx.DiGraph()
18
+ self._builder = GraphBuilder(attack=attack)
19
+
20
+ @classmethod
21
+ def from_attack_json(cls, path: str) -> "DetectionGraph":
22
+ attack = AttackReference.from_json(path)
23
+ return cls(attack=attack)
24
+
25
+ def add_rules(self, rules: Iterable):
26
+ g2 = self._builder.build(rules)
27
+ self._graph = nx.compose(self._graph, g2)
28
+
29
+ def export_json(self, path: str) -> None:
30
+ json_exporter.export_json(self._graph, path)
31
+
32
+ def export_graphml(self, path: str) -> None:
33
+ graphml_exporter.export_graphml(self._graph, path)
34
+
35
+ def export_html(self, path: str, hierarchical: bool = False, renderer: str | None = None, seed: int = 42, bundle: str = "cdn") -> None:
36
+ html_exporter.export_html(self._graph, path, hierarchical=hierarchical, renderer=renderer, seed=seed, bundle=bundle)
37
+
38
+ @property
39
+ def analytics(self):
40
+ class A:
41
+ def __init__(self, g, attack):
42
+ self._g = g
43
+ self._attack = attack
44
+
45
+ def coverage_by_technique(self):
46
+ return analytics_module.coverage_by_technique(self._g)
47
+
48
+ def unmapped_rules(self):
49
+ return analytics_module.find_unmapped_rules(self._g)
50
+
51
+ def orphan_techniques(self):
52
+ return analytics_module.find_orphan_techniques(self._g, self._attack)
53
+
54
+ return A(self._graph, self._attack)
@@ -0,0 +1,3 @@
1
+ from .detection import DetectionRule
2
+
3
+ __all__ = ["DetectionRule"]
@@ -0,0 +1,49 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ from dataclasses import dataclass
5
+ from pathlib import Path
6
+ from typing import Dict, List
7
+
8
+
9
+ @dataclass(frozen=True)
10
+ class AttackTactic:
11
+ id: str
12
+ name: str
13
+
14
+
15
+ @dataclass(frozen=True)
16
+ class AttackTechnique:
17
+ id: str
18
+ name: str
19
+ tactics: List[str]
20
+
21
+
22
+ class AttackReference:
23
+ """Simple in-memory ATT&CK reference loader for tests and fixtures.
24
+
25
+ Expects a JSON with `tactics` and `techniques` arrays. Techniques include a
26
+ `tactics` list of tactic ids that are valid for that technique.
27
+ """
28
+
29
+ def __init__(self, tactics: Dict[str, AttackTactic], techniques: Dict[str, AttackTechnique]):
30
+ self.tactics = tactics
31
+ self.techniques = techniques
32
+
33
+ @classmethod
34
+ def from_json(cls, path: str) -> "AttackReference":
35
+ p = Path(path)
36
+ data = json.loads(p.read_text())
37
+ tactics = {t["id"]: AttackTactic(id=t["id"], name=t.get("name", "")) for t in data.get("tactics", [])}
38
+ techniques = {}
39
+ for t in data.get("techniques", []):
40
+ tid = t.get("id")
41
+ techniques[tid] = AttackTechnique(id=tid, name=t.get("name", ""), tactics=t.get("tactics", []))
42
+
43
+ return cls(tactics=tactics, techniques=techniques)
44
+
45
+ def technique_belongs_to_tactic(self, technique_id: str, tactic_id: str) -> bool:
46
+ tech = self.techniques.get(technique_id)
47
+ if not tech:
48
+ return False
49
+ return tactic_id in tech.tactics
@@ -0,0 +1,27 @@
1
+ from __future__ import annotations
2
+
3
+ from pydantic import BaseModel, Field, ConfigDict
4
+ from typing import Optional
5
+
6
+
7
+ class DetectionRule(BaseModel):
8
+ """Canonical detection rule model shared across providers.
9
+
10
+ Important: do not infer or nest technique-to-tactic pairings here. Preserve
11
+ `tactics` and `techniques` as independent lists so the graph builder can
12
+ resolve authoritative relationships from ATT&CK reference data.
13
+ """
14
+
15
+ id: str
16
+ name: str
17
+ source_product: str
18
+ source_provider: str
19
+ tactics: list[str] = Field(default_factory=list)
20
+ techniques: list[str] = Field(default_factory=list)
21
+ severity: Optional[str] = None
22
+ enabled: Optional[bool] = None
23
+ description: Optional[str] = None
24
+ query: Optional[str] = None
25
+ tags: dict[str, str] = Field(default_factory=dict)
26
+
27
+ model_config = ConfigDict(frozen=True)
@@ -0,0 +1,3 @@
1
+ from .base import DetectionProvider
2
+
3
+ __all__ = ["DetectionProvider"]
@@ -0,0 +1,18 @@
1
+ from typing import Protocol, runtime_checkable
2
+ from typing import List
3
+
4
+ from detection_graph.models.detection import DetectionRule
5
+
6
+
7
+ @runtime_checkable
8
+ class DetectionProvider(Protocol):
9
+ """Protocol that providers must implement to normalize vendor payloads.
10
+
11
+ Providers should implement a lightweight, testable interface that returns
12
+ a list of canonical `DetectionRule` objects. Providers are responsible for
13
+ reading their input format (file, export, or API), validating required
14
+ fields, and preserving source identifiers in the returned models.
15
+ """
16
+
17
+ def get_rules(self) -> List[DetectionRule]:
18
+ ...
@@ -0,0 +1,49 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ from pathlib import Path
5
+ from typing import List
6
+
7
+ from detection_graph.models.detection import DetectionRule
8
+
9
+
10
+ class DefenderProvider:
11
+ """Fixture-based Defender provider.
12
+
13
+ Expects JSON with a top-level `rules` array using a simple exported shape.
14
+ """
15
+
16
+ def __init__(self, rules: List[DetectionRule]):
17
+ self._rules = rules
18
+
19
+ @classmethod
20
+ def from_json(cls, path: str) -> "DefenderProvider":
21
+ p = Path(path)
22
+ data = json.loads(p.read_text())
23
+ items = data.get("rules", [])
24
+ rules: List[DetectionRule] = []
25
+ for it in items:
26
+ rid = it.get("id")
27
+ name = it.get("displayName") or it.get("name") or rid
28
+ tactics = it.get("tactics") or []
29
+ techniques = it.get("techniques") or []
30
+ rules.append(
31
+ DetectionRule(
32
+ id=f"rule:defender:{rid}",
33
+ name=name,
34
+ source_product="Defender",
35
+ source_provider="defender",
36
+ tactics=[t.lower() for t in tactics],
37
+ techniques=[t.upper() for t in techniques],
38
+ severity=it.get("severity"),
39
+ enabled=it.get("enabled"),
40
+ description=it.get("description"),
41
+ query=it.get("query"),
42
+ tags=it.get("tags") or {},
43
+ )
44
+ )
45
+
46
+ return cls(rules)
47
+
48
+ def get_rules(self) -> List[DetectionRule]:
49
+ return list(self._rules)
@@ -0,0 +1,51 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ from pathlib import Path
5
+ from typing import List
6
+
7
+ from detection_graph.models.detection import DetectionRule
8
+ from detection_graph.providers.base import DetectionProvider
9
+
10
+
11
+ class SentinelProvider:
12
+ """Simple file-based Sentinel provider for fixtures.
13
+
14
+ This initial implementation expects a JSON file with a top-level `rules`
15
+ array containing objects with keys similar to Azure Sentinel exports.
16
+ """
17
+
18
+ def __init__(self, rules: List[DetectionRule]):
19
+ self._rules = rules
20
+
21
+ @classmethod
22
+ def from_json(cls, path: str) -> "SentinelProvider":
23
+ p = Path(path)
24
+ data = json.loads(p.read_text())
25
+ items = data.get("rules", [])
26
+ rules: List[DetectionRule] = []
27
+ for it in items:
28
+ rid = it.get("id") or it.get("ruleId") or it.get("name")
29
+ name = it.get("displayName") or it.get("name") or rid
30
+ tactics = it.get("tactics") or []
31
+ techniques = it.get("techniques") or []
32
+ rules.append(
33
+ DetectionRule(
34
+ id=f"rule:sentinel:{rid}",
35
+ name=name,
36
+ source_product="Microsoft Sentinel",
37
+ source_provider="sentinel",
38
+ tactics=[t.lower() for t in tactics],
39
+ techniques=[t.upper() for t in techniques],
40
+ severity=it.get("severity"),
41
+ enabled=it.get("enabled"),
42
+ description=it.get("description"),
43
+ query=it.get("query"),
44
+ tags=it.get("tags") or {},
45
+ )
46
+ )
47
+
48
+ return cls(rules)
49
+
50
+ def get_rules(self) -> List[DetectionRule]:
51
+ return list(self._rules)