<!-- Copyright (c) 2026 defconxt. All rights reserved. -->
<!-- Licensed under AGPL-3.0 — see LICENSE file for details. -->
<!-- NERF is a trademark of defconxt. -->
# NERF Training: Vulnerability Research Deep Dive

> Last updated: 2026-03-15
> NERF Training Module: Vulnerability discovery methodology, fuzzing, binary
> analysis, exploit development, browser/kernel/mobile research, responsible
> disclosure, CVSS scoring, patch analysis, and vulnerability management at scale.
---
## Table of Contents

1. [Vulnerability Discovery Methodology](#1-vulnerability-discovery-methodology)
2. [Fuzzing Deep Dive](#2-fuzzing-deep-dive)
3. [Binary Analysis](#3-binary-analysis)
4. [Exploit Development](#4-exploit-development)
5. [Browser Vulnerability Research](#5-browser-vulnerability-research)
6. [Responsible Disclosure Process](#6-responsible-disclosure-process)
7. [CVSS Scoring Methodology](#7-cvss-scoring-methodology)
8. [Exploit Mitigation Bypass](#8-exploit-mitigation-bypass)
9. [Kernel Exploitation](#9-kernel-exploitation)
10. [Mobile Vulnerability Research](#10-mobile-vulnerability-research)
11. [Patch Analysis and 1-Day Exploit Development](#11-patch-analysis-and-1-day-exploit-development)
12. [Vulnerability Management at Scale](#12-vulnerability-management-at-scale)
13. [Key Takeaways](#13-key-takeaways)
---
## 1. Vulnerability Discovery Methodology

### 1.1 Source Code Auditing

Source code audit remains the highest-fidelity method for discovering vulnerabilities.
It produces understanding of root cause, not just crash symptoms.

#### Manual Audit Workflow

```
1. SCOPE        Identify attack surface (parsers, auth, crypto, IPC, network handlers)
2. DECOMPOSE    Map data flow from untrusted input to sensitive operations
3. PATTERN SCAN Recognize known-bad patterns (see below)
4. TRACE        Follow tainted data through transformations and validation
5. HYPOTHESIZE  Form exploitation theory for each candidate bug
6. VALIDATE     Write PoC or construct trigger condition
7. VARIANT      Search for same pattern elsewhere in codebase
```

#### High-Value Audit Targets

| Target Class | Why It Matters | Example Bug Classes |
|---|---|---|
| Parsers (file, protocol, config) | Complex state machines processing untrusted input | Buffer overflow, integer overflow, type confusion |
| Authentication/authorization | Logic flaws bypass security boundaries | Auth bypass, privilege escalation, IDOR |
| Cryptographic implementations | Subtle errors destroy confidentiality | Timing side-channels, nonce reuse, padding oracles |
| Memory allocators/managers | Custom allocators multiply exploit primitives | Use-after-free, double-free, heap metadata corruption |
| IPC/RPC boundaries | Trust boundary crossings | Deserialization, TOCTOU, confused deputy |
| String handling | Ubiquitous and error-prone in C/C++ | Off-by-one, format string, truncation |
| Integer arithmetic | Implicit conversions and overflow | Signed/unsigned confusion, truncation, wraparound |

#### Source Code Audit Patterns by Language

**C/C++ critical patterns:**
```c
// PATTERN: Unchecked integer arithmetic before allocation
size_t total = count * element_size;  // Can wrap around to small value
void *buf = malloc(total);            // Undersized allocation
memcpy(buf, src, count * element_size); // Heap overflow

// PATTERN: Off-by-one in loop bounds
for (int i = 0; i <= len; i++) {  // Should be < len
Buf[i] = src[i];              // Writes one byte past buffer
}

// PATTERN: Use-after-free via dangling pointer
free(obj);
// ... intervening code that may reallocate ...
obj->method();  // UAF -- obj memory may contain attacker data

// PATTERN: Double free
free(ptr);
if (error_condition) {
Free(ptr);  // Double free -- heap metadata corruption
}

// PATTERN: Format string vulnerability
printf(user_input);  // Attacker controls format specifiers
// Should be: printf("%s", user_input);

// PATTERN: TOCTOU race condition
if (access(filepath, R_OK) == 0) {  // Check
Fd = open(filepath, O_RDONLY);    // Use -- file may have changed
}

// PATTERN: Signedness confusion
int len = get_length_from_network();  // Can be negative
if (len > MAX_BUF) return;           // Negative passes this check
memcpy(buf, src, len);               // Interpreted as huge unsigned value
```

**Java/JVM critical patterns:**
```java
// PATTERN: Unsafe deserialization
ObjectInputStream ois = new ObjectInputStream(untrustedInput);
Object obj = ois.readObject();  // Arbitrary code execution via gadget chains

// PATTERN: XXE in XML parsing
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
// Missing: factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
Document doc = factory.newDocumentBuilder().parse(untrustedXml);

// PATTERN: SQL injection
String query = "SELECT * FROM users WHERE name = '" + userInput + "'";
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(query);  // SQLi

// PATTERN: Path traversal
String path = basePath + File.separator + userFilename;
// Missing: canonical path validation
// userFilename = "../../../etc/passwd"
```

**Python critical patterns:**
```python
# PATTERN: Pickle deserialization (RCE)
import pickle
data = pickle.loads(untrusted_bytes)  # Arbitrary code execution

# PATTERN: eval/exec on user input
result = eval(user_expression)  # Code execution
exec(user_code)                 # Code execution

# PATTERN: SSTI (Server-Side Template Injection)
template = Template(user_input)  # If user controls template string
# Jinja2: {{ config.__class__.__init__.__globals__['os'].popen('id').read() }}

# PATTERN: Command injection
import os
os.system(f"convert {user_filename} output.png")  # Shell injection
# Should use: subprocess.run(["convert", user_filename, "output.png"])

# PATTERN: SSRF via user-controlled URL
import requests
resp = requests.get(user_url)  # Can hit internal services, cloud metadata
```

#### Automated Static Analysis with Semgrep

The `0xdea/semgrep-rules` collection provides ~40+ rules targeting C/C++ vulnerability classes:

**Buffer management** (13 rules): Unsafe `strcpy`, `sprintf`, `gets`, missing NUL termination, improper size calculations.

**Integer issues** (5 rules): Signed/unsigned conversion, truncation, wraparound errors.

**Memory allocation** (10 rules): malloc/free mismatches, heap management errors, C/C++ allocator mixing.

**API misuse**: Deprecated functions (`alloca`, `mktemp`, `signal`), command injection via `system()`/`popen()`, format string bugs.

Three-tiered scanning approach:
```bash
# Quick wins -- error-severity only
semgrep --config path/to/rules --severity ERROR target/

# Standard scan -- error + warning
semgrep --config path/to/rules --severity ERROR --severity WARNING target/

# Comprehensive -- all severities (higher FP rate)
semgrep --config path/to/rules target/
```

Output integrates with SARIF format for triage in VS Code SARIF Explorer or CI pipelines.

#### CodeQL for Source Code Audit

```ql
/**
 * Find SQL injection via string concatenation
 */
import java
import semmle.code.java.dataflow.TaintTracking
import semmle.code.java.security.SqlInjectionQuery
From SqlInjectionSink sink, RemoteFlowSource source
where TaintTracking::localFlow(source, sink)
select sink, "Potential SQL injection from $@.", source, "user input"
```

```ql
/**
 * Find command injection in Python
 */
import python
import semmle.python.security.dataflow.CommandInjection
From CommandInjection::Configuration config, DataFlow::PathNode source, DataFlow::PathNode sink
where config.hasFlowPath(source, sink)
select sink.getNode(), source, sink, "Command injection from $@.", source.getNode(), "user input"
```

### 1.2 Reverse Engineering for Vulnerability Discovery

When source code is unavailable, reverse engineering the binary is required:

```
REVERSE ENGINEERING AUDIT WORKFLOW:

1. IDENTIFY TARGET     Determine binary format, architecture, protections
2. LOAD INTO TOOL      IDA Pro, Ghidra, Binary Ninja
3. AUTO-ANALYSIS       Let decompiler identify functions, strings, imports
4. IDENTIFY IMPORTS    Focus on dangerous API calls:
                       - Memory: memcpy, malloc, free, realloc
                       - String: strcpy, strcat, sprintf, gets
                       - Process: system, exec, CreateProcess
                       - File: open, read, write, fopen
                       - Network: recv, recvfrom, WSARecv
5. TRACE DATA FLOW     Follow input from network/file to dangerous sinks
6. IDENTIFY PATTERNS   Type confusion, integer overflow, missing checks
7. BUILD HARNESS       Write test harness to trigger suspected bugs
8. VALIDATE            Confirm vulnerability with crash or proof of concept
```

### 1.3 Fuzzing (Introduction)

Fuzzing generates random or semi-random inputs to trigger crashes, hangs, and
unexpected behavior. Modern coverage-guided fuzzers are the dominant automated
vulnerability discovery technique. (Deep dive in Section 2.)

### 1.4 Differential Analysis

Compare behavior across versions, implementations, or configurations to find
inconsistencies that indicate bugs.

**Techniques:**
- **Patch diffing**: Compare pre-patch and post-patch binaries to identify what
Was fixed (reveals vulnerability location and nature)
- **Cross-implementation testing**: Same protocol parsed by different libraries --
Divergent behavior indicates at least one bug
- **Regression testing**: Run old test suites against new code
- **Semantic diffing**: Tools like BinDiff, Diaphora for binary-level comparison

### 1.5 Variant Analysis

After finding one vulnerability, systematically search for the same bug pattern:

```
1. ROOT CAUSE       Fully understand the original bug's root cause
                    Not "buffer overflow" but "missing length check when
Parsing TLV type 0x42 because the length field is
Trusted from the wire"

2. PATTERN EXTRACT  Generalize the bug into a searchable pattern
                    "Any TLV parser that uses the length field without
Bounds checking against remaining buffer"

3. SEARCH           Apply pattern across codebase
                    - Semgrep rules for syntactic patterns
                    - CodeQL for semantic/dataflow patterns
                    - Manual grep for API misuse patterns

4. VALIDATE         Confirm each candidate is reachable and triggerable

5. REPORT           File variants as separate CVEs (they are distinct vulns)
```

**Tools for variant analysis:**

| Tool | Strength | Use Case |
|---|---|---|
| **Semgrep** | Fast pattern matching, low setup | Syntactic patterns, API misuse |
| **CodeQL** | Semantic analysis, dataflow tracking | Taint analysis, complex patterns |
| **Joern** | Code property graphs, interprocedural | Deep dataflow across functions |
| **Coccinelle** | Semantic patches for C code | Structural matching |
| **grep/ripgrep** | Fast text search | Quick preliminary scans |
---
## 2. Fuzzing Deep Dive

### 2.1 Fuzzing Taxonomy

| Type | Description | Tools |
|---|---|---|
| **Coverage-guided** | Uses code coverage feedback to guide mutation | AFL++, libFuzzer, Honggfuzz |
| **Generation-based** | Produces inputs from grammar/protocol specifications | Peach, Boofuzz, syzkaller |
| **Mutation-based** | Modifies seed inputs via bit flips, splicing, dictionary | AFL++, Radamsa |
| **Blackbox** | No coverage feedback; brute force input variation | zzuf, Radamsa |
| **Greybox** | Limited program knowledge (e.g., coverage only) | AFL++, libFuzzer |
| **Kernel** | Targets OS kernel syscall interfaces | syzkaller, kAFL |
| **Hardware** | Targets firmware and hardware interfaces | kAFL, Unicorn mode, HALucinator |
| **Protocol** | Targets network protocol implementations | Boofuzz, AFLNet, SGFuzz |

### 2.2 AFL++ (American Fuzzy Lop Plus Plus)

AFL++ is the community-maintained successor to Google's AFL. Current version: 4.40c.

**Instrumentation modes:**
- **afl-clang-fast**: Primary LLVM-based compile-time instrumentation (recommended)
- **afl-clang-lto**: Link-time optimization instrumentation (best performance)
- **QEMU mode**: Binary-only fuzzing without source code
- **Frida mode**: Dynamic instrumentation at runtime (cross-platform)
- **Unicorn mode**: CPU emulation for firmware/embedded targets
- **Coresight mode**: ARM hardware-assisted tracing
- **Nyx mode**: Hypervisor-based snapshot fuzzing

**Key improvements over original AFL:**
- Collision-free coverage tracking (no hash collisions in coverage map)
- LAF-Intel & Redqueen: break multi-byte comparisons into byte-level checks
- MOpt mutators: mutation optimizer for improved test case diversity
- AFLFast++ power schedules: intelligent resource allocation to high-value seeds
- Custom mutator API: domain-specific mutation logic for structured formats
- Persistent mode: reduces fork overhead by processing multiple inputs per exec
- CmpLog: compare operand logging for automatic dictionary generation

**Standard workflow:**
```bash
# 1. Compile with instrumentation
export CC=afl-clang-fast
export CXX=afl-clang-fast++
export AFL_USE_ASAN=1  # Enable AddressSanitizer
./configure --disable-shared
make

# 2. Prepare seed corpus (small, valid inputs)
mkdir seeds/
cp valid_samples/* seeds/

# 3. Create dictionary (optional, for structured formats)
# Use afl/dictionaries/ or create custom tokens

# 4. Run fuzzer with CmpLog for comparison solving
afl-fuzz -i seeds/ -o findings/ -m none \
    -c ./target_cmplog -- ./target @@

# 5. Multi-core parallelization
afl-fuzz -i seeds/ -o findings/ -M main -- ./target @@     # master
afl-fuzz -i seeds/ -o findings/ -S worker01 -- ./target @@  # secondary
afl-fuzz -i seeds/ -o findings/ -S worker02 -- ./target @@  # secondary

# 6. Monitor progress
afl-whatsup -s findings/

# 7. Analyze crashes
ls findings/main/crashes/
# Reproduce: ./target < findings/main/crashes/id:000000,...
```

**Persistent mode harness** (dramatically increases throughput):
```c
// Wrap target in __AFL_FUZZ_INIT / __AFL_LOOP
__AFL_FUZZ_INIT();
int main() {
Unsigned char *buf = __AFL_FUZZ_TESTCASE_BUF;
While (__AFL_LOOP(10000)) {
Int len = __AFL_FUZZ_TESTCASE_LEN;
        // Reset target state between iterations
Reset_parser_state();
Parse_input(buf, len);  // target function
    }
Return 0;
}
```

**AFL++ power schedules:**
| Schedule | Description | Best For |
|----------|-------------|----------|
| explore (default) | Balanced exploration | General purpose |
| fast | Prioritize fast-executing seeds | Large corpora |
| coe | Cut-off exponential | Avoiding queue explosion |
| exploit | Focus on seeds with more coverage | Deep path exploration |
| rare | Prioritize rare edges | Complex targets |
| mmopt | Modified MOpt | Structured inputs |
| seek | Seek new edges aggressively | Well-fuzzed targets |

### 2.3 libFuzzer (LLVM)

In-process, coverage-guided fuzzer integrated with LLVM. Primary fuzzer for OSS-Fuzz.

```c
// Harness template
#include <stdint.h>
#include <stddef.h>
Int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) {
    // Reject inputs that are too large
If (size > MAX_INPUT_SIZE) return 0;

    // Call target function with fuzz input
Parse_format(data, size);
Return 0;
}

// Optional: Custom initialization
int LLVMFuzzerInitialize(int *argc, char ***argv) {
    // One-time setup (load configs, initialize libraries)
Return 0;
}

// Optional: Custom mutator for structured fuzzing
size_t LLVMFuzzerCustomMutator(uint8_t *data, size_t size,
Size_t max_size, unsigned int seed) {
    // Implement structure-aware mutation
Return new_size;
}
```

```bash
# Compile with fuzzer + sanitizer
clang -g -O1 -fsanitize=fuzzer,address -o fuzz_target fuzz_harness.c target.c

# Run with options
./fuzz_target corpus/ \
    -max_len=65536 \          # Maximum input size
    -timeout=10 \             # Per-input timeout (seconds)
    -rss_limit_mb=4096 \      # Memory limit
    -dict=format.dict \       # Dictionary file
    -jobs=8 \                 # Parallel jobs
    -workers=8 \              # Worker processes
    -print_final_stats=1      # Statistics at exit

# Merge corpora (deduplicate)
./fuzz_target -merge=1 minimized_corpus/ corpus1/ corpus2/

# Coverage report
./fuzz_target corpus/ -runs=0 -dump_coverage=1
```

**libFuzzer advantages over AFL++:**
- In-process (no fork overhead) -- higher throughput for small targets
- Direct LLVM integration (works with any LLVM sanitizer)
- Built-in corpus merging and minimization
- FuzzedDataProvider for structured input decomposition

**FuzzedDataProvider** (structured input from random bytes):
```cpp
#include <fuzzer/FuzzedDataProvider.h>
Int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) {
    FuzzedDataProvider provider(data, size);

    // Consume structured data from fuzz input
Int width = provider.ConsumeIntegralInRange<int>(1, 4096);
Int height = provider.ConsumeIntegralInRange<int>(1, 4096);
Std::string format = provider.ConsumeRandomLengthString(16);
Std::vector<uint8_t> pixels = provider.ConsumeRemainingBytes<uint8_t>();

    // Call target with structured input
Process_image(pixels.data(), pixels.size(), width, height, format.c_str());
Return 0;
}
```

### 2.4 Honggfuzz

Multi-process, multi-threaded fuzzer by Google.

**Key features:**
- Hardware-assisted feedback (Intel BTS, Intel PT) -- no recompilation needed
- Software-only coverage mode via compile-time instrumentation
- Persistent mode via HF_ITER for high throughput
- Built-in crash deduplication and minimization
- Linux-specific features: seccomp-bpf, namespace sandboxing

```bash
# Compile with Honggfuzz instrumentation
hfuzz-clang -fsanitize=address -o target target.c

# Run
honggfuzz -i seeds/ -o crashes/ --threads 8 \
    --dict format.dict -- ./target ___FILE___

# Persistent mode
honggfuzz -i seeds/ -o crashes/ --threads 8 \
    --persistent -- ./target_persistent

# Hardware feedback (Intel PT, no recompilation)
honggfuzz -i seeds/ -o crashes/ --threads 8 \
    --linux_perf_ipt_block -- ./target_binary ___FILE___
```

### 2.5 Grammar-Based and Structure-Aware Fuzzing

For structured formats (protobuf, JSON, XML, SQL, programming languages), raw
byte mutation is inefficient because most mutations produce syntactically invalid
inputs that are rejected early.

#### libprotobuf-mutator

```cpp
// Fuzz protobuf-based interfaces
#include "src/libfuzzer/libfuzzer_macro.h"
#include "my_proto.pb.h"

DEFINE_PROTO_FUZZER(const MyMessage& message) {
    // message is always a valid protobuf
    ProcessMessage(message);
}
```

#### Custom AFL++ Mutator

```c
// Structure-aware mutation for a custom format
typedef struct {
Afl_state_t *afl;
} my_mutator_t;
My_mutator_t *afl_custom_init(afl_state_t *afl, unsigned int seed) {
My_mutator_t *data = calloc(1, sizeof(my_mutator_t));
Data->afl = afl;
Srand(seed);
Return data;
}
Size_t afl_custom_fuzz(my_mutator_t *data, uint8_t *buf, size_t buf_size,
Uint8_t **out_buf, uint8_t *add_buf,
Size_t add_buf_size, size_t max_size) {
    // Parse buf into structure
My_format_t *parsed = parse_format(buf, buf_size);
If (!parsed) {
        // Fall back to byte-level mutation
        *out_buf = buf;
Return buf_size;
    }

    // Mutate at semantic level
Mutate_field(parsed, rand() % parsed->num_fields);

    // Serialize back
Size_t new_size = serialize_format(parsed, *out_buf, max_size);
Free_format(parsed);
Return new_size;
}
```

#### Grammar Fuzzing (Nautilus, Gramatron, Grimoire)

```
GRAMMAR FUZZING APPROACH:

1. Define input grammar (BNF, ANTLR, custom format)
   <expr>   ::= <number> | <expr> <op> <expr> | "(" <expr> ")"
   <op>     ::= "+" | "-" | "*" | "/"
   <number> ::= [0-9]+

2. Generate syntactically valid inputs via grammar derivation
3. Use coverage feedback to guide which grammar productions to explore
4. Mutate at grammar level (replace subtree, crossover between derivations)

LIMITATIONS (documented by Project Zero, 2025-2026):
- Grammar must be written manually (labor-intensive)
- Grammar may not perfectly match implementation (semantic gaps)
- Coverage feedback may not correlate well with grammar depth
- Difficulty balancing grammar-level and byte-level mutation
- Deep program states require long input sequences
```

### 2.6 Kernel Fuzzing (syzkaller)

Unsupervised coverage-guided kernel fuzzer by Google.

**Supported kernels**: Linux, FreeBSD, NetBSD, OpenBSD, Windows, Fuchsia, Darwin/XNU, gVisor.

**Architecture:**
- `syz-manager`: Central coordinator running on host
- `syz-agent`: Executes test programs in VMs/containers
- `syz-executor`: Low-level syscall execution in target kernel
- Coverage feedback via KCOV (Linux) or platform-specific mechanisms

**Syscall descriptions (syzlang):**
```
# Example syzlang description
open(file filename, flags flags[open_flags], mode flags[open_mode]) fd
read(fd fd, buf buffer[out], count len[buf])
write(fd fd, buf buffer[in], count len[buf])
close(fd fd)
mmap(addr vma, len len[addr], prot flags[mmap_prot],
Flags flags[mmap_flags], fd fd, offset fileoff) vma
ioctl$TIOCSCTTY(fd fd_tty, arg intptr)
```

**Workflow:**
```bash
# 1. Build kernel with KCOV and sanitizers
make defconfig
# Enable: CONFIG_KCOV=y, CONFIG_KASAN=y, CONFIG_KMSAN=y,
#         CONFIG_KCSAN=y, CONFIG_UBSAN=y, CONFIG_DEBUG_INFO=y
make -j$(nproc)

# 2. Create syz-manager config
{
    "target": "linux/amd64",
    "http": "127.0.0.1:56741",
    "workdir": "/path/to/workdir",
    "kernel_obj": "/path/to/linux",
    "image": "/path/to/bullseye.img",
    "syzkaller": "/path/to/syzkaller",
    "procs": 8,
    "type": "qemu",
    "vm": {
        "count": 4,
        "kernel": "/path/to/bzImage",
        "cpu": 2,
        "mem": 2048
    }
}

# 3. Run syzkaller
./syz-manager -config config.json

# 4. Monitor via web dashboard (http://127.0.0.1:56741)
#    - Coverage statistics
#    - Crash reports with reproducers
#    - Corpus statistics
```

**syzkaller output:**
- Crash reports with kernel stack traces (KASAN/KMSAN/KCSAN reports)
- Minimized C reproducers for each crash
- Automatic bisection to identify guilty commit
- Automatic reporting to syzbot (Linux kernel fuzzing dashboard)

### 2.7 Network Protocol Fuzzing (AFLNet, Boofuzz)

```
NETWORK FUZZING APPROACHES:

STATEFUL PROTOCOL FUZZING (AFLNet):
- Records network interaction as seed
- Mutates individual protocol messages while maintaining state
- Coverage-guided feedback from instrumented server
- Supports TCP and UDP protocols

GENERATION-BASED PROTOCOL FUZZING (Boofuzz):
- Define protocol specification (blocks, fields, groups)
- Generate valid-but-mutated protocol messages
- Monitor target for crashes, hangs, unusual responses
- Successor to Sulley fuzzing framework
```

**Boofuzz example:**
```python
from boofuzz import *
Session = Session(target=Target(
Connection=SocketConnection("target", 80, proto="tcp")
))
S_initialize("HTTP_GET")
s_string("GET", fuzzable=False)
s_delim(" ", fuzzable=False)
s_string("/index.html", name="uri")
s_delim(" ", fuzzable=False)
s_string("HTTP/1.1", fuzzable=False)
s_static("\r\n")
s_string("Host", fuzzable=False)
s_delim(": ", fuzzable=False)
s_string("target", name="host")
s_static("\r\n\r\n")
Session.connect(s_get("HTTP_GET"))
session.fuzz()
```

### 2.8 OSS-Fuzz and ClusterFuzz

Google's OSS-Fuzz provides continuous fuzzing for open source software.

**Impact** (as of 2025):
- 1,000+ projects enrolled
- 13,000+ vulnerabilities found
- 50,000+ stability bugs found

**Supported engines**: libFuzzer, AFL++, Honggfuzz (all run in parallel via ClusterFuzz).

**ClusterFuzz key capabilities:**
- Crash deduplication (eliminates noise)
- Testcase minimization (reduces to minimal reproducer)
- Regression bisection (identifies guilty commit)
- Coverage analysis (tracks progress over time)
- Ensemble fuzzing (multiple engines share interesting inputs)

**ClusterFuzzLite**: CI/CD variant. Runs fuzzers on every PR/commit for ~10 minutes.

### 2.9 Fuzzing Best Practices

```
HARNESS DESIGN:
1. Target function that processes untrusted input directly
2. Minimize initialization overhead (mock expensive operations)
3. Ensure determinism (same input = same behavior)
4. Handle variable-size inputs gracefully
5. Reset state between iterations (persistent mode)
6. ALWAYS compile with sanitizers (ASan + UBSan minimum)

CORPUS MANAGEMENT:
# Minimize corpus (remove redundant inputs)
afl-cmin -i raw_corpus/ -o minimized/ -- ./target @@

# Minimize individual testcases
afl-tmin -i crash_input -o minimized_crash -- ./target @@

COVERAGE ANALYSIS:
# Compile with coverage
clang -fprofile-instr-generate -fcoverage-mapping -o target_cov target.c

# Run corpus and generate report
for f in corpus/*; do ./target_cov "$f"; done
llvm-profdata merge -sparse *.profraw -o merged.profdata
llvm-cov show ./target_cov -instr-profile=merged.profdata -format=html > cov.html

PLATEAUING COVERAGE INDICATES:
- Checksums or magic bytes blocking -> add to dictionary or custom mutator
- Complex state machines -> structure-aware fuzzing
- Environmental dependencies -> improve harness mocking
- Deep nesting -> increase timeout, use directed fuzzing
```
---
## 3. Binary Analysis

### 3.1 Ghidra

NSA's open-source reverse engineering framework (released 2019).

**Key capabilities:**
- Decompiler for x86, ARM, MIPS, PowerPC, SPARC, and many more
- Collaborative reverse engineering (shared projects)
- Scripting via Java/Jython for automation
- Version tracking (binary diffing between versions)
- Extensible via plugins (PCode emulation, symbolic execution)
- Free and actively maintained

**Ghidra workflow for vulnerability research:**
```
1. IMPORT        Load binary, auto-analyze (identify functions, strings, imports)
2. STRINGS       Review string references for error messages, paths, credentials
3. IMPORTS       Focus on dangerous API calls (memcpy, system, exec)
4. ENTRY POINTS  Identify main, exported functions, signal handlers
5. DECOMPILE     Review decompiled code for vulnerability patterns
6. XREFS         Cross-reference dangerous functions to trace callers
7. DATA FLOW     Follow untrusted input through decompiled code
8. ANNOTATE      Rename functions, add comments, define structures
9. EMULATE       Use PCode emulation to validate hypotheses
10. SCRIPT       Automate pattern searches across binary
```

**Ghidra scripting for vulnerability discovery:**
```java
// Find all calls to memcpy with non-constant size argument
// (potential buffer overflow if size is user-controlled)
import ghidra.program.model.listing.*;
import ghidra.program.model.symbol.*;
Public class FindDangerousMemcpy extends GhidraScript {
    @Override
Public void run() throws Exception {
        SymbolTable symTable = currentProgram.getSymbolTable();
For (Symbol sym : symTable.getSymbols("memcpy")) {
For (Reference ref : getReferencesTo(sym.getAddress())) {
                Function caller = getFunctionContaining(ref.getFromAddress());
If (caller != null) {
Println("memcpy called from " + caller.getName() +
                            " at " + ref.getFromAddress());
                }
            }
        }
    }
}
```

### 3.2 IDA Pro

Industry-standard commercial disassembler and decompiler.

**Key capabilities:**
- Hex-Rays decompiler (x86, x64, ARM, ARM64, MIPS, PowerPC)
- Extensive processor support (70+ architectures)
- Large plugin ecosystem (BinDiff, Diaphora, FLIRT signatures)
- IDAPython scripting
- Debugger integration (local and remote)
- Type Library support (import headers for structure recovery)

**IDA Pro advantages over Ghidra:**
- More mature decompiler (better output quality in many cases)
- Faster analysis on large binaries
- Better FLIRT signature matching (library function identification)
- Larger third-party plugin ecosystem
- Better PDB/DWARF debug info handling

**Cost**: $1,879 (IDA Pro + one decompiler), higher for additional platforms.

### 3.3 Binary Ninja

Modern binary analysis platform with emphasis on intermediate languages.

**Unique features:**
- Multi-level IL (Lifted IL, Low Level IL, Medium Level IL, High Level IL)
- Clean API for automated analysis
- Cloud collaboration
- Cross-platform (macOS, Linux, Windows)
- Good balance of capability vs. learning curve

**Binary Ninja ILs:**
```
ASSEMBLY   →  Lifted IL  →  Low Level IL  →  Medium Level IL  →  High Level IL
(raw arch)    (normalized)   (SSA form)       (cleaned up)        (decompiled)

Each level provides different analysis capabilities:
- LLIL: Register-level analysis, constant propagation
- MLIL: Type-aware analysis, variable recovery
- HLIL: Human-readable decompilation, dataflow analysis
```

### 3.4 angr (Symbolic Execution)

Python framework for binary analysis using symbolic execution.

**Symbolic execution concept:**
```
Instead of concrete values, use symbolic variables:
X = symbolic("user_input")

Execute program with symbolic values:
If (x > 10):      # Path constraint: x > 10
If (x < 20):  # Path constraint: x > 10 AND x < 20
Vuln()     # Ask solver: is there x satisfying x > 10 AND x < 20?
                       # Solver returns: x = 15

This explores ALL program paths (up to computational limits)
and finds inputs that reach specific code locations.
```

**angr for vulnerability discovery:**
```python
import angr
import claripy

# Load binary
proj = angr.Project("./vulnerable_binary", auto_load_libs=False)

# Create symbolic input (32 bytes)
sym_input = claripy.BVS("input", 32 * 8)

# Create initial state with symbolic stdin
state = proj.factory.entry_state(stdin=sym_input)

# Create simulation manager
simgr = proj.factory.simgr(state)

# Explore: find path to vulnerable function, avoid error handlers
simgr.explore(
Find=0x401234,    # Address of vulnerable function
Avoid=0x401300    # Address of error handler
)

# Extract concrete input that reaches vulnerable function
if simgr.found:
Found_state = simgr.found[0]
Concrete_input = found_state.solver.eval(sym_input, cast_to=bytes)
Print(f"Input to trigger vulnerability: {concrete_input}")
```

**angr limitations:**
- Path explosion: number of paths grows exponentially with branches
- Symbolic memory: tracking all possible memory states is expensive
- Syscall modeling: must model OS behavior (angr provides SimProcedures)
- Concretization: sometimes must choose concrete values, losing generality
- Scalability: practical for functions/modules, challenging for whole programs

### 3.5 Dynamic Binary Instrumentation

**Frida** (cross-platform DBI):
```javascript
// Hook malloc to track allocations
Interceptor.attach(Module.findExportByName(null, "malloc"), {
OnEnter: function(args) {
This.size = args[0].toInt32();
    },
OnLeave: function(retval) {
Console.log(`malloc(${this.size}) = ${retval}`);
    }
});

// Hook specific function and modify arguments
Interceptor.attach(ptr("0x401234"), {
OnEnter: function(args) {
Console.log("arg0:", args[0].readUtf8String());
        // Modify argument
Args[0] = Memory.allocUtf8String("modified_input");
    }
});

// Trace all calls to a function
Stalker.follow(Process.getCurrentThreadId(), {
Events: { call: true },
OnCallSummary: function(summary) {
For (var addr in summary) {
Var symbol = DebugSymbol.fromAddress(ptr(addr));
Console.log(symbol.toString(), summary[addr]);
        }
    }
});
```

**DynamoRIO** (Windows/Linux DBI):
- Higher performance than Frida for intensive instrumentation
- Used by Dr. Memory (memory error detector)
- Custom tool development via API
- Trace recording for offline analysis

**Intel Pin** (x86/x64 DBI):
- Fine-grained instruction-level instrumentation
- Instruction counting, memory trace, cache simulation
- Plugin-based architecture
- Academic and research focus

### 3.6 Sanitizers for Binary Validation

| Sanitizer | Flag | Detects | Overhead |
|---|---|---|---|
| **AddressSanitizer (ASan)** | `-fsanitize=address` | Heap/stack/global OOB, UAF, double-free, leaks | ~2x slowdown, ~3x memory |
| **MemorySanitizer (MSan)** | `-fsanitize=memory` | Reads of uninitialized memory | ~3x slowdown |
| **ThreadSanitizer (TSan)** | `-fsanitize=thread` | Data races, deadlocks | ~5-15x slowdown |
| **UndefinedBehaviorSanitizer (UBSan)** | `-fsanitize=undefined` | Integer overflow, null deref, alignment | ~1.2x slowdown |
| **HWAddressSanitizer (HWASan)** | `-fsanitize=hwaddress` | Same as ASan but uses hardware tagging (ARM MTE) | ~1.1x overhead |

**Kernel variants**: KASAN, KMSAN, KCSAN -- same detection applied to kernel code.

```bash
# Compile with ASan + UBSan for fuzzing
clang -g -O1 -fsanitize=fuzzer,address,undefined \
    -fno-sanitize-recover=all \
    -o fuzz_target harness.c target.c

# ASan options
export ASAN_OPTIONS="detect_leaks=0:abort_on_error=1:symbolize=1:\
Allocator_may_return_null=1:detect_stack_use_after_return=1"
```
---
## 4. Exploit Development

### 4.1 From Discovery to Exploit

```
CRASH ANALYSIS       Triage fuzzer output or audit finding
    |                Determine: is this reachable? controllable? exploitable?
ROOT CAUSE           Identify the specific flaw (OOB write, UAF, type confusion)
    |                Map the vulnerable code path
TRIGGER CONSTRUCTION Build minimal reliable trigger
    |                Reduce to smallest input that causes the bug
PRIMITIVE ANALYSIS   Determine what the bug gives you
    |                Read primitive? Write primitive? Both? How constrained?
EXPLOITATION         Chain primitives into meaningful capability
    |                Information leak -> defeat ASLR -> code execution
RELIABILITY          Handle race conditions, heap layout, ASLR
    |                Target >= 90% reliability for practical use
WEAPONIZATION        Package for delivery (authorized engagement only)
```

### 4.2 Stack Buffer Overflow Exploitation

**Classic technique, still relevant on embedded/legacy systems:**

```
VULNERABLE CODE:
void process_input(char *input) {
Char buffer[64];
Strcpy(buffer, input);  // No bounds check
}

STACK LAYOUT:
Low addr  ┌─────────────────┐
          │ buffer[64]      │ ← overflow starts here
          ├─────────────────┤
          │ saved RBP       │ ← overwritten
          ├─────────────────┤
          │ return address   │ ← controlled! → redirect execution
High addr └─────────────────┘

EXPLOITATION (no mitigations):
1. Fill buffer with padding (64 bytes)
2. Overwrite saved RBP (8 bytes)
3. Overwrite return address with target (shellcode address or ROP gadget)
4. Place payload after return address or at known location

WITH MODERN MITIGATIONS:
- Stack canary: must leak or bypass canary before return address
- NX/DEP: cannot execute code on stack → use ROP
- ASLR: cannot predict addresses → need info leak first
- CFI: return address validated → need CFI-compatible target
```

### 4.3 Return-Oriented Programming (ROP)

**Concept:** Chain existing code snippets ("gadgets") ending in `ret` to build
arbitrary computation without injecting code.

```
ROP CHAIN CONSTRUCTION:

1. FIND GADGETS
   $ ropper --file ./target --search "pop rdi; ret"
   $ ROPgadget --binary ./target --ropchain

   Common gadgets needed:
   - pop rdi; ret          (set first argument)
   - pop rsi; ret          (set second argument)
   - pop rdx; ret          (set third argument)
   - mov [rdi], rsi; ret   (arbitrary write)
   - syscall; ret          (invoke kernel)

2. BUILD CHAIN (example: execve("/bin/sh"))

   STACK LAYOUT:
   ┌─────────────────────────┐
   │ addr of: pop rdi; ret   │  ← return address
   ├─────────────────────────┤
   │ addr of "/bin/sh"       │  ← popped into rdi
   ├─────────────────────────┤
   │ addr of: pop rsi; ret   │
   ├─────────────────────────┤
   │ 0x0000000000000000      │  ← argv = NULL
   ├─────────────────────────┤
   │ addr of: pop rdx; ret   │
   ├─────────────────────────┤
   │ 0x0000000000000000      │  ← envp = NULL
   ├─────────────────────────┤
   │ addr of: pop rax; ret   │
   ├─────────────────────────┤
   │ 0x000000000000003b      │  ← syscall number for execve
   ├─────────────────────────┤
   │ addr of: syscall; ret   │  ← execute!
   └─────────────────────────┘

3. MODERN CONSIDERATIONS:
   - Gadgets must be from executable pages (not DEP-protected)
   - ASLR randomizes gadget addresses → need leak first
   - Stack alignment requirements (RSP must be 16-byte aligned)
   - Some gadgets have side effects that corrupt state
```

**ROP tool comparison:**
| Tool | Features |
|------|----------|
| **ROPgadget** | Automatic chain generation, multi-arch, ELF/PE/Mach-O |
| **ropper** | Semantic search, JOP/COP support, interactive mode |
| **pwntools** | ROP chain builder integrated with exploit framework |
| **angr** | Automatic ROP chain generation via symbolic execution |
| **xrop** | Fast gadget finder with quality scoring |

### 4.4 Heap Exploitation

**Modern heap exploitation targets the memory allocator metadata and application
data structures:**

#### Use-After-Free (UAF)

```
UAF EXPLOITATION:

1. VULNERABILITY:
   Object A is freed, but pointer to A still exists (dangling pointer)

2. ALLOCATE REPLACEMENT:
   Allocate Object B of same size as A
   Heap allocator reuses freed memory → B occupies A's former location

3. CONFUSION:
   Code using dangling pointer to A now reads/writes Object B's data
   If B has different type/layout → type confusion

4. EXPLOITATION:
   - If A had a vtable pointer: B's data is read as vtable → control flow hijack
   - If A had a function pointer: B's data called as function → code execution
   - If A had a length field: B's data read as length → OOB access

EXAMPLE (Chrome V8):
   JSObject *obj = CreateObject();  // Allocate JSObject
   FreeObject(obj);                 // Free JSObject
   // ... GC or other allocation reclaims memory ...
   ArrayBuffer *buf = CreateArrayBuffer(sizeof(JSObject));
   // buf occupies obj's former memory
Obj->CallMethod();  // Reads buf's data as vtable → controlled RIP
```

#### Heap Overflow

```
HEAP OVERFLOW EXPLOITATION:

TCACHE POISONING (glibc 2.26+):
1. Overflow from chunk A into chunk B's header
2. Overwrite B's fd (forward) pointer in tcache freelist
3. Free B → tcache freelist now contains corrupted pointer
4. Next allocation from tcache returns attacker-controlled address
5. Write to returned address = arbitrary write primitive

OVERLAPPING CHUNKS:
1. Overflow to corrupt size field of adjacent free chunk
2. Modified size causes allocator to return overlapping region
3. Two pointers to same memory with different types = type confusion

HOUSE TECHNIQUES (glibc-specific):
- House of Force: Overwrite top chunk size → control next allocation location
- House of Einherjar: Abuse backward consolidation to overlap chunks
- House of Lore: Corrupt smallbin to return arbitrary address
- House of Orange: Create fake chunk via heap overflow, trigger _IO_flush_all_lockp
- tcache poisoning: Simpler variant for glibc 2.26+ tcache bins
```

#### Type Confusion

```
TYPE CONFUSION:

CONCEPT:
Code treats memory as Type A, but it actually contains Type B data.
If Type A and Type B have different layouts, attacker controls
fields that the code assumes are trusted.

COMMON SOURCES:
1. Use-after-free (reallocated as different type)
2. JIT compiler optimization bugs (incorrect type narrowing)
3. Variant types (union/variant mishandling)
4. Deserialization (wrong class instantiated)
5. DOM type confusion (HTML element cast to wrong subclass)

EXPLOITATION:
If Type A has:
Offset 0: vtable pointer (trusted)
Offset 8: data length (trusted)
Offset 16: data pointer

And Type B has:
Offset 0: user data (controlled)
Offset 8: user data (controlled)
Offset 16: user data (controlled)

Reading Type B as Type A:
  - offset 0 → vtable pointer → controlled → arbitrary function call
  - offset 8 → data length → controlled → OOB access
  - offset 16 → data pointer → controlled → arbitrary read/write
```

### 4.5 Exploit Primitive Chaining

```
TYPICAL EXPLOIT CHAIN:

BUG → INFO LEAK → ASLR BYPASS → CODE EXECUTION

Step 1: BUG
  UAF, OOB read/write, type confusion, etc.

Step 2: INFO LEAK (defeat ASLR)
  - OOB read to leak heap/stack/code pointers
  - Type confusion to read pointer fields
  - Side-channel (timing, cache) to infer addresses
  - Partial overwrite (only change low bytes of pointer)

Step 3: ASLR BYPASS
  - Leaked pointer reveals base address of:
    - libc (for system(), gadgets)
    - Binary (for PLT/GOT, gadgets)
    - Heap (for fake structures)
    - Stack (for ROP chain placement)

Step 4: CODE EXECUTION
  - Overwrite vtable/function pointer → ROP chain
  - Overwrite GOT entry → redirect function call
  - JIT spray → place controlled data in executable page
  - Stack pivot → redirect RSP to controlled memory → ROP
```
---
## 5. Browser Vulnerability Research

### 5.1 Browser Architecture and Attack Surface

```
MODERN BROWSER ARCHITECTURE:

BROWSER PROCESS (high privilege)
├── UI, bookmarks, history
├── Network stack
├── File system access
└── Process management

RENDERER PROCESS (sandboxed, per-tab)
├── JavaScript engine (V8, SpiderMonkey, JavaScriptCore)
├── DOM engine (Blink, Gecko, WebKit)
├── CSS engine
├── HTML parser
├── WebAssembly runtime
├── Canvas/WebGL (GPU access via IPC)
└── Web Workers

GPU PROCESS
├── Compositing
├── WebGL execution
├── Video decode
└── Canvas operations

NETWORK PROCESS
├── HTTP/HTTPS handling
├── DNS resolution
├── WebSocket connections
└── CORS enforcement

ATTACK CHAIN:
Renderer bug (JS/DOM/WASM) → Sandbox escape (IPC/Mojo/kernel) → System access
Most browser exploits require TWO bugs: renderer + sandbox escape
```

### 5.2 V8 (Chrome's JavaScript Engine)

**V8 architecture:**
```
SOURCE CODE → PARSER → AST → IGNITION (interpreter)
                                    ↓
                              SPARKPLUG (baseline compiler)
                                    ↓
                              MAGLEV (mid-tier compiler)
                                    ↓
                              TURBOFAN (optimizing JIT compiler)

VULNERABILITY HOTSPOTS:
1. Type system: V8 tracks types speculatively. If speculation is wrong
And the JIT doesn't deoptimize properly → type confusion

2. JIT compiler optimizations: Bounds check elimination, dead code
Elimination, escape analysis can incorrectly remove safety checks

3. Garbage collector: Object movement during GC can create dangling
References if the JIT code doesn't account for GC safepoints

4. Built-in functions: TypedArray, ArrayBuffer, Regex, JSON parsing --
Complex native code processing JavaScript-controlled inputs
```

**V8 vulnerability classes:**
```
JIT TYPE CONFUSION (most impactful):
- Turbofan assumes a value is of type T
- Generates optimized code without type checks
- Value is actually type U at runtime
- Result: OOB access, arbitrary read/write

EXAMPLE:
function exploit(arr) {
    // Turbofan speculates arr is always a packed SMI array
    // Generates code without bounds check
Return arr[0];
}

// Train the JIT with packed arrays
for (let i = 0; i < 100000; i++) {
Exploit([1, 2, 3]);
}

// Now pass a different type → type confusion
exploit(oob_array);  // JIT code reads without proper checks

BOUNDS CHECK ELIMINATION:
- JIT removes array bounds checks when it "proves" access is safe
- If proof is flawed (e.g., doesn't account for array shrinkage)
- Result: OOB read/write

OOB READ/WRITE TO ARBITRARY R/W:
1. Corrupt TypedArray backing store pointer (via JIT bug)
2. TypedArray now reads/writes arbitrary memory
3. Use this to build addrof (object address leak) and fakeobj (forge object)
4. Chain into code execution
```

### 5.3 SpiderMonkey (Firefox's JavaScript Engine)

**Architecture differences from V8:**
- Baseline interpreter → Baseline JIT → WarpMonkey (optimizing JIT)
- Different object representation (NaN-boxing vs V8's pointer tagging)
- Different GC design (incremental, generational, compacting)
- IonMonkey (legacy optimizer) replaced by WarpMonkey

**Vulnerability patterns:**
- JIT compilation bugs (similar classes to V8 but different implementation)
- GC interaction bugs (different GC architecture, different bug patterns)
- WebAssembly implementation bugs
- Regular expression engine vulnerabilities
- Prototype chain manipulation

### 5.4 WebKit/JavaScriptCore (Safari)

**Architecture:**
- LLInt (Low Level Interpreter) → Baseline JIT → DFG (Data Flow Graph) JIT → FTL (Faster Than Light) JIT
- Uses B3 (Bare Bones Backend) IR for FTL compilation

**Historical significance:**
- Primary target for iOS exploitation (Safari is mandatory renderer)
- FORCEDENTRY exploited ImageIO (not JSC directly) but via WebKit content
- PAC (Pointer Authentication) on ARM64e adds complexity to exploitation
- WebKit vulnerabilities often used in targeted surveillance (NSO Group chains)

### 5.5 Sandbox Escape

**Chrome sandbox (multi-process):**
```
RENDERER → MOJO IPC → BROWSER PROCESS

ESCAPE VECTORS:
1. Mojo IPC bugs: Renderer sends crafted IPC message that triggers
Vulnerability in browser process message handler

2. GPU process bugs: Renderer sends crafted GPU commands that
Trigger vulnerability in GPU process (less sandboxed)

3. Site isolation bypass: Renderer accesses data from other origins
   (Spectre-class, process sharing bugs)

4. OS kernel bugs: Renderer exploits kernel vulnerability to escape
Sandbox entirely (most powerful, most difficult)

RECENT EXAMPLES:
- CVE-2026-3910: V8 sandbox escape (Chrome, Mar 2026)
- Chrome sandbox relies on seccomp-bpf (Linux), seatbelt (macOS),
Restricted tokens (Windows)
- V8 sandbox (in-process) adds additional isolation layer around V8 heap
```

**Chrome V8 Sandbox (in-process):**
```
V8 introduced an in-process sandbox to limit JIT bug impact:
- V8 heap isolated in a virtual memory cage
- External pointers use indirection table (not raw pointers)
- Code pointers validated before use
- Limits UAF/type confusion exploitation to V8 heap only
- Escape requires: V8 bug + sandbox bypass (two bugs within renderer)

This is why Chrome V8 exploits now often require chaining:
1. JIT type confusion → V8 sandbox compromise
2. V8 sandbox escape → renderer process compromise
3. Renderer → browser/kernel → system compromise
```

### 5.6 Browser Bug Bounty Programs

| Program | Max Payout | Notable |
|---------|-----------|---------|
| Chrome VRP | $250,000 | Full chain bonus, MiraclePtr bypass bonus |
| Firefox Bug Bounty | $10,000 | Lower payouts but valuable targets |
| Safari/WebKit | $250,000 | Apple Security Research (via Apple program) |
| Edge | Via MSRC | Same engine as Chrome (Chromium) |
---
## 6. Responsible Disclosure Process

### 6.1 Disclosure Models

| Model | Timeline | Characteristics |
|---|---|---|
| **Coordinated disclosure** | 90 days typical | Researcher reports to vendor, negotiates fix timeline |
| **Full disclosure** | Immediate | Publish everything immediately; controversial but sometimes necessary |
| **Bug bounty** | Vendor-defined | Financial incentive; platform handles coordination |
| **Zero-day broker** | Undisclosed | Sold to governments/agencies; no public disclosure |

### 6.2 CVE Assignment Process

**CVE Numbering Authorities (CNAs):**
- **Root CNAs**: Oversee CNA programs (MITRE, CISA)
- **Regular CNAs**: Vendors (Microsoft, Google, Red Hat), coordinators (CERT/CC),
Bug bounty platforms (HackerOne)
- A CNA assigns CVEs for vulnerabilities within its defined scope

**CVE lifecycle:**
```
DISCOVERY            Researcher identifies vulnerability
    |
RESERVATION          CNA assigns CVE ID (state: RESERVED)
    |                ID exists but no public details
COORDINATION         Researcher + vendor negotiate fix timeline
    |                Typical: 90 days (Google P0), 45 days (ZDI)
PUBLICATION          CNA publishes CVE Record (state: PUBLISHED)
    |                Contains: description, affected products, CVSS, CWE
ENRICHMENT           NVD adds CVSS scores, CPE, CWE mappings
    |                EPSS generates exploitation probability
    |
REJECTION            (alternate path) CNA marks CVE as REJECTED
If duplicate, not a vuln, or out of scope
```

**How to request a CVE:**
```
1. DETERMINE CNA:
   - If vendor has its own CNA → report to vendor
   - If vendor uses third-party CNA (e.g., HackerOne) → report there
   - If no CNA covers the product → report to MITRE or CISA

2. PROVIDE:
   - Affected product and version(s)
   - Vulnerability type (CWE)
   - Attack vector and impact
   - Proof of concept (recommended)
   - Suggested CVSS score (optional)
   - Credit information

3. TIMELINE:
   - CVE reserved within 1-7 days (CNA dependent)
   - Publication coordinated with patch release
   - NVD enrichment: 1-14 days after publication (backlog dependent)
```

### 6.3 Coordinated Disclosure Timeline

```
Day 0      Researcher discovers vulnerability
Day 1-3    Researcher develops PoC, confirms exploitability
Day 3-7    Initial report to vendor (encrypted, via security@ or bug bounty)
Day 7-14   Vendor acknowledges receipt, assigns internal tracking
Day 14-60  Vendor develops and tests patch
Day 60-90  Patch released; CVE published
Day 90+    Researcher publishes full technical details + PoC

If vendor unresponsive:
  Day 30   Second contact attempt
  Day 45   Third contact attempt, warn of disclosure deadline
  Day 90   Publish regardless (Google Project Zero policy)
```

**Notable disclosure policies:**
- **Google Project Zero**: 90 days, +14 day grace if patch imminent, +30 days
For actively exploited (shorter to protect users)
- **ZDI (Zero Day Initiative)**: 120 days standard
- **CERT/CC**: 45 days

### 6.4 Bug Bounty Platforms

**HackerOne:**
- Largest platform: 3,000+ programs, $300M+ in bounties paid
- Managed triage service (HackerOne handles initial assessment)
- Mediation for disputes between researchers and vendors
- Structured reporting templates
- Reputation system for researchers

**Bugcrowd:**
- 1,000+ programs
- Managed bug bounty and pen testing programs
- CrowdMatch (researcher-to-program matching)
- Vulnerability Rating Taxonomy (VRT) for consistent assessment

**Direct vendor programs:**
- Google VRP, Microsoft MSRC, Apple Security Research
- Higher payouts for critical targets
- Direct communication with engineering teams
- Often require NDA until patch

### 6.5 Ethical and Legal Considerations

```
LEGAL FRAMEWORK:
- Computer Fraud and Abuse Act (CFAA) -- US federal law
  Unauthorized access to computer systems is a felony
  Good faith security research defense added in 2022 DOJ policy

- DMCA Section 1201 -- Circumvention of technical protection measures
  Exemptions for good faith security research (rulemaking dependent)

- EU NIS2 Directive -- Member states should not criminalize good faith research
  But implementation varies by country

BEST PRACTICES:
1. Only test systems you own or have explicit authorization to test
2. Document authorization (scope letters, bug bounty terms)
3. Do not access, modify, or exfiltrate data beyond what is necessary
4. Report findings promptly to affected parties
5. Do not threaten or extort vendors
6. Follow coordinated disclosure timelines
7. Consider hiring a lawyer familiar with computer security law
8. If in doubt about legality → DO NOT PROCEED → get legal advice
```
---
## 7. CVSS Scoring Methodology

### 7.1 CVSS v3.1

**Base Score metrics:**

```
ATTACK VECTOR (AV):          How the attacker reaches the vulnerability
  Network (N)                 Remotely exploitable via network (most severe)
  Adjacent (A)                Requires adjacent network access (same LAN)
  Local (L)                   Requires local access (logged in user)
  Physical (P)                Requires physical access to device

ATTACK COMPLEXITY (AC):       Conditions beyond attacker's control
  Low (L)                     No special conditions required
  High (H)                    Requires specific configuration, race condition, etc.

PRIVILEGES REQUIRED (PR):     Authentication level needed
  None (N)                    No authentication required (most severe)
  Low (L)                     Requires basic user privileges
  High (H)                    Requires admin/privileged access

USER INTERACTION (UI):        Does the victim need to do something?
  None (N)                    No user interaction (most severe)
  Required (R)                User must click link, open file, etc.

SCOPE (S):                    Can the impact cross security boundaries?
  Unchanged (U)               Impact limited to vulnerable component
  Changed (C)                 Impact extends beyond vulnerable component
                              (e.g., sandbox escape, VM escape)

CONFIDENTIALITY (C):          Impact on information disclosure
  None (N) | Low (L) | High (H)

INTEGRITY (I):                Impact on data modification
  None (N) | Low (L) | High (H)

AVAILABILITY (A):             Impact on service availability
  None (N) | Low (L) | High (H)
```

**Scoring examples:**

```
EXAMPLE 1: Remote Code Execution, no auth, no interaction
CVE-2026-20127 (Cisco SD-WAN Auth Bypass)
CVSS: 9.8 (AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H)
  - Network accessible
  - Low complexity (no special conditions)
  - No privileges required
  - No user interaction
  - Unchanged scope
  - Full CIA impact

EXAMPLE 2: Local privilege escalation
CVE-2026-21519 (Windows DWM Elevation)
CVSS: 7.8 (AV:L/AC:L/PR:L/UI:N/S:U/C:H/I:H/A:H)
  - Local access required (already on system)
  - Low complexity
  - Low privileges required (standard user)
  - No user interaction
  - Unchanged scope (stays within OS)
  - Full CIA impact (local scope)

EXAMPLE 3: XSS vulnerability requiring user click
CVE-2025-68461 (Roundcube XSS)
CVSS: 6.1 (AV:N/AC:L/PR:N/UI:R/S:C/C:L/I:L/A:N)
  - Network accessible
  - Low complexity
  - No authentication
  - User must interact (click link, view email)
  - Changed scope (XSS executes in victim's browser context)
  - Low confidentiality/integrity impact, no availability impact

EXAMPLE 4: Denial of Service, high complexity
CVSS: 5.9 (AV:N/AC:H/PR:N/UI:N/S:U/C:N/I:N/A:H)
  - Network accessible
  - High complexity (race condition, specific config needed)
  - No authentication
  - No user interaction
  - Only availability impact
```

### 7.2 CVSS v4.0

Released November 2023 by FIRST. Major changes from v3.1:

```
NEW IN CVSS v4.0:

1. SUPPLEMENTAL METRICS (informational, do not affect score)
   - Safety (S): Does exploitation affect human safety?
   - Automatable (AU): Can exploitation be automated?
   - Recovery (R): Can the system recover from exploitation?
   - Value Density (V): How many resources are affected per exploit?
   - Vulnerability Response Effort (RE): How much effort to remediate?
   - Provider Urgency (U): Vendor's urgency assessment

2. RENAMED/REFINED METRICS
   - Attack Requirements (AT) replaces Attack Complexity (AC)
     More precisely captures pre-conditions needed
   - User Interaction refined: None, Passive, Active
     Passive = viewing content; Active = clicking/typing

3. IMPACT METRICS split by vulnerability vs. subsequent systems
   - Vulnerable System Impact (VC, VI, VA)
   - Subsequent System Impact (SC, SI, SA)
   Replaces the Scope metric from v3.1

4. MULTIPLE SCORING CONTEXTS
   - CVSS-B: Base score only
   - CVSS-BT: Base + Threat (exploit maturity)
   - CVSS-BE: Base + Environmental (org-specific modifications)
   - CVSS-BTE: All three combined

SCORING EXAMPLE (CVSS v4.0):
CVSS:4.0/AV:N/AC:L/AT:N/PR:N/UI:N/VC:H/VI:H/VA:H/SC:N/SI:N/SA:N
Score: 9.3 (Critical)
```

**Key improvement**: CVSS v4.0 better distinguishes between vulnerabilities
with identical v3.1 scores by separating vulnerable system and subsequent
system impact, and by refining attack complexity and user interaction.

### 7.3 CVSS Limitations and Misuse

```
COMMON MISUSE:
1. Using CVSS as sole prioritization metric
   → CVSS does not measure exploitation likelihood (use EPSS)
2. Ignoring Temporal and Environmental metrics
   → Base score alone overestimates many vulnerabilities
3. Treating CVSS as a risk score
   → CVSS is severity, not risk. Risk = likelihood × impact × context
4. Requiring CVSS ≥ 7 for remediation
   → Some low-CVSS vulns are actively exploited (and vice versa)

BETTER APPROACH:
Combine CVSS (severity) + EPSS (exploitation likelihood) + CISA KEV
(known exploitation) + business context (asset criticality) for
risk-based prioritization. See Section 12 on SSVC.
```
---
## 8. Exploit Mitigation Bypass

### 8.1 ASLR Bypass via Information Leak

```
ASLR BYPASS TECHNIQUES:

1. DIRECT INFORMATION LEAK
   - OOB read to disclose pointers on heap/stack
   - Format string (%p, %x) to leak stack values
   - Uninitialized memory disclosure (pointer residue)
   - Type confusion to read pointer field as data

2. SIDE-CHANNEL BYPASS
   - Cache timing (Spectre-class) to infer addresses
   - KASLR bypass via prefetch timing
   - TSX-based ASLR bypass (transactional memory abort timing)
   - Branch predictor side channels

3. PARTIAL OVERWRITE
   - Overwrite only low 12 bits of a pointer (page offset is not randomized)
   - 16-bit partial overwrite: 1/4096 success rate (brute-forceable)
   - Works when ASLR only randomizes high bits

4. RELATIVE ADDRESSING
   - Bug gives relative read/write (e.g., array OOB by known offset)
   - Target adjacent data structures without knowing absolute addresses
   - Common in V8/browser exploitation

5. ASLR ENTROPY LIMITATIONS
   - 32-bit systems: typically 8-16 bits of entropy → brute-forceable
   - Some implementations have reduced entropy (alignment, region constraints)
   - Fork-based servers: child inherits parent's ASLR layout → retry after crash

6. JIT SPRAYING
   - Spray JIT-compiled code containing controlled constants
   - Constants interpreted as instructions at offset +1 or +2
   - JIT code is executable → bypass DEP
   - Predictable JIT allocation addresses bypass ASLR
   - Mostly mitigated in modern JIT engines (random NOP insertion, constant blinding)

PROJECT ZERO (2025-2026): Demonstrated KASLR defeat without information leaks
using linear mapping techniques. Significant because it eliminates the need
for a separate info leak bug in kernel exploit chains.
```

### 8.2 DEP/NX Bypass via ROP

```
DEP/NX BYPASS:

PROBLEM: Stack and heap are non-executable → cannot inject and run shellcode

SOLUTION 1: RETURN-ORIENTED PROGRAMMING (ROP)
- Chain existing code gadgets (ending in ret) from executable sections
- Build Turing-complete computation from gadgets
- See Section 4.3 for detailed ROP explanation

SOLUTION 2: RETURN-TO-LIBC
- Overwrite return address with libc function (system, execve)
- Simpler than full ROP but limited to available function arguments
- Modern variant: one_gadget (find libc addresses that directly spawn shell)

SOLUTION 3: MAKE MEMORY EXECUTABLE
- Call mprotect/VirtualProtect to change page permissions
- Set stack/heap as executable, then jump to shellcode
- Requires gadgets or function call to mprotect

SOLUTION 4: JIT CODE REUSE
- Write shellcode as JIT-compiled constants
- JIT pages are RWX (or W→X with toggle)
- May need to trigger JIT compilation to place constants

SOLUTION 5: SIGRETURN-ORIENTED PROGRAMMING (SROP)
- Abuse sigreturn to set all registers at once
- Single gadget (sigreturn syscall) plus fake signal frame
- Sets RSP, RIP, and all other registers in one operation
```

### 8.3 CFI/CET Bypass

```
CONTROL FLOW INTEGRITY (CFI) BYPASS:

WHAT CFI ENFORCES:
- Indirect calls must target valid function entry points
- Returns must match corresponding call sites
- Forward-edge (calls) and backward-edge (returns) protection

INTEL CET (Control-flow Enforcement Technology):
- Shadow Stack: Hardware-enforced return address integrity
  Return address pushed to both regular stack and shadow stack
Ret instruction compares both → fault if mismatch
- Indirect Branch Tracking (IBT): ENDBRANCH instruction required
At valid indirect call/jump targets

BYPASS APPROACHES:

1. COOP (Counterfeit Object-Oriented Programming)
   - Chain virtual method calls (all valid CFI targets)
   - Corrupt vtable to point to different but valid methods
   - Each method performs partial operation → chain for full effect
   - Stays within CFI-allowed call targets

2. LEGITIMATE FUNCTION CHAINING
   - Call only functions that CFI considers valid targets
   - Chain legitimate function calls to achieve arbitrary computation
   - Example: call malloc → call memcpy → call system
   - Each call is valid under CFI, but sequence is malicious

3. DATA-ONLY ATTACKS
   - Modify non-control data that influences program behavior
   - Change variables (authentication flags, file paths, sizes)
   - Never corrupt code pointers → CFI is irrelevant
   - Example: overwrite "is_admin = 0" → "is_admin = 1"

4. SHADOW STACK BYPASS (CET-specific)
   - Pivot shadow stack pointer (if writable)
   - Race condition during signal handling
   - WRMSR to modify shadow stack base (kernel exploit)
   - Some implementations use software shadow stacks (weaker)

5. EXCEPTION HANDLING ABUSE
   - Corrupt exception handler records
   - Trigger exception to redirect to controlled handler
   - Some CFI implementations don't cover exception paths
```

### 8.4 Stack Canary Bypass

```
STACK CANARY BYPASS:

1. INFORMATION LEAK
   - Leak canary via format string (%p at correct offset)
   - OOB read to read canary from stack
   - Uninitialized stack variable disclosure

2. CANARY BRUTE-FORCE (fork-based servers)
   - Fork preserves parent's canary value
   - After crash, child is restarted with SAME canary
   - Brute-force byte by byte: 256 * 8 = 2048 attempts for 64-bit

3. OVERWRITE WITHOUT HITTING CANARY
   - Overflow specific variables without reaching canary
   - Use write-what-where primitive that skips canary
   - Array index overflow (write to specific offset, not sequential)

4. THREAD STACK CANARY
   - Canary stored in TLS (Thread Local Storage)
   - If TLS is writable via overflow → overwrite canary check value
   - Match overwritten canary to overwritten check → pass validation

5. STRUCTURED EXCEPTION HANDLER (SEH) OVERWRITE (Windows)
   - Overflow SEH record instead of return address
   - SEH record is further from buffer → may not be canary-protected
   - Trigger exception → SEH handler called with attacker's address
```
---
## 9. Kernel Exploitation

### 9.1 Linux Kernel Exploitation

#### Attack Surface

```
LINUX KERNEL ATTACK SURFACE:

SYSCALL INTERFACE
├── 300+ syscalls (x86_64)
├── ioctl handlers (driver-specific, huge surface)
├── setsockopt/getsockopt (network protocol options)
├── Netfilter hooks (packet processing)
└── BPF verifier (eBPF programs)

FILE SYSTEMS
├── VFS layer
├── Individual FS implementations (ext4, btrfs, FUSE)
├── File operation handlers
└── Mount namespace interactions

NETWORK STACK
├── Protocol implementations (TCP, UDP, SCTP, DCCP)
├── Netfilter/nftables
├── Network device drivers
├── Socket operations
└── Packet parsing (L2-L4)

DEVICE DRIVERS
├── Character/block devices
├── USB drivers (large attack surface via USB)
├── GPU drivers (DRM/DRI)
├── Bluetooth stack
└── Input devices

NAMESPACES/CGROUPS
├── User namespace privilege boundaries
├── Container escape vectors
├── Namespace creation/management
└── Cgroup escape paths
```

#### Common Kernel Vulnerability Types

```
USE-AFTER-FREE:
- Most common exploitable kernel vulnerability class
- Race conditions in reference counting
- Object freed while another thread holds reference
- Exploited via heap spray to replace freed object

EXAMPLE: CVE-2025-38236 (Linux kernel MSG_OOB UAF)
- UAF in socket MSG_OOB handling
- Enables Chrome sandbox to kernel exploitation
- Freed socket buffer replaced with controlled data
- Demonstrates: browser exploit → kernel exploit chain

OUT-OF-BOUNDS ACCESS:
- Array index not validated against bounds
- Integer overflow in size calculation
- Off-by-one in loop termination

NULL POINTER DEREFERENCE:
- Kernel dereferences NULL pointer
- If user can map page 0 (mmap_min_addr=0) → code execution
- Modern kernels set mmap_min_addr=65536 → mostly DoS only
- But: userfaultfd can sometimes be leveraged

RACE CONDITIONS:
- TOCTOU in file operations
- Double-fetch from userspace (kernel reads user memory twice)
- Concurrent syscall interactions
- Timer/interrupt handler races

TYPE CONFUSION:
- Generic pointer cast to wrong type
- Union member access mismatch
- Netfilter expression type confusion
```

#### Linux Kernel Exploitation Techniques

```
PRIVILEGE ESCALATION STRATEGY:

1. ARBITRARY READ/WRITE PRIMITIVE
   From vulnerability → build read/write primitives
   UAF → heap spray → overlapping object → type confusion → R/W

2. LOCATE KERNEL STRUCTURES (bypassing KASLR)
   - Leak kernel text address from /proc/kallsyms (if readable)
   - Side-channel (prefetch timing, cache timing)
   - Kernel pointer leak via unprivileged interfaces
   - Linear mapping technique (Project Zero, 2025)

3. OVERWRITE CREDENTIALS
   Target: task_struct->cred
   - Find current task's cred structure
   - Overwrite uid/gid/euid/egid to 0
   - Current process is now root

   Alternative: modprobe_path
   - Overwrite modprobe_path to point to attacker script
   - Trigger unknown binary format execution
   - Kernel executes attacker script as root

4. NAMESPACE ESCAPE (container breakout)
   - Overwrite task_struct->nsproxy
   - Point to init_nsproxy (host namespace)
   - Process now operates in host namespace

COMMON EXPLOITATION PRIMITIVES:
Msg_msg SPRAY:
- msgsnd() allocates kmalloc objects of controlled size
- msgrcv() reads back data
- Overlap freed object with msg_msg → OOB read/write
- Versatile primitive for heap shaping
Pipe_buffer SPRAY:
- pipe() + write() creates pipe_buffer objects
- pipe_buffer contains function pointer (ops)
- Replace freed object with pipe_buffer → function pointer control
- DirtyPipe (CVE-2022-0847) was a pipe_buffer vulnerability

USERFAULTFD TECHNIQUE:
- Register userfaultfd handler on memory page
- Kernel copies from userspace → triggers page fault
- Handler pauses kernel mid-copy (extends race window)
- Manipulate kernel state while kernel is paused
- Note: Unprivileged userfaultfd restricted in recent kernels
```

### 9.2 Windows Kernel Exploitation

#### Windows Kernel Attack Surface

```
WINDOWS KERNEL ATTACK SURFACE:

WIN32K (window manager subsystem)
├── Huge legacy codebase (20+ years)
├── Highest vulnerability density in Windows kernel
├── Accessible from user mode via syscalls
├── Complex callback mechanism to user mode
├── GDI objects, windows, menus, cursors
└── Multiple CVEs every Patch Tuesday

NTOSKRNL (core kernel)
├── Object manager
├── Memory manager
├── I/O manager
├── Registry
├── Security reference monitor
└── Process/thread management

DRIVERS
├── Network drivers (NDIS, TDI, WFP)
├── File system drivers (NTFS, ReFS, SMB)
├── USB drivers
├── Print spooler (historically vulnerable)
├── Graphics drivers (WDDM)
└── Third-party drivers (antivirus, system utilities)
```

#### Windows Kernel Exploitation Techniques

```
TOKEN STEALING:
1. Find EPROCESS of current process
2. Find EPROCESS of System process (PID 4)
3. Copy System token to current process
4. Current process now has SYSTEM privileges

_EPROCESS structure:
  +0x4b8  Token          ← Replace with System token
  +0x448  ActiveProcessLinks  ← Linked list to find System process
  +0x440  UniqueProcessId     ← PID to identify processes

ARBITRARY READ/WRITE TO SYSTEM:
// Pseudocode for token stealing
kd> dt _EPROCESS
   +0x440 UniqueProcessId : Ptr64 Void
   +0x448 ActiveProcessLinks : _LIST_ENTRY
   +0x4b8 Token : _EX_FAST_REF

1. Read ActiveProcessLinks, walk list to find PID 4
2. Read Token from System EPROCESS
3. Write Token to current EPROCESS

WIN32K EXPLOITATION:
- Win32k callbacks: Kernel calls back to user mode during operation
- User-mode callback can modify kernel state
- Kernel resumes with stale state → UAF, type confusion

EXAMPLE FLOW:
1. Create window/menu/GDI object
2. Register callback handler for specific operation
3. Trigger kernel operation that invokes callback
4. In callback: destroy/modify the object
5. Kernel returns from callback, uses stale pointer → UAF

RECENT: Windows Administrator Protection bypass (Project Zero, 2026)
- 9 bypasses found before GA release
- UIAccess implementation problems
- Connected to historical Shatter Attack vulnerabilities
- Demonstrates: even new Windows security features have bugs at launch
```

#### Windows Kernel Mitigations

```
SMEP (Supervisor Mode Execution Prevention):
- Kernel cannot execute user-mode pages
- Bypass: ROP in kernel space, or disable CR4.SMEP via write primitive

SMAP (Supervisor Mode Access Prevention):
- Kernel cannot read/write user-mode pages (without stac/clac)
- Bypass: Use kernel heap data instead of user-mode structures
KCFG (Kernel Control Flow Guard):
- Validates indirect call targets in kernel
- Bitmap marks valid targets
- Bypass: Call valid but useful targets (dispatch table entries)

VBS (Virtualization-Based Security):
- Hypervisor protects kernel integrity
- Credential Guard: Isolates LSASS secrets in secure enclave
- HVCI: Hypervisor-enforced code integrity
- Bypass: Much harder -- requires hypervisor escape

KDP (Kernel Data Protection):
- VBS-protected read-only kernel memory regions
- Prevents modification of critical kernel data
- Protects security-sensitive data structures
```
---
## 10. Mobile Vulnerability Research

### 10.1 Android Vulnerability Research

#### Android Attack Surface

```
ANDROID ATTACK SURFACE:

APPLICATION LAYER
├── Third-party apps (Play Store, sideloaded)
├── System apps (Settings, Phone, Messages)
├── WebView (embedded browser in apps)
├── Intent handling (inter-app communication)
├── Content providers (data sharing between apps)
├── Broadcast receivers (system event handling)
└── Deep links and URL scheme handlers

FRAMEWORK LAYER
├── ActivityManager, PackageManager
├── MediaServer (media parsing -- historically vulnerable)
├── SurfaceFlinger (display compositor)
├── Binder IPC (inter-process communication)
├── Bluetooth stack (Fluoride/Gabeldorsche)
└── NFC stack

NATIVE LAYER
├── bionic (libc)
├── Media codecs (Stagefright, hardware codecs)
├── Image processing (Skia, DNG, HEIF parsers)
├── Audio processing (Dolby, OEM-specific)
├── GPU drivers (Adreno, Mali, PowerVR)
└── Camera HAL

KERNEL LAYER
├── Linux kernel (vendor-modified)
├── Device-specific drivers
├── TEE (TrustZone) interface
├── Binder driver
└── ION/dmabuf memory allocator

BASEBAND/MODEM
├── Cellular protocol stack
├── SMS/MMS parsing
├── RIL (Radio Interface Layer)
└── Usually separate processor with own firmware
```

#### Notable Android Vulnerability Research

```
ZERO-CLICK EXPLOITS:

PIXEL 9 0-CLICK CHAIN (Project Zero, Jan 2026):
- Audio transcription feature as new attack surface
- Dolby decoder vulnerability (CVE-2025-54957)
- BigWave driver sandbox escape
- 0-click = no user interaction required
- Demonstrates: new features = new attack surface

ANDROID DNG EXPLOIT (Project Zero, Dec 2025):
- Samsung Quram image library vulnerability
- DNG (Digital Negative) image format processing
- One-shot image-based exploit
- Comparable to iOS FORCEDENTRY in approach
- 0-click via MMS or auto-downloaded media

STAGEFRIGHT (2015, foundational):
- Integer overflow in MPEG4 parsing → heap overflow
- Triggerable via MMS (auto-downloaded, auto-processed)
- Affected 950M+ devices
- Led to Android Security Bulletin monthly patch cycle
- Led to significant media parsing hardening
```

#### Android Security Architecture

```
ANDROID SECURITY LAYERS:

APPLICATION SANDBOX:
- Each app runs as separate Linux user
- SELinux mandatory access control
- Scoped storage (Android 10+)
- Permission model (runtime permissions)

VERIFIED BOOT:
- Boot chain verification (bootloader → kernel → system)
- dm-verity for system partition integrity
- Android Verified Boot (AVB) 2.0

ENCRYPTION:
- File-based encryption (FBE)
- Metadata encryption
- Hardware-backed keystore (StrongBox)

EXPLOIT MITIGATIONS:
- ASLR, DEP/NX, stack canaries (standard)
- MTE (Memory Tagging Extension) on supported hardware (Pixel 8+)
  Tags memory with 4-bit tag → detects UAF, overflow with ~93.75% probability
- CFI (Control Flow Integrity) in kernel and system components
- Scudo hardened allocator (replaces jemalloc)
- Integer overflow sanitization in media codecs
- Seccomp-bpf for syscall filtering
```

### 10.2 iOS Vulnerability Research

#### iOS Attack Surface

```
IOS ATTACK SURFACE:

APPLICATION LAYER
├── Third-party apps (App Store, MDM distributed)
├── System apps (iMessage, Safari, Mail, FaceTime)
├── WebKit (mandatory browser engine for all apps)
├── Extension points (widgets, share extensions, keyboards)
├── URL schemes and Universal Links
└── Push notification handling

FRAMEWORKS
├── ImageIO (image format parsing -- major target)
├── CoreGraphics (PDF rendering)
├── AVFoundation (media processing)
├── Bluetooth (CoreBluetooth)
├── WebKit (JavaScript, HTML, CSS processing)
├── Network.framework
└── CallKit, Messages framework

KERNEL (XNU)
├── Mach microkernel
├── BSD layer
├── IOKit (driver framework -- huge attack surface)
├── AppleAVE2 (video encoder)
├── AppleCLCD (display driver)
├── AGXAccelerator (GPU driver)
└── APFS file system

SECURE ENCLAVE (SEP)
├── Separate processor
├── Key management
├── Face ID / Touch ID
├── Secure boot chain
└── Rarely targeted (high difficulty, high value)

BASEBAND
├── Cellular modem firmware
├── Protocol stack (LTE, 5G)
├── SMS/MMS processing
└── RIL equivalent
```

#### iOS Exploitation Challenges

```
IOS MITIGATIONS:

PAC (Pointer Authentication Codes) -- ARM64e:
- Every pointer signed with cryptographic tag
- Forging pointer requires signing key (embedded in hardware)
- Function pointers, return addresses, ObjC method pointers signed
- Bypass requires: PAC signing gadget, or PAC oracle attack,
Or hardware fault injection

PPL (Page Protection Layer):
- Hypervisor-like protection for page tables
- Prevents arbitrary kernel read/write from modifying code pages
- Requires PPL bypass to modify kernel code

KTRR (Kernel Text Readonly Region) / CTRR:
- Hardware-enforced read-only kernel text
- Cannot be disabled once set at boot
- Even kernel exploit cannot modify kernel code

SEPOS / Secure Enclave:
- Separate processor with own encrypted memory
- Manages keys, biometrics, secure storage
- Compromise requires physical attack or SEP firmware exploit

AMFI (Apple Mobile File Integrity):
- Code signing enforcement
- Every executable must be signed by Apple or enterprise certificate
- Prevents running arbitrary code even with kernel exploit

SANDBOX:
- Mandatory sandboxing for all third-party apps
- Container-based file system isolation
- IPC restrictions via Sandbox profiles
- Network, hardware access gated by entitlements
```

#### Jailbreak Chains

```
JAILBREAK CHAIN STRUCTURE:

1. INITIAL ENTRY
   - Safari exploit (WebKit vulnerability)
   - Kernel exploit via malicious app (rare, App Store review)
   - Bootrom exploit (checkm8 -- hardware, unpatchable)
   - Profile/MDM exploit

2. SANDBOX ESCAPE
   - IPC vulnerability to escape app sandbox
   - Mach message handling bug
   - IOKit driver vulnerability

3. KERNEL EXPLOIT
   - UAF, type confusion, or race condition in XNU/IOKit
   - Privilege escalation to kernel level
   - May require PAC bypass

4. POST-EXPLOITATION
   - PPL bypass for kernel code modification
   - AMFI bypass for unsigned code execution
   - Remount root filesystem as read-write
   - Install package manager (Cydia, Sileo)

NOTABLE JAILBREAK EXPLOITS:
- checkm8 (2019): Bootrom exploit (A5-A11 chips). Unpatchable.
  Physical access required. Tethered (re-exploit on each reboot).
- FORCEDENTRY (2021): NSO Group. Zero-click iMessage exploit.
  Integer overflow in JBIG2 decompressor → built Turing-complete
Virtual machine inside the image parser.
- Operation Triangulation (2023): Kaspersky self-discovery.
  Four zero-days chained. iMessage → Safari → kernel → hardware
Register exploitation for undocumented hardware feature bypass.
```

#### iOS Coruna Exploit Kit (THN, Mar 2026)

- Combines 23 exploits across five chains
- Targets iOS 13 through 17.2.1
- Commercial spyware-grade toolkit
- Demonstrates: exploit stockpiling and chaining at industrial scale
---
## 11. Patch Analysis and 1-Day Exploit Development

### 11.1 Patch Diffing Methodology

**Purpose:** Analyze vendor patches to understand what vulnerability was fixed,
then develop exploits for the narrow window between patch release and deployment.

```
PATCH DIFFING WORKFLOW:

1. OBTAIN VERSIONS
   - Download pre-patch and post-patch binaries
   - Or: git diff between tagged versions (if open source)
   - Or: Decompile both versions and diff decompiled output

2. BINARY DIFFING (no source code)
   Tools: BinDiff, Diaphora, Ghidra Version Tracking

   BinDiff:
A. Analyze both binaries in IDA Pro → export IDB files
B. Run BinDiff comparison → generates similarity scores
C. Focus on functions with:
      - High similarity but not identical (changed functions)
      - New functions added in patched version
      - Functions removed or renamed
D. Examine changed basic blocks within modified functions

   Diaphora (IDA plugin):
A. Export both IDBs to SQLite
B. Compare databases
C. Categorize: Best matches, Partial matches, Unmatched
D. Focus on partial matches (high similarity, some changes)

3. SOURCE DIFFING (open source)
   ```bash
Git diff v1.2.3..v1.2.4 -- src/
   ```

   Focus on:
   - Added bounds checks → previous version lacked them
   - Changed integer types → previous version had overflow
   - Added NULL checks → previous version had NULL deref
   - Modified allocation sizes → previous version had heap overflow
   - Added input validation → previous version trusted input
   - Changed comparison operators → previous version had off-by-one

4. ROOT CAUSE ANALYSIS
   - Identify the exact vulnerability from the patch
   - Determine: what was the incorrect behavior?
   - Determine: how is the corrected behavior different?
   - Determine: can the incorrect behavior be triggered?

5. TRIGGER CONSTRUCTION
   - Build input that triggers the pre-patch vulnerable path
   - Verify trigger causes crash/misbehavior on unpatched version
   - Verify trigger is handled safely on patched version
```

### 11.2 Patch Analysis Example

```
HYPOTHETICAL PATCH ANALYSIS:

DIFF OUTPUT:
-  if (length > MAX_SIZE) return -1;
+  if (length > MAX_SIZE || length < 0) return -1;
Buffer = malloc(length);

ROOT CAUSE:
- length is signed integer, can be negative
- Pre-patch: only checked upper bound, not lower bound
- Negative length passes the > MAX_SIZE check
- malloc with negative (large unsigned) value may:
A. Allocate huge buffer (resource exhaustion)
B. Return NULL (NULL deref if unchecked)
C. Allocate small buffer (implementation-dependent, heap overflow)

TRIGGER:
- Send packet with length field set to -1 (0xFFFFFFFF)
- Reaches vulnerable malloc call
- Subsequent memcpy uses original negative value → heap overflow

EXPLOITATION:
- Heap overflow of controlled size
- Overwrite adjacent heap metadata or application data
- Chain into arbitrary write → code execution
```

### 11.3 1-Day Exploit Development Timeline

```
1-DAY EXPLOIT TIMELINE:

Day 0:     Patch Tuesday (or advisory released)
Day 0-1:   Security researchers begin patch diffing
Day 1-3:   Root cause identified from patch analysis
Day 3-7:   PoC developed for vulnerability
Day 7-14:  Weaponized exploit developed (reliability, evasion)
Day 14-30: Widespread exploitation begins (if not patched)
Day 30+:   Long-tail exploitation of unpatched systems

REALITY CHECK:
- Some researchers publish PoC within 24 hours of patch
- Sophisticated actors may have exploit within days
- Many organizations take 30-90 days to apply patches
- This gap (patch available but not deployed) is prime exploitation window
- CISA KEV "due dates" are typically 14-21 days for this reason
```

### 11.4 Microsoft Patch Tuesday Analysis Workflow

```
MONTHLY WORKFLOW:

1. PATCH RELEASE (Second Tuesday)
   - Review Microsoft Security Update Guide
   - Identify: zero-days (actively exploited), critical RCEs, public disclosures
   - Cross-reference with CISA KEV additions

2. PRIORITIZE ANALYSIS TARGETS
   - Actively exploited zero-days (immediate analysis)
   - Pre-auth remote code execution (highest impact)
   - Sandbox/VM escapes (privilege boundary crossing)
   - Elevation of privilege in Win32k (historically exploitable)

3. OBTAIN PATCHES
   - Windows Update downloads (extract from .msu/.cab)
   - Microsoft Update Catalog (manual download)
   - Compare before/after DLL versions

4. BINARY DIFF
   - Focus on: ntoskrnl.exe, win32kfull.sys, win32kbase.sys,
Clfs.sys, afd.sys, http.sys, smbserver.sys
   - Use BinDiff/Diaphora on changed binaries
   - Identify patched functions

5. ASSESS RISK
   - Exploitability: How easy to trigger? Reliable?
   - Impact: What access does exploitation provide?
   - Exposure: How many systems are vulnerable?
   - Detection: Can exploitation be detected?
```
---
## 12. Vulnerability Management at Scale

### 12.1 The Scale Problem

```
ENTERPRISE VULNERABILITY MANAGEMENT REALITY:

INPUT:
- ~290 new CVEs published per day (2025 pace)
- ~48,000 CVEs per year
- Average enterprise: 50,000-500,000 IT assets
- Each asset may have dozens of known vulnerabilities
- Total: potentially millions of vulnerability instances

RESOURCE CONSTRAINT:
- Typical patch team: 3-10 people
- Patch capacity: 100-500 patches per month (with testing)
- Gap: orders of magnitude more vulnerabilities than patch capacity

CONCLUSION: Patching everything is mathematically impossible.
Risk-based prioritization is not optional -- it is survival.
```

### 12.2 EPSS (Exploit Prediction Scoring System)

**Overview:** Data-driven ML model estimating probability a CVE will be
exploited in the wild within 30 days. Maintained by FIRST.

**Key distinction from CVSS:** CVSS = severity (how bad could it be).
EPSS = likelihood (how likely will it be exploited). These are orthogonal.

**Input features:**
- Vendor data (CPE from NVD)
- Vulnerability age
- Reference categorization
- Description analysis
- CWE classification
- CVSS vectors
- List presence (CISA KEV, Project Zero, ZDI)
- Public exploit availability (Exploit-DB, GitHub, Metasploit)
- Scanner coverage (Nuclei, sn1per, jaeles, Intrigue)
- Exploitation activity data from honeypots, IDS/IPS sensors

**Performance (at 10% threshold vs. CVSS >= 7):**

| Strategy | Coverage | Efficiency | Effort |
|---|---|---|---|
| EPSS >= 10% | 63.2% | 65.2% | 2.7% |
| CVSS >= 7 | 82.2% | 4.0% | 57.4% |

EPSS achieves 16x better efficiency at 1/21 the effort.

**Integration:**
```bash
# Query EPSS API
curl -s "https://api.first.org/data/v1/epss?cve=CVE-2026-1603"

# Prioritization logic
if epss >= 0.1:
Remediate_immediately()    # High exploitation probability
elif epss >= 0.01 and cvss >= 7.0:
Schedule_next_cycle()      # Moderate risk
elif in_cisa_kev:
Remediate_immediately()    # Known exploited regardless of score
else:
Monitor()                  # Low priority
```

### 12.3 SSVC (Stakeholder-Specific Vulnerability Categorization)

Developed by CERT/CC and CISA. Decision-tree approach to vulnerability
prioritization based on stakeholder context.

```
SSVC DECISION TREE:

INPUT VARIABLES:
1. EXPLOITATION STATUS
   - None: No evidence of exploitation
   - PoC: Public proof-of-concept exists
   - Active: Active exploitation observed

2. AUTOMATABLE
   - No: Requires manual intervention per-target
   - Yes: Can be exploited at scale via automation

3. TECHNICAL IMPACT
   - Partial: Limited access (read-only, non-privileged, partial data)
   - Total: Full system compromise (RCE, admin access, full data)

4. MISSION PREVALENCE (CISA version)
   - Minimal: Not in critical infrastructure
   - Support: Supports critical functions
   - Essential: Part of critical infrastructure or essential service

OUTPUT DECISIONS:
- Track: Monitor, no immediate action
- Track*: Close monitoring, plan remediation
- Attend: Remediate in next regular cycle
- Act: Remediate immediately, out-of-cycle if necessary

EXAMPLE:
CVE-2026-20127 (Cisco SD-WAN Auth Bypass)
- Exploitation: Active
- Automatable: Yes (network scan + exploit)
- Technical Impact: Total (full control)
- Mission Prevalence: Essential (network infrastructure)
→ DECISION: ACT (immediate remediation)

CVE-2026-21262 (SQL Server Priv Esc)
- Exploitation: None
- Automatable: No (requires authenticated access)
- Technical Impact: Partial (privilege escalation, not RCE)
- Mission Prevalence: Support
→ DECISION: Track* (monitor, plan remediation)
```

### 12.4 Risk-Based Vulnerability Management Framework

```
COMPREHENSIVE PRIORITIZATION:

TIER 1: IMMEDIATE (24-48 hours)
├── CISA KEV entries (known exploitation, federal mandate)
├── EPSS > 0.5 AND CVSS >= 7.0
├── Active zero-day for internet-facing systems
├── Authentication bypass on perimeter devices
└── SSVC decision: ACT

TIER 2: URGENT (1-2 weeks)
├── EPSS > 0.1
├── CVSS >= 9.0 (Critical) on exposed systems
├── Vulnerability in security product (EDR, firewall, VPN)
├── Public PoC available for exposed system
└── SSVC decision: ATTEND

TIER 3: PLANNED (next patch cycle, 30 days)
├── CVSS >= 7.0 AND EPSS > 0.01
├── Critical/High on internal-only systems
├── Vulnerability in non-production environment
└── SSVC decision: Track*

TIER 4: ACCEPTED RISK (monitor, 90+ days)
├── CVSS < 7.0 AND EPSS < 0.01
├── Compensating controls in place
├── System scheduled for decommission
└── SSVC decision: Track

ADDITIONAL FACTORS:
- Asset criticality (revenue-generating, customer-facing, regulated)
- Exposure (internet-facing vs. internal only)
- Compensating controls (WAF, IPS, network segmentation)
- Organizational risk tolerance
- Regulatory requirements (PCI DSS, HIPAA, NIS2)
```

### 12.5 Vulnerability Management Tooling

```
SCANNING:
- Tenable Nessus/SC: Network vulnerability scanning
- Qualys: Cloud-based vulnerability management
- Rapid7 InsightVM: Agent-based + network scanning
- OpenVAS/Greenbone: Open-source vulnerability scanning
- Nuclei: Template-based scanning (fast, accurate for web)

PRIORITIZATION:
- EPSS API (first.org): Exploitation probability scoring
- CISA KEV feed: Known exploited vulnerabilities
- vulnx/cvemap: CVE enrichment and correlation
- Kenna.VM (Cisco): ML-based risk scoring

PATCH MANAGEMENT:
- WSUS/SCCM/Intune: Microsoft ecosystem
- Ansible/Chef/Puppet: Configuration management
- JAMF: macOS/iOS fleet management
- Custom automation for Linux patching

ASSET MANAGEMENT:
- ServiceNow CMDB
- Axonius: Asset discovery and management
- runZero: Network discovery
- SBOM tools (Syft, cdxgen): Software inventory

INTEGRATION WORKFLOW:
Scanner → Enrich (EPSS, KEV, CVSS) → Prioritize (SSVC) →
Ticket (Jira, ServiceNow) → Patch → Verify → Close
```

### 12.6 Metrics for Vulnerability Management

```
KEY METRICS:

MEAN TIME TO REMEDIATE (MTTR):
- Tier 1 (Critical/KEV): Target < 48 hours
- Tier 2 (High): Target < 14 days
- Tier 3 (Medium): Target < 30 days
- Tier 4 (Low): Target < 90 days

COVERAGE METRICS:
- % of assets scanned in last 30 days (target: >95%)
- % of critical vulns remediated within SLA (target: >90%)
- Number of KEV vulns open past due date (target: 0)

RISK METRICS:
- Total risk score trending over time
- Risk score by business unit / asset group
- Mean EPSS of open vulnerabilities

OPERATIONAL METRICS:
- Scan frequency and freshness
- False positive rate
- Exception/acceptance rate
- Vulnerability reopen rate
```
---
## 13. Key Takeaways

1. **Source code audit and fuzzing are complementary**: Auditing finds logic bugs
And design flaws that fuzzing misses. Fuzzing finds edge cases and memory
Corruption that humans miss. Use both.

2. **Always fuzz with sanitizers**: ASan + UBSan minimum. A crash without sanitizer
Context is a crash report. A crash with ASan is a bug report with root cause.

3. **EPSS over CVSS for prioritization**: CVSS tells you severity. EPSS tells you
Urgency. Combine both: prioritize high-EPSS vulns first, then high-CVSS.

4. **Variant analysis multiplies ROI**: Every bug you find is a template for
Finding more bugs. Systematize the pattern and sweep the codebase.

5. **Exploit chains are the norm**: Modern exploitation requires chaining
Multiple bugs (info leak + ASLR bypass + code execution + sandbox escape).
   Each mitigation raises the bar but does not make exploitation impossible.

6. **Binary analysis scales with tooling**: Ghidra, IDA, angr, and Frida provide
Overlapping capabilities. Choose based on task and invest in automation.

7. **Browser exploitation is a multi-bug discipline**: Renderer + sandbox escape
Minimum. V8 sandbox adds a third layer. Each layer requires separate research.

8. **Kernel exploitation targets change**: Linux msg_msg/pipe_buffer sprays,
   Windows Win32k callbacks -- techniques evolve with mitigations. Stay current.

9. **Patch analysis is time-sensitive**: The window between patch release and
Deployment is prime exploitation territory. Automate patch diffing.

10. **Prioritization frameworks save organizations**: SSVC + EPSS + KEV provides
A defensible, evidence-based prioritization strategy that scales.

11. **Disclosure timelines matter**: 90 days is industry standard. Coordinate
With vendors. But enforce deadlines -- indefinite silence enables indefinite risk.

12. **Mobile research requires specialized knowledge**: PAC, PPL, AMFI, SEP on iOS;
    MTE, TEE, verified boot on Android. Platform-specific mitigations define what
Is exploitable.
---
*Last updated: 2026-03-15*
*NERF Training Module -- Vulnerability Research Deep Dive*
