mcpField
B
building-ioc-defanging-and-sharing-pipeline

building-ioc-defanging-and-sharing-pipeline

github.com/mukul975安全35.2k148 次安装8 周前更新
代码仓库

关于 building-ioc-defanging-and-sharing-pipeline

介绍将原始失陷指标转化为安全、规范且去重结果的安全工作流,涵盖脱敏、STIX 2.1 转换,以及通过 MISP、TAXII 或邮件共享。

主要功能

  1. 01提取并规范化 IOC
  2. 02去重并验证指标
  3. 03对 URL、域名、IP 和邮件脱敏
  4. 04将指标转换为 STIX 2.1
  5. 05通过 MISP 和 TAXII 共享
  6. 06应用 TLP 标记

适用场景

  1. 01为事件报告准备安全指标
  2. 02汇总威胁情报源中的指标
  3. 03向 MISP 或 TAXII 发布指标
  4. 04生成机器可读的 STIX 包

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/mukul975/anthropic-cybersecurity-skills --skill building-ioc-defanging-and-sharing-pipeline

安装后在 Claude Code 中输入/building-ioc-defanging-and-sharing-pipeline确认已加载。

包含的文件

除 SKILL.md 外,安装时一起下载的参考资料和脚本。

LICENSE
references/
api-reference.md
scripts/
agent.py

详细介绍

构建 IOC 去毒化与共享流水线

概述

IOC 去毒化会修改潜在恶意的指标(URL、IP 地址、域名、电子邮件地址),以防止意外点击或执行,同时保持可读性以便分析和共享。本技能涵盖构建一条自动化流水线:从多个来源摄取原始 IOC,对其进行规范化与去重,应用去毒化以便人类安全查看,将其转换为 STIX 2.1 格式以供机器使用,并通过 TAXII 服务、MISP 实例和电子邮件报告进行分发。

何时使用

  • 在您的环境中部署或配置构建 IOC 去毒化与共享流水线能力时
  • 在依据合规要求建立安全控制措施时
  • 在为该领域构建或改进安全架构时
  • 在开展需要此实现的安全评估时

前提条件

  • Python 3.9+ 以及 defang、ioc-fanger、stix2、requests、validators 库
  • 用于自动化共享的 MISP 实例或 TAXII 服务
  • 了解 IOC 类型:IPv4/IPv6、域名、URL、电子邮件地址、文件哈希
  • 熟悉 STIX 2.1 Indicator 模式与 TLP 标记定义
  • 可访问威胁情报源以摄取 IOC

核心概念

IOC 去毒化标准

去毒化会替换可活动的协议和域名组件以防止执行:http:// 变为 hxxp://,https:// 变为 hxxps://,域名/IP 中的点变为 [.],电子邮件中的 @ 变为 [@]。这对于在报告、电子邮件、Slack 频道和粘贴站点中共享 IOC 至关重要,因为在这些地方自动链接可能会触发与恶意基础设施的网络连接。

IOC 规范化

来自不同来源的原始 IOC 格式不一致。规范化包括转换为小写、去除末尾斜杠和空白、从 URL 中提取域名、解析 URL 编码、验证格式正确性,以及跨来源去重。

STIX 2.1 Indicator 模式

STIX 模式以标准化格式表达 IOC:[ipv4-addr:value = '203.0.113.1']、[domain-name:value = 'malicious.example.com']、[url:value = 'http://evil.com/payload']、[file:hashes.'SHA-256' = 'abc123...']。每个 indicator 包含 valid_from、indicator_types、confidence,以及可选的 TLP 标记。

工作流

步骤 1:构建 IOC 提取与规范化
import re
import hashlib
from urllib.parse import urlparse, unquote
from datetime import datetime

class IOCExtractor:
    """Extract and normalize IOCs from text."""

    PATTERNS = {
        "ipv4": r'\b(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]?\d)\b',
        "domain": r'\b(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}\b',
        "url": r'https?://[^\s<>"{}|\\^`\[\]]+',
        "email": r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b',
        "md5": r'\b[a-fA-F0-9]{32}\b',
        "sha1": r'\b[a-fA-F0-9]{40}\b',
        "sha256": r'\b[a-fA-F0-9]{64}\b',
    }

    WHITELIST_DOMAINS = {
        "google.com", "microsoft.com", "amazon.com", "github.com",
        "cloudflare.com", "akamai.com", "example.com",
    }

    def extract_from_text(self, text):
        """Extract all IOC types from free text."""
        # Refang any already-defanged indicators first
        text = self._refang(text)
        iocs = {"ipv4": set(), "domain": set(), "url": set(),
                "email": set(), "md5": set(), "sha1": set(), "sha256": set()}

        for ioc_type, pattern in self.PATTERNS.items():
            matches = re.findall(pattern, text)
            for match in matches:
                normalized = self._normalize(match, ioc_type)
                if normalized and not self._is_whitelisted(normalized, ioc_type):
                    iocs[ioc_type].add(normalized)

        # Remove domains that are part of URLs
        url_domains = set()
        for url in iocs["url"]:
            parsed = urlparse(url)
            url_domains.add(parsed.netloc)
        iocs["domain"] -= url_domains

        total = sum(len(v) for v in iocs.values())
        print(f"[+] Extracted {total} unique IOCs from text")
        return {k: sorted(v) for k, v in iocs.items()}

    def _refang(self, text):
        """Convert defanged indicators back to active form."""
        text = text.replace("hxxp://", "http://").replace("hxxps://", "https://")
        text = text.replace("[.]", ".").replace("[@]", "@")
        text = text.replace("[://]", "://").replace("(.)", ".")
        return text

    def _normalize(self, value, ioc_type):
        """Normalize an IOC value."""
        value = value.strip().lower()
        if ioc_type == "url":
            value = unquote(value).rstrip("/")
        elif ioc_type == "domain":
            value = value.rstrip(".")
        return value

    def _is_whitelisted(self, value, ioc_type):
        """Check if IOC is in whitelist."""
        if ioc_type == "domain":
            return value in self.WHITELIST_DOMAINS
        if ioc_type == "url":
            parsed = urlparse(value)
            return parsed.netloc in self.WHITELIST_DOMAINS
        return False

extractor = IOCExtractor()
sample_text = """
Malware C2: hxxps://evil-domain[.]com/beacon
Drops payload from 192.168.1.100 and contacts 10[.]0[.]0[.]1
SHA256: 275a021bbfb6489e54d471899f7db9d1663fc695ec2fe2a2c4538aabf651fd0f
Phishing email from attacker[@]phishing-domain[.]com
"""
iocs = extractor.extract_from_text(sample_text)
步骤 2:去毒化引擎
class IOCDefanger:
    """Defang IOCs for safe sharing in reports and communications."""

    def defang_url(self, url):
        return url.replace("http://", "hxxp://").replace("https://", "hxxps://").replace(".", "[.]")

    def defang_domain(self, domain):
        return domain.replace(".", "[.]")

    def defang_ip(self, ip):
        return ip.replace(".", "[.]")

    def defang_email(self, email):
        return email.replace("@", "[@]").replace(".", "[.]")

    def defang_all(self, iocs):
        """Defang all IOCs in a dictionary."""
        defanged = {}
        for ioc_type, values in iocs.items():
            if ioc_type == "url":
                defanged[ioc_type] = [self.defang_url(v) for v in values]
            elif ioc_type == "domain":
                defanged[ioc_type] = [self.defang_domain(v) for v in values]
            elif ioc_type == "ipv4":
                defanged[ioc_type] = [self.defang_ip(v) for v in values]
            elif ioc_type == "email":
                defanged[ioc_type] = [self.defang_email(v) for v in values]
            else:
                defanged[ioc_type] = values  # Hashes don't need defanging
        return defanged

    def generate_sharing_report(self, iocs, defanged, report_name="IOC Report"):
        """Generate a human-readable defanged IOC report."""
        report = f"# {report_name}\n"
        report += f"Generated: {datetime.now().isoformat()}\n\n"

        for ioc_type in ["url", "domain", "ipv4", "email", "sha256", "sha1", "md5"]:
            values = defanged.get(ioc_type, [])
            if values:
                report += f"## {ioc_type.upper()} ({len(values)})\n"
                for v in values:
                    report += f"- `{v}`\n"
                report += "\n"

        return report

defanger = IOCDefanger()
defanged = defanger.defang_all(iocs)
report = defanger.generate_sharing_report(iocs, defanged, "Malware Campaign IOCs")
print(report)
步骤 3:转换为 STIX 2.1 格式
from stix2 import Indicator, Bundle, TLP_WHITE, TLP_GREEN, TLP_AMBER
from datetime import datetime

class STIXConverter:
    """Convert raw IOCs to STIX 2.1 Indicator objects."""

    TLP_MAP = {"white": TLP_WHITE, "green": TLP_GREEN, "amber": TLP_AMBER}

    def iocs_to_stix(self, iocs, tlp="green", confidence=75):
        """Convert IOC dictionary to STIX 2.1 bundle."""
        stix_objects = []
        marking = self.TLP_MAP.get(tlp, TLP_GREEN)

        for ip in iocs.get("ipv4", []):
            stix_objects.append(Indicator(
                name=f"Malicious IP: {ip}",
                pattern=f"[ipv4-addr:value = '{ip}']",
                pattern_type="stix",
                valid_from=datetime.now(),
                indicator_types=["malicious-activity"],
                confidence=confidence,
                object_marking_refs=[marking],
            ))

        for domain in iocs.get("domain", []):
            stix_objects.append(Indicator(
                name=f"Malicious Domain: {domain}",
                pattern=f"[domain-name:value = '{domain}']",
                pattern_type="stix",
                valid_from=datetime.now(),
                indicator_types=["malicious-activity"],
                confidence=confidence,
                object_marking_refs=[marking],
            ))

        for url in iocs.get("url", []):
            escaped = url.replace("'", "\\'")
            stix_objects.append(Indicator(
                name=f"Malicious URL: {url[:60]}",
                pattern=f"[url:value = '{escaped}']",
                pattern_type="stix",
                valid_from=datetime.now(),
                indicator_types=["malicious-activity"],
                confidence=confidence,
                object_marking_refs=[marking],
            ))

        for sha256 in iocs.get("sha256", []):
            stix_objects.append(Indicator(
                name=f"Malicious File Hash: {sha256[:16]}...",
                pattern=f"[file:hashes.'SHA-256' = '{sha256}']",
                pattern_type="stix",
                valid_from=datetime.now(),
                indicator_types=["malicious-activity"],
                confidence=confidence,
                object_marking_refs=[marking],
            ))

        bundle = Bundle(objects=stix_objects)
        print(f"[+] Created STIX bundle with {len(stix_objects)} indicators")
        return bundle

converter = STIXConverter()
stix_bundle = converter.iocs_to_stix(iocs, tlp="amber", confidence=80)
with open("iocs_stix_bundle.json", "w") as f:
    f.write(stix_bundle.serialize(pretty=True))
步骤 4:通过 MISP 和 TAXII 分发
import requests
import json

class IOCDistributor:
    """Distribute IOCs through various channels."""

    def push_to_misp(self, iocs, misp_url, misp_key, event_info):
        """Push IOCs to MISP as a new event."""
        headers = {
            "Authorization": misp_key,
            "Content-Type": "application/json",
            "Accept": "application/json",
        }
        event = {
            "Event": {
                "info": event_info,
                "distribution": "1",  # This community only
                "threat_level_id": "2",  # Medium
                "analysis": "2",  # Completed
                "Attribute": [],
            }
        }

        type_mapping = {
            "ipv4": "ip-dst",
            "domain": "domain",
            "url": "url",
            "email": "email-src",
            "md5": "md5",
            "sha1": "sha1",
            "sha256": "sha256",
        }

        for ioc_type, values in iocs.items():
            misp_type = type_mapping.get(ioc_type)
            if misp_type:
                for value in values:
                    event["Event"]["Attribute"].append({
                        "type": misp_type,
                        "value": value,
                        "category": "Network activity" if ioc_type in ("ipv4", "domain", "url") else "Payload delivery",
                        "to_ids": True,
                    })

        resp = requests.post(
            f"{misp_url}/events",
            headers=headers,
            json=event,
            verify=not os.environ.get("SKIP_TLS_VERIFY", "").lower() == "true",  # Set SKIP_TLS_VERIFY=true for self-signed certs in lab environments
        )
        if resp.status_code == 200:
            event_id = resp.json().get("Event", {}).get("id", "")
            print(f"[+] MISP event created: {event_id}")
            return event_id
        else:
            print(f"[-] MISP error: {resp.status_code} - {resp.text[:200]}")
            return None

    def push_to_taxii(self, stix_bundle, taxii_url, collection_id, username, password):
        """Push STIX bundle to TAXII 2.1 collection."""
        from taxii2client.v21 import Collection
        collection = Collection(
            f"{taxii_url}/collections/{collection_id}/",
            user=username, password=password,
        )
        response = collection.add_objects(stix_bundle.serialize())
        print(f"[+] TAXII: Published bundle, status: {response.status}")
        return response

distributor = IOCDistributor()
distributor.push_to_misp(
    iocs,
    misp_url="https://misp.organization.com",
    misp_key="YOUR_MISP_API_KEY",
    event_info="Malware Campaign IOCs - 2025",
)

验证标准

  • 能够从自由文本中正确提取 IOC,并支持反向去毒化
  • 去毒化产生安全、不可点击的指标
  • STIX 2.1 bundle 包含有效的 indicator 模式
  • IOC 成功分发到 MISP 和 TAXII
  • 去重可防止重复指标
  • 白名单可防止对已知良好域名产生误报

参考资料

评论

支持 Markdown