detection-graph 0.1.0__tar.gz → 0.1.2__tar.gz

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.
Files changed (36) hide show
  1. detection_graph-0.1.2/LICENSE +21 -0
  2. detection_graph-0.1.2/PKG-INFO +138 -0
  3. detection_graph-0.1.2/README.md +114 -0
  4. detection_graph-0.1.2/pyproject.toml +35 -0
  5. {detection_graph-0.1.0 → detection_graph-0.1.2}/src/detection_graph/__init__.py +1 -1
  6. {detection_graph-0.1.0 → detection_graph-0.1.2}/src/detection_graph/analytics/coverage.py +1 -1
  7. detection_graph-0.1.2/src/detection_graph/auth/azure.py +52 -0
  8. detection_graph-0.1.2/src/detection_graph/cli.py +80 -0
  9. detection_graph-0.1.2/src/detection_graph/exporters/html.py +21 -0
  10. detection_graph-0.1.2/src/detection_graph/providers/defender_azure.py +80 -0
  11. {detection_graph-0.1.0 → detection_graph-0.1.2}/src/detection_graph/providers/sentinel.py +0 -1
  12. detection_graph-0.1.2/src/detection_graph/providers/sentinel_azure.py +72 -0
  13. {detection_graph-0.1.0 → detection_graph-0.1.2}/src/detection_graph/visualizers/sigma_renderer.py +38 -72
  14. detection_graph-0.1.0/PKG-INFO +0 -16
  15. detection_graph-0.1.0/pyproject.toml +0 -25
  16. detection_graph-0.1.0/src/detection_graph/cli.py +0 -68
  17. detection_graph-0.1.0/src/detection_graph/exporters/html.py +0 -30
  18. {detection_graph-0.1.0 → detection_graph-0.1.2}/src/detection_graph/analytics/__init__.py +0 -0
  19. {detection_graph-0.1.0 → detection_graph-0.1.2}/src/detection_graph/builders/__init__.py +0 -0
  20. {detection_graph-0.1.0 → detection_graph-0.1.2}/src/detection_graph/builders/graph_builder.py +0 -0
  21. {detection_graph-0.1.0 → detection_graph-0.1.2}/src/detection_graph/exporters/__init__.py +0 -0
  22. {detection_graph-0.1.0 → detection_graph-0.1.2}/src/detection_graph/exporters/graphml.py +0 -0
  23. {detection_graph-0.1.0 → detection_graph-0.1.2}/src/detection_graph/exporters/json.py +0 -0
  24. {detection_graph-0.1.0 → detection_graph-0.1.2}/src/detection_graph/graph.py +0 -0
  25. {detection_graph-0.1.0 → detection_graph-0.1.2}/src/detection_graph/models/__init__.py +0 -0
  26. {detection_graph-0.1.0 → detection_graph-0.1.2}/src/detection_graph/models/attack.py +0 -0
  27. {detection_graph-0.1.0 → detection_graph-0.1.2}/src/detection_graph/models/detection.py +0 -0
  28. {detection_graph-0.1.0 → detection_graph-0.1.2}/src/detection_graph/providers/__init__.py +0 -0
  29. {detection_graph-0.1.0 → detection_graph-0.1.2}/src/detection_graph/providers/base.py +0 -0
  30. {detection_graph-0.1.0 → detection_graph-0.1.2}/src/detection_graph/providers/defender.py +0 -0
  31. {detection_graph-0.1.0 → detection_graph-0.1.2}/src/detection_graph/static/graphology.umd.min.js +0 -0
  32. {detection_graph-0.1.0 → detection_graph-0.1.2}/src/detection_graph/static/sigma.min.js +0 -0
  33. {detection_graph-0.1.0 → detection_graph-0.1.2}/src/detection_graph/static/sigma.umd.min.js +0 -0
  34. {detection_graph-0.1.0 → detection_graph-0.1.2}/src/detection_graph/static/vendor-manifest.json +0 -0
  35. {detection_graph-0.1.0 → detection_graph-0.1.2}/src/detection_graph/visualizers/__init__.py +0 -0
  36. {detection_graph-0.1.0 → detection_graph-0.1.2}/src/detection_graph/visualizers/pyvis_renderer.py +0 -0
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Andrew Dotson
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,138 @@
1
+ Metadata-Version: 2.4
2
+ Name: detection-graph
3
+ Version: 0.1.2
4
+ Summary: Interactive MITRE ATT&CK detection coverage graph for Microsoft security products
5
+ License: MIT
6
+ License-File: LICENSE
7
+ Keywords: mitre,attack,detection,sentinel,defender,security
8
+ Author: Andrew Dotson
9
+ Requires-Python: >=3.12,<4.0
10
+ Classifier: Development Status :: 4 - Beta
11
+ Classifier: Intended Audience :: Information Technology
12
+ Classifier: License :: OSI Approved :: MIT License
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Programming Language :: Python :: 3.12
15
+ Classifier: Programming Language :: Python :: 3.13
16
+ Classifier: Programming Language :: Python :: 3.14
17
+ Classifier: Programming Language :: Python :: 3.15
18
+ Requires-Dist: networkx (>=3.1,<4.0)
19
+ Requires-Dist: pandas (>=2.2,<3.0)
20
+ Requires-Dist: pydantic (>=2.2,<3.0)
21
+ Requires-Dist: pyvis (>=0.3,<0.4)
22
+ Description-Content-Type: text/markdown
23
+
24
+ # Microsoft Detection Graph
25
+
26
+ Microsoft Detection Graph builds an interactive MITRE ATT&CK coverage graph
27
+ from local Microsoft Sentinel or Microsoft Defender detection exports.
28
+
29
+ ## Quickstart
30
+
31
+ Requires Python 3.12 or newer.
32
+
33
+ ```bash
34
+ git clone https://github.com/andrewblastbeats/microsoft_detection_graph.git
35
+ cd microsoft_detection_graph
36
+ python3 -m venv .venv
37
+ source .venv/bin/activate
38
+ pip install -e .
39
+ ```
40
+
41
+ Build a graph from JSON exports that match the documented input shape below:
42
+
43
+ ```bash
44
+ detection-graph build \
45
+ --provider sentinel \
46
+ --input sentinel-rules.json \
47
+ --attack-data attack-reference.json \
48
+ --output output/coverage.html \
49
+ --bundle embed
50
+ ```
51
+
52
+ Analyze coverage without producing HTML:
53
+
54
+ ```bash
55
+ detection-graph analyze \
56
+ --provider sentinel \
57
+ --input sentinel-rules.json \
58
+ --attack-data attack-reference.json
59
+ ```
60
+
61
+ `--input-path` and `--attack-path` remain supported as explicit aliases.
62
+ Use `detection-graph --version` to report the installed version.
63
+
64
+ ### Input JSON
65
+
66
+ Provider exports must contain a `rules` array. Rule fields include `id`
67
+ (Sentinel also accepts `ruleId` or `name`), `name` or `displayName`,
68
+ `tactics`, `techniques`, and optional metadata such as `severity`,
69
+ `description`, `query`, `enabled`, and `tags`.
70
+
71
+ The ATT&CK reference file must contain `tactics` and `techniques` arrays.
72
+ Each technique has an `id`, `name`, and a `tactics` array listing its tactic
73
+ IDs. For example:
74
+
75
+ ```json
76
+ {
77
+ "tactics": [{"id": "initial-access", "name": "Initial Access"}],
78
+ "techniques": [{
79
+ "id": "T1078",
80
+ "name": "Valid Accounts",
81
+ "tactics": ["initial-access"]
82
+ }]
83
+ }
84
+ ```
85
+
86
+ The tool expects normalized JSON exports; it does not download current
87
+ ATT&CK data or convert arbitrary vendor export formats automatically.
88
+
89
+ ## Docker demo
90
+
91
+ The image generates a deterministic, offline example during the build and
92
+ serves it as an unprivileged user:
93
+
94
+ ```bash
95
+ docker build -t detection-graph .
96
+ docker run --rm --publish 8000:8000 detection-graph
97
+ ```
98
+
99
+ Open <http://localhost:8000/coverage_offline.html>.
100
+
101
+ ## Supported scope
102
+
103
+ The beta CLI reads local JSON exports for Sentinel and Defender. Direct Azure
104
+ cloud ingestion is not part of this release; the Azure provider modules are
105
+ experimental and have not been validated against a live tenant. This keeps
106
+ the initial release reproducible and avoids presenting Defender alerts as
107
+ authoritative detection-rule coverage.
108
+
109
+ ## Development
110
+
111
+ ```bash
112
+ make install
113
+ make lint
114
+ make test
115
+ make build
116
+ ```
117
+
118
+ See [CONTRIBUTING.md](./CONTRIBUTING.md) for pull request guidance.
119
+
120
+ The CI workflow tests Python 3.12 and 3.13, lints the source, builds the
121
+ package, and smoke-tests the container. Vendored browser assets are kept in
122
+ `src/detection_graph/static/`; regenerate them with
123
+ `python dev_scripts/vendor_sigma.py` when upgrading the visualizer.
124
+
125
+ ## Project status
126
+
127
+ This is a beta release. Before publishing:
128
+
129
+ 1. Enable private vulnerability reporting under **Settings → Security →
130
+ Code security and analysis**.
131
+ 2. Register a PyPI trusted publisher for owner `andrewblastbeats`, repository
132
+ `microsoft_detection_graph`, workflow `release.yml`, environment `pypi`.
133
+ Create the PyPI project/publisher registration first if the project does
134
+ not yet exist.
135
+ 3. Ensure GitHub Actions has permission to use the `pypi` environment.
136
+
137
+ The project is released under the MIT License.
138
+
@@ -0,0 +1,114 @@
1
+ # Microsoft Detection Graph
2
+
3
+ Microsoft Detection Graph builds an interactive MITRE ATT&CK coverage graph
4
+ from local Microsoft Sentinel or Microsoft Defender detection exports.
5
+
6
+ ## Quickstart
7
+
8
+ Requires Python 3.12 or newer.
9
+
10
+ ```bash
11
+ git clone https://github.com/andrewblastbeats/microsoft_detection_graph.git
12
+ cd microsoft_detection_graph
13
+ python3 -m venv .venv
14
+ source .venv/bin/activate
15
+ pip install -e .
16
+ ```
17
+
18
+ Build a graph from JSON exports that match the documented input shape below:
19
+
20
+ ```bash
21
+ detection-graph build \
22
+ --provider sentinel \
23
+ --input sentinel-rules.json \
24
+ --attack-data attack-reference.json \
25
+ --output output/coverage.html \
26
+ --bundle embed
27
+ ```
28
+
29
+ Analyze coverage without producing HTML:
30
+
31
+ ```bash
32
+ detection-graph analyze \
33
+ --provider sentinel \
34
+ --input sentinel-rules.json \
35
+ --attack-data attack-reference.json
36
+ ```
37
+
38
+ `--input-path` and `--attack-path` remain supported as explicit aliases.
39
+ Use `detection-graph --version` to report the installed version.
40
+
41
+ ### Input JSON
42
+
43
+ Provider exports must contain a `rules` array. Rule fields include `id`
44
+ (Sentinel also accepts `ruleId` or `name`), `name` or `displayName`,
45
+ `tactics`, `techniques`, and optional metadata such as `severity`,
46
+ `description`, `query`, `enabled`, and `tags`.
47
+
48
+ The ATT&CK reference file must contain `tactics` and `techniques` arrays.
49
+ Each technique has an `id`, `name`, and a `tactics` array listing its tactic
50
+ IDs. For example:
51
+
52
+ ```json
53
+ {
54
+ "tactics": [{"id": "initial-access", "name": "Initial Access"}],
55
+ "techniques": [{
56
+ "id": "T1078",
57
+ "name": "Valid Accounts",
58
+ "tactics": ["initial-access"]
59
+ }]
60
+ }
61
+ ```
62
+
63
+ The tool expects normalized JSON exports; it does not download current
64
+ ATT&CK data or convert arbitrary vendor export formats automatically.
65
+
66
+ ## Docker demo
67
+
68
+ The image generates a deterministic, offline example during the build and
69
+ serves it as an unprivileged user:
70
+
71
+ ```bash
72
+ docker build -t detection-graph .
73
+ docker run --rm --publish 8000:8000 detection-graph
74
+ ```
75
+
76
+ Open <http://localhost:8000/coverage_offline.html>.
77
+
78
+ ## Supported scope
79
+
80
+ The beta CLI reads local JSON exports for Sentinel and Defender. Direct Azure
81
+ cloud ingestion is not part of this release; the Azure provider modules are
82
+ experimental and have not been validated against a live tenant. This keeps
83
+ the initial release reproducible and avoids presenting Defender alerts as
84
+ authoritative detection-rule coverage.
85
+
86
+ ## Development
87
+
88
+ ```bash
89
+ make install
90
+ make lint
91
+ make test
92
+ make build
93
+ ```
94
+
95
+ See [CONTRIBUTING.md](./CONTRIBUTING.md) for pull request guidance.
96
+
97
+ The CI workflow tests Python 3.12 and 3.13, lints the source, builds the
98
+ package, and smoke-tests the container. Vendored browser assets are kept in
99
+ `src/detection_graph/static/`; regenerate them with
100
+ `python dev_scripts/vendor_sigma.py` when upgrading the visualizer.
101
+
102
+ ## Project status
103
+
104
+ This is a beta release. Before publishing:
105
+
106
+ 1. Enable private vulnerability reporting under **Settings → Security →
107
+ Code security and analysis**.
108
+ 2. Register a PyPI trusted publisher for owner `andrewblastbeats`, repository
109
+ `microsoft_detection_graph`, workflow `release.yml`, environment `pypi`.
110
+ Create the PyPI project/publisher registration first if the project does
111
+ not yet exist.
112
+ 3. Ensure GitHub Actions has permission to use the `pypi` environment.
113
+
114
+ The project is released under the MIT License.
@@ -0,0 +1,35 @@
1
+ [tool.poetry]
2
+ name = "detection-graph"
3
+ version = "0.1.2"
4
+ description = "Interactive MITRE ATT&CK detection coverage graph for Microsoft security products"
5
+ authors = ["Andrew Dotson"]
6
+ license = "MIT"
7
+ readme = "README.md"
8
+ keywords = ["mitre", "attack", "detection", "sentinel", "defender", "security"]
9
+ classifiers = [
10
+ "Development Status :: 4 - Beta",
11
+ "Intended Audience :: Information Technology",
12
+ "Programming Language :: Python :: 3",
13
+ "Programming Language :: Python :: 3.12",
14
+ "Programming Language :: Python :: 3.13",
15
+ ]
16
+ include = ["src/detection_graph/static/*"]
17
+
18
+ [tool.poetry.dependencies]
19
+ python = ">=3.12,<4.0"
20
+ pydantic = "^2.2"
21
+ networkx = "^3.1"
22
+ pandas = "^2.2"
23
+ pyvis = "^0.3"
24
+
25
+ [tool.poetry.group.dev.dependencies]
26
+ pytest = "^7.0"
27
+ ruff = ">=0.15,<0.16"
28
+ build = "^1.2"
29
+
30
+ [build-system]
31
+ requires = ["poetry-core>=1.0.0"]
32
+ build-backend = "poetry.core.masonry.api"
33
+
34
+ [tool.poetry.scripts]
35
+ detection-graph = "detection_graph.cli:main"
@@ -7,4 +7,4 @@ from .providers import sentinel, defender
7
7
 
8
8
  __all__ = ["DetectionGraph", "sentinel", "defender"]
9
9
 
10
- __version__ = "0.1.0"
10
+ __version__ = "0.1.2"
@@ -1,6 +1,6 @@
1
1
  from __future__ import annotations
2
2
 
3
- from typing import Dict, Set
3
+ from typing import Set
4
4
  import pandas as pd
5
5
  import networkx as nx
6
6
 
@@ -0,0 +1,52 @@
1
+ from __future__ import annotations
2
+
3
+ import os
4
+ import urllib.parse
5
+ import urllib.request
6
+ import json
7
+ from typing import Dict, Optional
8
+
9
+
10
+ def get_client_credentials_from_env() -> Dict[str, str]:
11
+ """Read Azure client credentials from environment variables.
12
+
13
+ Returns a dict with keys: tenant_id, client_id, client_secret.
14
+ """
15
+ tenant = os.environ.get("AZURE_TENANT_ID")
16
+ client = os.environ.get("AZURE_CLIENT_ID")
17
+ secret = os.environ.get("AZURE_CLIENT_SECRET")
18
+ if not (tenant and client and secret):
19
+ raise EnvironmentError("Azure client credentials not found in environment variables (AZURE_TENANT_ID, AZURE_CLIENT_ID, AZURE_CLIENT_SECRET)")
20
+ return {"tenant_id": tenant, "client_id": client, "client_secret": secret}
21
+
22
+
23
+ def acquire_token(tenant_id: str, client_id: str, client_secret: str, scope: str = "https://management.azure.com/.default") -> Dict[str, object]:
24
+ """Acquire an OAuth2 token from Azure AD using client credentials.
25
+
26
+ Uses a plain HTTP form POST to the v2 token endpoint and returns the parsed
27
+ JSON response (which contains access_token, expires_in, token_type, etc.).
28
+ This keeps the implementation dependency-free and testable; callers may
29
+ choose a different mechanism in production (azure-identity, MSAL).
30
+ """
31
+ token_url = f"https://login.microsoftonline.com/{tenant_id}/oauth2/v2.0/token"
32
+ data = {
33
+ "grant_type": "client_credentials",
34
+ "client_id": client_id,
35
+ "client_secret": client_secret,
36
+ "scope": scope,
37
+ }
38
+ body = urllib.parse.urlencode(data).encode("utf-8")
39
+ req = urllib.request.Request(token_url, data=body, method="POST")
40
+ req.add_header("Content-Type", "application/x-www-form-urlencoded")
41
+ with urllib.request.urlopen(req, timeout=30) as resp:
42
+ raw = resp.read().decode("utf-8")
43
+ return json.loads(raw)
44
+
45
+
46
+ def get_management_token_from_env(scope: Optional[str] = None) -> str:
47
+ creds = get_client_credentials_from_env()
48
+ token_resp = acquire_token(creds["tenant_id"], creds["client_id"], creds["client_secret"], scope or "https://management.azure.com/.default")
49
+ token = token_resp.get("access_token")
50
+ if not isinstance(token, str) or not token:
51
+ raise RuntimeError("Azure token response did not contain an access token")
52
+ return token
@@ -0,0 +1,80 @@
1
+ from __future__ import annotations
2
+
3
+ import argparse
4
+ import sys
5
+ from pathlib import Path
6
+
7
+ from detection_graph import __version__
8
+ from detection_graph.graph import DetectionGraph
9
+ from detection_graph.providers.defender import DefenderProvider
10
+ from detection_graph.providers.sentinel import SentinelProvider
11
+
12
+
13
+ def _add_input_arguments(parser: argparse.ArgumentParser) -> None:
14
+ parser.add_argument(
15
+ "--provider",
16
+ required=True,
17
+ choices=("sentinel", "defender"),
18
+ help="Provider format represented by the local JSON export",
19
+ )
20
+ parser.add_argument(
21
+ "--input",
22
+ "--input-path",
23
+ dest="input_path",
24
+ required=True,
25
+ help="Path to a local JSON export",
26
+ )
27
+ parser.add_argument(
28
+ "--attack-data",
29
+ "--attack-path",
30
+ dest="attack_path",
31
+ required=True,
32
+ help="Path to ATT&CK reference JSON",
33
+ )
34
+
35
+
36
+ def main(argv: list[str] | None = None) -> int:
37
+ parser = argparse.ArgumentParser(
38
+ prog="detection-graph",
39
+ description="Build and analyze ATT&CK coverage from local detection exports.",
40
+ )
41
+ parser.add_argument("--version", action="version", version=f"%(prog)s {__version__}")
42
+ subcommands = parser.add_subparsers(dest="command", required=True)
43
+
44
+ build_parser = subcommands.add_parser("build", help="Generate an interactive HTML graph")
45
+ _add_input_arguments(build_parser)
46
+ build_parser.add_argument("--output", required=True, help="Output HTML path")
47
+ build_parser.add_argument("--renderer", choices=("sigma", "pyvis"), default="sigma")
48
+ build_parser.add_argument("--seed", type=int, default=42)
49
+ build_parser.add_argument("--bundle", choices=("cdn", "local", "embed"), default="cdn")
50
+
51
+ analyze_parser = subcommands.add_parser("analyze", help="Print coverage by technique")
52
+ _add_input_arguments(analyze_parser)
53
+
54
+ args = parser.parse_args(argv)
55
+ try:
56
+ provider_type = SentinelProvider if args.provider == "sentinel" else DefenderProvider
57
+ provider = provider_type.from_json(args.input_path)
58
+ graph = DetectionGraph.from_attack_json(args.attack_path)
59
+ graph.add_rules(provider.get_rules())
60
+
61
+ if args.command == "build":
62
+ output_path = Path(args.output)
63
+ output_path.parent.mkdir(parents=True, exist_ok=True)
64
+ graph.export_html(
65
+ str(output_path),
66
+ renderer=args.renderer,
67
+ seed=args.seed,
68
+ bundle=args.bundle,
69
+ )
70
+ print(f"Wrote {output_path}")
71
+ else:
72
+ print(graph.analytics.coverage_by_technique().to_string(index=False))
73
+ return 0
74
+ except (OSError, ValueError) as error:
75
+ print(f"{parser.prog}: error: {error}", file=sys.stderr)
76
+ return 1
77
+
78
+
79
+ if __name__ == "__main__":
80
+ raise SystemExit(main())
@@ -0,0 +1,21 @@
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
+ selected_renderer = renderer or "sigma"
13
+ if selected_renderer == "sigma":
14
+ SigmaRenderer().render(graph, path, hierarchical=hierarchical, seed=seed, bundle=bundle)
15
+ return
16
+ if selected_renderer != "pyvis":
17
+ raise ValueError(f"Unsupported renderer: {selected_renderer}")
18
+
19
+ from detection_graph.visualizers.pyvis_renderer import PyVisRenderer
20
+ pr = PyVisRenderer()
21
+ pr.render(graph, path, hierarchical=hierarchical)
@@ -0,0 +1,80 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ import urllib.error
5
+ import urllib.request
6
+ from typing import Dict, Iterator, List, Optional
7
+
8
+ from detection_graph.auth.azure import acquire_token
9
+ from detection_graph.models.detection import DetectionRule
10
+
11
+
12
+ class DefenderAzureProvider:
13
+ """Fetch Defender alerts and normalize them as detection rules."""
14
+
15
+ def __init__(self, access_token: str, api_root: str):
16
+ self._token = access_token
17
+ self._api_root = api_root.rstrip("/")
18
+
19
+ @classmethod
20
+ def from_client_credentials(
21
+ cls,
22
+ tenant_id: str,
23
+ client_id: str,
24
+ client_secret: str,
25
+ scope: Optional[str] = None,
26
+ ) -> "DefenderAzureProvider":
27
+ response = acquire_token(
28
+ tenant_id,
29
+ client_id,
30
+ client_secret,
31
+ scope or "https://api.securitycenter.microsoft.com/.default",
32
+ )
33
+ token = response.get("access_token")
34
+ if not isinstance(token, str) or not token:
35
+ raise RuntimeError("Failed to acquire token for Defender APIs")
36
+ return cls(token, "https://api.securitycenter.microsoft.com")
37
+
38
+ def _get(self, url: str) -> Dict:
39
+ request = urllib.request.Request(url, method="GET")
40
+ request.add_header("Authorization", "Bearer " + self._token)
41
+ request.add_header("Accept", "application/json")
42
+ with urllib.request.urlopen(request, timeout=30) as response:
43
+ return json.loads(response.read().decode("utf-8"))
44
+
45
+ def _paged(self, first_url: str) -> Iterator[Dict]:
46
+ url = first_url
47
+ while url:
48
+ data = self._get(url)
49
+ if not isinstance(data, dict) or "value" not in data:
50
+ return
51
+ yield from data.get("value", [])
52
+ url = data.get("nextLink") or data.get("@odata.nextLink")
53
+
54
+ @staticmethod
55
+ def _rule(alert: Dict, source: str) -> DetectionRule:
56
+ rule_id = alert.get("id") or alert.get("alertId")
57
+ techniques = alert.get("attackTechniques") or alert.get("mdeAttackTechniques") or []
58
+ normalized_techniques = [
59
+ (technique.get("id") if isinstance(technique, dict) else str(technique)).upper()
60
+ for technique in techniques
61
+ ]
62
+ return DetectionRule(
63
+ id=f"rule:defender:{rule_id}",
64
+ name=alert.get("title") or alert.get("name") or rule_id,
65
+ source_product="Microsoft Defender",
66
+ source_provider="defender",
67
+ techniques=normalized_techniques,
68
+ severity=alert.get("severity"),
69
+ description=alert.get("description") or alert.get("descriptionText"),
70
+ tags={"source": source},
71
+ )
72
+
73
+ def get_rules(self) -> List[DetectionRule]:
74
+ try:
75
+ return [self._rule(alert, "securitycenter") for alert in self._paged(f"{self._api_root}/api/alerts")]
76
+ except (urllib.error.HTTPError, urllib.error.URLError):
77
+ return [
78
+ self._rule(alert, "graph")
79
+ for alert in self._paged("https://graph.microsoft.com/v1.0/security/alerts")
80
+ ]
@@ -5,7 +5,6 @@ from pathlib import Path
5
5
  from typing import List
6
6
 
7
7
  from detection_graph.models.detection import DetectionRule
8
- from detection_graph.providers.base import DetectionProvider
9
8
 
10
9
 
11
10
  class SentinelProvider:
@@ -0,0 +1,72 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ import urllib.request
5
+ from typing import List, Optional
6
+
7
+ from detection_graph.auth.azure import acquire_token
8
+ from detection_graph.models.detection import DetectionRule
9
+
10
+
11
+ class SentinelAzureProvider:
12
+ """Fetch Sentinel analytic rules using an Azure client-credential token."""
13
+
14
+ def __init__(self, access_token: str, workspace_resource_id: str):
15
+ self._token = access_token
16
+ self._workspace = workspace_resource_id.rstrip("/")
17
+
18
+ @classmethod
19
+ def from_client_credentials(
20
+ cls,
21
+ tenant_id: str,
22
+ client_id: str,
23
+ client_secret: str,
24
+ workspace_resource_id: str,
25
+ scope: Optional[str] = None,
26
+ ) -> "SentinelAzureProvider":
27
+ response = acquire_token(
28
+ tenant_id,
29
+ client_id,
30
+ client_secret,
31
+ scope or "https://management.azure.com/.default",
32
+ )
33
+ token = response.get("access_token")
34
+ if not isinstance(token, str) or not token:
35
+ raise RuntimeError("Failed to acquire token from Azure AD")
36
+ return cls(token, workspace_resource_id)
37
+
38
+ def _get(self, url: str) -> dict:
39
+ request = urllib.request.Request(url, method="GET")
40
+ request.add_header("Authorization", "Bearer " + self._token)
41
+ request.add_header("Accept", "application/json")
42
+ with urllib.request.urlopen(request, timeout=30) as response:
43
+ return json.loads(response.read().decode("utf-8"))
44
+
45
+ def get_rules(self) -> List[DetectionRule]:
46
+ api = (
47
+ f"{self._workspace}/providers/Microsoft.SecurityInsights/"
48
+ "alertRules?api-version=2023-02-01"
49
+ )
50
+ data = self._get(api)
51
+ rules: List[DetectionRule] = []
52
+ for item in data.get("value") or []:
53
+ rule_id = item.get("name") or item.get("id")
54
+ properties = item.get("properties") or {}
55
+ tactics = properties.get("tactics") or []
56
+ techniques = properties.get("techniques") or []
57
+ rules.append(
58
+ DetectionRule(
59
+ id=f"rule:sentinel:{rule_id}",
60
+ name=properties.get("displayName") or rule_id,
61
+ source_product="Microsoft Sentinel",
62
+ source_provider="sentinel",
63
+ tactics=[tactic.lower() for tactic in tactics],
64
+ techniques=[technique.upper() for technique in techniques],
65
+ severity=properties.get("severity"),
66
+ enabled=properties.get("enabled"),
67
+ description=properties.get("description") or properties.get("query"),
68
+ query=properties.get("query"),
69
+ tags=properties.get("tags") or {},
70
+ )
71
+ )
72
+ return rules
@@ -26,74 +26,41 @@ class SigmaRenderer:
26
26
  self.width = width
27
27
 
28
28
  def render(self, graph: nx.DiGraph, output_path: str, hierarchical: bool = False, seed: int = 42, bundle: str = "cdn") -> None:
29
- # Compute deterministic positions using NetworkX's spring layout
30
- try:
31
- pos = nx.spring_layout(graph, seed=seed)
32
- for n, (x, y) in pos.items():
33
- # ensure position metadata is present in node data
34
- if "data" not in graph.nodes[n]:
35
- graph.nodes[n]["data"] = {}
36
- graph.nodes[n]["data"]["x"] = float(x)
37
- graph.nodes[n]["data"]["y"] = float(y)
38
- except Exception:
39
- # fallback: let the client assign positions
40
- pass
41
-
42
- data = json_graph.node_link_data(graph)
43
-
44
- # enrich nodes with color and label
45
- for n in data.get("nodes", []):
46
- nmeta = n.get("data", {}) or {}
47
- ntype = nmeta.get("node_type")
48
- n["color"] = DEFAULT_COLORS.get(ntype, "#95a5a6")
49
- # label fallback
50
- n["label"] = nmeta.get("name") or n.get("id")
51
-
52
- # choose script tags based on bundle option
53
- if bundle == "cdn":
54
- scripts = (_CDN_GRAPHOLGY_SCRIPT, _CDN_SIGMA_SCRIPT)
55
- elif bundle == "local":
56
- # reference local package static assets relative to the HTML file
57
- # note: filenames match vendored assets in `src/detection_graph/static/`
58
- scripts = ("graphology.umd.min.js", "sigma.min.js")
59
- else:
60
- # embed mode: attempt to read bundled files from package resources or
61
- # fall back to reading from the filesystem (useful during development).
62
- try:
63
- import pkgutil
64
- import pathlib
65
- pkg_name = __package__
66
- gbytes = pkgutil.get_data(pkg_name, "../static/graphology.umd.min.js")
67
- sbytes = pkgutil.get_data(pkg_name, "../static/sigma.min.js")
68
- # fallback to disk relative to this file when pkgutil didn't find data
69
- if not gbytes:
70
- p = pathlib.Path(__file__).resolve().parent.parent / "static" / "graphology.umd.min.js"
71
- gbytes = p.read_bytes() if p.exists() else b""
72
- if not sbytes:
73
- p2 = pathlib.Path(__file__).resolve().parent.parent / "static" / "sigma.min.js"
74
- sbytes = p2.read_bytes() if p2.exists() else b""
75
- # When embedding, wrap raw JS into <script> tags so the template
76
- # receives valid script tags. Fall back to CDN tags if files missing.
77
- gs = ("<script>" + gbytes.decode("utf-8") + "</script>") if gbytes else _CDN_GRAPHOLGY_SCRIPT
78
- ss = ("<script>" + sbytes.decode("utf-8") + "</script>") if sbytes else _CDN_SIGMA_SCRIPT
79
- scripts = (gs, ss)
80
- except Exception:
81
- scripts = (_CDN_GRAPHOLGY_SCRIPT, _CDN_SIGMA_SCRIPT)
82
-
83
- # Use simple replacement to avoid Python format conflicts with JS template
29
+ if bundle not in {"cdn", "local", "embed"}:
30
+ raise ValueError(f"Unsupported bundle mode: {bundle}")
31
+
32
+ positions = nx.spring_layout(graph, seed=seed)
33
+ for node, (x, y) in positions.items():
34
+ graph.nodes[node].setdefault("data", {})
35
+ graph.nodes[node]["data"]["x"] = float(x)
36
+ graph.nodes[node]["data"]["y"] = float(y)
37
+
38
+ data = json_graph.node_link_data(graph)
39
+ for node in data.get("nodes", []):
40
+ metadata = node.get("data", {}) or {}
41
+ node["color"] = DEFAULT_COLORS.get(metadata.get("node_type"), "#95a5a6")
42
+ node["label"] = metadata.get("name") or node.get("id")
43
+
44
+ if bundle == "cdn":
45
+ scripts = (_CDN_GRAPHOLGY_SCRIPT, _CDN_SIGMA_SCRIPT)
46
+ elif bundle == "local":
47
+ scripts = ("graphology.umd.min.js", "sigma.min.js")
48
+ else:
49
+ from importlib.resources import files
50
+
51
+ static_dir = files("detection_graph").joinpath("static")
52
+ graphology = static_dir.joinpath("graphology.umd.min.js").read_text(encoding="utf-8")
53
+ sigma = static_dir.joinpath("sigma.min.js").read_text(encoding="utf-8")
54
+ scripts = (f"<script>{graphology}</script>", f"<script>{sigma}</script>")
55
+
56
+ serialized_data = json.dumps(data).replace("<", "\\u003c").replace(">", "\\u003e").replace("&", "\\u0026")
84
57
  html = (
85
- _SIGMA_TEMPLATE.replace("__DATA__", json.dumps(data))
86
- .replace("__GRAPH_SCRIPT_TAG__", scripts[0])
87
- .replace("__SIGMA_SCRIPT_TAG__", scripts[1])
58
+ _SIGMA_TEMPLATE.replace("__DATA__", serialized_data)
59
+ .replace("__GRAPH_SCRIPT_TAG__", scripts[0])
60
+ .replace("__SIGMA_SCRIPT_TAG__", scripts[1])
88
61
  )
89
-
90
- try:
91
- with open(output_path, "w", encoding="utf-8") as fh:
92
- fh.write(html)
93
- except Exception:
94
- # fallback to writing raw JSON if file write fails
95
- with open(output_path, "w", encoding="utf-8") as fh:
96
- fh.write(json.dumps(data, indent=2))
62
+ with open(output_path, "w", encoding="utf-8") as output_file:
63
+ output_file.write(html)
97
64
 
98
65
 
99
66
  _SIGMA_TEMPLATE = """
@@ -180,6 +147,7 @@ _SIGMA_TEMPLATE = """
180
147
  tooltip.style.borderRadius = '4px';
181
148
  tooltip.style.fontFamily = 'sans-serif';
182
149
  tooltip.style.fontSize = '12px';
150
+ tooltip.style.whiteSpace = 'pre-line';
183
151
  tooltip.style.display = 'none';
184
152
  document.body.appendChild(tooltip);
185
153
 
@@ -187,12 +155,10 @@ _SIGMA_TEMPLATE = """
187
155
  try {{
188
156
  renderer.on('enterNode', ({node}) => {{
189
157
  const attrs = g.getNodeAttributes(node) || {{}};
190
- const lines = [];
191
- for (const k in attrs) {{
192
- if (k === 'x' || k === 'y') continue;
193
- lines.push(`<strong>${{k}}</strong>: ${{String(attrs[k])}}`);
194
- }}
195
- tooltip.innerHTML = lines.join('<br>');
158
+ tooltip.textContent = Object.entries(attrs)
159
+ .filter(([key]) => key !== 'x' && key !== 'y')
160
+ .map(([key, value]) => `${{key}}: ${{String(value)}}`)
161
+ .join('\\n');
196
162
  tooltip.style.display = 'block';
197
163
  }});
198
164
  renderer.on('leaveNode', () => {{ tooltip.style.display = 'none'; }});
@@ -1,16 +0,0 @@
1
- Metadata-Version: 2.4
2
- Name: detection-graph
3
- Version: 0.1.0
4
- Summary: Interactive MITRE ATT&CK detection coverage graph for Microsoft security products
5
- Author: Your Name
6
- Author-email: you@example.com
7
- Requires-Python: >=3.12
8
- Classifier: Programming Language :: Python :: 3
9
- Classifier: Programming Language :: Python :: 3.12
10
- Classifier: Programming Language :: Python :: 3.13
11
- Classifier: Programming Language :: Python :: 3.14
12
- Requires-Dist: networkx (>=3.1,<4.0)
13
- Requires-Dist: pandas (>=2.2,<3.0)
14
- Requires-Dist: pydantic (>=2.2,<3.0)
15
- Requires-Dist: pyvis (>=0.3,<0.4)
16
- Requires-Dist: typer (>=0.10,<0.11)
@@ -1,25 +0,0 @@
1
- [tool.poetry]
2
- name = "detection-graph"
3
- version = "0.1.0"
4
- description = "Interactive MITRE ATT&CK detection coverage graph for Microsoft security products"
5
- authors = ["Your Name <you@example.com>"]
6
- include = ["src/detection_graph/static/*"]
7
-
8
- [tool.poetry.dependencies]
9
- python = ">=3.12"
10
- pydantic = "^2.2"
11
- networkx = "^3.1"
12
- pandas = "^2.2"
13
- pyvis = "^0.3"
14
- typer = "^0.10"
15
-
16
- [tool.poetry.dev-dependencies]
17
- pytest = "^7.0"
18
- ruff = "^0.15"
19
-
20
- [build-system]
21
- requires = ["poetry-core>=1.0.0"]
22
- build-backend = "poetry.core.masonry.api"
23
-
24
- [tool.poetry.scripts]
25
- detection-graph = "detection_graph.cli:main"
@@ -1,68 +0,0 @@
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())
@@ -1,30 +0,0 @@
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)