Skip to main content
Be Bitwise

Pattern-Based Auditing

Source Code Auditing · VR Foundations track

9 min read

In this module

Searching for Known Danger Signs

Source-sink analysis and taint tracking follow data flows. Pattern-based auditing doesn't bother — it just searches for code patterns known to be associated with vulnerabilities. Faster than full data flow analysis, and ruthlessly good at finding the bugs experienced developers know to avoid but that less careful code still contains.

Grep-Based Searching

The simplest form of pattern-based auditing is searching for dangerous function calls:

bash
# Find potentially dangerous C functions
grep -rn "strcpy\|strcat\|sprintf\|gets\|scanf" src/ --include="*.c"
# Find potential format string vulnerabilities
# (printf family called with a variable as the format string)
grep -rn "printf(\s*[a-zA-Z_]" src/ --include="*.c"
# Find potential command injection
grep -rn "system\|popen\|exec[lv]" src/ --include="*.c"
# Find malloc results, with the two lines after each,
# so you can see whether the pointer gets checked
grep -rn -A2 "=\s*malloc(" src/ --include="*.c"

Grep is blunt but fast. It floods you with false positives, but experienced auditors learn to scan the noise and pull out signal. It misses things too: the malloc search only finds results assigned on the same line, and two lines of context won't show a check that comes later or lives in a helper. Filtering the output with grep -v for if or NULL is tempting but worse, because it throws away lines like if (n > 0) p = malloc(n); where nothing checks p. The goal is modest: find the obvious bugs before lunch.

Semgrep for Structural Patterns

Semgrep improves on grep by understanding code structure. Instead of matching text patterns, Semgrep matches abstract syntax tree (AST) patterns, so it understands function calls, variable scope, and control flow:

yaml
# semgrep rule: find memcpy with unchecked size from network
rules:
- id: unchecked-memcpy-size
patterns:
- pattern: memcpy($DST, $SRC, $SIZE)
# size tested by an enclosing if
- pattern-not-inside: |
if (<... $SIZE ...>) $BODY;
# or by an earlier guard that bails out
- pattern-not-inside: |
if (<... $SIZE ...>) return ...;
...
message: "memcpy called with potentially unchecked size argument"
severity: WARNING
languages: [c]

This rule finds memcpy calls whose size argument isn't tested either by an enclosing if or by an earlier if (...) return guard. <... $SIZE ...> matches any condition that mentions the size, with or without braces around the body. It is much more precise than grep because it understands the code's structure, though it still trusts any test of $SIZE, including a wrong one like if (len > 64) memcpy(...). Test a rule like this against a few known-good and known-bad snippets before you believe its silence.

bash
# Run semgrep with a custom rule
semgrep --config my-rules.yaml src/
# Use the C rules from the Semgrep registry
semgrep --config "p/c" src/

Semgrep's community rules include hundreds of patterns for common vulnerabilities across many languages. The C pack is much smaller than those for languages like Python or JavaScript, so treat it as a starting point and expect to write your own rules for the patterns your target cares about.

Grep vs. Semgrep

Use grep for quick, broad searches when you want to see all instances of a function name. Use Semgrep when you need structural awareness - when the vulnerability pattern involves relationships between code elements (like a missing check before a dangerous call). Semgrep takes more setup but produces far fewer false positives.

Common Vulnerability Patterns

Beyond specific dangerous functions, experienced auditors recognise structural patterns associated with vulnerabilities:

Unchecked return values - when functions that can fail (malloc, open, read) have their return values ignored, the program proceeds with invalid state:

c
// VULNERABLE: malloc can return NULL
char *buf = malloc(user_size);
memcpy(buf, data, user_size); // NULL deref or heap corruption if malloc failed
// SAFE: check the return value
char *buf = malloc(user_size);
if (buf == NULL) return -1;
memcpy(buf, data, user_size);

TOCTOU (Time-of-Check to Time-of-Use) - a race condition where a resource's state changes between checking and using it:

c
// VULNERABLE: race between access() and open()
if (access("/tmp/config", R_OK) == 0) {
// Attacker replaces /tmp/config with symlink HERE
fd = open("/tmp/config", O_RDONLY); // Opens attacker's file
read(fd, buf, sizeof(buf));
}
// SAFER: open first, then check
fd = open("/tmp/config", O_RDONLY | O_NOFOLLOW);
if (fd >= 0) {
// fstat(fd, ...) to verify properties on the opened file
}

Double-free - freeing the same memory twice corrupts the heap allocator's metadata:

c
// VULNERABLE: error path frees, then normal path frees again
void process(struct request *req) {
if (validate(req) < 0) {
free(req->data);
// Missing return here!
}
// ... more processing ...
free(req->data); // Double-free if validate() failed
}

Integer overflow in size calculations - when arithmetic on sizes wraps around, allocations are undersized:

c
// VULNERABLE: if width * height overflows, allocation is tiny
size_t size = width * height * 4; // RGB + alpha, 4 bytes per pixel
char *image = malloc(size);
for (int i = 0; i < width * height; i++) {
image[i * 4] = pixels[i].r; // Writes past allocation
// ...
}
// SAFER: check for overflow before allocation
if (width > SIZE_MAX / height / 4) return -1; // Would overflow
size_t size = width * height * 4;

The wrap is easiest to see with the 32-bit size fields most file formats use. Predict what size comes out as for a 65536 × 16384 image before you run it.

Try itPredict the size first, then try 65536 x 16385 and see the allocation come out tiny but non-zero, which is the dangerous case.
C (GCC 9.2.0)

Off-by-one in loops - loops that iterate one time too many or too few, often in string handling:

c
// VULNERABLE: writes null terminator past buffer end
char buf[256];
for (int i = 0; i <= 256; i++) { // Should be i < 256
buf[i] = src[i];
if (src[i] == '\0') break;
}
// Also vulnerable: fence-post error
for (int i = 0; i < len; i++) {
buf[i] = src[i];
}
buf[len] = '\0'; // Off-by-one if buf has exactly len bytes allocated

Test yourself on the patterns. Each snippet has one bug; name it and the fix before you open the answer.

1. char *line = malloc(strlen(s)); strcpy(line, s);

Off-by-one. strlen doesn't count the terminating NUL, so strcpy writes one byte past the allocation. Allocate strlen(s) + 1.

2. if (stat(path, &st) == 0 && st.st_uid == getuid()) { fd = open(path, O_WRONLY); ... }

TOCTOU. The file checked by stat may not be the file opened a moment later; an attacker can swap in a symlink between the two. Open first, then fstat the descriptor you actually hold.

3. int n = hdr->count; struct item *items = malloc(n * sizeof(struct item));

Integer overflow (and a signed count). A large count wraps the multiplication, and a negative one becomes a huge size_t. Check n is positive and below SIZE_MAX / sizeof(struct item), or use calloc(n, sizeof(struct item)), which does the overflow check for you.

4. snprintf(msg, sizeof msg, user_name);

Format string. The user controls the format, so %x leaks the stack and %n writes to memory. Use snprintf(msg, sizeof msg, "%s", user_name). The grep for printf(\s*[a-zA-Z_] above does flag this line, but only by accident: it matches every snprintf(buf, ...), safe or not, because it takes the buffer for the format.

Variant Analysis

Variant analysis is one of the most productive techniques in vulnerability research. Find one bug, then hunt for the same pattern everywhere else. Developers tend to repeat themselves — same idioms, copy-pasted code, shared wrong assumptions.

The process:

  1. Find one vulnerability - through manual review, fuzzing, or any other method
  2. Abstract the pattern - identify what makes the code vulnerable. Is it a missing bounds check on a specific field? An unchecked return value from a specific function? A misuse of a particular API?
  3. Search for variants - use grep, Semgrep, or CodeQL to find all instances of the same pattern
  4. Verify each match - manually confirm whether each match is actually vulnerable

For example, if you discover that a PNG parser does not validate chunk length before using it in memcpy, search for all chunk parsers in the same codebase. If the developers made the mistake once, they likely made it in the IHDR chunk parser, the IDAT chunk parser, the tEXt chunk parser, and so on.

bash
# After finding a missing bounds check in handle_IHDR:
# Search for similar patterns in all chunk handlers
grep -n "memcpy.*chunk.*len\|memcpy.*->length" src/png_parser.c

Google Project Zero has found dozens of variants of the same vulnerability pattern in major software projects through disciplined variant analysis. It is one of the highest-yield techniques in the vulnerability researcher's toolkit.

Building Your Own Pattern Library

Over time, build a personal library of vulnerability patterns. Each new bug earns an entry: the code pattern that caused it, a Semgrep or grep rule that detects it, an example of vulnerable and fixed code, and the conditions required for exploitability.

This library compounds. New targets can be scanned against your accumulated knowledge in minutes, and patterns that look rare at first usually turn out to be scattered across codebases everywhere.

Automation Complements Manual Review

Pattern-based auditing is not a replacement for manual code review. It finds the obvious issues quickly, freeing your manual review time for the subtle, complex vulnerabilities that no pattern can capture - logic bugs, race conditions with unusual timing requirements, and vulnerabilities that span multiple subsystems. Use pattern matching to handle the routine work so your human analysis time goes to the hard problems.