ctf-agent 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (152) hide show
  1. package/AGENTS.md +131 -0
  2. package/Dockerfile +192 -0
  3. package/README.md +522 -0
  4. package/agents/ctf-analyzer.md +58 -0
  5. package/agents/ctf-controller.md +151 -0
  6. package/agents/ctf-speedrun.md +74 -0
  7. package/bin/ctf-agent.js +119 -0
  8. package/docker-compose.yml +13 -0
  9. package/mcp_config.json +19 -0
  10. package/package.json +44 -0
  11. package/references/ctf-triage-ladder.md +68 -0
  12. package/references/exploit-databases.md +575 -0
  13. package/references/llm-safety-and-policy-compliance.md +173 -0
  14. package/references/multi-agent-orchestration-and-policy-routing.md +278 -0
  15. package/references/security-events-and-intelligence.md +566 -0
  16. package/references/version-matrix.md +59 -0
  17. package/rules/ctf-execution-rules.md +44 -0
  18. package/rules/ctf-safety-framing-rules.md +140 -0
  19. package/rules/flag-validation-rules.md +25 -0
  20. package/scripts/__init__.py +1 -0
  21. package/scripts/ctf-tools.lock +205 -0
  22. package/scripts/ctf_init.py +1026 -0
  23. package/scripts/ctf_update.py +583 -0
  24. package/scripts/ctfd_client.py +81 -0
  25. package/scripts/cve_lookup.py +453 -0
  26. package/scripts/extract_flags.py +155 -0
  27. package/scripts/install_as_agent.py +278 -0
  28. package/scripts/install_ctf_tools.sh +603 -0
  29. package/scripts/parallel_triage.py +395 -0
  30. package/scripts/prompt_policy_sanitizer.py +283 -0
  31. package/scripts/scope_guard.py +444 -0
  32. package/scripts/skill_validator.py +504 -0
  33. package/scripts/workspace_cleaner.py +141 -0
  34. package/skills/ctf-ai-ml/SKILL.md +120 -0
  35. package/skills/ctf-ai-ml/adversarial-ml.md +623 -0
  36. package/skills/ctf-ai-ml/llm-attacks.md +487 -0
  37. package/skills/ctf-ai-ml/model-attacks.md +422 -0
  38. package/skills/ctf-crypto/SKILL.md +320 -0
  39. package/skills/ctf-crypto/advanced-math.md +798 -0
  40. package/skills/ctf-crypto/classic-ciphers.md +651 -0
  41. package/skills/ctf-crypto/ecc-attacks.md +347 -0
  42. package/skills/ctf-crypto/exotic-crypto-2.md +380 -0
  43. package/skills/ctf-crypto/exotic-crypto.md +528 -0
  44. package/skills/ctf-crypto/historical.md +113 -0
  45. package/skills/ctf-crypto/lattice-and-lwe.md +524 -0
  46. package/skills/ctf-crypto/modern-ciphers-2.md +563 -0
  47. package/skills/ctf-crypto/modern-ciphers-3.md +453 -0
  48. package/skills/ctf-crypto/modern-ciphers.md +649 -0
  49. package/skills/ctf-crypto/prng-attacks.md +257 -0
  50. package/skills/ctf-crypto/prng.md +664 -0
  51. package/skills/ctf-crypto/rsa-attacks-2.md +792 -0
  52. package/skills/ctf-crypto/rsa-attacks.md +487 -0
  53. package/skills/ctf-crypto/stream-ciphers.md +390 -0
  54. package/skills/ctf-crypto/zkp-and-advanced.md +456 -0
  55. package/skills/ctf-forensics/3d-printing.md +121 -0
  56. package/skills/ctf-forensics/SKILL.md +379 -0
  57. package/skills/ctf-forensics/disk-advanced.md +497 -0
  58. package/skills/ctf-forensics/disk-and-memory.md +491 -0
  59. package/skills/ctf-forensics/disk-recovery.md +699 -0
  60. package/skills/ctf-forensics/linux-forensics.md +511 -0
  61. package/skills/ctf-forensics/network-advanced.md +583 -0
  62. package/skills/ctf-forensics/network.md +645 -0
  63. package/skills/ctf-forensics/peripheral-capture.md +287 -0
  64. package/skills/ctf-forensics/signals-and-hardware.md +713 -0
  65. package/skills/ctf-forensics/steganography.md +694 -0
  66. package/skills/ctf-forensics/stego-advanced-2.md +475 -0
  67. package/skills/ctf-forensics/stego-advanced.md +481 -0
  68. package/skills/ctf-forensics/stego-image.md +691 -0
  69. package/skills/ctf-forensics/windows.md +625 -0
  70. package/skills/ctf-malware/SKILL.md +181 -0
  71. package/skills/ctf-malware/c2-and-protocols.md +274 -0
  72. package/skills/ctf-malware/pe-and-dotnet.md +108 -0
  73. package/skills/ctf-malware/scripts-and-obfuscation.md +449 -0
  74. package/skills/ctf-misc/SKILL.md +498 -0
  75. package/skills/ctf-misc/bashjails.md +323 -0
  76. package/skills/ctf-misc/ctfd-navigation.md +465 -0
  77. package/skills/ctf-misc/dns.md +255 -0
  78. package/skills/ctf-misc/encodings-advanced.md +504 -0
  79. package/skills/ctf-misc/encodings.md +431 -0
  80. package/skills/ctf-misc/games-and-vms-2.md +254 -0
  81. package/skills/ctf-misc/games-and-vms-3.md +690 -0
  82. package/skills/ctf-misc/games-and-vms-4.md +229 -0
  83. package/skills/ctf-misc/games-and-vms.md +529 -0
  84. package/skills/ctf-misc/linux-privesc.md +333 -0
  85. package/skills/ctf-misc/pyjails.md +671 -0
  86. package/skills/ctf-misc/rf-sdr.md +91 -0
  87. package/skills/ctf-osint/SKILL.md +198 -0
  88. package/skills/ctf-osint/geolocation-and-media.md +464 -0
  89. package/skills/ctf-osint/social-media.md +312 -0
  90. package/skills/ctf-osint/web-and-dns.md +341 -0
  91. package/skills/ctf-pwn/SKILL.md +214 -0
  92. package/skills/ctf-pwn/advanced-exploits-2.md +579 -0
  93. package/skills/ctf-pwn/advanced-exploits-3.md +598 -0
  94. package/skills/ctf-pwn/advanced-exploits-4.md +590 -0
  95. package/skills/ctf-pwn/advanced-exploits-5.md +119 -0
  96. package/skills/ctf-pwn/advanced-exploits.md +773 -0
  97. package/skills/ctf-pwn/advanced.md +326 -0
  98. package/skills/ctf-pwn/field-notes.md +245 -0
  99. package/skills/ctf-pwn/format-string.md +694 -0
  100. package/skills/ctf-pwn/heap-fsop.md +285 -0
  101. package/skills/ctf-pwn/heap-techniques-2.md +333 -0
  102. package/skills/ctf-pwn/heap-techniques.md +513 -0
  103. package/skills/ctf-pwn/kernel-bypass.md +421 -0
  104. package/skills/ctf-pwn/kernel-techniques.md +366 -0
  105. package/skills/ctf-pwn/kernel.md +636 -0
  106. package/skills/ctf-pwn/overflow-basics.md +611 -0
  107. package/skills/ctf-pwn/rop-advanced.md +725 -0
  108. package/skills/ctf-pwn/rop-and-shellcode.md +659 -0
  109. package/skills/ctf-pwn/sandbox-escape.md +313 -0
  110. package/skills/ctf-reverse/SKILL.md +163 -0
  111. package/skills/ctf-reverse/anti-analysis-ctf.md +204 -0
  112. package/skills/ctf-reverse/anti-analysis.md +693 -0
  113. package/skills/ctf-reverse/field-notes.md +376 -0
  114. package/skills/ctf-reverse/languages-compiled.md +666 -0
  115. package/skills/ctf-reverse/languages-platforms.md +592 -0
  116. package/skills/ctf-reverse/languages.md +553 -0
  117. package/skills/ctf-reverse/patterns-ctf-2.md +397 -0
  118. package/skills/ctf-reverse/patterns-ctf-3.md +797 -0
  119. package/skills/ctf-reverse/patterns-ctf.md +670 -0
  120. package/skills/ctf-reverse/patterns-runtime.md +274 -0
  121. package/skills/ctf-reverse/patterns.md +572 -0
  122. package/skills/ctf-reverse/platforms-hardware.md +387 -0
  123. package/skills/ctf-reverse/platforms.md +664 -0
  124. package/skills/ctf-reverse/tools-advanced-2.md +421 -0
  125. package/skills/ctf-reverse/tools-advanced.md +407 -0
  126. package/skills/ctf-reverse/tools-dynamic.md +679 -0
  127. package/skills/ctf-reverse/tools-emulation.md +319 -0
  128. package/skills/ctf-reverse/tools.md +573 -0
  129. package/skills/ctf-web/SKILL.md +153 -0
  130. package/skills/ctf-web/auth-and-access-2.md +82 -0
  131. package/skills/ctf-web/auth-and-access.md +783 -0
  132. package/skills/ctf-web/auth-infra.md +321 -0
  133. package/skills/ctf-web/auth-jwt.md +186 -0
  134. package/skills/ctf-web/client-side-advanced.md +739 -0
  135. package/skills/ctf-web/client-side.md +529 -0
  136. package/skills/ctf-web/cves.md +373 -0
  137. package/skills/ctf-web/field-notes.md +482 -0
  138. package/skills/ctf-web/node-and-prototype.md +200 -0
  139. package/skills/ctf-web/server-side-2.md +337 -0
  140. package/skills/ctf-web/server-side-advanced-2.md +559 -0
  141. package/skills/ctf-web/server-side-advanced-3.md +125 -0
  142. package/skills/ctf-web/server-side-advanced-4.md +480 -0
  143. package/skills/ctf-web/server-side-advanced.md +378 -0
  144. package/skills/ctf-web/server-side-deser.md +443 -0
  145. package/skills/ctf-web/server-side-exec-2.md +799 -0
  146. package/skills/ctf-web/server-side-exec.md +457 -0
  147. package/skills/ctf-web/server-side.md +629 -0
  148. package/skills/ctf-web/sql-injection.md +790 -0
  149. package/skills/ctf-web/web3.md +374 -0
  150. package/skills/ctf-writeup/SKILL.md +90 -0
  151. package/skills/solve-challenge/SKILL.md +269 -0
  152. package/skills.json +16 -0
@@ -0,0 +1,449 @@
1
+ # Scripts and Obfuscation Analysis
2
+
3
+ ## Table of Contents
4
+
5
+ - [Obfuscated Scripts (General)](#obfuscated-scripts-general)
6
+ - [JavaScript Deobfuscation](#javascript-deobfuscation)
7
+ - [PowerShell Analysis](#powershell-analysis)
8
+ - [Junk Code Detection](#junk-code-detection)
9
+ - [Hex-Encoded Payloads](#hex-encoded-payloads)
10
+ - [Debian Package Analysis](#debian-package-analysis)
11
+ - [Dynamic Analysis Techniques](#dynamic-analysis-techniques)
12
+ - [YARA Rules for Malware Detection](#yara-rules-for-malware-detection)
13
+ - [Shellcode Analysis](#shellcode-analysis)
14
+ - [Memory Forensics for Malware](#memory-forensics-for-malware)
15
+ - [Anti-Analysis Techniques](#anti-analysis-techniques)
16
+ - [VM / Sandbox Detection](#vm--sandbox-detection)
17
+ - [Timing-Based Evasion](#timing-based-evasion)
18
+ - [API Hashing](#api-hashing)
19
+ - [Process Injection Techniques](#process-injection-techniques)
20
+ - [Environment Variable / Hostname Checks](#environment-variable--hostname-checks)
21
+
22
+ ---
23
+
24
+ ## Obfuscated Scripts (General)
25
+
26
+ - Replace `eval`/`bash` with `echo` to print underlying code
27
+ - Extract base64/hex blobs and analyze with `file`
28
+ - Common deobfuscation chain: base64 decode -> gzip decode -> reverse -> base64 decode
29
+
30
+ ## JavaScript Deobfuscation
31
+
32
+ ```javascript
33
+ // Replace eval with console.log
34
+ eval = console.log;
35
+ // Then run the obfuscated code
36
+
37
+ // Common patterns
38
+ unescape() // URL decoding
39
+ String.fromCharCode() // Char codes
40
+ atob() // Base64
41
+ ```
42
+
43
+ ## PowerShell Analysis
44
+
45
+ ```powershell
46
+ # Common obfuscation
47
+ -enc / -EncodedCommand # Base64 encoded
48
+ IEX / Invoke-Expression # Eval equivalent
49
+ [System.Text.Encoding]::Unicode.GetString([System.Convert]::FromBase64String($encoded))
50
+ ```
51
+
52
+ ## Junk Code Detection
53
+
54
+ **Pattern:** Obfuscation adds meaningless instructions around real code
55
+
56
+ **Identification:**
57
+ - NOP sleds, push/pop pairs that cancel
58
+ - Arithmetic that results in zero/identity
59
+ - Dead writes (register written but never read before next write)
60
+ - Unconditional jumps to next instruction
61
+
62
+ **Filtering technique:**
63
+ ```python
64
+ # Identify real calls by looking for patterns
65
+ # junk, junk, junk, CALL target, junk, junk
66
+ # Extract call targets, ignore surrounding noise
67
+
68
+ def extract_real_calls(disassembly):
69
+ calls = []
70
+ for instr in disassembly:
71
+ if instr.mnemonic == 'call' and not is_junk_target(instr.operand):
72
+ calls.append(instr)
73
+ return calls
74
+ ```
75
+
76
+ ## Hex-Encoded Payloads
77
+
78
+ - Convert hex to bytes, try common transformations: subtract 1, XOR with key
79
+
80
+ ## Debian Package Analysis
81
+
82
+ ```bash
83
+ ar -x package.deb # Unpack debian package
84
+ tar -xf control.tar.xz # Check control files
85
+ # Look for postinst scripts that execute payloads
86
+ ```
87
+
88
+ ---
89
+
90
+ ## Dynamic Analysis Techniques
91
+
92
+ ```bash
93
+ # Behavioral monitoring with strace/ltrace
94
+ strace -f -e trace=network,file -o trace.log ./malware
95
+ ltrace -f -o ltrace.log ./malware
96
+
97
+ # Network monitoring during execution
98
+ # Terminal 1: capture traffic
99
+ sudo tcpdump -i any -w malware_traffic.pcap &
100
+ # Terminal 2: DNS monitoring
101
+ sudo tcpdump -i any port 53 -l | tee dns_queries.log &
102
+ # Terminal 3: run sample
103
+ timeout 60 ./malware
104
+
105
+ # File system monitoring (Linux)
106
+ inotifywait -m -r /tmp /var/tmp --format '%T %w%f %e' --timefmt '%H:%M:%S' &
107
+ ./malware
108
+
109
+ # Process monitoring
110
+ watch -n 1 'ps aux | grep -v grep | grep malware'
111
+
112
+ # Memory string extraction during runtime
113
+ # Run malware, then dump strings from its memory
114
+ pid=$(pgrep malware)
115
+ strings /proc/$pid/maps
116
+ cat /proc/$pid/mem 2>/dev/null | strings | grep -i flag
117
+ # Or use gdb: gdb -p $pid -batch -ex 'dump memory dump.bin 0x400000 0x500000'
118
+ ```
119
+
120
+ ```python
121
+ # Automated sandbox execution with timeout
122
+ import subprocess, os, tempfile
123
+
124
+ def run_sample(path, timeout=30):
125
+ """Run malware sample with monitoring"""
126
+ with tempfile.NamedTemporaryFile(suffix='.pcap', delete=False) as pcap:
127
+ # Start packet capture
128
+ tcpdump = subprocess.Popen(
129
+ ['sudo', 'tcpdump', '-i', 'any', '-w', pcap.name],
130
+ stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
131
+
132
+ try:
133
+ # Run with strace
134
+ result = subprocess.run(
135
+ ['strace', '-f', '-e', 'trace=network,file', path],
136
+ capture_output=True, text=True, timeout=timeout)
137
+ print("STDOUT:", result.stdout[:500])
138
+ print("STDERR (syscalls):", result.stderr[:2000])
139
+ except subprocess.TimeoutExpired:
140
+ print(f"Sample ran for {timeout}s (killed)")
141
+ finally:
142
+ tcpdump.terminate()
143
+ print(f"PCAP saved: {pcap.name}")
144
+ ```
145
+
146
+ **Key insight:** Dynamic analysis reveals runtime behavior that static analysis misses: actual C2 domains resolved, encryption keys in memory, dropped files, and anti-analysis checks that were bypassed. Always run in an isolated environment (VM snapshot, Docker container) and monitor network, filesystem, and process activity simultaneously.
147
+
148
+ ---
149
+
150
+ ### YARA Rules for Malware Detection
151
+
152
+ ```bash
153
+ # Basic YARA rule structure
154
+ cat > detect_malware.yar << 'EOF'
155
+ rule SuspiciousStrings {
156
+ meta:
157
+ description = "Detect common malware indicators"
158
+ strings:
159
+ $s1 = "cmd.exe /c" nocase
160
+ $s2 = "powershell -enc" nocase
161
+ $s3 = {4D 5A 90 00} // MZ header (hex pattern)
162
+ $s4 = /https?:\/\/[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}/ // IP-based URL
163
+ $xor_loop = {31 ?? 80 ?? ?? 4? 75} // XOR decode loop pattern
164
+ condition:
165
+ 2 of ($s*) or $xor_loop
166
+ }
167
+ EOF
168
+
169
+ # Scan files
170
+ yara detect_malware.yar suspicious_file.exe
171
+ yara -r detect_malware.yar /path/to/directory/ # Recursive scan
172
+
173
+ # Scan memory dump
174
+ yara detect_malware.yar memory.dmp
175
+ ```
176
+
177
+ **Common YARA patterns for CTFs:**
178
+ ```yara
179
+ rule Base64_PowerShell {
180
+ strings:
181
+ $enc = "powershell" nocase
182
+ $b64 = /[A-Za-z0-9+\/]{50,}={0,2}/
183
+ condition:
184
+ $enc and $b64
185
+ }
186
+
187
+ rule XOR_Encrypted_PE {
188
+ strings:
189
+ $mz = {4D 5A}
190
+ condition:
191
+ not $mz at 0 and filesize < 1MB
192
+ // PE without MZ header = likely XOR encrypted
193
+ }
194
+ ```
195
+
196
+ **Key insight:** YARA rules match byte patterns, strings, and regex against files or memory. In CTFs, write rules to detect specific obfuscation patterns (XOR loops, base64 blobs, encoded PowerShell), then apply to memory dumps or malware samples. Use `yarac` to compile rules for faster scanning.
197
+
198
+ ---
199
+
200
+ ### Shellcode Analysis
201
+
202
+ ```bash
203
+ # Extract shellcode from binary
204
+ objdump -d shellcode.bin -b binary -m i386:x86-64 -M intel
205
+
206
+ # Emulate shellcode with unicorn engine
207
+ python3 << 'PYEOF'
208
+ from unicorn import *
209
+ from unicorn.x86_const import *
210
+
211
+ shellcode = open('shellcode.bin', 'rb').read()
212
+ mu = Uc(UC_ARCH_X86, UC_MODE_64)
213
+ BASE = 0x400000
214
+ STACK = 0x7fff0000
215
+
216
+ mu.mem_map(BASE, 0x1000)
217
+ mu.mem_map(STACK - 0x1000, 0x2000)
218
+ mu.mem_write(BASE, shellcode)
219
+ mu.reg_write(UC_X86_REG_RSP, STACK)
220
+
221
+ # Hook syscalls to trace behavior
222
+ def hook_syscall(mu, user_data):
223
+ rax = mu.reg_read(UC_X86_REG_RAX)
224
+ print(f"syscall: {rax}")
225
+
226
+ mu.hook_add(UC_HOOK_INSN, hook_syscall, None, 1, 0, UC_X86_INS_SYSCALL)
227
+ mu.emu_start(BASE, BASE + len(shellcode))
228
+ PYEOF
229
+
230
+ # Disassemble with capstone
231
+ python3 -c "
232
+ from capstone import *
233
+ md = Cs(CS_ARCH_X86, CS_MODE_64)
234
+ code = open('shellcode.bin','rb').read()
235
+ for i in md.disasm(code, 0x0):
236
+ print(f'{i.address:#x}: {i.mnemonic} {i.op_str}')
237
+ "
238
+
239
+ # Quick analysis with scdbg (Windows shellcode emulator)
240
+ scdbg /f shellcode.bin
241
+ ```
242
+
243
+ **Key insight:** Shellcode in CTF malware challenges is often XOR-encoded or staged. Look for decoder stubs (short loops with XOR), then extract and decode the payload. Unicorn Engine emulation is safer than running shellcode — it intercepts syscalls without executing them.
244
+
245
+ ---
246
+
247
+ ### Memory Forensics for Malware
248
+
249
+ ```bash
250
+ # Volatility 3 — analyze memory dump for malware indicators
251
+ # List processes (look for suspicious names, unusual parents)
252
+ vol3 -f memory.dmp windows.pslist
253
+ vol3 -f memory.dmp windows.pstree
254
+
255
+ # Detect hidden/unlinked processes
256
+ vol3 -f memory.dmp windows.psscan
257
+
258
+ # Dump suspicious process memory
259
+ vol3 -f memory.dmp windows.memmap --pid PID --dump
260
+
261
+ # Extract injected code (process hollowing, DLL injection)
262
+ vol3 -f memory.dmp windows.malfind
263
+
264
+ # Network connections from malware
265
+ vol3 -f memory.dmp windows.netscan
266
+
267
+ # Command-line arguments (reveals malware parameters)
268
+ vol3 -f memory.dmp windows.cmdline
269
+
270
+ # DLL list per process (detect injected DLLs)
271
+ vol3 -f memory.dmp windows.dlllist --pid PID
272
+
273
+ # YARA scan on memory dump
274
+ vol3 -f memory.dmp yarascan.YaraScan --yara-rules "rule test { strings: $s = \"flag{\" condition: $s }"
275
+ ```
276
+
277
+ **Key insight:** `windows.malfind` detects injected code by finding memory regions with `PAGE_EXECUTE_READWRITE` protection and no corresponding mapped file — the hallmark of process injection. Combine with `windows.pstree` to find processes with unexpected parent-child relationships (e.g., `svchost.exe` spawned by `cmd.exe`).
278
+
279
+ ---
280
+
281
+ ## Anti-Analysis Techniques
282
+
283
+ Malware uses runtime checks to detect analysis environments and alter behavior. Bypass these to reach the actual malicious functionality. For comprehensive anti-debug, anti-VM/sandbox, and anti-DBI bypass strategies, see [ctf-reverse/anti-analysis.md](../ctf-reverse/anti-analysis.md).
284
+
285
+ ### VM / Sandbox Detection
286
+
287
+ **Pattern:** Malware checks for virtualization artifacts before executing payload. In CTFs, the "real" flag logic is behind these checks.
288
+
289
+ **Key insight:** Identify the detection method, then patch the check or fake the environment.
290
+
291
+ ```python
292
+ # Common VM detection checks and bypasses:
293
+
294
+ # 1. CPUID check (hypervisor bit 31 of ECX after CPUID leaf 1)
295
+ # Bypass: patch JNZ after CPUID to JMP, or run in bare metal
296
+ # In GDB: set $ecx = $ecx & ~(1<<31)
297
+
298
+ # 2. MAC address prefix (VMware: 00:0C:29, 00:50:56; VBox: 08:00:27)
299
+ # Bypass: change VM NIC MAC to real hardware prefix
300
+
301
+ # 3. Registry keys (Windows)
302
+ # HKLM\SOFTWARE\VMware, Inc.\VMware Tools
303
+ # HKLM\SYSTEM\CurrentControlSet\Services\VBoxGuest
304
+ # Bypass: delete keys or patch registry check
305
+
306
+ # 4. File/process checks
307
+ VM_ARTIFACTS = [
308
+ 'vmtoolsd.exe', 'vmwaretray.exe', 'VBoxService.exe',
309
+ 'qemu-ga.exe', 'sandboxie', 'wireshark.exe',
310
+ '/sys/class/dmi/id/product_name', # "VMware Virtual Platform"
311
+ 'C:\\windows\\system32\\drivers\\vmmouse.sys',
312
+ ]
313
+
314
+ # 5. Disk size check (VMs often have small disks)
315
+ # if total_disk < 60GB: exit()
316
+ # Bypass: expand VM disk or patch comparison
317
+
318
+ # 6. CPU count / RAM check
319
+ # if cpu_count < 2 or ram < 2GB: exit()
320
+ # Bypass: allocate more resources to VM
321
+ ```
322
+
323
+ ### Timing-Based Evasion
324
+
325
+ **Pattern:** Malware uses `sleep()`, `GetTickCount()`, or RDTSC to detect accelerated execution in sandboxes.
326
+
327
+ ```python
328
+ # Detection: large sleep followed by time check
329
+ # import time
330
+ # start = time.time()
331
+ # time.sleep(300) # 5 minutes
332
+ # if time.time() - start < 290: sys.exit() # Sandbox fast-forwarded sleep
333
+
334
+ # Bypass approaches:
335
+ # 1. Patch sleep to NOP: elf.asm(elf.symbols['sleep'], 'ret')
336
+ # 2. Hook GetTickCount/time() to return expected values
337
+ # 3. In GDB: set breakpoint after sleep, manually advance
338
+ # 4. Binary patching: change sleep(300) to sleep(0)
339
+ ```
340
+
341
+ **Key insight:** Look for calls to `sleep`, `time.sleep`, `NtDelayExecution`, `GetTickCount64`, `QueryPerformanceCounter`. If the sample just sits there doing nothing, it's likely in a sleep-based anti-sandbox check.
342
+
343
+ ### API Hashing
344
+
345
+ **Pattern:** Instead of importing functions by name (visible in strings/imports), malware resolves API addresses at runtime by hashing function names and comparing to hardcoded hash values.
346
+
347
+ ```python
348
+ # Common hash algorithms for API resolution:
349
+ # ROR13 (rotate-right 13) — most common, used by Metasploit
350
+ def ror13_hash(name):
351
+ h = 0
352
+ for c in name:
353
+ h = ((h >> 13) | (h << 19)) & 0xFFFFFFFF
354
+ h = (h + ord(c)) & 0xFFFFFFFF
355
+ return h
356
+
357
+ # DJB2 hash
358
+ def djb2_hash(name):
359
+ h = 5381
360
+ for c in name:
361
+ h = ((h * 33) + ord(c)) & 0xFFFFFFFF
362
+ return h
363
+
364
+ # CRC32-based
365
+ import binascii
366
+ def crc32_hash(name):
367
+ return binascii.crc32(name.encode()) & 0xFFFFFFFF
368
+
369
+ # Reversing: build lookup table from Windows API names
370
+ # hashdb.openanalysis.net — online API hash lookup
371
+ # ShellcodeHasher — matches hashes against known Windows APIs
372
+
373
+ # In Ghidra: find the hash comparison constant, look up in hashdb
374
+ # Pattern: loop over PEB→Ldr→InMemoryOrderModuleList, hash each export name
375
+ ```
376
+
377
+ **Key insight:** When strings output shows almost no readable API names but the binary clearly does complex operations, suspect API hashing. Look for the hash function (small loop with XOR/rotate/add), then use hashdb or build a rainbow table against `kernel32.dll` and `ntdll.dll` exports.
378
+
379
+ ### Process Injection Techniques
380
+
381
+ **Pattern:** Malware injects code into legitimate processes to evade detection. Understanding the injection method helps extract the actual payload.
382
+
383
+ ```bash
384
+ # Classic injection chain:
385
+ # 1. OpenProcess(target_pid)
386
+ # 2. VirtualAllocEx(remote, ..., PAGE_EXECUTE_READWRITE)
387
+ # 3. WriteProcessMemory(remote, shellcode)
388
+ # 4. CreateRemoteThread(remote, shellcode_addr)
389
+
390
+ # Process hollowing:
391
+ # 1. CreateProcess(legitimate.exe, CREATE_SUSPENDED)
392
+ # 2. NtUnmapViewOfSection(hollow out the image)
393
+ # 3. VirtualAllocEx + WriteProcessMemory (write malicious PE)
394
+ # 4. SetThreadContext (point EIP/RIP to new entry)
395
+ # 5. ResumeThread
396
+
397
+ # Detection in memory dumps:
398
+ vol3 -f memory.dmp windows.malfind # PAGE_EXECUTE_READWRITE without file backing
399
+ vol3 -f memory.dmp windows.hollowfind # Hollowed processes (VAD vs PEB mismatch)
400
+
401
+ # APC injection (no new thread):
402
+ # QueueUserAPC(shellcode_addr, target_thread, ...)
403
+ # Thread executes shellcode on next alertable wait
404
+
405
+ # For CTF: dump the injected code region and analyze separately
406
+ vol3 -f memory.dmp windows.malfind --dump --pid <PID>
407
+ ```
408
+
409
+ ### Environment Variable / Hostname Checks
410
+
411
+ **Pattern:** Malware checks for specific environment conditions (hostname, username, domain, locale) to target specific victims or avoid analysis labs.
412
+
413
+ ```python
414
+ # Common checks:
415
+ # - Hostname matches target: if socket.gethostname() != 'TARGET-PC': exit()
416
+ # - Username: if os.getlogin() in ['admin', 'sandbox', 'malware']: exit()
417
+ # - Domain membership: if 'WORKGROUP' in os.environ.get('USERDOMAIN', ''): exit()
418
+ # - Locale/language: WinAPI GetUserDefaultLangID()
419
+ # - Specific file must exist: if not os.path.exists('C:\\Users\\victim\\document.xlsx'): exit()
420
+
421
+ # Bypass: set environment variables before running
422
+ # export COMPUTERNAME=TARGET-PC
423
+ # Or patch the comparison in the binary
424
+ ```
425
+
426
+ **Key insight:** If a malware sample exits immediately or behaves differently than expected, trace its API calls with `strace`/`ltrace` or step through with a debugger. Look for string comparisons against environment values early in execution.
427
+
428
+ ---
429
+
430
+ ### Trojanized Plugin Analysis with Custom Alphabet C2 Decoding (INShAck 2018)
431
+
432
+ **Pattern:** Diff a malicious Sublime Text plugin against the official release to find injected base64 payload in try/except block. The payload uses Caesar-cipher-like rotation on a custom alphabet to encode the C2 domain, and XOR with 0x42 for the endpoint path.
433
+
434
+ ```python
435
+ # Custom alphabet rotation for C2 domain decoding
436
+ C = '0123456789abcdefghijklmnopqrstuvwxyz-.'
437
+ encoded_domain = "..."
438
+ domain = ''.join(C[(C.index(ch) - 0x0d) % len(C)] for ch in encoded_domain)
439
+
440
+ # XOR decoding for endpoint path
441
+ encoded_path = [44, 45, 54, 43, 36, 59]
442
+ path = ''.join(chr(b ^ 0x42) for b in encoded_path)
443
+
444
+ # Registration + flag retrieval
445
+ uuid = register_with_c2(domain)
446
+ flag = requests.get(f"http://{domain}/{path}", cookies={"uuid": uuid}).text
447
+ ```
448
+
449
+ **Key insight:** Trojanized plugins inject code in exception handlers (try/except blocks visible in diff). Custom alphabets for C2 encoding use modular rotation instead of standard ciphers. Always diff suspicious packages against known-good releases from the official repository to isolate injected code.