Skip to main content
Be Bitwise

Taint Analysis

Source Code Auditing · VR Foundations track

6 min read

In this module

Formalizing Data Flow Tracking

In the previous lesson you traced data flows by reading code. Taint analysis puts that process on firmer ground: assign a "tainted" label to data from untrusted sources and track how it propagates through every operation the program performs. When tainted data reaches a security-sensitive sink, flag it.

You can do this manually — on paper, or just in your head while reading — or with automated tools. Either way, the conceptual machinery is the same.

Tainted vs. Untainted Data

Every piece of data in a program is either tainted (derived from untrusted input) or untainted (generated internally or from trusted sources):

  • Data from recv(), read() on a network socket, argv, getenv(), or file reads is tainted at the source
  • Constants, compile-time values, and data generated by the program itself are untainted
  • Results of operations on tainted data inherit the taint

The rule is non-negotiable: taint propagates. Add a tainted value to an untainted one — result is tainted. Copy tainted bytes into a buffer — that region is tainted. The label follows the data through every transformation until a validation check sanitises it (more on that below).

Taint Propagation Rules

How taint propagates depends on the operation:

Assignment and copy: taint transfers directly. y = x makes y tainted if x is tainted. memcpy(dst, src, n) taints the destination bytes.

Arithmetic: the result of any arithmetic involving a tainted operand is tainted. result = tainted_len + 4 produces a tainted result. This is crucial because integer overflow vulnerabilities often involve arithmetic on attacker-controlled lengths.

Comparison: the result of comparing tainted data is itself tainted, and the comparison alone doesn't untaint the value being compared. Branching on that result creates an implicit flow: anything assigned inside the branch depends on the tainted value through control flow rather than data flow. Whether that counts as taint is a policy choice (see Taint Policies below). The exception is a comparison that acts as a validation check, which is how sanitisation works.

String operations: strcat(dst, tainted_src) taints the appended region of dst. strlen(tainted_string) produces a tainted length.

Array indexing: array[tainted_index] uses tainted data to compute an address. If the index is not bounds-checked, this is a potential out-of-bounds access.

c
// Taint propagation example
char buf[1024];
int n = recv(sockfd, buf, sizeof(buf), 0); // buf is TAINTED, n is TAINTED
struct header *hdr = (struct header *)buf; // hdr fields are TAINTED
uint32_t payload_len = hdr->length; // TAINTED (copied from tainted data)
uint32_t total = payload_len + HEADER_SIZE; // TAINTED (arithmetic on tainted)
char *out = malloc(total); // total is TAINTED -> potential issue
memcpy(out, buf + HEADER_SIZE, payload_len); // payload_len is TAINTED -> SINK

In this trace, taint flows from recv() through every variable that touches the received data, all the way to the malloc() size and memcpy() length. Both sinks consume tainted values without validation.

Taint Sanitisation

Taint is removed (sanitised) when data passes through a validation check that constrains it to safe values. If payload_len is checked against a maximum before use (if (payload_len > MAX_PAYLOAD) return ERROR;), the taint is conditionally removed - in the code path after the check, payload_len is known to be within bounds. This is how proper input validation works: it narrows the range of tainted data to safe values before it reaches sinks.

Here's the same code with that check added on line 5. Step through it and mark each variable as you'd mark it on paper. Then look hard at the last step, because the sanitiser covers one sink and not the other.

Tracking taint line by line

char buf[1024];
int n = recv(sockfd, buf, sizeof(buf), 0);
struct header *hdr = (struct header *)buf;
uint32_t payload_len = hdr->length;
if (payload_len > MAX_PAYLOAD) return ERROR;
uint32_t total = payload_len + HEADER_SIZE;
char *out = malloc(total);
memcpy(out, buf + HEADER_SIZE, payload_len);
buf = untainted
buf is a local array. Nothing has been written to it yet, so there's no taint.
Step 1/8

Taint Policies

Different taint policies define what counts as tainted and how strictly taint propagates:

Conservative (overtainting) - mark everything derived from untrusted input as tainted, even through indirect relationships. This catches more potential bugs but produces more false positives. If a tainted value is used in a branch condition, all code in the branch is considered taint-influenced.

Precise - only propagate taint through direct data dependencies. A branch condition influenced by tainted data does not taint variables modified inside the branch (unless those variables are also directly derived from tainted data). This reduces false positives but may miss implicit flows.

Undertainting - only track explicit, direct taint propagation. This misses many real vulnerabilities but is computationally cheap. Useful for a quick first pass.

For manual auditing, a precise policy works well. Track data that is directly derived from untrusted input and flag when it reaches a sink. You can always widen the scope if you suspect implicit flows.

Automated Taint Analysis Tools

Several tools perform taint analysis automatically:

Triton is a dynamic binary analysis framework that provides symbolic execution and taint analysis capabilities. It works at the instruction level, tracking how each register and memory location is influenced by input bytes:

python
# Conceptual Triton taint analysis
from triton import *
ctx = TritonContext(ARCH.X86_64)
# Mark input buffer as tainted
for i in range(input_size):
ctx.taintMemory(MemoryAccess(input_addr + i, 1))
# Execute instructions and track taint
ctx.processing(instruction)
# Check if a register is tainted
if ctx.isRegisterTainted(ctx.registers.rdi):
print("Argument to function is tainted!")

libdft (DataFlow Tracking) instruments x86 binaries using Intel PIN to perform byte-level taint tracking. It can identify exactly which input bytes influence each memory location and register at any point during execution.

PANDA (Platform for Architecture-Neutral Dynamic Analysis) records full system execution and provides taint analysis across the entire system, including kernel code. This is powerful for analysing how data flows across process boundaries and through system calls.

CodeQL provides static taint analysis through its data flow library. You write a configuration module that defines sources and sinks, and CodeQL's engine finds all paths between them. This uses the current module-based API (DataFlow::ConfigSig and TaintTracking::Global), which replaced the older TaintTracking::Configuration class:

text
/**
* @kind path-problem
*/
import cpp
import semmle.code.cpp.dataflow.new.TaintTracking
import semmle.code.cpp.security.FlowSources
module MemcpySizeConfig implements DataFlow::ConfigSig {
predicate isSource(DataFlow::Node source) { source instanceof RemoteFlowSource }
predicate isSink(DataFlow::Node sink) {
exists(FunctionCall fc |
fc.getTarget().hasGlobalName("memcpy") and
sink.asExpr() = fc.getArgument(2)
)
}
}
module MemcpySizeFlow = TaintTracking::Global<MemcpySizeConfig>;
import MemcpySizeFlow::PathGraph
from MemcpySizeFlow::PathNode source, MemcpySizeFlow::PathNode sink
where MemcpySizeFlow::flowPath(source, sink)
select sink.getNode(), source, sink, "Tainted data from $@ reaches a memcpy size argument.",
source.getNode(), "this source"

An isBarrier predicate in the same module is where you'd tell CodeQL which checks count as sanitisation.

Manual Taint Tracking on Paper

For smaller codebases or focused audits, manual taint tracking is often the most effective approach. Here is the process:

  1. Identify sources - list all functions that introduce untrusted data
  2. Mark variables - as you read code, annotate variables as tainted (T) or untainted (U)
  3. Track propagation - when tainted data is assigned, copied, or used in arithmetic, propagate the label
  4. Flag sinks - when a tainted variable reaches a dangerous function, mark it as a potential vulnerability
  5. Check for sanitisation - look backward from the flagged sink for bounds checks, validation, or escaping

A simple annotation format works well:

c
int handle_request(int sock) {
char buf[512]; // U (uninitialized)
int n = recv(sock, buf, 512, 0); // buf=T, n=T
uint16_t msg_type = *(uint16_t*)buf; // T (from buf)
uint32_t msg_len = *(uint32_t*)(buf+2); // T (from buf)
if (msg_type != MSG_DATA) return -1; // msg_type checked but msg_len NOT
char *payload = malloc(msg_len); // T -> malloc (potential int overflow?)
memcpy(payload, buf + 6, msg_len); // T -> memcpy len (POTENTIAL VULN)
// msg_len could exceed (n - 6), reading past received data
}

This manual annotation makes the vulnerability immediately visible: msg_len is tainted, never validated against n, and reaches both malloc and memcpy as a size argument.

Taint Analysis Limitations

No taint analysis approach is perfect:

Implicit flows - when tainted data influences control flow but not the data itself, basic taint analysis misses it. If if (tainted_flag) { x = secret; }, the value of x depends on the tainted flag through control flow, not data flow.

Over-tainting - in practice, almost all data in a network service is influenced by network input at some level. Conservative taint analysis can mark everything as tainted, making the results useless. Good taint policies and sanitisation recognition are essential.

Sanitisation recognition - automated tools struggle to recognise when validation is sufficient. A human auditor can determine that if (len <= MAX && len >= 0) adequately sanitizes a length for a subsequent memcpy, but automated tools may not understand the relationship between the check and the sink.

Despite these limitations, taint analysis — manual or automated — is one of the highest-yield techniques for finding real vulnerabilities in real code. It swaps the unanswerable question "is this code safe?" for a concrete one: "does untrusted data reach this sink?"