ctf-malware

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

CTF Malware & Network Analysis

CTF恶意软件与网络分析

Obfuscated Scripts

混淆脚本分析

  • Replace
    eval
    /
    bash
    with
    echo
    to print underlying code
  • Extract base64/hex blobs and analyze with
    file
  • Common deobfuscation chain: base64 decode → gzip decode → reverse → base64 decode
  • eval
    /
    bash
    替换为
    echo
    以打印底层代码
  • 提取base64/十六进制数据块,使用
    file
    命令分析
  • 常见反混淆流程:base64解码 → gzip解码 → 反转 → base64解码

Debian Package Analysis

Debian程序包分析

bash
ar -x package.deb           # Unpack debian package
tar -xf control.tar.xz      # Check control files
bash
ar -x package.deb           # Unpack debian package
tar -xf control.tar.xz      # Check control files

Look for postinst scripts that execute payloads

Look for postinst scripts that execute payloads

undefined
undefined

Custom Crypto Protocols

自定义加密协议分析

  • Stream ciphers may share keystream state for both directions
  • Concatenate ALL payloads chronologically before decryption
  • Look for hardcoded keys in
    .rodata
  • ChaCha20 keystream extraction: Send large nullbytes payload (0 XOR anything = anything)
  • Alternative: Pipe ciphertext from pcap directly into the binary
  • 流密码可能在双向通信中共享密钥流状态
  • 解密前按时间顺序拼接所有载荷
  • .rodata
    段中查找硬编码密钥
  • ChaCha20密钥流提取: 发送大量空字节载荷(0与任何值异或结果为原值)
  • 替代方法:将pcap中的密文直接传入二进制程序

PCAP Analysis

PCAP流量分析

bash
tshark -r file.pcap -Y "tcp.stream eq X" -T fields -e tcp.payload
Look for C2 communication patterns on unusual ports (e.g., port 21 not for FTP).
bash
tshark -r file.pcap -Y "tcp.stream eq X" -T fields -e tcp.payload
查找非标准端口上的C2通信模式(例如,端口21未用于FTP服务)。

Hex-Encoded Payloads

十六进制编码载荷分析

  • Convert hex to bytes, try common transformations: subtract 1, XOR with key
  • 将十六进制转换为字节,尝试常见变换:减1、与密钥异或

JavaScript Deobfuscation

JavaScript反混淆

javascript
// Replace eval with console.log
eval = console.log;
// Then run the obfuscated code

// Common patterns
unescape()           // URL decoding
String.fromCharCode() // Char codes
atob()               // Base64
javascript
// Replace eval with console.log
eval = console.log;
// Then run the obfuscated code

// Common patterns
unescape()           // URL decoding
String.fromCharCode() // Char codes
atob()               // Base64

PowerShell Analysis

PowerShell分析

powershell
undefined
powershell
undefined

Common obfuscation

Common obfuscation

-enc / -EncodedCommand # Base64 encoded IEX / Invoke-Expression # Eval equivalent [System.Text.Encoding]::Unicode.GetString([System.Convert]::FromBase64String($encoded))
undefined
-enc / -EncodedCommand # Base64 encoded IEX / Invoke-Expression # Eval equivalent [System.Text.Encoding]::Unicode.GetString([System.Convert]::FromBase64String($encoded))
undefined

PE Analysis

PE文件分析

bash
peframe malware.exe      # Quick triage
pe-sieve                 # Runtime analysis
pestudio                 # Static analysis (Windows)
bash
peframe malware.exe      # Quick triage
pe-sieve                 # Runtime analysis
pestudio                 # Static analysis (Windows)

Sandbox Evasion Checks

沙箱规避检测

Look for:
  • VM detection (VMware, VirtualBox artifacts)
  • Debugger detection (IsDebuggerPresent)
  • Timing checks (sleep acceleration)
  • Environment checks (username, computername)
  • File/registry checks for analysis tools
需查找以下特征:
  • 虚拟机检测(VMware、VirtualBox相关痕迹)
  • 调试器检测(IsDebuggerPresent)
  • 计时检测(睡眠加速)
  • 环境检测(用户名、计算机名)
  • 针对分析工具的文件/注册表检测

Network Indicators

网络指标提取

bash
undefined
bash
undefined

Extract IPs/domains

Extract IPs/domains

strings malware | grep -E '[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}' strings malware | grep -E '[a-zA-Z0-9.-]+.(com|net|org|io)'
strings malware | grep -E '[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}' strings malware | grep -E '[a-zA-Z0-9.-]+.(com|net|org|io)'

DNS queries

DNS queries

tshark -r capture.pcap -Y "dns.qry.name" -T fields -e dns.qry.name | sort -u
undefined
tshark -r capture.pcap -Y "dns.qry.name" -T fields -e dns.qry.name | sort -u
undefined

C2 Traffic Patterns

C2通信模式分析

  • Beaconing: regular intervals
  • Domain generation algorithms (DGA)
  • Encoded/encrypted payloads
  • HTTP(S) with custom headers
  • DNS tunneling
  • 信标:定期发送的通信
  • 域名生成算法(DGA)
  • 编码/加密载荷
  • 带自定义头的HTTP(S)通信
  • DNS隧道

Junk Code Detection

垃圾代码检测

Pattern: Obfuscation adds meaningless instructions around real code
Identification:
  • NOP sleds, push/pop pairs that cancel
  • Arithmetic that results in zero/identity
  • Dead writes (register written but never read before next write)
  • Unconditional jumps to next instruction
Filtering technique:
python
undefined
特征: 混淆操作会在真实代码周围添加无意义指令
识别方法:
  • NOP指令块、相互抵消的push/pop指令对
  • 结果为零/恒等的运算
  • 无效写入(寄存器被写入后,下次写入前未被读取)
  • 跳转到下一条指令的无条件跳转
过滤技巧:
python
undefined

Identify real calls by looking for patterns

Identify real calls by looking for patterns

junk, junk, junk, CALL target, junk, junk

junk, junk, junk, CALL target, junk, junk

Extract call targets, ignore surrounding noise

Extract call targets, ignore surrounding noise

def extract_real_calls(disassembly): calls = [] for instr in disassembly: if instr.mnemonic == 'call' and not is_junk_target(instr.operand): calls.append(instr) return calls
undefined
def extract_real_calls(disassembly): calls = [] for instr in disassembly: if instr.mnemonic == 'call' and not is_junk_target(instr.operand): calls.append(instr) return calls
undefined

.NET DNS-based C2

基于DNS的.NET C2分析

Pattern: Deobfuscated .NET malware with DNS C2
Analysis with dnSpy:
  1. Find network functions (TcpClient, DnsClient, etc.)
  2. Identify encoding/encryption wrappers
  3. Look for command dispatch (switch on opcode)
AsmResolver for programmatic analysis:
csharp
using AsmResolver.DotNet;
var module = ModuleDefinition.FromFile("malware.dll");
foreach (var type in module.GetAllTypes()) {
    foreach (var method in type.Methods) {
        // Analyze method body
    }
}
特征: 经过反混淆的.NET恶意软件使用DNS作为C2信道
使用dnSpy分析:
  1. 查找网络相关函数(TcpClient、DnsClient等)
  2. 识别编码/加密包装器
  3. 查找命令分发逻辑(基于操作码的switch语句)
使用AsmResolver进行程序化分析:
csharp
using AsmResolver.DotNet;
var module = ModuleDefinition.FromFile("malware.dll");
foreach (var type in module.GetAllTypes()) {
    foreach (var method in type.Methods) {
        // Analyze method body
    }
}

AES-CBC in Malware

恶意软件中的AES-CBC分析

Common key derivation:
  • MD5/SHA256 of hardcoded string
  • Derived from timestamp or PID
  • Password-based (PBKDF2)
Analysis approach:
python
from Crypto.Cipher import AES
from Crypto.Util.Padding import unpad
import hashlib
常见密钥派生方式:
  • 硬编码字符串的MD5/SHA256哈希
  • 从时间戳或PID派生
  • 基于密码(PBKDF2)
分析方法:
python
from Crypto.Cipher import AES
from Crypto.Util.Padding import unpad
import hashlib

Common pattern: key = MD5(password)

Common pattern: key = MD5(password)

password = b"hardcoded_password" key = hashlib.md5(password).digest()
password = b"hardcoded_password" key = hashlib.md5(password).digest()

IV often first 16 bytes of ciphertext

IV often first 16 bytes of ciphertext

iv = ciphertext[:16] ct = ciphertext[16:]
cipher = AES.new(key, AES.MODE_CBC, iv) plaintext = unpad(cipher.decrypt(ct), 16)
undefined
iv = ciphertext[:16] ct = ciphertext[16:]
cipher = AES.new(key, AES.MODE_CBC, iv) plaintext = unpad(cipher.decrypt(ct), 16)
undefined

Password Rotation in C2

C2中的密码轮换机制

Pattern: C2 uses rotating passwords based on time/sequence
Analysis:
  1. Find password generation function
  2. Identify rotation trigger (time-based, message count)
  3. Sync your decryptor with the rotation
python
def get_current_password(timestamp):
    # Password changes every hour
    hour_bucket = timestamp // 3600
    return hashlib.sha256(f"seed_{hour_bucket}".encode()).digest()
特征: C2基于时间/序列使用轮换密码
分析步骤:
  1. 查找密码生成函数
  2. 识别轮换触发条件(基于时间、消息计数)
  3. 使解密工具与密码轮换同步
python
def get_current_password(timestamp):
    # Password changes every hour
    hour_bucket = timestamp // 3600
    return hashlib.sha256(f"seed_{hour_bucket}".encode()).digest()

Malware Configuration Extraction

恶意软件配置提取

Common storage locations:
  • .data section (hardcoded)
  • Resources (PE resources, .NET resources)
  • Registry keys written at install
  • Encrypted config file dropped to disk
Extraction tools:
bash
undefined
常见存储位置:
  • .data段(硬编码)
  • 资源区(PE资源、.NET资源)
  • 安装时写入的注册表项
  • 写入磁盘的加密配置文件
提取工具:
bash
undefined

PE resources

PE resources

wrestool -x -t 10 malware.exe -o config.bin
wrestool -x -t 10 malware.exe -o config.bin

.NET resources

.NET resources

monodis --mresources malware.exe
monodis --mresources malware.exe

Strings in .rdata/.data

Strings in .rdata/.data

objdump -s -j .rdata malware.exe
undefined
objdump -s -j .rdata malware.exe
undefined

Identifying Encryption Algorithms

加密算法识别

By constants:
  • AES:
    0x637c777b
    ,
    0x63636363
    (S-box)
  • ChaCha20:
    expand 32-byte k
    or
    0x61707865
  • RC4: Sequential S-box initialization
  • TEA/XTEA:
    0x9E3779B9
    (golden ratio)
By structure:
  • Block cipher: Fixed-size blocks, padding
  • Stream cipher: Byte-by-byte, no padding
  • Hash: Mixing functions, rounds, constants
通过常量识别:
  • AES:
    0x637c777b
    0x63636363
    (S盒)
  • ChaCha20:
    expand 32-byte k
    0x61707865
  • RC4:顺序S盒初始化
  • TEA/XTEA:
    0x9E3779B9
    (黄金比例常数)
通过结构识别:
  • 分组密码:固定大小块、填充
  • 流密码:逐字节处理、无填充
  • 哈希:混合函数、轮次、常量

.NET Malware Analysis (C2 Extraction)

.NET恶意软件分析(C2提取)

Tools: ILSpy, dnSpy, dotPeek
LimeRAT C2 extraction (Whisper Of The Pain):
  1. Open .NET binary in dnSpy
  2. Find configuration class with Base64 encoded string
  3. Identify decryption method (typically AES-256-ECB with derived key)
  4. Key derivation: MD5 of hardcoded string → first 15 + full 16 bytes + null = 32-byte key
  5. Decrypt: Base64 decode → AES-ECB decrypt → reveals C2 IP/domain
python
from Crypto.Cipher import AES
import hashlib, base64

key_source = '${8\',`d0}n,~@J;oZ"9a'
md5 = hashlib.md5(key_source.encode()).hexdigest()
工具: ILSpy、dnSpy、dotPeek
LimeRAT C2提取(Whisper Of The Pain):
  1. 使用dnSpy打开.NET二进制文件
  2. 查找包含Base64编码字符串的配置类
  3. 识别解密方法(通常是带派生密钥的AES-256-ECB)
  4. 密钥派生:硬编码字符串的MD5哈希 → 前15字节 + 完整16字节 + 空字节 = 32字节密钥
  5. 解密:Base64解码 → AES-ECB解密 → 得到C2 IP/域名
python
from Crypto.Cipher import AES
import hashlib, base64

key_source = '${8\',`d0}n,~@J;oZ"9a'
md5 = hashlib.md5(key_source.encode()).hexdigest()

Key = md5[:30] + md5 + '\x00' (32 bytes total as hex → 16 bytes binary)

Key = md5[:30] + md5 + '\x00' (32 bytes total as hex → 16 bytes binary)

key = bytes.fromhex(md5[:30] + md5 + '00')[:32]
cipher = AES.new(key, AES.MODE_ECB) plaintext = cipher.decrypt(base64.b64decode(encrypted_b64))
undefined
key = bytes.fromhex(md5[:30] + md5 + '00')[:32]
cipher = AES.new(key, AES.MODE_ECB) plaintext = cipher.decrypt(base64.b64decode(encrypted_b64))
undefined

Telegram Bot API for Evidence Recovery

利用Telegram Bot API恢复取证数据

Pattern (Stomaker): Malware uses Telegram bot to exfiltrate stolen data.
Recover exfiltrated data via bot token:
python
undefined
特征(Stomaker恶意软件): 恶意软件使用Telegram Bot窃取并泄露数据
通过Bot令牌恢复泄露数据:
python
undefined

If you have the bot API token from malware source:

If you have the bot API token from malware source:

import requests
TOKEN = "bot_token_here"
import requests
TOKEN = "bot_token_here"

Get updates (message history)

Get updates (message history)

Download files sent to bot

Download files sent to bot

file_id = "..." r = requests.get(f"https://api.telegram.org/bot{TOKEN}/getFile?file_id={file_id}") file_path = r.json()['result']['file_path'] requests.get(f"https://api.telegram.org/file/bot{TOKEN}/{file_path}")
undefined
file_id = "..." r = requests.get(f"https://api.telegram.org/bot{TOKEN}/getFile?file_id={file_id}") file_path = r.json()['result']['file_path'] requests.get(f"https://api.telegram.org/file/bot{TOKEN}/{file_path}")
undefined

RC4-Encrypted WebSocket C2 Traffic

基于RC4加密的WebSocket C2流量分析

Pattern (Tampered Seal): Malware uses WSS over non-standard port with RC4 encryption.
Decryption workflow:
  1. Identify C2 port from malware source (not standard 443)
  2. Remap port with
    tcprewrite
    so Wireshark decodes TLS
  3. Add RSA key for TLS decryption → reveals WebSocket frames
  4. Find RC4 key hardcoded in malware binary
  5. Decrypt each WebSocket payload with RC4 via CyberChef
Malware communication patterns:
  • Registration message: hostname, OS, username, privileges
  • Exfiltration: screenshots, keylog data, file contents
  • Commands: reverse shell, file download, process list
特征(Tampered Seal恶意软件): 恶意软件在非标准端口上使用WSS并通过RC4加密
解密流程:
  1. 从恶意软件源码中找到C2端口(非标准443端口)
  2. 使用
    tcprewrite
    重映射端口,使Wireshark可解码TLS
  3. 添加RSA密钥以解密TLS → 得到WebSocket帧
  4. 在恶意软件二进制文件中查找硬编码的RC4密钥
  5. 通过CyberChef使用RC4解密每个WebSocket载荷
恶意软件通信模式:
  • 注册消息:主机名、操作系统、用户名、权限
  • 数据泄露:截图、键盘记录数据、文件内容
  • 命令:反向shell、文件下载、进程列表

PyInstaller + PyArmor Unpacking

PyInstaller + PyArmor脱壳

bash
undefined
bash
undefined

Step 1: Extract PyInstaller archive

Step 1: Extract PyInstaller archive

python pyinstxtractor.py malware.exe
python pyinstxtractor.py malware.exe

Look for main .pyc file in extracted directory

Look for main .pyc file in extracted directory

Step 2: If PyArmor-protected, use unpacker

Step 2: If PyArmor-protected, use unpacker

github.com/Svenskithesource/PyArmor-Unpacker

github.com/Svenskithesource/PyArmor-Unpacker

Three methods available; choose based on PyArmor version

Three methods available; choose based on PyArmor version

Step 3: Clean up deobfuscated source

Step 3: Clean up deobfuscated source

Remove fake/dead-code functions (confusion code)

Remove fake/dead-code functions (confusion code)

Identify core encryption/exfiltration logic

Identify core encryption/exfiltration logic

undefined
undefined