ByteCodeSecure/SkullLocker-Linux
GitHub: ByteCodeSecure/SkullLocker-Linux
一个用于安全研究的 Linux 勒索软件样本,采用 X25519 与 ChaCha20-Poly1305 混合加密方案,帮助研究人员理解勒索软件机制并构建检测与防御策略。
Stars: 0 | Forks: 0
# Skull Locker — Linux 勒索软件样本(研究与剖析)
.skull
```
## 加密实现分析
### 为何在没有私钥的情况下此加密不可破解
This is the core reason why crypto-ransomware is so destructive. Understanding the scheme helps defenders grasp why prevention (backups) is the only real mitigation.
```
┌─────────────────────────────────────────────────────────────────┐
│ ATTACKER (offline key generation) │
│ ┌─────────────────────────────────────────────────────────┐ │
│ │ X25519 keypair: │ │
│ │ private_key → kept secret by attacker │ │
│ │ public_key → hardcoded in malware binary: │ │
│ │ 94f35828bbaac2bb35465ec5c09bd42ccade70906e64b6856... │ │
│ └─────────────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────────┐
│ VICTIM SYSTEM (per-file encryption) │
│ ┌─────────────────────────────────────────────────────────┐ │
│ │ 1. Generate ephemeral X25519 keypair (random each file)│ │
│ │ 2. shared_secret = X25519(ephemeral_private, │ │
│ │ attacker_public_key) │ │
│ │ 3. file_key = OsRng::random_32_bytes() │ │
│ │ 4. encrypted_file_key = ChaCha20(file_key, │ │
│ │ key=shared_secret) │ │
│ │ 5. File header: ---key---{ephemeral_pub}:{enc_key}--- │ │
│ │ 6. File body = ChaCha20_chunks(content, key=file_key) │ │
│ └─────────────────────────────────────────────────────────┘ │
│ │
│ ← ephemeral_public_key stored in file (NOT the secret) │
│ ← private_key NEVER touches victim disk │
└─────────────────────────────────────────────────────────────────┘
```
**Decryption requires:**
1. Attacker's private key (possessed only by attacker)
2. Victim's `ephemeral_public_key` from file header (available)
3. `shared_secret = X25519(attacker_private, victim_ephemeral_public)`
4. Decrypt `encrypted_file_key` → get `file_key`
5. Decrypt file contents chunk by chunk
### 加密文件格式
```
[0..] ---key---:---endkey---\n
[N..] [ChaCha20-Poly1305 encrypted content — 1MB chunks]
```
### 选择性加密
| File Size | Encrypted Portion | Effect |
|-----------|-------------------|--------|
| ≤ 1 GB | 100% | Fully unusable |
| > 1 GB | First 20% only | File header corrupted — still unusable for most formats |
## 文件系统目标定位逻辑
### 主动攻击目录
```
~/Documents ~/Downloads ~/Pictures
~/Videos ~/Music ~/Desktop
~/Public ~/Templates
/home/* /media/* /mnt/*
```
### 系统保留黑名单(保持系统可启动)
The ransomware intentionally skips system directories so the victim can boot and pay:
```
System: /tmp /temp /proc /sys /dev /run /var /boot
Binaries: /lib /lib64 /bin /sbin /usr /opt /etc /root
User app: .cache .config .local snap flatpak
Browsers: .mozilla .chrome .firefox .thunderbird
Dev/misc: .steam .wine .git .svn .hg node_modules __pycache__
```
### 黑名单文件扩展名
```
Already encrypted: .skull
System/binaries: .exe .dll .so .a .o .ko
Packages: .deb .rpm
Archives: .tar .gz .bz2 .xz .zip .rar .7z
Disk images: .iso .img .bin .run .appimage .snap .flatpak
Runtime/temp: .lock .pid .log .tmp .swp .bak .cache .pyc .pyo .class
```
### 黑名单特定文件
```
Boot: vmlinuz initrd initramfs grub.cfg
System: fstab passwd shadow group hosts resolv.conf
Dev: Makefile configure install.sh setup.py requirements.txt
Shell: .bashrc .profile .bash_profile .vimrc .gitignore
```
## 入侵指标 (IoCs)
### 文件系统 IoCs
| Indicator | Description | Use In |
|-----------|-------------|--------|
| `*.skull` file extension | Files renamed after encryption | SIEM file rename alerts, EDR |
| `README.txt` in user directories | Ransom note drop | File integrity monitoring |
| `/tmp/skull_locker.lock` | Single-instance PID lock file | Auditd, SIEM |
| Header `---key---...:...---endkey---\n` | Encrypted file marker at byte 0 | YARA, file scanning |
### 二进制 / 代码 IoCs
| Indicator | Value |
|-----------|-------|
| Attacker public key (hex) | `94f35828bbaac2bb35465ec5c09bd42ccade70906e64b6856bad9bc6af72db41` |
| Rust package name | `skull_locker_linux` |
| Lock file path | `/tmp/skull_locker.lock` |
### 勒索信签名
```
--= Your files have been encrypted by Skull Locker =--
military-grade encryption
TOX messenger
https://tox.chat/download.html
within 72 hours
the decryption price will double
```
## 检测策略
### YARA 规则
```
rule SkullLocker_Encrypted_File {
meta:
description = "Detects files encrypted by Skull Locker ransomware"
threat_level = 10
reference = "Skull Locker Linux sample - research only"
strings:
$header = "---key---"
$footer = "---endkey---"
$pubkey = "94f35828bbaac2bb35465ec5c09bd42ccade70906e64b6856bad9bc6af72db41"
condition:
$header at 0 and $footer and $pubkey
}
rule SkullLocker_RansomNote {
meta:
description = "Detects Skull Locker ransom note"
strings:
$s1 = "Your files have been encrypted by Skull Locker"
$s2 = "tox.chat"
$s3 = "within 72 hours"
condition:
2 of them
}
rule SkullLocker_Binary {
meta:
description = "Detects Skull Locker ELF binary strings"
strings:
$sym1 = "skull_locker_linux"
$sym2 = "skull_locker.lock"
$sym3 = "---key---"
$sym4 = "---endkey---"
$sym5 = "chacha20poly1305"
condition:
4 of them
}
```
### Auditd 规则 (Linux 行为检测)
```
# 检测批量文件重命名为 .skull
-a always,exit -F arch=b64 -S rename -S renameat -k skull_locker_rename
# 检测锁文件创建
-a always,exit -F arch=b64 -S open -F path=/tmp/skull_locker.lock -k skull_locker_lock
# 检测对锁文件的 flock
-a always,exit -F arch=b64 -S flock -F path=/tmp/skull_locker.lock -k skull_locker_flock
```
### Falco 规则 (云原生运行时检测)
```
- rule: Skull Locker Ransomware Activity
desc: Detects file operations consistent with Skull Locker Linux ransomware
condition: >
(open_write and fd.name endswith ".skull") or
(rename and evt.arg.newpath endswith ".skull") or
(open_write and fd.name = "/tmp/skull_locker.lock")
output: >
Possible ransomware activity (user=%user.name command=%proc.cmdline
file=%fd.name container=%container.name)
priority: CRITICAL
tags: [ransomware, skull_locker, linux, file_encryption]
```
### inotify 蜜罐 (早期预警)
```
# 放置虚假“高价值”文件并在重命名时发出警报
touch ~/Documents/HONEYPOT_financial_data_2024.pdf
inotifywait -m ~/Documents -e rename --format '%f' | \
while read file; do
if echo "$file" | grep -q "\.skull$"; then
logger -p auth.crit "RANSOMWARE DETECTED: $file renamed to .skull"
# Send alert, isolate system, etc.
fi
done
```
## 防御与缓解
### 预防控制
| Control | Implementation | Effectiveness |
|---------|---------------|---------------|
| **Immutable offline backups** | 3-2-1 rule: 3 copies, 2 media, 1 offline/air-gapped | ★★★★★ Best mitigation |
| **Filesystem snapshots** | LVM snapshots, Btrfs subvolumes, ZFS snapshots | ★★★★☆ |
| **File immutability** | `chattr +i /home/user/critical_files/` | ★★★☆☆ |
| **noexec mounts** | `/home` and `/tmp` mounted with `noexec` | ★★★☆☆ |
| **AppArmor / SELinux** | Restrict process file access by policy | ★★★★☆ |
| **Principle of least privilege** | No root access for desktop applications | ★★★☆☆ |
| **Honeypot files** | Alert triggers on first `.skull` rename | ★★★★☆ Early warning |
| **EDR monitoring** | Detect mass rename operations via syscall analysis | ★★★★☆ |
### 事件响应 (如果被感染)
```
IMMEDIATE ACTIONS:
├── 1. ISOLATE: Disconnect from all networks immediately
├── 2. PRESERVE: Take memory dump (volatility) and disk image BEFORE any changes
├── 3. DO NOT REBOOT: Volatile evidence (keys in memory) may still be present
├── 4. INVENTORY: Find all *.skull files → ls -la $(find / -name "*.skull" 2>/dev/null)
├── 5. CHECK LOCK: cat /tmp/skull_locker.lock → PID may reveal process details
├── 6. RESTORE: From known-good offline backup
└── 7. REPORT: National cybercrime unit (IC3 in US, Action Fraud in UK, etc.)
```
## 安全分析环境设置
### 所需配置
```
┌─────────────────────────────────────────────────────────────┐
│ HOST MACHINE │
│ ┌───────────────────────────────────────────────────────┐ │
│ │ ISOLATED VM (VMware / VirtualBox / QEMU) │ │
│ │ │ │
│ │ ✓ Fresh Linux install (Ubuntu/Debian/Fedora) │ │
│ │ ✓ No real personal data │ │
│ │ ✗ NO network adapter (or Host-only ONLY) │ │
│ │ ✗ NO shared folders with host │ │
│ │ ✗ NO clipboard sharing │ │
│ │ │ │
│ │ WORKFLOW: │ │
│ │ 1. Take snapshot → "Clean_State_Before_Sample" │ │
│ │ 2. Load sample into VM │ │
│ │ 3. Analyze │ │
│ │ 4. Revert to "Clean_State_Before_Sample" │ │
│ │ 5. NEVER export sample to host machine │ │
│ └───────────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────────┘
```
### 静态分析 (无执行 — 完全安全)
```
# 字符串提取 — 揭示 IoCs、路径、消息
strings skull_locker_linux | grep -iE "(skull|key|readme|tox|lock|encrypt)"
# 符号表 — 揭示函数名称
nm skull_locker_linux 2>/dev/null
readelf -s skull_locker_linux 2>/dev/null | head -60
# 节头 — 揭示二进制结构
readelf -S skull_locker_linux
# 动态依赖项
ldd skull_locker_linux
# 用于威胁情报查询的哈希
sha256sum skull_locker_linux
md5sum skull_locker_linux
# 检查链接库 (静态 Rust 二进制文件 — 可能没有)
file skull_locker_linux
```
### 动态分析工具 (仅在隔离 VM 内)
```
# 系统调用追踪 — 揭示所有文件操作
strace -f -e trace=file,process -o strace_output.txt ./skull_locker_linux [args]
# 并行的实时文件监控
inotifywait -m -r /tmp /home -e create,rename,modify,delete \
--format '%T %w%f %e' --timefmt '%H:%M:%S' &
# 监控锁文件
watch -n 0.5 "ls -la /tmp/skull_locker.lock 2>/dev/null; cat /tmp/skull_locker.lock 2>/dev/null"
```
## 源代码结构
### 文件概览
| File | Lines | Purpose |
|------|-------|---------|
| `src/main.rs` | ~60 | Entry point, CLI argument parsing, orchestration |
| `src/crypto.rs` | ~120 | Encryption engine (ChaCha20 + X25519 + nonce management) |
| `src/disk.rs` | ~150 | File system targeting, blacklists, directory traversal |
| `src/utils.rs` | ~80 | Lock file (flock), ransom note deployment |
| `Cargo.toml` | ~20 | Rust dependencies manifest |
| `build.sh` | ~10 | Build automation script |
### `src/crypto.rs` — 加密引擎分析
This is the most important file for cryptographic understanding:
```
encrypt_file(path, attacker_pubkey):
1. Read entire file into memory (or stream for large files)
2. ephemeral_secret = X25519StaticSecret::random_from_rng(OsRng)
3. ephemeral_public = X25519PublicKey::from(&ephemeral_secret)
4. shared_secret = ephemeral_secret.diffie_hellman(&attacker_pubkey)
5. file_key = OsRng::fill_bytes(32)
6. encrypted_file_key = ChaCha20Poly1305(
key=shared_secret.as_bytes(),
nonce=[0u8; 12],
plaintext=file_key
)
7. Write header: "---key---{ephemeral_pub_hex}:{enc_key_hex}---endkey---\n"
8. For each 1MB chunk (nonce = counter):
Write ChaCha20Poly1305(key=file_key, nonce=[counter,0,0,0,0], chunk)
9. Delete original file
10. Write encrypted data to .skull
```
### `src/disk.rs` — 目标定位分析
Key function `get_target_directories()` builds target list:
1. Reads `$HOME` environment variable
2. Appends standard subdirectory names (Documents, Downloads, etc.)
3. Enumerates all entries in `/home/`
4. Adds all entries under `/media/` and `/mnt/`
Key function `process_directory()` encryption loop:
1. Drops `README.txt` ransom note first
2. Uses `walkdir::WalkDir::new(path).max_depth(5)` for traversal
3. Filters each entry through blacklist check
4. Skips files larger than 10GB
5. Calls `encrypt_file()` or `encrypt_file_silent()` per file
### `src/utils.rs` — 锁与勒索信分析
Lock file mechanism using Unix `flock()`:
```
// Creates /tmp/skull_locker.lock
// Calls flock(fd, LOCK_EX | LOCK_NB)
// LOCK_NB means: fail immediately if already locked
// Writes PID to lock file
// Returns error if another instance is running
```
## 行为分析
### 进程行为签名
| Behavior | System Call | Observable Effect | Detection Method |
|----------|-------------|-------------------|-----------------|
| Lock acquisition | `flock(LOCK_EX\|LOCK_NB)` on `/tmp/skull_locker.lock` | PID file created | auditd, inotify |
| Target discovery | `opendir()`/`readdir()` on `/home`, `/media`, `/mnt` | Directory listing burst | strace, eBPF |
| Ransom note drop | `creat()` + `write()` on `README.txt` | New file in each dir | inotify, EDR |
| File encryption | `open()` + `read()` + `write()` + `rename()` | Files become `.skull` | SIEM, EDR, YARA |
| 1MB chunk I/O | Sequential `read(1048576)` + `write()` | Characteristic I/O profile | eBPF syscall trace |
### 攻击期间的资源概况
| Resource | Observed Pattern |
|----------|-----------------|
| **CPU** | 20–60% (ChaCha20 is fast, disk I/O is the bottleneck) |
| **Disk I/O** | Very high — every file read + written + renamed |
| **Memory** | ~10–50 MB (1MB chunk buffer + key material) |
| **Network** | Zero (encryption is fully local — C2 contact happens separately) |
### 预估加密速度
| Storage Type | Throughput | 10GB encrypted in... |
|--------------|------------|----------------------|
| NVMe SSD | ~1000 MB/s | ~10 seconds |
| SATA SSD | ~500 MB/s | ~20 seconds |
| HDD | ~100 MB/s | ~100 seconds |
## 研究参考
| Resource | URL / Reference |
|----------|----------------|
| ChaCha20-Poly1305 Spec | [RFC 8439](https://datatracker.ietf.org/doc/html/rfc8439) |
| X25519 Key Exchange | [RFC 7748](https://datatracker.ietf.org/doc/html/rfc7748) |
| CISA Ransomware Guide | [cisa.gov/ransomware](https://www.cisa.gov/ransomware) |
| Linux Ransomware Analysis | *Practical Malware Analysis* — Sikorski & Honig |
| YARA Rules Documentation | [yara.readthedocs.io](https://yara.readthedocs.io) |
| Falco Runtime Security | [falco.org](https://falco.org) |
| eBPF Security Monitoring | [ebpf.io](https://ebpf.io) |
| `x25519-dalek` Rust Crate | [docs.rs/x25519-dalek](https://docs.rs/x25519-dalek) |
| `chacha20poly1305` Rust Crate | [docs.rs/chacha20poly1305](https://docs.rs/chacha20poly1305) |
| National Cybercrime Reporting | IC3: ic3.gov / Action Fraud: actionfraud.police.uk |
# Español — 恶意软件分析与研究指南
## 目录
1. [Clasificación de la Muestra](#clasificación-de-la-muestra)
2. [Descripción Técnica General](#descripción-técnica-general)
3. [Análisis de la Implementación Criptográfica](#análisis-de-la-implementación-criptográfica)
4. [Lógica de Targeting del Sistema de Archivos](#lógica-de-targeting-del-sistema-de-archivos)
5. [Indicadores de Compromiso (IoCs)](#indicadores-de-compromiso-iocs)
6. [Estrategias de Detección](#estrategias-de-detección)
7. [Defensa y Mitigación](#defensa-y-mitigación)
8. [Configuración de Entorno Seguro para Análisis](#configuración-de-entorno-seguro-para-análisis)
9. [Estructura del Código Fuente](#estructura-del-código-fuente)
10. [Análisis de Comportamiento](#análisis-de-comportamiento)
11. [Referencias de Investigación](#referencias-de-investigación)
## 样本分类
| Propiedad | Valor |
|-----------|-------|
| **Nombre** | Skull Locker |
| **Tipo** | Ransomware — Cifrado de Archivos |
| **SO Objetivo** | Linux (x86_64) |
| **Lenguaje** | Rust (Edición 2021) |
| **Binario** | `skull_locker_linux` (ELF 64-bit) |
| **Cifrado** | ChaCha20-Poly1305 (AEAD) |
| **Intercambio de Claves** | X25519 Elliptic Curve Diffie-Hellman |
| **Extensión de Archivo** | `.skull` añadida a archivos cifrados |
| **Nota de Rescate** | `README.txt` depositada en directorios objetivo |
| **Canal C2** | TOX messenger (P2P descentralizado) |
| **Nivel de Amenaza** | Crítico — cifrado de archivos irreversible sin clave privada del atacante |
## 通用技术描述
Skull Locker es una muestra de **crypto-ransomware** que apunta a entornos Linux de escritorio y servidor. Implementa un esquema de cifrado híbrido combinando intercambio de claves asimétricasX25519) con un cifrador simétrico autenticado (ChaCha20-Poly1305) para asegurar que la recuperación de archivos sea matemáticamente imposible sin la clave privada del atacante.
### 攻击流程(用于防御性理解)
```
Ejecución
│
▼
Verificación instancia única ──── ¿Ya en ejecución? → Salir
│ (usa /tmp/skull_locker.lock via flock())
▼
Descubrimiento de Objetivos
│ - Subdirectorios del hogar del usuario
│ - Todos los directorios /home/* (sistemas multi-usuario)
│ - Medios externos: /media/*, /mnt/*
▼
Por directorio:
├── Depositar nota de rescate (README.txt)
└── Recorrido recursivo de archivos (profundidad máx. 5)
├── Omitir: dirs en lista negra, tipos de archivo, archivos > 10GB
└── Para cada archivo válido:
├── Generar clave aleatoria de 32 bytes por archivo (OsRng)
├── Intercambio ECDH con clave pública hardcodeada del atacante
├── Cifrar clave del archivo con ChaCha20-Poly1305
├── Cifrar contenido del archivo en bloques de 1MB
├── Anteponer encabezado de metadatos
└── Renombrar original a .skull
```
## 加密实现分析
### 为何在没有私钥的情况下此加密不可破解
Esta es la razón central por la que el crypto-ransomware es tan destructivo. Comprender el esquema ayuda a los defensores a entender por qué la **prevención** (copias de seguridad) es la única mitigación real.
```
┌─────────────────────────────────────────────────────────────────┐
│ ATACANTE (generación de claves offline) │
│ ┌─────────────────────────────────────────────────────────┐ │
│ │ Par de claves X25519: │ │
│ │ clave_privada → guardada en secreto por el atacante │ │
│ │ clave_pública → hardcodeada en binario del malware: │ │
│ │ 94f35828bbaac2bb35465ec5c09bd42ccade70906e64b6856... │ │
│ └─────────────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────────┐
│ SISTEMA VÍCTIMA (cifrado por archivo) │
│ ┌─────────────────────────────────────────────────────────┐ │
│ │ 1. Generar par efímero X25519 (aleatório por archivo) │ │
│ │ 2. secreto_compartido = X25519(efímero_privada, │ │
│ │ clave_pública_atacante) │ │
│ │ 3. clave_archivo = OsRng::bytes_aleatorios(32) │ │
│ │ 4. clave_cifrada = ChaCha20(clave_archivo, │ │
│ │ clave=secreto_compartido) │ │
│ │ 5. Encabezado: ---key---{efím_pub}:{clave_cifrada}--- │ │
│ │ 6. Cuerpo = ChaCha20_bloques(contenido, clave_archivo) │ │
│ └─────────────────────────────────────────────────────────┘ │
│ │
│ ← clave_pública_efímera guardada en el archivo (no el secreto)│
│ ← clave_privada NUNCA toca el disco de la víctima │
└─────────────────────────────────────────────────────────────────┘
```
### 加密后的文件格式
```
[0..] ---key---:---endkey---\n
[N..] [Contenido cifrado con ChaCha20-Poly1305 en bloques de 1MB]
```
### 选择性加密
| Tamaño del Archivo | Porción Cifrada | Efecto |
|--------------------|-----------------|--------|
| ≤ 1 GB | 100% del archivo | Completamente inutilizable |
| > 1 GB | Solo el primer 20% | Encabezado del archivo corrompido — inutilizable para la mayoría de formatos |
## 文件系统目标定位逻辑
### 主动攻击目录
```
~/Documentos ~/Descargas ~/Imágenes
~/Videos ~/Música ~/Escritorio
~/Público ~/Plantillas
/home/* /media/* /mnt/*
```
### 系统黑名单(保持系统可启动)
El ransomware omite intencionalmente los directorios del sistema para que la víctima pueda arrancar y pagar:
```
Sistema: /tmp /temp /proc /sys /dev /run /var /boot
Binarios: /lib /lib64 /bin /sbin /usr /opt /etc /root
App usuario:.cache .config .local snap flatpak
Navegadores:.mozilla .chrome .firefox .thunderbird
Dev: .steam .wine .git .svn .hg node_modules __pycache__
```
## 入侵指标 (IoCs)
### 文件系统 IoCs
| Indicador | Descripción | Usar En |
|-----------|-------------|---------|
| Extensión `*.skull` | Archivos renombrados tras el cifrado | Alertas SIEM de rename, EDR |
| `README.txt` en directorios de usuario | Nota de rescate depositada | Monitoreo de integridad de archivos |
| `/tmp/skull_locker.lock` | Archivo de bloqueo PID de instancia única | Auditd, SIEM |
| Encabezado `---key---...:...---endkey---\n` en byte 0 | Marcador de archivo cifrado | YARA, escaneo de archivos |
### 二进制 / 代码 IoCs
| Indicador | Valor |
|-----------|-------|
| Clave pública del atacante (hex) | `94f35828bbaac2bb35465ec5c09bd42ccade70906e64b6856bad9bc6af72db41` |
| Nombre del paquete Rust | `skull_locker_linux` |
| Ruta del archivo de bloqueo | `/tmp/skull_locker.lock` |
### 勒索信签名
```
--= Your files have been encrypted by Skull Locker =--
military-grade encryption
TOX messenger
https://tox.chat/download.html
within 72 hours
the decryption price will double
```
## 检测策略
### YARA 规则
```
rule SkullLocker_Archivo_Cifrado {
meta:
description = "Detecta archivos cifrados por el ransomware Skull Locker"
nivel_amenaza = 10
strings:
$encabezado = "---key---"
$pie = "---endkey---"
$clave_pub = "94f35828bbaac2bb35465ec5c09bd42ccade70906e64b6856bad9bc6af72db41"
condition:
$encabezado at 0 and $pie and $clave_pub
}
rule SkullLocker_Nota_Rescate {
meta:
description = "Detecta nota de rescate de Skull Locker"
strings:
$s1 = "Your files have been encrypted by Skull Locker"
$s2 = "tox.chat"
$s3 = "within 72 hours"
condition:
2 of them
}
```
### Auditd 规则
```
# 检测批量重命名为 .skull 扩展名
-a always,exit -F arch=b64 -S rename -S renameat -k skull_locker_rename
# 检测锁文件创建
-a always,exit -F arch=b64 -S open -F path=/tmp/skull_locker.lock -k skull_locker_lock
```
### inotify 蜜罐 (早期预警)
```
# 放置诱饵文件并在重命名为 .skull 时发出警报
touch ~/Documents/HONEYPOT_datos_financieros_2024.pdf
inotifywait -m ~/Documents -e rename --format '%f' | \
while read archivo; do
if echo "$archivo" | grep -q "\.skull$"; then
logger -p auth.crit "RANSOMWARE DETECTADO: $archivo renombrado a .skull"
fi
done
```
## 防御与缓解
### 预防控制
| Control | Implementación | Efectividad |
|---------|---------------|-------------|
| **Copias de seguridad inmutables offline** | Regla 3-2-1: 3 copias, 2 medios, 1 offline/air-gapped | ★★★★★ Mejor mitigación |
| **Snapshots del sistema de archivos** | LVM snapshots, subvolúmenes Btrfs, snapshots ZFS | ★★★★☆ |
| **Inmutabilidad de archivos** | `chattr +i /home/usuario/archivos_criticos/` | ★★★☆☆ |
| **Montajes noexec** | `/home` y `/tmp` con `noexec` | ★★★☆☆ |
| **AppArmor / SELinux** | Restringir acceso a archivos por proceso | ★★★★☆ |
| **Archivos trampa (honeypot)** | Alerta en primer rename a `.skull` | ★★★★☆ Advertencia temprana |
| **EDR con monitoreo de syscalls** | Detectar operaciones masivas de rename | ★★★★☆ |
### 事件响应 (如果被感染)
```
ACCIONES INMEDIATAS:
├── 1. AISLAR: Desconectar de todas las redes inmediatamente
├── 2. PRESERVAR: Volcado de memoria + imagen de disco ANTES de cualquier cambio
├── 3. NO REINICIAR: Puede haber evidencia volátil (claves en memoria)
├── 4. INVENTARIAR: find / -name "*.skull" 2>/dev/null | wc -l
├── 5. VERIFICAR BLOQUEO: cat /tmp/skull_locker.lock → el PID puede revelar detalles
├── 6. RESTAURAR: Desde backup offline conocido y limpio
└── 7. REPORTAR: Unidad nacional de cibercrimen de tu país
```
## 安全分析环境设置
### 检查清单
- [ ] Crear VM nueva (VMware/VirtualBox/QEMU) — sin datos reales
- [ ] **Desconectar TODAS las interfaces de red** antes de cargar la muestra
- [ ] Deshabilitar carpetas compartidas y portapapeles con el anfitrión
- [ ] Tomar snapshot → `Estado_Limpio_Antes_Muestra`
- [ ] Copiar muestra a la VM
- [ ] Realizar análisis
- [ ] Revertir a `Estado_Limpio_Antes_Muestra` al terminar
- [ ] **Nunca** exportar la muestra a la máquina anfitriona
### 静态分析 (无执行 — 完全安全)
```
# strings 提取 — 揭示 IoCs、路径、消息
strings skull_locker_linux | grep -iE "(skull|key|readme|tox|lock|encrypt)"
# 符号表
nm skull_locker_linux 2>/dev/null
# 用于威胁情报查询的哈希
sha256sum skull_locker_linux
md5sum skull_locker_linux
# 二进制类型
file skull_locker_linux
```
## 源代码结构
| Archivo | Propósito para el Investigador |
|---------|-------------------------------|
| `src/main.rs` | Punto de entrada, argumentos CLI, orquestación |
| `src/crypto.rs` | **El más importante**: implementación completa de ChaCha20 + X25519 |
| `src/disk.rs` | Lógica de targeting, listas negras, recorrido de directorios |
| `src/utils.rs` | Gestión de archivo de bloqueo flock(), despliegue de nota de rescate |
| `Cargo.toml` | Dependencias criptográficas (análisis de surface de ataque) |
### 关键依赖项
```
chacha20poly1305 = "0.10" # Cifrador simétrico AEAD — punto central del cifrado
x25519-dalek = "2.0" # ECDH asimétrico — razón por la que no es recuperable
rand = "0.8" # RNG criptográfico — genera claves únicas por archivo
nix = "0.27" # flock() y syscalls Unix — mecanismo de instancia única
walkdir = "2.4" # Recorrido recursivo — alcance del ataque
```
## 行为分析
### 进程行为签名
| Comportamiento | Syscall | Efecto Observable | Método de Detección |
|----------------|---------|-------------------|---------------------|
| Adquisición de bloqueo | `flock(LOCK_EX\|LOCK_NB)` | PID escrito en `/tmp/skull_locker.lock` | auditd, inotify |
| Descubrimiento | `opendir()`/`readdir()` en `/home`, `/media` | Ráfaga de listado de directorios | strace, eBPF |
| Nota de rescate | `creat()` + `write()` en `README.txt` | Nuevo archivo en cada directorio | inotify, EDR |
| Cifrado | `open()` + `read()` + `write()` + `rename()` | Archivos → `.skull` | SIEM, EDR, YARA |
| E/S en bloques | `read(1048576)` secuencial + `write()` | Perfil de E/S característico | eBPF trace |
### 预估加密速度
| Tipo de Almacenamiento | Rendimiento | 10 GB cifrados en... |
|------------------------|-------------|----------------------|
| NVMe SSD | ~1000 MB/s | ~10 segundos |
| SATA SSD | ~500 MB/s | ~20 segundos |
| HDD | ~100 MB/s | ~100 segundos |
## 研究参考
| Recurso | Referencia |
|---------|-----------|
| Especificación ChaCha20-Poly1305 | [RFC 8439](https://datatracker.ietf.org/doc/html/rfc8439) |
| Intercambio de claves X25519 | [RFC 7748](https://datatracker.ietf.org/doc/html/rfc7748) |
| Guía de Ransomware CISA | [cisa.gov/ransomware](https://www.cisa.gov/ransomware) |
| Análisis de Malware Práctico | *Practical Malware Analysis* — Sikorski & Honig |
| Documentación YARA | [yara.readthedocs.io](https://yara.readthedocs.io) |
| Falco Runtime Security | [falco.org](https://falco.org) |
| eBPF Security | [ebpf.io](https://ebpf.io) |
| Reporte nacional (EE.UU.) | [ic3.gov](https://www.ic3.gov) |
| Reporte nacional (UK) | [actionfraud.police.uk](https://www.actionfraud.police.uk) |
## 许可证 / License
See [LICENSE](LICENSE) for details. / Ver [LICENSE](LICENSE) para más detalles.
## ⚠️ 严重警告 — AVISO CRÍTICO ⚠️
### 🚨 这是真实的勒索软件源代码 — 仅供研究使用 🚨
### 🚨 这是真实的 Ransomware 代码 — 仅供研究使用 🚨
## 🌐 语言 / Language
- [English — Malware Analysis & Research Guide](#english--malware-analysis--research-guide)
- [Español — Guía de Análisis de Malware e Investigación](#español--guía-de-análisis-de-malware-e-investigación)
# English — 恶意软件分析与研究指南
## 目录
1. [Sample Classification](#sample-classification)
2. [Technical Overview](#technical-overview)
3. [Cryptographic Implementation Analysis](#cryptographic-implementation-analysis)
4. [File System Targeting Logic](#file-system-targeting-logic)
5. [Indicators of Compromise (IoCs)](#indicators-of-compromise-iocs)
6. [Detection Strategies](#detection-strategies)
7. [Defense & Mitigation](#defense--mitigation)
8. [Safe Analysis Environment Setup](#safe-analysis-environment-setup)
9. [Source Code Structure](#source-code-structure)
10. [Behavioral Analysis](#behavioral-analysis)
11. [Research References](#research-references)
## 样本分类
| Property | Value |
|----------|-------|
| **Name** | Skull Locker |
| **Type** | Ransomware — File Encryption |
| **Target OS** | Linux (x86_64) |
| **Language** | Rust (Edition 2021) |
| **Binary** | `skull_locker_linux` (ELF 64-bit) |
| **Encryption** | ChaCha20-Poly1305 (AEAD) |
| **Key Exchange** | X25519 Elliptic Curve Diffie-Hellman |
| **File Extension** | `.skull` appended to encrypted files |
| **Ransom Note** | `README.txt` dropped in targeted directories |
| **C2 Channel** | TOX messenger (decentralized P2P) |
| **Threat Level** | Critical — irreversible file encryption without attacker private key |
## 技术概览
Skull Locker is a **crypto-ransomware** sample targeting Linux desktop and server environments. It implements a hybrid encryption scheme combining asymmetric key exchange (X25519) with a symmetric authenticated cipher (ChaCha20-Poly1305) to ensure that file recovery is mathematically impossible without the attacker's private key.
### 攻击流程(用于防御性理解)
```
Execution
│
▼
Single-instance check ──── Already running? → Exit
│ (uses /tmp/skull_locker.lock via flock())
▼
Target Discovery
│ - User home subdirectories (Documents, Downloads, Pictures, etc.)
│ - All /home/* directories (multi-user systems)
│ - External media: /media/*, /mnt/*
▼
Per-directory:
├── Drop ransom note (README.txt)
└── Recursive file walk (max depth 5)
├── Skip: blacklisted dirs, file types, files > 10GB
└── For each valid file:
├── Generate per-file random 32-byte key (OsRng)
├── ECDH key exchange with hardcoded attacker public key
├── Encrypt file key with ChaCha20-Poly1305
├── Encrypt file contents in 1MB chunks
├── Prepend metadata header to encrypted file
└── Rename original to 标签:AEAD加密, ChaCha20-Poly1305, Cloudflare, DNS 反向解析, DNS 解析, EDR检测, HTTP工具, IoC指标, Linux勒索软件, MITRE ATT&CK, Rust恶意软件, 中高交互蜜罐, 可视化界面, 威胁情报, 子域名变形, 开发者工具, 恶意代码分析, 恶意软件开发, 数据加密, 文件加密, 样本分析, 流密码加密, 白盒测试, 网络安全, 网络安全审计, 计算机病毒, 通知系统, 配置文件, 隐私保护, 黑盒测试