awesome-dfir-skills
A curated collection of DFIR skills and workflows for InfoSec practitioners.
Safety scan
A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.
Badge for your README
Markdown
[](/listings/tsale-awesome-dfir-skills)HTML
<a href="/listings/tsale-awesome-dfir-skills"><img src="/api/listings/tsale-awesome-dfir-skills/badge.svg" alt="findsafeskills safety rating" /></a>Install
Install instructions from the README
As written by the repo's author. findsafeskills has not verified these steps.
1. Pick a skill from `skills/README.md` 2. Copy/paste it into your AI assistant (Claude, Codex, etc.) 3. Feed it your artifacts when prompted 4. Watch the magic happen ✨
**Pro tip:** Keep placeholders like `{{time_window}}` as-is—fill them in when the skill asks for them.
---
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.
README.md · README · 99 lines
View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)
- # 🔥 awesome-dfir-skills
- [](https://awesome.re)
- [](http://makeapullrequest.com)
- [](#)
- A community-driven collection of DFIR / incident response **skills**: reusable prompts, workflows, and helper files that help practitioners move faster, stay consistent, and maybe—just maybe—get some sleep.
- ---
- ## 🚀 Quick Start
- 1. Pick a skill from `skills/README.md`
- 2. Copy/paste it into your AI assistant (Claude, Codex, etc.)
- 3. Feed it your artifacts when prompted
- 4. Watch the magic happen ✨
- **Pro tip:** Keep placeholders like `{{time_window}}` as-is—fill them in when the skill asks for them.
- ---
- ## 🤔 What's a "Skill" Anyway?
- Think of a skill as a **cheat code for IR**. It's a small, reusable artifact you can copy/paste into your AI assistant or playbook to get consistent, high-quality outputs every time.
- Each skill is designed to:
- | Feature | Why It Matters |
- |---------|----------------|
- | 📥 Clear inputs & outputs | No guessing games |
- | 🎯 Explicit about unknowns | Fewer hallucinations, more facts |
- | 🔒 Safe-by-default | Evidence handling & privacy baked in |
- ---
- ## 📁 Repository Layout
- ```
- skills/
- ├── README.md # Start here → skill catalog
- ├── _templates/
- │ └── skill.md # Template for new skills
- └── <category>/
- └── <skill-id>/
- ├── skill.md # The skill entrypoint
- └── helpers/ # Query snippets, regex, parsers
- ```
- ---
- ## 🛠️ Platform Setup
- ### Claude Desktop / Claude.ai
- Skills are folders of instructions that Claude loads dynamically:
- 1. Use the skill's **Skill prompt** as workflow instructions
- 2. Provide inputs in-chat when prompted
- 3. Keep `{{placeholders}}` intact—fill values in the corresponding sections
- ### OpenAI / Codex
- Codex loads skills from a dedicated folder (e.g., `$REPO_ROOT/.codex/skills`):
- 1. Mirror or symlink skills from `skills/` to your Codex skill location
- 2. Invoke skills explicitly (mention them) or let Codex pick them up implicitly
- 3. Provide artifacts as inputs; keep `{{...}}` placeholders as-is
- ---
- ## 🤝 Contributing
- ### How to Add a Skill
- 1. Copy `skills/_templates/skill.md`
- 2. Create `skills/<category>/<skill-id>/skill.md`
- 3. Keep it practical, tool-agnostic where possible
- 4. Test on real (or realistic) artifacts
- **Coming soon:** Metadata validator and detailed contribution guidelines.
- ---
- ## 💡 Inspiration
- - [Claude Skills](https://support.claude.com/en/articles/12512176-what-are-skills) — Anthropic's skill system
- - [OpenAI Codex Skills](https://developers.openai.com/codex/skills/) — OpenAI's approach
- ---
- ## 📜 License
- MIT — Use it, fork it, improve it.
- ---
- <p align="center">
- <strong>Made with ☕ and mild panic by the DFIR community</strong>
- </p>
skills/analysis/malware-analysis-tr/scripts/triage.py · Bundled script · 1,152 lines · 1 finding marked
- #!/usr/bin/env python3
- """
- Malware Triage - Multi-source threat intelligence lookup.
- API keys can be configured via:
- 1. Config file: ~/.config/malware-triage/config.json
- 2. Environment variables: VIRUSTOTAL_API_KEY, ABUSEIPDB_API_KEY
- 3. Command line: --vt-key, --abuseipdb-key
- """
- import argparse
- import hashlib
- import json
- import os
- import re
- import sys
- import time
- from datetime import datetime, timezone
- from pathlib import Path
- from typing import Optional
- from urllib.parse import quote
- # Check for requests library
- try:
- import requests
- except ImportError:
- print("Error: requests library required. Install with: pip install requests --break-system-packages")
- sys.exit(1)
- def load_config() -> dict:
- """
- Load API keys from config file.
- Config file locations (in order of priority):
- 1. Skill's own config directory (bundled with skill)
- 2. /mnt/user-data/uploads/config.json (Claude Desktop uploads)
- 3. ~/.config/malware-triage/config.json
- 4. ./config.json (current directory)
- """
- # Get the skill's directory (parent of scripts/)
- script_dir = Path(__file__).parent
- skill_dir = script_dir.parent
- config_paths = [
- # Bundled with skill
- skill_dir / "config" / "config.json",
- skill_dir / "config" / "api_keys.json",
- skill_dir / "config.json",
- # Claude Desktop uploads
- Path("/mnt/user-data/uploads/config.json"),
- Path("/mnt/user-data/uploads/api_keys.json"),
- # User home config
- Path.home() / ".config" / "malware-triage" / "config.json",
- Path.home() / ".malware-triage.json",
- # Current directory
- Path("config.json"),
- ]
- for config_path in config_paths:
- if config_path.exists():
- try:
- with open(config_path) as f:
- config = json.load(f)
- print(f"[*] Loaded config from: {config_path}", file=sys.stderr)
- return config
- except (json.JSONDecodeError, IOError) as e:
- print(f"[!] Failed to load {config_path}: {e}", file=sys.stderr)
- continue
- return {}
- def get_api_key(key_name: str, cli_value: Optional[str] = None) -> Optional[str]:
- """
- Get API key from multiple sources (priority order):
- 1. Command line argument
- 2. Environment variable
- 3. Config file
- """
- # CLI takes priority
- if cli_value:
- return cli_value
- # Then environment variable
- env_key = os.environ.get(key_name)
- if env_key:
- return env_key
- # Finally config file
- config = load_config()
- config_key_map = {
- "VIRUSTOTAL_API_KEY": ["virustotal_api_key", "vt_api_key", "virustotal"],
- "ABUSEIPDB_API_KEY": ["abuseipdb_api_key", "abuseipdb"],
- "ABUSECH_AUTH_KEY": ["abusech_auth_key", "abuse_ch_auth_key", "malwarebazaar_auth_key", "auth_key"],
- }
- possible_keys = config_key_map.get(key_name, [key_name.lower()])
- for config_key in possible_keys:
- if config_key in config:
- return config[config_key]
- return None
- def create_default_config():
- """Create a default config file template."""
- config_dir = Path.home() / ".config" / "malware-triage"
- config_path = config_dir / "config.json"
- if config_path.exists():
- print(f"Config already exists: {config_path}")
- return
- config_dir.mkdir(parents=True, exist_ok=True)
- default_config = {
- "abusech_auth_key": "YOUR_ABUSECH_AUTH_KEY_HERE",
- "virustotal_api_key": "YOUR_VT_API_KEY_HERE",
- "abuseipdb_api_key": "YOUR_ABUSEIPDB_API_KEY_HERE",
- }
- with open(config_path, "w") as f:
- json.dump(default_config, f, indent=2)
- print(f"Created config file: {config_path}")
- print("Edit this file with your API keys.")
- print()
- print("Get your keys from:")
- print(" - abuse.ch (MalwareBazaar/ThreatFox): https://auth.abuse.ch/")
- print(" - VirusTotal: https://www.virustotal.com/gui/my-apikey")
- print(" - AbuseIPDB: https://www.abuseipdb.com/account/api")
- class ThreatIntelClient:
- """Base class for threat intel API clients."""
- def __init__(self, api_key: Optional[str] = None):
- self.api_key = api_key
- self.session = requests.Session()
- self.session.headers.update({
- "User-Agent": "MalwareTriage/1.0 (Threat Intelligence Lookup Tool)",
- "Accept": "application/json",
- "Content-Type": "application/x-www-form-urlencoded",
- })
- def _safe_request(self, method: str, url: str, **kwargs) -> Optional[dict]:
- """Make a request with error handling."""
- try:
- resp = self.session.request(method, url, timeout=30, **kwargs)
- if resp.status_code == 200:
- return resp.json()
- elif resp.status_code == 404:
- return {"error": "not_found", "status": 404}
- elif resp.status_code == 429:
- return {"error": "rate_limited", "status": 429}
- elif resp.status_code == 401:
- return {"error": "unauthorized", "status": 401, "detail": resp.text[:200]}
- else:
- return {"error": f"http_{resp.status_code}", "status": resp.status_code, "detail": resp.text[:200]}
- except requests.exceptions.Timeout:
- return {"error": "timeout"}
- except requests.exceptions.RequestException as e:
- return {"error": str(e)}
- except json.JSONDecodeError:
- return {"error": "invalid_json"}
- class MalwareBazaar(ThreatIntelClient):
- """MalwareBazaar API client (abuse.ch) - Requires Auth-Key."""
- BASE_URL = "https://mb-api.abuse.ch/api/v1/"
- def __init__(self, auth_key: Optional[str] = None):
- super().__init__()
- self.auth_key = auth_key
- if self.auth_key:
- self.session.headers.update({"Auth-Key": self.auth_key})
- def _is_configured(self) -> bool:
- return bool(self.auth_key)
- def query_hash(self, hash_value: str) -> dict:
- """Query MalwareBazaar for a file hash."""
- if not self._is_configured():
- return {"source": "malwarebazaar", "found": False, "error": "no_auth_key"}
- data = {"query": "get_info", "hash": hash_value}
- result = self._safe_request("POST", self.BASE_URL, data=data)
- if not result or "error" in result:
- return {"source": "malwarebazaar", "found": False, "error": result.get("error") if result else "request_failed", "detail": result.get("detail") if result else None}
- if result.get("query_status") == "hash_not_found":
- return {"source": "malwarebazaar", "found": False}
- if result.get("query_status") == "ok" and result.get("data"):
- sample = result["data"][0]
- return {
- "source": "malwarebazaar",
- "found": True,
- "sha256": sample.get("sha256_hash"),
- "sha1": sample.get("sha1_hash"),
- "md5": sample.get("md5_hash"),
- "file_name": sample.get("file_name"),
- "file_type": sample.get("file_type"),
- "file_size": sample.get("file_size"),
- "signature": sample.get("signature"), # Malware family
- "first_seen": sample.get("first_seen"),
- "last_seen": sample.get("last_seen"),
- "tags": sample.get("tags", []),
- "intelligence": sample.get("intelligence", {}),
- "delivery_method": sample.get("delivery_method"),
- "comment": sample.get("comment"),
- "reporter": sample.get("reporter"),
- "yara_rules": sample.get("yara_rules", []),
- "vendor_intel": sample.get("vendor_intel", {}),
- }
- return {"source": "malwarebazaar", "found": False, "raw_status": result.get("query_status")}
- def query_tag(self, tag: str, limit: int = 10) -> dict:
- """Query MalwareBazaar for samples by tag (e.g., malware family)."""
- if not self._is_configured():
- return {"source": "malwarebazaar", "found": False, "error": "no_auth_key"}
- data = {"query": "get_taginfo", "tag": tag, "limit": limit}
- result = self._safe_request("POST", self.BASE_URL, data=data)
- if not result or "error" in result:
- return {"source": "malwarebazaar", "found": False}
- if result.get("query_status") == "ok" and result.get("data"):
- samples = []
- for sample in result["data"][:limit]:
- samples.append({
- "sha256": sample.get("sha256_hash"),
- "file_name": sample.get("file_name"),
- "signature": sample.get("signature"),
- "first_seen": sample.get("first_seen"),
- })
- return {"source": "malwarebazaar", "found": True, "tag": tag, "samples": samples, "count": len(samples)}
- return {"source": "malwarebazaar", "found": False}
- class ThreatFox(ThreatIntelClient):
- """ThreatFox API client (abuse.ch) - Requires Auth-Key."""
- BASE_URL = "https://threatfox-api.abuse.ch/api/v1/"
- def __init__(self, auth_key: Optional[str] = None):
- super().__init__()
- self.auth_key = auth_key
- if self.auth_key:
- self.session.headers.update({"Auth-Key": self.auth_key})
- def _is_configured(self) -> bool:
- return bool(self.auth_key)
- def query_ioc(self, ioc: str) -> dict:
- """Query ThreatFox for an IOC (hash, IP, domain, URL)."""
- if not self._is_configured():
- return {"source": "threatfox", "found": False, "error": "no_auth_key"}
- data = {"query": "search_ioc", "search_term": ioc}
- result = self._safe_request("POST", self.BASE_URL, data=data)
- if not result or "error" in result:
- return {"source": "threatfox", "found": False, "error": result.get("error") if result else "request_failed", "detail": result.get("detail") if result else None}
- if result.get("query_status") == "no_result":
- return {"source": "threatfox", "found": False}
- if result.get("query_status") == "ok" and result.get("data"):
- iocs = []
- for entry in result["data"]:
- iocs.append({
- "ioc": entry.get("ioc"),
- "ioc_type": entry.get("ioc_type"),
- "threat_type": entry.get("threat_type"),
- "malware": entry.get("malware"),
- "malware_alias": entry.get("malware_alias"),
- "malware_malpedia": entry.get("malware_malpedia"),
- "confidence": entry.get("confidence_level"),
- "first_seen": entry.get("first_seen"),
- "last_seen": entry.get("last_seen"),
- "reporter": entry.get("reporter"),
- "tags": entry.get("tags", []),
- })
- return {"source": "threatfox", "found": True, "iocs": iocs, "count": len(iocs)}
- return {"source": "threatfox", "found": False}
- def query_malware(self, malware_name: str, limit: int = 10) -> dict:
- """Query ThreatFox for IOCs associated with a malware family."""
- if not self._is_configured():
- return {"source": "threatfox", "found": False, "error": "no_auth_key"}
- data = {"query": "malwareinfo", "malware": malware_name}
- result = self._safe_request("POST", self.BASE_URL, data=data)
- if not result or "error" in result:
- return {"source": "threatfox", "found": False}
- if result.get("query_status") == "ok" and result.get("data"):
- return {
- "source": "threatfox",
- "found": True,
- "malware": malware_name,
- "ioc_count": len(result["data"]),
- "sample_iocs": result["data"][:limit]
- }
- return {"source": "threatfox", "found": False}
- class URLhaus(ThreatIntelClient):
- """URLhaus API client (abuse.ch) - Auth-Key optional but recommended."""
- BASE_URL = "https://urlhaus-api.abuse.ch/v1/"
- def __init__(self, auth_key: Optional[str] = None):
- super().__init__()
- self.auth_key = auth_key
- if self.auth_key:
- self.session.headers.update({"Auth-Key": self.auth_key})
- def query_url(self, url: str) -> dict:
- """Query URLhaus for a URL."""
- data = {"url": url}
- result = self._safe_request("POST", f"{self.BASE_URL}url/", data=data)
- if not result or "error" in result:
- return {"source": "urlhaus", "found": False, "error": result.get("error") if result else "request_failed"}
- if result.get("query_status") == "no_results":
- return {"source": "urlhaus", "found": False}
- if result.get("query_status") == "ok":
- return {
- "source": "urlhaus",
- "found": True,
- "url": result.get("url"),
- "url_status": result.get("url_status"), # online/offline
- "threat": result.get("threat"),
- "tags": result.get("tags", []),
- "host": result.get("host"),
- "date_added": result.get("date_added"),
- "last_online": result.get("last_online"),
- "takedown_time_seconds": result.get("takedown_time_seconds"),
- "payloads": result.get("payloads", []),
- }
- return {"source": "urlhaus", "found": False}
- def query_host(self, host: str) -> dict:
- """Query URLhaus for a domain or IP."""
- data = {"host": host}
- result = self._safe_request("POST", f"{self.BASE_URL}host/", data=data)
- if not result or "error" in result:
- return {"source": "urlhaus", "found": False, "error": result.get("error") if result else "request_failed"}
- if result.get("query_status") == "no_results":
- return {"source": "urlhaus", "found": False}
- if result.get("query_status") == "ok":
- return {
- "source": "urlhaus",
- "found": True,
- "host": result.get("host"),
- "firstseen": result.get("firstseen"),
- "url_count": result.get("url_count"),
- "urls": result.get("urls", [])[:10], # Limit URLs returned
- }
- return {"source": "urlhaus", "found": False}
- def query_hash(self, hash_value: str) -> dict:
- """Query URLhaus for a payload hash."""
- hash_type = "sha256_hash" if len(hash_value) == 64 else "md5_hash"
- data = {hash_type: hash_value}
- result = self._safe_request("POST", f"{self.BASE_URL}payload/", data=data)
- if not result or "error" in result:
- return {"source": "urlhaus", "found": False}
- if result.get("query_status") == "no_results":
- return {"source": "urlhaus", "found": False}
- if result.get("query_status") == "ok":
- return {
- "source": "urlhaus",
- "found": True,
- "md5": result.get("md5_hash"),
- "sha256": result.get("sha256_hash"),
- "file_type": result.get("file_type"),
- "file_size": result.get("file_size"),
- "signature": result.get("signature"),
- "firstseen": result.get("firstseen"),
- "lastseen": result.get("lastseen"),
- "download_count": result.get("url_count"),
- "urls": result.get("urls", [])[:10],
- }
- return {"source": "urlhaus", "found": False}
- class VirusTotal(ThreatIntelClient):
- """VirusTotal API client - Requires API key."""
- BASE_URL = "https://www.virustotal.com/api/v3/"
- def __init__(self, api_key: Optional[str] = None):
- super().__init__(api_key)
- if self.api_key:
- self.session.headers.update({"x-apikey": self.api_key})
- def _is_configured(self) -> bool:
- return bool(self.api_key)
- def query_hash(self, hash_value: str) -> dict:
- """Query VirusTotal for a file hash."""
- if not self._is_configured():
- return {"source": "virustotal", "found": False, "error": "no_api_key"}
- result = self._safe_request("GET", f"{self.BASE_URL}files/{hash_value}")
- if not result or "error" in result:
- error = result.get("error") if result else "request_failed"
- if error == "not_found":
- return {"source": "virustotal", "found": False}
- return {"source": "virustotal", "found": False, "error": error}
- if "data" in result:
- attrs = result["data"].get("attributes", {})
- stats = attrs.get("last_analysis_stats", {})
- return {
- "source": "virustotal",
- "found": True,
- "sha256": attrs.get("sha256"),
- "sha1": attrs.get("sha1"),
- "md5": attrs.get("md5"),
- "file_name": attrs.get("meaningful_name") or attrs.get("names", ["unknown"])[0] if attrs.get("names") else "unknown",
- "file_type": attrs.get("type_description"),
- "file_size": attrs.get("size"),
- "magic": attrs.get("magic"),
- "detections": {
- "malicious": stats.get("malicious", 0),
- "suspicious": stats.get("suspicious", 0),
- "undetected": stats.get("undetected", 0),
- "total": sum(stats.values()) if stats else 0,
- },
- "detection_rate": f"{stats.get('malicious', 0)}/{sum(stats.values())}" if stats else "0/0",
- "popular_threat_names": attrs.get("popular_threat_classification", {}).get("suggested_threat_label"),
- "tags": attrs.get("tags", []),
- "first_submission": attrs.get("first_submission_date"),
- "last_analysis": attrs.get("last_analysis_date"),
- "reputation": attrs.get("reputation"),
- "signature_info": attrs.get("signature_info"),
- }
- return {"source": "virustotal", "found": False}
- def query_ip(self, ip: str) -> dict:
- """Query VirusTotal for an IP address."""
- if not self._is_configured():
- return {"source": "virustotal", "found": False, "error": "no_api_key"}
- result = self._safe_request("GET", f"{self.BASE_URL}ip_addresses/{ip}")
- if not result or "error" in result:
- return {"source": "virustotal", "found": False, "error": result.get("error") if result else "request_failed"}
- if "data" in result:
- attrs = result["data"].get("attributes", {})
- stats = attrs.get("last_analysis_stats", {})
- return {
- "source": "virustotal",
- "found": True,
- "ip": ip,
- "asn": attrs.get("asn"),
- "as_owner": attrs.get("as_owner"),
- "country": attrs.get("country"),
- "reputation": attrs.get("reputation"),
- "detections": {
- "malicious": stats.get("malicious", 0),
- "suspicious": stats.get("suspicious", 0),
- "harmless": stats.get("harmless", 0),
- },
- "tags": attrs.get("tags", []),
- "last_analysis": attrs.get("last_analysis_date"),
- }
- return {"source": "virustotal", "found": False}
- def query_domain(self, domain: str) -> dict:
- """Query VirusTotal for a domain."""
- if not self._is_configured():
- return {"source": "virustotal", "found": False, "error": "no_api_key"}
- result = self._safe_request("GET", f"{self.BASE_URL}domains/{domain}")
- if not result or "error" in result:
- return {"source": "virustotal", "found": False, "error": result.get("error") if result else "request_failed"}
- if "data" in result:
- attrs = result["data"].get("attributes", {})
- stats = attrs.get("last_analysis_stats", {})
- return {
- "source": "virustotal",
- "found": True,
- "domain": domain,
- "registrar": attrs.get("registrar"),
- "creation_date": attrs.get("creation_date"),
- "reputation": attrs.get("reputation"),
- "detections": {
- "malicious": stats.get("malicious", 0),
- "suspicious": stats.get("suspicious", 0),
- "harmless": stats.get("harmless", 0),
- },
- "categories": attrs.get("categories", {}),
- "tags": attrs.get("tags", []),
- "last_analysis": attrs.get("last_analysis_date"),
- }
- return {"source": "virustotal", "found": False}
- class AbuseIPDB(ThreatIntelClient):
- """AbuseIPDB API client - Requires API key."""
- BASE_URL = "https://api.abuseipdb.com/api/v2/"
- def __init__(self, api_key: Optional[str] = None):
- super().__init__(api_key)
- if self.api_key:
- self.session.headers.update({"Key": self.api_key, "Accept": "application/json"})
- def _is_configured(self) -> bool:
- return bool(self.api_key)
- def query_ip(self, ip: str) -> dict:
- """Query AbuseIPDB for an IP address."""
- if not self._is_configured():
- return {"source": "abuseipdb", "found": False, "error": "no_api_key"}
- params = {"ipAddress": ip, "maxAgeInDays": 90, "verbose": True}
- result = self._safe_request("GET", f"{self.BASE_URL}check", params=params)
- if not result or "error" in result:
- return {"source": "abuseipdb", "found": False, "error": result.get("error") if result else "request_failed"}
- if "data" in result:
- data = result["data"]
- return {
- "source": "abuseipdb",
- "found": True,
- "ip": data.get("ipAddress"),
- "is_public": data.get("isPublic"),
- "abuse_confidence_score": data.get("abuseConfidenceScore"),
- "country": data.get("countryCode"),
- "isp": data.get("isp"),
- "domain": data.get("domain"),
- "usage_type": data.get("usageType"),
- "is_tor": data.get("isTor"),
- "is_whitelisted": data.get("isWhitelisted"),
- "total_reports": data.get("totalReports"),
- "num_distinct_users": data.get("numDistinctUsers"),
- "last_reported": data.get("lastReportedAt"),
- }
- return {"source": "abuseipdb", "found": False}
- # IOC type detection
- def detect_ioc_type(ioc: str) -> str:
- """Detect the type of IOC."""
- ioc = ioc.strip()
- # Hash detection
- if re.match(r'^[a-fA-F0-9]{32}$', ioc):
- return "md5"
- if re.match(r'^[a-fA-F0-9]{40}$', ioc):
- return "sha1"
- if re.match(r'^[a-fA-F0-9]{64}$', ioc):
- return "sha256"
- # URL detection
- if re.match(r'^https?://', ioc, re.IGNORECASE):
- return "url"
- # IP detection
- if re.match(r'^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$', ioc):
- return "ipv4"
- # Domain detection (simple)
- if re.match(r'^[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(\.[a-zA-Z]{2,})+$', ioc):
- return "domain"
- return "unknown"
- def calculate_file_hashes(filepath: str) -> dict:
- """Calculate hashes for a file."""
- path = Path(filepath)
- if not path.exists():
- return {"error": f"File not found: {filepath}"}
- data = path.read_bytes()
- return {
- "md5": hashlib.md5(data).hexdigest(),
- "sha1": hashlib.sha1(data).hexdigest(),
- "sha256": hashlib.sha256(data).hexdigest(),
- "size": len(data),
- }
- class MalwareTriage:
- """Main triage orchestrator."""
- def __init__(self, vt_key: Optional[str] = None, abuseipdb_key: Optional[str] = None,
- abusech_key: Optional[str] = None, verbose: bool = True):
- # Get API keys from multiple sources
- vt_api_key = get_api_key("VIRUSTOTAL_API_KEY", vt_key)
- abuseipdb_api_key = get_api_key("ABUSEIPDB_API_KEY", abuseipdb_key)
- abusech_auth_key = get_api_key("ABUSECH_AUTH_KEY", abusech_key)
- if verbose:
- if abusech_auth_key:
- print(f"[*] abuse.ch Auth-Key loaded (ends with ...{abusech_auth_key[-4:]})", file=sys.stderr)
- else:
- print("[!] abuse.ch Auth-Key NOT found (MalwareBazaar/ThreatFox will fail)", file=sys.stderr)
- if vt_api_key:
- print(f"[*] VirusTotal API key loaded (ends with ...{vt_api_key[-4:]})", file=sys.stderr)
- else:
- print("[!] VirusTotal API key NOT found", file=sys.stderr)
- if abuseipdb_api_key:
- print(f"[*] AbuseIPDB API key loaded (ends with ...{abuseipdb_api_key[-4:]})", file=sys.stderr)
- else:
- print("[!] AbuseIPDB API key NOT found", file=sys.stderr)
- # Initialize clients with auth keys
- self.malwarebazaar = MalwareBazaar(abusech_auth_key)
- self.threatfox = ThreatFox(abusech_auth_key)
- self.urlhaus = URLhaus(abusech_auth_key)
- self.virustotal = VirusTotal(vt_api_key)
- self.abuseipdb = AbuseIPDB(abuseipdb_api_key)
- self.api_status = {
- "malwarebazaar": bool(abusech_auth_key),
- "threatfox": bool(abusech_auth_key),
- "urlhaus": True, # Works without key but better with
- "virustotal": bool(vt_api_key),
- "abuseipdb": bool(abuseipdb_api_key),
- }
- def triage_hash(self, hash_value: str) -> dict:
- """Triage a file hash across all sources."""
- results = {
- "query": hash_value,
- "type": detect_ioc_type(hash_value),
- "timestamp": datetime.now(timezone.utc).isoformat(),
- "sources": [],
- "verdict": "unknown",
- "summary": {},
- }
- # Query all sources
- sources_to_query = [
- ("malwarebazaar", self.malwarebazaar.query_hash),
- ("urlhaus", self.urlhaus.query_hash),
- ("threatfox", self.threatfox.query_ioc),
- ("virustotal", self.virustotal.query_hash),
- ]
- for source_name, query_func in sources_to_query:
- try:
- result = query_func(hash_value)
- results["sources"].append(result)
- time.sleep(0.5) # Rate limiting
- except Exception as e:
- results["sources"].append({"source": source_name, "found": False, "error": str(e)})
- # Aggregate verdict
- results["verdict"], results["summary"] = self._aggregate_hash_verdict(results["sources"])
- return results
- def triage_ip(self, ip: str) -> dict:
- """Triage an IP address across all sources."""
- results = {
- "query": ip,
- "type": "ipv4",
- "timestamp": datetime.now(timezone.utc).isoformat(),
- "sources": [],
- "verdict": "unknown",
- "summary": {},
- }
- # Query all sources
- sources_to_query = [
- ("urlhaus", self.urlhaus.query_host),
- ("threatfox", self.threatfox.query_ioc),
- ("virustotal", self.virustotal.query_ip),
- ("abuseipdb", self.abuseipdb.query_ip),
- ]
- for source_name, query_func in sources_to_query:
- try:
- result = query_func(ip)
- results["sources"].append(result)
- time.sleep(0.5)
- except Exception as e:
- results["sources"].append({"source": source_name, "found": False, "error": str(e)})
- results["verdict"], results["summary"] = self._aggregate_ip_verdict(results["sources"])
- return results
- def triage_domain(self, domain: str) -> dict:
- """Triage a domain across all sources."""
- results = {
- "query": domain,
- "type": "domain",
- "timestamp": datetime.now(timezone.utc).isoformat(),
- "sources": [],
- "verdict": "unknown",
- "summary": {},
- }
- sources_to_query = [
- ("urlhaus", self.urlhaus.query_host),
- ("threatfox", self.threatfox.query_ioc),
- ("virustotal", self.virustotal.query_domain),
- ]
- for source_name, query_func in sources_to_query:
- try:
- result = query_func(domain)
- results["sources"].append(result)
- time.sleep(0.5)
- except Exception as e:
- results["sources"].append({"source": source_name, "found": False, "error": str(e)})
- results["verdict"], results["summary"] = self._aggregate_domain_verdict(results["sources"])
- return results
- def triage_url(self, url: str) -> dict:
- """Triage a URL across all sources."""
- results = {
- "query": url,
- "type": "url",
- "timestamp": datetime.now(timezone.utc).isoformat(),
- "sources": [],
- "verdict": "unknown",
- "summary": {},
- }
- sources_to_query = [
- ("urlhaus", self.urlhaus.query_url),
- ("threatfox", self.threatfox.query_ioc),
- ]
- for source_name, query_func in sources_to_query:
- try:
- result = query_func(url)
- results["sources"].append(result)
- time.sleep(0.5)
- except Exception as e:
- results["sources"].append({"source": source_name, "found": False, "error": str(e)})
- results["verdict"], results["summary"] = self._aggregate_url_verdict(results["sources"])
- return results
- def triage_file(self, filepath: str) -> dict:
- """Triage a file by calculating hashes and querying."""
- hashes = calculate_file_hashes(filepath)
- if "error" in hashes:
- return {"error": hashes["error"]}
- results = self.triage_hash(hashes["sha256"])
- results["file_info"] = {
- "path": filepath,
- "hashes": hashes,
- }
- return results
- def triage_auto(self, ioc: str) -> dict:
- """Auto-detect IOC type and triage."""
- ioc_type = detect_ioc_type(ioc)
- if ioc_type in ["md5", "sha1", "sha256"]:
- return self.triage_hash(ioc)
- elif ioc_type == "ipv4":
- return self.triage_ip(ioc)
- elif ioc_type == "domain":
- return self.triage_domain(ioc)
- elif ioc_type == "url":
- return self.triage_url(ioc)
- else:
- return {"error": f"Unknown IOC type: {ioc}", "query": ioc}
- def _aggregate_hash_verdict(self, sources: list) -> tuple:
- """Aggregate verdict from hash query results."""
- malware_names = set()
- tags = set()
- found_in = []
- vt_detection = None
- for source in sources:
- if source.get("found"):
- found_in.append(source["source"])
- # Extract malware family names
- if source.get("signature"):
- malware_names.add(source["signature"])
- if source.get("popular_threat_names"):
- malware_names.add(source["popular_threat_names"])
- if source.get("malware"):
- malware_names.add(source["malware"])
- # Extract tags
- if source.get("tags"):
- tags.update(source["tags"])
- # Get VT detection rate
- if source["source"] == "virustotal" and source.get("detections"):
- vt_detection = source["detections"]
- # Determine verdict
- if not found_in:
- verdict = "clean_or_unknown"
- elif vt_detection and vt_detection.get("malicious", 0) > 5:
- verdict = "malicious"
- elif found_in:
- verdict = "suspicious"
- else:
- verdict = "unknown"
- summary = {
- "found_in_sources": found_in,
- "malware_families": list(malware_names),
- "tags": list(tags),
- }
- if vt_detection:
- summary["virustotal_detection"] = f"{vt_detection.get('malicious', 0)}/{vt_detection.get('total', 0)}"
- return verdict, summary
- def _aggregate_ip_verdict(self, sources: list) -> tuple:
- """Aggregate verdict from IP query results."""
- found_in = []
- abuse_score = None
- vt_malicious = 0
- url_count = 0
- for source in sources:
- if source.get("found"):
- found_in.append(source["source"])
- if source["source"] == "abuseipdb":
- abuse_score = source.get("abuse_confidence_score")
- if source["source"] == "virustotal" and source.get("detections"):
- vt_malicious = source["detections"].get("malicious", 0)
- if source["source"] == "urlhaus":
- url_count = source.get("url_count", 0)
- # Determine verdict
- if abuse_score and abuse_score > 50:
- verdict = "malicious"
- elif vt_malicious > 3:
- verdict = "malicious"
- elif url_count > 0 or found_in:
- verdict = "suspicious"
- else:
- verdict = "clean_or_unknown"
- summary = {
- "found_in_sources": found_in,
- }
- if abuse_score is not None:
- summary["abuse_confidence_score"] = abuse_score
- if vt_malicious:
- summary["virustotal_malicious"] = vt_malicious
- if url_count:
- summary["urlhaus_url_count"] = url_count
- return verdict, summary
- def _aggregate_domain_verdict(self, sources: list) -> tuple:
- """Aggregate verdict from domain query results."""
- found_in = []
- vt_malicious = 0
- url_count = 0
- for source in sources:
- if source.get("found"):
- found_in.append(source["source"])
- if source["source"] == "virustotal" and source.get("detections"):
- vt_malicious = source["detections"].get("malicious", 0)
- if source["source"] == "urlhaus":
- url_count = source.get("url_count", 0)
- if vt_malicious > 3:
- verdict = "malicious"
- elif url_count > 0 or found_in:
- verdict = "suspicious"
- else:
- verdict = "clean_or_unknown"
- return verdict, {"found_in_sources": found_in, "virustotal_malicious": vt_malicious, "urlhaus_url_count": url_count}
- def _aggregate_url_verdict(self, sources: list) -> tuple:
- """Aggregate verdict from URL query results."""
- found_in = []
- threat_type = None
- for source in sources:
- if source.get("found"):
- found_in.append(source["source"])
- if source.get("threat"):
- threat_type = source["threat"]
- if found_in:
- verdict = "malicious"
- else:
- verdict = "clean_or_unknown"
- return verdict, {"found_in_sources": found_in, "threat_type": threat_type}
- def format_triage_report(results: dict, format_type: str = "text") -> str:
- """Format triage results for output."""
- if format_type == "json":
- return json.dumps(results, indent=2, default=str)
- # Text format
- lines = []
- lines.append("=" * 70)
- lines.append("MALWARE TRIAGE REPORT")
- lines.append("=" * 70)
- lines.append(f"\n[QUERY]")
- lines.append(f" IOC: {results.get('query', 'N/A')}")
- lines.append(f" Type: {results.get('type', 'N/A')}")
- lines.append(f" Timestamp: {results.get('timestamp', 'N/A')}")
- # File info if present
- if results.get("file_info"):
- fi = results["file_info"]
- lines.append(f"\n[FILE INFO]")
- lines.append(f" Path: {fi['path']}")
- lines.append(f" MD5: {fi['hashes'].get('md5')}")
- lines.append(f" SHA1: {fi['hashes'].get('sha1')}")
- lines.append(f" SHA256: {fi['hashes'].get('sha256')}")
- lines.append(f" Size: {fi['hashes'].get('size'):,} bytes")
- # Verdict
- verdict = results.get("verdict", "unknown")
- verdict_emoji = {"malicious": "🔴", "suspicious": "🟡", "clean_or_unknown": "🟢", "unknown": "⚪"}.get(verdict, "⚪")
- lines.append(f"\n[VERDICT] {verdict_emoji} {verdict.upper()}")
- # Summary
- summary = results.get("summary", {})
- if summary:
- lines.append(f"\n[SUMMARY]")
- if summary.get("found_in_sources"):
- lines.append(f" Found in: {', '.join(summary['found_in_sources'])}")
- if summary.get("malware_families"):
- lines.append(f" Malware: {', '.join(summary['malware_families'])}")
- if summary.get("virustotal_detection"):
- lines.append(f" VT Score: {summary['virustotal_detection']}")
- if summary.get("abuse_confidence_score") is not None:
- lines.append(f" AbuseIPDB Score: {summary['abuse_confidence_score']}%")
- if summary.get("tags"):
- lines.append(f" Tags: {', '.join(summary['tags'][:10])}")
- # Source details
- lines.append(f"\n[SOURCE DETAILS]")
- for source in results.get("sources", []):
- source_name = source.get("source", "unknown").upper()
- found = "✓" if source.get("found") else "✗"
- lines.append(f"\n [{source_name}] {found}")
- if source.get("error"):
- lines.append(f" Error: {source['error']}")
- continue
- if not source.get("found"):
- lines.append(f" Not found in database")
- continue
- # Source-specific details
- if source.get("signature"):
- lines.append(f" Malware: {source['signature']}")
- if source.get("popular_threat_names"):
- lines.append(f" Threat: {source['popular_threat_names']}")
- if source.get("detection_rate"):
- lines.append(f" Detection: {source['detection_rate']}")
- if source.get("first_seen"):
- lines.append(f" First seen: {source['first_seen']}")
- if source.get("abuse_confidence_score") is not None:
- lines.append(f" Abuse score: {source['abuse_confidence_score']}%")
- if source.get("total_reports"):
- lines.append(f" Reports: {source['total_reports']}")
- if source.get("url_count"):
- lines.append(f" Malicious URLs: {source['url_count']}")
- if source.get("tags"):
- lines.append(f" Tags: {', '.join(source['tags'][:5])}")
- lines.append("\n" + "=" * 70)
- return "\n".join(lines)
- def main():
- parser = argparse.ArgumentParser(
- description="Malware triage - Multi-source threat intelligence lookup",
- formatter_class=argparse.RawDescriptionHelpFormatter,
- epilog="""
- Examples:
- %(prog)s 44d88612fea8a8f36de82e1278abb02f # MD5 hash
- %(prog)s -t hash e3b0c44298fc1c149afbf4c8996fb924... # SHA256 hash
- %(prog)s -t ip 45.33.32.156 # IP address
- %(prog)s -t domain evil.com # Domain
- %(prog)s -t url http://evil.com/malware.exe # URL
- Dismissed after review: Links to a Windows program from code, which is how droppers fetch their payload
- Line 1,039 on GitHub
- %(prog)s -t file /path/to/sample.exe # File
- %(prog)s --batch iocs.txt # Batch mode
- API Key Configuration (in priority order):
- 1. Command line: --abusech-key, --vt-key, --abuseipdb-key
- 2. Environment variables: ABUSECH_AUTH_KEY, VIRUSTOTAL_API_KEY, ABUSEIPDB_API_KEY
- 3. Config file: ~/.config/malware-triage/config.json
- Create config file:
- %(prog)s --init-config
- Get your API keys from:
- - abuse.ch (MalwareBazaar/ThreatFox): https://auth.abuse.ch/
- - VirusTotal: https://www.virustotal.com/gui/my-apikey
- - AbuseIPDB: https://www.abuseipdb.com/account/api
- """
- )
- parser.add_argument("ioc", nargs="?", help="IOC to triage (hash, IP, domain, URL)")
- parser.add_argument("-t", "--type", choices=["hash", "ip", "domain", "url", "file", "auto"],
- default="auto", help="IOC type (default: auto-detect)")
- parser.add_argument("-f", "--format", choices=["text", "json"], default="text",
- help="Output format (default: text)")
- parser.add_argument("-o", "--output", help="Output file")
- parser.add_argument("--batch", help="File containing IOCs (one per line)")
- parser.add_argument("--status", action="store_true", help="Show API configuration status")
- parser.add_argument("--init-config", action="store_true", help="Create default config file")
- parser.add_argument("--abusech-key", help="abuse.ch Auth-Key (for MalwareBazaar/ThreatFox)")
- parser.add_argument("--vt-key", help="VirusTotal API key")
- parser.add_argument("--abuseipdb-key", help="AbuseIPDB API key")
- args = parser.parse_args()
- if args.init_config:
- create_default_config()
- return
- triage = MalwareTriage(
- vt_key=args.vt_key,
- abuseipdb_key=args.abuseipdb_key,
- abusech_key=args.abusech_key
- )
- if args.status:
- print("API Configuration Status:")
- print("-" * 40)
- for api, configured in triage.api_status.items():
- status = "✓ Configured" if configured else "✗ Not configured"
- print(f" {api:<15} {status}")
- # Show config file location
- print()
- print("Config file locations (in priority order):")
- config_paths = [
- Path.home() / ".config" / "malware-triage" / "config.json",
- Path.home() / ".malware-triage.json",
- Path("config.json"),
- ]
- for p in config_paths:
- exists = "✓" if p.exists() else "✗"
- print(f" {exists} {p}")
- print()
- print("Run with --init-config to create a config file.")
- return
- if not args.ioc and not args.batch:
- parser.print_help()
- return
- # Process IOCs
- results_list = []
- if args.batch:
- iocs = Path(args.batch).read_text().strip().split("\n")
- for ioc in iocs:
- ioc = ioc.strip()
- if not ioc or ioc.startswith("#"):
- continue
- print(f"Triaging: {ioc}...", file=sys.stderr)
- result = triage.triage_auto(ioc)
- results_list.append(result)
- else:
- if args.type == "file":
- result = triage.triage_file(args.ioc)
- elif args.type == "hash":
- result = triage.triage_hash(args.ioc)
- elif args.type == "ip":
- result = triage.triage_ip(args.ioc)
- elif args.type == "domain":
- result = triage.triage_domain(args.ioc)
- elif args.type == "url":
- result = triage.triage_url(args.ioc)
- else:
- result = triage.triage_auto(args.ioc)
- results_list.append(result)
- # Format output
- if args.batch and args.format == "json":
- output = json.dumps(results_list, indent=2, default=str)
- elif args.batch:
- output = "\n\n".join(format_triage_report(r, args.format) for r in results_list)
- else:
- output = format_triage_report(results_list[0], args.format)
- if args.output:
- Path(args.output).write_text(output)
- print(f"Results written to {args.output}", file=sys.stderr)
- else:
- print(output)
- if __name__ == "__main__":
- main()
Ratings and comments
Sign in to rate this skill.
Sign inFree to use. If it’s helped, pass it on.