Auditing Real Code
Source Code Auditing · VR Foundations track
9 min read
In this module
Putting It All Together
Three techniques now in hand: source-sink analysis, taint tracking, pattern matching. In practice you use all three together, guided by the attack surface analysis from Introduction to Vulnerability Research. This lesson walks through auditing a real C codebase, from initial reconnaissance to documented findings.
Prioritizing Hot Spots
In a codebase with hundreds of thousands of lines, you cannot read everything. Prioritise the code most likely to contain exploitable vulnerabilities:
Network-facing parsers — code that processes data directly from the network. Find the first function that touches data after recv() or accept(). Parsing logic is notoriously hard to get right, and this is where attacker-controlled data enters the system.
File format parsers — same idea but triggered by opening files. Image decoders, document parsers, archive extractors, config readers: all high-priority.
Privilege boundary code — functions running with elevated privileges (setuid, kernel modules, system services). Bugs here have maximum blast radius.
Memory allocation patterns — code that derives sizes from input and allocates accordingly. Integer overflows in those calculations produce undersized allocations and heap overflows downstream.
Error handling paths — developers focus on the happy path. Error paths are tested less, reviewed less, and that's where double-frees, missing cleanup, and uninitialised variables hide.
# Find error handling code that might have cleanup issuesgrep -n "goto\s*err\|goto\s*fail\|goto\s*cleanup" src/*.c
# Find functions with complex error paths (many goto labels)grep -c "goto\s" src/*.c | sort -t: -k2 -rn | head -20Code Review Checklists
Experienced auditors work through mental or written checklists at each sink and trust boundary. Here is a practical checklist for C/C++ code:
At every buffer operation:
- Is the destination buffer size known?
- Is the copy/write length validated against the buffer size?
- Could integer arithmetic overflow when computing the length?
- Is the null terminator accounted for in string operations?
At every memory allocation:
- Is the return value checked for NULL?
- Could the size calculation overflow?
- Is the allocated memory properly freed on all code paths (including errors)?
- Could the memory be freed twice?
At every user-controlled branch:
- Does the code handle all possible input values, or just the expected ones?
- Is there a default case for switch statements on untrusted input?
- Could unexpected input cause infinite loops or excessive resource consumption?
At every file operation:
- Are symbolic links followed unsafely?
- Is there a TOCTOU window between checking and using the file?
- Are file permissions checked before reading sensitive data?
At every inter-process communication point:
- Is the sender authenticated?
- Are message sizes validated?
- Could a malicious peer cause resource exhaustion?
Using CodeQL for Automated Queries
CodeQL treats your source code as a database and lets you write queries that find patterns too complex for grep or even Semgrep. Here is a practical workflow:
# Create a CodeQL database from a C project.# C/C++ extraction watches the build, so give it the build command.codeql database create codeql-db --language=cpp --source-root=. \ --command="make -j8"
# Run the standard buffer-overflow queries (CWE-120) against itcodeql database analyze codeql-db \ codeql/cpp-queries:Security/CWE/CWE-120 --download \ --format=sarif-latest --output=results.sarifCodeQL's pre-built queries cover many CWE categories:
- CWE-120: Buffer overflow from external input
- CWE-190: Integer overflow
- CWE-416: Use after free
- CWE-476: NULL pointer dereference
- CWE-78: OS command injection
You can also write custom queries. For example, to find all places where a network read result is used as a size without bounds checking:
/** * @name Network data used as buffer size without bounds check * @kind path-problem */
import cppimport semmle.code.cpp.dataflow.new.TaintTrackingimport semmle.code.cpp.security.FlowSources
module NetworkReadToSizeConfig implements DataFlow::ConfigSig { // Data CodeQL models as arriving from the network (recv and friends) predicate isSource(DataFlow::Node source) { source instanceof RemoteFlowSource }
predicate isSink(DataFlow::Node sink) { exists(FunctionCall fc | fc.getTarget().hasGlobalName(["malloc", "realloc", "calloc"]) and sink.asExpr() = fc.getAnArgument() ) }}
module NetworkReadToSize = TaintTracking::Global<NetworkReadToSizeConfig>;import NetworkReadToSize::PathGraph
from NetworkReadToSize::PathNode source, NetworkReadToSize::PathNode sinkwhere NetworkReadToSize::flowPath(source, sink)select sink.getNode(), source, sink, "Allocation size comes from $@.", source.getNode(), "network data"This uses the module-based API (DataFlow::ConfigSig with TaintTracking::Global). Older tutorials subclass TaintTracking::Configuration, which is deprecated.
CodeQL truly shines for variant analysis. When you find a vulnerability manually, write a CodeQL query that captures the pattern and run it against the entire codebase. This finds every instance of the same pattern in seconds, even across millions of lines of code. Several major vulnerability discoveries (including some in Chrome and the Linux kernel) came from CodeQL variant analysis after an initial manual find.
Walking Through a Real Audit
Let us walk through auditing a hypothetical network service that accepts messages from clients. The service reads a message header containing a type field and a length field, then reads the message body.
Step 1: Identify the entry point.
Find where network data first enters the program. Search for accept(), recv(), or the framework's connection handler:
void handle_connection(int client_fd) { struct msg_header hdr; if (read_exact(client_fd, &hdr, sizeof(hdr)) < 0) return;
char *body = malloc(hdr.body_len); if (read_exact(client_fd, body, hdr.body_len) < 0) { free(body); return; }
dispatch_message(hdr.type, body, hdr.body_len); free(body);}Step 2: Apply taint analysis.
hdr is entirely tainted - both hdr.type and hdr.body_len come from the network. hdr.body_len flows directly into malloc() as a size argument and into read_exact() as a length argument.
Step 3: Check for vulnerabilities.
- What if
hdr.body_lenis 0?malloc(0)is implementation-defined - it may return NULL or a unique pointer. The subsequentread_exactwith length 0 is probably fine, butdispatch_messagewith a zero-length body might not handle it correctly. - What if
hdr.body_lenis very large (e.g., 4GB)? Whethermalloc()fails depends on the platform: on 64-bit Linux with memory overcommit it often succeeds, while on a 32-bit system or under a memory limit it returns NULL. The code checks for NULL... wait, it does not. Themallocreturn is assigned tobodybut never checked beforeread_exactuses it. Where the allocation fails, this is a NULL pointer dereference bug. - Is
hdr.body_lenvalidated against a reasonable maximum? No. This allows denial of service by forcing large allocations.
Step 4: Follow into dispatch_message.
void dispatch_message(uint16_t type, char *body, uint32_t len) { switch (type) { case MSG_LOGIN: handle_login(body, len); break; case MSG_DATA: handle_data(body, len); break; // No default case - unknown types silently ignored }}Step 5: Audit each handler.
void handle_login(char *body, uint32_t len) { char username[64]; char password[64];
// Extract null-terminated strings from body strncpy(username, body, 63); username[63] = '\0';
char *pass_start = body + strlen(body) + 1; strncpy(password, pass_start, 63); password[63] = '\0';
authenticate(username, password);}Finding: strlen(body) is called to find the password offset, but body might not contain a null terminator within len bytes. If the attacker sends a body with no null bytes, strlen() reads past the end of the allocated buffer. This is an out-of-bounds read that could leak heap memory or crash the service.
This is the kind of subtle bug that pattern-based searching alone would miss. It requires understanding the data flow and the assumptions the code makes about its input.
Case Studies of Source Audit Discoveries
Many high-profile vulnerabilities were found through source code auditing:
Heartbleed (CVE-2014-0160) was a missing bounds check in OpenSSL's heartbeat extension. The code trusted a length field from the network without verifying it against the actual received data length - a textbook source-sink analysis finding. The tainted length field from the TLS heartbeat request was used directly as the size argument to memcpy, allowing attackers to read up to 64KB of server memory per request.
Shellshock (CVE-2014-6271) was found by auditing how Bash processed environment variables. The source was environment variable values (attacker-controlled in CGI contexts), and the sink was Bash's function definition parser, which continued executing code beyond the function definition.
These cases show that even heavily-reviewed code in critical infrastructure carries bugs discoverable through systematic auditing. Source-sink analysis, taint tracking, pattern matching, tool-assisted querying — these are the exact techniques the researchers used. Nothing exotic.