返回网格
SKILL / GITHUB

analyzing-campaign-attribution-evidence

公开中

Systematically evaluate cyber-campaign evidence to attribute an operation to a threat actor, using the Diamond Model and Analysis of Competing Hypotheses (ACH) to weigh infrastructure overlaps, TTP consistency, malware code similarity, and timing/language artifacts into confidence-weighted attribution assessments. Use when an incident investigation needs a defensible attribution confidence level.

开发 analyzing-campaign-attribution-evidence 8 FILES 4 VIEWS 2026-08-18 09:00 SOURCE
GrokClaude CodeCursorCodexCLI
安装

一键装到本地 agent

和 SkillsMP 一样,先看源码再安装。Grok 用分享链接;Claude / Cursor / Codex 下载 zip 解到技能目录。

META

NAMEanalyzing-campaign-attribution-evidence
SLUGanalyzing-campaign-attribution-evidence
SOURCEgithub
BYTES43438

AI 怎么用

  1. 复制上面的 AI URL
  2. 粘贴到 Claude / ChatGPT / Grok / Cursor
  3. 再说你要做什么,AI 会先读 skill 再动手

SKILL.MD

AGENT READABLE

name: analyzing-campaign-attribution-evidence
description: Systematically evaluate cyber-campaign evidence to attribute an operation to a threat actor, using the Diamond Model and Analysis of Competing Hypotheses (ACH) to weigh infrastructure overlaps, TTP consistency, malware code similarity, and timing/language artifacts into confidence-weighted attribution assessments. Use when an incident investigation needs a defensible attribution confidence level.
domain: cybersecurity
subdomain: threat-intelligence
tags:
- threat-intelligence
- cti
- ioc
- mitre-attack
- stix
- attribution
- campaign-analysis
version: '1.0'
author: mahipal
license: Apache-2.0
nist_csf:
- ID.RA-01
- ID.RA-05
- DE.CM-01
- DE.AE-02
mitre_attack:
- T1587.001
- T1583.001
- T1588.002
- T1071.001

Analyzing Campaign Attribution Evidence

Overview

Campaign attribution analysis involves systematically evaluating evidence to determine which threat actor or group is responsible for a cyber operation. This skill covers collecting and weighting attribution indicators using the Diamond Model and ACH (Analysis of Competing Hypotheses), analyzing infrastructure overlaps, TTP consistency, malware code similarities, operational timing patterns, and language artifacts to build confidence-weighted attribution assessments.

When to Use

  • When investigating security incidents that require analyzing campaign attribution evidence
  • When building detection rules or threat hunting queries for this domain
  • When SOC analysts need structured procedures for this analysis type
  • When validating security monitoring coverage for related attack techniques

Prerequisites

  • Python 3.9+ with attackcti, stix2, networkx libraries
  • Access to threat intelligence platforms (MISP, OpenCTI)
  • Understanding of Diamond Model of Intrusion Analysis
  • Familiarity with MITRE ATT&CK threat group profiles
  • Knowledge of malware analysis and infrastructure tracking techniques

Key Concepts

Attribution Evidence Categories

  1. Infrastructure Overlap: Shared C2 servers, domains, IP ranges, hosting providers
  2. TTP Consistency: Matching ATT&CK techniques and sub-techniques across campaigns
  3. Malware Code Similarity: Shared code bases, compilers, PDB paths, encryption routines
  4. Operational Patterns: Timing (working hours, time zones), targeting patterns, operational tempo
  5. Language Artifacts: Embedded strings, variable names, error messages in specific languages
  6. Victimology: Target sector, geography, and organizational profile consistency

Confidence Levels

  • High Confidence: Multiple independent evidence categories converge on same actor
  • Moderate Confidence: Several evidence categories match, some ambiguity remains
  • Low Confidence: Limited evidence, possible false flags or shared tooling

Analysis of Competing Hypotheses (ACH)

Structured analytical method that evaluates evidence against multiple competing hypotheses. Each piece of evidence is scored as consistent, inconsistent, or neutral with respect to each hypothesis. The hypothesis with the least inconsistent evidence is favored.

Workflow

Step 1: Collect Attribution Evidence

from stix2 import MemoryStore, Filter
from collections import defaultdict

class AttributionAnalyzer:
    def __init__(self):
        self.evidence = []
        self.hypotheses = {}

    def add_evidence(self, category, description, value, confidence):
        self.evidence.append({
            "category": category,
            "description": description,
            "value": value,
            "confidence": confidence,
            "timestamp": None,
        })

    def add_hypothesis(self, actor_name, actor_id=""):
        self.hypotheses[actor_name] = {
            "actor_id": actor_id,
            "consistent_evidence": [],
            "inconsistent_evidence": [],
            "neutral_evidence": [],
            "score": 0,
        }

    def evaluate_evidence(self, evidence_idx, actor_name, assessment):
        """Assess evidence against a hypothesis: consistent/inconsistent/neutral."""
        if assessment == "consistent":
            self.hypotheses[actor_name]["consistent_evidence"].append(evidence_idx)
            self.hypotheses[actor_name]["score"] += self.evidence[evidence_idx]["confidence"]
        elif assessment == "inconsistent":
            self.hypotheses[actor_name]["inconsistent_evidence"].append(evidence_idx)
            self.hypotheses[actor_name]["score"] -= self.evidence[evidence_idx]["confidence"] * 2
        else:
            self.hypotheses[actor_name]["neutral_evidence"].append(evidence_idx)

    def rank_hypotheses(self):
        """Rank hypotheses by attribution score."""
        ranked = sorted(
            self.hypotheses.items(),
            key=lambda x: x[1]["score"],
            reverse=True,
        )
        return [
            {
                "actor": name,
                "score": data["score"],
                "consistent": len(data["consistent_evidence"]),
                "inconsistent": len(data["inconsistent_evidence"]),
                "confidence": self._score_to_confidence(data["score"]),
            }
            for name, data in ranked
        ]

    def _score_to_confidence(self, score):
        if score >= 80:
            return "HIGH"
        elif score >= 40:
            return "MODERATE"
        else:
            return "LOW"

Step 2: Infrastructure Overlap Analysis

def analyze_infrastructure_overlap(campaign_a_infra, campaign_b_infra):
    """Compare infrastructure between two campaigns for attribution."""
    overlap = {
        "shared_ips": set(campaign_a_infra.get("ips", [])).intersection(
            campaign_b_infra.get("ips", [])
        ),
        "shared_domains": set(campaign_a_infra.get("domains", [])).intersection(
            campaign_b_infra.get("domains", [])
        ),
        "shared_asns": set(campaign_a_infra.get("asns", [])).intersection(
            campaign_b_infra.get("asns", [])
        ),
        "shared_registrars": set(campaign_a_infra.get("registrars", [])).intersection(
            campaign_b_infra.get("registrars", [])
        ),
    }

    overlap_score = 0
    if overlap["shared_ips"]:
        overlap_score += 30
    if overlap["shared_domains"]:
        overlap_score += 25
    if overlap["shared_asns"]:
        overlap_score += 15
    if overlap["shared_registrars"]:
        overlap_score += 10

    return {
        "overlap": {k: list(v) for k, v in overlap.items()},
        "overlap_score": overlap_score,
        "assessment": "STRONG" if overlap_score >= 40 else "MODERATE" if overlap_score >= 20 else "WEAK",
    }

Step 3: TTP Comparison Across Campaigns

from attackcti import attack_client

def compare_campaign_ttps(campaign_techniques, known_actor_techniques):
    """Compare campaign TTPs against known threat actor profiles."""
    campaign_set = set(campaign_techniques)
    actor_set = set(known_actor_techniques)

    common = campaign_set.intersection(actor_set)
    unique_campaign = campaign_set - actor_set
    unique_actor = actor_set - campaign_set

    jaccard = len(common) / len(campaign_set.union(actor_set)) if campaign_set.union(actor_set) else 0

    return {
        "common_techniques": sorted(common),
        "common_count": len(common),
        "unique_to_campaign": sorted(unique_campaign),
        "unique_to_actor": sorted(unique_actor),
        "jaccard_similarity": round(jaccard, 3),
        "overlap_percentage": round(len(common) / len(campaign_set) * 100, 1) if campaign_set else 0,
    }

Step 4: Generate Attribution Report

def generate_attribution_report(analyzer):
    """Generate structured attribution assessment report."""
    rankings = analyzer.rank_hypotheses()

    report = {
        "assessment_date": "2026-02-23",
        "total_evidence_items": len(analyzer.evidence),
        "hypotheses_evaluated": len(analyzer.hypotheses),
        "rankings": rankings,
        "primary_attribution": rankings[0] if rankings else None,
        "evidence_summary": [
            {
                "index": i,
                "category": e["category"],
                "description": e["description"],
                "confidence": e["confidence"],
            }
            for i, e in enumerate(analyzer.evidence)
        ],
    }

    return report

Validation Criteria

  • Evidence collection covers all six attribution categories
  • ACH matrix properly evaluates evidence against competing hypotheses
  • Infrastructure overlap analysis identifies shared indicators
  • TTP comparison uses ATT&CK technique IDs for precision
  • Attribution confidence levels are properly justified
  • Report includes alternative hypotheses and false flag considerations

References

FULL BUNDLE (8 files)
# Agent Skill Package: analyzing-campaign-attribution-evidence

You are loading a published Agent Skill. Follow SKILL.md exactly.
Supporting files from the original zip are inlined below.
When SKILL.md says to read `references/...` or `scripts/...`, use the matching FILE section here — do not say the file is missing.

Canonical URL: https://skill.hk/s/analyzing-campaign-attribution-evidence.md
Human page: https://skill.hk/s/analyzing-campaign-attribution-evidence

Files (8):
- SKILL.md
- assets/template.md
- LICENSE
- references/api-reference.md
- references/standards.md
- references/workflows.md
- scripts/agent.py
- scripts/process.py

========================================================================
FILE: SKILL.md
========================================================================

---
name: analyzing-campaign-attribution-evidence
description: Systematically evaluate cyber-campaign evidence to attribute an operation to a threat actor, using the Diamond Model and Analysis of Competing Hypotheses (ACH) to weigh infrastructure overlaps, TTP consistency, malware code similarity, and timing/language artifacts into confidence-weighted attribution assessments. Use when an incident investigation needs a defensible attribution confidence level.
domain: cybersecurity
subdomain: threat-intelligence
tags:
- threat-intelligence
- cti
- ioc
- mitre-attack
- stix
- attribution
- campaign-analysis
version: '1.0'
author: mahipal
license: Apache-2.0
nist_csf:
- ID.RA-01
- ID.RA-05
- DE.CM-01
- DE.AE-02
mitre_attack:
- T1587.001
- T1583.001
- T1588.002
- T1071.001
---
# Analyzing Campaign Attribution Evidence

## Overview

Campaign attribution analysis involves systematically evaluating evidence to determine which threat actor or group is responsible for a cyber operation. This skill covers collecting and weighting attribution indicators using the Diamond Model and ACH (Analysis of Competing Hypotheses), analyzing infrastructure overlaps, TTP consistency, malware code similarities, operational timing patterns, and language artifacts to build confidence-weighted attribution assessments.


## When to Use

- When investigating security incidents that require analyzing campaign attribution evidence
- When building detection rules or threat hunting queries for this domain
- When SOC analysts need structured procedures for this analysis type
- When validating security monitoring coverage for related attack techniques

## Prerequisites

- Python 3.9+ with `attackcti`, `stix2`, `networkx` libraries
- Access to threat intelligence platforms (MISP, OpenCTI)
- Understanding of Diamond Model of Intrusion Analysis
- Familiarity with MITRE ATT&CK threat group profiles
- Knowledge of malware analysis and infrastructure tracking techniques

## Key Concepts

### Attribution Evidence Categories
1. **Infrastructure Overlap**: Shared C2 servers, domains, IP ranges, hosting providers
2. **TTP Consistency**: Matching ATT&CK techniques and sub-techniques across campaigns
3. **Malware Code Similarity**: Shared code bases, compilers, PDB paths, encryption routines
4. **Operational Patterns**: Timing (working hours, time zones), targeting patterns, operational tempo
5. **Language Artifacts**: Embedded strings, variable names, error messages in specific languages
6. **Victimology**: Target sector, geography, and organizational profile consistency

### Confidence Levels
- **High Confidence**: Multiple independent evidence categories converge on same actor
- **Moderate Confidence**: Several evidence categories match, some ambiguity remains
- **Low Confidence**: Limited evidence, possible false flags or shared tooling

### Analysis of Competing Hypotheses (ACH)
Structured analytical method that evaluates evidence against multiple competing hypotheses. Each piece of evidence is scored as consistent, inconsistent, or neutral with respect to each hypothesis. The hypothesis with the least inconsistent evidence is favored.

## Workflow

### Step 1: Collect Attribution Evidence

```python
from stix2 import MemoryStore, Filter
from collections import defaultdict

class AttributionAnalyzer:
    def __init__(self):
        self.evidence = []
        self.hypotheses = {}

    def add_evidence(self, category, description, value, confidence):
        self.evidence.append({
            "category": category,
            "description": description,
            "value": value,
            "confidence": confidence,
            "timestamp": None,
        })

    def add_hypothesis(self, actor_name, actor_id=""):
        self.hypotheses[actor_name] = {
            "actor_id": actor_id,
            "consistent_evidence": [],
            "inconsistent_evidence": [],
            "neutral_evidence": [],
            "score": 0,
        }

    def evaluate_evidence(self, evidence_idx, actor_name, assessment):
        """Assess evidence against a hypothesis: consistent/inconsistent/neutral."""
        if assessment == "consistent":
            self.hypotheses[actor_name]["consistent_evidence"].append(evidence_idx)
            self.hypotheses[actor_name]["score"] += self.evidence[evidence_idx]["confidence"]
        elif assessment == "inconsistent":
            self.hypotheses[actor_name]["inconsistent_evidence"].append(evidence_idx)
            self.hypotheses[actor_name]["score"] -= self.evidence[evidence_idx]["confidence"] * 2
        else:
            self.hypotheses[actor_name]["neutral_evidence"].append(evidence_idx)

    def rank_hypotheses(self):
        """Rank hypotheses by attribution score."""
        ranked = sorted(
            self.hypotheses.items(),
            key=lambda x: x[1]["score"],
            reverse=True,
        )
        return [
            {
                "actor": name,
                "score": data["score"],
                "consistent": len(data["consistent_evidence"]),
                "inconsistent": len(data["inconsistent_evidence"]),
                "confidence": self._score_to_confidence(data["score"]),
            }
            for name, data in ranked
        ]

    def _score_to_confidence(self, score):
        if score >= 80:
            return "HIGH"
        elif score >= 40:
            return "MODERATE"
        else:
            return "LOW"
```

### Step 2: Infrastructure Overlap Analysis

```python
def analyze_infrastructure_overlap(campaign_a_infra, campaign_b_infra):
    """Compare infrastructure between two campaigns for attribution."""
    overlap = {
        "shared_ips": set(campaign_a_infra.get("ips", [])).intersection(
            campaign_b_infra.get("ips", [])
        ),
        "shared_domains": set(campaign_a_infra.get("domains", [])).intersection(
            campaign_b_infra.get("domains", [])
        ),
        "shared_asns": set(campaign_a_infra.get("asns", [])).intersection(
            campaign_b_infra.get("asns", [])
        ),
        "shared_registrars": set(campaign_a_infra.get("registrars", [])).intersection(
            campaign_b_infra.get("registrars", [])
        ),
    }

    overlap_score = 0
    if overlap["shared_ips"]:
        overlap_score += 30
    if overlap["shared_domains"]:
        overlap_score += 25
    if overlap["shared_asns"]:
        overlap_score += 15
    if overlap["shared_registrars"]:
        overlap_score += 10

    return {
        "overlap": {k: list(v) for k, v in overlap.items()},
        "overlap_score": overlap_score,
        "assessment": "STRONG" if overlap_score >= 40 else "MODERATE" if overlap_score >= 20 else "WEAK",
    }
```

### Step 3: TTP Comparison Across Campaigns

```python
from attackcti import attack_client

def compare_campaign_ttps(campaign_techniques, known_actor_techniques):
    """Compare campaign TTPs against known threat actor profiles."""
    campaign_set = set(campaign_techniques)
    actor_set = set(known_actor_techniques)

    common = campaign_set.intersection(actor_set)
    unique_campaign = campaign_set - actor_set
    unique_actor = actor_set - campaign_set

    jaccard = len(common) / len(campaign_set.union(actor_set)) if campaign_set.union(actor_set) else 0

    return {
        "common_techniques": sorted(common),
        "common_count": len(common),
        "unique_to_campaign": sorted(unique_campaign),
        "unique_to_actor": sorted(unique_actor),
        "jaccard_similarity": round(jaccard, 3),
        "overlap_percentage": round(len(common) / len(campaign_set) * 100, 1) if campaign_set else 0,
    }
```

### Step 4: Generate Attribution Report

```python
def generate_attribution_report(analyzer):
    """Generate structured attribution assessment report."""
    rankings = analyzer.rank_hypotheses()

    report = {
        "assessment_date": "2026-02-23",
        "total_evidence_items": len(analyzer.evidence),
        "hypotheses_evaluated": len(analyzer.hypotheses),
        "rankings": rankings,
        "primary_attribution": rankings[0] if rankings else None,
        "evidence_summary": [
            {
                "index": i,
                "category": e["category"],
                "description": e["description"],
                "confidence": e["confidence"],
            }
            for i, e in enumerate(analyzer.evidence)
        ],
    }

    return report
```

## Validation Criteria

- Evidence collection covers all six attribution categories
- ACH matrix properly evaluates evidence against competing hypotheses
- Infrastructure overlap analysis identifies shared indicators
- TTP comparison uses ATT&CK technique IDs for precision
- Attribution confidence levels are properly justified
- Report includes alternative hypotheses and false flag considerations

## References

- [Diamond Model of Intrusion Analysis](https://www.activeresponse.org/wp-content/uploads/2013/07/diamond.pdf)
- [MITRE ATT&CK Groups](https://attack.mitre.org/groups/)
- [Analysis of Competing Hypotheses](https://www.cia.gov/static/9a5f1162fd0932c29e985f0159f56c07/Tradecraft-Primer-apr09.pdf)
- [Threat Attribution Framework](https://www.mandiant.com/resources/reports)


========================================================================
FILE: assets/template.md
========================================================================

# Campaign Attribution Analysis Report Template

## Report Metadata
| Field | Value |
|-------|-------|
| Report ID | CTI-YYYY-NNNN |
| Date | YYYY-MM-DD |
| Classification | TLP:AMBER |
| Analyst | [Name] |
| Confidence | High/Moderate/Low |

## Executive Summary
[Brief overview of key findings and their significance]

## Key Findings
1. [Finding 1 with supporting evidence]
2. [Finding 2 with supporting evidence]
3. [Finding 3 with supporting evidence]

## Detailed Analysis
### Finding 1
- **Evidence**: [Description of evidence]
- **Confidence**: High/Moderate/Low
- **MITRE ATT&CK**: [Relevant technique IDs]
- **Impact Assessment**: [Potential impact to organization]

## Indicators of Compromise
| Type | Value | Context | Confidence |
|------|-------|---------|-----------|
| | | | |

## Recommendations
1. **Immediate**: [Actions requiring immediate attention]
2. **Short-term**: [Actions within 1-2 weeks]
3. **Long-term**: [Strategic improvements]

## References
- [Source 1]
- [Source 2]


========================================================================
FILE: LICENSE
========================================================================


                                 Apache License
                           Version 2.0, January 2004
                        http://www.apache.org/licenses/

   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION

   1. Definitions.

      "License" shall mean the terms and conditions for use, reproduction,
      and distribution as defined by Sections 1 through 9 of this document.

      "Licensor" shall mean the copyright owner or entity authorized by
      the copyright owner that is granting the License.

      "Legal Entity" shall mean the union of the acting entity and all
      other entities that control, are controlled by, or are under common
      control with that entity. For the purposes of this definition,
      "control" means (i) the power, direct or indirect, to cause the
      direction or management of such entity, whether by contract or
      otherwise, or (ii) ownership of fifty percent (50%) or more of the
      outstanding shares, or (iii) beneficial ownership of such entity.

      "You" (or "Your") shall mean an individual or Legal Entity
      exercising permissions granted by this License.

      "Source" form shall mean the preferred form for making modifications,
      including but not limited to software source code, documentation
      source, and configuration files.

      "Object" form shall mean any form resulting from mechanical
      transformation or translation of a Source form, including but
      not limited to compiled object code, generated documentation,
      and conversions to other media types.

      "Work" shall mean the work of authorship, whether in Source or
      Object form, made available under the License, as indicated by a
      copyright notice that is included in or attached to the work
      (an example is provided in the Appendix below).

      "Derivative Works" shall mean any work, whether in Source or Object
      form, that is based on (or derived from) the Work and for which the
      editorial revisions, annotations, elaborations, or other modifications
      represent, as a whole, an original work of authorship. For the purposes
      of this License, Derivative Works shall not include works that remain
      separable from, or merely link (or bind by name) to the interfaces of,
      the Work and Derivative Works thereof.

      "Contribution" shall mean any work of authorship, including
      the original version of the Work and any modifications or additions
      to that Work or Derivative Works thereof, that is intentionally
      submitted to the Licensor for inclusion in the Work by the copyright owner
      or by an individual or Legal Entity authorized to submit on behalf of
      the copyright owner. For the purposes of this definition, "submitted"
      means any form of electronic, verbal, or written communication sent
      to the Licensor or its representatives, including but not limited to
      communication on electronic mailing lists, source code control systems,
      and issue tracking systems that are managed by, or on behalf of, the
      Licensor for the purpose of discussing and improving the Work, but
      excluding communication that is conspicuously marked or otherwise
      designated in writing by the copyright owner as "Not a Contribution."

      "Contributor" shall mean Licensor and any individual or Legal Entity
      on behalf of whom a Contribution has been received by the Licensor and
      subsequently incorporated within the Work.

   2. Grant of Copyright License. Subject to the terms and conditions of
      this License, each Contributor hereby grants to You a perpetual,
      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      copyright license to reproduce, prepare Derivative Works of,
      publicly display, publicly perform, sublicense, and distribute the
      Work and such Derivative Works in Source or Object form.

   3. Grant of Patent License. Subject to the terms and conditions of
      this License, each Contributor hereby grants to You a perpetual,
      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      (except as stated in this section) patent license to make, have made,
      use, offer to sell, sell, import, and otherwise transfer the Work,
      where such license applies only to those patent claims licensable
      by such Contributor that are necessarily infringed by their
      Contribution(s) alone or by combination of their Contribution(s)
      with the Work to which such Contribution(s) was submitted. If You
      institute patent litigation against any entity (including a
      cross-claim or counterclaim in a lawsuit) alleging that the Work
      or a Contribution incorporated within the Work constitutes direct
      or contributory patent infringement, then any patent licenses
      granted to You under this License for that Work shall terminate
      as of the date such litigation is filed.

   4. Redistribution. You may reproduce and distribute copies of the
      Work or Derivative Works thereof in any medium, with or without
      modifications, and in Source or Object form, provided that You
      meet the following conditions:

      (a) You must give any other recipients of the Work or
          Derivative Works a copy of this License; and

      (b) You must cause any modified files to carry prominent notices
          stating that You changed the files; and

      (c) You must retain, in the Source form of any Derivative Works
          that You distribute, all copyright, patent, trademark, and
          attribution notices from the Source form of the Work,
          excluding those notices that do not pertain to any part of
          the Derivative Works; and

      (d) If the Work includes a "NOTICE" text file as part of its
          distribution, then any Derivative Works that You distribute must
          include a readable copy of the attribution notices contained
          within such NOTICE file, excluding any notices that do not
          pertain to any part of the Derivative Works, in at least one
          of the following places: within a NOTICE text file distributed
          as part of the Derivative Works; within the Source form or
          documentation, if provided along with the Derivative Works; or,
          within a display generated by the Derivative Works, if and
          wherever such third-party notices normally appear. The contents
          of the NOTICE file are for informational purposes only and
          do not modify the License. You may add Your own attribution
          notices within Derivative Works that You distribute, alongside
          or as an addendum to the NOTICE text from the Work, provided
          that such additional attribution notices cannot be construed
          as modifying the License.

      You may add Your own copyright statement to Your modifications and
      may provide additional or different license terms and conditions
      for use, reproduction, or distribution of Your modifications, or
      for any such Derivative Works as a whole, provided Your use,
      reproduction, and distribution of the Work otherwise complies with
      the conditions stated in this License.

   5. Submission of Contributions. Unless You explicitly state otherwise,
      any Contribution intentionally submitted for inclusion in the Work
      by You to the Licensor shall be under the terms and conditions of
      this License, without any additional terms or conditions.
      Notwithstanding the above, nothing herein shall supersede or modify
      the terms of any separate license agreement you may have executed
      with Licensor regarding such Contributions.

   6. Trademarks. This License does not grant permission to use the trade
      names, trademarks, service marks, or product names of the Licensor,
      except as required for reasonable and customary use in describing the
      origin of the Work and reproducing the content of the NOTICE file.

   7. Disclaimer of Warranty. Unless required by applicable law or
      agreed to in writing, Licensor provides the Work (and each
      Contributor provides its Contributions) on an "AS IS" BASIS,
      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
      implied, including, without limitation, any warranties or conditions
      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
      PARTICULAR PURPOSE. You are solely responsible for determining the
      appropriateness of using or redistributing the Work and assume any
      risks associated with Your exercise of permissions under this License.

   8. Limitation of Liability. In no event and under no legal theory,
      whether in tort (including negligence), contract, or otherwise,
      unless required by applicable law (such as deliberate and grossly
      negligent acts) or agreed to in writing, shall any Contributor be
      liable to You for damages, including any direct, indirect, special,
      incidental, or consequential damages of any character arising as a
      result of this License or out of the use or inability to use the
      Work (including but not limited to damages for loss of goodwill,
      work stoppage, computer failure or malfunction, or any and all
      other commercial damages or losses), even if such Contributor
      has been advised of the possibility of such damages.

   9. Accepting Warranty or Additional Liability. While redistributing
      the Work or Derivative Works thereof, You may choose to offer,
      and charge a fee for, acceptance of support, warranty, indemnity,
      or other liability obligations and/or rights consistent with this
      License. However, in accepting such obligations, You may act only
      on Your own behalf and on Your sole responsibility, not on behalf
      of any other Contributor, and only if You agree to indemnify,
      defend, and hold each Contributor harmless for any liability
      incurred by, or claims asserted against, such Contributor by reason
      of your accepting any such warranty or additional liability.

   END OF TERMS AND CONDITIONS

   APPENDIX: How to apply the Apache License to your work.

      To apply the Apache License to your work, attach the following
      boilerplate notice, with the fields enclosed by brackets "[]"
      replaced with your own identifying information. (Don't include
      the brackets!)  The text should be enclosed in the appropriate
      comment syntax for the file format. Please do not remove or change
      the license header comment from a contributed file except when
      necessary.

   Copyright 2026 mukul975

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.


========================================================================
FILE: references/api-reference.md
========================================================================

# API Reference: Campaign Attribution Evidence Analysis

## Diamond Model of Intrusion Analysis

### Four Core Features
| Feature | Description | Attribution Value |
|---------|-------------|-------------------|
| Adversary | Threat actor identity | Direct attribution |
| Capability | Malware, exploits, tools | Indirect - shared tooling |
| Infrastructure | C2, domains, IPs | Strong - operational overlap |
| Victim | Targets, sectors, regions | Contextual - targeting pattern |

### Pivot Analysis
```
Adversary ←→ Capability ←→ Infrastructure ←→ Victim
    ↕              ↕              ↕              ↕
  (HUMINT)     (Malware DB)   (WHOIS/DNS)   (Victimology)
```

## Analysis of Competing Hypotheses (ACH)

### Matrix Format
```
Evidence \ Hypothesis  |  APT28  |  APT29  |  Lazarus  |  Unknown
-----------------------------------------------------------------
Infrastructure overlap  |   ++    |    -    |     -     |    N
TTP consistency        |   ++    |   ++    |     -     |    N
Malware similarity     |    +    |    -    |     -     |    N
Timing (UTC+3)         |   ++    |   ++    |     -     |    N
Language (Russian)     |   ++    |   ++    |     -     |    N
```

### Scoring
| Symbol | Meaning | Weight |
|--------|---------|--------|
| `++` | Strongly consistent | +2 |
| `+` | Consistent | +1 |
| `N` | Neutral | 0 |
| `-` | Inconsistent | -1 |
| `--` | Strongly inconsistent | -2 |

## MITRE ATT&CK Group Queries

### Python (mitreattack-python)
```python
from mitreattack.stix20 import MitreAttackData
attack = MitreAttackData("enterprise-attack.json")
group = attack.get_group_by_alias("APT29")
techniques = attack.get_techniques_used_by_group(group.id)
```

### STIX2 Relationship Query
```python
from stix2 import Filter
relationships = src.query([
    Filter("type", "=", "relationship"),
    Filter("source_ref", "=", group_id),
    Filter("relationship_type", "=", "uses"),
])
```

## Infrastructure Overlap Tools

### PassiveTotal / RiskIQ
```bash
# WHOIS history
curl -u user:key "https://api.passivetotal.org/v2/whois?query=domain.com"

# Passive DNS
curl -u user:key "https://api.passivetotal.org/v2/dns/passive?query=1.2.3.4"
```

### VirusTotal Relations
```bash
curl -H "x-apikey: KEY" \
  "https://www.virustotal.com/api/v3/domains/example.com/communicating_files"
```

## Confidence Assessment Framework

| Level | Score Range | Criteria |
|-------|------------|---------|
| HIGH | 0.8-1.0 | Multiple independent evidence types converge |
| MEDIUM | 0.5-0.8 | Significant evidence with some gaps |
| LOW | 0.2-0.5 | Limited evidence, alternative hypotheses remain |
| NEGLIGIBLE | 0.0-0.2 | Insufficient evidence for attribution |

## STIX Attribution Objects

### Campaign Object
```json
{
  "type": "campaign",
  "name": "Operation DarkShadow",
  "first_seen": "2024-01-15T00:00:00Z",
  "last_seen": "2024-03-20T00:00:00Z",
  "objective": "Espionage targeting defense sector"
}
```

### Attribution Relationship
```json
{
  "type": "relationship",
  "relationship_type": "attributed-to",
  "source_ref": "campaign--abc123",
  "target_ref": "intrusion-set--def456",
  "confidence": 75
}
```


========================================================================
FILE: references/standards.md
========================================================================

# Standards and Frameworks Reference

## Applicable Standards
- **STIX 2.1**: Structured Threat Information eXpression for CTI data representation
- **TAXII 2.1**: Transport protocol for sharing CTI over HTTPS
- **MITRE ATT&CK**: Adversary tactics, techniques, and procedures taxonomy
- **Diamond Model**: Intrusion analysis framework (Adversary, Capability, Infrastructure, Victim)
- **Traffic Light Protocol (TLP)**: Information sharing classification (CLEAR, GREEN, AMBER, RED)

## MITRE ATT&CK Relevance
- Technique mapping for threat actor behavior classification
- Data sources for detection capability assessment
- Mitigation strategies linked to specific techniques

## Industry Frameworks
- NIST Cybersecurity Framework (CSF) 2.0 - Identify function
- ISO 27001:2022 - A.5.7 Threat Intelligence
- FIRST Standards - TLP, CSIRT, vulnerability coordination

## References
- [STIX 2.1 Specification](https://docs.oasis-open.org/cti/stix/v2.1/stix-v2.1.html)
- [MITRE ATT&CK](https://attack.mitre.org/)
- [Diamond Model Paper](https://www.activeresponse.org/wp-content/uploads/2013/07/diamond.pdf)
- [NIST CSF 2.0](https://www.nist.gov/cyberframework)


========================================================================
FILE: references/workflows.md
========================================================================

# Campaign Attribution Analysis Workflows

## Workflow 1: Collection and Analysis
```
[Intelligence Sources] --> [Data Collection] --> [Analysis] --> [Reporting]
        |                        |                   |               |
        v                        v                   v               v
  OSINT/HUMINT/SIGINT    Normalize/Enrich    Assess/Correlate  Disseminate
```

### Steps:
1. **Planning**: Define intelligence requirements and collection priorities
2. **Collection**: Gather data from relevant sources
3. **Processing**: Normalize data formats and filter noise
4. **Analysis**: Apply analytical frameworks and correlate findings
5. **Production**: Generate intelligence products and reports
6. **Dissemination**: Share with stakeholders via appropriate channels
7. **Feedback**: Collect consumer feedback to refine future collection

## Workflow 2: Continuous Monitoring
```
[Watchlist] --> [Automated Monitoring] --> [Change Detection] --> [Alert/Update]
```

### Steps:
1. **Define Watchlist**: Identify indicators, actors, and topics to monitor
2. **Configure Monitoring**: Set up automated collection from relevant sources
3. **Change Detection**: Identify new or changed intelligence
4. **Assessment**: Evaluate significance of changes
5. **Alerting**: Notify stakeholders of significant intelligence updates
6. **Archive**: Store intelligence for historical analysis and trending


========================================================================
FILE: scripts/agent.py
========================================================================

#!/usr/bin/env python3
"""Campaign attribution analysis agent using Diamond Model and ACH methodology.

Evaluates attribution evidence including infrastructure overlaps, TTP consistency,
malware code similarity, timing patterns, and language artifacts.
"""

import json
import re
from collections import defaultdict
from datetime import datetime


DIAMOND_DIMENSIONS = {
    "adversary": "Threat actor identity, group attribution",
    "capability": "Malware, exploits, tools used",
    "infrastructure": "C2 servers, domains, IP addresses",
    "victim": "Targeted sectors, regions, organizations",
}

EVIDENCE_WEIGHTS = {
    "infrastructure_overlap": 0.25,
    "ttp_consistency": 0.30,
    "malware_code_similarity": 0.25,
    "timing_pattern": 0.10,
    "language_artifact": 0.10,
}

CONFIDENCE_LEVELS = {
    (0.8, 1.0): "HIGH - Strong attribution confidence",
    (0.5, 0.8): "MEDIUM - Moderate attribution, further analysis recommended",
    (0.2, 0.5): "LOW - Weak attribution, insufficient evidence",
    (0.0, 0.2): "NEGLIGIBLE - No meaningful attribution possible",
}


def diamond_model_analysis(adversary=None, capability=None, infrastructure=None, victim=None):
    """Structure evidence using the Diamond Model of Intrusion Analysis."""
    model = {
        "adversary": {
            "identified": adversary is not None,
            "details": adversary or "Unknown",
        },
        "capability": {
            "tools": capability.get("tools", []) if capability else [],
            "exploits": capability.get("exploits", []) if capability else [],
            "malware": capability.get("malware", []) if capability else [],
        },
        "infrastructure": {
            "c2_servers": infrastructure.get("c2", []) if infrastructure else [],
            "domains": infrastructure.get("domains", []) if infrastructure else [],
            "ip_addresses": infrastructure.get("ips", []) if infrastructure else [],
        },
        "victim": {
            "sectors": victim.get("sectors", []) if victim else [],
            "regions": victim.get("regions", []) if victim else [],
        },
        "pivot_opportunities": [],
    }
    if infrastructure and infrastructure.get("c2"):
        model["pivot_opportunities"].append("Pivot from C2 infrastructure to related campaigns")
    if capability and capability.get("malware"):
        model["pivot_opportunities"].append("Pivot from malware samples to shared infrastructure")
    return model


def evaluate_infrastructure_overlap(campaign_infra, known_actor_infra):
    """Score infrastructure overlap between campaign and known actor."""
    campaign_set = set(campaign_infra)
    known_set = set(known_actor_infra)
    if not campaign_set or not known_set:
        return 0.0, []
    overlap = campaign_set & known_set
    score = len(overlap) / max(len(campaign_set), len(known_set))
    return round(score, 4), sorted(overlap)


def evaluate_ttp_consistency(campaign_ttps, actor_ttps):
    """Score TTP consistency using MITRE ATT&CK technique overlap."""
    campaign_set = set(campaign_ttps)
    actor_set = set(actor_ttps)
    if not campaign_set or not actor_set:
        return 0.0, []
    overlap = campaign_set & actor_set
    jaccard = len(overlap) / len(campaign_set | actor_set)
    return round(jaccard, 4), sorted(overlap)


def evaluate_malware_similarity(sample_features, known_features):
    """Score malware code similarity based on feature comparison."""
    if not sample_features or not known_features:
        return 0.0
    matches = 0
    total = max(len(sample_features), len(known_features))
    for feature in sample_features:
        if feature in known_features:
            matches += 1
    return round(matches / total, 4) if total > 0 else 0.0


def evaluate_timing_pattern(campaign_timestamps, actor_timezone_offset=None):
    """Analyze operational timing to infer timezone/working hours."""
    if not campaign_timestamps:
        return {"score": 0.0, "working_hours": None, "timezone_guess": None}
    hours = []
    for ts in campaign_timestamps:
        try:
            if isinstance(ts, str):
                dt = datetime.fromisoformat(ts.replace("Z", "+00:00"))
            else:
                dt = ts
            adjusted = dt.hour + (actor_timezone_offset or 0)
            hours.append(adjusted % 24)
        except (ValueError, TypeError):
            continue
    if not hours:
        return {"score": 0.0}
    work_hours = sum(1 for h in hours if 8 <= h <= 18)
    work_ratio = work_hours / len(hours)
    avg_hour = sum(hours) / len(hours)
    return {
        "score": round(work_ratio, 4),
        "average_hour_utc": round(avg_hour, 1),
        "work_hour_ratio": round(work_ratio, 4),
        "sample_size": len(hours),
    }


def evaluate_language_artifacts(strings_list):
    """Detect language artifacts in malware strings or documents."""
    language_indicators = {
        "Russian": [r"[а-яА-Я]{3,}", r"codepage.*1251", r"locale.*ru"],
        "Chinese": [r"[\u4e00-\u9fff]{2,}", r"codepage.*936", r"GB2312"],
        "Korean": [r"[\uac00-\ud7af]{2,}", r"codepage.*949", r"EUC-KR"],
        "Farsi": [r"[\u0600-\u06ff]{3,}", r"codepage.*1256"],
        "English": [r"\b(the|and|for|with)\b"],
    }
    detections = defaultdict(int)
    for s in strings_list:
        for lang, patterns in language_indicators.items():
            for pattern in patterns:
                if re.search(pattern, s, re.IGNORECASE):
                    detections[lang] += 1
    total = sum(detections.values()) or 1
    scored = {lang: round(count / total, 4) for lang, count in detections.items()}
    return scored


def ach_analysis(hypotheses, evidence_items):
    """Analysis of Competing Hypotheses (ACH) for attribution."""
    matrix = {}
    for hyp in hypotheses:
        hyp_name = hyp["name"]
        matrix[hyp_name] = {"consistent": 0, "inconsistent": 0, "neutral": 0, "score": 0}
        for evidence in evidence_items:
            ev_name = evidence["name"]
            consistency = evidence.get("hypotheses", {}).get(hyp_name, "neutral")
            if consistency == "consistent":
                matrix[hyp_name]["consistent"] += evidence.get("weight", 1)
            elif consistency == "inconsistent":
                matrix[hyp_name]["inconsistent"] += evidence.get("weight", 1)
            else:
                matrix[hyp_name]["neutral"] += evidence.get("weight", 1)
        c = matrix[hyp_name]["consistent"]
        i = matrix[hyp_name]["inconsistent"]
        matrix[hyp_name]["score"] = round((c - i) / (c + i + 0.01), 4)
    return matrix


def compute_attribution_score(scores):
    """Compute weighted attribution confidence score."""
    total = 0.0
    for evidence_type, weight in EVIDENCE_WEIGHTS.items():
        score = scores.get(evidence_type, 0.0)
        total += score * weight
    confidence = "UNKNOWN"
    for (low, high), label in CONFIDENCE_LEVELS.items():
        if low <= total < high:
            confidence = label
            break
    return round(total, 4), confidence


def generate_attribution_report(campaign_name, candidate_actor, evidence):
    """Generate structured attribution assessment report."""
    scores = {}
    details = {}

    infra_score, infra_overlap = evaluate_infrastructure_overlap(
        evidence.get("campaign_infra", []), evidence.get("actor_infra", []))
    scores["infrastructure_overlap"] = infra_score
    details["infrastructure_overlap"] = infra_overlap

    ttp_score, ttp_overlap = evaluate_ttp_consistency(
        evidence.get("campaign_ttps", []), evidence.get("actor_ttps", []))
    scores["ttp_consistency"] = ttp_score
    details["ttp_consistency"] = ttp_overlap

    malware_score = evaluate_malware_similarity(
        evidence.get("sample_features", []), evidence.get("known_features", []))
    scores["malware_code_similarity"] = malware_score

    timing = evaluate_timing_pattern(
        evidence.get("timestamps", []), evidence.get("tz_offset"))
    scores["timing_pattern"] = timing.get("score", 0.0)
    details["timing"] = timing

    lang = evaluate_language_artifacts(evidence.get("strings", []))
    scores["language_artifact"] = max(lang.values()) if lang else 0.0
    details["language_artifacts"] = lang

    total_score, confidence = compute_attribution_score(scores)

    return {
        "campaign": campaign_name,
        "candidate_actor": candidate_actor,
        "attribution_score": total_score,
        "confidence_level": confidence,
        "evidence_scores": scores,
        "evidence_details": details,
    }


if __name__ == "__main__":
    print("=" * 60)
    print("Campaign Attribution Evidence Analysis Agent")
    print("Diamond Model, ACH, TTP/infrastructure/malware scoring")
    print("=" * 60)

    demo_evidence = {
        "campaign_infra": ["185.220.101.1", "evil-domain.com", "c2.attacker.net"],
        "actor_infra": ["185.220.101.1", "c2.attacker.net", "other-domain.org"],
        "campaign_ttps": ["T1566.001", "T1059.001", "T1053.005", "T1071.001", "T1041"],
        "actor_ttps": ["T1566.001", "T1059.001", "T1053.005", "T1071.001", "T1021.001", "T1003.001"],
        "sample_features": ["xor_0x55", "mutex_Global\\QWE", "ua_Mozilla5", "rc4_key"],
        "known_features": ["xor_0x55", "mutex_Global\\QWE", "ua_Mozilla5", "aes_cbc"],
        "timestamps": ["2024-03-15T06:30:00Z", "2024-03-15T07:15:00Z",
                        "2024-03-16T08:00:00Z", "2024-03-16T09:45:00Z"],
        "tz_offset": 3,
        "strings": ["Привет мир", "connect to server", "upload file"],
    }

    report = generate_attribution_report("Operation DarkShadow", "APT29", demo_evidence)

    print(f"\n[*] Campaign: {report['campaign']}")
    print(f"[*] Candidate: {report['candidate_actor']}")
    print(f"[*] Attribution Score: {report['attribution_score']}")
    print(f"[*] Confidence: {report['confidence_level']}")
    print("\n--- Evidence Scores ---")
    for ev, score in report["evidence_scores"].items():
        weight = EVIDENCE_WEIGHTS.get(ev, 0)
        print(f"  {ev:30s} score={score:.4f}  weight={weight}")
    print(f"\n[*] Full report:\n{json.dumps(report, indent=2, default=str)}")


========================================================================
FILE: scripts/process.py
========================================================================

#!/usr/bin/env python3
"""
Campaign Attribution Evidence Analysis Script

Implements structured attribution analysis:
- Analysis of Competing Hypotheses (ACH) matrix
- Infrastructure overlap scoring
- TTP similarity comparison using ATT&CK
- Evidence weighting and confidence assessment

Requirements:
    pip install attackcti stix2 requests

Usage:
    python process.py --evidence evidence.json --hypotheses actors.json --output report.json
    python process.py --compare-ttps --campaign campaign_techs.json --actor APT29
"""

import argparse
import json
import sys
from collections import defaultdict


class AttributionEngine:
    """Structured attribution analysis using ACH methodology."""

    def __init__(self):
        self.evidence = []
        self.hypotheses = {}

    def load_evidence(self, filepath):
        with open(filepath) as f:
            self.evidence = json.load(f)

    def add_evidence(self, category, description, value, confidence):
        self.evidence.append({
            "id": len(self.evidence),
            "category": category,
            "description": description,
            "value": value,
            "confidence": confidence,
        })

    def add_hypothesis(self, actor_name, supporting_info=""):
        self.hypotheses[actor_name] = {
            "info": supporting_info,
            "assessments": {},
            "score": 0,
        }

    def evaluate(self, evidence_id, actor_name, assessment):
        """Evaluate evidence against hypothesis: C=consistent, I=inconsistent, N=neutral."""
        weight = self.evidence[evidence_id]["confidence"]
        self.hypotheses[actor_name]["assessments"][evidence_id] = assessment

        if assessment == "C":
            self.hypotheses[actor_name]["score"] += weight
        elif assessment == "I":
            self.hypotheses[actor_name]["score"] -= weight * 2

    def generate_ach_matrix(self):
        matrix = {"evidence": [], "hypotheses": {}}
        for e in self.evidence:
            matrix["evidence"].append({
                "id": e["id"],
                "category": e["category"],
                "description": e["description"],
            })

        for actor, data in self.hypotheses.items():
            matrix["hypotheses"][actor] = {
                "assessments": data["assessments"],
                "score": data["score"],
                "consistent": sum(1 for a in data["assessments"].values() if a == "C"),
                "inconsistent": sum(1 for a in data["assessments"].values() if a == "I"),
                "neutral": sum(1 for a in data["assessments"].values() if a == "N"),
            }

        return matrix

    def rank(self):
        ranked = sorted(
            self.hypotheses.items(), key=lambda x: x[1]["score"], reverse=True
        )
        results = []
        for name, data in ranked:
            incon = sum(1 for a in data["assessments"].values() if a == "I")
            confidence = "HIGH" if data["score"] >= 80 and incon == 0 else \
                        "MODERATE" if data["score"] >= 40 else "LOW"
            results.append({
                "actor": name,
                "score": data["score"],
                "confidence": confidence,
                "inconsistent_count": incon,
            })
        return results


def compare_ttp_similarity(campaign_techs, actor_techs):
    campaign_set = set(campaign_techs)
    actor_set = set(actor_techs)
    common = campaign_set & actor_set

    jaccard = len(common) / len(campaign_set | actor_set) if (campaign_set | actor_set) else 0
    return {
        "common": sorted(common),
        "jaccard_similarity": round(jaccard, 3),
        "campaign_coverage": round(len(common) / len(campaign_set) * 100, 1) if campaign_set else 0,
    }


def main():
    parser = argparse.ArgumentParser(description="Campaign Attribution Analysis")
    parser.add_argument("--evidence", help="Evidence JSON file")
    parser.add_argument("--hypotheses", help="Hypotheses JSON file")
    parser.add_argument("--compare-ttps", action="store_true")
    parser.add_argument("--campaign", help="Campaign techniques JSON")
    parser.add_argument("--actor", help="Actor name for ATT&CK lookup")
    parser.add_argument("--output", default="attribution_report.json")

    args = parser.parse_args()
    engine = AttributionEngine()

    if args.evidence and args.hypotheses:
        engine.load_evidence(args.evidence)
        with open(args.hypotheses) as f:
            hyps = json.load(f)
        for h in hyps:
            engine.add_hypothesis(h["name"], h.get("info", ""))
            for eid, assessment in h.get("evaluations", {}).items():
                engine.evaluate(int(eid), h["name"], assessment)

        matrix = engine.generate_ach_matrix()
        rankings = engine.rank()
        report = {"ach_matrix": matrix, "rankings": rankings}
        print(json.dumps(report, indent=2))

        with open(args.output, "w") as f:
            json.dump(report, f, indent=2)

    elif args.compare_ttps and args.campaign:
        with open(args.campaign) as f:
            campaign_techs = json.load(f)

        if args.actor:
            try:
                from attackcti import attack_client
                lift = attack_client()
                groups = lift.get_groups()
                group = next(
                    (g for g in groups if args.actor.lower() in g.get("name", "").lower()),
                    None,
                )
                if group:
                    gid = group["external_references"][0]["external_id"]
                    techs = lift.get_techniques_used_by_group(gid)
                    actor_techs = [
                        t["external_references"][0]["external_id"]
                        for t in techs if t.get("external_references")
                    ]
                    result = compare_ttp_similarity(campaign_techs, actor_techs)
                    print(json.dumps(result, indent=2))
            except ImportError:
                print("[-] attackcti not installed")


if __name__ == "__main__":
    main()

assets/template.md

IN BUNDLE
# Campaign Attribution Analysis Report Template

## Report Metadata
| Field | Value |
|-------|-------|
| Report ID | CTI-YYYY-NNNN |
| Date | YYYY-MM-DD |
| Classification | TLP:AMBER |
| Analyst | [Name] |
| Confidence | High/Moderate/Low |

## Executive Summary
[Brief overview of key findings and their significance]

## Key Findings
1. [Finding 1 with supporting evidence]
2. [Finding 2 with supporting evidence]
3. [Finding 3 with supporting evidence]

## Detailed Analysis
### Finding 1
- **Evidence**: [Description of evidence]
- **Confidence**: High/Moderate/Low
- **MITRE ATT&CK**: [Relevant technique IDs]
- **Impact Assessment**: [Potential impact to organization]

## Indicators of Compromise
| Type | Value | Context | Confidence |
|------|-------|---------|-----------|
| | | | |

## Recommendations
1. **Immediate**: [Actions requiring immediate attention]
2. **Short-term**: [Actions within 1-2 weeks]
3. **Long-term**: [Strategic improvements]

## References
- [Source 1]
- [Source 2]

LICENSE

IN BUNDLE
                                 Apache License
                           Version 2.0, January 2004
                        http://www.apache.org/licenses/

   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION

   1. Definitions.

      "License" shall mean the terms and conditions for use, reproduction,
      and distribution as defined by Sections 1 through 9 of this document.

      "Licensor" shall mean the copyright owner or entity authorized by
      the copyright owner that is granting the License.

      "Legal Entity" shall mean the union of the acting entity and all
      other entities that control, are controlled by, or are under common
      control with that entity. For the purposes of this definition,
      "control" means (i) the power, direct or indirect, to cause the
      direction or management of such entity, whether by contract or
      otherwise, or (ii) ownership of fifty percent (50%) or more of the
      outstanding shares, or (iii) beneficial ownership of such entity.

      "You" (or "Your") shall mean an individual or Legal Entity
      exercising permissions granted by this License.

      "Source" form shall mean the preferred form for making modifications,
      including but not limited to software source code, documentation
      source, and configuration files.

      "Object" form shall mean any form resulting from mechanical
      transformation or translation of a Source form, including but
      not limited to compiled object code, generated documentation,
      and conversions to other media types.

      "Work" shall mean the work of authorship, whether in Source or
      Object form, made available under the License, as indicated by a
      copyright notice that is included in or attached to the work
      (an example is provided in the Appendix below).

      "Derivative Works" shall mean any work, whether in Source or Object
      form, that is based on (or derived from) the Work and for which the
      editorial revisions, annotations, elaborations, or other modifications
      represent, as a whole, an original work of authorship. For the purposes
      of this License, Derivative Works shall not include works that remain
      separable from, or merely link (or bind by name) to the interfaces of,
      the Work and Derivative Works thereof.

      "Contribution" shall mean any work of authorship, including
      the original version of the Work and any modifications or additions
      to that Work or Derivative Works thereof, that is intentionally
      submitted to the Licensor for inclusion in the Work by the copyright owner
      or by an individual or Legal Entity authorized to submit on behalf of
      the copyright owner. For the purposes of this definition, "submitted"
      means any form of electronic, verbal, or written communication sent
      to the Licensor or its representatives, including but not limited to
      communication on electronic mailing lists, source code control systems,
      and issue tracking systems that are managed by, or on behalf of, the
      Licensor for the purpose of discussing and improving the Work, but
      excluding communication that is conspicuously marked or otherwise
      designated in writing by the copyright owner as "Not a Contribution."

      "Contributor" shall mean Licensor and any individual or Legal Entity
      on behalf of whom a Contribution has been received by the Licensor and
      subsequently incorporated within the Work.

   2. Grant of Copyright License. Subject to the terms and conditions of
      this License, each Contributor hereby grants to You a perpetual,
      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      copyright license to reproduce, prepare Derivative Works of,
      publicly display, publicly perform, sublicense, and distribute the
      Work and such Derivative Works in Source or Object form.

   3. Grant of Patent License. Subject to the terms and conditions of
      this License, each Contributor hereby grants to You a perpetual,
      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      (except as stated in this section) patent license to make, have made,
      use, offer to sell, sell, import, and otherwise transfer the Work,
      where such license applies only to those patent claims licensable
      by such Contributor that are necessarily infringed by their
      Contribution(s) alone or by combination of their Contribution(s)
      with the Work to which such Contribution(s) was submitted. If You
      institute patent litigation against any entity (including a
      cross-claim or counterclaim in a lawsuit) alleging that the Work
      or a Contribution incorporated within the Work constitutes direct
      or contributory patent infringement, then any patent licenses
      granted to You under this License for that Work shall terminate
      as of the date such litigation is filed.

   4. Redistribution. You may reproduce and distribute copies of the
      Work or Derivative Works thereof in any medium, with or without
      modifications, and in Source or Object form, provided that You
      meet the following conditions:

      (a) You must give any other recipients of the Work or
          Derivative Works a copy of this License; and

      (b) You must cause any modified files to carry prominent notices
          stating that You changed the files; and

      (c) You must retain, in the Source form of any Derivative Works
          that You distribute, all copyright, patent, trademark, and
          attribution notices from the Source form of the Work,
          excluding those notices that do not pertain to any part of
          the Derivative Works; and

      (d) If the Work includes a "NOTICE" text file as part of its
          distribution, then any Derivative Works that You distribute must
          include a readable copy of the attribution notices contained
          within such NOTICE file, excluding any notices that do not
          pertain to any part of the Derivative Works, in at least one
          of the following places: within a NOTICE text file distributed
          as part of the Derivative Works; within the Source form or
          documentation, if provided along with the Derivative Works; or,
          within a display generated by the Derivative Works, if and
          wherever such third-party notices normally appear. The contents
          of the NOTICE file are for informational purposes only and
          do not modify the License. You may add Your own attribution
          notices within Derivative Works that You distribute, alongside
          or as an addendum to the NOTICE text from the Work, provided
          that such additional attribution notices cannot be construed
          as modifying the License.

      You may add Your own copyright statement to Your modifications and
      may provide additional or different license terms and conditions
      for use, reproduction, or distribution of Your modifications, or
      for any such Derivative Works as a whole, provided Your use,
      reproduction, and distribution of the Work otherwise complies with
      the conditions stated in this License.

   5. Submission of Contributions. Unless You explicitly state otherwise,
      any Contribution intentionally submitted for inclusion in the Work
      by You to the Licensor shall be under the terms and conditions of
      this License, without any additional terms or conditions.
      Notwithstanding the above, nothing herein shall supersede or modify
      the terms of any separate license agreement you may have executed
      with Licensor regarding such Contributions.

   6. Trademarks. This License does not grant permission to use the trade
      names, trademarks, service marks, or product names of the Licensor,
      except as required for reasonable and customary use in describing the
      origin of the Work and reproducing the content of the NOTICE file.

   7. Disclaimer of Warranty. Unless required by applicable law or
      agreed to in writing, Licensor provides the Work (and each
      Contributor provides its Contributions) on an "AS IS" BASIS,
      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
      implied, including, without limitation, any warranties or conditions
      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
      PARTICULAR PURPOSE. You are solely responsible for determining the
      appropriateness of using or redistributing the Work and assume any
      risks associated with Your exercise of permissions under this License.

   8. Limitation of Liability. In no event and under no legal theory,
      whether in tort (including negligence), contract, or otherwise,
      unless required by applicable law (such as deliberate and grossly
      negligent acts) or agreed to in writing, shall any Contributor be
      liable to You for damages, including any direct, indirect, special,
      incidental, or consequential damages of any character arising as a
      result of this License or out of the use or inability to use the
      Work (including but not limited to damages for loss of goodwill,
      work stoppage, computer failure or malfunction, or any and all
      other commercial damages or losses), even if such Contributor
      has been advised of the possibility of such damages.

   9. Accepting Warranty or Additional Liability. While redistributing
      the Work or Derivative Works thereof, You may choose to offer,
      and charge a fee for, acceptance of support, warranty, indemnity,
      or other liability obligations and/or rights consistent with this
      License. However, in accepting such obligations, You may act only
      on Your own behalf and on Your sole responsibility, not on behalf
      of any other Contributor, and only if You agree to indemnify,
      defend, and hold each Contributor harmless for any liability
      incurred by, or claims asserted against, such Contributor by reason
      of your accepting any such warranty or additional liability.

   END OF TERMS AND CONDITIONS

   APPENDIX: How to apply the Apache License to your work.

      To apply the Apache License to your work, attach the following
      boilerplate notice, with the fields enclosed by brackets "[]"
      replaced with your own identifying information. (Don't include
      the brackets!)  The text should be enclosed in the appropriate
      comment syntax for the file format. Please do not remove or change
      the license header comment from a contributed file except when
      necessary.

   Copyright 2026 mukul975

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.

references/api-reference.md

IN BUNDLE
# API Reference: Campaign Attribution Evidence Analysis

## Diamond Model of Intrusion Analysis

### Four Core Features
| Feature | Description | Attribution Value |
|---------|-------------|-------------------|
| Adversary | Threat actor identity | Direct attribution |
| Capability | Malware, exploits, tools | Indirect - shared tooling |
| Infrastructure | C2, domains, IPs | Strong - operational overlap |
| Victim | Targets, sectors, regions | Contextual - targeting pattern |

### Pivot Analysis
```
Adversary ←→ Capability ←→ Infrastructure ←→ Victim
    ↕              ↕              ↕              ↕
  (HUMINT)     (Malware DB)   (WHOIS/DNS)   (Victimology)
```

## Analysis of Competing Hypotheses (ACH)

### Matrix Format
```
Evidence \ Hypothesis  |  APT28  |  APT29  |  Lazarus  |  Unknown
-----------------------------------------------------------------
Infrastructure overlap  |   ++    |    -    |     -     |    N
TTP consistency        |   ++    |   ++    |     -     |    N
Malware similarity     |    +    |    -    |     -     |    N
Timing (UTC+3)         |   ++    |   ++    |     -     |    N
Language (Russian)     |   ++    |   ++    |     -     |    N
```

### Scoring
| Symbol | Meaning | Weight |
|--------|---------|--------|
| `++` | Strongly consistent | +2 |
| `+` | Consistent | +1 |
| `N` | Neutral | 0 |
| `-` | Inconsistent | -1 |
| `--` | Strongly inconsistent | -2 |

## MITRE ATT&CK Group Queries

### Python (mitreattack-python)
```python
from mitreattack.stix20 import MitreAttackData
attack = MitreAttackData("enterprise-attack.json")
group = attack.get_group_by_alias("APT29")
techniques = attack.get_techniques_used_by_group(group.id)
```

### STIX2 Relationship Query
```python
from stix2 import Filter
relationships = src.query([
    Filter("type", "=", "relationship"),
    Filter("source_ref", "=", group_id),
    Filter("relationship_type", "=", "uses"),
])
```

## Infrastructure Overlap Tools

### PassiveTotal / RiskIQ
```bash
# WHOIS history
curl -u user:key "https://api.passivetotal.org/v2/whois?query=domain.com"

# Passive DNS
curl -u user:key "https://api.passivetotal.org/v2/dns/passive?query=1.2.3.4"
```

### VirusTotal Relations
```bash
curl -H "x-apikey: KEY" \
  "https://www.virustotal.com/api/v3/domains/example.com/communicating_files"
```

## Confidence Assessment Framework

| Level | Score Range | Criteria |
|-------|------------|---------|
| HIGH | 0.8-1.0 | Multiple independent evidence types converge |
| MEDIUM | 0.5-0.8 | Significant evidence with some gaps |
| LOW | 0.2-0.5 | Limited evidence, alternative hypotheses remain |
| NEGLIGIBLE | 0.0-0.2 | Insufficient evidence for attribution |

## STIX Attribution Objects

### Campaign Object
```json
{
  "type": "campaign",
  "name": "Operation DarkShadow",
  "first_seen": "2024-01-15T00:00:00Z",
  "last_seen": "2024-03-20T00:00:00Z",
  "objective": "Espionage targeting defense sector"
}
```

### Attribution Relationship
```json
{
  "type": "relationship",
  "relationship_type": "attributed-to",
  "source_ref": "campaign--abc123",
  "target_ref": "intrusion-set--def456",
  "confidence": 75
}
```

references/standards.md

IN BUNDLE
# Standards and Frameworks Reference

## Applicable Standards
- **STIX 2.1**: Structured Threat Information eXpression for CTI data representation
- **TAXII 2.1**: Transport protocol for sharing CTI over HTTPS
- **MITRE ATT&CK**: Adversary tactics, techniques, and procedures taxonomy
- **Diamond Model**: Intrusion analysis framework (Adversary, Capability, Infrastructure, Victim)
- **Traffic Light Protocol (TLP)**: Information sharing classification (CLEAR, GREEN, AMBER, RED)

## MITRE ATT&CK Relevance
- Technique mapping for threat actor behavior classification
- Data sources for detection capability assessment
- Mitigation strategies linked to specific techniques

## Industry Frameworks
- NIST Cybersecurity Framework (CSF) 2.0 - Identify function
- ISO 27001:2022 - A.5.7 Threat Intelligence
- FIRST Standards - TLP, CSIRT, vulnerability coordination

## References
- [STIX 2.1 Specification](https://docs.oasis-open.org/cti/stix/v2.1/stix-v2.1.html)
- [MITRE ATT&CK](https://attack.mitre.org/)
- [Diamond Model Paper](https://www.activeresponse.org/wp-content/uploads/2013/07/diamond.pdf)
- [NIST CSF 2.0](https://www.nist.gov/cyberframework)

references/workflows.md

IN BUNDLE
# Campaign Attribution Analysis Workflows

## Workflow 1: Collection and Analysis
```
[Intelligence Sources] --> [Data Collection] --> [Analysis] --> [Reporting]
        |                        |                   |               |
        v                        v                   v               v
  OSINT/HUMINT/SIGINT    Normalize/Enrich    Assess/Correlate  Disseminate
```

### Steps:
1. **Planning**: Define intelligence requirements and collection priorities
2. **Collection**: Gather data from relevant sources
3. **Processing**: Normalize data formats and filter noise
4. **Analysis**: Apply analytical frameworks and correlate findings
5. **Production**: Generate intelligence products and reports
6. **Dissemination**: Share with stakeholders via appropriate channels
7. **Feedback**: Collect consumer feedback to refine future collection

## Workflow 2: Continuous Monitoring
```
[Watchlist] --> [Automated Monitoring] --> [Change Detection] --> [Alert/Update]
```

### Steps:
1. **Define Watchlist**: Identify indicators, actors, and topics to monitor
2. **Configure Monitoring**: Set up automated collection from relevant sources
3. **Change Detection**: Identify new or changed intelligence
4. **Assessment**: Evaluate significance of changes
5. **Alerting**: Notify stakeholders of significant intelligence updates
6. **Archive**: Store intelligence for historical analysis and trending

scripts/agent.py

IN BUNDLE
#!/usr/bin/env python3
"""Campaign attribution analysis agent using Diamond Model and ACH methodology.

Evaluates attribution evidence including infrastructure overlaps, TTP consistency,
malware code similarity, timing patterns, and language artifacts.
"""

import json
import re
from collections import defaultdict
from datetime import datetime


DIAMOND_DIMENSIONS = {
    "adversary": "Threat actor identity, group attribution",
    "capability": "Malware, exploits, tools used",
    "infrastructure": "C2 servers, domains, IP addresses",
    "victim": "Targeted sectors, regions, organizations",
}

EVIDENCE_WEIGHTS = {
    "infrastructure_overlap": 0.25,
    "ttp_consistency": 0.30,
    "malware_code_similarity": 0.25,
    "timing_pattern": 0.10,
    "language_artifact": 0.10,
}

CONFIDENCE_LEVELS = {
    (0.8, 1.0): "HIGH - Strong attribution confidence",
    (0.5, 0.8): "MEDIUM - Moderate attribution, further analysis recommended",
    (0.2, 0.5): "LOW - Weak attribution, insufficient evidence",
    (0.0, 0.2): "NEGLIGIBLE - No meaningful attribution possible",
}


def diamond_model_analysis(adversary=None, capability=None, infrastructure=None, victim=None):
    """Structure evidence using the Diamond Model of Intrusion Analysis."""
    model = {
        "adversary": {
            "identified": adversary is not None,
            "details": adversary or "Unknown",
        },
        "capability": {
            "tools": capability.get("tools", []) if capability else [],
            "exploits": capability.get("exploits", []) if capability else [],
            "malware": capability.get("malware", []) if capability else [],
        },
        "infrastructure": {
            "c2_servers": infrastructure.get("c2", []) if infrastructure else [],
            "domains": infrastructure.get("domains", []) if infrastructure else [],
            "ip_addresses": infrastructure.get("ips", []) if infrastructure else [],
        },
        "victim": {
            "sectors": victim.get("sectors", []) if victim else [],
            "regions": victim.get("regions", []) if victim else [],
        },
        "pivot_opportunities": [],
    }
    if infrastructure and infrastructure.get("c2"):
        model["pivot_opportunities"].append("Pivot from C2 infrastructure to related campaigns")
    if capability and capability.get("malware"):
        model["pivot_opportunities"].append("Pivot from malware samples to shared infrastructure")
    return model


def evaluate_infrastructure_overlap(campaign_infra, known_actor_infra):
    """Score infrastructure overlap between campaign and known actor."""
    campaign_set = set(campaign_infra)
    known_set = set(known_actor_infra)
    if not campaign_set or not known_set:
        return 0.0, []
    overlap = campaign_set & known_set
    score = len(overlap) / max(len(campaign_set), len(known_set))
    return round(score, 4), sorted(overlap)


def evaluate_ttp_consistency(campaign_ttps, actor_ttps):
    """Score TTP consistency using MITRE ATT&CK technique overlap."""
    campaign_set = set(campaign_ttps)
    actor_set = set(actor_ttps)
    if not campaign_set or not actor_set:
        return 0.0, []
    overlap = campaign_set & actor_set
    jaccard = len(overlap) / len(campaign_set | actor_set)
    return round(jaccard, 4), sorted(overlap)


def evaluate_malware_similarity(sample_features, known_features):
    """Score malware code similarity based on feature comparison."""
    if not sample_features or not known_features:
        return 0.0
    matches = 0
    total = max(len(sample_features), len(known_features))
    for feature in sample_features:
        if feature in known_features:
            matches += 1
    return round(matches / total, 4) if total > 0 else 0.0


def evaluate_timing_pattern(campaign_timestamps, actor_timezone_offset=None):
    """Analyze operational timing to infer timezone/working hours."""
    if not campaign_timestamps:
        return {"score": 0.0, "working_hours": None, "timezone_guess": None}
    hours = []
    for ts in campaign_timestamps:
        try:
            if isinstance(ts, str):
                dt = datetime.fromisoformat(ts.replace("Z", "+00:00"))
            else:
                dt = ts
            adjusted = dt.hour + (actor_timezone_offset or 0)
            hours.append(adjusted % 24)
        except (ValueError, TypeError):
            continue
    if not hours:
        return {"score": 0.0}
    work_hours = sum(1 for h in hours if 8 <= h <= 18)
    work_ratio = work_hours / len(hours)
    avg_hour = sum(hours) / len(hours)
    return {
        "score": round(work_ratio, 4),
        "average_hour_utc": round(avg_hour, 1),
        "work_hour_ratio": round(work_ratio, 4),
        "sample_size": len(hours),
    }


def evaluate_language_artifacts(strings_list):
    """Detect language artifacts in malware strings or documents."""
    language_indicators = {
        "Russian": [r"[а-яА-Я]{3,}", r"codepage.*1251", r"locale.*ru"],
        "Chinese": [r"[\u4e00-\u9fff]{2,}", r"codepage.*936", r"GB2312"],
        "Korean": [r"[\uac00-\ud7af]{2,}", r"codepage.*949", r"EUC-KR"],
        "Farsi": [r"[\u0600-\u06ff]{3,}", r"codepage.*1256"],
        "English": [r"\b(the|and|for|with)\b"],
    }
    detections = defaultdict(int)
    for s in strings_list:
        for lang, patterns in language_indicators.items():
            for pattern in patterns:
                if re.search(pattern, s, re.IGNORECASE):
                    detections[lang] += 1
    total = sum(detections.values()) or 1
    scored = {lang: round(count / total, 4) for lang, count in detections.items()}
    return scored


def ach_analysis(hypotheses, evidence_items):
    """Analysis of Competing Hypotheses (ACH) for attribution."""
    matrix = {}
    for hyp in hypotheses:
        hyp_name = hyp["name"]
        matrix[hyp_name] = {"consistent": 0, "inconsistent": 0, "neutral": 0, "score": 0}
        for evidence in evidence_items:
            ev_name = evidence["name"]
            consistency = evidence.get("hypotheses", {}).get(hyp_name, "neutral")
            if consistency == "consistent":
                matrix[hyp_name]["consistent"] += evidence.get("weight", 1)
            elif consistency == "inconsistent":
                matrix[hyp_name]["inconsistent"] += evidence.get("weight", 1)
            else:
                matrix[hyp_name]["neutral"] += evidence.get("weight", 1)
        c = matrix[hyp_name]["consistent"]
        i = matrix[hyp_name]["inconsistent"]
        matrix[hyp_name]["score"] = round((c - i) / (c + i + 0.01), 4)
    return matrix


def compute_attribution_score(scores):
    """Compute weighted attribution confidence score."""
    total = 0.0
    for evidence_type, weight in EVIDENCE_WEIGHTS.items():
        score = scores.get(evidence_type, 0.0)
        total += score * weight
    confidence = "UNKNOWN"
    for (low, high), label in CONFIDENCE_LEVELS.items():
        if low <= total < high:
            confidence = label
            break
    return round(total, 4), confidence


def generate_attribution_report(campaign_name, candidate_actor, evidence):
    """Generate structured attribution assessment report."""
    scores = {}
    details = {}

    infra_score, infra_overlap = evaluate_infrastructure_overlap(
        evidence.get("campaign_infra", []), evidence.get("actor_infra", []))
    scores["infrastructure_overlap"] = infra_score
    details["infrastructure_overlap"] = infra_overlap

    ttp_score, ttp_overlap = evaluate_ttp_consistency(
        evidence.get("campaign_ttps", []), evidence.get("actor_ttps", []))
    scores["ttp_consistency"] = ttp_score
    details["ttp_consistency"] = ttp_overlap

    malware_score = evaluate_malware_similarity(
        evidence.get("sample_features", []), evidence.get("known_features", []))
    scores["malware_code_similarity"] = malware_score

    timing = evaluate_timing_pattern(
        evidence.get("timestamps", []), evidence.get("tz_offset"))
    scores["timing_pattern"] = timing.get("score", 0.0)
    details["timing"] = timing

    lang = evaluate_language_artifacts(evidence.get("strings", []))
    scores["language_artifact"] = max(lang.values()) if lang else 0.0
    details["language_artifacts"] = lang

    total_score, confidence = compute_attribution_score(scores)

    return {
        "campaign": campaign_name,
        "candidate_actor": candidate_actor,
        "attribution_score": total_score,
        "confidence_level": confidence,
        "evidence_scores": scores,
        "evidence_details": details,
    }


if __name__ == "__main__":
    print("=" * 60)
    print("Campaign Attribution Evidence Analysis Agent")
    print("Diamond Model, ACH, TTP/infrastructure/malware scoring")
    print("=" * 60)

    demo_evidence = {
        "campaign_infra": ["185.220.101.1", "evil-domain.com", "c2.attacker.net"],
        "actor_infra": ["185.220.101.1", "c2.attacker.net", "other-domain.org"],
        "campaign_ttps": ["T1566.001", "T1059.001", "T1053.005", "T1071.001", "T1041"],
        "actor_ttps": ["T1566.001", "T1059.001", "T1053.005", "T1071.001", "T1021.001", "T1003.001"],
        "sample_features": ["xor_0x55", "mutex_Global\\QWE", "ua_Mozilla5", "rc4_key"],
        "known_features": ["xor_0x55", "mutex_Global\\QWE", "ua_Mozilla5", "aes_cbc"],
        "timestamps": ["2024-03-15T06:30:00Z", "2024-03-15T07:15:00Z",
                        "2024-03-16T08:00:00Z", "2024-03-16T09:45:00Z"],
        "tz_offset": 3,
        "strings": ["Привет мир", "connect to server", "upload file"],
    }

    report = generate_attribution_report("Operation DarkShadow", "APT29", demo_evidence)

    print(f"\n[*] Campaign: {report['campaign']}")
    print(f"[*] Candidate: {report['candidate_actor']}")
    print(f"[*] Attribution Score: {report['attribution_score']}")
    print(f"[*] Confidence: {report['confidence_level']}")
    print("\n--- Evidence Scores ---")
    for ev, score in report["evidence_scores"].items():
        weight = EVIDENCE_WEIGHTS.get(ev, 0)
        print(f"  {ev:30s} score={score:.4f}  weight={weight}")
    print(f"\n[*] Full report:\n{json.dumps(report, indent=2, default=str)}")

scripts/process.py

IN BUNDLE
#!/usr/bin/env python3
"""
Campaign Attribution Evidence Analysis Script

Implements structured attribution analysis:
- Analysis of Competing Hypotheses (ACH) matrix
- Infrastructure overlap scoring
- TTP similarity comparison using ATT&CK
- Evidence weighting and confidence assessment

Requirements:
    pip install attackcti stix2 requests

Usage:
    python process.py --evidence evidence.json --hypotheses actors.json --output report.json
    python process.py --compare-ttps --campaign campaign_techs.json --actor APT29
"""

import argparse
import json
import sys
from collections import defaultdict


class AttributionEngine:
    """Structured attribution analysis using ACH methodology."""

    def __init__(self):
        self.evidence = []
        self.hypotheses = {}

    def load_evidence(self, filepath):
        with open(filepath) as f:
            self.evidence = json.load(f)

    def add_evidence(self, category, description, value, confidence):
        self.evidence.append({
            "id": len(self.evidence),
            "category": category,
            "description": description,
            "value": value,
            "confidence": confidence,
        })

    def add_hypothesis(self, actor_name, supporting_info=""):
        self.hypotheses[actor_name] = {
            "info": supporting_info,
            "assessments": {},
            "score": 0,
        }

    def evaluate(self, evidence_id, actor_name, assessment):
        """Evaluate evidence against hypothesis: C=consistent, I=inconsistent, N=neutral."""
        weight = self.evidence[evidence_id]["confidence"]
        self.hypotheses[actor_name]["assessments"][evidence_id] = assessment

        if assessment == "C":
            self.hypotheses[actor_name]["score"] += weight
        elif assessment == "I":
            self.hypotheses[actor_name]["score"] -= weight * 2

    def generate_ach_matrix(self):
        matrix = {"evidence": [], "hypotheses": {}}
        for e in self.evidence:
            matrix["evidence"].append({
                "id": e["id"],
                "category": e["category"],
                "description": e["description"],
            })

        for actor, data in self.hypotheses.items():
            matrix["hypotheses"][actor] = {
                "assessments": data["assessments"],
                "score": data["score"],
                "consistent": sum(1 for a in data["assessments"].values() if a == "C"),
                "inconsistent": sum(1 for a in data["assessments"].values() if a == "I"),
                "neutral": sum(1 for a in data["assessments"].values() if a == "N"),
            }

        return matrix

    def rank(self):
        ranked = sorted(
            self.hypotheses.items(), key=lambda x: x[1]["score"], reverse=True
        )
        results = []
        for name, data in ranked:
            incon = sum(1 for a in data["assessments"].values() if a == "I")
            confidence = "HIGH" if data["score"] >= 80 and incon == 0 else \
                        "MODERATE" if data["score"] >= 40 else "LOW"
            results.append({
                "actor": name,
                "score": data["score"],
                "confidence": confidence,
                "inconsistent_count": incon,
            })
        return results


def compare_ttp_similarity(campaign_techs, actor_techs):
    campaign_set = set(campaign_techs)
    actor_set = set(actor_techs)
    common = campaign_set & actor_set

    jaccard = len(common) / len(campaign_set | actor_set) if (campaign_set | actor_set) else 0
    return {
        "common": sorted(common),
        "jaccard_similarity": round(jaccard, 3),
        "campaign_coverage": round(len(common) / len(campaign_set) * 100, 1) if campaign_set else 0,
    }


def main():
    parser = argparse.ArgumentParser(description="Campaign Attribution Analysis")
    parser.add_argument("--evidence", help="Evidence JSON file")
    parser.add_argument("--hypotheses", help="Hypotheses JSON file")
    parser.add_argument("--compare-ttps", action="store_true")
    parser.add_argument("--campaign", help="Campaign techniques JSON")
    parser.add_argument("--actor", help="Actor name for ATT&CK lookup")
    parser.add_argument("--output", default="attribution_report.json")

    args = parser.parse_args()
    engine = AttributionEngine()

    if args.evidence and args.hypotheses:
        engine.load_evidence(args.evidence)
        with open(args.hypotheses) as f:
            hyps = json.load(f)
        for h in hyps:
            engine.add_hypothesis(h["name"], h.get("info", ""))
            for eid, assessment in h.get("evaluations", {}).items():
                engine.evaluate(int(eid), h["name"], assessment)

        matrix = engine.generate_ach_matrix()
        rankings = engine.rank()
        report = {"ach_matrix": matrix, "rankings": rankings}
        print(json.dumps(report, indent=2))

        with open(args.output, "w") as f:
            json.dump(report, f, indent=2)

    elif args.compare_ttps and args.campaign:
        with open(args.campaign) as f:
            campaign_techs = json.load(f)

        if args.actor:
            try:
                from attackcti import attack_client
                lift = attack_client()
                groups = lift.get_groups()
                group = next(
                    (g for g in groups if args.actor.lower() in g.get("name", "").lower()),
                    None,
                )
                if group:
                    gid = group["external_references"][0]["external_id"]
                    techs = lift.get_techniques_used_by_group(gid)
                    actor_techs = [
                        t["external_references"][0]["external_id"]
                        for t in techs if t.get("external_references")
                    ]
                    result = compare_ttp_similarity(campaign_techs, actor_techs)
                    print(json.dumps(result, indent=2))
            except ImportError:
                print("[-] attackcti not installed")


if __name__ == "__main__":
    main()
SKILL GRID · 上传 ZIP 或 GitHub 链接,把技能变成一张可分享的卡 ■■□■ GOOGLE 四色 · PIXEL DECK