criticalCode Injection

SQL Injection via Unsanitized Input

What Is This Vulnerability?

SQL injection occurs when user-supplied data is concatenated directly into SQL queries without proper sanitization or parameterization. An attacker can manipulate the query logic to read, modify, or delete data they should not have access to, and in some cases execute administrative operations on the database.

Why It Happens

Developers often build SQL queries using string concatenation or template literals with raw user input. This happens when ORMs are bypassed for performance, when legacy code predates parameterized query support, or when input validation is mistakenly treated as a substitute for parameterized queries.

Example Code

Vulnerableroutes/users.ts
app.get("/users", async (req, res) => {
  const { username } = req.query;
  const result = await db.query(
    `SELECT * FROM users WHERE username = '${username}'`
  );
  res.json(result.rows);
});
Fixedroutes/users.ts
app.get("/users", async (req, res) => {
  const { username } = req.query;
  const result = await db.query(
    "SELECT * FROM users WHERE username = $1",
    [username]
  );
  res.json(result.rows);
});

How Hackers Exploit It

Attackers submit crafted payloads like ' OR '1'='1 in form fields, query parameters, or HTTP headers. Automated tools such as sqlmap can enumerate databases, dump tables, and extract credentials within minutes. In severe cases, attackers use stacked queries to drop tables or execute system commands via xp_cmdshell.

How to Fix It

Always use parameterized queries or prepared statements. If you use an ORM like Prisma or Drizzle, stick to its query builder instead of raw SQL. Apply the principle of least privilege to database accounts so the application user cannot drop tables or access system procedures. Add a web application firewall as an additional layer of defense.

Frequently Asked Questions

What is the easiest way to prevent SQL injection?
Use parameterized queries or prepared statements. Every major database driver and ORM supports them. Never concatenate user input into SQL strings, even if you think you have validated the input elsewhere.
Can an ORM still be vulnerable to SQL injection?
Yes. If you use raw query methods like Prisma's $queryRawUnsafe or Sequelize's literal(), you bypass the ORM's built-in protections. Always prefer the ORM's query builder and avoid raw SQL unless absolutely necessary.
Does input validation stop SQL injection?
Input validation reduces the attack surface but is not sufficient on its own. Parameterized queries are the primary defense. Validation should be used alongside parameterization, not as a replacement.

Related Security Topics

Check Your Code for This Vulnerability

Run a free scan to check if your site is affected by sql injection via unsanitized input.