TExcelTAD

Code Review, Taint Analysis, Semgrep and CodeQL

Fuzzing finds bugs on the paths it reaches. Reading code finds bugs on every path, including the ones no input generator would ever produce: an authorisation check missing on one endpoint, a length that is validated in one handler but not in its twin. Static analysis is the umbrella for both the human reading and the tools that reason about code without running it. This lesson covers the reviewer's heuristics, the idea of taint analysis that underlies most security tools, and the two query-based tools researchers use most, Semgrep and CodeQL.

Review heuristics

Experienced reviewers don't read code top to bottom. They follow the data and look for known shapes:

  • Start at the entry points from your attack-surface list: request handlers, file parsers, IPC methods, system calls.
  • Follow lengths and indices. Every length from input must be compared with every buffer it touches. Every index must be checked against the array it indexes, with the right signedness and type width.
  • Look for the twin. Code with a check in one place and a copy-pasted sibling without it (Variant Analysis).
  • Distrust conversions. int to size_t, 64-bit to 32-bit, string to number, path to canonical path: each is a place where two parts of the code disagree.
  • Read error paths. Cleanup after a failure (double free, use-after-free, half-initialised state) is tested far less than success.
  • Check the security decisions themselves. Who can call this? Is the check done before or after the action? Is it done on the same value that is used (time-of-check to time-of-use)?
  • Read the history. Past advisories and security commits show where the code was fragile.

Taint analysis: sources, sinks, sanitizers

Most security bugs have the same shape: data an attacker controls (source) reaches a dangerous operation (sink) without passing through something that makes it safe (sanitizer):

Bug class Source Sink Sanitizer
SQL injection request parameters execute(string) parameters (?), never string building
command injection request, file names os.system, popen an argument list, shlex.quote
path traversal file names from users open, send_file canonicalise + prefix check
buffer overflow length fields from files memcpy(dst, src, len) len <= sizeof dst

Taint analysis marks values from sources as tainted, propagates the mark through assignments, string operations and function calls, removes it at sanitizers, and reports tainted values that reach sinks. The example implements a deliberately small version with Python's ast module, for one function of a toy web handler: no branches, no aliasing, no calls into other functions. It runs in your browser:

python · try it yourself
import ast

CODE = '''
def export(request, db):
    name = request.args["name"]
    fmt = request.args.get("fmt", "csv")
    limit = int(request.args.get("limit", "10"))
    safe = shlex.quote(name)
    db.execute("SELECT * FROM t WHERE owner = ?", (name,))
    db.execute(f"SELECT * FROM t LIMIT {limit}")
    db.execute("SELECT * FROM t WHERE fmt = '" + fmt + "'")
    path = "/srv/exports/" + name
    data = open(path).read()
    os.system("gzip " + safe)
    os.system("convert --format " + fmt)
    return data
'''

SOURCES = {"request.args"}                       # attacker-controlled input
SANITIZERS = {"int", "shlex.quote"}               # make a value safe for its sink
SINKS = {"db.execute": 0, "os.system": 0, "open": 0}   # function -> dangerous argument index

def dotted(node):
    if isinstance(node, ast.Name):
        return node.id
    if isinstance(node, ast.Attribute):
        return dotted(node.value) + "." + node.attr
    if isinstance(node, (ast.Subscript, ast.Call)):
        return dotted(node.value if isinstance(node, ast.Subscript) else node.func)
    return ""

def tainted(node, env):
    """Does this expression carry attacker data? (No branches, no aliasing: a toy.)"""
    if isinstance(node, ast.Call):
        fn = dotted(node.func)
        if fn in SANITIZERS:
            return False
        if fn.startswith("request.args"):
            return True
        return any(tainted(a, env) for a in node.args)
    if isinstance(node, ast.Name):
        return env.get(node.id, False)
    if isinstance(node, (ast.Subscript, ast.Attribute)):
        return dotted(node).startswith(tuple(SOURCES)) or tainted(node.value, env)
    return any(tainted(c, env) for c in ast.iter_child_nodes(node))

env, findings = {}, []
for stmt in ast.parse(CODE).body[0].body:
    if isinstance(stmt, ast.Assign):
        env[stmt.targets[0].id] = tainted(stmt.value, env)
    for call in [n for n in ast.walk(stmt) if isinstance(n, ast.Call)]:
        fn = dotted(call.func)
        if fn in SINKS and call.args and tainted(call.args[SINKS[fn]], env):
            findings.append((stmt.lineno - 1, fn, ast.unparse(call.args[0])))

print("tainted variables:", sorted(v for v, t in env.items() if t))
for line, fn, arg in findings:
    print(f"line {line:2d}: tainted data reaches {fn}(): {arg}")
tainted variables: ['fmt', 'name', 'path']
line  8: tainted data reaches db.execute(): "SELECT * FROM t WHERE fmt = '" + fmt + "'"
line 10: tainted data reaches open(): path
line 12: tainted data reaches os.system(): 'convert --format ' + fmt

Three real findings, and four correct non-findings:

  • Line 8 builds SQL from fmt by concatenation: SQL injection (SQL Injection Prevention). Line 6 passes name as a parameter, so it is not reported; line 7 interpolates limit, but int() sanitised it.
  • Line 10 opens a path built from name: path traversal with name = "../../etc/passwd".
  • Line 12 passes fmt to a shell: command injection. Line 11 uses safe, quoted with shlex.quote, and is not reported.

Real tools add what the toy lacks: inter-procedural flow (taint through function calls and returns), field and alias tracking, branches and loops (flow sensitivity), library models (thousands of known sources, sinks and sanitizers), and path conditions. Each addition trades speed and noise against missed bugs.

Semgrep: patterns that look like code

Semgrep matches patterns written in the target language's own syntax, with metavariables ($X) and ellipses (...). It is fast, runs without building the code, and suits project-specific rules in CI. It also has a taint mode. The rules below are illustrative (not run here; check details against the current Semgrep documentation):

yaml
rules:
  - id: request-data-to-shell
    mode: taint
    languages: [python]
    severity: ERROR
    message: Request data reaches a shell command
    pattern-sources:
      - pattern: request.args[...]
      - pattern: request.args.get(...)
    pattern-sanitizers:
      - pattern: shlex.quote(...)
      - pattern: int(...)
    pattern-sinks:
      - pattern: os.system(...)

  - id: memcpy-into-fixed-buffer-unchecked
    languages: [c]
    severity: WARNING
    message: memcpy into fixed buffer $BUF with a length not compared to sizeof $BUF
    patterns:
      - pattern-inside: |
          char $BUF[$N];
          ...
      - pattern: memcpy($BUF, $SRC, $LEN);
      - pattern-not-inside: |
          if (<... $LEN > sizeof $BUF ...>) return ...;
          ...

The second rule would flag rec_name in the toy TLV parser and stop flagging it once the length check is added. Pattern rules are shallow (one function, syntactic), which makes them predictable and easy to tune.

CodeQL: code as a database

CodeQL compiles the code base (for C/C++ it normally observes a real build) into a relational database of the program: the syntax tree, the control-flow graph, data flow, types. Queries are written in QL, a declarative, object-oriented logic language, and its data-flow libraries do inter-procedural taint tracking. A sketch in the shape of a CodeQL C/C++ query (illustrative, not run):

text
import cpp

from FunctionCall call, LocalVariable buf
where call.getTarget().hasName("memcpy")
  and call.getArgument(0) = buf.getAnAccess()
  and buf.getType() instanceof ArrayType
  and not exists(RelationalOperation cmp |
        cmp.getAnOperand().(VariableAccess).getTarget() =
          call.getArgument(2).(VariableAccess).getTarget())
select call, "memcpy into fixed array " + buf.getName() + " with an unchecked length"

CodeQL is used by GitHub code scanning and by many security teams for variant analysis across large code bases: write the query once for a bug you understand, run it everywhere. Its licence allows free use on open-source code; check it before using it on closed code.

How static findings are detected, triaged and fixed

Static tools produce candidates. Each needs the same triage as a fuzzer crash: is the source really attacker-controlled, is there a sanitizer the tool does not know, is the path feasible? Good teams run a small set of high-precision rules as a blocking CI check, keep noisier rules for review, and add a rule for every bug class they have been bitten by. The fix for a true positive is the sanitizer at the right place (parameters, argument lists, canonicalise-then-check, bounds checks), and the rule stays in CI so the pattern cannot come back.

Pitfalls

  • False positives erode trust. A rule that cries wolf gets ignored or disabled. Tune or drop it.
  • False negatives are silent. "No findings" means "no findings by these rules", not "no bugs".
  • Sanitizers in the wrong context. HTML escaping does not make a value safe for SQL; shlex.quote does not make a path safe for open.
  • Reviewing only the diff. A change can make old code reachable; follow the data beyond the changed lines.

Practice

1. Add os.path.basename as a sanitizer for open only. Why must sanitizers be sink-specific?

basename removes directory parts, which prevents traversal for open, but does nothing against SQL or shell injection. A global sanitizer list would hide real findings; real tools tie sanitizers to sink kinds (Semgrep's taint labels, CodeQL's flow states).

2. Does the toy catch cmd = "x" if flag else fmt followed by os.system(cmd)? And the same with an if statement?

The conditional expression is caught: tainted() recurses into every child of the expression, so fmt taints cmd. The if statement version (if flag: / cmd = fmt) is missed, because the loop only records assignments at the top level of the function body. Handling statements inside branches, and merging the taint of both branches, is what flow-sensitive analysis adds.

3. Write the C review checklist item that would have caught both seeded TLV bugs.

"For every buffer access with an index or length derived from input: show the comparison with the buffer's size on every path, with < for indices and <= for lengths, and the type of both operands." rec_name has no comparison; rec_sum uses <= for an index.

Test yourself

In taint analysis, what is a sanitizer?

  1. A sanitizer build like ASan
  2. An operation that makes a tainted value safe for a particular kind of sink
  3. A source of data
  4. A test case

Why was line 6 (execute("... owner = ?", (name,))) not reported?

  1. name is not tainted
  2. name is passed as a query parameter, not built into the SQL string
  3. execute is not a sink
  4. The tool skipped it by mistake

What distinguishes CodeQL from Semgrep's pattern rules?

  1. CodeQL only runs on Python
  2. CodeQL builds a database of the program and supports inter-procedural data-flow queries
  3. Semgrep needs a build
  4. CodeQL has no false positives

A static tool reports zero findings. What can you conclude?

  1. The code is secure
  2. Its rules matched nothing; bugs outside the rules' reach remain possible
  3. The tool is broken
  4. Fuzzing is unnecessary