Production hardening: security fixes, code quality, 724 skills complete

- Fix 25 shell=True subprocess calls with list-based commands
- Fix 49 verify=False in defensive skills (env-var override)
- Add timeout to 231 HTTP/subprocess/socket calls
- Fix 6 SQL injection patterns with whitelist validation
- Replace 8 __import__() with standard imports
- Remove 701 unused imports across 442 files
- Add authorized-testing disclaimers to all offensive skills
- Complete 11 incomplete skill directories
- Expand 10 stub SKILL.md files with full content
- Fix 2 YAML parse errors in frontmatter
- Fix 5 pre-existing syntax errors
- Convert 22 hardcoded paths/ports to environment variables
- Back up 21 redundant skill pairs to .bak
- Fix 2 global declaration errors
- 724/724 skills with full folder anatomy (SKILL.md + agent.py + api-reference.md + LICENSE)
- 0 compile errors across all 724 agent.py files
This commit is contained in:
mukul975
2026-03-19 13:26:49 +01:00
parent 63b442d347
commit c47eed6a64
900 changed files with 23085 additions and 2720 deletions
@@ -0,0 +1,201 @@
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.
@@ -0,0 +1,132 @@
---
name: executing-diamond-model-analysis
description: >
Applies the Diamond Model of Intrusion Analysis to structure adversary activity into its four
core vertices (adversary, capability, infrastructure, victim) and identifies relationships between
them to pivot investigations and attribute campaigns. Use when analyzing a completed intrusion,
linking disparate incidents to a common threat actor, or building structured analytic products
for threat intelligence dissemination. Activates for requests involving Diamond Model, intrusion
analysis, campaign clustering, or adversary attribution methodology.
domain: cybersecurity
subdomain: threat-intelligence
tags: [Diamond-Model, intrusion-analysis, attribution, campaign-clustering, CTI, MITRE-ATT&CK]
version: 1.0.0
author: team-cybersecurity
license: Apache-2.0
---
# Executing Diamond Model Analysis
## When to Use
Use this skill when:
- Analyzing a confirmed intrusion to understand the complete adversary-capability-infrastructure-victim relationship
- Attempting to link two or more incidents to a common threat actor using shared infrastructure or capability indicators
- Structuring a finished intelligence product that explains adversary behavior in a formal analytic framework
**Do not use** this skill during active incident containment — Diamond Model analysis is a post-event or concurrent intelligence activity, not a response procedure.
## Prerequisites
- Completed incident investigation data: logs, forensic artifacts, malware samples, network captures
- Access to MITRE ATT&CK, VirusTotal, Shodan, and passive DNS databases for vertex enrichment
- Link analysis platform (Maltego, Analyst's Notebook, or graph database like Neo4j) for multi-event correlation
- Familiarity with the original Diamond Model paper: Caltagirone, Pendergast, Betz (2013)
## Workflow
### Step 1: Populate the Four Core Vertices
**Adversary Vertex**: Who conducted the activity?
- Operator (direct keyboard access) vs. Customer (who commissioned the attack) distinction
- Attribution confidence level (Low/Medium/High) with supporting evidence
- Known aliases, ATT&CK Group ID, sector targeting history
**Capability Vertex**: What tools and techniques were used?
- Malware families: names, YARA signatures, behavioral characteristics
- Exploits: CVEs exploited, exploit kit identifiers
- ATT&CK techniques employed (T-numbers)
- Capability sophistication: commodity (off-shelf) vs. custom-developed
**Infrastructure Vertex**: What systems were used to conduct the attack?
- C2 servers: IPs, domains, hosting providers, certificate fingerprints
- Delivery infrastructure: phishing domains, watering holes, compromised servers
- Operational relay boxes (ORBs): intermediate proxies obscuring true origin
**Victim Vertex**: Who/what was targeted?
- Organization profile: sector, size, geography, technology stack
- Personae: specific individuals targeted (CISO, finance team, executives)
- Assets targeted: intellectual property, financial systems, OT/ICS
### Step 2: Identify Vertex Relationships (Edges)
Document relationships between vertices:
- Adversary → uses → Capability (malware development/deployment relationship)
- Adversary → uses → Infrastructure (operational relationship)
- Infrastructure → delivers → Capability (technical delivery mechanism)
- Capability → targets → Victim (attack surface relationship)
- Infrastructure → attacks → Victim (direct connection)
Each edge should be supported by at least two independent data points (evidence-backed, not inferred).
### Step 3: Apply Meta-Features for Enrichment
Meta-features provide additional context beyond the four vertices:
**Timestamp**: When did each phase of the intrusion occur? Map to cyber kill chain phases.
**Phase**: Which kill chain phase does this activity represent?
- Reconnaissance → Weaponization → Delivery → Exploitation → Installation → C2 → Actions on Objectives
**Direction**: Attack direction (external-to-internal, internal-to-external for exfiltration)
**Result**: Outcome of each adversary action (success/failure/partial)
**Resources**: Adversary resources invested (time, money, infrastructure cost, zero-day usage)
### Step 4: Cluster Events Using Vertex Pivoting
Apply Diamond Model pivoting logic to cluster related incidents:
- **Infrastructure pivot**: Same C2 IP across multiple incidents → same or related adversary
- **Capability pivot**: Same malware hash or YARA signature → same tool developer
- **Adversary pivot**: Same victimology pattern (sector + geography + asset type) → same targeting criteria
- **Victim pivot**: Same victim across multiple incidents → sustained campaign against organization
```
Incident A: IP 185.220.101.x, domain evil-redir[.]com, SUNBURST malware variant
Incident B: IP 185.220.101.y (same /24), domain redir-evil[.]com, modified SUNBURST
→ Infrastructure cluster (same /24 block) + Capability cluster (same malware family) = High confidence same actor
```
### Step 5: Produce Structured Analytic Output
Document analysis in structured format:
- Diamond event diagram for each discrete intrusion event
- Activity thread connecting multiple events across time
- Activity group (cluster) with confidence assessment
- Competing hypotheses analysis: alternative attribution explanations with evidence weighting (ACH methodology)
## Key Concepts
| Term | Definition |
|------|-----------|
| **Diamond Model** | Intrusion analysis framework with four vertices (adversary, capability, infrastructure, victim) connected by edges representing relationships |
| **Activity Thread** | A time-ordered sequence of Diamond events representing a single adversary operation |
| **Activity Group** | A cluster of Diamond events linked by shared vertex properties, suggesting a common adversary |
| **Adversary Operator vs. Customer** | Diamond Model distinction: operator has keyboard access; customer directs/funds the operation |
| **Pivoting** | Using a known vertex value to discover additional related events or infrastructure (e.g., one IP revealing 20 more C2 domains) |
| **ACH** | Analysis of Competing Hypotheses — structured analytic technique for evaluating evidence against multiple attribution hypotheses |
## Tools & Systems
- **Maltego**: Graph-based link analysis ideal for visualizing Diamond vertex relationships and infrastructure pivots
- **Neo4j**: Graph database for storing and querying complex Diamond event clusters at scale; supports Cypher query language
- **MISP**: Diamond Model meta-feature tagging supported via MISP galaxies and correlation engine
- **Analyst's Notebook (IBM i2)**: Law enforcement/intelligence-grade link analysis for adversary relationship mapping
## Common Pitfalls
- **Conflating operator and customer**: Not distinguishing between who conducted the attack and who directed it leads to incorrect attribution targeting.
- **Infrastructure re-use assumption**: Bulletproof hosting providers sell the same IP blocks to multiple criminal groups. Shared IP ≠ same actor without additional corroboration.
- **Analysis without confidence levels**: Diamond Model conclusions presented without confidence qualifiers appear more certain than the evidence supports.
- **Ignoring the victim vertex**: Analysis often over-focuses on adversary/capability and neglects victim characterization, which provides crucial context for predicting future targeting.
- **Static diagrams**: Diamond events should be time-stamped and evolve as new evidence emerges. Static diagrams without version history mask analytic evolution.
@@ -0,0 +1,73 @@
# API Reference: Diamond Model Analysis Agent
## Dependencies
| Library | Version | Purpose |
|---------|---------|---------|
| Python stdlib | 3.8+ | json, dataclasses, hashlib, argparse |
## CLI Usage
```bash
python scripts/agent.py \
--input events.json \
--output diamond_report.json \
--pivot-type infrastructure \
--pivot-value "185.220.101.42"
```
## Input Format
```json
[
{
"event_id": "EVT-001",
"timestamp": "2025-01-15T14:30:00Z",
"adversary": ["APT29"],
"adversary_confidence": "high",
"capabilities": ["SUNBURST", "T1071.001"],
"infrastructure": ["185.220.101.42", "evil-redir.com"],
"victims": ["TargetCorp"],
"phase": "C2",
"result": "success"
}
]
```
## Functions
### `create_event(event_data) -> DiamondEvent`
Constructs a `DiamondEvent` dataclass from raw dict. Auto-generates `event_id` via MD5 if not provided.
### `pivot_on_vertex(events, vertex_type, value) -> list`
Returns events sharing a specified vertex value. Supports pivoting on `adversary`, `capability`, `infrastructure`, `victim`.
### `cluster_events(events) -> dict`
Groups events by shared infrastructure or capability values. Returns clusters with overlapping event IDs.
### `build_activity_thread(events) -> list`
Sorts events chronologically and assigns sequence numbers for timeline reconstruction.
### `generate_report(events) -> dict`
Produces the full Diamond Model report with unique entities, activity thread, and clusters.
## Data Classes
### `Vertex`
Fields: `vertex_type` (str), `values` (list), `confidence` (str), `notes` (str)
### `DiamondEvent`
Fields: `event_id`, `timestamp`, `adversary` (Vertex), `capability` (Vertex), `infrastructure` (Vertex), `victim` (Vertex), `phase`, `direction`, `result`
## Output Schema
```json
{
"report_date": "ISO-8601",
"total_events": 5,
"unique_adversaries": ["APT29"],
"unique_infrastructure": ["185.220.101.42"],
"activity_thread": [{"sequence": 1, "event_id": "EVT-001", ...}],
"clusters": {"clusters": [...], "total_events": 5}
}
```
@@ -0,0 +1,175 @@
#!/usr/bin/env python3
# For authorized penetration testing and educational environments only.
# Usage against targets without prior mutual consent is illegal.
# It is the end user's responsibility to obey all applicable local, state and federal laws.
"""Diamond Model intrusion analysis agent for structuring adversary activity."""
import argparse
import json
import hashlib
import logging
from datetime import datetime
from dataclasses import dataclass, field
from typing import List
logging.basicConfig(level=logging.INFO, format="%(asctime)s [%(levelname)s] %(message)s")
logger = logging.getLogger(__name__)
@dataclass
class Vertex:
vertex_type: str
values: List[str] = field(default_factory=list)
confidence: str = "medium"
notes: str = ""
@dataclass
class DiamondEvent:
event_id: str
timestamp: str
adversary: Vertex
capability: Vertex
infrastructure: Vertex
victim: Vertex
phase: str = ""
direction: str = "external-to-internal"
result: str = "success"
meta_notes: str = ""
def create_event(event_data: dict) -> DiamondEvent:
"""Build a DiamondEvent from a raw dict of incident data."""
return DiamondEvent(
event_id=event_data.get("event_id", hashlib.md5(
json.dumps(event_data, sort_keys=True).encode()
).hexdigest()[:8]),
timestamp=event_data.get("timestamp", datetime.utcnow().isoformat()),
adversary=Vertex(
vertex_type="adversary",
values=event_data.get("adversary", []),
confidence=event_data.get("adversary_confidence", "medium"),
),
capability=Vertex(
vertex_type="capability",
values=event_data.get("capabilities", []),
),
infrastructure=Vertex(
vertex_type="infrastructure",
values=event_data.get("infrastructure", []),
),
victim=Vertex(
vertex_type="victim",
values=event_data.get("victims", []),
),
phase=event_data.get("phase", ""),
direction=event_data.get("direction", "external-to-internal"),
result=event_data.get("result", "success"),
)
def pivot_on_vertex(events: List[DiamondEvent], vertex_type: str, value: str) -> List[DiamondEvent]:
"""Pivot across events sharing a common vertex value."""
matches = []
for event in events:
vertex = getattr(event, vertex_type, None)
if vertex and value in vertex.values:
matches.append(event)
logger.info("Pivot on %s='%s' returned %d events", vertex_type, value, len(matches))
return matches
def cluster_events(events: List[DiamondEvent]) -> dict:
"""Cluster events by shared infrastructure and capability vertices."""
infra_map = {}
cap_map = {}
for event in events:
for val in event.infrastructure.values:
infra_map.setdefault(val, []).append(event.event_id)
for val in event.capability.values:
cap_map.setdefault(val, []).append(event.event_id)
clusters = []
for key, eids in infra_map.items():
if len(eids) > 1:
clusters.append({"pivot": "infrastructure", "value": key, "event_ids": eids})
for key, eids in cap_map.items():
if len(eids) > 1:
clusters.append({"pivot": "capability", "value": key, "event_ids": eids})
return {"clusters": clusters, "total_events": len(events)}
def build_activity_thread(events: List[DiamondEvent]) -> List[dict]:
"""Order events into a time-sorted activity thread."""
sorted_events = sorted(events, key=lambda e: e.timestamp)
thread = []
for idx, event in enumerate(sorted_events):
thread.append({
"sequence": idx + 1,
"event_id": event.event_id,
"timestamp": event.timestamp,
"phase": event.phase,
"adversary": event.adversary.values,
"capability": event.capability.values,
"infrastructure": event.infrastructure.values,
"victim": event.victim.values,
"result": event.result,
})
return thread
def generate_report(events: List[DiamondEvent]) -> dict:
"""Generate a complete Diamond Model analysis report."""
clusters = cluster_events(events)
thread = build_activity_thread(events)
all_adversaries = set()
all_infra = set()
all_caps = set()
for e in events:
all_adversaries.update(e.adversary.values)
all_infra.update(e.infrastructure.values)
all_caps.update(e.capability.values)
return {
"report_date": datetime.utcnow().isoformat(),
"total_events": len(events),
"unique_adversaries": sorted(all_adversaries),
"unique_infrastructure": sorted(all_infra),
"unique_capabilities": sorted(all_caps),
"activity_thread": thread,
"clusters": clusters,
}
def load_events_from_file(filepath: str) -> List[DiamondEvent]:
"""Load raw event data from a JSON file."""
with open(filepath) as f:
raw = json.load(f)
events_data = raw if isinstance(raw, list) else raw.get("events", [])
return [create_event(e) for e in events_data]
def main():
parser = argparse.ArgumentParser(description="Diamond Model Analysis Agent")
parser.add_argument("--input", required=True, help="JSON file with raw event data")
parser.add_argument("--output", default="diamond_report.json", help="Output report path")
parser.add_argument("--pivot-type", choices=["adversary", "capability", "infrastructure", "victim"])
parser.add_argument("--pivot-value", help="Value to pivot on")
args = parser.parse_args()
events = load_events_from_file(args.input)
logger.info("Loaded %d Diamond events", len(events))
if args.pivot_type and args.pivot_value:
events = pivot_on_vertex(events, args.pivot_type, args.pivot_value)
report = generate_report(events)
with open(args.output, "w") as f:
json.dump(report, f, indent=2, default=str)
logger.info("Diamond Model report saved to %s", args.output)
print(json.dumps(report, indent=2, default=str))
if __name__ == "__main__":
main()