From 37b7a8e537c5e3a71276b8be435aea9bc15034f0 Mon Sep 17 00:00:00 2001 From: cuteNBD <206630735+bingdongni@users.noreply.github.com> Date: Tue, 17 Nov 2026 22:53:10 +0800 Subject: [PATCH 1/2] feat: export defensive log source mappings from a local STIX bundle --- mitreattack/attackToExcel/README.md | 8 +++ mitreattack/attackToExcel/attackToExcel.py | 10 +++ mitreattack/attackToExcel/stixToDf.py | 41 ++++++++++++ tests/test_to_excel.py | 78 ++++++++++++++++++++++ 4 files changed, 137 insertions(+) diff --git a/mitreattack/attackToExcel/README.md b/mitreattack/attackToExcel/README.md index a775cb8..015c124 100644 --- a/mitreattack/attackToExcel/README.md +++ b/mitreattack/attackToExcel/README.md @@ -141,3 +141,11 @@ print(citations_df[citations_df["reference"].str.contains("LOLBAS Wmic")]) # reference citation url # 1010 LOLBAS Wmic LOLBAS. (n.d.). Wmic.exe. Retrieved July 31, 2... https://lolbas-project.github.io/lolbas/Binari... ``` + +### Export defensive mappings as CSV + +```shell +attack-to-excel defensive-mappings enterprise-attack.json > defensive-mappings.csv +``` + +Each row joins an active technique to a detection strategy, one of its analytics, and a referenced log source or channel. The STIX and ATT&CK identifiers are included for joining with other datasets. Only the relationships declared in the local bundle are exported. Bundles predating detection strategies produce a header with no rows. diff --git a/mitreattack/attackToExcel/attackToExcel.py b/mitreattack/attackToExcel/attackToExcel.py index 149ed77..0ab596c 100644 --- a/mitreattack/attackToExcel/attackToExcel.py +++ b/mitreattack/attackToExcel/attackToExcel.py @@ -774,6 +774,16 @@ def _validate_cli_value(value: str, allowed_values: tuple[str, ...], label: str) return value +@app.command("defensive-mappings") +def defensive_mappings_cli( + stix_file: Annotated[Path, typer.Argument(exists=True, dir_okay=False, readable=True)], +): + """Write technique-to-log-source mappings from a local ATT&CK STIX bundle as CSV.""" + src = MemoryStore() + src.load_from_file(str(stix_file)) + stixToDf.techniqueDetectionLogSourcesDf(src).to_csv(sys.stdout, index=False) + + @app.command("from-stix") def from_stix_cli( domain: Annotated[ diff --git a/mitreattack/attackToExcel/stixToDf.py b/mitreattack/attackToExcel/stixToDf.py index 0e63a8b..66cc42f 100644 --- a/mitreattack/attackToExcel/stixToDf.py +++ b/mitreattack/attackToExcel/stixToDf.py @@ -598,6 +598,8 @@ def detectionStrategiesAnalyticsLogSourcesDf(src): for analytic_id in ds.get("x_mitre_analytic_refs", []): analytic = analytics_by_id.get(analytic_id) + if analytic is None: + continue analytic_attack_id = analytic["external_references"][0]["external_id"] platforms = ", ".join(sorted(analytic.get("x_mitre_platforms", []))) @@ -625,6 +627,45 @@ def detectionStrategiesAnalyticsLogSourcesDf(src): return pd.DataFrame(rows) +def techniqueDetectionLogSourcesDf(src): + """Map active techniques to the detection strategies, analytics and log sources referenced by the bundle.""" + techniques = remove_revoked_deprecated(src.query([Filter("type", "=", "attack-pattern")])) + by_id = { + technique["id"]: ref["external_id"] + for technique in techniques + for ref in technique.get("external_references", []) + if ref.get("source_name") in MITRE_ATTACK_ID_SOURCE_NAMES and "external_id" in ref + } + detects = src.query([Filter("type", "=", "relationship"), Filter("relationship_type", "=", "detects")]) + technique_columns = ["technique_id", "technique_attack_id", "detection_strategy_id"] + links = pd.DataFrame.from_records( + ( + (rel["target_ref"], by_id[rel["target_ref"]], rel["source_ref"]) + for rel in remove_revoked_deprecated(detects) + if rel["target_ref"] in by_id + ), + columns=technique_columns, + ).drop_duplicates() + log_sources = detectionStrategiesAnalyticsLogSourcesDf(src).rename(columns={"analytic_name": "analytic_attack_id"}) + # Keep the same CSV schema for bundles with no detection strategies. + columns = [ + "technique_attack_id", + "technique_id", + "detection_strategy_attack_id", + "detection_strategy_id", + "analytic_attack_id", + "analytic_id", + "platforms", + "log_source_name", + "channel", + "data_component_attack_id", + "data_component_id", + ] + if log_sources.empty: + return pd.DataFrame(columns=columns) + return links.merge(log_sources, on="detection_strategy_id")[columns] + + def groupsToDf(src): """Parse STIX groups from the given data and return corresponding pandas dataframes. diff --git a/tests/test_to_excel.py b/tests/test_to_excel.py index b470457..9ee26c2 100644 --- a/tests/test_to_excel.py +++ b/tests/test_to_excel.py @@ -1,12 +1,17 @@ """Tests for ATT&CK to Excel export behavior.""" +import csv +import io +import json from dataclasses import dataclass from pathlib import Path +from uuid import uuid4 import pandas as pd import pytest import stix2 from openpyxl import load_workbook +from typer.testing import CliRunner from mitreattack.attackToExcel import attackToExcel @@ -799,3 +804,76 @@ def test_enterprise_latest_smoke(tmp_path: Path, memstore_enterprise_latest: sti excel_folder = tmp_path / domain assert (excel_folder / f"{domain}.xlsx").exists() assert (excel_folder / f"{domain}-techniques.xlsx").exists() + + +@pytest.mark.parametrize("revoked", [False, True]) +def test_defensive_mappings_cli(tmp_path, revoked): + """Export active mappings and ignore missing analytics and revoked relationships.""" + def obj(kind, name, **fields): + return { + "type": kind, + "id": f"{kind}--{uuid4()}", + "name": name, + "created": "2025-01-01T00:00:00.000Z", + "modified": "2025-01-01T00:00:00.000Z", + **fields, + } + + def refs(external_id): + return [{"source_name": "mitre-attack", "external_id": external_id}] + + component = obj("x-mitre-data-component", "Events", external_references=refs("DC0001")) + analytic = obj( + "x-mitre-analytic", + "Correlation", + external_references=refs("AN0001"), + x_mitre_platforms=["Linux"], + x_mitre_log_source_references=[ + {"name": "Local audit", "channel": "events", "x_mitre_data_component_ref": component["id"]} + ], + ) + strategy = obj( + "x-mitre-detection-strategy", + "Coverage", + external_references=refs("DET0001"), + x_mitre_analytic_refs=[analytic["id"], f"x-mitre-analytic--{uuid4()}"], + ) + technique = stix2.AttackPattern(name="Example", external_references=refs("T0001")) + relation = stix2.Relationship( + relationship_type="detects", + source_ref=strategy["id"], + target_ref=technique.id, + revoked=revoked, + allow_custom=True, + ) + bundle = { + "type": "bundle", + "id": f"bundle--{uuid4()}", + "objects": [component, analytic, strategy, json.loads(technique.serialize()), json.loads(relation.serialize())], + } + path = tmp_path / "bundle.json" + path.write_text(json.dumps(bundle), encoding="utf-8") + + result = CliRunner().invoke(attackToExcel.app, ["defensive-mappings", str(path)]) + assert result.exit_code == 0, result.exception + reader = csv.DictReader(io.StringIO(result.stdout)) + assert "analytic_attack_id" in reader.fieldnames + rows = list(reader) + if revoked: + assert rows == [] + else: + assert rows == [ + { + "technique_attack_id": "T0001", + "technique_id": technique.id, + "detection_strategy_attack_id": "DET0001", + "detection_strategy_id": strategy["id"], + "analytic_attack_id": "AN0001", + "analytic_id": analytic["id"], + "platforms": "Linux", + "log_source_name": "Local audit", + "channel": "events", + "data_component_attack_id": "DC0001", + "data_component_id": component["id"], + } + ] From 02c1e158e0e1be2e80059866afccacb67ccf47c4 Mon Sep 17 00:00:00 2001 From: cuteNBD <206630735+bingdongni@users.noreply.github.com> Date: Tue, 17 Nov 2026 22:55:52 +0800 Subject: [PATCH 2/2] style: match the formatter in the CLI test --- tests/test_to_excel.py | 1 + 1 file changed, 1 insertion(+) diff --git a/tests/test_to_excel.py b/tests/test_to_excel.py index 9ee26c2..8d82424 100644 --- a/tests/test_to_excel.py +++ b/tests/test_to_excel.py @@ -809,6 +809,7 @@ def test_enterprise_latest_smoke(tmp_path: Path, memstore_enterprise_latest: sti @pytest.mark.parametrize("revoked", [False, True]) def test_defensive_mappings_cli(tmp_path, revoked): """Export active mappings and ignore missing analytics and revoked relationships.""" + def obj(kind, name, **fields): return { "type": kind,