building-adversary-infrastructure-tracking-system

构建自动化系统,利用被动 DNS、证书透明度、WHOIS 数据和 IP 富化来映射和监控威胁行为者的命令与控制(C2)网络,追踪对手基础设施。

9 stars

Best use case

building-adversary-infrastructure-tracking-system is best used when you need a repeatable AI agent workflow instead of a one-off prompt.

构建自动化系统,利用被动 DNS、证书透明度、WHOIS 数据和 IP 富化来映射和监控威胁行为者的命令与控制(C2)网络,追踪对手基础设施。

Teams using building-adversary-infrastructure-tracking-system should expect a more consistent output, faster repeated execution, less prompt rewriting.

When to use this skill

  • You want a reusable workflow that can be run more than once with consistent structure.

When not to use this skill

  • You only need a quick one-off answer and do not need a reusable workflow.
  • You cannot install or maintain the underlying files, dependencies, or repository context.

Installation

Claude Code / Cursor / Codex

$curl -o ~/.claude/skills/building-adversary-infrastructure-tracking-system/SKILL.md --create-dirs "https://raw.githubusercontent.com/killvxk/cybersecurity-skills-zh/main/skills/building-adversary-infrastructure-tracking-system/SKILL.md"

Manual Installation

  1. Download SKILL.md from GitHub
  2. Place it in .claude/skills/building-adversary-infrastructure-tracking-system/SKILL.md inside your project
  3. Restart your AI agent — it will auto-discover the skill

How building-adversary-infrastructure-tracking-system Compares

Feature / Agentbuilding-adversary-infrastructure-tracking-systemStandard Approach
Platform SupportNot specifiedLimited / Varies
Context Awareness High Baseline
Installation ComplexityUnknownN/A

Frequently Asked Questions

What does this skill do?

构建自动化系统,利用被动 DNS、证书透明度、WHOIS 数据和 IP 富化来映射和监控威胁行为者的命令与控制(C2)网络,追踪对手基础设施。

Where can I find the source code?

You can find the source code on GitHub using the link provided at the top of the page.

SKILL.md Source

# 构建对手基础设施追踪系统

## 概述

对手基础设施追踪利用被动 DNS 记录、证书透明度日志、WHOIS 注册数据和 IP 富化来发现、映射和监控威胁行为者的命令与控制(C2)网络。攻击者在不同攻击活动中频繁复用托管服务商、注册商、SSL 证书和命名模式,使分析人员能够从已知指标枢纽到发现新的基础设施。本技能涵盖构建识别基础设施关系的自动化追踪系统、检测与对手模式匹配的新注册域名,以及维护持续更新的威胁行为者网络地图。

## 前置条件

- Python 3.9+,安装 `requests`、`dnspython`、`python-whois`、`shodan`、`networkx` 库
- API 密钥:SecurityTrails、PassiveTotal/RiskIQ、Shodan、VirusTotal
- 访问被动 DNS 数据源
- 了解 DNS 基础设施、托管和域名注册
- 用于关系可视化的图数据库(Neo4j)或 NetworkX

## 核心概念

### 被动 DNS

被动 DNS 捕获历史 DNS 解析数据,记录哪些域名解析到了哪些 IP 以及发生时间。与主动 DNS 查询不同,即使记录已更改,被动 DNS 也会保留历史关系,使分析人员能够追踪基础设施变化、识别共享托管模式,并发现历史上解析到相同 IP 的相关域名。

### 基础设施枢纽

枢纽通过跟踪连接来识别相关基础设施:IP 枢纽(查找某 IP 上的所有域名)、域名枢纽(查找某域名解析过的所有 IP)、WHOIS 枢纽(查找同一注册人的域名)、证书枢纽(查找共享 SSL 证书的主机)以及 NS/MX 枢纽(查找使用相同域名服务器或邮件服务器的域名)。

### 对手基础设施模式

威胁行为者表现出一定模式:偏好的注册商(Namecheap、REG.RU、Tucows)、偏好的托管(防弹托管服务商、云服务)、域名生成算法(DGA)、一致的命名模式,以及跨攻击活动复用证书。

## 实践步骤

### 步骤 1:被动 DNS 基础设施发现

```python
import requests
import json
from collections import defaultdict
from datetime import datetime

class InfrastructureTracker:
    def __init__(self, securitytrails_key=None, vt_key=None, shodan_key=None):
        self.st_key = securitytrails_key
        self.vt_key = vt_key
        self.shodan_key = shodan_key
        self.infrastructure_graph = defaultdict(lambda: {"nodes": set(), "edges": []})

    def passive_dns_lookup(self, domain):
        """查询域名的被动 DNS 历史解析记录。"""
        headers = {"apikey": self.st_key}
        url = f"https://api.securitytrails.com/v1/history/{domain}/dns/a"
        resp = requests.get(url, headers=headers, timeout=30)
        if resp.status_code == 200:
            records = resp.json().get("records", [])
            history = []
            for record in records:
                for value in record.get("values", []):
                    history.append({
                        "domain": domain,
                        "ip": value.get("ip", ""),
                        "first_seen": record.get("first_seen", ""),
                        "last_seen": record.get("last_seen", ""),
                        "type": record.get("type", "a"),
                    })
            print(f"[+] 被动 DNS for {domain}: {len(history)} 条记录")
            return history
        return []

    def reverse_ip_lookup(self, ip_address):
        """查找托管在某 IP 上的所有域名。"""
        headers = {"apikey": self.st_key}
        url = f"https://api.securitytrails.com/v1/ips/nearby/{ip_address}"
        resp = requests.get(url, headers=headers, timeout=30)
        if resp.status_code == 200:
            blocks = resp.json().get("blocks", [])
            domains = []
            for block in blocks:
                for site in block.get("sites", []):
                    domains.append(site)
            print(f"[+] 反向 IP 查询 {ip_address}: {len(domains)} 个域名")
            return domains
        return []

    def whois_lookup(self, domain):
        """获取用于枢纽的 WHOIS 注册数据。"""
        headers = {"apikey": self.st_key}
        url = f"https://api.securitytrails.com/v1/domain/{domain}/whois"
        resp = requests.get(url, headers=headers, timeout=30)
        if resp.status_code == 200:
            data = resp.json()
            whois_data = {
                "domain": domain,
                "registrar": data.get("registrar", ""),
                "registrant_org": data.get("registrant_org", ""),
                "registrant_email": data.get("registrant_email", ""),
                "name_servers": data.get("nameServers", []),
                "created_date": data.get("createdDate", ""),
                "updated_date": data.get("updatedDate", ""),
                "expires_date": data.get("expiresDate", ""),
            }
            return whois_data
        return {}

    def pivot_from_seed(self, seed_indicator, indicator_type="domain", depth=2):
        """从种子指标递归枢纽以发现基础设施。"""
        discovered = {"domains": set(), "ips": set(), "relationships": []}

        if indicator_type == "domain":
            discovered["domains"].add(seed_indicator)
            # 获取域名的 IP
            pdns = self.passive_dns_lookup(seed_indicator)
            for record in pdns:
                ip = record["ip"]
                discovered["ips"].add(ip)
                discovered["relationships"].append({
                    "source": seed_indicator, "target": ip,
                    "type": "resolves_to",
                    "first_seen": record["first_seen"],
                    "last_seen": record["last_seen"],
                })

                if depth > 1:
                    # 对已发现的 IP 进行反向查询
                    reverse_domains = self.reverse_ip_lookup(ip)
                    for rd in reverse_domains[:20]:
                        discovered["domains"].add(rd)
                        discovered["relationships"].append({
                            "source": rd, "target": ip,
                            "type": "hosted_on",
                        })

        elif indicator_type == "ip":
            discovered["ips"].add(seed_indicator)
            domains = self.reverse_ip_lookup(seed_indicator)
            for domain in domains[:20]:
                discovered["domains"].add(domain)
                discovered["relationships"].append({
                    "source": domain, "target": seed_indicator,
                    "type": "hosted_on",
                })

        print(f"[+] 从 {seed_indicator} 枢纽: "
              f"{len(discovered['domains'])} 个域名, "
              f"{len(discovered['ips'])} 个 IP, "
              f"{len(discovered['relationships'])} 个关系")
        return discovered

tracker = InfrastructureTracker(
    securitytrails_key="YOUR_ST_KEY",
    vt_key="YOUR_VT_KEY",
)
```

### 步骤 2:构建基础设施图

```python
import networkx as nx

class InfrastructureGraph:
    def __init__(self):
        self.graph = nx.Graph()

    def add_discovery(self, discovery_data):
        """将已发现的基础设施添加到图中。"""
        for domain in discovery_data["domains"]:
            self.graph.add_node(domain, type="domain")
        for ip in discovery_data["ips"]:
            self.graph.add_node(ip, type="ip")
        for rel in discovery_data["relationships"]:
            self.graph.add_edge(
                rel["source"], rel["target"],
                relationship=rel["type"],
                first_seen=rel.get("first_seen", ""),
                last_seen=rel.get("last_seen", ""),
            )

    def find_clusters(self):
        """识别基础设施集群。"""
        components = list(nx.connected_components(self.graph))
        clusters = []
        for component in components:
            domains = [n for n in component if self.graph.nodes[n].get("type") == "domain"]
            ips = [n for n in component if self.graph.nodes[n].get("type") == "ip"]
            clusters.append({
                "size": len(component),
                "domains": sorted(domains),
                "ips": sorted(ips),
                "domain_count": len(domains),
                "ip_count": len(ips),
            })
        clusters.sort(key=lambda x: x["size"], reverse=True)
        print(f"[+] 基础设施集群: {len(clusters)} 个")
        return clusters

    def find_hub_nodes(self, top_n=10):
        """查找高中心性节点(共享基础设施)。"""
        centrality = nx.degree_centrality(self.graph)
        top_nodes = sorted(centrality.items(), key=lambda x: x[1], reverse=True)[:top_n]
        hubs = []
        for node, score in top_nodes:
            hubs.append({
                "node": node,
                "type": self.graph.nodes[node].get("type", "unknown"),
                "centrality": round(score, 4),
                "connections": self.graph.degree(node),
            })
        return hubs

    def export_graph(self, output_file="infrastructure_graph.json"):
        data = nx.node_link_data(self.graph)
        with open(output_file, "w") as f:
            json.dump(data, f, indent=2)
        print(f"[+] 图已导出: {self.graph.number_of_nodes()} 个节点, "
              f"{self.graph.number_of_edges()} 条边")

infra_graph = InfrastructureGraph()
discovery = tracker.pivot_from_seed("evil-domain.com", depth=2)
infra_graph.add_discovery(discovery)
clusters = infra_graph.find_clusters()
hubs = infra_graph.find_hub_nodes()
infra_graph.export_graph()
```

### 步骤 3:监控新基础设施

```python
import time

class InfrastructureMonitor:
    def __init__(self, tracker, known_indicators):
        self.tracker = tracker
        self.known = set(known_indicators)
        self.alerts = []

    def check_new_registrations(self, patterns):
        """检查是否有与对手模式匹配的新注册域名。"""
        import re
        new_domains = []
        for pattern in patterns:
            # 查询 SecurityTrails 查找匹配模式的新域名
            headers = {"apikey": self.tracker.st_key}
            url = "https://api.securitytrails.com/v1/domains/list"
            params = {"include_ips": "true", "page": 1}
            body = {"filter": {"keyword": pattern}}
            resp = requests.post(url, headers=headers, json=body, timeout=30)
            if resp.status_code == 200:
                records = resp.json().get("records", [])
                for record in records:
                    domain = record.get("hostname", "")
                    if domain not in self.known:
                        new_domains.append({
                            "domain": domain,
                            "pattern_matched": pattern,
                            "first_seen": datetime.now().isoformat(),
                        })
                        self.known.add(domain)

        if new_domains:
            print(f"[ALERT] {len(new_domains)} 个新域名匹配模式")
            self.alerts.extend(new_domains)
        return new_domains

    def generate_infrastructure_report(self, clusters, hubs):
        report = f"""# 对手基础设施追踪报告
生成时间: {datetime.now().isoformat()}

## 摘要
- 识别基础设施集群: {len(clusters)} 个
- 追踪域名总数: {sum(c['domain_count'] for c in clusters)}
- 追踪 IP 总数: {sum(c['ip_count'] for c in clusters)}
- 检测新域名: {len(self.alerts)} 个

## 顶级基础设施枢纽节点
| 节点 | 类型 | 连接数 | 中心性 |
|------|------|-------------|------------|
"""
        for hub in hubs[:10]:
            report += (f"| {hub['node']} | {hub['type']} "
                       f"| {hub['connections']} | {hub['centrality']} |\n")

        report += "\n## 基础设施集群\n"
        for i, cluster in enumerate(clusters[:5], 1):
            report += f"\n### 集群 {i}({cluster['size']} 个节点)\n"
            report += f"- 域名: {', '.join(cluster['domains'][:5])}\n"
            report += f"- IP: {', '.join(cluster['ips'][:5])}\n"

        with open("infrastructure_report.md", "w") as f:
            f.write(report)
        print("[+] 基础设施报告已保存")

monitor = InfrastructureMonitor(tracker, known_indicators=set())
```

## 验收标准

- 被动 DNS 查询返回历史解析数据
- 反向 IP 查询发现共同托管域名
- 基础设施枢纽从种子指标扩展
- 图分析识别集群和枢纽节点
- 通过模式监控检测到新的基础设施
- 生成包含可执行建议的报告

## 参考资料

- [Juniper: Threat Hunting with Passive DNS](https://blogs.juniper.net/en-us/threat-research/threat-hunting-with-passive-dns-discovering-the-attacker-infrastructure)
- [Censys: Advanced Persistent Infrastructure Tracking](https://censys.com/blog/advanced-persistent-infrastructure-tracking)
- [Embee Research: Malware Infrastructure with DNS Pivoting](https://www.embeeresearch.io/infrastructure-analysis-with-dns-pivoting/)
- [Validin: Passive DNS Threat Hunting](https://www.validin.com/blog/announcing_validin_threat_hunting_platform/)
- [SecurityTrails API](https://securitytrails.com/corp/api)
- [Hunt.io: Uncovering Malicious Infrastructure](https://hunt.io/blog/practical-guide-unconvering-malicious-infrastructure)

Related Skills

tracking-threat-actor-infrastructure

9
from killvxk/cybersecurity-skills-zh

威胁行为者基础设施追踪涉及使用被动 DNS、证书透明度日志、Shodan/Censys 扫描、WHOIS 分析和网络指纹技术,对对手控制的 C2 服务器、钓鱼域名和暂存服务器等资产进行监控、映射和持续追踪

scanning-infrastructure-with-nessus

9
from killvxk/cybersecurity-skills-zh

Tenable Nessus 是业界领先的漏洞扫描器,用于识别网络基础设施(包括服务器、工作站、网络设备和操作系统)中的安全弱点。

performing-adversary-in-the-middle-phishing-detection

9
from killvxk/cybersecurity-skills-zh

检测和响应中间人(AiTM)钓鱼攻击,这类攻击使用 EvilProxy、Evilginx 和 Tycoon 2FA 等反向代理工具包绕过 MFA 并窃取会话令牌。

implementing-ticketing-system-for-incidents

9
from killvxk/cybersecurity-skills-zh

实施集成事件工单系统,将 SIEM 告警对接 ServiceNow、Jira 或 TheHive, 用于结构化事件跟踪、SLA 管理、升级工作流和合规文档记录。 适用于 SOC 团队需要通过自动化工单创建、分配路由和解决跟踪来规范事件生命周期管理时。

implementing-patch-management-for-ot-systems

9
from killvxk/cybersecurity-skills-zh

本技能涵盖为OT/ICS环境实施结构化补丁管理程序,在传统IT补丁方法可能导致过程中断或安全隐患的情况下进行管理。内容包括供应商兼容性测试、基于风险的补丁优先级排序、通过测试环境的分阶段部署、维护窗口协调、回滚程序,以及在因运营约束或供应商限制无法应用补丁时的补偿控制措施。

implementing-infrastructure-as-code-security-scanning

9
from killvxk/cybersecurity-skills-zh

本技能涵盖使用 Checkov、tfsec 和 KICS 等工具为基础设施即代码(IaC)模板实施自动化安全扫描。 内容包括在部署前检测 Terraform、CloudFormation、Kubernetes 清单和 Helm charts 中的配置错误, 建立基于策略的治理,以及将 IaC 扫描集成到 CI/CD 管道中以防止不安全的云资源配置。

eradicating-malware-from-infected-systems

9
from killvxk/cybersecurity-skills-zh

系统性地清除受感染系统中的恶意软件、后门和攻击者持久化机制,确保彻底根除并防止再次感染。

detecting-attacks-on-scada-systems

9
from killvxk/cybersecurity-skills-zh

本技能涵盖检测针对数据采集与监控(SCADA)系统的网络攻击,包括工业协议的中间人攻击、向PLC注入未授权命令、HMI入侵、历史数据操纵以及对控制系统通信的拒绝服务攻击。它利用OT专用入侵检测系统、工业协议异常检测和过程数据分析来识别传统IT安全工具无法发现的攻击。

detecting-anomalies-in-industrial-control-systems

9
from killvxk/cybersecurity-skills-zh

本技能涵盖使用机器学习模型(基于OT网络基线训练)、基于物理过程模型以及工业协议通信行为分析,在工业控制环境中部署异常检测(anomaly detection)系统。内容涉及为SCADA轮询模式构建正常行为基线、检测Modbus/DNP3/OPC UA流量中的偏差、识别未授权设备,以及将网络异常与历史数据服务器的物理过程数据进行关联。

conducting-cloud-infrastructure-penetration-test

9
from killvxk/cybersecurity-skills-zh

针对 AWS、Azure 和 GCP 执行云基础设施渗透测试,使用 Pacu、ScoutSuite 和 Prowler 识别 IAM 错误配置、暴露的存储桶、不安全的无服务器函数和云原生攻击路径。

building-vulnerability-scanning-workflow

9
from killvxk/cybersecurity-skills-zh

使用 Nessus、Qualys 和 OpenVAS 等工具构建结构化的漏洞扫描工作流, 对基础设施中的安全漏洞进行发现、优先级排序和修复跟踪。适用于 SOC 团队 需要建立定期漏洞评估流程、将扫描结果与 SIEM 告警集成,以及构建 修复跟踪仪表盘的场景。

building-vulnerability-exception-tracking-system

9
from killvxk/cybersecurity-skills-zh

构建具有审批工作流、补偿控制文档和到期管理功能的漏洞例外与风险接受跟踪系统。