Injection and cross-site scripting
Why mixing data with code is dangerous, and the fix for SQL injection and XSS.
Most injection bugs share one cause: untrusted input is treated as code. The fix is always to keep data and code separate.
SQL injection
# Vulnerable: input is pasted into the query
query = "SELECT * FROM users WHERE email = '" + email + "'"
# email = x' OR '1'='1 returns every user
# Safe: parameterized query
cursor.execute("SELECT * FROM users WHERE email = %s", (email,))Placeholders send the value to the database separately, so it can never change the structure of the query. Escaping by hand is fragile.
Cross-site scripting (XSS)
XSS happens when a page shows user input as HTML, letting an attacker run JavaScript in other users' browsers: stealing sessions, acting as the user, or rewriting the page.
// Vulnerable
el.innerHTML = comment;
// Safe: text is not parsed as HTML
el.textContent = comment;- Use frameworks that escape output by default, and be wary of
innerHTML,dangerouslySetInnerHTMLandv-html. - Set a Content-Security-Policy header to limit where scripts can load from.
- Mark session cookies
HttpOnlyso scripts cannot read them. - If you must allow HTML, sanitize it with a maintained library, not with regex.
NoteThe same principle covers command injection: never build a shell command by concatenating user input. Pass arguments as a list instead.
Test yourself
Answer all the questions, then check them. Finish with every answer right to mark the lesson as done.