Berildocs GitHub

References

Vulnerability research

Finding a bug is a data-flow problem with a business question attached. The data-flow part asks whether attacker input reaches a dangerous operation without a correct check. The business part asks what happens when it does.

This guide covers the research side: attack surface, bug classes, source audit, binary audit, sanitizers, crash triage, exploitability, and the report. Exploitation steps live in exploit-development.md. Fuzzing steps live in fuzzing.md.

Rules of engagement#

  • Confirm the target is in scope and the test window is agreed.
  • Start with read-only behavior. Write only where the plan allows it.
  • Record every request, binary hash, and version.
  • Stop at the agreed proof. Do not pivot through production for fun.
  • Separate a crash from an exploit. A crash is a lead.
  • Date every claim. Software changes under you.

Attack surface map#

Before testing, list every place data enters and every place it lands.

Web and API#

  • Query, path, header, cookie, body, multipart, JSON, XML, GraphQL.
  • File upload, import, webhook, URL fetch, PDF and image render.
  • OAuth redirect, SAML assertion, JWT claim, session store.
  • Admin and tenant boundaries.
  • Background jobs fed by user data.
  • SDK and mobile-only endpoints.

Desktop#

  • File parsers, drag and drop, clipboard, deep links, protocol handlers.
  • Update channel and signature check.
  • Plugin and extension loader.
  • Local IPC: named pipes, Unix sockets, COM, DBus.
  • Privileged helper and setuid binary.
  • Browser embedding and WebView bridge.

Mobile#

  • Exported activities, services, receivers, providers.
  • Deep links and universal links.
  • WebView JavaScript bridge.
  • Shared preferences, keychain, keystore, local databases.
  • Background workers and push payloads.
  • Mobile API that trusts client headers.

Cloud and infrastructure#

  • Metadata service, instance role, IAM policy.
  • Public storage, queue, function URL, container registry.
  • Kubernetes API, service account, admission webhook.
  • CI runner, artifact store, deployment key.
  • Terraform state and secret manager.

Kernel and driver#

  • IOCTL buffers, METHOD_NEITHER user pointers, SystemBuffer sizes.
  • copy_from_user, copy_to_user, probe_for_read, probe_for_write.
  • IRP handling, cancel routines, object lifetimes.
  • Syscall argument parsing, netlink, io_uring, eBPF, userfaultfd.

Bug classes and the primitive#

ClassTypical root causePrimitive
Stack overflowUnbounded copy into fixed stack bufferReturn address or local variable control
Heap overflowWrong allocation size or off-by-oneAdjacent chunk metadata or object
Use after freeMissing refcount or stale pointerReallocation with controlled data
Double freeTwo owners release the same objectAllocator metadata corruption
Type confusionWrong cast or union tagField interpreted at wrong width or type
Integer bugOverflow, underflow, truncation in size mathSmall allocation, large copy
Format stringUser text passed as formatArbitrary read, then write
OOB readIndex without bounds checkMemory disclosure
RaceCheck and use without a lockState bypass, double spend
DeserializationTrusted object graph from inputCode execution or property injection
Path traversalUnsanitized path joinFile read or write outside root
SSRFServer fetches attacker URLInternal access, metadata
Auth bypassMissing or wrong identity checkHorizontal or vertical access
LogicWrong order, negative value, stale stateFinancial or access impact

The bug class suggests the primitive. The primitive suggests the impact. Work in that order.

Source audit#

Find the entry points#

# routes and handlers
rg -n "app\.(get|post|put|delete)|router\.|@GetMapping|@PostMapping|http\.HandleFunc" .

# file and network entry
rg -n "readFile|createReadStream|open\(|fopen|recv\(|read\(" .

# deserialization
rg -n "pickle\.loads|yaml\.load|unserialize|ObjectInputStream|JsonConvert|readObject" .

# process execution
rg -n "system\(|exec\(|popen|subprocess|child_process|Runtime\.exec|ProcessBuilder|Command::new" .

# templates
rg -n "render_template|Template\(|Handlebars|Mustache|Smarty|Twig|Jinja" .

# SQL
rg -n "query\(|execute\(|raw\(|createQuery|db\.Raw|sequelize\.query" .

Trace the data#

For each source, follow the variable:

  1. Which function receives it?
  2. Is it decoded, normalized, or parsed first?
  3. What size, length, or index is derived from it?
  4. Which check applies, and can it be skipped on another path?
  5. Where does it land: allocation, copy, query, file, command, template?
  6. Is there a second parser between the check and the sink?

A source-to-sink trace with no check is a candidate. A check on one path and no check on a sibling path is often the real bug.

Dangerous patterns by language#

  • C: strcpy, strcat, sprintf, gets, memcpy with a computed size, alloca, VLA, signed/unsigned mix.
  • C++: raw new[], std::copy into a fixed buffer, reinterpret_cast, virtual dispatch after free, iterator invalidation.
  • Python: pickle, yaml.load without SafeLoader, eval, exec, subprocess with shell=True, os.path.join with an absolute second argument.
  • Node: child_process.exec, eval, new Function, vm, path.join traversal, prototype pollution through lodash.merge.
  • PHP: include, unserialize, eval, preg_replace /e, type juggling with ==, variable variables.
  • Java: ObjectInputStream, XML parsers without external entity limits, expression languages, JDBC string concatenation.
  • Go: text/template with user data, exec.Command with a shell, InsecureSkipVerify, unchecked slice bounds.
  • Rust: unwrap on parser output, unsafe blocks, from_utf8_unchecked, integer casts with as.

Taint and data-flow tools#

semgrep --config auto .
codeql database create db --language=javascript --source=.
codeql database analyze db codeql/javascript-security --format=sarif-latest -o out.sarif
joern
weggli -r 'func $F($X) { $Y = $X; }' .

Semgrep is fast and rule-based. CodeQL builds a real data-flow graph but is slower. Joern and weggli are for querying syntax and call structure. None replace reading the code.

Binary audit#

When source is missing, use reverse-engineering.md. Focus on:

  • parsers and length fields;
  • allocation followed by copy;
  • signed comparisons on unsigned lengths;
  • bounds checks that use the wrong variable;
  • object lifetime around callbacks;
  • error paths that free twice or not at all.

A decompiler makes the code look safer than it is. Check the assembly at every size calculation.

Sanitizers#

Build with sanitizers when source is available.

clang -fsanitize=address,undefined -fno-omit-frame-pointer -g -O1 target.c -o target_asan
clang -fsanitize=memory -g -O1 target.c -o target_msan
clang -fsanitize=thread -g -O1 target.c -o target_tsan
SanitizerFindsCost
ASANHeap, stack, global OOB, UAF, double free2x to 3x slowdown
UBSANSigned overflow, shift, alignment, nullLow
MSANUninitialized readsNeeds full rebuild
TSANData races5x to 15x slowdown

ASAN options worth knowing:

export ASAN_OPTIONS=abort_on_error=1:detect_leaks=0:symbolize=1:strict_string_checks=1
export UBSAN_OPTIONS=print_stacktrace=1:halt_on_error=1

Crash triage#

A crash needs four answers: is it deterministic, is the faulting address controlled, is the instruction pointer controlled, and what mitigation stands in the way.

Linux#

gdb -q ./target_asan
(gdb) run crash.bin
(gdb) bt full
(gdb) info registers
(gdb) x/32gx $rsp
(gdb) p $_siginfo

Use rr record for non-deterministic crashes. Use CASR to classify and cluster:

casr-gdb -o crash.casrep -- ./target crash.bin
casr-cli crash.casrep
casr-cluster -d reports dedup
casr-cluster -c dedup clusters

Windows#

0:000> g
0:000> .exr -1
0:000> k
0:000> r
0:000> !analyze -v
0:000> .ttime

WinDbg TTD records the run. Rewind to the instruction before the fault and inspect the object.

Triage table#

ObservationMeaning
Fault address is 0x41414141Direct buffer control
Fault address is a small offset from a controlled pointerStruct field control
Instruction pointer is controlledLikely direct execution
Instruction pointer is a heap pointerNeed a fake vtable or JOP
Crash only with ASANLatent OOB, may still be exploitable
Crash only under loadRace
Crash in freeHeap metadata corruption
Crash in memcpy with a huge sizeInteger bug upstream

Deduplicate by stack hash and fault type before you spend time. CASR and afl-cmin help.

Minimize the input:

afl-tmin -i crash.bin -o min.bin -- ./target @@

Exploitability#

Exploitability is a chain of questions:

  1. Is the fault reachable from an untrusted source?
  2. Which bytes are controlled, at what width?
  3. Is there an information leak?
  4. Which mitigations are active?
  5. Is there a useful target: return address, vtable, function pointer, GOT, callback?
  6. Can the exploit repeat reliably?

If any answer is missing, the finding may still be valid but the severity is lower. Say that in the report.

Mitigations#

MitigationCheckBypass family
NX / DEPchecksec, PE NX_COMPAT, GNU_STACKROP, JOP, ret2libc
ASLR / PIEELF type, PE DYNAMIC_BASEInfo leak, partial overwrite, brute force
Stack canary__stack_chk_fail, /GSLeak, SEH overwrite, non-return target
RELROGNU_RELRO, BIND_NOWGOT if partial, else heap target
CFG / CETGUARD_CF, shadow stackJOP, call-preceded gadgets, data-only
Safe unlinking / MTEallocator version, Android targetAllocator-specific primitives
SMEP / SMAPcr4, kernel configROP to native_write_cr4, data-only

A mitigation check is not a finding on its own. It changes the severity and the exploit path.

Race conditions#

Prove the window, not only the odd result.

  1. Identify the invariant: one use, one balance, one approval.
  2. Map the check and the write. If they are separate, the window exists.
  3. Send parallel requests. Use a single-packet attack for HTTP/2.
  4. Count successes and compare with the intended limit.
  5. Repeat to show reliability.

Tools: Burp Turbo Intruder, a small asyncio script, wrk. For local binaries, rr and thread sanitizer.

Patch diffing#

Diff the vendor patch to find the missing check.

bindiff --primary old.idb --secondary new.idb --output diff.BinDiff
ghidriff old.bin new.bin -o diff.md
git log -p -- path/to/file

Read the changed branch. The fix usually names the bug: a length check, a null check, a lock, a copy bound.

Report#

A vulnerability report needs:

  • title with the primitive and the asset;
  • affected version and hash;
  • attacker starting position;
  • precondition and reachability;
  • minimal reproduction;
  • observed result and proof;
  • impact in business terms;
  • root cause with the code or address;
  • remediation;
  • CVSS and CWE only after the narrative.

Separate confirmed behavior from inference. A triager can rerun a request. A triager cannot rerun a guess.

Sources#

  • SnailSploit/Claude-Red bug identification, crash analysis, exploit development
  • trailofbits/skills audit and fuzzing skills
  • mukul975/anthropic-cybersecurity-skills vulnerability-class skills
  • OWASP WSTG and API Security Top 10
  • MITRE CWE and CAPEC
  • CASR documentation
  • Ghidra and Binary Ninja workflow docs