Skip to main content
Be Bitwise

Source & Sink Analysis

Source Code Auditing · VR Foundations track

8 min read

In this module

Following Data from Danger to Damage

In the previous module, you learned to map attack surfaces — identifying where untrusted data enters a program. Source-sink analysis takes that further: systematically tracing untrusted data from its entry point (the source) to the security-sensitive operation where it lands (the sink). No adequate validation between them? You've found a potential vulnerability.

This is the backbone of code auditing. Every buffer overflow, command injection, and SQL injection is a source-to-sink flow with a missing check somewhere in the middle.

What Are Sources?

A source is any point where attacker-controlled data enters the program. Sources represent the boundary between trusted and untrusted worlds. In C and C++ programs, common sources include:

Network input functions:

c
recv(sockfd, buffer, length, flags); // TCP data
recvfrom(sockfd, buffer, length, ...); // UDP data
read(sockfd, buffer, length); // Generic read from socket
SSL_read(ssl, buffer, length); // TLS-encrypted data

File input functions:

c
read(fd, buffer, length); // Read from file descriptor
fread(buffer, size, n, fp); // Read from FILE stream
fgets(buffer, size, fp); // Read line from FILE stream
mmap(NULL, length, PROT_READ, MAP_PRIVATE, fd, 0); // Memory-map file

Command-line and environment:

c
int main(int argc, char *argv[]); // argv entries are attacker-controlled
char *value = getenv("VARNAME"); // Environment variables

User input:

c
scanf("%s", buffer); // Read formatted input from stdin
gets(buffer); // Read line from stdin (never use this)

The rule is simple: any data originating outside the program's trust boundary is a source. Even data read from a file on disk qualifies if an attacker can influence that file's contents — shared directories, temp files, uploaded content, you name it.

What Are Sinks?

A sink is a function or operation where data is used in a security-sensitive way. If attacker-controlled data reaches a sink without proper validation, the result is typically a vulnerability. Sinks are categorised by the type of vulnerability they enable:

Memory corruption sinks:

c
memcpy(dst, src, len); // If len is attacker-controlled: buffer overflow
strcpy(dst, src); // No length limit: classic buffer overflow
sprintf(dst, fmt, ...); // No length limit on output
strcat(dst, src); // Appends without checking remaining space
memmove(dst, src, len); // Same risk as memcpy

Command execution sinks:

c
system(command); // Executes a shell command
execve(path, argv, envp); // Replaces process with new program
popen(command, mode); // Opens pipe to shell command

Format string sinks:

c
printf(user_string); // If user_string contains %x, %n: format string vuln
fprintf(fp, user_string); // Same risk
syslog(LOG_INFO, user_string); // Same risk

SQL/query sinks (in applications that use databases):

c
// String concatenation into SQL queries
snprintf(query, sizeof(query), "SELECT * FROM users WHERE name='%s'", username);
mysql_query(conn, query);
The Sink Determines the Bug Class

The type of sink determines the vulnerability class. Data reaching memcpy without a bounds check is a buffer overflow. The same data reaching system() is a command injection. The same data reaching a SQL query is SQL injection. Source-sink analysis is powerful because it finds all these bug classes with a single methodology - just map the flows and classify the sinks.

Tracing Data Flow

The challenge is bridging source to sink. In a small program, you can trace data flow linearly. In a real codebase, data passes through dozens of functions, gets copied into new variables, transformed, and stashed in structs before it gets anywhere near a dangerous operation.

Consider this simplified example:

c
// Source: read packet from network
int handle_packet(int sockfd) {
char raw[4096];
int n = recv(sockfd, raw, sizeof(raw), 0); // SOURCE
struct packet *pkt = parse_packet(raw, n);
if (pkt == NULL) return -1;
process_payload(pkt);
free(pkt);
return 0;
}
struct packet *parse_packet(char *data, int len) {
if (len < sizeof(struct header)) return NULL;
struct header *hdr = (struct header *)data;
// Allocate based on length field from packet (attacker-controlled!)
struct packet *pkt = malloc(sizeof(struct packet) + hdr->payload_len);
if (!pkt) return NULL;
// SINK: memcpy with attacker-controlled length
memcpy(pkt->payload, data + sizeof(struct header), hdr->payload_len);
return pkt;
}

The data flow here is: recv() (source) -> raw buffer -> parse_packet() -> hdr->payload_len extracted from attacker data -> used as length in memcpy() (sink). The vulnerability is that hdr->payload_len comes from the attacker and is used without checking that it does not exceed the actual received data length len. An attacker sends a packet with payload_len = 0xFFFFFFFF but only 100 bytes of actual data, causing a read past the end of raw. There's a second bug on the line before: sizeof(struct packet) + hdr->payload_len is computed in size_t, and where that's 32 bits, a payload_len near 0xFFFFFFFF wraps the sum to a tiny number. malloc then succeeds with a small block, and the memcpy writes far past it.

Drawn as hops, the missing check has an obvious home. It belongs on the last edge before the sink, where both values it needs (hdr->payload_len and len) are in scope:

The len < sizeof(struct header) test on the way in only proves the header is there. It says nothing about the payload the header claims to describe.

Identifying Missing Sanitisation

Between source and sink, there should be sanitisation - code that validates, constrains, or transforms the data to make it safe for the sink. Common sanitisation patterns include:

Bounds checking:

c
// Good: validates length before use
if (hdr->payload_len > len - sizeof(struct header)) {
return NULL; // Reject oversized payload
}
memcpy(pkt->payload, data + sizeof(struct header), hdr->payload_len);

Input validation:

c
// Good: validates content before passing to sink
if (!is_valid_hostname(user_input)) {
return ERROR;
}

Parameterised queries:

c
// Best: the query text and the data travel separately,
// so nothing in username can change the SQL
MYSQL_STMT *stmt = mysql_stmt_init(conn);
const char *sql = "SELECT * FROM users WHERE name = ?";
mysql_stmt_prepare(stmt, sql, strlen(sql));
unsigned long name_len = strlen(username);
MYSQL_BIND param;
memset(&param, 0, sizeof(param));
param.buffer_type = MYSQL_TYPE_STRING;
param.buffer = (char *)username;
param.buffer_length = name_len;
param.length = &name_len;
mysql_stmt_bind_param(stmt, &param);
mysql_stmt_execute(stmt);

Escaping/encoding is the fallback when you can't use a parameterised query:

c
// Escaping writes into a caller buffer of at least 2*len+1 bytes
char escaped[2 * MAX_NAME + 1];
mysql_real_escape_string(conn, escaped, username, strlen(username));
snprintf(query, sizeof(query), "SELECT * FROM users WHERE name='%s'", escaped);

Escaping only works if every call site remembers to do it, uses the connection's character set, and keeps the value inside quotes. When you see escaping in an audit, check all three; when you see a prepared statement, the SQL injection question mostly goes away.

When auditing, you are looking for source-to-sink paths where sanitisation is missing, incomplete, or bypassable. Ask these questions at every step:

  • Is the length validated before it is used in a memory operation?
  • Does query data go through a parameterised query, and are special characters escaped before data reaches a command sink?
  • Does the validation actually cover all cases, or can it be bypassed with edge-case inputs?
  • Is the validation performed on the right data - the actual bytes that reach the sink, not a copy that might differ?

Practical Source-Sink Audit Workflow

When auditing a codebase, work in both directions:

Forward from sources: start at each source function (recv, read, getenv, argv) and trace where the data goes. Follow it through calls, assignments, and struct fields until you find sinks or lose the trail.

Backward from sinks: start at dangerous functions (memcpy, strcpy, system, sprintf) and work backward through parameters, return values, and struct fields until you hit a source or find adequate validation.

Backward is usually faster. There are fewer sinks than sources, and dropping into a dangerous function immediately focuses you on the code paths that actually matter.

bash
# Find all calls to dangerous sink functions in a codebase
grep -rn "memcpy\|strcpy\|sprintf\|strcat\|system\|popen\|exec" src/ \
--include="*.c" --include="*.cpp" | grep -v "test"

This gives you a list of sink locations. For each one, trace backward: where does each argument come from? Is any argument derived from untrusted input? If so, is it validated before reaching the sink?