Skip to content
Tutorials Center
My learning

Topics

Lesson 18 of 31 ยท Web Application Security Concepts

Injection and Input Validation: Defense

Understand injection flaws and how to defend against them: SQL injection, cross-site scripting, parameterized queries, output encoding and the limits of WAFs.

Injection is one idea with many faces: an application builds a command or document by gluing text together, and part of that text comes from a user. If the user's text can change the structure of the command rather than just its data, the user is now writing code. SQL injection, cross-site scripting (XSS), operating-system command injection and LDAP injection are all the same mistake in different places.

This lesson explains the two most important cases in a defensive way: why they happen, and the small number of habits that prevent almost all of them. It builds on Web Application Security Concepts. The examples run against an in-memory SQLite database with invented data, and they contrast unsafe and safe code so you can see the difference in behavior. There is nothing to attack: it is a toy database inside your browser tab.

Only test for injection on applications you own or are authorized to test. Sending injection strings at someone else's site is an attack, even if "nothing happened".

The root cause: data mixed with code

Imagine a login query built like this (shown read-only, in pseudo-code):

TEXT
query = "SELECT * FROM users WHERE name = '" + input + "'"

When input is alice, the query is fine. But the database cannot tell which characters came from the programmer and which came from the user. If the user's text contains a quote and extra SQL, the database reads those as part of the command. The programmer's intention (a name to compare) became attacker-controlled logic.

Why injection works

Text glued together Code and data share one string.
No boundary The interpreter cannot tell them apart.
User controls part Input changes the command.
1 / 2

SQL injection and the real fix

The solid defense is parameterized queries (also called prepared statements). The SQL text is sent with placeholders, and the values are sent separately. The database parses the command first, so values can never become commands, whatever characters they contain.

The example creates a tiny in-memory table. The unsafe function glues text; the safe one uses a placeholder. Both are called with a harmless name and with a string that is shaped like an injection. Look at how the unsafe version changes meaning while the safe one treats the string as just a (non-existent) name.

Python Unsafe versus parameterized query

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

For the second input, the unsafe query returns every user, because the quote broke out of the string and the added condition is always true. The safe query returned nothing: the database looked for a user whose name is literally that odd string.

Defense checklist for SQL:

  • Use parameterized queries or the query builder / ORM of your framework for all values, including search boxes and sort parameters.
  • Identifiers cannot be parameters (table or column names). If a user can choose a sort column, allow-list the permitted names in code.
  • Give the application's database account only the privileges it needs (no schema changes, no access to other databases). This limits the damage if a bug slips through.
  • Do not show raw database error messages to users; log them privately.
  • Escaping quotes by hand is not a substitute: it is easy to get wrong and varies by database.

Cross-site scripting (XSS)

XSS is injection into HTML and JavaScript. If an application writes user text into a page without encoding it, a browser may treat that text as markup or script. Then a script chosen by an attacker runs in the victim's browser with the site's authority: it can read the page, act as the user, and steal data that JavaScript can reach. There are three common types: stored (the text is saved, then shown to others), reflected (it is echoed straight from the request) and DOM-based (client-side code inserts it).

The primary defense is output encoding for the right context: when you place data in HTML text, convert the characters that have meaning (<, >, &, quotes) into harmless entities. Different contexts (HTML text, attribute values, JavaScript strings, URLs, CSS) need different encoding, which is why using a template engine that encodes automatically is so valuable. Blade's {{ }}, Jinja2 and React's JSX all encode by default; the dangerous ones are the explicit "raw" escape hatches such as {!! !!}, |safe or dangerouslySetInnerHTML.

This stand-in prints a comment as unsafe raw HTML and as encoded HTML. It shows the text only; the page does not run the resulting markup.

Python Output encoding in action

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Additional layers for XSS, each partial on its own:

  • A Content-Security-Policy that forbids inline scripts and limits script sources, so an injected script has a harder time running.
  • HttpOnly cookies, so a script cannot read the session ID.
  • If you must accept HTML (a rich-text editor), pass it through a well-maintained sanitizer with an allow-list of tags, never a home-made regular expression.
  • Avoid DOM sinks such as innerHTML for untrusted text; use textContent.

Input validation: useful, but not the main defense

Validation checks that input has the expected shape before using it: an age is an integer from 0 to 150, a country is one from a fixed list, an email has one @, a file upload has an allowed type and size. Prefer allow-lists (accept only what is known good) over block-lists (reject known bad), because attackers invent variants that block-lists miss. Validate on the server; client-side checks are for convenience because they can be bypassed.

Validation reduces the attack surface and gives better error messages, but it does not replace parameterization and encoding. A name like O'Brien or a comment about HTML is legitimate input and must work; the safe answer is to handle it correctly at the point of use, not to ban the characters.

What about a WAF?

A web application firewall inspects requests and blocks ones that look like attacks, using rules and signatures. It is a useful extra layer, especially for virtual patching a known flaw while the code is being fixed, and for blocking bulk scanning noise. But a WAF has limits:

  • It guesses from patterns, so it has false positives (blocking legitimate users) and false negatives (missing encoded or unusual attacks).
  • It cannot know your application's logic, so it does not detect broken access control.
  • Attackers test bypasses, so it must be tuned and monitored.

Treat a WAF as a seatbelt, not as permission to write vulnerable code. The fix for an injection flaw is always in the code.

What is real and what is the stand-in

The attack classes, parameterized queries, output encoding and WAF behavior are real. The SQLite database is a real engine, but it holds three invented rows and is not connected to any web application. The strings are shown for teaching what the defenses prevent; the code makes no network requests.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the root cause shared by SQL injection and XSS?

    Both happen when untrusted text is interpreted as code (SQL or HTML/JavaScript) instead of being treated purely as data.
  2. 2. Why do parameterized queries prevent SQL injection?

    The database knows which part is the command and which part is data, so no value can change the query's structure.
  3. 3. A page needs to display a user's comment inside HTML text. What is the primary defense against XSS?

    Context-correct output encoding removes the special meaning of markup characters. Other measures are extra layers.
  4. 4. Which statement about a WAF is correct?

    A WAF works from patterns and has false positives and false negatives. The real fix stays in the application.
  5. 5. A report page lets users choose the sort column by name. How should the column be handled in SQL?

    Identifiers cannot be bound as parameters, and dropdown values can be forged, so only a server-side allow-list is safe.

Summary

  • Injection happens when untrusted text is interpreted as code; the cure is to keep code and data separate.
  • Use parameterized queries for every value, allow-list identifiers, and limit database privileges.
  • Prevent XSS with context-aware output encoding, auto-encoding templates, CSP, HttpOnly cookies and sanitizers for allowed HTML.
  • Validate input with allow-lists on the server, but do not rely on validation instead of parameterization or encoding.
  • A WAF is a helpful extra layer with real limits, not a replacement for fixing the code.

Next in the track: Reading Web Server Logs for Attacks.