anthropic-cybersecurity-skills
817 structured cybersecurity skills for AI agents · Mapped to 6 frameworks: MITRE ATT&CK, NIST CSF 2.0, MITRE ATLAS, D3FEND, NIST AI RMF & MITRE F3 (Fight Fraud) · agentskills.io standard · Works with Claude Code, GitHub Copilot, Codex CLI, Cursor, Gemini CLI & 20+ platforms · 29 security domains · Apache 2.0
Safety scan
A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.
Check it deeper on your machine
Its scripts were only partly scanned.
As a Claude Code plugin, install it and then ask Claude Code:
/plugin marketplace add keithmackay/mackayi/plugin install scanskillsafety@mackayiDo a deep scan of https://github.com/mukul975/anthropic-cybersecurity-skills with scanskillsafety
Or from a terminal, clone it and run it:
git clone https://github.com/keithmackay/scanskillsafety-skill ~/.claude/skills/scanskillsafetynode ~/.claude/skills/scanskillsafety/cli.cjs --deep 'https://github.com/mukul975/anthropic-cybersecurity-skills'
It checks the exact commit: every file, its packages against OSV (api.osv.dev), how it compares with this page's scan (findsafeskills.com receives the repository's address), and, if you agree, Claude reading every file with your own Claude subscription. It never runs the code.
Badge for your README
Markdown
[](/listings/mukul975--anthropic-cybersecurity-skills)HTML
<a href="/listings/mukul975--anthropic-cybersecurity-skills"><img src="/api/listings/mukul975--anthropic-cybersecurity-skills/badge.svg" alt="findsafeskills safety rating" /></a>Install
Install instructions from the README
As written by the repo's author. findsafeskills has not verified these steps.
# Option 1: npx (recommended) npx skills add mukul975/Anthropic-Cybersecurity-Skills # Option 2: Git clone git clone https://github.com/mukul975/Anthropic-Cybersecurity-Skills.git cd Anthropic-Cybersecurity-Skills
Works immediately with Claude Code, GitHub Copilot, OpenAI Codex CLI, Cursor, Gemini CLI, and any [agentskills.io](https://agentskills.io)-compatible platform.
What was scanned
The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.
.claude-plugin/marketplace.json · Manifest · 37 lines
View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)
- {
- "name": "anthropic-cybersecurity-skills",
- "owner": {
- "name": "mukul975",
- "email": "mukuljangra5@gmail.com"
- },
- "metadata": {
- "description": "818 cybersecurity skills for AI agents mapped to 6 frameworks: MITRE ATT&CK, NIST CSF 2.0, MITRE ATLAS, D3FEND, NIST AI RMF, and the MITRE Fight Fraud Framework (F3).",
- "version": "1.3.0"
- },
- "plugins": [
- {
- "name": "cybersecurity-skills",
- "source": "./",
- "description": "818 cybersecurity skills covering web security, pentesting, DFIR, threat intelligence, cloud security, malware analysis, and more. Mapped to 6 frameworks.",
- "version": "1.3.0",
- "author": {
- "name": "mukul975"
- },
- "license": "Apache-2.0",
- "keywords": [
- "cybersecurity",
- "pentesting",
- "forensics",
- "threat-intelligence",
- "cloud-security",
- "malware-analysis",
- "incident-response",
- "zero-trust",
- "devsecops"
- ],
- "category": "security",
- "homepage": "https://github.com/mukul975/Anthropic-Cybersecurity-Skills",
- "repository": "https://github.com/mukul975/Anthropic-Cybersecurity-Skills"
- }
- ]
- }
README.md · README · 465 lines
View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)
- <p align="center">
- <img src="assets/banner.png" alt="Anthropic Cybersecurity Skills" width="100%">
- </p>
- <div align="center">
- # Anthropic Cybersecurity Skills
- ### The largest open-source cybersecurity skills library for AI agents
- [](https://mahipal.engineer/survey?utm_source=github_badge&utm_medium=readme&utm_campaign=gars2026)
- [](LICENSE)
- [](#whats-inside--34-security-domains)
- [](#six-frameworks-one-skill-library)
- [](https://ctid.mitre.org/fraud/)
- [](#whats-inside--34-security-domains)
- [](#compatible-platforms)
- [](https://github.com/mukul975/Anthropic-Cybersecurity-Skills/stargazers)
- [](https://github.com/mukul975/Anthropic-Cybersecurity-Skills/network/members)
- [](https://github.com/mukul975/Anthropic-Cybersecurity-Skills/commits/main)
- [](https://agentskills.io)
- [](CONTRIBUTING.md)
- [](https://casky.ai/?utm_source=github&utm_medium=readme&utm_campaign=cohort_launch#waitlist)
- [](https://github.com/NousResearch/hermes-agent)
- **818 production-grade cybersecurity skills · 34 security domains · 6 framework mappings · 26+ AI platforms**
- [Get Started](#quick-start) · [What's Inside](#whats-inside--34-security-domains) · [Frameworks](#six-frameworks-one-skill-library) · [Platforms](#compatible-platforms) · [Contributing](#contributing)
- </div>
- ---
- > ⚠️ **Community Project** — This is an independent, community-created project. Not affiliated with Anthropic PBC.
- >
- > 🔐 **Authorized & lawful use only.** This library includes offensive and dual-use techniques (e.g. red-team C2, phishing simulation, exploitation) intended for **authorized penetration testing, security research, defense, and education**. Only use them against systems you own or have **explicit written permission** to test, and comply with all applicable laws and rules of engagement. You are solely responsible for how you use these skills. See [SECURITY.md](SECURITY.md) and [CODE_OF_CONDUCT.md](CODE_OF_CONDUCT.md).
- ## Give any AI agent the security skills of a senior analyst
- A junior analyst knows which Volatility3 plugin to run on a suspicious memory dump, which Sigma rules catch Kerberoasting, and how to scope a cloud breach across three providers. **Your AI agent doesn't — unless you give it these skills.**
- This repo contains **818 structured cybersecurity skills** spanning **34 security domains**, each following the [agentskills.io](https://agentskills.io) open standard. The library maps across **six industry frameworks** — MITRE ATT&CK, NIST CSF 2.0, MITRE ATLAS, MITRE D3FEND, NIST AI RMF, and the MITRE Fight Fraud Framework (F3) — with each skill mapped to the frameworks **relevant to its type** (a forensics skill carries ATT&CK + CSF; an AI-security skill adds ATLAS and AI RMF). Clone it, point your agent at it, and your next security investigation gets expert-level guidance in seconds.
- ## Six frameworks, one skill library
- Each skill maps to the frameworks that fit its subject — ATT&CK and NIST CSF are near-universal, while ATLAS, AI RMF, D3FEND, and F3 apply where they're relevant. **Framework coverage across the 817 skills:** MITRE ATT&CK **805** · NIST CSF 2.0 **804** · MITRE D3FEND **139** · NIST AI RMF **97** · MITRE F3 **94** · MITRE ATLAS **93**.
- | Framework | Version | Framework scope | What it maps |
- |---|---|---|---|
- | [MITRE ATT&CK](https://attack.mitre.org) | v19.1 | 15 tactics · Enterprise/Mobile/ICS | Adversary behaviors and TTPs |
- | [NIST CSF 2.0](https://www.nist.gov/cyberframework) | 2.0 | 6 functions · 22 categories · 106 subcategories | Organizational security posture |
- | [MITRE ATLAS](https://atlas.mitre.org) | 2026.07 | 101 techniques · 77 sub-techniques | AI/ML adversarial threats |
- | [MITRE D3FEND](https://d3fend.mitre.org) | v1.4.0 | 270 techniques | Defensive countermeasures |
- | [NIST AI RMF](https://airc.nist.gov/AI_RMF) | 1.0 | 4 functions (Govern/Map/Measure/Manage) | AI risk management |
- | [MITRE F3 (Fight Fraud Framework)](https://ctid.mitre.org/fraud/) | v1.1 (2026-04-09) | 8 tactics · 123 techniques · 94 fraud-relevant skills | Cyber-enabled financial fraud TTPs |
- **Example — each skill maps only to the frameworks relevant to it (one may hit all six, another just a couple):**
- | Skill | ATT&CK | NIST CSF | ATLAS | D3FEND | AI RMF | F3 |
- |---|---|---|---|---|---|---|
- | `analyzing-network-traffic-of-malware` | T1071 | DE.CM | AML.T0047 | D3-NTA | MEASURE-2.6 | — |
- | `detecting-business-email-compromise` | T1566 | DE.AE | — | — | — | F1005.006 · monetization |
- ### 🆕 MITRE Fight Fraud Framework (F3) — 94 fraud-relevant skills
- [](https://ctid.mitre.org/fraud/)
- The **[MITRE Fight Fraud Framework (F3)](https://ctid.mitre.org/fraud/)** was released **April 9, 2026** by MITRE's Center for Threat-Informed Defense (CTID), co-developed with JPMorganChase, Citigroup, Lloyds Banking Group, Standard Chartered, CrowdStrike, Verizon Business, FS-ISAC, and others. It is an ATT&CK-compatible TTP catalog for **cyber-enabled financial fraud** — filling the gap ATT&CK leaves after initial compromise.
- F3 v1.1 adds **two fraud-specific tactics** that ATT&CK does not enumerate:
- - **Positioning** (`FA0001`) — actions taken after access to collect/manipulate data and prepare the fraud (synthetic-identity seeding, account warming, beneficiary setup, SIM-swap pre-positioning, banking-session hijack).
- - **Monetization** (`FA0002`) — converting stolen assets into usable funds (money-mule layering, APP fraud, crypto off-ramping, card cash-out, refund/chargeback abuse).
- Fraud-specific techniques use `F1XXX` IDs (e.g. `F1005.003` Add Beneficiary, `F1025.003` Wire Transfer, `F1007` Adversary-in-the-Browser); reused ATT&CK techniques keep their `T1XXX` IDs. Mappings live in each skill's `mitre_f3:` frontmatter block — all 123 F3 v1.1 technique IDs were verified against the upstream STIX bundle. See [`docs/mitre-f3-mapping.md`](docs/mitre-f3-mapping.md) for the schema.
- ### MITRE ATT&CK v19.1 — 805/817 skills mapped
- Every skill carries a `mitre_attack` frontmatter list validated against **MITRE ATT&CK v19.1** (the latest release) using the official `mitreattack-python` library — 290 distinct techniques and sub-techniques (146 base + 144 sub) across Enterprise, ICS, and Mobile. Zero revoked or deprecated IDs. v19.1's restructured Defense Evasion (now split into **Stealth** and **Defense Impairment**) is reflected below.
- | Tactic | ID | Skills |
- |--------|----|--------|
- | Reconnaissance | TA0043 | 103 |
- | Resource Development | TA0042 | 22 |
- | Initial Access | TA0001 | 467 |
- | Execution | TA0002 | 350 |
- | Persistence | TA0003 | 444 |
- | Privilege Escalation | TA0004 | 464 |
- | Stealth | TA0005 | 442 |
- | Defense Impairment | TA0112 | 92 |
- | Credential Access | TA0006 | 202 |
- | Discovery | TA0007 | 237 |
- | Lateral Movement | TA0008 | 68 |
- | Collection | TA0009 | 172 |
- | Command and Control | TA0011 | 123 |
- | Exfiltration | TA0010 | 82 |
- | Impact | TA0040 | 50 |
- ## Quick start
- ```bash
- # Option 1: npx (recommended)
- npx skills add mukul975/Anthropic-Cybersecurity-Skills
- # Option 2: Git clone
- git clone https://github.com/mukul975/Anthropic-Cybersecurity-Skills.git
- cd Anthropic-Cybersecurity-Skills
- ```
- Works immediately with Claude Code, GitHub Copilot, OpenAI Codex CLI, Cursor, Gemini CLI, and any [agentskills.io](https://agentskills.io)-compatible platform.
- ## 🌍 GARS-2026 — Global Agentic AI Readiness Survey
- I'm running a global academic study measuring how ready security professionals,
- developers, and enterprise teams actually are for agentic AI — MCP servers,
- tool calling, governance, and human-in-the-loop workflows.
- **If you use this repo, your response would be a genuinely valuable data point.**
- 📋 **Take the survey (10 min):**
- [Survey Link](https://mahipal.engineer/survey?utm_source=github_repo&utm_medium=readme&utm_campaign=gars2026)
- - 60 questions · Anonymous · Supervised by SRH Berlin
- - You get **50 Casky Tokens** for early access to [casky.ai](https://casky.ai)
- - Results published open access under CC-BY 4.0
- ## 🚀 Try it on the Playground
- Experience Casky.ai hands-on — no setup required.
- **[→ Launch Playground on Casky.ai](https://casky.ai/?utm_source=github&utm_medium=readme&utm_campaign=cohort_launch#waitlist)**
- The playground lets you:
- - Run live cybersecurity skill exercises against real targets
- - See AI agents execute structured skills in real time
- - Explore MITRE ATT&CK mapped workflows interactively
- - Test threat hunting, DFIR, and penetration testing scenarios
- No installation. No configuration. Just open and start.
- ## Why this exists
- The cybersecurity workforce gap hit **4.8 million unfilled roles** globally in 2024 (ISC2). AI agents can help close that gap — but only if they have structured domain knowledge to work from. Today's agents can write code and search the web, but they lack the practitioner playbooks that turn a generic LLM into a capable security analyst.
- Existing security tool repos give you wordlists, payloads, or exploit code. None of them give an AI agent the structured decision-making workflow a senior analyst follows: when to use each technique, what prerequisites to check, how to execute step-by-step, and how to verify results. That is the gap this project fills.
- **Anthropic Cybersecurity Skills** is not a collection of scripts or checklists. It is an **AI-native knowledge base** built from the ground up for the agentskills.io standard — YAML frontmatter for sub-second discovery, structured Markdown for step-by-step execution, and reference files for deep technical context. Every skill encodes real practitioner workflows, not generated summaries.
- ## What's inside — 34 security domains
- | Domain | Skills | Key capabilities |
- |---|---|---|
- | Cloud Security | 66 | AWS, Azure, GCP hardening · CSPM · cloud attack emulation · cloud forensics |
- | SOC Operations | 63 | Playbooks · escalation workflows · Graph-log detection · tabletop exercises |
- | Threat Hunting | 58 | Hypothesis-driven hunts · LOTL detection · EVTX hunting · fleet hunting |
- | Threat Intelligence | 52 | STIX/TAXII · MISP · OpenCTI · feed integration · actor profiling |
- | Web Application Security | 46 | OWASP Top 10 · SQLi · XSS · SSRF · deserialization |
- | Network Security | 43 | IDS/IPS · firewall rules · VLAN segmentation · traffic analysis |
- | Digital Forensics | 41 | Disk imaging · memory forensics · Hayabusa/KAPE/Plaso timelines |
- | Identity & Access Management | 40 | Entra ID/ROADtools · device-code phishing · PAM · zero trust identity |
- | Malware Analysis | 39 | Static/dynamic analysis · reverse engineering · sandboxing |
- | Red Teaming | 35 | ADCS/Certipy · BloodHound CE · Sliver/Havoc C2 · NTLM relay |
- | Container Security | 33 | K8s RBAC · image scanning · Falco · container escape |
- | OT/ICS Security | 29 | Modbus · DNP3 · IEC 62443 · historian defense · SCADA |
- | API Security | 28 | GraphQL · REST · OWASP API Top 10 · WAF bypass |
- | Incident Response | 26 | Breach containment · ransomware response · IR playbooks |
- | Vulnerability Management | 25 | Nessus · scanning workflows · patch prioritization · CVSS |
- | Penetration Testing | 23 | Network · web · cloud · mobile · NetExec lateral movement |
- | DevSecOps | 18 | CI/CD security · Trivy IaC/image scanning · code signing |
- | Zero Trust Architecture | 18 | BeyondCorp · CISA maturity model · microsegmentation |
- | Endpoint Security | 17 | EDR · LOTL detection · fileless malware · persistence hunting |
- | Phishing Defense | 16 | Email authentication · BEC detection · phishing IR |
- | Cryptography | 16 | TLS · Ed25519 · post-quantum migration · key management |
- | AI Security | 14 | LLM red-teaming (garak/PyRIT) · prompt injection · MCP/agentic security · guardrails |
- | Mobile Security | 13 | Android/iOS analysis · mobile pentesting · MDM forensics |
- | Ransomware Defense | 13 | Precursor detection · response · recovery · encryption analysis |
- | Compliance & Governance | 10 | NIST 800-30/RMF · CMMC · HIPAA · TPRM · CIS benchmarks |
- | Supply Chain Security | 8 | SBOMs · dependency confusion · malicious-package triage · SLSA/Sigstore |
- | Threat Detection | 7 | Credential dumping · golden-ticket forgery · pass-the-ticket · LOLBAS · UEBA insider signals |
- | Hardware & Firmware Security | 6 | CHIPSEC/UEFI audit · Secure Boot bypass · TPM attestation · bootkit hunting |
- | Deception Technology | 6 | Honeytokens · canarytokens · breach detection |
- | Blockchain Security | 2 | Ethereum smart-contract vulnerabilities · Foundry audit workflows |
- | Wireless Security | 2 | Bluetooth Low Energy attack detection · BLE security assessment |
- | Privacy Compliance | 2 | GDPR data-subject access requests · privacy impact assessments |
- | Data Protection | 1 | Data loss prevention with Microsoft Purview |
- | Purple Team | 1 | Atomic Red Team purple-team testing |
- *817 skills across 34 domains. Counts come from the `subdomain` field in each skill's frontmatter.*
- ## How AI agents use these skills
- Each skill costs **~30 tokens to scan** (frontmatter only) and **500–2,000 tokens to fully load** (complete workflow). This progressive disclosure architecture lets agents search all 818 skills in a single pass without blowing context windows.
- ```
- User prompt: "Analyze this memory dump for signs of credential theft"
- Agent's internal process:
- 1. Scans 818 skill frontmatters (~30 tokens each)
- → identifies 12 relevant skills by matching tags, description, domain
- 2. Loads top 3 matches:
- • performing-memory-forensics-with-volatility3
- • hunting-for-credential-dumping-lsass
- • analyzing-windows-event-logs-for-credential-access
- 3. Executes the structured Workflow section step-by-step
- → runs Volatility3 plugins, checks LSASS access patterns,
- correlates with event log evidence
- 4. Validates results using the Verification section
- → confirms IOCs, maps findings to ATT&CK T1003 (Credential Dumping)
- ```
- **Without these skills**, the agent guesses at tool commands and misses critical steps. **With them**, it follows the same playbook a senior DFIR analyst would use.
- ## Skill anatomy
- Every skill follows a consistent directory structure:
- ```
- skills/performing-memory-forensics-with-volatility3/
- ├── SKILL.md ← Skill definition (YAML frontmatter + Markdown body)
- ├── references/
- │ ├── standards.md ← MITRE ATT&CK, ATLAS, D3FEND, NIST mappings
- │ └── workflows.md ← Deep technical procedure reference
- ├── scripts/
- │ └── process.py ← Working helper scripts
- └── assets/
- └── template.md ← Filled-in checklists and report templates
- ```
- ### YAML frontmatter (real example)
- ```yaml
- ---
- name: performing-memory-forensics-with-volatility3
- description: >-
- Analyze memory dumps to extract running processes, network connections,
- injected code, and malware artifacts using the Volatility3 framework.
- domain: cybersecurity
- subdomain: digital-forensics
- tags: [forensics, memory-analysis, volatility3, incident-response, dfir]
- atlas_techniques: [AML.T0047]
- d3fend_techniques: [D3-MA, D3-PSMD]
- nist_ai_rmf: [MEASURE-2.6]
- nist_csf: [DE.CM-01, RS.AN-03]
- version: "1.2"
- author: mukul975
- license: Apache-2.0
- ---
- ```
- ### Markdown body sections
- ```markdown
- ## When to Use
- Trigger conditions — when should an AI agent activate this skill?
- ## Prerequisites
- Required tools, access levels, and environment setup.
- ## Workflow
- Step-by-step execution guide with specific commands and decision points.
- ## Verification
- How to confirm the skill was executed successfully.
- ```
- Frontmatter fields: `name` (kebab-case, 1–64 chars), `description` (keyword-rich for agent discovery), `domain`, `subdomain`, `tags`, `atlas_techniques` (MITRE ATLAS IDs), `d3fend_techniques` (MITRE D3FEND IDs), `nist_ai_rmf` (NIST AI RMF references), `nist_csf` (NIST CSF 2.0 categories). MITRE ATT&CK technique mappings are documented in each skill's `references/standards.md` file and in the ATT&CK Navigator layer included with releases.
- <details>
- <summary><strong>📊 MITRE ATT&CK Enterprise coverage — all 15 tactics</strong></summary>
-
- | Tactic | ID | Coverage | Key skills |
- |---|---|---|---|
- | Reconnaissance | TA0043 | Strong | OSINT, subdomain enumeration, DNS recon |
- | Resource Development | TA0042 | Moderate | Phishing infrastructure, C2 setup detection |
- | Initial Access | TA0001 | Strong | Phishing simulation, exploit detection, forced browsing |
- | Execution | TA0002 | Strong | PowerShell analysis, fileless malware, script block logging |
- | Persistence | TA0003 | Strong | Scheduled tasks, registry, service accounts, LOTL |
- | Privilege Escalation | TA0004 | Strong | Kerberoasting, AD attacks, cloud privilege escalation |
- | Stealth | TA0005 | Strong | Obfuscation, rootkit analysis, evasion detection |
- | Defense Impairment | TA0112 | Moderate | Impair Defenses (T1562), log/indicator removal, EDR tampering |
- | Credential Access | TA0006 | Strong | Mimikatz detection, pass-the-hash, credential dumping |
- | Discovery | TA0007 | Moderate | BloodHound, AD enumeration, network scanning |
- | Lateral Movement | TA0008 | Strong | SMB exploits, lateral movement detection with Splunk |
- | Collection | TA0009 | Moderate | Email forensics, data staging detection |
- | Command and Control | TA0011 | Strong | C2 beaconing, DNS tunneling, Cobalt Strike analysis |
- | Exfiltration | TA0010 | Strong | DNS exfiltration, DLP controls, data loss detection |
- | Impact | TA0040 | Strong | Ransomware defense, encryption analysis, recovery |
- An **ATT&CK Navigator layer file** is included in the [v1.0.0 release assets](https://github.com/mukul975/Anthropic-Cybersecurity-Skills/releases/tag/v1.0.0) for visual coverage mapping.
- > **Note:** ATT&CK v19 lands April 28, 2026 — splitting Defense Evasion (TA0005) into two new tactics: *Stealth* and *Impair Defenses*. Skill mappings will be updated in a forthcoming release.
- </details>
- <details>
- <summary><strong>📊 NIST CSF 2.0 alignment — all 6 functions</strong></summary>
-
- | Function | Skills | Examples |
- |---|---|---|
- | **Govern (GV)** | 30+ | Risk strategy, policy frameworks, roles & responsibilities |
- | **Identify (ID)** | 120+ | Asset discovery, threat landscape assessment, risk analysis |
- | **Protect (PR)** | 150+ | IAM hardening, WAF rules, zero trust, encryption |
- | **Detect (DE)** | 200+ | Threat hunting, SIEM correlation, anomaly detection |
- | **Respond (RS)** | 160+ | Incident response, forensics, breach containment |
- | **Recover (RC)** | 40+ | Ransomware recovery, BCP, disaster recovery |
- NIST CSF 2.0 (February 2024) added the **Govern** function and expanded scope from critical infrastructure to all organizations. Skill mappings align to all 22 categories and reference 106 subcategories.
- </details>
- <details>
- <summary><strong>📊 Framework deep dive — ATLAS, D3FEND, AI RMF</strong></summary>
-
- ### MITRE ATLAS 2026.07 — AI/ML adversarial threats
- ATLAS maps adversarial tactics, techniques, and case studies specific to AI and machine learning systems. Release 2026.07 covers **101 techniques and 77 sub-techniques** including agentic AI attack vectors added in late 2025: AI agent context poisoning, tool invocation abuse, MCP server compromises, and malicious agent deployment. Skills mapped to ATLAS help agents identify and defend against threats to ML pipelines, model weights, inference APIs, and autonomous workflows.
- ### MITRE D3FEND v1.4.0 — Defensive countermeasures
- D3FEND is an NSA-funded knowledge graph of **270 defensive techniques** organized across 7 tactical categories: Model, Harden, Detect, Isolate, Deceive, Evict, and Restore. Built on OWL 2 ontology, it uses a shared Digital Artifact layer to bidirectionally map defensive countermeasures to ATT&CK offensive techniques. Skills tagged with D3FEND identifiers let agents recommend specific countermeasures for detected threats.
- ### NIST AI RMF 1.0 + GenAI Profile (AI 600-1)
- The AI Risk Management Framework defines 4 core functions — Govern, Map, Measure, Manage — with **72 subcategories** for trustworthy AI development. The GenAI Profile (AI 600-1, July 2024) adds **12 risk categories** specific to generative AI, from confabulation and data privacy to prompt injection and supply chain risks. Colorado's AI Act (effective February 2026) provides a **legal safe harbor** for organizations complying with NIST AI RMF, making these mappings directly relevant to regulatory compliance.
- </details>
- ## Compatible platforms
- **AI code assistants**
- Claude Code (Anthropic) · GitHub Copilot (Microsoft) · Cursor · Windsurf · Cline · Aider · Continue · Roo Code · Amazon Q Developer · Tabnine · Sourcegraph Cody · JetBrains AI
- **CLI agents**
- OpenAI Codex CLI · Gemini CLI (Google)
- **Autonomous agents**
- Devin · Replit Agent · SWE-agent · OpenHands
- **Agent frameworks & SDKs**
- LangChain · CrewAI · AutoGen · Semantic Kernel · Haystack · Vercel AI SDK · Any MCP-compatible agent
- All platforms that support the [agentskills.io](https://agentskills.io) standard can load these skills with zero configuration.
- ## What people are saying
- > *"A database of real, organized security skills that any AI agent can plug into and use. Not tutorials. Not blog posts."*
- > — **[Hasan Toor (@hasantoxr)](https://x.com/hasantoxr/status/2033193922349179249)**, AI/tech creator
- > *"This is not a random collection of security scripts. It's a structured operational knowledge base designed for AI-driven security workflows."*
- > — **[fazal-sec](https://fazal-sec.medium.com/claude-skills-ai-powered-cybersecurity-the-complete-guide-to-building-intelligent-security-7bb7e9d14c8e)**, Medium
- ## Featured in
- | Where | Type | Link |
- |---|---|---|
- | **awesome-agent-skills** | Awesome List (1,000+ skills index) | [VoltAgent/awesome-agent-skills](https://github.com/VoltAgent/awesome-agent-skills) |
- | **awesome-ai-security** | Awesome List (AI security tools) | [ottosulin/awesome-ai-security](https://github.com/ottosulin/awesome-ai-security) |
- | **awesome-codex-cli** | Awesome List (Codex CLI resources) | [RoggeOhta/awesome-codex-cli](https://github.com/RoggeOhta/awesome-codex-cli) |
- | **SkillsLLM** | Skills directory & marketplace | [skillsllm.com/skill/anthropic-cybersecurity-skills](https://skillsllm.com/skill/anthropic-cybersecurity-skills) |
- | **Openflows** | Signal analysis & tracking | [openflows.org](https://openflows.org/currency/currents/anthropic-cybersecurity-skills/) |
- | **NeverSight skills_feed** | Automated skills index | [NeverSight/skills_feed](https://github.com/NeverSight/skills_feed) |
- ## Star history
- <a href="https://star-history.dera.page/#mukul975/Anthropic-Cybersecurity-Skills&Date">
- <picture>
- <source media="(prefers-color-scheme: dark)" srcset="https://star-history.dera.page/svg?repos=mukul975/Anthropic-Cybersecurity-Skills&type=Date&theme=dark" />
- <source media="(prefers-color-scheme: light)" srcset="https://star-history.dera.page/svg?repos=mukul975/Anthropic-Cybersecurity-Skills&type=Date" />
- <img alt="Star History Chart" src="https://star-history.dera.page/svg?repos=mukul975/Anthropic-Cybersecurity-Skills&type=Date" width="100%" />
- </picture>
- </a>
- ## Releases
- | Version | Date | Highlights |
- |---|---|---|
- | [v1.0.0](https://github.com/mukul975/Anthropic-Cybersecurity-Skills/releases/tag/v1.0.0) | March 11, 2026 | 734 skills · 26 domains · MITRE ATT&CK + NIST CSF 2.0 mapping · ATT&CK Navigator layer |
- Skills have continued to grow on `main` since v1.0.0 — the library now contains **818 skills** with **6-framework mapping** (MITRE ATLAS, D3FEND, NIST AI RMF, and the MITRE Fight Fraud Framework added post-release). Check [Releases](https://github.com/mukul975/Anthropic-Cybersecurity-Skills/releases) for the latest tagged version.
- ## Contributing
- This project grows through community contributions. Here is how to get involved:
- **Add a new skill** — Read [SCOPE.md](SCOPE.md) first, then the template in [CONTRIBUTING.md](CONTRIBUTING.md). The thinnest domains are the ones most worth adding to: Data Protection and Purple Team have one skill each, and Blockchain Security, Wireless Security and Privacy Compliance have two. Submit one skill per PR, with the title `Add skill: your-skill-name`.
- **Improve existing skills** — Add framework mappings, fix workflows, update tool references, or contribute scripts and templates. Deepening a skill that already exists is worth as much to this library as adding a new one.
- **Report issues** — Found an inaccurate procedure or broken script? [Open an issue](https://github.com/mukul975/Anthropic-Cybersecurity-Skills/issues).
- Every PR is reviewed for technical accuracy and agentskills.io standard compliance. I do that review myself, and the queue is currently longer than I would like — some pull requests have been open for months. I am working through them, and small, focused PRs move fastest. Check [good first issues](https://github.com/mukul975/Anthropic-Cybersecurity-Skills/issues?q=is%3Aissue+is%3Aopen+label%3A%22good+first+issue%22) for a starting point.
- This project follows the [Contributor Covenant](https://www.contributor-covenant.org/). By participating, you agree to uphold this code.
- ## 🙏 Thanks to our contributors
- This library is built by the community. Thank you to everyone who has contributed:
- <!-- contributors:start -->
- <p align="center">
- <a href="https://github.com/mukul975" title="mukul975 — maintainer"><img src="https://github.com/mukul975.png?size=100" width="72" height="72" alt="@mukul975"></a>
- <a href="https://github.com/valorisa" title="valorisa — 18 contributions"><img src="https://github.com/valorisa.png?size=100" width="72" height="72" alt="@valorisa"></a>
- <a href="https://github.com/juliosuas" title="juliosuas — 13 contributions"><img src="https://github.com/juliosuas.png?size=100" width="72" height="72" alt="@juliosuas"></a>
- <a href="https://github.com/Daytona39264" title="Daytona39264 — 3 contributions"><img src="https://github.com/Daytona39264.png?size=100" width="72" height="72" alt="@Daytona39264"></a>
- <a href="https://github.com/kevglynn" title="kevglynn — 2 contributions"><img src="https://github.com/kevglynn.png?size=100" width="72" height="72" alt="@kevglynn"></a>
- <a href="https://github.com/andrewibrah" title="andrewibrah — 2 contributions"><img src="https://github.com/andrewibrah.png?size=100" width="72" height="72" alt="@andrewibrah"></a>
- <a href="https://github.com/Bortlesboat" title="Bortlesboat — 1 contribution"><img src="https://github.com/Bortlesboat.png?size=100" width="72" height="72" alt="@Bortlesboat"></a>
- <a href="https://github.com/DevRedious" title="DevRedious — 1 contribution"><img src="https://github.com/DevRedious.png?size=100" width="72" height="72" alt="@DevRedious"></a>
- <a href="https://github.com/ioxoi" title="ioxoi — 1 contribution"><img src="https://github.com/ioxoi.png?size=100" width="72" height="72" alt="@ioxoi"></a>
- <a href="https://github.com/OctoBored" title="OctoBored — 1 contribution"><img src="https://github.com/OctoBored.png?size=100" width="72" height="72" alt="@OctoBored"></a>
- <a href="https://github.com/shanujans" title="shanujans — 1 contribution"><img src="https://github.com/shanujans.png?size=100" width="72" height="72" alt="@shanujans"></a>
- <a href="https://github.com/farhan6667" title="farhan6667 — 1 contribution"><img src="https://github.com/farhan6667.png?size=100" width="72" height="72" alt="@farhan6667"></a>
- <a href="https://github.com/dakshverma23" title="dakshverma23 — 1 contribution"><img src="https://github.com/dakshverma23.png?size=100" width="72" height="72" alt="@dakshverma23"></a>
- <a href="https://github.com/nyxst4ck" title="nyxst4ck — 1 contribution"><img src="https://github.com/nyxst4ck.png?size=100" width="72" height="72" alt="@nyxst4ck"></a>
- </p>
- <p align="center"><sub>14 contributors, ordered by contribution count · see the full <a href="https://github.com/mukul975/Anthropic-Cybersecurity-Skills/graphs/contributors">contributor graph</a></sub></p>
- <!-- contributors:end -->
- ## Community
- 💬 [Discussions](https://github.com/mukul975/Anthropic-Cybersecurity-Skills/discussions) — Questions, ideas, and roadmap conversations
- 🐛 [Issues](https://github.com/mukul975/Anthropic-Cybersecurity-Skills/issues) — Bug reports and feature requests
- 🔒 [Security Policy](SECURITY.md) — Responsible disclosure process (48-hour acknowledgment)
- ## Citation
- If you use this project in research or publications:
- ```bibtex
- @software{anthropic_cybersecurity_skills,
- author = {Jangra, Mahipal},
- title = {Anthropic Cybersecurity Skills},
- year = {2026},
- url = {https://github.com/mukul975/Anthropic-Cybersecurity-Skills},
- license = {Apache-2.0},
- note = {818 structured cybersecurity skills for AI agents,
- mapped to MITRE ATT\&CK, NIST CSF 2.0, MITRE ATLAS,
- MITRE D3FEND, and NIST AI RMF}
- }
- ```
- ## License
- This project is licensed under the [Apache License 2.0](LICENSE). You are free to use, modify, and distribute these skills in both personal and commercial projects.
- ---
- <div align="center">
- **If this project helps your security work, consider giving it a ⭐**
- [⭐ Star](https://github.com/mukul975/Anthropic-Cybersecurity-Skills/stargazers) · [🍴 Fork](https://github.com/mukul975/Anthropic-Cybersecurity-Skills/fork) · [💬 Discuss](https://github.com/mukul975/Anthropic-Cybersecurity-Skills/discussions) · [📝 Contribute](CONTRIBUTING.md)
- Community project by [@mukul975](https://github.com/mukul975). Not affiliated with Anthropic PBC.
- </div>
skills/analyzing-indicators-of-compromise/scripts/agent.py · Bundled script · 251 lines · 1 finding marked
- #!/usr/bin/env python3
- """IOC analysis and enrichment agent using VirusTotal, AbuseIPDB, and MalwareBazaar APIs."""
- import re
- import os
- import json
- import datetime
- try:
- import requests
- HAS_REQUESTS = True
- except ImportError:
- HAS_REQUESTS = False
- def classify_ioc(value):
- """Classify an IOC by type: ipv4, domain, url, sha256, sha1, md5, email."""
- value = value.strip()
- if re.match(r"^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$", value):
- return "ipv4"
- if re.match(r"^[a-fA-F0-9]{64}$", value):
- return "sha256"
- if re.match(r"^[a-fA-F0-9]{40}$", value):
- return "sha1"
- if re.match(r"^[a-fA-F0-9]{32}$", value):
- return "md5"
- if re.match(r"^https?://", value):
- return "url"
- if re.match(r"^[^@]+@[^@]+\.[^@]+$", value):
- return "email"
- if re.match(r"^[a-zA-Z0-9][a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$", value):
- return "domain"
- return "unknown"
- def defang_ioc(value):
- """Defang an IOC for safe documentation."""
- value = value.replace("http://", "hxxp://")
- value = value.replace("https://", "hxxps://")
- value = re.sub(r"\.(?=\w)", "[.]", value)
- return value
- def refang_ioc(value):
- """Refang a defanged IOC for querying APIs."""
- value = value.replace("hxxp://", "http://")
- value = value.replace("hxxps://", "https://")
- value = value.replace("[.]", ".")
- value = value.replace("[://]", "://")
- return value
- def is_private_ip(ip):
- """Check if an IP is RFC 1918 private."""
- octets = [int(o) for o in ip.split(".")]
- if octets[0] == 10:
- return True
- if octets[0] == 172 and 16 <= octets[1] <= 31:
- return True
- if octets[0] == 192 and octets[1] == 168:
- return True
- if octets[0] == 127:
- return True
- return False
- def query_virustotal_hash(sha256, api_key):
- """Query VirusTotal for a file hash."""
- url = f"https://www.virustotal.com/api/v3/files/{sha256}"
- resp = requests.get(url, headers={"x-apikey": api_key}, timeout=30)
- if resp.status_code == 200:
- data = resp.json().get("data", {}).get("attributes", {})
- stats = data.get("last_analysis_stats", {})
- return {
- "sha256": sha256,
- "malicious": stats.get("malicious", 0),
- "total": sum(stats.values()),
- "type_description": data.get("type_description", ""),
- "popular_threat_name": data.get("popular_threat_classification", {}).get(
- "suggested_threat_label", ""),
- "tags": data.get("tags", []),
- }
- return None
- def query_virustotal_domain(domain, api_key):
- """Query VirusTotal for domain reputation."""
- url = f"https://www.virustotal.com/api/v3/domains/{domain}"
- resp = requests.get(url, headers={"x-apikey": api_key}, timeout=30)
- if resp.status_code == 200:
- data = resp.json().get("data", {}).get("attributes", {})
- stats = data.get("last_analysis_stats", {})
- return {
- "domain": domain,
- "malicious": stats.get("malicious", 0),
- "suspicious": stats.get("suspicious", 0),
- "reputation": data.get("reputation", 0),
- "registrar": data.get("registrar", ""),
- "creation_date": data.get("creation_date", ""),
- }
- return None
- def query_abuseipdb(ip, api_key, max_age_days=90):
- """Query AbuseIPDB for IP reputation."""
- url = "https://api.abuseipdb.com/api/v2/check"
- resp = requests.get(url, headers={"Key": api_key, "Accept": "application/json"},
- params={"ipAddress": ip, "maxAgeInDays": max_age_days}, timeout=30)
- if resp.status_code == 200:
- data = resp.json().get("data", {})
- return {
- "ip": ip,
- "abuse_confidence": data.get("abuseConfidenceScore", 0),
- "total_reports": data.get("totalReports", 0),
- "country": data.get("countryCode", ""),
- "isp": data.get("isp", ""),
- "domain": data.get("domain", ""),
- "is_tor": data.get("isTor", False),
- }
- return None
- def query_malwarebazaar(sha256):
- """Query MalwareBazaar for file hash information."""
- url = "https://mb-api.abuse.ch/api/v1/"
- resp = requests.post(url, data={"query": "get_info", "hash": sha256}, timeout=30)
- if resp.status_code == 200:
- result = resp.json()
- if result.get("query_status") == "ok" and result.get("data"):
- entry = result["data"][0]
- return {
- "sha256": sha256,
- "signature": entry.get("signature", ""),
- "tags": entry.get("tags", []),
- "file_type": entry.get("file_type", ""),
- "reporter": entry.get("reporter", ""),
- "first_seen": entry.get("first_seen", ""),
- }
- return None
- def score_ioc(vt_result=None, abuse_result=None, mb_result=None):
- """Assign a confidence score and disposition to an IOC."""
- score = 0
- reasons = []
- if vt_result:
- malicious = vt_result.get("malicious", 0)
- if malicious >= 15:
- score += 40
- reasons.append(f"VT: {malicious} detections (high)")
- elif malicious >= 5:
- score += 20
- reasons.append(f"VT: {malicious} detections (moderate)")
- elif malicious > 0:
- score += 5
- reasons.append(f"VT: {malicious} detections (low)")
- if abuse_result:
- abuse_score = abuse_result.get("abuse_confidence", 0)
- if abuse_score >= 70:
- score += 30
- reasons.append(f"AbuseIPDB: {abuse_score}% confidence")
- elif abuse_score >= 30:
- score += 15
- reasons.append(f"AbuseIPDB: {abuse_score}% confidence")
- if mb_result:
- score += 30
- reasons.append(f"MalwareBazaar: {mb_result.get('signature', 'known malware')}")
- if score >= 70:
- disposition = "BLOCK"
- elif score >= 40:
- disposition = "MONITOR"
- else:
- disposition = "INVESTIGATE"
- return {"score": score, "disposition": disposition, "reasons": reasons}
- def enrich_ioc(value, vt_key=None, abuse_key=None):
- """Enrich a single IOC with multi-source intelligence."""
- ioc_type = classify_ioc(value)
- result = {
- "ioc": value,
- "type": ioc_type,
- "defanged": defang_ioc(value),
- "enrichment": {},
- "timestamp": datetime.datetime.utcnow().isoformat() + "Z",
- }
- if not HAS_REQUESTS:
- result["error"] = "requests library not installed"
- return result
- if ioc_type == "ipv4" and is_private_ip(value):
- result["note"] = "RFC 1918 private IP - skipping external enrichment"
- return result
- if ioc_type in ("sha256", "sha1", "md5") and vt_key:
- result["enrichment"]["virustotal"] = query_virustotal_hash(value, vt_key)
- result["enrichment"]["malwarebazaar"] = query_malwarebazaar(value)
- elif ioc_type == "ipv4":
- if abuse_key:
- result["enrichment"]["abuseipdb"] = query_abuseipdb(value, abuse_key)
- if vt_key:
- result["enrichment"]["virustotal"] = query_virustotal_domain(value, vt_key)
- elif ioc_type == "domain" and vt_key:
- result["enrichment"]["virustotal"] = query_virustotal_domain(value, vt_key)
- scoring = score_ioc(
- result["enrichment"].get("virustotal"),
- result["enrichment"].get("abuseipdb"),
- result["enrichment"].get("malwarebazaar"),
- )
- result["score"] = scoring["score"]
- result["disposition"] = scoring["disposition"]
- result["reasons"] = scoring["reasons"]
- return result
- if __name__ == "__main__":
- print("=" * 60)
- print("IOC Analysis & Enrichment Agent")
- print("VirusTotal, AbuseIPDB, MalwareBazaar integration")
- print("=" * 60)
- demo_iocs = [
- "185.220.101.42",
- "evil-domain.com",
- "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
- "http://malicious-site.com/payload.exe",
- Dismissed after review: Links to a Windows program from code, which is how droppers fetch their payload
- Line 227 on GitHub
- "192.168.1.100",
- ]
- print("\n--- IOC Classification & Defanging ---")
- for ioc in demo_iocs:
- ioc_type = classify_ioc(ioc)
- defanged = defang_ioc(ioc)
- private = " (private)" if ioc_type == "ipv4" and is_private_ip(ioc) else ""
- print(f" {ioc_type:8s} | {defanged}{private}")
- vt_key = os.environ.get("VT_API_KEY")
- abuse_key = os.environ.get("ABUSEIPDB_API_KEY")
- if vt_key or abuse_key:
- print("\n--- Enrichment (live API queries) ---")
- for ioc in demo_iocs:
- result = enrich_ioc(ioc, vt_key, abuse_key)
- print(f"\n {result['ioc']} ({result['type']})")
- print(f" Disposition: {result.get('disposition', 'N/A')} "
- f"(score: {result.get('score', 0)})")
- for reason in result.get("reasons", []):
- print(f" - {reason}")
- else:
- print("\n[*] Set VT_API_KEY and/or ABUSEIPDB_API_KEY environment variables for live enrichment.")
skills/analyzing-linux-system-artifacts/scripts/agent.py · Bundled script · 263 lines · 1 finding marked
- #!/usr/bin/env python3
- """Linux system artifact forensics agent for investigating compromised systems."""
- import os
- import sys
- import glob
- import shlex
- import subprocess
- def run_cmd(cmd):
- """Execute a command and return output."""
- if isinstance(cmd, str):
- cmd = shlex.split(cmd)
- result = subprocess.run(cmd, capture_output=True, text=True, timeout=30)
- return result.stdout.strip(), result.stderr.strip(), result.returncode
- def analyze_passwd(passwd_path):
- """Analyze /etc/passwd for suspicious accounts."""
- findings = []
- with open(passwd_path, "r") as f:
- for line in f:
- parts = line.strip().split(":")
- if len(parts) < 7:
- continue
- username, _, uid, gid = parts[0], parts[1], int(parts[2]), int(parts[3])
- home, shell = parts[5], parts[6]
- if uid == 0 and username != "root":
- findings.append({
- "severity": "CRITICAL",
- "finding": f"UID 0 account: {username} (shell: {shell})",
- })
- login_shells = ["/bin/bash", "/bin/sh", "/bin/zsh", "/usr/bin/zsh"]
- if uid < 1000 and uid > 0 and shell in login_shells:
- findings.append({
- "severity": "WARNING",
- "finding": f"System account with login shell: {username} (UID:{uid})",
- })
- if uid >= 1000 and shell not in ["/bin/false", "/usr/sbin/nologin", "/bin/sync"]:
- findings.append({
- "severity": "INFO",
- "finding": f"Interactive user: {username} (UID:{uid}, Home:{home})",
- })
- return findings
- def analyze_shadow(shadow_path):
- """Analyze /etc/shadow for password hash types and status."""
- findings = []
- with open(shadow_path, "r") as f:
- for line in f:
- parts = line.strip().split(":")
- if len(parts) < 3:
- continue
- username = parts[0]
- pwd_hash = parts[1]
- if pwd_hash and pwd_hash not in ("*", "!", "!!", ""):
- hash_type = "Unknown"
- if pwd_hash.startswith("$6$"):
- hash_type = "SHA-512"
- elif pwd_hash.startswith("$5$"):
- hash_type = "SHA-256"
- elif pwd_hash.startswith("$y$"):
- hash_type = "yescrypt"
- elif pwd_hash.startswith("$1$"):
- hash_type = "MD5 (WEAK)"
- findings.append({
- "severity": "WARNING",
- "finding": f"{username} uses weak MD5 password hash",
- })
- findings.append({
- "severity": "INFO",
- "finding": f"{username}: {hash_type} hash, last changed day {parts[2]}",
- })
- return findings
- def analyze_bash_history(history_path, username="unknown"):
- """Analyze bash history for suspicious commands."""
- suspicious_patterns = [
- "wget", "curl", "nc ", "ncat", "netcat", "python -c", "python3 -c",
- "perl -e", "base64", "chmod 777", "chmod +s", "/dev/tcp", "/dev/udp",
- Dismissed after review: Sets the setuid bit, so the program runs with its owner's rights
- Line 83 on GitHub
- "nmap", "masscan", "hydra", "john", "hashcat", "passwd", "useradd",
- "iptables -F", "ufw disable", "history -c", "rm -rf", "dd if=",
- "crontab", "systemctl enable", "ssh-keygen", "scp ", "rsync",
- "/tmp/", "/dev/shm/", "mkfifo", "socat",
- ]
- findings = []
- with open(history_path, "r", errors="ignore") as f:
- lines = f.readlines()
- for i, line in enumerate(lines):
- line_stripped = line.strip()
- for pattern in suspicious_patterns:
- if pattern in line_stripped.lower():
- findings.append({
- "user": username,
- "line_number": i + 1,
- "command": line_stripped[:200],
- "matched_pattern": pattern,
- })
- break
- return findings
- def check_cron_persistence(evidence_root):
- """Check cron jobs for persistence mechanisms."""
- findings = []
- cron_paths = [
- os.path.join(evidence_root, "etc/crontab"),
- *glob.glob(os.path.join(evidence_root, "etc/cron.d/*")),
- *glob.glob(os.path.join(evidence_root, "var/spool/cron/crontabs/*")),
- ]
- for cron_path in cron_paths:
- if os.path.exists(cron_path) and os.path.isfile(cron_path):
- with open(cron_path, "r", errors="ignore") as f:
- for line in f:
- line = line.strip()
- if line and not line.startswith("#"):
- suspicious = any(
- p in line.lower()
- for p in ["wget", "curl", "/tmp/", "/dev/shm/", "base64",
- "python", "bash -i", "reverse", "nc ", "ncat"]
- )
- if suspicious:
- findings.append({
- "severity": "HIGH",
- "source": cron_path,
- "entry": line[:200],
- })
- return findings
- def check_ssh_keys(evidence_root):
- """Check for unauthorized SSH authorized_keys."""
- findings = []
- key_files = glob.glob(
- os.path.join(evidence_root, "home/*/.ssh/authorized_keys")
- ) + glob.glob(
- os.path.join(evidence_root, "root/.ssh/authorized_keys")
- )
- for key_file in key_files:
- if os.path.exists(key_file):
- with open(key_file, "r") as f:
- keys = [l.strip() for l in f if l.strip() and not l.startswith("#")]
- if keys:
- findings.append({
- "file": key_file,
- "key_count": len(keys),
- "keys": [k[:80] + "..." for k in keys],
- })
- return findings
- def check_systemd_persistence(evidence_root):
- """Check for suspicious systemd service files."""
- findings = []
- service_dirs = [
- os.path.join(evidence_root, "etc/systemd/system"),
- os.path.join(evidence_root, "usr/lib/systemd/system"),
- ]
- for svc_dir in service_dirs:
- if not os.path.exists(svc_dir):
- continue
- for svc_file in glob.glob(os.path.join(svc_dir, "*.service")):
- with open(svc_file, "r", errors="ignore") as f:
- content = f.read()
- suspicious = any(
- p in content.lower()
- for p in ["/tmp/", "/dev/shm/", "wget", "curl", "reverse",
- "bash -i", "nc ", "python", "base64"]
- )
- if suspicious:
- findings.append({
- "severity": "HIGH",
- "file": svc_file,
- "preview": content[:300],
- })
- return findings
- def check_ld_preload(evidence_root):
- """Check for LD_PRELOAD rootkit indicators."""
- findings = []
- preload_path = os.path.join(evidence_root, "etc/ld.so.preload")
- if os.path.exists(preload_path):
- with open(preload_path, "r") as f:
- content = f.read().strip()
- if content:
- findings.append({
- "severity": "CRITICAL",
- "finding": f"/etc/ld.so.preload contains: {content}",
- })
- return findings
- def find_suid_binaries(evidence_root):
- """Find SUID/SGID binaries (potential privilege escalation)."""
- result = subprocess.run(
- ["find", evidence_root, "-perm", "-4000", "-type", "f"],
- capture_output=True, text=True, timeout=30
- )
- stdout = result.stdout.strip()
- return stdout.splitlines() if result.returncode == 0 and stdout else []
- def find_suspicious_tmp_files(evidence_root):
- """Find suspicious files in /tmp and /dev/shm."""
- findings = []
- for tmp_dir in ["tmp", "dev/shm"]:
- full_path = os.path.join(evidence_root, tmp_dir)
- if os.path.exists(full_path):
- for root, dirs, files in os.walk(full_path):
- for fname in files:
- fpath = os.path.join(root, fname)
- findings.append(fpath)
- return findings
- if __name__ == "__main__":
- print("=" * 60)
- print("Linux System Artifacts Forensics Agent")
- print("User accounts, persistence, shell history, rootkit detection")
- print("=" * 60)
- evidence_root = sys.argv[1] if len(sys.argv) > 1 else "/mnt/evidence"
- if os.path.exists(evidence_root):
- print(f"\n[*] Examining evidence root: {evidence_root}")
- passwd_path = os.path.join(evidence_root, "etc/passwd")
- if os.path.exists(passwd_path):
- print("\n--- User Account Analysis ---")
- for f in analyze_passwd(passwd_path):
- print(f" [{f['severity']}] {f['finding']}")
- print("\n--- Cron Persistence ---")
- cron = check_cron_persistence(evidence_root)
- for c in cron:
- print(f" [{c['severity']}] {c['source']}: {c['entry'][:80]}")
- print("\n--- SSH Authorized Keys ---")
- ssh = check_ssh_keys(evidence_root)
- for s in ssh:
- print(f" {s['file']}: {s['key_count']} keys")
- print("\n--- Systemd Persistence ---")
- systemd = check_systemd_persistence(evidence_root)
- for s in systemd:
- print(f" [{s['severity']}] {s['file']}")
- print("\n--- LD_PRELOAD Rootkit Check ---")
- ld = check_ld_preload(evidence_root)
- for l in ld:
- print(f" [{l['severity']}] {l['finding']}")
- print("\n--- Suspicious Temp Files ---")
- tmp = find_suspicious_tmp_files(evidence_root)
- for t in tmp[:20]:
- print(f" {t}")
- else:
- print(f"\n[DEMO] Usage: python agent.py <evidence_mount_point>")
- print("[*] Mount a forensic image and provide the path for analysis.")
skills/analyzing-persistence-mechanisms-in-linux/scripts/agent.py · Bundled script · 261 lines · 1 finding marked
- #!/usr/bin/env python3
- """Analyze Linux persistence mechanisms: crontab, systemd, LD_PRELOAD, shell profiles, SSH keys."""
- import os
- import re
- import json
- import glob
- import subprocess
- import argparse
- from datetime import datetime
- from collections import defaultdict
- CRON_PATHS = [
- "/etc/crontab", "/etc/cron.d/", "/etc/cron.daily/", "/etc/cron.hourly/",
- "/etc/cron.weekly/", "/etc/cron.monthly/", "/var/spool/cron/crontabs/",
- "/var/spool/cron/",
- ]
- SYSTEMD_PATHS = [
- "/etc/systemd/system/", "/lib/systemd/system/", "/usr/lib/systemd/system/",
- "/run/systemd/system/",
- ]
- SHELL_PROFILES = [".bashrc", ".bash_profile", ".profile", ".zshrc", ".bash_logout"]
- SUSPICIOUS_PATTERNS = [
- r"(nc|ncat|netcat)\s+.*-[elp]", r"(bash|sh)\s+-i\s+>&", r"/dev/tcp/",
- Note: Quoted as data in code: Shows a reverse-shell command template (placeholder or no destination)
- Line 27 on GitHub
- r"curl\s+.*\|\s*(bash|sh)", r"wget\s+.*-O\s*-\s*\|\s*(bash|sh)",
- r"python.*-c\s+.*socket", r"base64\s+--decode", r"chmod\s+\+s\s",
- r"(socat|openssl)\s+.*exec", r"crontab\s+-r",
- ]
- def scan_crontabs():
- """Scan all crontab locations for suspicious entries."""
- findings = []
- for path in CRON_PATHS:
- if os.path.isfile(path):
- findings.extend(_scan_cron_file(path))
- elif os.path.isdir(path):
- for entry in os.listdir(path):
- full_path = os.path.join(path, entry)
- if os.path.isfile(full_path):
- findings.extend(_scan_cron_file(full_path))
- user_crontabs = subprocess.run(
- ["bash", "-c", "for u in $(cut -d: -f1 /etc/passwd); do crontab -l -u $u 2>/dev/null && echo \"__USER:$u\"; done"],
- capture_output=True, text=True,
- timeout=120,
- )
- if user_crontabs.returncode == 0:
- current_user = None
- for line in user_crontabs.stdout.splitlines():
- if line.startswith("__USER:"):
- current_user = line.split(":")[1]
- elif line.strip() and not line.startswith("#") and current_user:
- risk = _assess_cron_risk(line)
- findings.append({
- "type": "user_crontab", "user": current_user,
- "command": line.strip(), "risk": risk,
- "mitre": "T1053.003",
- })
- return findings
- def _scan_cron_file(filepath):
- """Scan a single cron file for entries."""
- entries = []
- try:
- with open(filepath) as f:
- for line in f:
- line = line.strip()
- if line and not line.startswith("#"):
- risk = _assess_cron_risk(line)
- entries.append({
- "type": "cron_file", "path": filepath,
- "command": line, "risk": risk,
- "mtime": datetime.fromtimestamp(os.path.getmtime(filepath)).isoformat(),
- "mitre": "T1053.003",
- })
- except PermissionError:
- entries.append({"type": "cron_file", "path": filepath, "error": "Permission denied"})
- return entries
- def _assess_cron_risk(command):
- """Assess risk level of a cron command."""
- for pattern in SUSPICIOUS_PATTERNS:
- if re.search(pattern, command, re.IGNORECASE):
- return "critical"
- if any(kw in command.lower() for kw in ["wget", "curl", "/tmp/", "base64", "chmod"]):
- return "high"
- return "low"
- def scan_systemd_units():
- """Scan systemd service and timer units for persistence."""
- findings = []
- for base_path in SYSTEMD_PATHS:
- if not os.path.isdir(base_path):
- continue
- for unit_file in glob.glob(os.path.join(base_path, "*.service")) + \
- glob.glob(os.path.join(base_path, "*.timer")):
- try:
- stat = os.stat(unit_file)
- with open(unit_file) as f:
- content = f.read()
- risk = "low"
- exec_lines = re.findall(r"ExecStart\s*=\s*(.+)", content)
- for ex in exec_lines:
- if any(s in ex for s in ["/tmp/", "/dev/shm/", "curl", "wget", "bash -c"]):
- risk = "high"
- for pattern in SUSPICIOUS_PATTERNS:
- if re.search(pattern, ex, re.IGNORECASE):
- risk = "critical"
- dpkg_check = subprocess.run(
- ["dpkg", "-S", unit_file], capture_output=True, text=True,
- timeout=120,
- )
- package_managed = dpkg_check.returncode == 0
- if not package_managed:
- risk = max(risk, "medium", key=lambda x: ["low", "medium", "high", "critical"].index(x))
- findings.append({
- "type": "systemd_unit", "path": unit_file,
- "exec_start": exec_lines, "package_managed": package_managed,
- "risk": risk, "mtime": datetime.fromtimestamp(stat.st_mtime).isoformat(),
- "mitre": "T1543.002",
- })
- except (PermissionError, FileNotFoundError):
- continue
- return findings
- def scan_ld_preload():
- """Check for LD_PRELOAD hijacking."""
- findings = []
- preload_file = "/etc/ld.so.preload"
- if os.path.exists(preload_file):
- with open(preload_file) as f:
- content = f.read().strip()
- if content:
- findings.append({
- "type": "ld_preload_file", "path": preload_file,
- "libraries": content.splitlines(), "risk": "critical",
- "mitre": "T1574.006",
- })
- env_check = subprocess.run(["env"], capture_output=True, text=True, timeout=120)
- for line in env_check.stdout.splitlines():
- if line.startswith("LD_PRELOAD="):
- findings.append({
- "type": "ld_preload_env", "value": line.split("=", 1)[1],
- "risk": "critical", "mitre": "T1574.006",
- })
- return findings
- def scan_shell_profiles():
- """Scan shell profile files for injected commands."""
- findings = []
- for home_dir in glob.glob("/home/*") + ["/root"]:
- for profile in SHELL_PROFILES:
- filepath = os.path.join(home_dir, profile)
- if not os.path.exists(filepath):
- continue
- try:
- with open(filepath) as f:
- content = f.read()
- for pattern in SUSPICIOUS_PATTERNS:
- matches = re.findall(pattern, content, re.IGNORECASE)
- if matches:
- findings.append({
- "type": "shell_profile", "path": filepath,
- "matched_pattern": pattern, "risk": "critical",
- "mitre": "T1546.004",
- })
- except PermissionError:
- continue
- etc_profiles = glob.glob("/etc/profile.d/*.sh")
- for filepath in etc_profiles:
- dpkg = subprocess.run(["dpkg", "-S", filepath], capture_output=True, text=True, timeout=120)
- if dpkg.returncode != 0:
- findings.append({
- "type": "etc_profile_d", "path": filepath,
- "package_managed": False, "risk": "medium", "mitre": "T1546.004",
- })
- return findings
- def scan_ssh_authorized_keys():
- """Audit SSH authorized_keys files for unauthorized entries."""
- findings = []
- for home_dir in glob.glob("/home/*") + ["/root"]:
- auth_keys = os.path.join(home_dir, ".ssh", "authorized_keys")
- if not os.path.exists(auth_keys):
- continue
- try:
- with open(auth_keys) as f:
- for i, line in enumerate(f, 1):
- line = line.strip()
- if not line or line.startswith("#"):
- continue
- risk = "low"
- if "command=" in line:
- risk = "high"
- if "no-pty" not in line and "command=" in line:
- risk = "critical"
- findings.append({
- "type": "authorized_key", "path": auth_keys,
- "line_number": i, "key_snippet": line[:80] + "...",
- "has_command_restriction": "command=" in line,
- "risk": risk, "mitre": "T1098.004",
- })
- except PermissionError:
- continue
- return findings
- def generate_report(cron, systemd, ld_preload, profiles, ssh_keys):
- """Generate persistence analysis report."""
- all_findings = cron + systemd + ld_preload + profiles + ssh_keys
- risk_counts = defaultdict(int)
- for f in all_findings:
- risk_counts[f.get("risk", "unknown")] += 1
- return {
- "report_time": datetime.utcnow().isoformat(),
- "total_findings": len(all_findings),
- "risk_summary": dict(risk_counts),
- "crontab_findings": len(cron),
- "systemd_findings": len(systemd),
- "ld_preload_findings": len(ld_preload),
- "shell_profile_findings": len(profiles),
- "ssh_key_findings": len(ssh_keys),
- "findings": all_findings,
- }
- def main():
- parser = argparse.ArgumentParser(description="Linux Persistence Mechanism Analyzer")
- parser.add_argument("--output", default="linux_persistence_report.json")
- parser.add_argument("--scan", nargs="+", default=["all"],
- choices=["all", "cron", "systemd", "ldpreload", "profiles", "ssh"])
- args = parser.parse_args()
- scans = set(args.scan) if "all" not in args.scan else {"cron", "systemd", "ldpreload", "profiles", "ssh"}
- cron = scan_crontabs() if "cron" in scans else []
- systemd = scan_systemd_units() if "systemd" in scans else []
- ld_preload = scan_ld_preload() if "ldpreload" in scans else []
- profiles = scan_shell_profiles() if "profiles" in scans else []
- ssh_keys = scan_ssh_authorized_keys() if "ssh" in scans else []
- report = generate_report(cron, systemd, ld_preload, profiles, ssh_keys)
- with open(args.output, "w") as f:
- json.dump(report, f, indent=2, default=str)
- print(f"[+] Scanned {len(scans)} persistence categories")
- print(f"[+] Found {report['total_findings']} persistence artifacts")
- print(f"[+] Risk: critical={report['risk_summary'].get('critical', 0)} "
- f"high={report['risk_summary'].get('high', 0)}")
- print(f"[+] Report saved to {args.output}")
- if __name__ == "__main__":
- main()
skills/auditing-mcp-servers-for-tool-poisoning/scripts/agent.py · Bundled script · 155 lines · 2 findings marked
- #!/usr/bin/env python3
- # For authorized MCP server auditing only. Do not scan servers you do not control
- # or lack written permission to assess.
- """MCP tool-poisoning audit agent.
- Two modes:
- static -- run Invariant Labs mcp-scan over an MCP config and parse results,
- plus a local heuristic scan of tool descriptions in the config.
- enum -- launch a stdio MCP server, enumerate tools, and heuristically flag
- poisoned descriptions (hidden instructions, smuggled unicode).
- Examples:
- python agent.py static --config ~/.cursor/mcp.json
- python agent.py enum --command node --args ./suspect-mcp-server.js
- """
- import argparse
- import json
- import re
- import shutil
- import subprocess
- import sys
- from datetime import datetime, timezone
- # Heuristics for instructions aimed at the assistant inside a tool description.
- POISON_PATTERNS = [
- r"do not (tell|inform|mention to) the user",
- r"ignore (previous|prior|all) instructions",
- r"<important>|<system>|\[system\]",
- Note: Usual in code (tag names in paths and patterns): Contains a <important> block, a common wrapper for instructions hidden in a tool description
- Line 28 on GitHub
- r"read .*(\.ssh|id_rsa|\.env|credentials|passwd)",
- r"(send|exfiltrate|post) .* to https?://",
- r"before (using|calling) (this|any) tool,? (you must|always)",
- r"call (the )?\w+ tool (first|before)",
- ]
- SMUGGLE = re.compile(r"[---\U000e0000-\U000e007f]")
- Note: Usual in code (characters a sanitizer strips): Contains 2 bidirectional-override character(s), which make text display in a different order from how it's read
- Line 34 on GitHub
- def heuristic_flags(description: str):
- flags = []
- low = (description or "").lower()
- for pat in POISON_PATTERNS:
- if re.search(pat, low):
- flags.append(f"pattern:{pat}")
- if SMUGGLE.search(description or ""):
- flags.append("unicode-smuggling")
- if len(description or "") > 1500:
- flags.append("oversized-description")
- return flags
- def run_static(args):
- findings = {"ts": datetime.now(timezone.utc).isoformat(),
- "config": args.config, "atlas": "AML.T0010", "scanner": None,
- "heuristic": []}
- # 1. Invoke mcp-scan if available
- runner = shutil.which("uvx") or shutil.which("mcp-scan")
- if runner:
- cmd = ([runner, "mcp-scan@latest", "--json", args.config]
- if "uvx" in runner else [runner, "--json", args.config])
- try:
- res = subprocess.run(cmd, capture_output=True, text=True, timeout=240)
- try:
- findings["scanner"] = json.loads(res.stdout)
- except json.JSONDecodeError:
- findings["scanner"] = {"raw": res.stdout[:4000], "stderr": res.stderr[:1000]}
- except subprocess.TimeoutExpired:
- findings["scanner"] = {"error": "mcp-scan timed out"}
- else:
- findings["scanner"] = {"error": "uvx/mcp-scan not found; install uv: "
- "curl -LsSf https://astral.sh/uv/install.sh | sh"}
- # 2. Local heuristic scan of any descriptions embedded in the config
- try:
- with open(args.config, encoding="utf-8") as fh:
- cfg = json.load(fh)
- for desc in _walk_descriptions(cfg):
- f = heuristic_flags(desc)
- if f:
- findings["heuristic"].append({"flags": f, "snippet": desc[:200]})
- except (OSError, json.JSONDecodeError) as exc:
- findings["heuristic"].append({"error": str(exc)})
- print(json.dumps(findings, indent=2))
- return findings
- def _walk_descriptions(obj):
- """Yield any 'description' string values found anywhere in a nested config."""
- if isinstance(obj, dict):
- for k, v in obj.items():
- if k == "description" and isinstance(v, str):
- yield v
- else:
- yield from _walk_descriptions(v)
- elif isinstance(obj, list):
- for item in obj:
- yield from _walk_descriptions(item)
- def run_enum(args):
- try:
- import asyncio
- from mcp import ClientSession, StdioServerParameters
- from mcp.client.stdio import stdio_client
- except ImportError:
- print("Install: pip install mcp", file=sys.stderr)
- sys.exit(1)
- async def _enum():
- params = StdioServerParameters(command=args.command, args=args.args or [])
- out = {"ts": datetime.now(timezone.utc).isoformat(),
- "server": f"{args.command} {' '.join(args.args or [])}",
- "atlas": "AML.T0010", "tools": []}
- async with stdio_client(params) as (r, w):
- async with ClientSession(r, w) as s:
- await s.initialize()
- tools = await s.list_tools()
- for t in tools.tools:
- flags = heuristic_flags(t.description or "")
- out["tools"].append({
- "name": t.name,
- "desc_len": len(t.description or ""),
- "flags": flags,
- "verdict": "POISONED?" if flags else "clean",
- })
- print(json.dumps(out, indent=2))
- return out
- try:
- asyncio.run(_enum())
- except Exception as exc: # connection/protocol errors
- print(f"[!] MCP enumeration failed: {exc}", file=sys.stderr)
- sys.exit(2)
- def main():
- ap = argparse.ArgumentParser(description="MCP tool-poisoning audit agent")
- sub = ap.add_subparsers(dest="mode", required=True)
- ps = sub.add_parser("static", help="Run mcp-scan + heuristic scan on a config")
- ps.add_argument("--config", required=True, help="Path to MCP config JSON")
- pe = sub.add_parser("enum", help="Enumerate tools from a stdio MCP server")
- pe.add_argument("--command", required=True, help="Server launch command, e.g. node")
- pe.add_argument("--args", nargs="*", help="Arguments to the server command")
- args = ap.parse_args()
- if args.mode == "static":
- run_static(args)
- else:
- run_enum(args)
- if __name__ == "__main__":
- main()
skills/building-detection-rule-with-splunk-spl/scripts/process.py · Bundled script · 338 lines · 1 finding marked
- #!/usr/bin/env python3
- """
- Splunk SPL Detection Rule Builder and Validator
- Generates, validates, and manages Splunk SPL detection rules
- for SOC correlation searches. Supports MITRE ATT&CK mapping
- and rule quality scoring.
- """
- import json
- import re
- import hashlib
- from datetime import datetime
- from typing import Optional
- MITRE_TECHNIQUES = {
- "T1110.001": {"name": "Password Guessing", "tactic": "Credential Access"},
- "T1110.003": {"name": "Password Spraying", "tactic": "Credential Access"},
- "T1059.001": {"name": "PowerShell", "tactic": "Execution"},
- "T1059.003": {"name": "Windows Command Shell", "tactic": "Execution"},
- "T1021.002": {"name": "SMB/Windows Admin Shares", "tactic": "Lateral Movement"},
- "T1021.001": {"name": "Remote Desktop Protocol", "tactic": "Lateral Movement"},
- "T1048": {"name": "Exfiltration Over C2 Channel", "tactic": "Exfiltration"},
- "T1048.003": {"name": "Exfiltration Over Unencrypted Protocol", "tactic": "Exfiltration"},
- "T1053.005": {"name": "Scheduled Task", "tactic": "Persistence"},
- "T1003.001": {"name": "LSASS Memory", "tactic": "Credential Access"},
- "T1078": {"name": "Valid Accounts", "tactic": "Defense Evasion"},
- "T1078.002": {"name": "Domain Accounts", "tactic": "Defense Evasion"},
- "T1547.001": {"name": "Registry Run Keys", "tactic": "Persistence"},
- "T1055": {"name": "Process Injection", "tactic": "Defense Evasion"},
- "T1071.001": {"name": "Web Protocols", "tactic": "Command and Control"},
- "T1036.005": {"name": "Match Legitimate Name", "tactic": "Defense Evasion"},
- "T1027": {"name": "Obfuscated Files or Information", "tactic": "Defense Evasion"},
- "T1218.011": {"name": "Rundll32", "tactic": "Defense Evasion"},
- "T1543.003": {"name": "Windows Service", "tactic": "Persistence"},
- "T1105": {"name": "Ingress Tool Transfer", "tactic": "Command and Control"},
- }
- class SplunkDetectionRule:
- """Represents a Splunk SPL detection rule with metadata and validation."""
- def __init__(
- self,
- name: str,
- description: str,
- spl_query: str,
- mitre_techniques: list,
- severity: str = "medium",
- schedule_cron: str = "*/15 * * * *",
- time_window: str = "-20m",
- data_sources: Optional[list] = None,
- false_positive_notes: Optional[list] = None,
- ):
- self.name = name
- self.description = description
- self.spl_query = spl_query
- self.mitre_techniques = mitre_techniques
- self.severity = severity
- self.schedule_cron = schedule_cron
- self.time_window = time_window
- self.data_sources = data_sources or []
- self.false_positive_notes = false_positive_notes or []
- self.created = datetime.utcnow().isoformat()
- self.rule_id = self._generate_rule_id()
- def _generate_rule_id(self) -> str:
- hash_input = f"{self.name}:{self.spl_query}"
- return f"SPL-{hashlib.sha256(hash_input.encode()).hexdigest()[:12].upper()}"
- def validate(self) -> dict:
- """Validate the SPL detection rule for common issues."""
- issues = []
- score = 100
- # Check for missing time constraint
- if "earliest=" not in self.spl_query and "span=" not in self.spl_query:
- issues.append("WARNING: No time constraint in query - may scan too much data")
- score -= 10
- # Check for wildcard-heavy searches
- wildcard_count = self.spl_query.count("*")
- if wildcard_count > 5:
- issues.append(f"WARNING: {wildcard_count} wildcards detected - may impact performance")
- score -= 5 * min(wildcard_count - 5, 4)
- # Check for aggregation
- agg_commands = ["stats", "eventstats", "streamstats", "tstats", "chart", "timechart"]
- has_aggregation = any(cmd in self.spl_query.lower() for cmd in agg_commands)
- if not has_aggregation:
- issues.append("WARNING: No aggregation command - rule may generate excessive alerts")
- score -= 15
- # Check for threshold
- if "where" not in self.spl_query.lower():
- issues.append("WARNING: No where clause - rule has no threshold filtering")
- score -= 15
- # Check for enrichment
- if "lookup" not in self.spl_query.lower():
- issues.append("INFO: No lookup enrichment - consider adding asset/identity context")
- score -= 5
- # Check MITRE mapping
- if not self.mitre_techniques:
- issues.append("WARNING: No MITRE ATT&CK technique mapped")
- score -= 10
- for tech_id in self.mitre_techniques:
- if tech_id not in MITRE_TECHNIQUES:
- issues.append(f"WARNING: Unknown MITRE technique ID: {tech_id}")
- score -= 5
- # Check severity is valid
- valid_severities = ["informational", "low", "medium", "high", "critical"]
- if self.severity not in valid_severities:
- issues.append(f"ERROR: Invalid severity '{self.severity}' - must be one of {valid_severities}")
- score -= 20
- # Check for eval description
- if "eval description" not in self.spl_query.lower() and "eval rule_description" not in self.spl_query.lower():
- issues.append("INFO: No description field in output - analysts will lack context")
- score -= 5
- # Check for CIM data model usage
- if "datamodel=" in self.spl_query.lower() or "tstats" in self.spl_query.lower():
- score += 5 # Bonus for using CIM-accelerated searches
- return {
- "rule_id": self.rule_id,
- "rule_name": self.name,
- "valid": score >= 60,
- "quality_score": max(0, min(100, score)),
- "issues": issues,
- "issue_count": len(issues),
- }
- def to_splunk_savedsearch_conf(self) -> str:
- """Generate Splunk savedsearches.conf stanza for the rule."""
- mitre_str = ", ".join(self.mitre_techniques)
- stanza = f"""[{self.name}]
- search = {self.spl_query}
- description = {self.description}
- dispatch.earliest_time = {self.time_window}
- dispatch.latest_time = now
- cron_schedule = {self.schedule_cron}
- is_scheduled = 1
- enableSched = 1
- alert.severity = {self._severity_to_int()}
- alert.suppress = 1
- alert.suppress.period = 1h
- alert.suppress.fields = src_ip
- action.notable = 1
- action.notable.param.rule_title = {self.name}
- action.notable.param.rule_description = {self.description}
- action.notable.param.severity = {self.severity}
- action.notable.param.security_domain = threat
- action.notable.param.drilldown_name = View triggering events
- action.notable.param.drilldown_search = {self.spl_query}
- action.notable.param.mitre_attack = {mitre_str}
- """
- return stanza
- def _severity_to_int(self) -> int:
- mapping = {"informational": 1, "low": 2, "medium": 3, "high": 4, "critical": 5}
- return mapping.get(self.severity, 3)
- def to_json(self) -> str:
- return json.dumps(
- {
- "rule_id": self.rule_id,
- "name": self.name,
- "description": self.description,
- "spl_query": self.spl_query,
- "mitre_techniques": self.mitre_techniques,
- "severity": self.severity,
- "schedule_cron": self.schedule_cron,
- "time_window": self.time_window,
- "data_sources": self.data_sources,
- "false_positive_notes": self.false_positive_notes,
- "created": self.created,
- },
- indent=2,
- )
- class DetectionRuleLibrary:
- """Manages a collection of Splunk detection rules."""
- def __init__(self):
- self.rules = []
- def add_rule(self, rule: SplunkDetectionRule):
- self.rules.append(rule)
- def validate_all(self) -> dict:
- results = {"total_rules": len(self.rules), "valid_rules": 0, "invalid_rules": 0, "details": []}
- for rule in self.rules:
- validation = rule.validate()
- results["details"].append(validation)
- if validation["valid"]:
- results["valid_rules"] += 1
- else:
- results["invalid_rules"] += 1
- return results
- def get_mitre_coverage(self) -> dict:
- coverage = {}
- for rule in self.rules:
- for tech_id in rule.mitre_techniques:
- if tech_id not in coverage:
- coverage[tech_id] = {
- "technique": MITRE_TECHNIQUES.get(tech_id, {}).get("name", "Unknown"),
- "tactic": MITRE_TECHNIQUES.get(tech_id, {}).get("tactic", "Unknown"),
- "rules": [],
- }
- coverage[tech_id]["rules"].append(rule.name)
- return {
- "techniques_covered": len(coverage),
- "total_known_techniques": len(MITRE_TECHNIQUES),
- "coverage_percentage": round(len(coverage) / len(MITRE_TECHNIQUES) * 100, 1),
- "coverage_map": coverage,
- }
- def export_savedsearches_conf(self) -> str:
- output = "# Auto-generated Splunk savedsearches.conf\n"
- output += f"# Generated: {datetime.utcnow().isoformat()}\n"
- output += f"# Total Rules: {len(self.rules)}\n\n"
- for rule in self.rules:
- output += rule.to_splunk_savedsearch_conf() + "\n"
- return output
- def build_sample_detection_library() -> DetectionRuleLibrary:
- """Build a sample detection rule library with common SOC use cases."""
- library = DetectionRuleLibrary()
- library.add_rule(
- SplunkDetectionRule(
- name="Brute Force - Multiple Failed Logins",
- description="Detects brute force attacks with multiple failed login attempts from a single source",
- spl_query=(
- '| tstats summariesonly=true count from datamodel=Authentication '
- 'where Authentication.action=failure by Authentication.src, Authentication.user, _time span=5m '
- '| rename "Authentication.*" as * '
- '| stats count as total_failures dc(user) as unique_users values(user) as targeted_users by src '
- '| where total_failures > 20 AND unique_users > 3 '
- '| lookup asset_lookup ip as src OUTPUT priority as asset_priority '
- '| eval severity=case(unique_users > 10, "critical", unique_users > 5, "high", true(), "medium") '
- '| eval description="Brute force detected from ".src." targeting ".unique_users." accounts"'
- ),
- mitre_techniques=["T1110.001"],
- severity="high",
- schedule_cron="*/5 * * * *",
- time_window="-10m",
- data_sources=["Windows Security Event Log", "Linux Auth Log"],
- false_positive_notes=["Service accounts with expired passwords", "Misconfigured applications"],
- )
- )
- library.add_rule(
- SplunkDetectionRule(
- name="Suspicious PowerShell Execution",
- description="Detects encoded or obfuscated PowerShell commands indicating potential malicious activity",
- spl_query=(
- 'index=wineventlog sourcetype=WinEventLog:Security EventCode=4104 '
- '| where match(ScriptBlockText, "(?i)(encodedcommand|invoke-expression|iex|downloadstring|frombase64string|net\\.webclient|invoke-mimikatz)") '
- Note: Quoted as data in code: Runs code it decodes (base64, hex, character codes, reversed text or a compressed blob), which hides what runs from a reader
- Line 268 on GitHub
- '| stats count values(ScriptBlockText) as commands by Computer, UserName '
- '| where count > 0 '
- '| lookup identity_lookup identity as UserName OUTPUT department, manager '
- '| eval severity="high" '
- '| eval description="Suspicious PowerShell on ".Computer." by ".UserName'
- ),
- mitre_techniques=["T1059.001", "T1027"],
- severity="high",
- data_sources=["Windows PowerShell Script Block Logging"],
- false_positive_notes=["IT automation scripts using encoded commands", "SCCM deployment scripts"],
- )
- )
- library.add_rule(
- SplunkDetectionRule(
- name="Lateral Movement - Multiple Host Access",
- description="Detects a user or source IP accessing an unusual number of hosts via network logon",
- spl_query=(
- '| tstats summariesonly=true dc(Authentication.dest) as unique_hosts '
- 'from datamodel=Authentication where Authentication.action=success Authentication.Logon_Type=3 '
- 'by Authentication.src, Authentication.user, _time span=1h '
- '| rename "Authentication.*" as * '
- '| where unique_hosts > 5 '
- '| lookup asset_lookup ip as src OUTPUT asset_name, asset_category '
- '| eval severity=case(unique_hosts > 20, "critical", unique_hosts > 10, "high", true(), "medium") '
- '| eval description=user." accessed ".unique_hosts." hosts from ".src." in 1 hour"'
- ),
- mitre_techniques=["T1021.002", "T1078.002"],
- severity="high",
- data_sources=["Windows Security Event Log"],
- false_positive_notes=["Vulnerability scanners", "IT management tools", "Software deployment systems"],
- )
- )
- return library
- if __name__ == "__main__":
- library = build_sample_detection_library()
- print("=" * 70)
- print("SPLUNK SPL DETECTION RULE LIBRARY")
- print("=" * 70)
- # Validate all rules
- validation = library.validate_all()
- print(f"\nTotal Rules: {validation['total_rules']}")
- print(f"Valid Rules: {validation['valid_rules']}")
- print(f"Invalid Rules: {validation['invalid_rules']}")
- for detail in validation["details"]:
- print(f"\n--- {detail['rule_name']} ---")
- print(f" Rule ID: {detail['rule_id']}")
- print(f" Quality Score: {detail['quality_score']}/100")
- print(f" Valid: {detail['valid']}")
- for issue in detail["issues"]:
- print(f" {issue}")
- # MITRE coverage
- coverage = library.get_mitre_coverage()
- print(f"\nMITRE ATT&CK Coverage: {coverage['techniques_covered']}/{coverage['total_known_techniques']} ({coverage['coverage_percentage']}%)")
- for tech_id, info in coverage["coverage_map"].items():
- print(f" {tech_id} ({info['technique']}): {', '.join(info['rules'])}")
- # Export savedsearches.conf
- conf = library.export_savedsearches_conf()
- print(f"\n{'=' * 70}")
- print("GENERATED savedsearches.conf")
- print("=" * 70)
- print(conf)
skills/building-threat-intelligence-platform/scripts/agent.py · Bundled script · 163 lines · 1 finding marked
- #!/usr/bin/env python3
- """Threat intelligence platform builder.
- Core TIP components: STIX/TAXII ingestion, indicator lifecycle management,
- confidence scoring, sharing groups, and intelligence dissemination.
- """
- import json
- import datetime
- import re
- import uuid
- STIX_INDICATOR_TYPES = {
- "ipv4-addr": "[ipv4-addr:value = '{}']",
- "domain-name": "[domain-name:value = '{}']",
- "url": "[url:value = '{}']",
- "file-sha256": "[file:hashes.'SHA-256' = '{}']",
- "file-md5": "[file:hashes.MD5 = '{}']",
- "email-addr": "[email-addr:value = '{}']",
- }
- TLP_DEFINITIONS = {
- "TLP:CLEAR": {"color": "white", "sharing": "Unlimited", "code": 0},
- "TLP:GREEN": {"color": "green", "sharing": "Community", "code": 1},
- "TLP:AMBER": {"color": "amber", "sharing": "Organization", "code": 2},
- "TLP:AMBER+STRICT": {"color": "amber", "sharing": "Need-to-know only", "code": 3},
- "TLP:RED": {"color": "red", "sharing": "Named recipients only", "code": 4},
- }
- def classify_indicator(value):
- """Classify indicator type from raw value."""
- if re.match(r"^[0-9]{1,3}(\\.[0-9]{1,3}){3}$", value):
- return "ipv4-addr"
- if re.match(r"^[a-fA-F0-9]{64}$", value):
- return "file-sha256"
- if re.match(r"^[a-fA-F0-9]{32}$", value):
- return "file-md5"
- if re.match(r"^[a-zA-Z0-9][a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$", value):
- return "domain-name"
- if value.startswith("http://") or value.startswith("https://"):
- return "url"
- if "@" in value:
- return "email-addr"
- return "unknown"
- def create_stix_indicator(value, indicator_type=None, confidence=50, tlp="TLP:AMBER"):
- """Create a STIX 2.1 Indicator object."""
- if not indicator_type:
- indicator_type = classify_indicator(value)
- pattern_template = STIX_INDICATOR_TYPES.get(indicator_type)
- if not pattern_template:
- return {"error": "Unsupported indicator type: " + indicator_type}
- now = datetime.datetime.utcnow().isoformat(timespec="milliseconds") + "Z"
- indicator_id = "indicator--" + str(uuid.uuid5(uuid.NAMESPACE_URL, value))
- indicator = {
- "type": "indicator",
- "spec_version": "2.1",
- "id": indicator_id,
- "created": now,
- "modified": now,
- "name": "{}: {}".format(indicator_type, value),
- "pattern": pattern_template.format(value),
- "pattern_type": "stix",
- "valid_from": now,
- "confidence": confidence,
- "labels": ["malicious-activity"],
- "object_marking_refs": [tlp_to_marking_ref(tlp)],
- }
- return indicator
- def tlp_to_marking_ref(tlp):
- """Convert TLP label to STIX marking definition ID."""
- tlp_refs = {
- "TLP:CLEAR": "marking-definition--613f2e26-407d-48c7-9eca-b8e91df99dc9",
- "TLP:GREEN": "marking-definition--34098fce-860f-48ae-8e50-ebd3cc5e41da",
- "TLP:AMBER": "marking-definition--f88d31f6-486f-44da-b317-01333bde0b82",
- "TLP:AMBER+STRICT": "marking-definition--826578e1-40a3-4b46-a8d8-b9931fdd750e",
- "TLP:RED": "marking-definition--5e57c739-391a-4eb3-b6be-7d15ca92d5ed",
- }
- return tlp_refs.get(tlp, tlp_refs["TLP:AMBER"])
- def calculate_indicator_score(sources_count, age_days, confirmed_sightings, false_positives):
- """Calculate indicator confidence score (0-100)."""
- source_score = min(sources_count * 15, 40)
- age_penalty = min(age_days * 0.5, 30)
- sighting_score = min(confirmed_sightings * 10, 30)
- fp_penalty = min(false_positives * 15, 30)
- score = source_score - age_penalty + sighting_score - fp_penalty
- return max(0, min(100, round(score)))
- def build_stix_bundle(indicators):
- """Build STIX 2.1 Bundle from list of indicators."""
- bundle = {
- "type": "bundle",
- "id": "bundle--" + str(uuid.uuid4()),
- "objects": indicators,
- }
- return bundle
- def generate_tip_report(indicators, platform_name="Internal TIP"):
- """Generate TIP status report."""
- type_counts = {}
- for ind in indicators:
- itype = ind.get("name", "").split(":")[0] if ":" in ind.get("name", "") else "unknown"
- type_counts[itype] = type_counts.get(itype, 0) + 1
- return {
- "platform": platform_name,
- "generated_at": datetime.datetime.utcnow().isoformat() + "Z",
- "total_indicators": len(indicators),
- "type_breakdown": type_counts,
- "avg_confidence": round(
- sum(i.get("confidence", 0) for i in indicators) / max(len(indicators), 1), 1
- ),
- }
- if __name__ == "__main__":
- print("=" * 60)
- print("Threat Intelligence Platform Builder")
- print("STIX 2.1 indicators, scoring, TLP marking, bundle export")
- print("=" * 60)
- demo_values = [
- "198.51.100.42",
- "evil-domain.example.com",
- "a" * 64,
- "https://evil.example.com/payload.exe",
- Dismissed after review: Links to a Windows program from code, which is how droppers fetch their payload
- Line 137 on GitHub
- "attacker@evil.example.com",
- ]
- indicators = []
- for val in demo_values:
- ind = create_stix_indicator(val, confidence=75, tlp="TLP:AMBER")
- if "error" not in ind:
- indicators.append(ind)
- print("\n--- Indicators Created ---")
- for ind in indicators:
- print(" {} [confidence={}]".format(ind["name"], ind["confidence"]))
- print(" Pattern: {}".format(ind["pattern"]))
- bundle = build_stix_bundle(indicators)
- print("\nSTIX Bundle: {} ({} objects)".format(bundle["id"], len(bundle["objects"])))
- score = calculate_indicator_score(sources_count=3, age_days=5, confirmed_sightings=2, false_positives=0)
- print("\nSample score calculation: {}".format(score))
- report = generate_tip_report(indicators)
- print("\n--- Platform Report ---")
- for k, v in report.items():
- print(" {}: {}".format(k, v))
- print("\n" + json.dumps({"indicators_created": len(indicators)}, indent=2))
Ratings and comments
Sign in to rate this skill.
Sign inFree to use. If it’s helped, pass it on.