cybersec-toolkit
Cybersecurity skill library — security how-tos, offensive/defensive methodology, and CTF/bounty playbooks for Claude Code.
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
It has changed since its scan on 15 Nov 2026. 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/26zl/cybersec-toolkit 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/26zl/cybersec-toolkit'
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/26zl--cybersec-toolkit)HTML
<a href="/listings/26zl--cybersec-toolkit"><img src="/api/listings/26zl--cybersec-toolkit/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.
__1. Install the tools__ on a supported Linux distro or on Termux:
git clone --depth 1 --branch v1.5.0 https://github.com/26zl/cybersec-toolkit.git && cd cybersec-toolkit ./install.sh --doctor # read-only preflight: distro, prerequisites, MCP server, sandbox sudo ./install.sh --profile ctf # one profile; with no flags, all 18 modules
__2. Connect an AI client.__ The tracked configs for Claude Code (`.mcp.json`, also read by the GitHub Copilot CLI), Codex, Gemini CLI, and OpenCode start the server through `scripts/mcp-launch.sh`, with external targets and script execution disabled. Choose where the tools run:
| Mode | Tools run | Host needs | One-time setup | | ---- | --------- | ---------- | -------------- | | Sandbox (default) | In a disposable Kata VM, from the sandbox image | Linux with KVM, Docker 23+ with a Kata runtime, Node.js 22+ | `make sandbox-image`, then `npm --prefix sandbox ci --ignore-scripts` | | Host (`--local`) | As your user, with the tools `install.sh` installed | [uv](https://docs.astral.sh/uv/) | Add `--local` to the launcher, or set `CYBERSEC_SANDBOX_MODE=local` in the client's `env` |
Kata needs KVM: on macOS, on Windows, and in VMs without nested virtualization, use host mode.
__3. Restart the client.__ The 15 tools appear (`/mcp` in Claude Code). Then ask for what you need, for example "triage this binary" or "map the attack surface of my lab at 10.10.0.0/24".
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 · 28 lines
- {
- "$schema": "https://json.schemastore.org/claude-code-marketplace.json",
- "name": "cybersec-toolkit",
- "description": "Cybersecurity skill library — security how-tos, offensive/defensive methodology, and CTF/bounty playbooks for Claude Code.",
- "owner": {
- "name": "26zl",
- "url": "https://github.com/26zl"
- },
- "plugins": [
- {
- "name": "cybersec-toolkit",
- "source": "./",
- "description": "872 on-demand security skills for CTF, pentest, bug bounty, DFIR, detection engineering, cloud, identity, and red/blue team work. Bundled skills carry mixed licenses — see .claude/skills/SKILLS.md attribution.",
- "version": "1.5.0",
- "license": "MIT AND Apache-2.0 AND CC-BY-SA-4.0",
- "category": "security",
- "keywords": [
- "security",
- "pentest",
- "ctf",
- "bug-bounty",
- "dfir",
- "red-team",
- "blue-team"
- ]
- }
- ]
- }
README.md · README · 676 lines
- <!-- mcp-name: io.github.26zl/cybersec-toolkit -->
- [](https://github.com/26zl/cybersec-toolkit/actions/workflows/ci.yml)
- [](https://github.com/26zl/cybersec-toolkit/actions/workflows/integration.yml)
- [](https://github.com/26zl/cybersec-toolkit/actions/workflows/security.yml)
- [](https://scorecard.dev/viewer/?uri=github.com/26zl/cybersec-toolkit)
- [](https://github.com/26zl/cybersec-toolkit/commits/main)
- [](LICENSE)
- [](https://github.com/26zl/cybersec-toolkit/pkgs/container/cybersec-toolkit)
- [](https://glama.ai/mcp/servers/26zl/cybersec-toolkit)
- 
- __A security toolkit that AI agents can drive, under rules you set.__ One command installs 670+ security tools on Linux or Termux. An [MCP (Model Context Protocol)](https://modelcontextprotocol.io/) server lets Claude Code, Codex, Gemini CLI, OpenCode, and other MCP clients discover, recommend, and run those tools through a governed execution path, inside a disposable Kata Containers VM by default. 872 Agent Skills supply the methodology for CTF, pentest, bug bounty, DFIR, and blue-team work.
- | Component | What you get |
- | --------- | ------------ |
- | [Installer](#installer) | 670+ tools in 18 modules, 14 profiles, and 12 install methods for Debian/Ubuntu/Kali/Parrot, Fedora/RHEL, Arch, openSUSE, and Termux |
- | [MCP server](#mcp-server) | 15 tools for discovery, advice, and governed execution; external targets and script execution are off by default |
- | [Sandbox](#sandbox-and-host-mode) | One Kata Containers VM per session by default; `--local` runs the server on the host |
- | [Agent Skills](#agent-skills) | 872 skills (31 project-authored, 841 curated), also installable as a Claude Code plugin |
- > __What makes it different:__ most toolkits stop at _installing_ tools. Here an AI can also _drive_ them: infer the problem type, pick tools from every module and profile, and work through the problem with you step by step. When you explicitly authorize it, the same toolchain runs an autonomous solver loop. __Companion by default; autonomous only when you ask.__ It complements Kali, Parrot, or BlackArch rather than replacing them: it runs on the machine you already have, Termux included.
- [Quick start](#quick-start) · [How it works](#how-it-works) · [Trust & safety](#trust--safety) · [Installer](#installer) · [MCP server](#mcp-server) · [Agent Skills](#agent-skills) · [Development](#development) · [License](#license)
- ## Quick start
- __1. Install the tools__ on a supported Linux distro or on Termux:
- ```bash
- git clone --depth 1 --branch v1.5.0 https://github.com/26zl/cybersec-toolkit.git && cd cybersec-toolkit
- ./install.sh --doctor # read-only preflight: distro, prerequisites, MCP server, sandbox
- sudo ./install.sh --profile ctf # one profile; with no flags, all 18 modules
- ```
- __2. Connect an AI client.__ The tracked configs for Claude Code (`.mcp.json`, also read by the GitHub Copilot CLI), Codex, Gemini CLI, and OpenCode start the server through `scripts/mcp-launch.sh`, with external targets and script execution disabled. Choose where the tools run:
- | Mode | Tools run | Host needs | One-time setup |
- | ---- | --------- | ---------- | -------------- |
- | Sandbox (default) | In a disposable Kata VM, from the sandbox image | Linux with KVM, Docker 23+ with a Kata runtime, Node.js 22+ | `make sandbox-image`, then `npm --prefix sandbox ci --ignore-scripts` |
- | Host (`--local`) | As your user, with the tools `install.sh` installed | [uv](https://docs.astral.sh/uv/) | Add `--local` to the launcher, or set `CYBERSEC_SANDBOX_MODE=local` in the client's `env` |
- Kata needs KVM: on macOS, on Windows, and in VMs without nested virtualization, use host mode.
- __3. Restart the client.__ The 15 tools appear (`/mcp` in Claude Code). Then ask for what you need, for example "triage this binary" or "map the attack surface of my lab at 10.10.0.0/24".
- ## How it works
- Two entry points share one tool registry. An __operator__ runs the bash installer to put tools on disk: on the host, or into the sandbox image at build time. An __AI agent__ talks to the MCP server, which runs inside a Kata VM by default, to discover, recommend, and execute those tools through one governed path. `tools_config.json` is the registry: the MCP server reads it, and CI validators keep it in step with the module arrays the installer works from, along with the rest of the Python and bash sides.
- <!-- Rendered from assets/how-it-works.mmd so it displays consistently everywhere.
- Re-render with:
- npm_config_cache=/tmp/cybersec-npm-cache npx --yes \
- --package @mermaid-js/mermaid-cli@11.16.0 mmdc \
- -i assets/how-it-works.mmd -o assets/how-it-works.png -t dark -b "#0d1117" -s 3 -->
- 
- Solid arrows are runtime or installation actions; dashed lines are validation and context relationships. Client configurations enter through the root-aware launcher. By default it starts `sandbox/mcp.mjs`, which boots a disposable VM through a [Sandcastle](https://github.com/mattpocock/sandcastle) Kata provider (`sandbox/kata.mjs`) and bridges the client's stdio to the server inside; with `--local` it starts the server on the host. Two boundaries are opt-in: a scope file makes the VM a network boundary, and `CYBERSEC_LOCAL_SANDBOX=1` starts every host-mode tool and script inside bubblewrap. `security.py` governs `run_tool` and `run_pipeline` through the allowlist, argument checks, and network policy without invoking a shell. `run_script` is a separate, disabled-by-default capability that runs arbitrary code. Every call is recorded in a hash-chained audit log on the host, and `scripts/agent-guard.sh`, a client-side hook, reads that log to send target work through an advisor before a security tool is run from the client's own shell. Agent Skills stay outside the execution path: `.claude/skills/` is canonical, and `scripts/sync-skills.sh` generates `.agents/skills/` for clients that read the portable mirror. Target work ends in a local, git-ignored writeup under `writeups/`. Mermaid source: [`assets/how-it-works.mmd`](assets/how-it-works.mmd).
- ## Trust & safety
- What runs, and what is gated:
- - __Default-safe MCP.__ `CYBERSEC_MCP_ALLOW_EXTERNAL=0` rejects network targets that do not resolve to private or loopback ranges, and `CYBERSEC_MCP_ALLOW_SCRIPTS=0` disables `run_script`. External scopes and scripting are explicit opt-ins.
- - __One gate for governed execution__ (`mcp_server/security.py`): registry allowlist, no shell (`create_subprocess_exec`, never `shell=True`), argument sanitization, a per-tool blocked-flag denylist (e.g. `sqlmap --os-shell`, `nmap -iL`, file-list and target-injection flags), target and network policy, rate limiting, output caps, and timeouts. The policy knows enough CLI grammar to tell a target from a header, wordlist, output path, or target-list flag. Tool output reaches the model without terminal escape sequences or LLM control markers, and lines addressed to an AI reader are flagged.
- - __Tools run in a disposable VM by default.__ The launcher boots a [Kata Containers](docs/SANDBOX.md) VM with its own kernel, no host filesystem beyond an optional `CYBERSEC_SANDBOX_WORKSPACE` mount, no Docker socket, a non-root user with every capability dropped, and memory, CPU, and process limits. It is destroyed when the client disconnects. Startup fails closed instead of falling back to the host; `--local` is the explicit opt-out.
- - __A scope file makes the VM a network boundary.__ `CYBERSEC_SANDBOX_SCOPE` names a file listing the addresses, ranges, names and ports of the engagement. The launcher loads it as a default-deny firewall inside the VM before the server starts, and refuses to start if it cannot; tools, their child processes and `run_script` bodies all sit behind it and cannot change it ([details and limits](docs/SANDBOX.md#network-scope)).
- - __Know the limits.__ Without a scope file the VM reaches whatever its Docker network reaches, and `CYBERSEC_MCP_ALLOW_EXTERNAL` is a preflight check on resolved addresses, not a firewall (`CYBERSEC_SANDBOX_NETWORK=none` removes the network). Inside the VM, and on your host in `--local` mode, allowed tools run with the server user's permissions, and some of them spawn child processes or load plugins. `--local` mode has no firewall of its own; `CYBERSEC_LOCAL_SANDBOX=1` at least starts its tools inside bubblewrap, without your credential stores, the agent client's configuration or other processes ([what it covers](docs/SANDBOX.md#host-mode-behind-bubblewrap)).
- - __Tool output goes to your model provider.__ Whatever a tool prints — scan results, page content, and any credential or personal data it finds on a target — is returned to the AI client and sent to the model it uses. By default only the local audit log is redacted; set `CYBERSEC_MCP_REDACT_OUTPUT=1` to also redact credential-shaped strings from what the client receives. If an engagement's rules forbid sharing client data with a third party, drive the server from a local model (see [AI clients](docs/AI_CLIENTS.md)).
- - __Repository hooks run automatically.__ Opening this repository in Claude Code runs the tracked hooks in `.claude/settings.json`: `scripts/agent-guard.sh` at session start and before each Bash command. They only emit routing context or a deny decision, make no network calls, and fail open; set `CYBERSEC_AGENT_GUARD=0` to disable them.
- - __Audit trail without leaks.__ Actions are logged as JSON lines to an owner-only (`0600`), rotating log under the user's state directory (`~/.local/state/cybersec-tools-mcp/audit.log` by default). Script bodies are never stored, only their SHA256 and length, and credential-shaped strings are redacted from tool arguments. A sandboxed server mirrors its records to the same host log, and records are hash-chained, so an edited or deleted record inside a chain shows up in `make audit-verify` ([limits](docs/SANDBOX.md#tamper-evidence)).
- - __Least privilege in the installer.__ It runs as root but drops to the invoking user (`$SUDO_USER`) for cloned-repo builds, `go`/`cargo`/`gem` builds, and project setup steps (theHarvester, pwndbg); binary releases are SHA256-verified when checksums are published. `pipx` installs (into the shared `/opt/pipx`) and global `npm` installs still run as root, so their build and install scripts execute with root privileges — see the [supply chain model](#supply-chain-model). Go binaries are copied into `/usr/local/bin` as root-owned files; cargo, gem, cloned-repo, source-build, patator and Foundry tools are exposed there as links or wrappers into trees the invoking user owns, so that user can change what those commands run.
- - __Dual-use tooling is gated.__ C2 and phishing frameworks (Sliver, Caldera, gophish, evilginx, wifiphisher, BeEF, …) are __off by default__ and install only with `--include-c2` (the `redteam` and `full` profiles set it); the MCP layer reflects this and never auto-runs them. The gate covers frameworks built to phish or to run implants. Exploitation and auditing suites that can also do those things, such as Metasploit, airgeddon and hostapd-mana, are in the default set.
- - __Authorized use only.__ See [`SECURITY.md`](SECURITY.md), the [supply chain model](#supply-chain-model), and the [disclaimer](#disclaimer).
- ## Installer
- ### Requirements
- A supported Linux distro (Debian/Ubuntu/Kali/Parrot, Fedora/RHEL, Arch, openSUSE) or Termux. Runtimes (Python, Go, Ruby, Java, Rust, Node.js), dev libraries, pipx, and build tools are installed automatically. The installer does not run on macOS or native Windows; use WSL or [Docker](#docker-and-podman).
- - __Docker__ is needed for `--enable-docker` (C2 frameworks, MobSF, BeEF, BloodHound, TheHive, Cortex) and for the `blueteam`, `redteam`, `blockchain`, and `mobile` profiles, which enable Docker images by default (see [Profiles](#profiles)). Install it yourself: [Docker Engine docs](https://docs.docker.com/engine/install/).
- - __GitHub authentication__ is recommended. The installer downloads ~50 release binaries and makes ~50+ GitHub API calls; unauthenticated requests are limited to 60 per hour, authenticated ones to 5,000. It uses your `gh auth login` session automatically, also under `sudo`. Alternatively, pass a [personal access token](https://github.com/settings/tokens) (no scopes needed) through `sudo`, which otherwise drops it: `sudo --preserve-env=GITHUB_TOKEN ./install.sh`.
- ### Install
- __From the latest release__ (pinned; recommended):
- ```bash
- git clone --depth 1 --branch v1.5.0 https://github.com/26zl/cybersec-toolkit.git && cd cybersec-toolkit && sudo ./install.sh
- ```
- __From `main`__ (newest tools and fixes, including unreleased work):
- ```bash
- git clone https://github.com/26zl/cybersec-toolkit.git && cd cybersec-toolkit && sudo ./install.sh
- ```
- With no flags, the installer covers the standard tools of all 18 modules. C2/phishing tools and Docker images stay opt-in unless a profile enables them (the Docker and C2 columns under [Profiles](#profiles)); `--profile full --enable-docker` installs everything the current platform supports. To install a subset:
- ```bash
- sudo ./install.sh --profile ctf # CTF tools only
- sudo ./install.sh --profile redteam --enable-docker # Red team + Docker C2
- sudo ./install.sh --module web --module recon # Specific modules
- sudo ./install.sh --tool sqlmap --tool nmap # Individual tools
- ./install.sh --dry-run --profile ctf # Preview without installing; no root needed
- ./install.sh --doctor # Read-only preflight; no root needed
- ```
- <details>
- <summary><strong>All flags</strong></summary>
- ```bash
- ./install.sh --help # Full help
- ./install.sh --list-profiles # Show profiles
- ./install.sh --list-modules # Show modules
- sudo ./install.sh --skip-heavy # Skip large/slow packages
- sudo ./install.sh --skip-pipx # Skip all pipx (Python) installs
- sudo ./install.sh --skip-go # Skip all Go tool installs
- sudo ./install.sh --skip-cargo # Skip all Cargo (Rust) installs
- sudo ./install.sh --skip-gems # Skip all Ruby gem installs
- sudo ./install.sh --skip-git # Skip all git clone installs
- sudo ./install.sh --skip-binary # Skip all binary release downloads
- sudo ./install.sh --skip-source # Skip build-from-source, snap, npm, and curl-pipe installs
- sudo ./install.sh --fast # Skip checksum verification (see Supply chain model)
- sudo ./install.sh --require-checksums # Fail if a binary release has no checksum file
- sudo ./install.sh --production # Strict checksum preset for release downloads
- sudo ./install.sh --upgrade-system # Upgrade system packages before installing
- ./install.sh --list-sessions # List install sessions and exit
- sudo ./install.sh --rollback <id|last> # Roll back a session's tools (add --yes when not on a terminal)
- ./install.sh --version # Show installer version and exit
- sudo ./install.sh --enable-docker # Pull Docker images
- sudo ./install.sh --include-c2 # Include C2/phishing frameworks (Empire and BeEF also need --enable-docker)
- sudo ./install.sh -j 8 # 8 parallel install jobs (default: 4)
- sudo ./install.sh -v # Verbose / debug output
- ```
- `--tool` installs only the named tool, without the full dependency setup. Dry-run time estimates count install entries across methods, so they can exceed the de-duplicated 670+ tool registry.
- Tuning variables (environment): `GITHUB_TOOL_DIR` (default `/opt`, `~/tools` on Termux) sets where repositories are cloned; `GO_MIN_VERSION` (default `1.21`), `PYTHON_MIN_VERSION` / `PYTHON_TRY_MAX` (`3.11` / `3.13`) and `NODE_MIN_VERSION` (`22`) set the runtime versions the bootstrap accepts; `ZYPPER_REFRESH_ATTEMPTS` / `ZYPPER_REFRESH_DELAY` (`3` / `15` seconds, doubling) tune openSUSE metadata retries; `CYBERSEC_ZYPPER_AUTO_IMPORT_KEYS=1` trusts new repository keys on refresh (see the [supply chain model](#supply-chain-model)); `PKG_AUTOREMOVE=1` adds `apt-get autoremove` to package removal (`remove.sh --remove-deps` sets it).
- </details>
- <details>
- <summary><strong>Why a full install takes 15-45 minutes</strong></summary>
- The time goes to I/O-bound work that no scripting language can speed up:
- | What takes time | Why |
- | --- | --- |
- | System packages (apt/dnf) | Downloading and unpacking `.deb`/`.rpm` packages and resolving dependencies |
- | Go tools | Downloading modules and compiling each binary |
- | pipx (Python) | Creating one isolated venv per tool and downloading wheels |
- | Cargo (Rust) crates | Compiling from source |
- | Git clones | Cloning each repository |
- | Binary releases | Downloading pre-built binaries from GitHub |
- `./install.sh --dry-run` prints the live per-method breakdown. System packages install first, in one transaction. The pipx, Go, Cargo, gem, npm, git, and binary batches then run side by side: pipx, Go, git, and binary releases install up to `-j` tools at once (4 by default), while Cargo, gem, and npm work through their lists one tool at a time. Source builds run last, one after another. To go faster: install a profile or `--module` instead of everything, `--skip-cargo` to avoid Rust compilation, `-j 8` for more parallel jobs, and an [apt-cacher-ng](https://wiki.debian.org/AptCacherNg) proxy for repeated installs.
- </details>
- ### Docker and Podman
- The prebuilt image is the installer on Ubuntu, not a sandbox. Its default command is a dry run of the `full` profile:
- ```bash
- docker run --rm ghcr.io/26zl/cybersec-toolkit # preview only
- docker run -it --name cybersec --entrypoint bash ghcr.io/26zl/cybersec-toolkit # keep a container
- sudo ./install.sh --profile ctf # inside it; reattach with: docker start -ai cybersec
- ```
- Build it yourself with `docker build -t cybersec-toolkit .`, or run a throwaway install through the bundled Compose file with `docker compose run --rm installer --profile ctf`. On Apple silicon, add `--platform linux/amd64` to `docker build` and `docker run`. Podman works as a drop-in replacement (`podman compose` needs a compose provider). The image grants the `toolkit` user passwordless sudo so the installer can manage packages; treat code inside it as root-capable.
- Every published image carries a signed build-provenance attestation. To check that the one you pulled was built by this repository's release workflow, run `gh attestation verify oci://ghcr.io/26zl/cybersec-toolkit:<version> --repo 26zl/cybersec-toolkit` (needs the GitHub CLI).
- ### Termux (Android)
- ```bash
- pkg install git
- git clone https://github.com/26zl/cybersec-toolkit.git && cd cybersec-toolkit
- ./install.sh --profile lightweight
- ```
- ### Profiles
- | Profile | Modules | Docker | C2 | Description |
- | ------- | ------- | ------ | -- | ----------- |
- | `full` | All 18 | — | yes | Complete security toolkit |
- | `ctf` | misc, crypto, pwn, reversing, stego, forensics, cracking, web, mobile, blockchain | — | — | CTF competitions |
- | `redteam` | misc, networking, recon, web, enterprise, pwn, mobile, cracking, cloud, wireless, reversing, crypto | yes | yes | Offensive security |
- | `web` | misc, networking, recon, web, llm | — | — | Web application testing |
- | `osint` | misc, recon | — | — | OSINT gathering |
- | `forensics` | misc, forensics, blueteam, reversing, stego, cracking | — | — | Digital forensics and incident response |
- | `pwn` | misc, pwn, reversing, crypto | — | — | Binary exploitation and reverse engineering |
- | `mobile` | misc, mobile, web, reversing | yes | — | Mobile application security testing |
- | `cloud` | misc, cloud, containers, networking, recon | — | — | Cloud and container security auditing |
- | `blockchain` | misc, blockchain, web, crypto | yes | — | Smart contract auditing and blockchain security |
- | `wireless` | misc, wireless, networking | — | — | WiFi, Bluetooth, and SDR security |
- | `lightweight` | misc, networking, recon, web, cracking | — | — | Hobby ethical hacking essentials (HTB, THM, bug bounty) |
- | `crackstation` | misc, cracking, crypto | — | — | Hash cracking |
- | `blueteam` | misc, blueteam, forensics, reversing, mobile, containers, networking, cloud, recon | yes | — | Defensive security, IR, malware analysis |
- Docker and C2 show what each profile enables by default. A profile that enables Docker stops with an error when Docker is not installed; install Docker first, or select the same modules with `--module` instead of the profile.
- ### Modules
- | Module | Tools | Description |
- | ------ | ----- | ----------- |
- | `misc` | 40 | Post-exploitation, social engineering, wordlists, resources, C2 (Docker + Loki) |
- | `networking` | 58 | Port scanning, packet capture, tunneling, MITM, protocol tools |
- | `recon` | 82 | Subdomain enumeration, OSINT, DNS, automated recon frameworks |
- | `web` | 60 | Vulnerability scanning, fuzzing, SQLi, XSS, CMS scanners, API testing |
- | `crypto` | 15 | RSA attacks, cipher analysis, hash attacks, constraint solving |
- | `pwn` | 36 | Exploit frameworks, binary exploitation, fuzzing, payload generation |
- | `reversing` | 35 | Disassemblers, debuggers, emulation, Java/Python reversing |
- | `forensics` | 62 | Disk/memory forensics, file carving, timeline analysis, log analysis, hardware/serial |
- | `enterprise` | 81 | Active Directory, Kerberos, Azure AD, credential harvesting, lateral movement |
- | `wireless` | 41 | WiFi cracking, Bluetooth, SDR, rogue AP |
- | `cracking` | 34 | Hash cracking (john, hashcat), brute force, wordlist generation |
- | `stego` | 15 | Image/audio steganography, detection, StegCracker |
- | `cloud` | 22 | AWS/Azure/GCP security auditing, Checkov |
- | `containers` | 15 | Docker/Kubernetes security (Grype, Syft, Kubescape, kubeaudit) |
- | `blueteam` | 40 | IDS/IPS, SIEM, incident response, threat intelligence, hardening, malware analysis (YARA, ClamAV, FLOSS, Capa, Loki) |
- | `mobile` | 18 | Android/iOS app testing, APK analysis, MobSF (Docker) |
- | `blockchain` | 15 | Smart contract auditing (Slither, Mythril, Foundry, Aderyn), blockchain forensics, Echidna (Docker) |
- | `llm` | 14 | LLM red teaming, prompt injection, jailbreak testing, AI vulnerability scanning |
- <details>
- <summary><strong>Install methods</strong> — preferred order: apt > pipx > go > cargo > binary > gem > Docker > git clone > source</summary>
- | Method | Count | Examples |
- | ------ | ----- | ------- |
- | Git clone | 193 | GitHub repos with auto-setup, resources, wordlists |
- | System packages (apt/dnf/pacman/zypper) | 172 | nmap, wireshark, john, hashcat |
- | pipx | 137 | sqlmap, impacket, bloodhound, volatility3 |
- | Go install | 63 | nuclei, subfinder, ffuf, httpx |
- | Binary release | 54 | gitleaks, chainsaw, findomain, FLOSS, Capa, Loki, Syft, Kubescape |
- | Build from source | 25 | massdns, duplicut, AFLplusplus, honggfuzz |
- | Docker | 13 | Empire, MobSF, BeEF, BloodHound, TheHive, Cortex, PentAGI |
- | Cargo (Rust) | 8 | feroxbuster, RustScan, pwninit, yara-x-cli |
- | Ruby gem | 6 | wpscan, evil-winrm, brakeman |
- | npm | 6 | promptfoo, apk-mitm, surya, solgraph, rea-agents |
- | Special | 5 | Metasploit, Foundry, Steampipe, patator (curl-pipe installers), crypto venv bootstrap |
- | Snap | 1 | zaproxy |
- </details>
- ### Post-install scripts
- All scripts support `--help` and `--version`. On Linux, `update.sh` and `remove.sh` need root (`sudo`), as do `backup.sh schedule` and `unschedule`; `verify.sh` and the other `backup.sh` commands run as your user. Termux needs no root. Without a terminal, pass `--yes` to `remove.sh` (and to `install.sh --rollback`).
- | Script | Purpose | Example |
- | ------ | ------- | ------- |
- | `scripts/verify.sh` | Check which tools are installed | `./scripts/verify.sh --module web --skip-heavy` |
- | `scripts/update.sh` | Update the tools this toolkit installed | `sudo ./scripts/update.sh --skip-system` |
- | `scripts/remove.sh` | Remove tools by module | `sudo ./scripts/remove.sh --module enterprise --yes` |
- | `scripts/remove.sh --deep-clean` | Remove all toolkit tools, then purge caches and build artifacts | `sudo ./scripts/remove.sh --deep-clean --yes` |
- | `scripts/backup.sh` | Back up and restore tool configs | `./scripts/backup.sh backup` |
- After a full removal, `--deep-clean` removes the Go module/build cache, the Cargo registry, pip/pipx/npm/gem caches, leftover venvs of the pipx tools it installed, dangling symlinks into its own trees, and log files. Venvs that other tools keep in the same pipx home (for example `pipx install --global`) stay, and so do symlinks that point anywhere else. Add `--remove-deps` to also purge Rustup toolchains.
- `update.sh` and `remove.sh` act on what `.versions` records as installed by this toolkit: a tool that was already on the system is recorded as `existing` and left alone. A record started by a release before 1.1.0 lists the host's own system packages as installed by the toolkit; `remove.sh` keeps every system package for such a record and says so.
- <details>
- <summary><strong>Tool locations</strong></summary>
- Non-system tools land in `/usr/local/bin/` on Linux and `$PREFIX/bin` on Termux; system packages use their default location (`/usr/bin/`).
- | Method | Binary location (Linux) | Binary location (Termux) | Data location |
- | ------ | ----------------------- | ------------------------ | ------------- |
- | pipx | `/usr/local/bin/` | `$PREFIX/bin/` | `/opt/pipx/` or `~/.local/pipx/` |
- | Go | `/usr/local/bin/` | `$PREFIX/bin/` | `/opt/go/` or `~/.go/` |
- | Cargo | `/usr/local/bin/` (symlinked) | `$PREFIX/bin/` (symlinked) | `~/.cargo/` |
- | Git repos | `/usr/local/bin/` (symlinked) | `$PREFIX/bin/` (symlinked) | `/opt/<repo>/` or `~/tools/<repo>/` |
- | Binary releases | `/usr/local/bin/` | Skipped (glibc incompatible with Bionic) | -- |
- The `.versions` file records what was installed, how, and when. A release directory under `/opt` that this toolkit did not create is never written to.
- </details>
- <details>
- <summary><strong>Optional Docker images</strong> (<code>--enable-docker</code>)</summary>
- If `--enable-docker` is set and Docker is missing, the installer stops and asks you to install Docker first.
- | Image | Module | Flag | Description |
- | ----- | ------ | ---- | ----------- |
- | `bcsecurity/empire` | misc | `--enable-docker --include-c2` | Empire C2 |
- | `spiderfoot/spiderfoot` | misc | `--enable-docker` | SpiderFoot OSINT |
- | `beefproject/beef` | web | `--enable-docker --include-c2` | BeEF browser exploitation |
- | `opensecurity/mobile-security-framework-mobsf` | mobile | `--enable-docker` | MobSF |
- | `specterops/bloodhound` | enterprise | `--enable-docker` | BloodHound CE |
- | `trailofbits/echidna` | blockchain | `--enable-docker` | Echidna smart contract fuzzer |
- | `checkmarx/kics:latest` | cloud | `--enable-docker` | KICS infrastructure-as-code scanner |
- | `sagemath/sagemath:latest` | crypto | `--enable-docker` | SageMath (Coppersmith, Groebner bases, curve arithmetic) |
- | `strangebee/thehive:latest` | blueteam | `--enable-docker` | TheHive IR platform |
- | `thehiveproject/cortex:latest` | blueteam | `--enable-docker` | Cortex analysis |
- | `zeek/zeek:latest` | blueteam | `--enable-docker` | Zeek network analysis |
- | `wagga40/zircolite:latest` | blueteam | `--enable-docker` | Zircolite EVTX detection |
- | `vxcontrol/pentagi:latest` | llm | `--enable-docker` | PentAGI autonomous pentesting |
- </details>
- ### Distro support
- __Debian/Ubuntu/Kali is the primary target__ and has the strongest test coverage: Kali and Parrot get the full apt set, while plain Debian/Ubuntu skip a handful of Kali-only packages. Fedora, Arch, and openSUSE skip the packages their repositories do not carry (the `-` entries in [`lib/distro_compat.tsv`](lib/distro_compat.tsv), several dozen per distro) and run in the integration workflow.
- | Platform | Status |
- | -------- | ------ |
- | __WSL__ | Supported for installs and MCP use; the wireless module and kernel-level packages are skipped. No dedicated CI job, so validate release-critical changes in a local WSL distro. See [Windows Defender false positives](#windows-defender-false-positives) if the repo lives on a Windows-mounted path. |
- | __ARM__ (aarch64/armv7) | Supported, with automatic skips for x86-only binary releases and x86-only build-from-source tools. No dedicated CI job. |
- | __Termux__ (Android) | Supported without sudo. Docker, snap, binary releases, and build-from-source are skipped (Bionic incompatible). No dedicated CI job. |
- | __Windows__ (native) | Not supported. Use WSL. |
- | __macOS__ | The installer is not supported; use the Docker image. The MCP server runs on macOS in host mode (`--local`). |
- | __Other Linux distros__ | Distros without `apt`/`dnf`/`pacman`/`zypper` (NixOS, Gentoo, Void, Alpine, Slackware, …) are detected and blocked with a clear error. Use the [Docker image](#docker-and-podman). |
- ### What the installer changes
- Beyond installing packages, an install can change the system in ways `remove.sh` does not undo:
- - __apt sources__: the Metasploit repository (`/etc/apt/sources.list.d/metasploit-framework.list`, key in `/usr/share/keyrings/metasploit-framework.gpg`), which `remove.sh` deletes again when it removes a Metasploit this toolkit installed; and, through NodeSource's setup script, a NodeSource repository and key, which stay. apt keeps trusting NodeSource after removal; delete its source by hand if you no longer want that.
- - __Arch__: `ParallelDownloads` is enabled in `/etc/pacman.conf`.
- - __snapd__ on apt-based distros, for snap-only tools.
- - __Runtimes__: the Go SDK in `/usr/local/go`; rustup, cargo, and uv in the invoking user's home.
- - __Tools__ in `/opt`, `/opt/pipx`, and `/usr/local/bin`.
- Data the toolkit keeps, stored only on this machine:
- - `.versions`, `.install_sessions/`, and `*.log` in the checkout: install provenance and logs.
- - `~/.local/state/cybersec-tools-mcp/`: the MCP audit log and its rotations, `remote_hosts.json`, and the agent guard's `guard-session*` markers and `guard-denials.log`.
- - `~/cybersec_tools_backup/`: encrypted configuration backups.
- - `writeups/` in the checkout (git-ignored).
- `remove.sh --deep-clean` clears caches and the checkout's logs, but not the MCP state directory, backups, or writeups; delete those yourself when you no longer need them.
- ### Supply chain model
- The installer downloads and runs code from the internet. On Linux it runs as root (`sudo`); on Termux it runs in the app's user sandbox.
- - __System packages__: signed by your distro's repositories (apt, dnf, pacman, zypper, pkg). On openSUSE, `zypper refresh` trusts new or rotated repository keys automatically only when `CI=true` or `CYBERSEC_ZYPPER_AUTO_IMPORT_KEYS=1` is set.
- - __pipx/Go/Cargo/Gem/npm__: fetched from their registries without signature verification; pipx tools are isolated in venvs. Go, Cargo, and Gem builds run as the invoking user; pipx and global npm installs run as root, so package build backends and npm lifecycle scripts execute with root privileges.
- - __Binary releases__: SHA256-verified using upstream checksum files, exact-asset GitHub release digests, or reviewed repository/tag/asset checksums in `lib/release_checksums.tsv`. A mismatch always fails; `--require-checksums` or `--production` also fails when verification data is unavailable. These checks establish download integrity, not independent publisher authentication. `--fast` skips ordinary release verification and cannot be combined with strict flags; private runtime dependencies always require verification.
- - __Runtime bootstraps__: the rustup, uv, and cargo-binstall installers and NodeSource's setup script (run as root) are fetched over HTTPS and sanity-checked before they run, but not signature-verified; in strict mode (`--production`/`--require-checksums`) the rustup, uv, and cargo-binstall installers are skipped when they would run as root (i.e. without `sudo` from a normal user), and NodeSource's script is always skipped in favour of the distro's signed `nodejs`/`npm`. cargo-binstall then downloads prebuilt Rust binaries where available; `--skip-source` skips its installer on a fresh host, so Rust tools compile from crates.io.
- - __Go SDK__: installed only when the system Go is older than `GO_MIN_VERSION`, and then kept until go.dev publishes a newer release. The tarball is SHA256-verified against go.dev, or against checksums embedded for the fallback release when go.dev's API cannot be reached; strict mode fails when neither is available.
- - __Git repos__: cloned at HEAD; the repo's own `setup.py` is never run. `requirements.txt` installs into a per-repo venv as the invoking user, where dependency sdists can still build, and outside strict mode (`--production` or `--require-checksums`) a failed pinned install is retried with `==` relaxed to `>=`.
- - __Build from source__: runs `make` as the invoking user, not root. Review what you build.
- - __MCP Python dependencies__: resolved by `uv` with a 5-day `exclude-newer` window, and Dependabot waits the same 5 days. This does not apply to the security tools themselves, which follow their upstream release channels.
- - __Toolkit Docker images__: Ubuntu and uv are digest-pinned; apt packages resolve from the current signed Ubuntu repositories, so rebuilds are not bit-for-bit reproducible.
- - __Optional tool images__: pulled by mutable tags, several of them `latest`. `--production` does not pin or verify them.
- `--production` does not pin Git clones, language-package registries, or build-from-source tools; those track their upstream release channels.
- ### Windows Defender false positives
- On a Windows-mounted path (e.g. `C:\Users\<you>\...`, or any folder visible from Windows while you work in WSL), Microsoft Defender and other AV products may quarantine individual files. IOC tables, sample obfuscated PowerShell, malware-analysis snippets, and exploit strings in `.claude/skills/`, `writeups/`, and parts of `mcp_server/` contain the same byte patterns real attackers use. Common verdicts include `Trojan:Script/Wacatac.B!ml`, `HackTool:*`, and generic `Heur.*`. These are false positives for a security toolkit.
- <details>
- <summary><strong>Workarounds</strong></summary>
- 1. __Exclude the repo folder__ (recommended on a personal dev box), from an elevated PowerShell:
- ```powershell
- Add-MpPreference -ExclusionPath "C:\path\to\cybersec-toolkit"
- ```
- 2. __Restore files from quarantine__ via Windows Security → Virus & threat protection → Protection history → "Allow on device". This is per file and does not prevent re-detection.
- 3. __Keep the repo inside the WSL filesystem__ (e.g. `~/cybersec-toolkit`). Defender does not scan WSL2's virtual disk by default. `scripts/sync-wsl.sh` does this for the MCP server.
- Files removed by Defender show up as `D` in `git status`; restore them with `git checkout -- <path>` once the exclusion is in place.
- </details>
- ## MCP server
- The server gives MCP-capable clients read access to the 670+ tool registry, install status and recommendations, and governed execution of installed tools. The agent knows every tool, which ones are available, and how to chain them.
- ### Supported clients
- Claude Code, Codex, Gemini CLI, OpenCode and the GitHub Copilot CLI pick up the tracked configs automatically; Claude Desktop, Copilot in VS Code, Hermes Agent, OpenClaw, DeepSeek Harness, Cursor, Cline, Goose, Continue and LM Studio connect through their own MCP settings, and Ollama or Open WebUI through an MCP host or bridge. The support matrix, with skill discovery and test status per client, lives in [`docs/AI_CLIENTS.md`](docs/AI_CLIENTS.md).
- Coordinating several agents across any MCP client is in [`docs/ORCHESTRATION.md`](docs/ORCHESTRATION.md).
- The server is published to the [official MCP Registry](https://registry.modelcontextprotocol.io/) as `io.github.26zl/cybersec-toolkit` and listed on Glama:
- <a href="https://glama.ai/mcp/servers/26zl/cybersec-toolkit"><img width="380" height="200" src="https://glama.ai/mcp/servers/26zl/cybersec-toolkit/badge" alt="Cybersec Toolkit MCP server on Glama" /></a>
- ### What the AI can do
- | Tool | What it does |
- | ---- | ------------ |
- | `list_tools` | List/filter all 670+ tools by module, method, or install status (includes URLs) |
- | `check_installed` | Check if a tool is installed (6 detection strategies) |
- | `get_tool_info` | Full details: method, module, URL, install/update/remove commands |
- | `get_module_info` | Deep-dive a module: all tools, install status, which profiles use it |
- | `get_profile_tools` | See every tool a profile installs, grouped by module |
- | `suggest_for_ctf` | Curated tool recommendations for 14 CTF challenge categories |
- | `suggest_for_bounty` | Bug bounty tool recommendations for 7 target types with methodology and common vulns |
- | `guided_assessment` | Companion-first solve assistant for an authorized target: classifies the target/finding, returns triage gates, recommends skills, picks tools from all modules/profiles, and guides step by step; opt-in `autonomous` starts an auto-solver loop over `run_tool`, `run_pipeline`, and the separately gated `run_script` |
- | `get_cve_info` | Map a CVE id or nickname (e.g. `log4shell`) to curated skills, registry tools, modules, and live NVD/KEV/EPSS lookup commands |
- | `recommend_install` | Natural-language → profile/module/tool recommendation |
- | `list_profiles` | All 14 profiles with tool counts and install commands |
- | `run_tool` | Execute installed tools safely (sanitized args, network policy, rate limiting, audit logging); supports remote execution over SSH |
- | `run_pipeline` | Pipe tools together without a shell (`strings binary \| grep flag`) |
- | `run_script` | Explicit opt-in Python/Bash execution, with per-script venv selection |
- | `manage_remote_hosts` | Add, remove, list, and test SSH remote hosts for remote tool execution |
- <details>
- <summary><strong>Usage examples — full workflows, offense to defense</strong></summary>
- The agent can query every tool and its install state, chain governed tool calls, parse the output, and pivot on what it finds. Script execution requires a separate opt-in.
- #### External recon → attack surface (needs `CYBERSEC_MCP_ALLOW_EXTERNAL=1`, authorized scope only)
- - __"Enumerate the attack surface for target.com and flag anything exploitable"__ — fans out `amass` / `subfinder` → resolves and probes with `httpx` → fingerprints with `whatweb` → runs `nuclei` templates → content discovery with `ffuf`, then ranks hosts by exposure and proposes next steps
- - __"Found an open redirect on `/go?url=` — weaponize it"__ — verifies with `curl`, then builds an SSRF / OAuth-token-theft PoC and probes for an exploitable callback
- #### Web exploitation
- - __"Confirm and exploit the SQLi on the login endpoint"__ — `sqlmap` to confirm and dump (destructive `--os-shell`/`--os-cmd` are policy-blocked), then `run_script` to automate the auth bypass and pull just enough for a PoC
- - __"GraphQL introspection is on — map it and hunt IDOR"__ — pulls the schema, generates queries, fuzzes object IDs, and diffs authenticated vs unauthenticated responses
- #### Active Directory / internal
- - __"Low-priv creds on 10.10.0.0/24 — find a path to Domain Admin"__ — collects with `bloodhound`, kerberoasts with `netexec` (`--kerberoasting`), cracks the TGS in `hashcat`, then validates lateral movement with `netexec`, all on a Kali box over SSH (`manage_remote_hosts`, host mode)
- - __"Check for DCSync rights and dump if the path exists"__ — enumerates replication ACLs, then runs secretsdump (the `impacket` tool) against the DC
- #### Binary exploitation & reversing
- - __"Build a ret2libc exploit for this 64-bit binary"__ — triages with `checksec` / `readelf`, finds gadgets with `ROPgadget`, leaks libc via a `puts@plt` call, then writes the full `pwntools` chain in `venv="pwntools"` and pops a shell locally
- - __"Recover the algorithm from this stripped binary"__ — `objdump` / `radare2` disassembly piped into targeted analysis, then a `run_script` reimplementation to verify behavior
- #### Crypto
- - __"Break this RSA — small `e`, several ciphertexts"__ — detects the attack (Håstad / common modulus / Wiener) and solves it with `pycryptodome` + `sympy` in a venv, returning plaintext
- - __"This JWT is HS256 with a weak key"__ — cracks the signing secret and forges an admin token
- #### Blue team · detection engineering
- - __"Write a Sigma rule for this technique and convert it to my SIEM"__ — authors the rule and renders it for the target backend (Splunk / Elastic) via `sigma-cli`
- - __"Hunt these Windows event logs for lateral movement"__ — runs `chainsaw` over the EVTX with Sigma rules, then summarizes hits by host and timeline
- - __"Build YARA rules from these samples and scan the tree"__ — generates `yara` signatures and runs them recursively
- #### DFIR · malware triage
- - __"Timeline this memory dump"__ — sweeps `volatility3` plugins (`pslist`, `netscan`, `malfind`) and chains them into one narrative
- - __"Hunt for C2 beaconing in this pcap"__ — `tshark` / `tcpdump` extraction → `suricata` rules → flags periodic callbacks
- - __"Statically triage this suspicious file"__ — `file` → `strings` → `capa` / `yara`, then extracts IOCs for enrichment
- #### Cloud · containers · ops
- - __"Audit this AWS account for public S3 and risky IAM"__ — runs `prowler` / `scoutsuite` and surfaces only the high-severity findings
- - __"Scan this image and k8s manifests before deploy"__ — `grype` image scan plus `kubescape` config checks
- - __"What's my redteam coverage — and fix the gaps"__ — diffs `get_profile_tools("redteam")` against install status and emits the exact install commands
- #### Mobile · wireless · blockchain
- - __"Static-analyze this APK for secrets and insecure storage"__ — `apktool` / `jadx` decompile → MobSF-style checks, then greps for keys and endpoints
- - __"Audit this Wi-Fi capture"__ — parses the handshake and runs `aircrack-ng` / `hashcat` against it
- - __"Review this Solidity contract for reentrancy"__ — runs `slither-analyzer` / `mythril` and explains the findings
- `run_tool` and `run_pipeline` are argument-sanitized, network-policed, rate-limited, and audit-logged, and destructive flags (`--os-shell`, `-rf`, `--exploit`, …) are blocked. `run_script` is off by default: enabling it runs arbitrary code with the server user's filesystem and network permissions (inside the VM by default, on your host with `--local`), and the external-target policy does not constrain it. Use only against systems you are authorized to test.
- </details>
- ### Sandbox and host mode
- `scripts/mcp-launch.sh` starts the server inside a Kata Containers VM unless you pass `--local` or set `CYBERSEC_SANDBOX_MODE=local`. The VM is created by a [Sandcastle](https://github.com/mattpocock/sandcastle) isolated-sandbox provider (`sandbox/kata.mjs`) that pins the Kata runtime; the same provider can also back a Sandcastle agent-orchestration loop instead of an MCP client. Startup fails closed: a missing runtime, sandbox image, KVM device, Node.js, or launcher dependency, an image built from older server sources, or a scope that cannot be enforced stops the server with the reason instead of falling back to the host. `./install.sh --doctor` reports sandbox readiness. Setup, tuning, and the threat model are in [`docs/SANDBOX.md`](docs/SANDBOX.md).
- - __The VM has its own tool set.__ The sandbox image ships the MCP server plus `file`, `git`, `binutils`, `nmap`, `curl`, and Python. Tools installed on the host are not visible inside it, and `check_installed` and the advisors report the guest's tools. Bake a profile into the image instead, and rebuild after pulling server changes, because the image carries its own copy of the server:
- ```bash
- make sandbox-image TOOLKIT_PROFILE=ctf
- ```
- - __Files__: the VM sees no host path unless `CYBERSEC_SANDBOX_WORKSPACE` names an absolute directory, which appears as `/workspace` (read-only with `CYBERSEC_SANDBOX_WORKSPACE_RO=1`). Use a case directory outside this checkout; one inside it is refused, because the client reads instruction files and skills from the project tree. Pass guest paths to `run_tool`.
- - __Network__: the VM uses Docker's default bridge. Set `CYBERSEC_SANDBOX_SCOPE` to a scope file to limit it to the engagement's destinations, or `CYBERSEC_SANDBOX_NETWORK=none` for offline analysis.
- - __Privileges__: uid 10001, all capabilities dropped, `no-new-privileges`, and 2 GB / 2 vCPUs / 512 processes by default. Raw-socket scans (`nmap -sS`, `-sU`, OS detection) are not available in the sandbox: the guest user is unprivileged and `no-new-privileges` is set, so an added `NET_RAW` capability never becomes effective. Use connect scans (`-sT`) or `--local` mode.
- - __Host mode only__: remote execution over SSH (`manage_remote_hosts`) and venvs under `~/.ctf-venvs/` that you created on the host.
- - __Audit__: records leave the VM on a stderr side channel and are appended to the host log, so the trail outlives the VM.
- ### Client setup
- Claude Code reads the tracked `.mcp.json`:
- ```json
- {
- "mcpServers": {
- "cybersec-tools": {
- "command": "bash",
- "args": [
- "-lc",
- "cd \"$(git rev-parse --show-toplevel)\" && exec bash scripts/mcp-launch.sh"
- ],
- "env": {
- "CYBERSEC_MCP_ALLOW_EXTERNAL": "0",
- "CYBERSEC_MCP_ALLOW_SCRIPTS": "0"
- }
- }
- }
- }
- ```
- The login shell (`bash -lc`) picks up `node` and `uv` from your profile, so profile scripts must not print to stdout, which carries the MCP protocol. Other clients use the same launcher; from any directory:
- ```bash
- bash /path/to/cybersec-toolkit/scripts/mcp-launch.sh # Kata VM (default)
- bash /path/to/cybersec-toolkit/scripts/mcp-launch.sh --local # host, no VM boundary
- ```
- - __Codex__: the project `.codex/config.toml` resolves the Git root first, so it works from any subdirectory. If Codex ignores project config, copy the `[mcp_servers.cybersec-tools]` block into `~/.codex/config.toml`.
- - __Cursor / Continue / Cline / Goose__: add the launch command in the client's MCP settings, with an absolute path if the client's working directory is not the repo root.
- - __LM Studio (≥0.3.17)__: an MCP host itself. Add the server to its `mcp.json` (same `mcpServers` shape as `.mcp.json`) with an absolute path. MCP over LM Studio's API needs ≥0.4.0 and an MCP-capable endpoint such as `/api/v1/chat` or `/v1/responses`.
- - __Ollama and other local models__: a model runtime does not speak MCP. Put an MCP-capable host in front of it (OpenCode, Hermes, OpenClaw, [Kit](https://github.com/mark3labs/kit), LM Studio, Cline, Continue, Goose, or Open WebUI through an MCP→OpenAPI bridge such as `mcpo`) and point that host at the launcher.
- Start with this one server and keep scripts and external targets off unless you have an authorized scope; prefer hosts with human-in-the-loop tool approval. Vendor-neutral repository instructions live in [`AGENTS.md`](AGENTS.md); Claude Code reads [`CLAUDE.md`](CLAUDE.md), Gemini CLI reads [`GEMINI.md`](GEMINI.md).
- <details>
- <summary><strong>Connect from WSL (e.g. Kali Linux)</strong></summary>
- The server speaks stdio, so a Windows client can launch it inside WSL. This runs it directly in WSL, without the Kata VM (the equivalent of `--local`):
- ```json
- {
- "mcpServers": {
- "cybersec-tools": {
- "command": "wsl",
- "args": [
- "-d", "kali-linux",
- "bash", "-lc",
- "cd ~/cybersec-toolkit/mcp_server && uv run fastmcp run server.py --transport stdio --no-banner"
- ]
- }
- }
- }
- ```
- Use a clone inside the WSL filesystem, or run `scripts/sync-wsl.sh` from a Windows checkout to copy the server to `~/cybersec-toolkit` in WSL (uv cannot create a venv on NTFS). Passing `CYBERSEC_MCP_*` variables from Windows needs `WSLENV`; see [`mcp_server/README.md`](mcp_server/README.md).
- </details>
- <details>
- <summary><strong>Connect from Docker</strong></summary>
- Runs the server in the installer image. This is an ordinary container, not the Kata VM, and its user has passwordless sudo:
- ```json
- {
- "mcpServers": {
- "cybersec-tools": {
- "command": "docker",
- "args": [
- "run", "-i", "--rm",
- "-e", "CYBERSEC_MCP_ALLOW_EXTERNAL=0", "-e", "CYBERSEC_MCP_ALLOW_SCRIPTS=0",
- "--entrypoint", "bash", "cybersec-toolkit",
- "-c",
- "cd /opt/cybersec-toolkit/mcp_server && uv run fastmcp run server.py --transport stdio --no-banner"
- ]
- }
- }
- }
- ```
- </details>
- ### Script execution
- `run_script` lets the agent write and run Python or Bash. Enable it with `"CYBERSEC_MCP_ALLOW_SCRIPTS": "1"` in the client's `env` block. Scripts get the server process's filesystem and network permissions (the VM by default, your user in `--local` mode), and `CYBERSEC_MCP_ALLOW_EXTERNAL` does not constrain them. Review generated code and scope before opting in.
- Python libraries without console scripts live in named venvs under `~/.ctf-venvs/` (override with `CYBERSEC_MCP_VENVS_DIR`), selected per script with the `venv` parameter. `./install.sh --module crypto` creates `~/.ctf-venvs/crypto` with `pycryptodome`, `sympy`, `gmpy2`, `numpy`, `z3`, `fpylll` (+ `cysignals`, which fpylll needs at import time but does not declare), and `cypari2`, so the agent can call `run_script(code, venv="crypto")`. In the sandbox, venvs are guest paths: build the image with `TOOLKIT_PROFILE=ctf` to get `crypto`. Some packages need an older Python, for example pwntools:
- ```bash
- python3.12 -m venv ~/.ctf-venvs/pwntools
- ~/.ctf-venvs/pwntools/bin/pip install pwntools z3-solver
- ```
- Without a named venv, scripts see FastMCP and the standard library; `cd mcp_server && uv sync --extra ctf-core` adds `requests`, `pycryptodome`, `beautifulsoup4`, Pillow, and NumPy.
- Reusable helpers the agent writes for you (exploits, multi-step solvers, parsers, protocol helpers) are saved under `manual_scripts/`. In companion mode the agent proposes a script and runs it only after you approve; in `autonomous` mode it writes and runs scoped helpers when tools and pipelines stop making progress. Plain recon and HTTP requests stay `run_tool` calls.
- ### Test the server
- ```bash
- cd mcp_server && uv run fastmcp dev inspector server.py
- ```
- This opens the MCP Inspector for exercising each tool interactively. [`mcp_server/README.md`](mcp_server/README.md) covers Claude Desktop setup and the full server reference.
- ## Agent Skills
- 872 Agent Skills live in `.claude/skills/`, the canonical tree that Claude Code discovers directly. Skills load on demand for the task at hand instead of occupying context permanently. 31 are project-authored and 841 are curated from open-source projects, each attributed in [`THIRD_PARTY_NOTICES.md`](THIRD_PARTY_NOTICES.md):
- - 10 project developer skills (`add-tool`, `validate-all`, `module-scaffold`, `writeup-template`, `mcp-sync-check`, `security-wordlists`, `security-payloads`, `guided-assessment`, `skill-dependency-audit`, `skill-curation-router`)
- - 4 cross-skill coordinators (`finding-triage`, `security-comms`, `authorization-gate`, `evidence-hygiene`) that route findings, communication, authorization checks, and evidence sanitization
- - 7 coverage-gap anchors (GRC/privacy, AI/LLM security, IoT/embedded/hardware, mainframe, telecom/5G, SAP/ERP, supply-chain/product security)
- - 6 CTF methodology skills (`ctf-crypto`, `ctf-pwn`, `ctf-web`, `ctf-rev`, `ctf-forensics`, `ctf-stego`) and 4 bug bounty methodology skills (`bounty-recon`, `bounty-web`, `bounty-api`, `bounty-mobile`)
- - 754 operational how-tos from [mukul975/Anthropic-Cybersecurity-Skills](https://github.com/mukul975/Anthropic-Cybersecurity-Skills) (Apache 2.0)
- - 58 offensive methodology skills from [SnailSploit Claude-Red](https://github.com/SnailSploit/Claude-Red) (MIT)
- - 14 code audit skills from [Trail of Bits](https://github.com/trailofbits/skills) (CC-BY-SA 4.0)
- - 10 bug bounty workflow skills from [BugHunter (Agentic-Bug-Hunter)](https://github.com/awarexone/Agentic-Bug-Hunter) (MIT)
- - 4 high-level workflows from [Transilience](https://github.com/transilienceai/communitytools) (MIT)
- - 1 coding-agent workflow skill from [multica-ai/andrej-karpathy-skills](https://github.com/multica-ai/andrej-karpathy-skills) (MIT)
- Source and category index: [`.claude/skills/SKILLS.md`](.claude/skills/SKILLS.md). Ranking and curation: `.claude/skills/CURATION.md` and `curation.json`, regenerated with `python3 scripts/curate_claude_skills.py --write`.
- __As a Claude Code plugin.__ The repo doubles as a [plugin marketplace](https://docs.claude.com/en/docs/claude-code/plugins), so any project can pull in the skill library without cloning:
- ```text
- /plugin marketplace add 26zl/cybersec-toolkit
- /plugin install cybersec-toolkit@cybersec-toolkit
- ```
- The plugin carries the skills only; the MCP server is configured separately (see [MCP server](#mcp-server)).
- __In other clients.__ OpenCode, Codex, Gemini CLI, GitHub Copilot, Cursor, Cline, Goose, Hermes, OpenClaw, and DeepSeek Harness support Agent Skills through their own paths. `scripts/sync-skills.sh` mirrors `.claude/skills/` into the git-ignored `.agents/skills/` for clients that read that location (`--check` reports drift; `make setup` runs it). Continue and LM Studio do not document automatic skill discovery; give them selected skill content as rules or context instead. Details: [`docs/AI_CLIENTS.md`](docs/AI_CLIENTS.md).
- __Helper-script dependencies.__ Some vendored skills include helper scripts with optional Python imports, declared in [`.claude/skills/requirements.txt`](.claude/skills/requirements.txt) and generated from the import inventory. `scripts/validate_claude_skills.py` checks skill metadata, index counts, curation freshness, and helper-script syntax.
- ```bash
- python3 scripts/audit_skill_dependencies.py --check-declared # verify declarations
- python3 -m pip install -r .claude/skills/requirements.txt # optional, ideally in a venv
- ```
- ## Development
- Contributions are welcome: testing installs on different distros, adding missing tools, fixing package mappings, improving MCP workflows, writing example use cases, and reporting rough edges from real CTF, lab, bug bounty, pentest, DFIR, or defensive work. Open an issue for bigger changes or send a focused PR for small fixes; [`CONTRIBUTING.md`](CONTRIBUTING.md) has the validation checklist.
- ```bash
- git clone https://github.com/26zl/cybersec-toolkit.git && cd cybersec-toolkit
- make setup # submodules, MCP deps, sandbox deps, skill mirror
- make check # lint, validators, bats, pytest, sandbox tests
- ```
- `make help` lists every target; the raw commands are in [`AGENTS.md`](AGENTS.md). The MCP Python project resolves dependencies with `uv` and `exclude-newer = "5 days"`, so fresh releases are ignored for five days to limit the blast radius of a compromised upload; Dependabot and the weekly uv update workflow use the same cooldown. Run the shell tests on Linux, macOS, or WSL: native Windows checkouts can rewrite the Bats submodules with CRLF and fail with `$'\r'`.
- Release notes for every version, including security fixes and upgrade steps, are on the [GitHub Releases](https://github.com/26zl/cybersec-toolkit/releases) page; `git log $(git describe --tags --abbrev=0)..` shows what has landed since the latest release.
- ## Star History
- <a href="https://www.star-history.com/?repos=26zl%2Fcybersec-toolkit&type=date&legend=top-left">
- <picture>
- <source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/chart?repos=26zl/cybersec-toolkit&type=date&theme=dark&legend=top-left" />
- <source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/chart?repos=26zl/cybersec-toolkit&type=date&legend=top-left" />
- <img alt="Star History Chart" src="https://api.star-history.com/chart?repos=26zl/cybersec-toolkit&type=date&legend=top-left" />
- </picture>
- </a>
- ## License
- MIT License. See [LICENSE](LICENSE).
- The repository also redistributes third-party components under their own terms, including some under CC-BY-SA-4.0 (ShareAlike, not relicensable to MIT). If you redistribute or adapt bundled content, follow those terms; see [`THIRD_PARTY_NOTICES.md`](THIRD_PARTY_NOTICES.md).
- Contribution workflow: [`CONTRIBUTING.md`](CONTRIBUTING.md). Community expectations: [`CODE_OF_CONDUCT.md`](CODE_OF_CONDUCT.md). Vulnerability reporting: [`SECURITY.md`](SECURITY.md).
- ## Disclaimer
- This project is provided for educational, defensive, and explicitly authorized
- security testing only. Use it only on systems you own or have written permission
- to assess, and follow all applicable laws, rules of engagement, third-party tool
- licenses, and service terms.
- The toolkit includes dual-use offensive and defensive tools. Some commands can
- scan networks, execute exploits, modify systems, or trigger security alerts.
- MCP/AI integrations are guarded by safety policies, but users remain responsible
- for reviewing scope, prompts, commands, and outputs before running actions.
- This repository does not redistribute the security tools themselves; it installs
- publicly available, open-source projects from their official upstream sources at
- install time. It is intended for lawful, authorized use only.
- The project is provided "as is", without warranty. Maintainers are not
- responsible for misuse, damage, data loss, service disruption, or legal
- consequences from using this toolkit.
- Third-party content is bundled under its original license — see
- [`THIRD_PARTY_NOTICES.md`](THIRD_PARTY_NOTICES.md).
.claude/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.")
.claude/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.")
.claude/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()
.claude/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)
.claude/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.