mcpField
R
reverse-engineering-firmware-analysis

reverse-engineering-firmware-analysis

github.com/dnyoussef安全3250 次安装15 周前更新
代码仓库

关于 reverse-engineering-firmware-analysis

面向安全研究人员的固件分析技能,指导分析 IoT 设备、路由器和嵌入式系统固件。内容涵盖提取、服务发现、凭据与漏洞检查,并强调隔离执行和合法授权。

主要功能

  1. 01固件识别与文件系统提取
  2. 02分析启动服务和网络监听
  3. 03搜索硬编码凭据与漏洞
  4. 04要求隔离环境分析
  5. 05通过多种方法验证发现

适用场景

  1. 01评估 IoT 固件的安全风险
  2. 02检查设备暴露的网络服务
  3. 03排查固件中的凭据与注入点
  4. 04在沙箱中分析可疑固件

安装

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

$npx skills add https://github.com/dnyoussef/context-cascade --skill reverse-engineering-firmware-analysis

安装后在 Claude Code 中输入/reverse-engineering-firmware-analysis确认已加载。

包含的文件

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

SKILL-meta.yaml
resources/
README.md
resources/scripts/
binwalk-extractor.py
qemu-emulator.sh

详细介绍


以库为先的协议(强制要求)

在编写任何代码之前,必须检查:

第 1 步:库目录
  • 位置:.claude/library/catalog.json
  • 如果匹配度 >70%:复用或调整
第 2 步:模式指南
  • 位置:.claude/docs/inventories/LIBRARY-PATTERNS-GUIDE.md
  • 如果存在适用模式:遵循文档说明的方法
第 3 步:现有项目
  • 位置:D:\Projects\*
  • 如果找到:提取并调整
决策矩阵
匹配度操作
库 >90%直接复用
库 70-90%尽量少地调整
存在模式遵循模式
存在于项目中提取
无匹配项构建(之后添加到库中)

何时使用此技能

在分析恶意软件样本、为安全研究逆向分析二进制文件、开展漏洞评估、从可疑文件中提取 IOC、验证软件供应链安全,或进行 CTF 挑战和二进制利用研究时,请使用此技能。

何时不要使用此技能

不要用于未经授权的商业软件逆向分析、分析生产系统上的二进制文件、在没有合法授权的情况下逆向软件、违反服务条款或 EULA,或在隔离环境之外分析恶意软件。简单的字符串提取请勿使用此技能(改用基础工具)。

成功标准

  • 识别所有与安全相关的行为(网络、文件、注册表、进程活动)
  • 提取恶意指标并提供置信度评分(IOC、C2 域名、加密密钥)
  • 记录漏洞,并在适用时映射到 CVE
  • 在沙箱环境(带快照的 VM/容器)中完成分析
  • 通过多种分析方法(静态 + 动态 + 符号执行)验证发现
  • 生成完整的 IOC 报告(采用 STIX/MISP 格式,以便共享威胁情报)
  • 漏洞评估中零误报
  • 创建漏洞利用概念验证(如开展漏洞研究)

边缘情况与挑战

  • 反分析技术(调试器检测、VM 检测、时序检查)
  • 需要解包的混淆或加壳二进制文件
  • 带有加密载荷的多阶段恶意软件
  • 需要专门分析的内核模式 Rootkit
  • 符号执行状态爆炸(>10,000 条路径)
  • 复杂程序的二进制分析超时(>24 小时)
  • 合法软件行为导致的误报
  • 需要 SSL 拦截的加密网络流量

防护措施(关键安全规则)

  • 绝不在主机系统上执行未知二进制文件(仅限隔离的 VM/沙箱)
  • 绝不在没有适当遏制措施的情况下分析恶意软件(优先使用物理隔离实验室)
  • 绝不在没有合法授权的情况下逆向工程软件
  • 绝不公开分享提取的凭据或加密密钥
  • 绝不为未经授权的用途绕过许可机制
  • 始终使用带网络监控的沙箱环境
  • 始终在执行可疑二进制文件前创建 VM 快照
  • 始终通过多种分析方法验证发现
  • 始终记录带时间戳的分析方法
  • 始终假定二进制文件具有恶意性,直到证明安全为止
  • 始终使用网络隔离,防止恶意软件通信
  • 分享前始终清理 IOC(隐藏内部 IP 地址)

基于证据的验证

所有逆向工程发现都必须通过以下方式验证:

  1. 多方法分析——通过静态 + 动态 + 符号执行确认相同行为
  2. 沙箱验证——在隔离环境中执行并捕获所有活动
  3. 网络监控——通过数据包捕获验证基于网络的发现
  4. 内存取证——通过内存转储验证运行时机密
  5. 行为关联——与已知恶意软件特征(YARA、ClamAV)交叉比对
  6. 可复现性——第二位分析人员能够根据分析产物复现发现

逆向工程:固件分析

此技能的功能

从 IoT 设备、路由器和嵌入式系统中提取并分析固件:

  • 提取(30 分钟至 2 小时):使用 binwalk 提取 SquashFS/JFFS2/CramFS 文件系统
  • 服务分析(1 至 3 小时):梳理 init 脚本、守护进程和网络监听器
  • 漏洞评估(1 至 3 小时):查找硬编码凭据、CVE 和注入点
  • 二进制分析(1 至 2 小时):对提取的二进制文件应用第 1 至 4 级分析

时间安排:总计 2 至 8 小时


前置条件

工具
  • binwalk - 固件提取(binwalk -Me firmware.bin)
  • unsquashfs - SquashFS 提取
  • file - 文件类型识别
  • QEMU(可选)- 模拟提取的二进制文件
  • Jefferson(可选)- JFFS2 提取
  • strings - 分析固件中的字符串
MCP 服务
  • filesystem - 浏览提取出的固件
  • security-manager - CVE 扫描
  • connascence-analyzer - 代码质量分析
  • memory-mcp - 存储发现结果
  • sequential-thinking - 二进制分析的决策门控

⚠️ 严重安全警告

绝不要在主机系统上执行固件二进制文件或提取出的文件!

所有固件提取、二进制执行和模拟都必须在以下环境中进行:

  • 隔离的 VM(VMware/VirtualBox,启用网络隔离和快照)
  • Docker 容器,采用严格的安全策略,且无法访问主机文件系统
  • 通过 sandbox-configurator 技能配置的 E2B 沙箱,并监控执行过程
  • 固件分析环境(使用 -snapshot 的 QEMU、firmadyne 沙箱)

不安全执行的后果:

  • 安装后门并获得持久网络访问权限
  • 提取硬编码凭据,危及相关设备安全
  • 恶意软件传播到开发基础设施
  • 被 IoT 僵尸网络招募(Mirai、Hajime 变种)
  • 云 API 密钥和服务遭到入侵

安全实践:

  • 在无法访问网络的隔离容器中提取固件
  • 使用快照模式模拟 QEMU(-snapshot 标志)
  • 绝不要将模拟设备连接到生产网络
  • 仅在隔离环境中验证提取出的凭据
  • 固件模拟期间监控所有网络连接
  • 将所有 IoT 固件视为可能已遭入侵
  • 对提取出的文件系统使用只读挂载

快速开始

# 1. Full firmware analysis
/re:firmware router-firmware.bin

# 2. Extract filesystem only
/re:firmware iot-device.img --extract-only

# 3. Analyze extracted services
/re:firmware camera-fw.bin --analyze-services true

# 4. Extract + analyze specific binary
/re:firmware router.bin --analyze-binary /usr/sbin/httpd

阶段 1:固件识别(5 至 10 分钟)

步骤 1:基本文件分析
# Identify file type
file firmware.bin

# Expected output examples:
# - "firmware.bin: u-boot legacy uImage, MIPS OpenWrt Linux-4.14.63"
# - "firmware.bin: data" (encrypted or compressed)
# - "firmware.bin: Flattened device tree blob (DTB)"
步骤 2:熵分析

检查固件是否已加密或压缩:

# Entropy analysis
binwalk --entropy firmware.bin

# Output visualization:
# High entropy throughout (> 0.9): Likely encrypted
# Low entropy with peaks: Normal firmware with compressed sections
# Uniform low entropy (< 0.5): Uncompressed firmware

解读:

  • 熵 0.9-1.0:固件已加密(需要解密密钥)
  • 熵 0.6-0.8:存在压缩区段(正常)
  • 熵 0.3-0.5:未压缩数据
步骤 3:组件识别
# Identify firmware components
binwalk --signature firmware.bin

# Expected output:
# DECIMAL       HEXADECIMAL     DESCRIPTION
# --------------------------------------------------------------------------------
# 0             0x0             uImage header, header size: 64 bytes
# 64            0x40            LZMA compressed data
# 1048576       0x100000        Squashfs filesystem, little endian
# 15728640      0xF00000        JFFS2 filesystem, little endian

组件:

  • 引导加载程序:u-boot、Das U-Boot
  • 内核:Linux 内核(使用 LZMA/gzip 压缩)
  • 根文件系统:SquashFS、JFFS2、CramFS、UBIFS
  • 配置:用于持久化数据的 JFFS2 分区

阶段 2:文件系统提取(30 分钟至 2 小时)

步骤 1:自动提取
# Extract all filesystem components automatically
binwalk --extract --matryoshka firmware.bin

# --extract (-e): Extract identified components
# --matryoshka (-M): Recursively scan extracted files

# Output directory structure:
# _firmware.bin.extracted/
# ├── 0.lzma              # Compressed kernel
# ├── 100000.squashfs     # Root filesystem
# ├── squashfs-root/      # Extracted root filesystem
# └── jffs2-root/         # Extracted configuration partition
步骤 2:验证提取结果
# Navigate to extracted filesystem
cd _firmware.bin.extracted/squashfs-root/

# Verify critical directories exist
ls -la

# Expected structure:
# drwxr-xr-x  bin/        # Binaries
# drwxr-xr-x  etc/        # Configuration files
# drwxr-xr-x  lib/        # Shared libraries
# drwxr-xr-x  usr/        # User programs
# drwxr-xr-x  www/        # Web interface
# drwxr-xr-x  sbin/       # System binaries
步骤 3:手动提取(自动提取失败时)
对于 SquashFS:
# Find SquashFS offset from binwalk
binwalk firmware.bin | grep -i squashfs
# Output: 1048576       0x100000        Squashfs filesystem

# Extract from offset
dd if=firmware.bin bs=1 skip=1048576 of=squashfs.img

# Unsquash manually
unsquashfs -dest ./squashfs-root squashfs.img

# Verify
ls ./squashfs-root/
对于 JFFS2:
# Install jefferson (JFFS2 extractor)
pip install jefferson

# Extract JFFS2
jefferson jffs2.img --dest ./jffs2-root

# Or use firmware-mod-kit
extract-firmware.sh firmware.bin
对于 CramFS:
# Install cramfs tools
sudo apt install cramfsprogs

# Mount (requires root)
sudo mount -t cramfs -o loop cramfs.img /mnt/cramfs

# Or extract
cramfsck -x ./cramfs-root cramfs.img
步骤 4:处理加密固件
# Check entropy
binwalk --entropy firmware.bin

# If high entropy (encrypted):
# 1. Search for decryption keys in vendor documentation
# 2. Check for known encryption schemes (AES, 3DES, RSA)
# 3. Use firmware-mod-kit or binwalk plugins for known devices

# Example: TP-Link firmware decryption
tplink-safeloader -d firmware.bin -o decrypted.bin

# Example: D-Link firmware decryption
binwalk -e --dd='.*' firmware.bin

阶段 3:服务发现(1 至 3 小时)

步骤 1:识别 init 系统
# Check for init scripts
ls ./squashfs-root/etc/init.d/

# Common init systems:
# - init.d/ scripts (SysVinit)
# - rc.d/ scripts (BSD-style init)
# - systemd/ units (systemd)
# - procd/ configs (OpenWrt procd)
步骤 2:分析启动服务
# OpenWrt/procd example
cat ./squashfs-root/etc/rc.d/*

# SysVinit example
cat ./squashfs-root/etc/init.d/rcS

# Example output:
# #!/bin/sh
# /usr/sbin/telnetd -l /bin/sh
# /usr/sbin/httpd -p 80 -h /www
# /usr/sbin/dropbear -p 22

需要梳理的关键服务:

  • telnetd:Telnet 服务端口(23)
  • httpd:Web 服务端口(80/443)
  • dropbear/sshd:SSH 服务端口(22)
  • ftpd:FTP 服务端口(21)
  • upnpd:UPnP 守护进程
  • dnsmasq:DNS/DHCP 服务端
步骤 3:查找网络监听器
# Search for network binding code
grep -r "0.0.0.0" ./squashfs-root/etc/
grep -r "bind(" ./squashfs-root/usr/sbin/ 2>/dev/null
grep -r "listen(" ./squashfs-root/usr/sbin/ 2>/dev/null

# Search for port numbers
grep -rE ":[0-9]{2,5}" ./squashfs-root/etc/ | grep -E "(80|443|23|22|21)"

# Example findings:
# ./squashfs-root/etc/config/uhttpd:  option listen_http '0.0.0.0:80'
# ./squashfs-root/etc/config/dropbear: option Port '22'
# ./squashfs-root/etc/inetd.conf:telnet stream tcp nowait root /usr/sbin/telnetd
步骤 4:梳理 CGI 脚本和 Web 界面
# Find web root
ls ./squashfs-root/www/
ls ./squashfs-root/usr/www/

# Find CGI scripts (potential injection points)
find ./squashfs-root/www/ -name "*.cgi" -o -name "*.sh"

# Example CGI scripts:
# ./squashfs-root/www/cgi-bin/login.cgi
# ./squashfs-root/www/cgi-bin/admin.cgi
# ./squashfs-root/www/cgi-bin/status.sh

# Analyze for command injection
grep -E "(system|popen|exec)" ./squashfs-root/www/cgi-bin/*.cgi

输出摘要:

Network Services Detected:
- telnetd on 0.0.0.0:23 (CRITICAL: Unauthenticated shell access)
- httpd on 0.0.0.0:80 (Web interface)
- dropbear on 0.0.0.0:22 (SSH with password auth)
- upnpd on 0.0.0.0:1900 (UPnP potential SSRF)

CGI Scripts Found:
- /cgi-bin/admin.cgi (Command injection vulnerable)
- /cgi-bin/login.cgi (Credential check)
- /cgi-bin/upgrade.cgi (Firmware upload)

阶段 4:凭据搜寻(30 分钟至 1 小时)

步骤 1:检查 Shadow 和 Passwd 文件
# Unix password files
cat ./squashfs-root/etc/passwd
cat ./squashfs-root/etc/shadow

# Example vulnerable shadow file:
# root:$1$12345678$abcdefghijklmnopqrstuv:0:0:root:/root:/bin/sh
# admin:admin:0:0:admin:/root:/bin/sh  # CRITICAL: Plaintext password!

常见问题:

  • 密码哈希为空(无密码登录)
  • 弱密码/默认密码(admin/admin)
  • 硬编码的哈希(可破解)
步骤 2:搜索配置文件
# Search for common password keywords
grep -ri "password" ./squashfs-root/etc/ 2>/dev/null
grep -ri "passwd" ./squashfs-root/etc/ 2>/dev/null
grep -ri "pwd" ./squashfs-root/etc/ 2>/dev/null
grep -ri "secret" ./squashfs-root/etc/ 2>/dev/null

# Example findings:
# ./etc/config/wireless: option key 'default_wifi_password_12345'
# ./etc/shadow: root:5up:0:0:root:/root:/bin/sh
# ./etc/config/system: option admin_password 'admin'
步骤 3:查找 API 密钥和令牌
# Search for long alphanumeric strings (API keys)
grep -rE "[A-Za-z0-9]{32,}" ./squashfs-root/etc/config/

# Search for common API key patterns
grep -ri "api_key\|token\|secret_key" ./squashfs-root/etc/

# Search for cloud service credentials
grep -ri "aws\|azure\|gcp\|s3" ./squashfs-root/etc/

# Example findings:
# ./etc/cloud-config.json: "api_key": "sk_live_abcdef1234567890"
# ./etc/mqtt.conf: mqtt_token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
步骤 4:提取 SSL 证书和私钥
# Find SSL certificates
find ./squashfs-root/ -name "*.pem" -o -name "*.key" -o -name "*.crt"

# Example findings:
# ./etc/ssl/private/server.key (CRITICAL: Private key embedded)
# ./etc/ssl/certs/ca.crt

# Check for weak/default keys
openssl rsa -in ./etc/ssl/private/server.key -text -noout

# If key is weak (512-bit RSA), flag as critical

凭据摘要:

Hardcoded Credentials Found:
- Root password: "5up" (plaintext in /etc/shadow)
- Admin password: "admin" (default credentials)
- WiFi password: "default_wifi_password_12345" (weak)
- API key: "sk_live_abcdef..." (exposed in /etc/cloud-config.json)
- SSL private key: /etc/ssl/private/server.key (512-bit RSA, weak)

阶段 5:漏洞扫描(1-3 小时)

步骤 1:识别库版本
# Find shared libraries
ls ./squashfs-root/lib/
ls ./squashfs-root/usr/lib/

# Check library versions
strings ./squashfs-root/lib/libc.so.0 | grep -i version

# Example output:
# OpenSSL 1.0.1e (VULNERABLE: Heartbleed CVE-2014-0160)
# BusyBox v1.24.1 (CHECK: Known CVEs)
# Dropbear 2014.63 (CHECK: Known CVEs)
步骤 2:使用 MCP 扫描 CVE
# Use security-manager MCP for automated CVE scanning
/re:firmware router.bin --cve-scan true

幕后原理:

// Automatically invoked by skill
const cveResults = await mcp__security-manager__scan_vulnerabilities({
  filesystem_root: "./squashfs-root/",
  library_scan: true,
  cve_database: "nvd",  // National Vulnerability Database
  check_versions: true
})

// Example output:
// {
//   "vulnerabilities": [
//     {
//       "cve": "CVE-2014-0160",
//       "severity": "CRITICAL",
//       "component": "OpenSSL 1.0.1e",
//       "description": "Heartbleed vulnerability allows memory disclosure",
//       "cvss": 7.5
//     },
//     {
//       "cve": "CVE-2019-12345",
//       "severity": "HIGH",
//       "component": "httpd CGI handler",
//       "description": "Command injection via admin.cgi parameter",
//       "cvss": 8.8
//     }
//   ]
// }
步骤 3:手动评估漏洞
检查命令注入:
# Analyze CGI scripts for command injection
grep -E "(system|exec|popen|shell_exec)" ./squashfs-root/www/cgi-bin/*.cgi

# Example vulnerable code in admin.cgi:
# system("ping -c 1 " . $QUERY_STRING);  # CRITICAL: Command injection!
检查 SQL 注入:
# Find database queries
grep -rE "(SELECT|INSERT|UPDATE|DELETE)" ./squashfs-root/www/

# Example vulnerable query:
# $query = "SELECT * FROM users WHERE username='" . $_GET['user'] . "'";
检查路径遍历:
# Find file operations
grep -rE "(fopen|readfile|include)" ./squashfs-root/www/

# Example vulnerable code:
# readfile("/www/" . $_GET['file']);  # Path traversal: ?file=../etc/shadow
步骤 4:检查后门
# Search for suspicious listening ports
grep -rE "port.*[0-9]{4,5}" ./squashfs-root/etc/

# Search for reverse shell code
grep -rE "(nc.*-e|bash.*>&|/dev/tcp)" ./squashfs-root/

# Search for hidden services
find ./squashfs-root/ -name ".*" -type f

# Check for suspicious cron jobs
cat ./squashfs-root/etc/crontabs/*

漏洞报告:

CRITICAL Vulnerabilities:
1. CVE-2014-0160 (Heartbleed) - OpenSSL 1.0.1e
2. Command Injection - admin.cgi (unauthenticated)
3. Hardcoded credentials - root:5up

HIGH Vulnerabilities:
4. Path Traversal - download.cgi
5. Weak SSL certificate - 512-bit RSA key
6. Telnet enabled on 0.0.0.0:23 (no authentication)

MEDIUM Vulnerabilities:
7. Default credentials - admin:admin
8. UPnP enabled (SSRF potential)
9. SQL Injection - login.cgi

阶段 6:二进制分析(1-2 小时)

提取固件后,对需要关注的二进制文件应用第 1-4 级分析。

步骤 1:识别目标二进制文件
# Web server binary
ls ./squashfs-root/usr/sbin/httpd

# Telnet daemon
ls ./squashfs-root/usr/sbin/telnetd

# Custom binaries
find ./squashfs-root/usr/bin/ -type f -executable
步骤 2:应用第 1 级分析(字符串分析)
# Analyze web server strings
/re:strings ./squashfs-root/usr/sbin/httpd

# Look for:
# - Hardcoded URLs (C2 servers, update servers)
# - Debug messages revealing logic
# - Version strings
# - Hardcoded credentials

输出示例:

Strings Found in httpd:
- "admin:5up" (hardcoded credential)
- "http://firmware-updates.vendor.com/check" (update URL)
- "DEBUG: Command executed: %s" (command injection point)
- "OpenSSL/1.0.1e" (vulnerable version)
步骤 3:应用第 2 级分析(静态分析)
# Disassemble httpd binary
/re:static ./squashfs-root/usr/sbin/httpd --tool ghidra

# Find critical functions:
# - handle_cgi_request()
# - authenticate_user()
# - execute_command()

反编译代码示例(Ghidra 输出):

// Function: handle_admin_cgi
void handle_admin_cgi(char *query_string) {
  char command[256];
  char *cmd_param;

  // VULNERABILITY: No input validation!
  cmd_param = get_param(query_string, "cmd");
  sprintf(command, "sh -c '%s'", cmd_param);
  system(command);  // CRITICAL: Command injection!
}
步骤 4:应用第 3 级分析(动态分析)- 可选
# Emulate binary with QEMU
qemu-mipsel-static ./squashfs-root/usr/sbin/httpd

# Or use full system emulation with firmadyne
firmadyne.sh router-firmware.bin

# Debug with GDB
gdb-multiarch ./squashfs-root/usr/sbin/httpd
(gdb) set architecture mips
(gdb) break handle_admin_cgi
(gdb) run
步骤 5:应用第 4 级分析(符号执行)- 进阶
# Use Angr for symbolic analysis
/re:symbolic ./squashfs-root/usr/sbin/httpd \
  --target-addr 0x401234 \  # execute_command function
  --input-symbolic cmd_param \
  --find-exploits true

综合工作流示例

工作流 1:路由器固件完整分析

场景:分析 TP-Link 路由器固件,查找漏洞

步骤 1:提取(30 分钟)

# Download firmware
wget http://vendor.com/TL-WR841N-v14-firmware.bin

# Identify and extract
binwalk -E TL-WR841N-v14-firmware.bin  # Check entropy
binwalk -Me TL-WR841N-v14-firmware.bin # Extract

# Navigate to filesystem
cd _TL-WR841N-v14-firmware.bin.extracted/squashfs-root/

步骤 2:服务发现(1 小时)

# Find init scripts
cat etc/rc.d/S*

# Services found:
# - telnetd on 0.0.0.0:23 (CRITICAL)
# - httpd on 0.0.0.0:80
# - dnsmasq on 0.0.0.0:53

# Map CGI scripts
find www/ -name "*.cgi"

# CGI scripts found:
# - www/cgi-bin/admin.cgi (admin interface)
# - www/cgi-bin/upgrade.cgi (firmware upload)

步骤 3:凭据搜寻(15 分钟)

# Check shadow file
cat etc/shadow
# Output: admin:5up:0:0:admin:/root:/bin/sh

# Check config files
grep -ri "password" etc/config/
# Output: option admin_password 'admin'

# CRITICAL: Default credentials admin:5up

步骤 4:CVE 扫描(30 分钟)

# Check library versions
strings lib/libc.so.0 | grep version
# OpenSSL 1.0.1e (CVE-2014-0160 Heartbleed)

# Automated CVE scan
/re:firmware TL-WR841N-v14-firmware.bin --cve-scan true

# Results:
# - CVE-2014-0160 (CRITICAL): Heartbleed
# - CVE-2019-12345 (HIGH): Command injection in admin.cgi

步骤 5:二进制分析(1 小时)

# Analyze admin CGI
/re:strings www/cgi-bin/admin.cgi
# Found: "system(sh -c %s)" - command injection

# Static analysis
/re:static www/cgi-bin/admin.cgi --tool ghidra

# Decompiled code shows:
# char *cmd = getenv("QUERY_STRING");
# system(cmd);  # CRITICAL: No sanitization!

最终报告:

TP-Link TL-WR841N Firmware Analysis
====================================

CRITICAL Vulnerabilities:
1. Hardcoded credentials: admin:5up
2. Unauthenticated telnet on port 23
3. Command injection in admin.cgi
4. Heartbleed (CVE-2014-0160) in OpenSSL 1.0.1e

HIGH Vulnerabilities:
5. Weak default WiFi password
6. No CSRF protection on admin interface

Attack Scenario:
1. Telnet to router (no password required)
2. Or exploit command injection: http://router/cgi-bin/admin.cgi?cmd=reboot
3. Gain root shell access

Recommendation: Update to patched firmware version

用时:总计 3.25 小时


工作流 2:IoT 摄像头固件安全审计

场景:审计 Wyze 摄像头固件的云 API 安全性

步骤 1:提取(45 分钟)

# Extract firmware
binwalk --extract --matryoshka wyze-cam-v3-firmware.bin

# Filesystem type: UBIFS (NAND flash filesystem)
# Manual extraction required
jefferson ubifs.img --dest ./wyze-root/

步骤 2:服务发现(1.5 小时)

# Find cloud service configuration
grep -ri "api\|cloud\|server" ./wyze-root/etc/

# Found:
# ./etc/cloud-config.json:
# {
#   "api_endpoint": "https://api.wyze.com/v1",
#   "device_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
#   "api_key": "sk_live_abcdef1234567890"
# }

# CRITICAL: Hardcoded API credentials!

步骤 3:分析云通信(1 小时)

# Find MQTT broker configuration
cat ./wyze-root/etc/mqtt.conf

# Broker: mqtt.wyze.com:8883
# Username: camera-12345
# Password: hardcoded_mqtt_pass

# Analyze cloud binary
/re:strings ./wyze-root/usr/bin/cloud-agent

# Found:
# - "Bearer eyJhbGci..." (hardcoded auth token)
# - "https://firmware-updates.wyze.com/" (update URL)

步骤 4:CVE 扫描(30 分钟)

# Check libraries
ls ./wyze-root/lib/

# Found vulnerable libraries:
# - libssl.so.1.0.0 (CVE-2014-0160 Heartbleed)
# - libcurl.so.4 (CVE-2020-8231 Remote code execution)

步骤 5:分析云 Agent 二进制文件(1 小时)

# Static analysis
/re:static ./wyze-root/usr/bin/cloud-agent --tool ghidra

# Decompiled authentication function:
void cloud_authenticate() {
  char *token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...";
  char *api_key = "sk_live_abcdef1234567890";

  http_request("POST", "https://api.wyze.com/v1/auth",
               headers=["Authorization: Bearer " + token]);
}

# CRITICAL: All cameras use same API key!

最终报告:

Wyze Cam v3 Firmware Security Audit
====================================

CRITICAL Vulnerabilities:
1. Hardcoded API credentials shared across all devices
2. Hardcoded JWT token for cloud authentication
3. MQTT credentials in plaintext
4. CVE-2014-0160 (Heartbleed)
5. CVE-2020-8231 (libcurl RCE)

Attack Scenario:
1. Extract API key from firmware
2. Authenticate to Wyze cloud API
3. Access all cameras using same API key
4. Stream/download video from any camera

Impact: Complete compromise of all Wyze cameras using this firmware

Recommendation:
- Implement per-device API keys
- Remove hardcoded credentials
- Update vulnerable libraries

用时:总计 4.75 小时


工作流 3:智能恒温器固件——查找调试接口

场景:分析类似 Nest 的恒温器,查找隐藏的调试接口

步骤 1:提取(1 小时)

# Encrypted firmware (high entropy)
binwalk --entropy thermostat-firmware.bin
# Entropy: 0.95 (encrypted)

# Search for decryption keys in vendor SDK
find ./vendor-sdk/ -name "*.key" -o -name "*aes*"

# Found: encryption_key.bin
# Decrypt firmware
openssl enc -d -aes-256-cbc -in thermostat-firmware.bin \
  -out decrypted.bin -K $(cat encryption_key.bin)

# Extract decrypted firmware
binwalk --extract --matryoshka decrypted.bin

步骤 2:查找调试接口(30 分钟)

# Search for UART/serial references
grep -ri "uart\|serial\|console" ./squashfs-root/etc/

# Found:
# ./etc/inittab: ttyS0::respawn:/bin/sh  # UART console!

# Search for debug commands
grep -ri "debug\|test\|diag" ./squashfs-root/usr/bin/

# Found debug binary
ls ./squashfs-root/usr/bin/debug-shell

步骤 3:分析调试 Shell(1 小时)

# String analysis of debug shell
/re:strings ./squashfs-root/usr/bin/debug-shell

# Found:
# - "Enter admin password:" (authentication required)
# - "Debug mode enabled"
# - "dump_nvram" (NVRAM dumping command)
# - "factory_reset"

# Static analysis
/re:static ./squashfs-root/usr/bin/debug-shell --tool ghidra

# Decompiled password check:
bool check_debug_password(char *input) {
  char *correct_password = "DebugMode2023";  // Hardcoded!
  return strcmp(input, correct_password) == 0;
}

步骤 4:测试调试接口(30 分钟)

# Emulate debug shell
qemu-arm-static ./squashfs-root/usr/bin/debug-shell

# Connect to UART console
screen /dev/ttyUSB0 115200

# Enter debug password: DebugMode2023
# Access granted!

# Available debug commands:
# - dump_nvram (dumps all settings including WiFi password)
# - factory_reset (wipes device)
# - enable_telnet (enables telnet on port 23)

最终报告:

Smart Thermostat Debug Interface Analysis
==========================================

CRITICAL Findings:
1. UART console enabled with debug shell access
2. Hardcoded debug password: "DebugMode2023"
3. Debug commands allow full device control
4. NVRAM dump reveals WiFi credentials

Attack Scenario:
1. Open device and connect to UART pins
2. Boot device and access serial console
3. Launch debug-shell
4. Enter password "DebugMode2023"
5. Execute dump_nvram to extract WiFi password
6. Execute enable_telnet for remote access

Impact: Physical access to device = full compromise

Recommendation:
- Disable debug interfaces in production firmware
- Use unique per-device debug passwords
- Implement secure boot to prevent firmware modifications

用时:总计 3 小时


高级选项

自定义提取目标
# Extract specific filesystem only
/re:firmware router.bin --extract-filesystem squashfs --skip-analysis

# Extract and analyze specific binary
/re:firmware router.bin --analyze-binary /usr/sbin/httpd --level 2

# Extract configuration partition only
/re:firmware router.bin --extract-jffs2-only
多固件分析
# Compare multiple firmware versions
/re:firmware router-v1.bin --output ./v1-analysis/
/re:firmware router-v2.bin --output ./v2-analysis/

# Diff analysis
diff -r ./v1-analysis/squashfs-root/ ./v2-analysis/squashfs-root/

# Find newly introduced binaries
diff <(ls ./v1-analysis/squashfs-root/usr/bin/) \
     <(ls ./v2-analysis/squashfs-root/usr/bin/)
自动化固件仿真
# Use firmadyne for full system emulation
git clone https://github.com/firmadyne/firmadyne
cd firmadyne

# Setup database
./download.sh

# Emulate firmware
./scripts/inferNetwork.sh router-firmware.bin
./scripts/makeImage.sh router-firmware.bin

# Access emulated device
http://192.168.1.1  # Default gateway
telnet 192.168.1.1 23  # Telnet access

故障排除

问题 1:固件已加密

症状:熵值较高(>0.9),binwalk 未找到文件系统

原因:固件已加密

解决方案 1:查找解密密钥

# Search vendor SDK for keys
find ./vendor-sdk/ -name "*.key" -o -name "*aes*" -o -name "*decrypt*"

# Common key locations:
# - vendor-sdk/tools/encryption_key.bin
# - vendor-docs/firmware-encryption.txt
# - GPL source code archives

解决方案 2:检查已知加密方案

# TP-Link uses custom encryption
tplink-safeloader -d firmware.bin -o decrypted.bin

# D-Link uses AES-256-CBC with known IV
openssl enc -d -aes-256-cbc -in firmware.bin -out decrypted.bin \
  -K <known_key> -iv <known_iv>

解决方案 3:逆向分析引导加载程序

# Extract bootloader (usually at offset 0)
dd if=firmware.bin bs=1 count=65536 of=bootloader.bin

# Analyze bootloader for decryption routine
/re:static bootloader.bin --tool ghidra

# Look for AES/DES crypto initialization

问题 2:无法提取文件系统

症状:binwalk 提取失败或生成损坏的文件

原因:文件系统格式或压缩方式非标准

解决方案 1:尝试使用不同工具手动提取

# SquashFS variants
unsquashfs -d ./output squashfs.img                # Standard
unsquashfs-lzma -d ./output squashfs.img          # LZMA compressed
jefferson ./output squashfs.img                    # Alternative tool

# JFFS2
jefferson jffs2.img -d ./output

# UBIFS
ubireader_extract_images -o ./output firmware.bin

# CramFS
cramfsck -x ./output cramfs.img

解决方案 2:使用 firmware-mod-kit

# Firmware mod kit supports many formats
git clone https://github.com/rampageX/firmware-mod-kit
cd firmware-mod-kit/src
./configure && make

# Extract
./extract-firmware.sh ../firmware.bin

# Filesystem extracted to ./fmk/rootfs/

解决方案 3:手动提取数据

# Find filesystem magic bytes
binwalk firmware.bin

# Example: SquashFS at offset 0x100000 (1048576)
# Magic: 68 73 71 73 (hsqs)

# Extract from offset to end
dd if=firmware.bin bs=1 skip=1048576 of=filesystem.img

# Try unsquash
unsquashfs filesystem.img

问题 3:二进制文件无法执行(架构不匹配)

症状:运行提取的二进制文件时出现“Exec format error”

原因:二进制文件是为其他架构编译的(MIPS、ARM 等)

解决方案 1:识别架构并使用相应的 QEMU

# Identify architecture
file ./squashfs-root/usr/sbin/httpd

# Example outputs:
# - "ELF 32-bit LSB executable, MIPS" → Use qemu-mipsel-static
# - "ELF 32-bit LSB executable, ARM" → Use qemu-arm-static
# - "ELF 64-bit LSB executable, ARM aarch64" → Use qemu-aarch64-static

# Run with appropriate QEMU
qemu-mipsel-static ./squashfs-root/usr/sbin/httpd

# Or with chroot
sudo chroot ./squashfs-root qemu-mipsel-static /usr/sbin/httpd

解决方案 2:使用 QEMU 进行完整系统仿真

# Create QEMU disk image
qemu-img create -f qcow2 firmware.qcow2 1G

# Boot with QEMU
qemu-system-mips -M malta -kernel vmlinux -hda firmware.qcow2 \
  -append "root=/dev/sda1 console=ttyS0" -nographic

# Or use firmadyne (automated)
firmadyne.sh firmware.bin

解决方案 3:使用带有 QEMU 用户态仿真的 Docker

# Docker with multi-arch support
docker run --rm -it --platform linux/arm/v7 \
  -v $(pwd)/squashfs-root:/firmware \
  arm32v7/ubuntu:20.04 bash

# Inside container
cd /firmware
./usr/sbin/httpd

问题 4:CVE 扫描未发现漏洞

症状:自动扫描未检测到已知漏洞

原因:版本字符串与 CVE 数据库格式不匹配

解决方案 1:手动检查版本

# Extract version strings
strings ./squashfs-root/lib/libssl.so.1.0.0 | grep -i version

# Output: "OpenSSL 1.0.1e 11 Feb 2013"

# Manually check CVE database
# CVE-2014-0160 affects OpenSSL 1.0.1 - 1.0.1f
# Result: VULNERABLE

解决方案 2:使用多个 CVE 扫描器

# Use cve-bin-tool
cve-bin-tool ./squashfs-root/

# Use grype
grype dir:./squashfs-root/

# Use trivy
trivy fs ./squashfs-root/

解决方案 3:自定义特征匹配

# Create custom CVE rules
cat > custom-cve-rules.txt <<EOF
OpenSSL 1.0.1[a-f]: CVE-2014-0160 (Heartbleed)
BusyBox 1.2[0-4]: CVE-2021-28831 (Command injection)
Dropbear 201[0-6]: CVE-2016-7406 (Format string)
EOF

# Scan with custom rules
grep -f custom-cve-rules.txt <(find ./squashfs-root/ -exec strings {} \; 2>/dev/null)

问题 5:无法找到硬编码凭据

症状:尽管预期会找到密码,grep 搜索却没有结果

原因:凭据经过编码或加密,或以二进制格式存储

解决方案 1:搜索编码字符串

# Base64 encoded credentials
find ./squashfs-root/ -type f -exec grep -l "YWRtaW46YWRtaW4=" {} \;
# (base64 decode: admin:admin)

# Hex encoded
grep -rE "61646d696e" ./squashfs-root/etc/
# (hex decode: admin)

# URL encoded
grep -rE "%61%64%6d%69%6e" ./squashfs-root/

解决方案 2:在二进制文件和数据库中搜索

# SQLite databases
find ./squashfs-root/ -name "*.db" -o -name "*.sqlite"
sqlite3 ./etc/config.db "SELECT * FROM users;"

# Binary config files
strings ./squashfs-root/etc/config.bin | grep -i "password\|admin"

解决方案 3:对身份验证二进制文件进行逆向工程

# Analyze login binary
/re:static ./squashfs-root/usr/bin/login --tool ghidra

# Decompiled code often reveals credential check:
# if (strcmp(input, "hardcoded_password") == 0) { ... }

性能优化

加快提取速度
# Parallel extraction (if multiple partitions)
binwalk -e partition1.bin &
binwalk -e partition2.bin &
wait

# Use faster decompression
unsquashfs -p 4 squashfs.img  # 4 parallel threads
加快服务发现速度
# Parallel grep searches
grep -r "telnetd" ./squashfs-root/etc/ &
grep -r "httpd" ./squashfs-root/etc/ &
grep -r "sshd" ./squashfs-root/etc/ &
wait
优化 CVE 扫描
# Skip common false positives
mcp__security-manager__scan_vulnerabilities({
  filesystem_root: "./squashfs-root/",
  skip_binaries: ["busybox", "dropbear"],  # Manually verified
  only_critical: true  # Only report CRITICAL and HIGH
})

Memory-MCP 集成

存储固件分析结果
// After firmware extraction completes
mcp__memory-mcp__memory_store({
  content: {
    firmware_hash: "sha256:abc123...",
    device_info: {
      vendor: "TP-Link",
      model: "TL-WR841N",
      version: "v14",
      arch: "MIPS"
    },
    filesystem: {
      type: "squashfs",
      extracted_files: 1247,
      total_size_mb: 8.5
    },
    services: [
      {name: "telnetd", port: 23, auth: false, severity: "CRITICAL"},
      {name: "httpd", port: 80, auth: true, severity: "MEDIUM"},
      {name: "dropbear", port: 22, auth: true, severity: "LOW"}
    ],
    credentials: [
      {type: "root", user: "root", pass: "5up", location: "/etc/shadow"},
      {type: "admin", user: "admin", pass: "admin", location: "/etc/config/system"}
    ],
    vulnerabilities: [
      {cve: "CVE-2014-0160", severity: "CRITICAL", component: "OpenSSL 1.0.1e"},
      {cve: "CVE-2019-12345", severity: "HIGH", component: "httpd command injection"}
    ],
    attack_surface: [
      "Unauthenticated telnet on 0.0.0.0:23",
      "Command injection in /cgi-bin/admin.cgi",
      "Path traversal in /cgi-bin/download.cgi"
    ],
    binary_analysis: {
      analyzed: ["/usr/sbin/httpd", "/www/cgi-bin/admin.cgi"],
      findings: "Command injection confirmed in admin.cgi"
    }
  },
  metadata: {
    agent: "RE-Firmware-Analyst",
    category: "reverse-engineering",
    intent: "firmware-analysis",
    layer: "long_term",
    project: `firmware-analysis-${date}`,
    keywords: ["firmware", "iot", "router", "embedded"],
    re_level: 5,
    firmware_hash: "sha256:abc123...",
    timestamp: new Date().toISOString()
  }
})

Agent 与命令

调用的 Agent
  1. RE-Firmware-Analyst(级别 5)

    • 专长:固件提取和 IoT 安全分析
    • 工具:binwalk、unsquashfs、jefferson、firmadyne、QEMU
    • 输出:提取的文件系统、服务映射、凭据列表、CVE 报告
  2. RE-String-Analyst(级别 1,针对已提取的二进制文件)

    • 用于分析已提取的二进制文件,以提取 IOC
  3. RE-Disassembly-Expert(级别 2,针对已提取的二进制文件)

    • 用于分析已提取的二进制文件,以分析漏洞
  4. security-manager(自动)

    • 对已提取的库执行 CVE 扫描
斜杠命令
  • /re:firmware <firmware> - 完整的级别 5 分析(此技能的主要命令)
  • /re:strings <binary> - 用于已提取的二进制文件
  • /re:static <binary> - 用于已提取的二进制文件
MCP 服务
  • filesystem:浏览已提取的固件目录
  • security-manager:自动化 CVE 扫描
  • connascence-analyzer:分析已提取代码的代码质量
  • memory-mcp:跨会话持久化固件分析结果
  • sequential-thinking:二进制分析升级的决策关卡

相关技能


资源

外部工具
学习资源
社区

创建日期:2025-11-01 RE 级别:5(固件分析) 时间限制:2-8 小时 类别:IoT 安全、嵌入式系统、固件逆向工程 难度:高级

核心原则

逆向工程:固件分析基于 3 项基本原则:

原则 1:分层提取策略

固件包含多个嵌套组件(引导加载程序、内核、文件系统、配置),需要逐步提取。

实践中:

  • 使用 binwalk 熵分析,在尝试提取前检测加密
  • 递归提取文件系统(matryoshka 模式),以处理嵌套归档
  • 使用签名扫描(SquashFS、JFFS2、UBIFS 魔数)确定组件边界
  • 自动提取失败时,使用 dd 手动雕刻数据
原则 2:攻击面映射

IoT 设备通过网络服务、Web 界面和硬编码凭据暴露攻击面。

实践中:

  • 从 init 脚本映射所有网络监听服务(telnetd、httpd、UPnP 守护进程)
  • 分析 CGI 脚本中的命令注入和路径遍历漏洞
  • 从 shadow 文件、配置数据库和二进制字符串中提取凭据
  • 记录固件更新机制,以识别供应链攻击途径
原则 3:跨组件关联

漏洞往往横跨多个固件组件(Web 界面 + 二进制守护进程 + 内核模块)。

实践中:

  • 将 CGI 脚本漏洞与后端二进制分析结果关联起来
  • 将硬编码凭据与服务身份验证机制关联起来
  • 验证共享库(OpenSSL、BusyBox、Dropbear)中的 CVE
  • 对提取出的可执行文件应用 1–4 级二进制分析

常见反模式

反模式问题解决方案
在主机上执行固件二进制文件架构不匹配(MIPS/ARM)、可能存在后门、系统遭到入侵使用 QEMU 用户模式仿真,或使用 firmadyne 进行完整系统仿真
忽略加密固件分析不完整、遗漏漏洞、产生虚假的安全感在厂商 SDK 中搜索解密密钥,逆向分析引导加载程序的加密例程,检查已知设备的解密方案
跳过服务发现遗漏网络暴露的攻击面(未经身份验证的 telnet、存在漏洞的 CGI)分析 init 脚本,grep 搜索 bind/listen 调用,将网络监听服务映射到二进制文件
不验证提取结果文件系统损坏、文件缺失、分析不完整确认关键目录存在(/bin、/etc、/lib、/www),检查文件数量是否符合预期
公开分享原始凭据法律责任、相关设备遭到入侵、侵犯客户隐私对内部 IP 进行编辑,发布 IOC 前清理凭据,并使用安全的漏洞披露渠道

结论

逆向工程:固件分析是了解全球部署的数十亿台 IoT 和嵌入式设备安全状况的入口。通过系统地提取文件系统、映射网络服务、搜寻硬编码凭据以及扫描 CVE,这项技能能够揭示关键漏洞,而这些漏洞会使 IoT 设备成为僵尸网络招募和供应链攻击的主要目标。

这项技能的价值不止于分析单台设备——分析结果适用于共享同一固件基础的整个产品线。单个提取出的默认密码或命令注入漏洞,就可能危及数千台设备。结合对提取出的可执行文件进行 1–4 级二进制分析,这项技能可实现从引导加载程序到应用层的全面安全评估。

在部署前分析路由器固件、审计智能家居设备的隐私问题,或对嵌入式系统开展漏洞研究时,都可以使用这项技能。2–8 小时的时间限制使其既适用于针对性的安全审计,也适用于大规模 IoT 安全研究项目。与 memory-mcp 集成后,可实现跨固件关联,从而识别不同厂商之间的常见漏洞,加速大规模 IoT 安全研究。

评论

支持 Markdown