Belajar
← All lessons

How SQL injection works

your text, kept as datayour text, run as SQLcommented out

Log in without the password

NamePassword
The query the server builds
Rows back

Try a single ' as the name. Then ' OR '1'='1 as the password

server.js

app.post("/login", async (req, res) => {  const { name, password } = req.body;  const sql = "SELECT id, name, role FROM users " +    "WHERE name = '" + name + "' AND password = '" + password + "'";  const rows = await db.query(sql);  if (rows.length === 0) return res.status(401).end();  req.session.user = rows[0];  res.redirect("/dashboard");});

Read another table with UNION

Search products
The query the server builds
Search results

Try ' UNION SELECT name, password FROM users --

UNION needs as many columns as the first SELECT. Here that's two

server.js

app.get("/search", async (req, res) => {  const sql = "SELECT name, price FROM products " +    "WHERE name LIKE '%" + req.query.q + "%'";  const rows = await db.query(sql);  res.render("results", { rows });});

The fix: parameters keep your text as data

Browser
App server
Database

server.js

const { password } = req.body;// glued: your text becomes part of the SQLconst sql = "SELECT id, name, role FROM users " +  "WHERE name = 'admin' AND password = '" + password + "'";const rows = db.prepare(sql).all();

server-fixed.js

const { password } = req.body;// parameters: the SQL has a ? where the value goesconst stmt = db.prepare("SELECT id, name, role FROM users " +  "WHERE name = 'admin' AND password = ?");const rows = stmt.all(password);if (rows.length === 0) return res.status(401).end();

Topics

Next: How XSS works

Open lesson