Generated banner for Audit Context Building
Generated logo for Audit Context Building

Audit Context Building

Trail of BitsOfficialPublished by Trail of Bits

  • Skill
  • Research and analysis
  • Security
  • CC-BY-SA-4.0
  • Medium risk

From the author

Understand a codebase before looking for bugs in it - what each function assumes, what it guarantees, and what it depends on elsewhere. Use when starting an audit, threat model, or architecture review on unfamiliar code, and before any vulnerability-hunting pass.
— the description by Trail of Bits

AutoGineer summary

Written by AutoGineer from the skill’s own files, not by the author

Audit Context Building is a preparatory workflow designed to establish a comprehensive understanding of an unfamiliar codebase. By mapping out function-level assumptions, guarantees, and cross-function dependencies, it creates a structured dossier that serves as the foundation for subsequent vulnerability hunting. It explicitly separates the context-gathering phase from the bug-finding phase to ensure that security assessments are based on a complete, documented understanding of the system's logic rather than premature assumptions.

What it does

  • Analyzes function-level assumptions, guarantees, and dependencies.
  • Generates a central dossier and individual function records.
  • Identifies critical gaps where code relies on unverified assumptions.
  • Documents open questions and areas of ambiguity within the codebase.
  • Maps cross-function rules and reachability paths.
  • Provides a standardized format for auditing diverse targets like C, Solidity, or web services.

When to use it

  • At the start of a security audit, threat model, or architecture review.
  • When working with an unfamiliar codebase.
  • When previous audit attempts failed due to a lack of system-wide understanding.
  • Before performing any vulnerability-hunting or exploit-development tasks.

Advantages

  • Prevents premature or inaccurate vulnerability reporting.
  • Highlights 'nothing found' assumptions that are prime targets for security research.
  • Creates a shared, objective map of the system for the audit team.
  • Ensures that complex code paths are traced thoroughly rather than guessed.

Usage examples

“Run the audit context building workflow on the src/auth directory.”
The agent will analyze the functions in the specified directory, generating a dossier and individual function reports detailing assumptions and dependencies.
“Analyze the single function verify_signature in crypto.c using the context builder.”
The agent will perform a focused analysis of that specific function, returning a structured record of its internal logic and external requirements.

Install

  1. Download the skill as a ZIP:

    https://autogineer.com/agent-skills/trailofbits/audit-context-building/download
  2. Unzip it into the cross-client skills folder of your project:

    mkdir -p .agents/skills && unzip audit-context-building.zip -d .agents/skills

Documentation by Trail of Bits

Audit Context Building

Build understanding, not verdicts. This runs before anyone hunts for bugs, and feeds that work.

When to Use

At the start of an audit, a threat model, or an architecture review, when the code is unfamiliar. Also when an earlier pass produced findings nobody could judge, because no one had mapped out how the system fits together.

When NOT to Use

Do not name vulnerabilities, suggest fixes, write proofs-of-concept, or rate severity. Those belong to the hunting phase, which runs next and with the whole picture in hand. When the code counts on something and nothing checks it, record that plainly and move on — whether it matters is decided later.

Not worth the tokens on code you already understand.

Do not analyze in this context

The analysis is long, and this context needs to survive to use it. Dispatch it:

  • A codebase, or more than one function — run /audit-context-building:audit-context <path>. It orients, analyzes each function in its own subagent, and writes audit-context/DOSSIER.md plus one file per function under audit-context/functions/. Only compact records return here.

  • A single function — dispatch the audit-context-building:function-analyzer agent at it. It writes its prose to disk and returns a record.

Then work from what comes back: the index, the unenforced assumptions, the open questions. Read a function's file when you need its detail.

The workflow is what enforces this, not this text: a subagent bound to a return schema cannot return prose. Treat this section as routing, and route.

What comes back, and how to read it

Each record lists what must always be true (with the line that shows it), what the function takes on faith (with whatever establishes it), which functions it calls and what it needs from each, and anything still unclear. The dossier adds the rules that span several functions, who can reach what, and where the complicated parts cluster.

Two things matter more than the rest:

  • Assumptions marked nothing found. The code counts on something being true and nothing anywhere makes it true. This is the most useful thing to hand the hunting phase.

  • The open questions. An honest list of what is still unclear beats a confident answer that turns out to be wrong. Carry them forward instead of closing them out.

Where two records disagree, both are quoted rather than quietly reconciled. That is a fact about the code, not a flaw in the analysis.

The format

ANALYSIS_FORMAT.md defines it, and FUNCTION_MICRO_ANALYSIS_EXAMPLE.md works through examples in C and Solidity. Read them when extending this plugin or deciding whether a record can be trusted.

The format is the same whatever the target. What changes is what fills each slot, and what counts as a call you cannot see inside. DOMAIN_NOTES.md maps that across smart contracts, C and C++, decompiled firmware, and web services — read it when the target is not plain source code.

The rule that matters most: follow the calls. Whether a function is correct usually depends on something another function does, and you cannot see that from the caller alone. A limit looks enforced because the value came back from a function whose name suggests it was checked. So read the function being called, follow every path through it rather than only the one that succeeds, and say what makes each assumption true. When nothing does, use those words: nothing found. Every claim cites a line, or becomes an open question.

Files

resources/FUNCTION_MICRO_ANALYSIS_EXAMPLE.md

Worked Example

A complete per-function analysis. The subject is C; the format is language-neutral, and the notes at the end cover what changes for contract code.

The point of this example is the callee. session_acquire looks safe read on its own, and the analysis only becomes accurate once session_lookup has been read.


session_acquire in src/session.c (L112-L138)

// L112
int session_acquire(uint32_t id, struct session **out) {
    struct session *s = session_lookup(id);      // L113
    if (!s)                                       // L114
        return -ENOENT;
    s->refcount++;                                // L116
    *out = s;                                     // L117
    return 0;
}

Purpose: Hands a caller a borrowed reference to a live session and records that the borrow happened, so the session is not freed underneath it. Every caller that later calls session_release is paired with this function; the refcount discipline of the whole session table rests on that pairing.

Inputs & Assumptions:

  • id (uint32_t): session identifier. Trust: untrusted — reaches this from the request parser at src/proto.c:L88 without validation.

  • out (struct session **): caller-provided storage for the result. Trust: trusted (internal callers only, per the caller list below).

  • Implicit: the global session table g_sessions (src/session.c:L31) and the lock protecting it.

  • Precondition: out is non-NULL. Nothing in this function establishes it and nothing checks it; both callers pass the address of a local (src/proto.c:L94, src/admin.c:L51).

  • Precondition: the caller holds g_session_lock. Established by the callers, not here — see Open Questions.

Outputs & Effects:

  • Returns 0 on success, -ENOENT when no session matches.

  • State write: increments s->refcount (L116).

  • State write: *out on the success path only. On the error path *out is left untouched (L114), so a caller that does not check the return value reads whatever was in its local.

  • No external interactions, no events.

  • Postcondition on success: the session's refcount is one higher and the caller owes a matching session_release.

Block-by-Block:

// L113
struct session *s = session_lookup(id);
  • What: Resolves the untrusted id to a session pointer.

  • Why here: Nothing can proceed without the lookup, and it is the only place id is consumed.

  • Assumes: session_lookup returns NULL rather than a stale pointer for an expired session.

  • Establishes: nothing on its own — see the callee analysis below, which is where this gets interesting.

  • Depended on by: L114 and L116 both.

// L114-L115
if (!s)
    return -ENOENT;
  • What: Rejects a lookup miss.

  • Why here: Guards the dereference at L116.

  • Assumes: NULL is the only failure representation session_lookup uses.

  • Establishes: s != NULL for the remainder of the function.

  • Depended on by: L116, L117.

// L116-L117
s->refcount++;
*out = s;
  • What: Records the borrow and publishes the pointer.

  • Why here: After the NULL guard; the increment precedes publication so the caller never holds a pointer that has not been counted.

  • Assumes: the caller holds g_session_lock, since refcount++ is not atomic (refcount is a plain int at src/session.h:L22).

  • Establishes: the borrow is accounted for.

  • Depended on by: every subsequent session_release.

Cross-Function Dependencies:

  • Callee session_lookup (internal, src/session.c:L94-L110): read in full. It walks g_sessions and returns the matching entry. Two properties matter here and neither is visible from session_acquire:

    1. It compares s->id == id (L102) but does not check s->state. An entry in state SESSION_CLOSING (set at L204 of session_close, which does not remove the entry from the table until L211) still matches. So session_acquire can take a reference to a session that is mid-teardown. session_acquire reads as though liveness were established; it is established nowhere.

    2. It returns NULL only when the walk falls off the end (L109). The expiry check at L104 continues past expired entries rather than deleting them, so expiry is enforced only on the lookup path — an entry already borrowed by another caller stays reachable through that caller's pointer.

  • Callers: proto_handle_request (src/proto.c:L94) — takes g_session_lock at L91, so the locking precondition holds. admin_dump_session (src/admin.c:L51) — no lock acquisition anywhere in the function; the increment at L116 races. That path assumes a precondition nothing establishes.

  • Shared state: g_sessions with session_lookup, session_close, session_reap. s->refcount with session_release.

  • Invariant coupling: the table's central invariant — every entry's refcount equals the number of outstanding borrows — holds only if every acquire is under the lock. One of the two callers breaks that.

Open Questions:

  • unclear; need to inspect whether g_session_lock is documented as a caller precondition anywhere. Nothing in session.h states it, and only one of two callers honors it.

  • unclear; need to inspect session_reap (src/reap.c) to know whether it can free an entry whose refcount is non-zero. That decides whether the SESSION_CLOSING window above is reachable in practice.


What this example shows

The SESSION_CLOSING observation and the unlocked-caller observation are both invisible from session_acquire alone. Reading only the subject function, session_lookup returning non-NULL reads as though it established liveness. Reading the callee shows it establishes identity and nothing more.

Both are recorded as unenforced assumptions with the line that should have enforced them. Neither is called a use-after-free or a race condition, neither gets a severity, and no fix is proposed — the hunting phase makes those calls with the whole system model in front of it.

Note also what the record does not do: there is no invariant invented to reach a count, and blocks that do one thing get one line each.


The same shape in Solidity

The format does not change between domains; see DOMAIN_NOTES.md for the full mapping. This abbreviated record shows the contract idioms in place, and the same callee trap in a different dialect.

// L61
function withdraw(uint256 amount) external {
    require(_debit(msg.sender, amount), "insufficient");   // L62
    (bool ok, ) = msg.sender.call{value: amount}("");      // L63
    require(ok, "transfer failed");                        // L64
    totalDeposits -= amount;                               // L65
}

Inputs & Assumptions:

  • amount (uint256): user-specified. Trust: untrusted.

  • Implicit: msg.sender, balanceOf[msg.sender] (L12), hasCreditLine[msg.sender] (L13).

  • Precondition: the caller's balance covers amount. Established by _debit, and only on one of its two paths — see below.

Outputs & Effects:

  • Storage writes: balanceOf[msg.sender] inside _debit (L48, L52); totalDeposits at L65.

  • External interaction: msg.sender.call{value: amount} (L63) — value transfer to an arbitrary address.

  • No event emitted on withdrawal. Off-chain accounting cannot observe this path.

Block-by-Block (L62-L65):

  • What: debits the balance, sends the ether, then decrements the running total.

  • Why here: the debit precedes the transfer, which reads as checks-effects-interactions.

  • Assumes: _debit returning true means the balance covered the amount.

  • Establishes: nothing the later lines can rely on — totalDeposits at L65 lands after the external call at L63, so it is not in effect during re-entry.

Cross-Function Dependencies:

  • Callee _debit (internal, L44-L54): read in full. Two paths, and they do not agree.

    • Default path (L50-L52): if (balanceOf[account] < amount) return false; then subtracts. The bound holds.

    • Credit-line path (L46-L49): when hasCreditLine[account] is set, it subtracts inside an unchecked block and returns true without comparing balance to amount. For those accounts the caller's precondition is established by nothing, and the subtraction wraps instead of reverting.

  • Invariant coupling: sum(balanceOf) == totalDeposits is the contract's central invariant. It is maintained on the default path and not on the credit-line path.

Open Questions:

  • unclear; need to inspect who can set hasCreditLine and whether it is ever cleared (L13 declares it; no setter appears in this file).

Note what the record does not say: it does not call L63 a reentrancy vulnerability or the unchecked block an integer underflow, and it proposes no fix. It says where each precondition is established, and names the one that is established nowhere. The hunting phase takes it from there.

Requirements and compatibility

Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta

“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.

Needs: Declares allowed tools

Security

What our scanner noticed· Medium risk

  • Zero-width Unicode characters

A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.

Attribution and licence

Published by
Trail of Bits
Publisher
Trail of Bits (Official)
Source
trailofbits/skills · plugins/audit-context-building/skills/audit-context-building · commit e4dd0bb
Licence
Creative Commons Attribution-ShareAlike 4.0 International (redistribution allowed)
  • LICENSE (added by AutoGineer from LICENSE)
  • ATTRIBUTION.md (written by AutoGineer)
Synced

AutoGineer is not affiliated with or endorsed by Trail of Bits or Trail of Bits.

Download ZIP

The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download audit-context-building.zip