Injection Attacks (OWASP A05:2025)
On this page
SQL injection: logging in without a password
A login route builds its SQL by pasting in the form fields:
const sql = `SELECT id, email FROM users
WHERE email = '${req.body.email}' AND password = '${req.body.password}'`;Send this as the email, with any password:
admin@example.com' --{"loggedInAs":"admin@example.com"} 200The quote closes the string, and -- turns the rest of the query, the password check included, into a comment. A second payload, x' OR '1'='1 in both fields, logged in as the first user in the table.
The database can't tell your SQL from the attacker's, because by the time it sees the query they're one string. Every injection attack follows that pattern: data ends up somewhere an interpreter reads it as code.
The fix: parameterized queries
db.prepare('SELECT id, email FROM users WHERE email = ? AND password = ?')
.get(req.body.email, req.body.password);{"error":"Invalid email or password"} 401With a parameterized query, the SQL text and the values reach the database separately. A quote in the email is just a character in the email. (Real code compares a password hash, not the password; Day 8 covers that.)
Parameters cover values only. Table names, column names and ORDER BY directions can't be parameters, so if users choose them, check against a fixed allow-list:
const SORTABLE = new Set(['created_at', 'amount']);
const col = SORTABLE.has(req.query.sort) ? req.query.sort : 'created_at';In .NET the same rule holds, with one trap. EF Core's FromSqlRaw takes a finished string, so C# interpolation builds the injectable query before EF ever sees it. FromSql (EF Core 7 and later) takes the interpolated string apart and sends each value as a parameter:
db.Users.FromSqlRaw($"SELECT * FROM users WHERE email = '{email}'"); // injectable
db.Users.FromSql($"SELECT * FROM users WHERE email = {email}"); // parameterizedThe two lines differ by three letters and a pair of quotes, which is why code review should flag every FromSqlRaw and ExecuteSqlRaw that contains $". Dapper and plain ADO.NET are safe the same way: @email in the SQL, the value in a parameter object.
NoSQL operator injection with $ne
MongoDB-style queries are objects, not strings, so they look safe. But JSON lets the client send an object where you expected a string:
new Query({ email: req.body.email, password: req.body.password }).find(users){"email":"admin@example.com","password":{"$ne":null}}{"loggedInAs":"admin@example.com"} 200$ne: null means "password is not null", which is true for every user. (This lab uses the mingo library, which evaluates MongoDB query syntax in memory; a real MongoDB driver behaves the same.) The fix is checking types before building the query:
if (typeof email !== 'string' || typeof password !== 'string')
return res.status(400).json({ error: 'bad input' });{"error":"bad input"} 400One framework detail: in Express 4, password[$ne]=x in a form or query string was parsed into an object too. Express 5 defaults to simple parsing, and the lab echoed it back as a plain key, {"password[$ne]":"x"}. JSON bodies still allow objects, so validate types either way. A schema library such as Zod does this for every field.
XSS: injection into HTML
Cross-site scripting (XSS) is injection into HTML. If a comment containing <script> is inserted into a page as raw HTML, the browser runs it with the reader's session. The fixes follow the same rule:
- Let the template engine escape output by default (React, Razor, Jinja and most others do). Be careful with escape hatches like
dangerouslySetInnerHTML,v-html, and in .NET,@Html.Raw(...)and Blazor'sMarkupString. - Encode for the context: HTML body, attribute, URL and JavaScript each need different escaping.
- Add a Content-Security-Policy as a second layer. The Browser Security Headers course covers it in depth.
Command, LDAP and template injection
Shell commands (exec with string building; use execFile with an argument array), LDAP filters, template engines rendering user-supplied templates, and expression languages. Equifax's 2017 breach of about 147 million people began with Apache Struts evaluating an expression an attacker put in a request's Content-Type header.
Check yourself
No. Parameters can carry values, but not identifiers like column names, so col is pasted into the SQL text and can contain injected SQL. Map the user's choice to a fixed allow-list, for example { 'price': 'price', 'date': 'created_at' }, and reject anything else.
Sending {"$ne": null} as the password matches any user. Reject anything that isn't a string, ideally with schema validation on the whole body.
The query text and the values are sent to the database separately: the database parses the SQL structure first, then binds the values as data. A value can never change the structure of the query, whatever quotes or keywords it contains, so injection through that value is impossible rather than merely harder.
It converts characters that have meaning in the output context, such as < and " in HTML, into harmless representations, so user data is displayed as text rather than interpreted as markup or script. Template engines that encode by default, plus a Content Security Policy, are the main defenses.
Shell quoting rules are complex, and characters like ;, $() or backticks can break out of naive quoting to run extra commands. Pass arguments as an array to the process API without invoking a shell, and validate input against an allow-list.