Skip to content
Back to search

awesome-dfir-skills

MarketplaceWorks with Claude CodeGitHub

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.

Checked today
Badge for your README
findsafeskills safety rating

Markdown

[![findsafeskills safety rating](/api/listings/tsale-awesome-dfir-skills/badge.svg)](/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)

  1. # 🔥 awesome-dfir-skills
  2. [![Awesome](https://awesome.re/badge.svg)](https://awesome.re)
  3. [![PRs Welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg)](http://makeapullrequest.com)
  4. [![DFIR](https://img.shields.io/badge/DFIR-Skills-blue.svg)](#)
  5. 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.
  6. ---
  7. ## 🚀 Quick Start
  8. 1. Pick a skill from `skills/README.md`
  9. 2. Copy/paste it into your AI assistant (Claude, Codex, etc.)
  10. 3. Feed it your artifacts when prompted
  11. 4. Watch the magic happen ✨
  12. **Pro tip:** Keep placeholders like `{{time_window}}` as-is—fill them in when the skill asks for them.
  13. ---
  14. ## 🤔 What's a "Skill" Anyway?
  15. 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.
  16. Each skill is designed to:
  17. | Feature | Why It Matters |
  18. |---------|----------------|
  19. | 📥 Clear inputs & outputs | No guessing games |
  20. | 🎯 Explicit about unknowns | Fewer hallucinations, more facts |
  21. | 🔒 Safe-by-default | Evidence handling & privacy baked in |
  22. ---
  23. ## 📁 Repository Layout
  24. ```
  25. skills/
  26. ├── README.md # Start here → skill catalog
  27. ├── _templates/
  28. │ └── skill.md # Template for new skills
  29. └── <category>/
  30. └── <skill-id>/
  31. ├── skill.md # The skill entrypoint
  32. └── helpers/ # Query snippets, regex, parsers
  33. ```
  34. ---
  35. ## 🛠️ Platform Setup
  36. ### Claude Desktop / Claude.ai
  37. Skills are folders of instructions that Claude loads dynamically:
  38. 1. Use the skill's **Skill prompt** as workflow instructions
  39. 2. Provide inputs in-chat when prompted
  40. 3. Keep `{{placeholders}}` intact—fill values in the corresponding sections
  41. ### OpenAI / Codex
  42. Codex loads skills from a dedicated folder (e.g., `$REPO_ROOT/.codex/skills`):
  43. 1. Mirror or symlink skills from `skills/` to your Codex skill location
  44. 2. Invoke skills explicitly (mention them) or let Codex pick them up implicitly
  45. 3. Provide artifacts as inputs; keep `{{...}}` placeholders as-is
  46. ---
  47. ## 🤝 Contributing
  48. ### How to Add a Skill
  49. 1. Copy `skills/_templates/skill.md`
  50. 2. Create `skills/<category>/<skill-id>/skill.md`
  51. 3. Keep it practical, tool-agnostic where possible
  52. 4. Test on real (or realistic) artifacts
  53. **Coming soon:** Metadata validator and detailed contribution guidelines.
  54. ---
  55. ## 💡 Inspiration
  56. - [Claude Skills](https://support.claude.com/en/articles/12512176-what-are-skills) — Anthropic's skill system
  57. - [OpenAI Codex Skills](https://developers.openai.com/codex/skills/) — OpenAI's approach
  58. ---
  59. ## 📜 License
  60. MIT — Use it, fork it, improve it.
  61. ---
  62. <p align="center">
  63. <strong>Made with ☕ and mild panic by the DFIR community</strong>
  64. </p>
skills/analysis/malware-analysis-tr/scripts/triage.py · Bundled script · 1,152 lines · 1 finding marked
  1. #!/usr/bin/env python3
  2. """
  3. Malware Triage - Multi-source threat intelligence lookup.
  4. API keys can be configured via:
  5. 1. Config file: ~/.config/malware-triage/config.json
  6. 2. Environment variables: VIRUSTOTAL_API_KEY, ABUSEIPDB_API_KEY
  7. 3. Command line: --vt-key, --abuseipdb-key
  8. """
  9. import argparse
  10. import hashlib
  11. import json
  12. import os
  13. import re
  14. import sys
  15. import time
  16. from datetime import datetime, timezone
  17. from pathlib import Path
  18. from typing import Optional
  19. from urllib.parse import quote
  20. # Check for requests library
  21. try:
  22. import requests
  23. except ImportError:
  24. print("Error: requests library required. Install with: pip install requests --break-system-packages")
  25. sys.exit(1)
  26. def load_config() -> dict:
  27. """
  28. Load API keys from config file.
  29. Config file locations (in order of priority):
  30. 1. Skill's own config directory (bundled with skill)
  31. 2. /mnt/user-data/uploads/config.json (Claude Desktop uploads)
  32. 3. ~/.config/malware-triage/config.json
  33. 4. ./config.json (current directory)
  34. """
  35. # Get the skill's directory (parent of scripts/)
  36. script_dir = Path(__file__).parent
  37. skill_dir = script_dir.parent
  38. config_paths = [
  39. # Bundled with skill
  40. skill_dir / "config" / "config.json",
  41. skill_dir / "config" / "api_keys.json",
  42. skill_dir / "config.json",
  43. # Claude Desktop uploads
  44. Path("/mnt/user-data/uploads/config.json"),
  45. Path("/mnt/user-data/uploads/api_keys.json"),
  46. # User home config
  47. Path.home() / ".config" / "malware-triage" / "config.json",
  48. Path.home() / ".malware-triage.json",
  49. # Current directory
  50. Path("config.json"),
  51. ]
  52. for config_path in config_paths:
  53. if config_path.exists():
  54. try:
  55. with open(config_path) as f:
  56. config = json.load(f)
  57. print(f"[*] Loaded config from: {config_path}", file=sys.stderr)
  58. return config
  59. except (json.JSONDecodeError, IOError) as e:
  60. print(f"[!] Failed to load {config_path}: {e}", file=sys.stderr)
  61. continue
  62. return {}
  63. def get_api_key(key_name: str, cli_value: Optional[str] = None) -> Optional[str]:
  64. """
  65. Get API key from multiple sources (priority order):
  66. 1. Command line argument
  67. 2. Environment variable
  68. 3. Config file
  69. """
  70. # CLI takes priority
  71. if cli_value:
  72. return cli_value
  73. # Then environment variable
  74. env_key = os.environ.get(key_name)
  75. if env_key:
  76. return env_key
  77. # Finally config file
  78. config = load_config()
  79. config_key_map = {
  80. "VIRUSTOTAL_API_KEY": ["virustotal_api_key", "vt_api_key", "virustotal"],
  81. "ABUSEIPDB_API_KEY": ["abuseipdb_api_key", "abuseipdb"],
  82. "ABUSECH_AUTH_KEY": ["abusech_auth_key", "abuse_ch_auth_key", "malwarebazaar_auth_key", "auth_key"],
  83. }
  84. possible_keys = config_key_map.get(key_name, [key_name.lower()])
  85. for config_key in possible_keys:
  86. if config_key in config:
  87. return config[config_key]
  88. return None
  89. def create_default_config():
  90. """Create a default config file template."""
  91. config_dir = Path.home() / ".config" / "malware-triage"
  92. config_path = config_dir / "config.json"
  93. if config_path.exists():
  94. print(f"Config already exists: {config_path}")
  95. return
  96. config_dir.mkdir(parents=True, exist_ok=True)
  97. default_config = {
  98. "abusech_auth_key": "YOUR_ABUSECH_AUTH_KEY_HERE",
  99. "virustotal_api_key": "YOUR_VT_API_KEY_HERE",
  100. "abuseipdb_api_key": "YOUR_ABUSEIPDB_API_KEY_HERE",
  101. }
  102. with open(config_path, "w") as f:
  103. json.dump(default_config, f, indent=2)
  104. print(f"Created config file: {config_path}")
  105. print("Edit this file with your API keys.")
  106. print()
  107. print("Get your keys from:")
  108. print(" - abuse.ch (MalwareBazaar/ThreatFox): https://auth.abuse.ch/")
  109. print(" - VirusTotal: https://www.virustotal.com/gui/my-apikey")
  110. print(" - AbuseIPDB: https://www.abuseipdb.com/account/api")
  111. class ThreatIntelClient:
  112. """Base class for threat intel API clients."""
  113. def __init__(self, api_key: Optional[str] = None):
  114. self.api_key = api_key
  115. self.session = requests.Session()
  116. self.session.headers.update({
  117. "User-Agent": "MalwareTriage/1.0 (Threat Intelligence Lookup Tool)",
  118. "Accept": "application/json",
  119. "Content-Type": "application/x-www-form-urlencoded",
  120. })
  121. def _safe_request(self, method: str, url: str, **kwargs) -> Optional[dict]:
  122. """Make a request with error handling."""
  123. try:
  124. resp = self.session.request(method, url, timeout=30, **kwargs)
  125. if resp.status_code == 200:
  126. return resp.json()
  127. elif resp.status_code == 404:
  128. return {"error": "not_found", "status": 404}
  129. elif resp.status_code == 429:
  130. return {"error": "rate_limited", "status": 429}
  131. elif resp.status_code == 401:
  132. return {"error": "unauthorized", "status": 401, "detail": resp.text[:200]}
  133. else:
  134. return {"error": f"http_{resp.status_code}", "status": resp.status_code, "detail": resp.text[:200]}
  135. except requests.exceptions.Timeout:
  136. return {"error": "timeout"}
  137. except requests.exceptions.RequestException as e:
  138. return {"error": str(e)}
  139. except json.JSONDecodeError:
  140. return {"error": "invalid_json"}
  141. class MalwareBazaar(ThreatIntelClient):
  142. """MalwareBazaar API client (abuse.ch) - Requires Auth-Key."""
  143. BASE_URL = "https://mb-api.abuse.ch/api/v1/"
  144. def __init__(self, auth_key: Optional[str] = None):
  145. super().__init__()
  146. self.auth_key = auth_key
  147. if self.auth_key:
  148. self.session.headers.update({"Auth-Key": self.auth_key})
  149. def _is_configured(self) -> bool:
  150. return bool(self.auth_key)
  151. def query_hash(self, hash_value: str) -> dict:
  152. """Query MalwareBazaar for a file hash."""
  153. if not self._is_configured():
  154. return {"source": "malwarebazaar", "found": False, "error": "no_auth_key"}
  155. data = {"query": "get_info", "hash": hash_value}
  156. result = self._safe_request("POST", self.BASE_URL, data=data)
  157. if not result or "error" in result:
  158. return {"source": "malwarebazaar", "found": False, "error": result.get("error") if result else "request_failed", "detail": result.get("detail") if result else None}
  159. if result.get("query_status") == "hash_not_found":
  160. return {"source": "malwarebazaar", "found": False}
  161. if result.get("query_status") == "ok" and result.get("data"):
  162. sample = result["data"][0]
  163. return {
  164. "source": "malwarebazaar",
  165. "found": True,
  166. "sha256": sample.get("sha256_hash"),
  167. "sha1": sample.get("sha1_hash"),
  168. "md5": sample.get("md5_hash"),
  169. "file_name": sample.get("file_name"),
  170. "file_type": sample.get("file_type"),
  171. "file_size": sample.get("file_size"),
  172. "signature": sample.get("signature"), # Malware family
  173. "first_seen": sample.get("first_seen"),
  174. "last_seen": sample.get("last_seen"),
  175. "tags": sample.get("tags", []),
  176. "intelligence": sample.get("intelligence", {}),
  177. "delivery_method": sample.get("delivery_method"),
  178. "comment": sample.get("comment"),
  179. "reporter": sample.get("reporter"),
  180. "yara_rules": sample.get("yara_rules", []),
  181. "vendor_intel": sample.get("vendor_intel", {}),
  182. }
  183. return {"source": "malwarebazaar", "found": False, "raw_status": result.get("query_status")}
  184. def query_tag(self, tag: str, limit: int = 10) -> dict:
  185. """Query MalwareBazaar for samples by tag (e.g., malware family)."""
  186. if not self._is_configured():
  187. return {"source": "malwarebazaar", "found": False, "error": "no_auth_key"}
  188. data = {"query": "get_taginfo", "tag": tag, "limit": limit}
  189. result = self._safe_request("POST", self.BASE_URL, data=data)
  190. if not result or "error" in result:
  191. return {"source": "malwarebazaar", "found": False}
  192. if result.get("query_status") == "ok" and result.get("data"):
  193. samples = []
  194. for sample in result["data"][:limit]:
  195. samples.append({
  196. "sha256": sample.get("sha256_hash"),
  197. "file_name": sample.get("file_name"),
  198. "signature": sample.get("signature"),
  199. "first_seen": sample.get("first_seen"),
  200. })
  201. return {"source": "malwarebazaar", "found": True, "tag": tag, "samples": samples, "count": len(samples)}
  202. return {"source": "malwarebazaar", "found": False}
  203. class ThreatFox(ThreatIntelClient):
  204. """ThreatFox API client (abuse.ch) - Requires Auth-Key."""
  205. BASE_URL = "https://threatfox-api.abuse.ch/api/v1/"
  206. def __init__(self, auth_key: Optional[str] = None):
  207. super().__init__()
  208. self.auth_key = auth_key
  209. if self.auth_key:
  210. self.session.headers.update({"Auth-Key": self.auth_key})
  211. def _is_configured(self) -> bool:
  212. return bool(self.auth_key)
  213. def query_ioc(self, ioc: str) -> dict:
  214. """Query ThreatFox for an IOC (hash, IP, domain, URL)."""
  215. if not self._is_configured():
  216. return {"source": "threatfox", "found": False, "error": "no_auth_key"}
  217. data = {"query": "search_ioc", "search_term": ioc}
  218. result = self._safe_request("POST", self.BASE_URL, data=data)
  219. if not result or "error" in result:
  220. return {"source": "threatfox", "found": False, "error": result.get("error") if result else "request_failed", "detail": result.get("detail") if result else None}
  221. if result.get("query_status") == "no_result":
  222. return {"source": "threatfox", "found": False}
  223. if result.get("query_status") == "ok" and result.get("data"):
  224. iocs = []
  225. for entry in result["data"]:
  226. iocs.append({
  227. "ioc": entry.get("ioc"),
  228. "ioc_type": entry.get("ioc_type"),
  229. "threat_type": entry.get("threat_type"),
  230. "malware": entry.get("malware"),
  231. "malware_alias": entry.get("malware_alias"),
  232. "malware_malpedia": entry.get("malware_malpedia"),
  233. "confidence": entry.get("confidence_level"),
  234. "first_seen": entry.get("first_seen"),
  235. "last_seen": entry.get("last_seen"),
  236. "reporter": entry.get("reporter"),
  237. "tags": entry.get("tags", []),
  238. })
  239. return {"source": "threatfox", "found": True, "iocs": iocs, "count": len(iocs)}
  240. return {"source": "threatfox", "found": False}
  241. def query_malware(self, malware_name: str, limit: int = 10) -> dict:
  242. """Query ThreatFox for IOCs associated with a malware family."""
  243. if not self._is_configured():
  244. return {"source": "threatfox", "found": False, "error": "no_auth_key"}
  245. data = {"query": "malwareinfo", "malware": malware_name}
  246. result = self._safe_request("POST", self.BASE_URL, data=data)
  247. if not result or "error" in result:
  248. return {"source": "threatfox", "found": False}
  249. if result.get("query_status") == "ok" and result.get("data"):
  250. return {
  251. "source": "threatfox",
  252. "found": True,
  253. "malware": malware_name,
  254. "ioc_count": len(result["data"]),
  255. "sample_iocs": result["data"][:limit]
  256. }
  257. return {"source": "threatfox", "found": False}
  258. class URLhaus(ThreatIntelClient):
  259. """URLhaus API client (abuse.ch) - Auth-Key optional but recommended."""
  260. BASE_URL = "https://urlhaus-api.abuse.ch/v1/"
  261. def __init__(self, auth_key: Optional[str] = None):
  262. super().__init__()
  263. self.auth_key = auth_key
  264. if self.auth_key:
  265. self.session.headers.update({"Auth-Key": self.auth_key})
  266. def query_url(self, url: str) -> dict:
  267. """Query URLhaus for a URL."""
  268. data = {"url": url}
  269. result = self._safe_request("POST", f"{self.BASE_URL}url/", data=data)
  270. if not result or "error" in result:
  271. return {"source": "urlhaus", "found": False, "error": result.get("error") if result else "request_failed"}
  272. if result.get("query_status") == "no_results":
  273. return {"source": "urlhaus", "found": False}
  274. if result.get("query_status") == "ok":
  275. return {
  276. "source": "urlhaus",
  277. "found": True,
  278. "url": result.get("url"),
  279. "url_status": result.get("url_status"), # online/offline
  280. "threat": result.get("threat"),
  281. "tags": result.get("tags", []),
  282. "host": result.get("host"),
  283. "date_added": result.get("date_added"),
  284. "last_online": result.get("last_online"),
  285. "takedown_time_seconds": result.get("takedown_time_seconds"),
  286. "payloads": result.get("payloads", []),
  287. }
  288. return {"source": "urlhaus", "found": False}
  289. def query_host(self, host: str) -> dict:
  290. """Query URLhaus for a domain or IP."""
  291. data = {"host": host}
  292. result = self._safe_request("POST", f"{self.BASE_URL}host/", data=data)
  293. if not result or "error" in result:
  294. return {"source": "urlhaus", "found": False, "error": result.get("error") if result else "request_failed"}
  295. if result.get("query_status") == "no_results":
  296. return {"source": "urlhaus", "found": False}
  297. if result.get("query_status") == "ok":
  298. return {
  299. "source": "urlhaus",
  300. "found": True,
  301. "host": result.get("host"),
  302. "firstseen": result.get("firstseen"),
  303. "url_count": result.get("url_count"),
  304. "urls": result.get("urls", [])[:10], # Limit URLs returned
  305. }
  306. return {"source": "urlhaus", "found": False}
  307. def query_hash(self, hash_value: str) -> dict:
  308. """Query URLhaus for a payload hash."""
  309. hash_type = "sha256_hash" if len(hash_value) == 64 else "md5_hash"
  310. data = {hash_type: hash_value}
  311. result = self._safe_request("POST", f"{self.BASE_URL}payload/", data=data)
  312. if not result or "error" in result:
  313. return {"source": "urlhaus", "found": False}
  314. if result.get("query_status") == "no_results":
  315. return {"source": "urlhaus", "found": False}
  316. if result.get("query_status") == "ok":
  317. return {
  318. "source": "urlhaus",
  319. "found": True,
  320. "md5": result.get("md5_hash"),
  321. "sha256": result.get("sha256_hash"),
  322. "file_type": result.get("file_type"),
  323. "file_size": result.get("file_size"),
  324. "signature": result.get("signature"),
  325. "firstseen": result.get("firstseen"),
  326. "lastseen": result.get("lastseen"),
  327. "download_count": result.get("url_count"),
  328. "urls": result.get("urls", [])[:10],
  329. }
  330. return {"source": "urlhaus", "found": False}
  331. class VirusTotal(ThreatIntelClient):
  332. """VirusTotal API client - Requires API key."""
  333. BASE_URL = "https://www.virustotal.com/api/v3/"
  334. def __init__(self, api_key: Optional[str] = None):
  335. super().__init__(api_key)
  336. if self.api_key:
  337. self.session.headers.update({"x-apikey": self.api_key})
  338. def _is_configured(self) -> bool:
  339. return bool(self.api_key)
  340. def query_hash(self, hash_value: str) -> dict:
  341. """Query VirusTotal for a file hash."""
  342. if not self._is_configured():
  343. return {"source": "virustotal", "found": False, "error": "no_api_key"}
  344. result = self._safe_request("GET", f"{self.BASE_URL}files/{hash_value}")
  345. if not result or "error" in result:
  346. error = result.get("error") if result else "request_failed"
  347. if error == "not_found":
  348. return {"source": "virustotal", "found": False}
  349. return {"source": "virustotal", "found": False, "error": error}
  350. if "data" in result:
  351. attrs = result["data"].get("attributes", {})
  352. stats = attrs.get("last_analysis_stats", {})
  353. return {
  354. "source": "virustotal",
  355. "found": True,
  356. "sha256": attrs.get("sha256"),
  357. "sha1": attrs.get("sha1"),
  358. "md5": attrs.get("md5"),
  359. "file_name": attrs.get("meaningful_name") or attrs.get("names", ["unknown"])[0] if attrs.get("names") else "unknown",
  360. "file_type": attrs.get("type_description"),
  361. "file_size": attrs.get("size"),
  362. "magic": attrs.get("magic"),
  363. "detections": {
  364. "malicious": stats.get("malicious", 0),
  365. "suspicious": stats.get("suspicious", 0),
  366. "undetected": stats.get("undetected", 0),
  367. "total": sum(stats.values()) if stats else 0,
  368. },
  369. "detection_rate": f"{stats.get('malicious', 0)}/{sum(stats.values())}" if stats else "0/0",
  370. "popular_threat_names": attrs.get("popular_threat_classification", {}).get("suggested_threat_label"),
  371. "tags": attrs.get("tags", []),
  372. "first_submission": attrs.get("first_submission_date"),
  373. "last_analysis": attrs.get("last_analysis_date"),
  374. "reputation": attrs.get("reputation"),
  375. "signature_info": attrs.get("signature_info"),
  376. }
  377. return {"source": "virustotal", "found": False}
  378. def query_ip(self, ip: str) -> dict:
  379. """Query VirusTotal for an IP address."""
  380. if not self._is_configured():
  381. return {"source": "virustotal", "found": False, "error": "no_api_key"}
  382. result = self._safe_request("GET", f"{self.BASE_URL}ip_addresses/{ip}")
  383. if not result or "error" in result:
  384. return {"source": "virustotal", "found": False, "error": result.get("error") if result else "request_failed"}
  385. if "data" in result:
  386. attrs = result["data"].get("attributes", {})
  387. stats = attrs.get("last_analysis_stats", {})
  388. return {
  389. "source": "virustotal",
  390. "found": True,
  391. "ip": ip,
  392. "asn": attrs.get("asn"),
  393. "as_owner": attrs.get("as_owner"),
  394. "country": attrs.get("country"),
  395. "reputation": attrs.get("reputation"),
  396. "detections": {
  397. "malicious": stats.get("malicious", 0),
  398. "suspicious": stats.get("suspicious", 0),
  399. "harmless": stats.get("harmless", 0),
  400. },
  401. "tags": attrs.get("tags", []),
  402. "last_analysis": attrs.get("last_analysis_date"),
  403. }
  404. return {"source": "virustotal", "found": False}
  405. def query_domain(self, domain: str) -> dict:
  406. """Query VirusTotal for a domain."""
  407. if not self._is_configured():
  408. return {"source": "virustotal", "found": False, "error": "no_api_key"}
  409. result = self._safe_request("GET", f"{self.BASE_URL}domains/{domain}")
  410. if not result or "error" in result:
  411. return {"source": "virustotal", "found": False, "error": result.get("error") if result else "request_failed"}
  412. if "data" in result:
  413. attrs = result["data"].get("attributes", {})
  414. stats = attrs.get("last_analysis_stats", {})
  415. return {
  416. "source": "virustotal",
  417. "found": True,
  418. "domain": domain,
  419. "registrar": attrs.get("registrar"),
  420. "creation_date": attrs.get("creation_date"),
  421. "reputation": attrs.get("reputation"),
  422. "detections": {
  423. "malicious": stats.get("malicious", 0),
  424. "suspicious": stats.get("suspicious", 0),
  425. "harmless": stats.get("harmless", 0),
  426. },
  427. "categories": attrs.get("categories", {}),
  428. "tags": attrs.get("tags", []),
  429. "last_analysis": attrs.get("last_analysis_date"),
  430. }
  431. return {"source": "virustotal", "found": False}
  432. class AbuseIPDB(ThreatIntelClient):
  433. """AbuseIPDB API client - Requires API key."""
  434. BASE_URL = "https://api.abuseipdb.com/api/v2/"
  435. def __init__(self, api_key: Optional[str] = None):
  436. super().__init__(api_key)
  437. if self.api_key:
  438. self.session.headers.update({"Key": self.api_key, "Accept": "application/json"})
  439. def _is_configured(self) -> bool:
  440. return bool(self.api_key)
  441. def query_ip(self, ip: str) -> dict:
  442. """Query AbuseIPDB for an IP address."""
  443. if not self._is_configured():
  444. return {"source": "abuseipdb", "found": False, "error": "no_api_key"}
  445. params = {"ipAddress": ip, "maxAgeInDays": 90, "verbose": True}
  446. result = self._safe_request("GET", f"{self.BASE_URL}check", params=params)
  447. if not result or "error" in result:
  448. return {"source": "abuseipdb", "found": False, "error": result.get("error") if result else "request_failed"}
  449. if "data" in result:
  450. data = result["data"]
  451. return {
  452. "source": "abuseipdb",
  453. "found": True,
  454. "ip": data.get("ipAddress"),
  455. "is_public": data.get("isPublic"),
  456. "abuse_confidence_score": data.get("abuseConfidenceScore"),
  457. "country": data.get("countryCode"),
  458. "isp": data.get("isp"),
  459. "domain": data.get("domain"),
  460. "usage_type": data.get("usageType"),
  461. "is_tor": data.get("isTor"),
  462. "is_whitelisted": data.get("isWhitelisted"),
  463. "total_reports": data.get("totalReports"),
  464. "num_distinct_users": data.get("numDistinctUsers"),
  465. "last_reported": data.get("lastReportedAt"),
  466. }
  467. return {"source": "abuseipdb", "found": False}
  468. # IOC type detection
  469. def detect_ioc_type(ioc: str) -> str:
  470. """Detect the type of IOC."""
  471. ioc = ioc.strip()
  472. # Hash detection
  473. if re.match(r'^[a-fA-F0-9]{32}$', ioc):
  474. return "md5"
  475. if re.match(r'^[a-fA-F0-9]{40}$', ioc):
  476. return "sha1"
  477. if re.match(r'^[a-fA-F0-9]{64}$', ioc):
  478. return "sha256"
  479. # URL detection
  480. if re.match(r'^https?://', ioc, re.IGNORECASE):
  481. return "url"
  482. # IP detection
  483. 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):
  484. return "ipv4"
  485. # Domain detection (simple)
  486. if re.match(r'^[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(\.[a-zA-Z]{2,})+$', ioc):
  487. return "domain"
  488. return "unknown"
  489. def calculate_file_hashes(filepath: str) -> dict:
  490. """Calculate hashes for a file."""
  491. path = Path(filepath)
  492. if not path.exists():
  493. return {"error": f"File not found: {filepath}"}
  494. data = path.read_bytes()
  495. return {
  496. "md5": hashlib.md5(data).hexdigest(),
  497. "sha1": hashlib.sha1(data).hexdigest(),
  498. "sha256": hashlib.sha256(data).hexdigest(),
  499. "size": len(data),
  500. }
  501. class MalwareTriage:
  502. """Main triage orchestrator."""
  503. def __init__(self, vt_key: Optional[str] = None, abuseipdb_key: Optional[str] = None,
  504. abusech_key: Optional[str] = None, verbose: bool = True):
  505. # Get API keys from multiple sources
  506. vt_api_key = get_api_key("VIRUSTOTAL_API_KEY", vt_key)
  507. abuseipdb_api_key = get_api_key("ABUSEIPDB_API_KEY", abuseipdb_key)
  508. abusech_auth_key = get_api_key("ABUSECH_AUTH_KEY", abusech_key)
  509. if verbose:
  510. if abusech_auth_key:
  511. print(f"[*] abuse.ch Auth-Key loaded (ends with ...{abusech_auth_key[-4:]})", file=sys.stderr)
  512. else:
  513. print("[!] abuse.ch Auth-Key NOT found (MalwareBazaar/ThreatFox will fail)", file=sys.stderr)
  514. if vt_api_key:
  515. print(f"[*] VirusTotal API key loaded (ends with ...{vt_api_key[-4:]})", file=sys.stderr)
  516. else:
  517. print("[!] VirusTotal API key NOT found", file=sys.stderr)
  518. if abuseipdb_api_key:
  519. print(f"[*] AbuseIPDB API key loaded (ends with ...{abuseipdb_api_key[-4:]})", file=sys.stderr)
  520. else:
  521. print("[!] AbuseIPDB API key NOT found", file=sys.stderr)
  522. # Initialize clients with auth keys
  523. self.malwarebazaar = MalwareBazaar(abusech_auth_key)
  524. self.threatfox = ThreatFox(abusech_auth_key)
  525. self.urlhaus = URLhaus(abusech_auth_key)
  526. self.virustotal = VirusTotal(vt_api_key)
  527. self.abuseipdb = AbuseIPDB(abuseipdb_api_key)
  528. self.api_status = {
  529. "malwarebazaar": bool(abusech_auth_key),
  530. "threatfox": bool(abusech_auth_key),
  531. "urlhaus": True, # Works without key but better with
  532. "virustotal": bool(vt_api_key),
  533. "abuseipdb": bool(abuseipdb_api_key),
  534. }
  535. def triage_hash(self, hash_value: str) -> dict:
  536. """Triage a file hash across all sources."""
  537. results = {
  538. "query": hash_value,
  539. "type": detect_ioc_type(hash_value),
  540. "timestamp": datetime.now(timezone.utc).isoformat(),
  541. "sources": [],
  542. "verdict": "unknown",
  543. "summary": {},
  544. }
  545. # Query all sources
  546. sources_to_query = [
  547. ("malwarebazaar", self.malwarebazaar.query_hash),
  548. ("urlhaus", self.urlhaus.query_hash),
  549. ("threatfox", self.threatfox.query_ioc),
  550. ("virustotal", self.virustotal.query_hash),
  551. ]
  552. for source_name, query_func in sources_to_query:
  553. try:
  554. result = query_func(hash_value)
  555. results["sources"].append(result)
  556. time.sleep(0.5) # Rate limiting
  557. except Exception as e:
  558. results["sources"].append({"source": source_name, "found": False, "error": str(e)})
  559. # Aggregate verdict
  560. results["verdict"], results["summary"] = self._aggregate_hash_verdict(results["sources"])
  561. return results
  562. def triage_ip(self, ip: str) -> dict:
  563. """Triage an IP address across all sources."""
  564. results = {
  565. "query": ip,
  566. "type": "ipv4",
  567. "timestamp": datetime.now(timezone.utc).isoformat(),
  568. "sources": [],
  569. "verdict": "unknown",
  570. "summary": {},
  571. }
  572. # Query all sources
  573. sources_to_query = [
  574. ("urlhaus", self.urlhaus.query_host),
  575. ("threatfox", self.threatfox.query_ioc),
  576. ("virustotal", self.virustotal.query_ip),
  577. ("abuseipdb", self.abuseipdb.query_ip),
  578. ]
  579. for source_name, query_func in sources_to_query:
  580. try:
  581. result = query_func(ip)
  582. results["sources"].append(result)
  583. time.sleep(0.5)
  584. except Exception as e:
  585. results["sources"].append({"source": source_name, "found": False, "error": str(e)})
  586. results["verdict"], results["summary"] = self._aggregate_ip_verdict(results["sources"])
  587. return results
  588. def triage_domain(self, domain: str) -> dict:
  589. """Triage a domain across all sources."""
  590. results = {
  591. "query": domain,
  592. "type": "domain",
  593. "timestamp": datetime.now(timezone.utc).isoformat(),
  594. "sources": [],
  595. "verdict": "unknown",
  596. "summary": {},
  597. }
  598. sources_to_query = [
  599. ("urlhaus", self.urlhaus.query_host),
  600. ("threatfox", self.threatfox.query_ioc),
  601. ("virustotal", self.virustotal.query_domain),
  602. ]
  603. for source_name, query_func in sources_to_query:
  604. try:
  605. result = query_func(domain)
  606. results["sources"].append(result)
  607. time.sleep(0.5)
  608. except Exception as e:
  609. results["sources"].append({"source": source_name, "found": False, "error": str(e)})
  610. results["verdict"], results["summary"] = self._aggregate_domain_verdict(results["sources"])
  611. return results
  612. def triage_url(self, url: str) -> dict:
  613. """Triage a URL across all sources."""
  614. results = {
  615. "query": url,
  616. "type": "url",
  617. "timestamp": datetime.now(timezone.utc).isoformat(),
  618. "sources": [],
  619. "verdict": "unknown",
  620. "summary": {},
  621. }
  622. sources_to_query = [
  623. ("urlhaus", self.urlhaus.query_url),
  624. ("threatfox", self.threatfox.query_ioc),
  625. ]
  626. for source_name, query_func in sources_to_query:
  627. try:
  628. result = query_func(url)
  629. results["sources"].append(result)
  630. time.sleep(0.5)
  631. except Exception as e:
  632. results["sources"].append({"source": source_name, "found": False, "error": str(e)})
  633. results["verdict"], results["summary"] = self._aggregate_url_verdict(results["sources"])
  634. return results
  635. def triage_file(self, filepath: str) -> dict:
  636. """Triage a file by calculating hashes and querying."""
  637. hashes = calculate_file_hashes(filepath)
  638. if "error" in hashes:
  639. return {"error": hashes["error"]}
  640. results = self.triage_hash(hashes["sha256"])
  641. results["file_info"] = {
  642. "path": filepath,
  643. "hashes": hashes,
  644. }
  645. return results
  646. def triage_auto(self, ioc: str) -> dict:
  647. """Auto-detect IOC type and triage."""
  648. ioc_type = detect_ioc_type(ioc)
  649. if ioc_type in ["md5", "sha1", "sha256"]:
  650. return self.triage_hash(ioc)
  651. elif ioc_type == "ipv4":
  652. return self.triage_ip(ioc)
  653. elif ioc_type == "domain":
  654. return self.triage_domain(ioc)
  655. elif ioc_type == "url":
  656. return self.triage_url(ioc)
  657. else:
  658. return {"error": f"Unknown IOC type: {ioc}", "query": ioc}
  659. def _aggregate_hash_verdict(self, sources: list) -> tuple:
  660. """Aggregate verdict from hash query results."""
  661. malware_names = set()
  662. tags = set()
  663. found_in = []
  664. vt_detection = None
  665. for source in sources:
  666. if source.get("found"):
  667. found_in.append(source["source"])
  668. # Extract malware family names
  669. if source.get("signature"):
  670. malware_names.add(source["signature"])
  671. if source.get("popular_threat_names"):
  672. malware_names.add(source["popular_threat_names"])
  673. if source.get("malware"):
  674. malware_names.add(source["malware"])
  675. # Extract tags
  676. if source.get("tags"):
  677. tags.update(source["tags"])
  678. # Get VT detection rate
  679. if source["source"] == "virustotal" and source.get("detections"):
  680. vt_detection = source["detections"]
  681. # Determine verdict
  682. if not found_in:
  683. verdict = "clean_or_unknown"
  684. elif vt_detection and vt_detection.get("malicious", 0) > 5:
  685. verdict = "malicious"
  686. elif found_in:
  687. verdict = "suspicious"
  688. else:
  689. verdict = "unknown"
  690. summary = {
  691. "found_in_sources": found_in,
  692. "malware_families": list(malware_names),
  693. "tags": list(tags),
  694. }
  695. if vt_detection:
  696. summary["virustotal_detection"] = f"{vt_detection.get('malicious', 0)}/{vt_detection.get('total', 0)}"
  697. return verdict, summary
  698. def _aggregate_ip_verdict(self, sources: list) -> tuple:
  699. """Aggregate verdict from IP query results."""
  700. found_in = []
  701. abuse_score = None
  702. vt_malicious = 0
  703. url_count = 0
  704. for source in sources:
  705. if source.get("found"):
  706. found_in.append(source["source"])
  707. if source["source"] == "abuseipdb":
  708. abuse_score = source.get("abuse_confidence_score")
  709. if source["source"] == "virustotal" and source.get("detections"):
  710. vt_malicious = source["detections"].get("malicious", 0)
  711. if source["source"] == "urlhaus":
  712. url_count = source.get("url_count", 0)
  713. # Determine verdict
  714. if abuse_score and abuse_score > 50:
  715. verdict = "malicious"
  716. elif vt_malicious > 3:
  717. verdict = "malicious"
  718. elif url_count > 0 or found_in:
  719. verdict = "suspicious"
  720. else:
  721. verdict = "clean_or_unknown"
  722. summary = {
  723. "found_in_sources": found_in,
  724. }
  725. if abuse_score is not None:
  726. summary["abuse_confidence_score"] = abuse_score
  727. if vt_malicious:
  728. summary["virustotal_malicious"] = vt_malicious
  729. if url_count:
  730. summary["urlhaus_url_count"] = url_count
  731. return verdict, summary
  732. def _aggregate_domain_verdict(self, sources: list) -> tuple:
  733. """Aggregate verdict from domain query results."""
  734. found_in = []
  735. vt_malicious = 0
  736. url_count = 0
  737. for source in sources:
  738. if source.get("found"):
  739. found_in.append(source["source"])
  740. if source["source"] == "virustotal" and source.get("detections"):
  741. vt_malicious = source["detections"].get("malicious", 0)
  742. if source["source"] == "urlhaus":
  743. url_count = source.get("url_count", 0)
  744. if vt_malicious > 3:
  745. verdict = "malicious"
  746. elif url_count > 0 or found_in:
  747. verdict = "suspicious"
  748. else:
  749. verdict = "clean_or_unknown"
  750. return verdict, {"found_in_sources": found_in, "virustotal_malicious": vt_malicious, "urlhaus_url_count": url_count}
  751. def _aggregate_url_verdict(self, sources: list) -> tuple:
  752. """Aggregate verdict from URL query results."""
  753. found_in = []
  754. threat_type = None
  755. for source in sources:
  756. if source.get("found"):
  757. found_in.append(source["source"])
  758. if source.get("threat"):
  759. threat_type = source["threat"]
  760. if found_in:
  761. verdict = "malicious"
  762. else:
  763. verdict = "clean_or_unknown"
  764. return verdict, {"found_in_sources": found_in, "threat_type": threat_type}
  765. def format_triage_report(results: dict, format_type: str = "text") -> str:
  766. """Format triage results for output."""
  767. if format_type == "json":
  768. return json.dumps(results, indent=2, default=str)
  769. # Text format
  770. lines = []
  771. lines.append("=" * 70)
  772. lines.append("MALWARE TRIAGE REPORT")
  773. lines.append("=" * 70)
  774. lines.append(f"\n[QUERY]")
  775. lines.append(f" IOC: {results.get('query', 'N/A')}")
  776. lines.append(f" Type: {results.get('type', 'N/A')}")
  777. lines.append(f" Timestamp: {results.get('timestamp', 'N/A')}")
  778. # File info if present
  779. if results.get("file_info"):
  780. fi = results["file_info"]
  781. lines.append(f"\n[FILE INFO]")
  782. lines.append(f" Path: {fi['path']}")
  783. lines.append(f" MD5: {fi['hashes'].get('md5')}")
  784. lines.append(f" SHA1: {fi['hashes'].get('sha1')}")
  785. lines.append(f" SHA256: {fi['hashes'].get('sha256')}")
  786. lines.append(f" Size: {fi['hashes'].get('size'):,} bytes")
  787. # Verdict
  788. verdict = results.get("verdict", "unknown")
  789. verdict_emoji = {"malicious": "🔴", "suspicious": "🟡", "clean_or_unknown": "🟢", "unknown": "⚪"}.get(verdict, "⚪")
  790. lines.append(f"\n[VERDICT] {verdict_emoji} {verdict.upper()}")
  791. # Summary
  792. summary = results.get("summary", {})
  793. if summary:
  794. lines.append(f"\n[SUMMARY]")
  795. if summary.get("found_in_sources"):
  796. lines.append(f" Found in: {', '.join(summary['found_in_sources'])}")
  797. if summary.get("malware_families"):
  798. lines.append(f" Malware: {', '.join(summary['malware_families'])}")
  799. if summary.get("virustotal_detection"):
  800. lines.append(f" VT Score: {summary['virustotal_detection']}")
  801. if summary.get("abuse_confidence_score") is not None:
  802. lines.append(f" AbuseIPDB Score: {summary['abuse_confidence_score']}%")
  803. if summary.get("tags"):
  804. lines.append(f" Tags: {', '.join(summary['tags'][:10])}")
  805. # Source details
  806. lines.append(f"\n[SOURCE DETAILS]")
  807. for source in results.get("sources", []):
  808. source_name = source.get("source", "unknown").upper()
  809. found = "✓" if source.get("found") else "✗"
  810. lines.append(f"\n [{source_name}] {found}")
  811. if source.get("error"):
  812. lines.append(f" Error: {source['error']}")
  813. continue
  814. if not source.get("found"):
  815. lines.append(f" Not found in database")
  816. continue
  817. # Source-specific details
  818. if source.get("signature"):
  819. lines.append(f" Malware: {source['signature']}")
  820. if source.get("popular_threat_names"):
  821. lines.append(f" Threat: {source['popular_threat_names']}")
  822. if source.get("detection_rate"):
  823. lines.append(f" Detection: {source['detection_rate']}")
  824. if source.get("first_seen"):
  825. lines.append(f" First seen: {source['first_seen']}")
  826. if source.get("abuse_confidence_score") is not None:
  827. lines.append(f" Abuse score: {source['abuse_confidence_score']}%")
  828. if source.get("total_reports"):
  829. lines.append(f" Reports: {source['total_reports']}")
  830. if source.get("url_count"):
  831. lines.append(f" Malicious URLs: {source['url_count']}")
  832. if source.get("tags"):
  833. lines.append(f" Tags: {', '.join(source['tags'][:5])}")
  834. lines.append("\n" + "=" * 70)
  835. return "\n".join(lines)
  836. def main():
  837. parser = argparse.ArgumentParser(
  838. description="Malware triage - Multi-source threat intelligence lookup",
  839. formatter_class=argparse.RawDescriptionHelpFormatter,
  840. epilog="""
  841. Examples:
  842. %(prog)s 44d88612fea8a8f36de82e1278abb02f # MD5 hash
  843. %(prog)s -t hash e3b0c44298fc1c149afbf4c8996fb924... # SHA256 hash
  844. %(prog)s -t ip 45.33.32.156 # IP address
  845. %(prog)s -t domain evil.com # Domain
  846. %(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
  847. %(prog)s -t file /path/to/sample.exe # File
  848. %(prog)s --batch iocs.txt # Batch mode
  849. API Key Configuration (in priority order):
  850. 1. Command line: --abusech-key, --vt-key, --abuseipdb-key
  851. 2. Environment variables: ABUSECH_AUTH_KEY, VIRUSTOTAL_API_KEY, ABUSEIPDB_API_KEY
  852. 3. Config file: ~/.config/malware-triage/config.json
  853. Create config file:
  854. %(prog)s --init-config
  855. Get your API keys from:
  856. - abuse.ch (MalwareBazaar/ThreatFox): https://auth.abuse.ch/
  857. - VirusTotal: https://www.virustotal.com/gui/my-apikey
  858. - AbuseIPDB: https://www.abuseipdb.com/account/api
  859. """
  860. )
  861. parser.add_argument("ioc", nargs="?", help="IOC to triage (hash, IP, domain, URL)")
  862. parser.add_argument("-t", "--type", choices=["hash", "ip", "domain", "url", "file", "auto"],
  863. default="auto", help="IOC type (default: auto-detect)")
  864. parser.add_argument("-f", "--format", choices=["text", "json"], default="text",
  865. help="Output format (default: text)")
  866. parser.add_argument("-o", "--output", help="Output file")
  867. parser.add_argument("--batch", help="File containing IOCs (one per line)")
  868. parser.add_argument("--status", action="store_true", help="Show API configuration status")
  869. parser.add_argument("--init-config", action="store_true", help="Create default config file")
  870. parser.add_argument("--abusech-key", help="abuse.ch Auth-Key (for MalwareBazaar/ThreatFox)")
  871. parser.add_argument("--vt-key", help="VirusTotal API key")
  872. parser.add_argument("--abuseipdb-key", help="AbuseIPDB API key")
  873. args = parser.parse_args()
  874. if args.init_config:
  875. create_default_config()
  876. return
  877. triage = MalwareTriage(
  878. vt_key=args.vt_key,
  879. abuseipdb_key=args.abuseipdb_key,
  880. abusech_key=args.abusech_key
  881. )
  882. if args.status:
  883. print("API Configuration Status:")
  884. print("-" * 40)
  885. for api, configured in triage.api_status.items():
  886. status = "✓ Configured" if configured else "✗ Not configured"
  887. print(f" {api:<15} {status}")
  888. # Show config file location
  889. print()
  890. print("Config file locations (in priority order):")
  891. config_paths = [
  892. Path.home() / ".config" / "malware-triage" / "config.json",
  893. Path.home() / ".malware-triage.json",
  894. Path("config.json"),
  895. ]
  896. for p in config_paths:
  897. exists = "✓" if p.exists() else "✗"
  898. print(f" {exists} {p}")
  899. print()
  900. print("Run with --init-config to create a config file.")
  901. return
  902. if not args.ioc and not args.batch:
  903. parser.print_help()
  904. return
  905. # Process IOCs
  906. results_list = []
  907. if args.batch:
  908. iocs = Path(args.batch).read_text().strip().split("\n")
  909. for ioc in iocs:
  910. ioc = ioc.strip()
  911. if not ioc or ioc.startswith("#"):
  912. continue
  913. print(f"Triaging: {ioc}...", file=sys.stderr)
  914. result = triage.triage_auto(ioc)
  915. results_list.append(result)
  916. else:
  917. if args.type == "file":
  918. result = triage.triage_file(args.ioc)
  919. elif args.type == "hash":
  920. result = triage.triage_hash(args.ioc)
  921. elif args.type == "ip":
  922. result = triage.triage_ip(args.ioc)
  923. elif args.type == "domain":
  924. result = triage.triage_domain(args.ioc)
  925. elif args.type == "url":
  926. result = triage.triage_url(args.ioc)
  927. else:
  928. result = triage.triage_auto(args.ioc)
  929. results_list.append(result)
  930. # Format output
  931. if args.batch and args.format == "json":
  932. output = json.dumps(results_list, indent=2, default=str)
  933. elif args.batch:
  934. output = "\n\n".join(format_triage_report(r, args.format) for r in results_list)
  935. else:
  936. output = format_triage_report(results_list[0], args.format)
  937. if args.output:
  938. Path(args.output).write_text(output)
  939. print(f"Results written to {args.output}", file=sys.stderr)
  940. else:
  941. print(output)
  942. if __name__ == "__main__":
  943. main()

Ratings and comments

Sign in to rate this skill.

Sign in

Free to use. If it’s helped, pass it on.