Databases Bug Report

Login bypassed by ' OR 1=1 -- because our login query concatenated input

A legacy admin login built its SQL by string concatenation. One crafted username logged an attacker in as the first user. Root cause, the real fix with prepared statements, and how we proved it was closed.

Mateusz Kowalczyk Mateusz Kowalczyk @mateuszkowalczyk · November 16, 2026 · 8 min read · 127 Views
Banner: SQL injection login bypass fixed with prepared statements

An internal alert fired on a Sunday: a session appeared for the admin account from an IP that had never touched the app before, and the account owner was asleep. The access log showed a single successful POST to the old staff login endpoint, no failed attempts before it, no password reset. That "first try, no failures" shape is what pulled us out of bed — a stolen password usually shows up after a burst of guesses, not on the first request.

The endpoint was a legacy staff portal we had inherited and not yet migrated. The login handler logged the raw query it executed (itself a problem, but useful here). In the application log we found:

[login] executing: SELECT id, username, role FROM staff_users
        WHERE username = '' OR 1=1 -- ' AND password = 'whatever'
[login] matched user id=1 (admin), issuing session

The submitted username field was not admin. It was:

' OR 1=1 -- 

The attacker never knew or guessed a password. The password branch of the query was commented out, the WHERE clause became always-true, and the database returned every row. The code took the first one — id=1, the oldest account, which happened to be admin — and logged them in.

Reproducing it locally

We pointed a throwaway copy of the staff DB at the handler and replayed the input. The bypass was deterministic:

curl -i https://staff.example.test/login \
  --data-urlencode "username=' OR 1=1 -- " \
  --data-urlencode "password=x"
# HTTP/1.1 302 Found
# Location: /dashboard
# Set-Cookie: staff_session=...

Every variation from the usual injection cheat sheets worked too — ' OR '1'='1, admin' --, ' OR 1=1 LIMIT 1 -- . They are not separate vulnerabilities; they are the same one hole poked with different sticks. That detail mattered for the fix: there is no list of "bad strings" to block, because the grammar of SQL gives an attacker endless equivalents. The only durable fix is to stop building queries out of strings.

The handler built the query by pasting user input directly into SQL text:

// legacy StaffLoginController::login() — the vulnerable version
$username = $_POST['username'];
$password = $_POST['password'];

$sql = "SELECT id, username, role FROM staff_users
        WHERE username = '$username' AND password = '$password'";

$row = $db->query($sql)->fetch();   // mysqli / raw PDO::query, no binding
if ($row) {
    loginUser($row);
}

Two independent mistakes stacked on top of each other.

1. The input became code, not data. When $username is ' OR 1=1 -- , string interpolation produces:

SELECT id, username, role FROM staff_users
WHERE username = '' OR 1=1 -- ' AND password = '...'

The attacker's single quote closed the intended string literal, OR 1=1 added an always-true condition, and -- (comment, with the trailing space MySQL requires) deleted the rest of the query, including the password check. The database faithfully did what the final SQL said: return all rows. The database was not "tricked" — it was handed a different program than we meant to write, because we let untrusted text decide the structure of the statement, not just the values in it.

2. Authentication was done in SQL, with a plaintext password column. Even without the injection, the query compared password = '$password' against a column that stored the password as entered. So the passwords were not hashed, and the "are you allowed in" decision was a side effect of a row match rather than an explicit check in code. That is why commenting out the password clause was enough: there was no separate verification step to fail.

The injection is the headline (OWASP has ranked injection in its Top 10 for years, most recently as part of A03), but the plaintext-password design is what turned a read into a full account takeover.

Why input filtering is the wrong fix

Our first instinct was to "escape quotes" or reject inputs containing ', --, or OR. Every one of those is a trap:

  • Legitimate values contain those characters (an O'Brien username, a password with -- in it).
  • Encodings multiply the payloads: %27, Unicode variants, /* */ comment styles, # comments on MySQL.
  • A denylist is a bet that you thought of every bypass. Attackers only need one you missed.

Filtering treats the symptom. The cause is that data is being parsed as code. Fix the cause.

The fix has two parts: never build SQL from strings again, and move authentication into explicit, hash-based verification.

1. Parameterized query (prepared statement)

With a prepared statement, the SQL text and the parameters travel to the database separately. The driver sends the query structure first; the values are bound afterward and can never change the statement's grammar. ' OR 1=1 -- becomes a username that is simply looked up and not found.

// fixed: bind the value, look the user up by username only
$stmt = $pdo->prepare(
    'SELECT id, username, role, password_hash
     FROM staff_users
     WHERE username = :username
     LIMIT 1'
);
$stmt->execute(['username' => $_POST['username']]);
$row = $stmt->fetch(PDO::FETCH_ASSOC);

To make the separation real rather than emulated, turn off emulated prepares on MySQL so the driver uses true server-side prepared statements:

$pdo = new PDO($dsn, $user, $pass, [
    PDO::ATTR_EMULATE_PREPARES   => false,
    PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
]);

The same rule holds in every stack — bind, never concatenate:

# Python, psycopg / sqlite3: pass params as the second argument, not via f-strings
cur.execute("SELECT id, role, password_hash FROM staff_users WHERE username = %s",
            (username,))
// Node, mysql2: placeholders + values array
const [rows] = await pool.execute(
  'SELECT id, role, password_hash FROM staff_users WHERE username = ? LIMIT 1',
  [username],
);

If you use an ORM or query builder (Eloquent, Django ORM, Hibernate), its parameter binding does this for you — the danger is DB::raw(), whereRaw("... '$x'"), string-formatted JPQL and friends, which quietly drop back to concatenation. Those are the lines to grep for.

2. Verify the password in application code, against a hash

Look the user up by username alone, then check the password with a constant-time hash verify. The password is never part of the WHERE clause.

if ($row && password_verify($_POST['password'], $row['password_hash'])) {
    loginUser($row);           // explicit allow decision
} else {
    // same generic message + timing for "no such user" and "wrong password"
    return back()->withErrors(['login' => 'Invalid username or password.']);
}

Store hashes with a modern algorithm (password_hash($plain, PASSWORD_DEFAULT) gives bcrypt or argon2) and re-hash on next successful login to migrate the legacy plaintext column. Return the same error and similar response time whether the username exists or not, so the form cannot be used to enumerate accounts.

3. Defense in depth

Not a replacement for the above, but cheap insurance:

  • Least-privilege DB user. The login path only needs SELECT on staff_users. A separate read-only account limits what any future injection could do.
  • Remove query logging of raw SQL in production, and never log credentials.
  • Static analysis / CI gate. Add a check that fails the build on string-interpolated SQL (whereRaw, concatenation into query()), so this cannot come back unnoticed.

We did not want to "look fixed"; we wanted proof the class of bug was closed.

1. Regression test with the actual payloads. We turned the cheat-sheet strings into a test so any reintroduction fails CI:

/** @dataProvider injectionPayloads */
public function test_login_rejects_injection_payloads(string $username): void
{
    $res = $this->post('/staff/login', [
        'username' => $username,
        'password' => 'anything',
    ]);

    $res->assertSessionHasErrors('login');
    $this->assertGuest();          // no session issued
}

public static function injectionPayloads(): array
{
    return array_map(fn ($p) => [$p], [
        "' OR 1=1 -- ",
        "' OR '1'='1",
        'admin" --',
        "') OR ('1'='1",
        "' OR 1=1 LIMIT 1 -- ",
    ]);
}

All of them now land on the same "Invalid username or password" path, and assertGuest() confirms no session is created.

2. Confirm true prepared statements. With ATTR_EMULATE_PREPARES => false, we checked the MySQL general log during a test login and saw the two-step protocol — Prepare with the placeholder, then Execute with the value as a parameter — rather than one fully-interpolated query string. That is the signal the value can no longer alter the SQL grammar.

3. Password path. A unit test asserts a correct password logs in, a wrong password does not, and that a legacy plaintext row is transparently re-hashed to bcrypt on first successful login.

4. Security implications reviewed. Because the breach returned every row, we treated all staff accounts as exposed: forced password resets, invalidated existing sessions, and audited the access logs for other sessions created through the old endpoint. We also searched the codebase for sibling patterns — whereRaw(, string concatenation into ->query(, sprintf( building SQL — and fixed two more endpoints that had the same shape but had not yet been found.

Takeaways

  • ' OR 1=1 -- and its dozens of variants are one bug — untrusted input parsed as SQL code. Blocking strings is a losing game; parameterizing the query removes the hole entirely.
  • Never put a password in a WHERE clause. Look the user up by identifier, then verify a hash in code.
  • Prove it with the payloads as regression tests and by confirming real (non-emulated) prepared statements, so the fix cannot silently regress.

Add a label

#mysql #authentication #sql-injection #prepared-statements #pdo
Written by
Mateusz Kowalczyk @mateuszkowalczyk

I started as an application developer and drifted toward the database because that is where our incidents kept ending up. For the last eight years I have looked after PostgreSQL and MySQL clusters for e-commerce and SaaS teams, from schema reviews to late-night failovers. Relational databases are well documented, yet the same surprises keep catching good engineers: a NOT IN that returns nothing because of one NULL, an index silently skipped after a type conversion, a FOR UPDATE that locked far more than intended, a replica that disagreed with its primary after promotion. In each post I reproduce the problem on a small dataset, read the plan or lock output together with you, explain the rule behind it and show the fix with numbers before and after. Where engines differ, I run the same test on both and show the results side by side.

Advertisement

Comments

0

No comments yet. Be the first to comment!

Sign In to post a comment.