Communitygithub.com

对抗性基础设施追踪系统

构建一个自动化的对抗性基础设施追踪系统,利用Python(dnspython、python-whois、shodan、networkx)通过被动DNS、证书透明度日志、WHOIS记录和IP丰富化,映射威胁行为者的C2网络,并标记符合已知模式的新注册域名。适用于从已知指标出发发现相关C2基础设施,或持续更新威胁行为者地图。

对抗性基础设施追踪系统 是什么?

该技能旨在帮助安全分析师构建一个自动化的对抗性基础设施追踪系统。它通过集成被动DNS、证书透明度日志、WHOIS注册数据和IP丰富化等多种数据源,利用Python库(如dnspython、python-whois、shodan、networkx)实现基础设施的发现、映射和持续监控。核心功能包括从已知指标(如域名或IP)递归执行基础设施枢轴(pivot),发现共享托管、SSL证书重用等关联模式,并使用NetworkX构建关系图识别集群和枢纽节点。此外,系统还支持基于模式监控新注册域名,生成包含基础设施集群、枢纽节点和警报的可操作报告。该技能适用于SecurityTrails、PassiveTotal/RiskIQ、Shodan和VirusTotal等平台,要求Python 3.9+及相应API密钥。通过自动化重复的手动分析流程,显著提升威胁狩猎和事件响应中基础设施追踪的效率和覆盖面。

兼容平台~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/mukul975/Anthropic-Cybersecurity-Skills/tree/main/skills/building-adversary-infrastructure-tracking-system

在你喜欢的 AI 中提问

打开一个已预加载此 Agent Skill 的新对话。

文档

构建对抗性基础设施追踪系统

概述

对抗性基础设施追踪利用被动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基础设施发现

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"[+] {domain}的被动DNS记录:{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_address}的逆向IP查找:{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:构建基础设施图

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:监控新基础设施

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"[警报] 检测到{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查找发现共宿主域名
  • 基础设施枢轴从种子指标扩展
  • 图分析识别集群和枢纽节点
  • 通过模式监控检测到新基础设施
  • 生成包含可操作建议的报告

参考资料

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

abusing-dpapi-for-credential-access

Extract and decrypt Windows DPAPI-protected secrets (Credential Manager, browser logins/cookies, Wi-Fi credentials, KeePass keys) online or offline using SharpDPAPI, SharpChrome, Mimikatz, or Impacket

abusing-shadow-credentials-for-privesc

Take over Active Directory accounts by writing attacker-controlled public keys to msDS-KeyCredentialLink (Shadow Credentials) with pyWhisker, Whisker, or Certipy, then authenticate via PKINIT to recover the target

achieving-cmmc-level-2-compliance

>-

acquiring-disk-image-with-dd-and-dcfldd

Create forensically sound bit-for-bit disk images with dd or dcfldd on a Linux forensic workstation, preserving evidence integrity through hash verification (MD5/SHA) during acquisition. Use when imaging a suspect drive, USB device, or memory card for investigation, preserving volatile disk evidence during incident response, or producing a verified copy for legal or law-enforcement proceedings before any destructive analysis.

analyzing-active-directory-acl-abuse

Detect dangerous ACL misconfigurations in Active Directory using ldap3

analyzing-android-malware-with-apktool

Perform static analysis of Android APK malware using apktool for resource decompilation, jadx for Java source recovery, and androguard for manifest inspection, dangerous permission-combination detection, and identification of obfuscated code, dynamic code loading, and reflection-based API calls. Use to statically triage a suspicious APK without executing it or to build mobile malware detection rules.

analyzing-api-gateway-access-logs

Parses API Gateway access logs (AWS API Gateway, Kong, Nginx) to detect

analyzing-apt-group-with-mitre-navigator

Query ATT&CK data with attackcti, mitreattack-python, and stix2, then build MITRE ATT&CK Navigator layers and multi-layer heatmap overlays mapping one or more APT groups

analyzing-azure-activity-logs-for-threats

Queries Azure Monitor activity logs and sign-in logs via azure-monitor-query

analyzing-bootkit-and-rootkit-samples

Analyzes bootkit and advanced rootkit malware infecting the Master

analyzing-browser-forensics-with-hindsight

Parse Chromium-based browser databases with Hindsight to extract and correlate browsing history, downloads, cookies, cached content, autofill data, saved passwords, and extensions from Chrome, Edge, Brave, Opera, and Vivaldi into a unified timeline (XLSX, JSON, or SQLite output). Use during incident response, insider-threat investigations, or criminal cases when you need to reconstruct a user

analyzing-campaign-attribution-evidence

Systematically evaluate cyber-campaign evidence to attribute an operation to a threat actor, using the Diamond Model and Analysis of Competing Hypotheses (ACH) to weigh infrastructure overlaps, TTP consistency, malware code similarity, and timing/language artifacts into confidence-weighted attribution assessments. Use when an incident investigation needs a defensible attribution confidence level.

analyzing-certificate-transparency-for-phishing

Monitor Certificate Transparency logs using crt.sh and Certstream to

analyzing-cloud-storage-access-patterns

Detect abnormal access in AWS S3, GCS, and Azure Blob Storage by analyzing CloudTrail Data Events, GCS audit logs, and Azure Storage Analytics for after-hours bulk downloads, new-IP access, and API-call spikes (e.g. GetObject) via statistical baselines and time-series anomaly detection. Use when investigating suspected cloud data exfiltration or building related detection rules.

analyzing-cobalt-strike-beacon-configuration

Extract and analyze Cobalt Strike beacon configuration from PE files

analyzing-cobaltstrike-malleable-c2-profiles

Parse and analyze Cobalt Strike Malleable C2 profiles with dissect.cobaltstrike (profiles and beacon-payload configs) and pyMalleableC2 (AST parsing) to extract HTTP/DNS transforms, URIs, headers, sleep/jitter, and injection behavior, then generate network detection signatures. Use when reverse-engineering a captured malleable profile or building detections against Cobalt Strike Beacon traffic.

analyzing-command-and-control-communication

Analyzes malware C2 communication over HTTP, HTTPS, DNS, and custom

analyzing-cyber-kill-chain

Analyzes intrusion activity against the Lockheed Martin Cyber Kill Chain

analyzing-disk-image-with-autopsy

Perform comprehensive forensic analysis of raw (dd), E01, or AFF disk images with Autopsy and The Sleuth Kit, recovering deleted files, examining metadata and embedded artifacts, keyword searching, and building investigation timelines with visual reports. Use for structured analysis of a forensic disk image or when stakeholders need visual reports from evidence.

analyzing-dns-logs-for-exfiltration

Analyzes DNS query logs to detect data exfiltration via DNS tunneling,

相关技能