Input Validation and Injection

Video + 12 min read · includes a lab

User
Your server
Data and code apart
Database
User input
SQL with input mixed in
Input Validation and Injection
0:00 / 6:45 · Input Validation and Injection
Chapters and transcript

Input Validation and Injection Injection happens when your program mixes data from a user with code that something else will run, such as a SQL query, an HTML page or a shell command. In this lesson, you will learn the developer side: validation on the server, parameterised queries, output encoding and safe commands. All of them keep data and code apart.

The root cause Every injection bug has the same shape. Your program builds one string from your instructions and the user input. Then it hands that string to an interpreter, a program that runs instructions. It might be a database, a browser, or the operating system shell. The interpreter cannot tell which part came from you. A quote, a less-than sign or a semicolon can change your meaning.

The root cause So the fix is never to find the bad characters. The fix is to keep data and code apart, with tools designed for that. For the database, SQL injection is stopped with parameterised queries. For the browser, cross-site scripting is stopped with output encoding for the right context. For the shell, avoid the shell and pass arguments as a list. Validation is a helpful extra layer on top.

Validate on the server First, input validation: checking that each value has the shape you expect, on the server. Prefer an allowlist. Describe exactly what is allowed, and reject everything else. A blocklist tries to list bad values, and it always misses something.

Validate on the server Good validation checks five things. Type: is it a number, a date, a true or false value? Length: a minimum and a maximum. Format: for example, a Pakistani mobile number is eleven digits starting with zero three. Range: a quantity between one and ninety-nine, not minus five. Allowed values: a sort field may only be price or date.

Validate on the server Here is server validation at work. The server uses an allowlist pattern: eleven digits starting with zero three. A value with letters is rejected with a clear message. A correct number is accepted. In real projects, a library such as Zod or Joi for Node.js, or Pydantic for Python, keeps checks consistent. But a comment or an address must allow many characters, so you still need the main fixes.

Parameterised queries Now the main fix for databases. When you join the input into the SQL text, the database reads it all as one command. A parameterised query, also called a prepared statement, sends the command with a placeholder, and sends the value separately. The database treats the value only as data, never as part of the command, whatever characters it contains.

Parameterised queries In code, the bad pattern joins the email into the SQL, with a plus sign in Node.js or an f-string in Python. The good pattern uses a placeholder. sqlite3 and mysql2 use a question mark, psycopg uses percent s, and node-postgres uses dollar one. ORMs such as Prisma or SQLAlchemy parameterise for you, but use placeholders in raw queries too. Placeholders work for values, not column names, so check a sort column against an allowlist.

Output encoding Next, cross-site scripting. Here a user saves a display name that contains HTML tags. When the page uses innerHTML, the browser treats the name as HTML, so the tags take effect, and scripts could run the same way. When the page uses textContent, the name is always shown as plain text, exactly as typed. That is the safe property.

Output encoding Output encoding means converting special characters so the browser shows them as text. For example, the less-than sign becomes ampersand, l, t, semicolon. The best habit is to let your framework do it. React, Angular and Vue encode by default. So do server templates such as Jinja2, Django templates and EJS. Problems start when developers switch this protection off.

Output encoding Be careful with anything that skips the protection. innerHTML, outerHTML and document dot write with user data. React dangerouslySetInnerHTML. The unescaped EJS tag, and the safe filter in Jinja2 or Django. User input inside script blocks or event attributes such as onclick. And links: a javascript colon link can run code, so allow only http and https. If users need formatting, use a sanitiser such as DOMPurify. A Content Security Policy adds another layer.

Command injection Command injection happens when input is joined into a command that runs in the shell. An attacker types a host name, then a semicolon and a second command. Your code joins it into one string and runs it in a shell, with exec in Node.js or shell equals True in Python. The shell sees the semicolon, and the extra command runs too. Semicolon, double ampersand and the pipe all let attackers add commands.

Command injection Here is a safe ping tool on a developer laptop. It uses execFile with a list of arguments, so no shell is involved and the semicolon has no special meaning. It also validates the host: only letters, numbers, dots and hyphens, with no leading hyphen, so the value cannot be read as an option. The bad input is rejected. A normal host works. Better still, ask if you need a shell command at all.

Quick check Quick check. Your comment box must allow quotes and angle brackets, because people write them in normal text. A comment arrives with an HTML tag inside. What protects the page when you show that comment? Choose one.

Practise safely Practise on a project you own. Search your code for risky patterns: joined SQL, innerHTML, exec, os dot system and shell equals True. Decide whether user input can reach each one. Rewrite it with the safe pattern. Then test with harmless input, such as O Brien with an apostrophe, or a bold tag. A correct fix shows them exactly as typed. Only test applications you own or have written permission to test.

Key takeaways Let us put it together. Injection mixes data with code, so keep them apart. Validate on the server with allowlists. Use parameterised queries for every database value. Let your framework encode output, and avoid innerHTML. And run programs without a shell, with arguments as a list. Now read the lesson below, try the lab, and answer the quiz.

Injection happens when your program mixes data from a user with code that something else will run, such as a SQL query, an HTML page or a shell command. The Web Hacking path shows how attackers abuse this. This lesson shows the developer's side: the habits and code patterns that stop it.

The root cause: mixing data and code

Every injection bug has the same shape. Your program builds a string that contains both your instructions and the user's input, then hands the whole string to an interpreter: a database, a browser or the operating system shell. The interpreter cannot tell which part came from you and which part came from the user. If the input contains special characters, such as a quote, a < sign or a ;, it can change the meaning of your instructions.

So the fix is never "find the bad characters". The fix is to keep data and code apart, using tools designed for that:

Interpreter Attack Main fix
Database SQL injection Parameterised queries
Browser Cross-site scripting (XSS) Output encoding for the right context
Operating system shell Command injection Avoid the shell; pass arguments as a list

Validation, which we cover first, is a helpful extra layer on top of these fixes.

Validate input on the server

Input validation means checking that each value has the shape you expect before you use it. Do it on the server, as the last lesson explained.

Prefer an allowlist: describe exactly what is allowed and reject everything else. A blocklist, which tries to list bad values, always misses something.

Good validation checks:

  • Type: is it a number, a date, a true or false value?
  • Length: minimum and maximum
  • Format: for example, a Pakistani mobile number is 11 digits starting with 03
  • Range: a quantity between 1 and 99, not -5 or 1,000,000
  • Allowed values: a sort field may only be price or date

A short example in Node.js:

function isValidMobile(value) {
  return typeof value === 'string' && /^03[0-9]{9}$/.test(value);
}

const ALLOWED_SORT = ['price', 'date'];
const sort = ALLOWED_SORT.includes(req.query.sort) ? req.query.sort : 'date';

The same idea in Python:

import re

def is_valid_mobile(value):
    return isinstance(value, str) and re.fullmatch(r"03[0-9]{9}", value) is not None

In real projects, a validation library such as Zod or Joi for Node.js, or Pydantic for Python, makes this easier and more consistent.

Remember the limit: validation reduces risk, but a field like a comment or an address must allow many characters. You still need the main fixes below.

Parameterised queries

A parameterised query (also called a prepared statement) sends the SQL command and the data to the database separately. The database treats the data only as a value, never as part of the command, no matter what characters it contains.

Node.js with the mysql2 library:

// Bad: user input is joined into the SQL text
const [rows] = await db.query(
  "SELECT id, name FROM customers WHERE email = '" + email + "'"
);

// Good: ? is a placeholder, the value is sent separately
const [rows] = await db.execute(
  'SELECT id, name FROM customers WHERE email = ?',
  [email]
);

Python with the built-in sqlite3 module:

# Bad: an f-string builds the SQL
cur.execute(f"SELECT id, name FROM customers WHERE email = '{email}'")

# Good: the value is passed as a parameter
cur.execute("SELECT id, name FROM customers WHERE email = ?", (email,))

Different libraries use different placeholder styles. sqlite3 and mysql2 use ?, psycopg for PostgreSQL uses %s, and node-postgres uses $1, $2. The idea is the same in all of them. Note that %s in psycopg is a placeholder, not Python string formatting: you pass the values as a separate argument.

Two more points:

  • ORMs (libraries that map tables to objects, such as Prisma, Sequelize, SQLAlchemy or the Django ORM) parameterise for you. But most ORMs also have a "raw query" feature. If you use it, use placeholders there too.
  • Placeholders work for values, not for table or column names. If a user chooses a column to sort by, check it against an allowlist, as in the sort example above.

Output encoding against XSS

Cross-site scripting happens when user input is placed into a page and the browser treats it as HTML or JavaScript. The fix is output encoding: converting special characters so the browser shows them as text. For example, < becomes &lt; and " becomes &quot;.

The most important habit is to let your framework do it. React, Angular and Vue encode values by default. So do server templates such as Jinja2 (used by Flask, which turns on auto-escaping for HTML templates), Django templates and EJS when you use <%= %>. Problems start when developers switch this protection off.

In browser JavaScript, choose the safe property:

// Bad: the name is parsed as HTML, so tags and scripts can run
el.innerHTML = 'Welcome, ' + user.name;

// Good: the name is always shown as plain text
el.textContent = 'Welcome, ' + user.name;

If you build HTML by hand in Python, encode it:

import html

safe_name = html.escape(user_name)
page = "<p>Welcome, " + safe_name + "</p>"

Be careful with these, because they skip the protection:

  • innerHTML, outerHTML and document.write with user data
  • React's dangerouslySetInnerHTML
  • <%- %> in EJS and the |safe filter in Jinja2 or Django
  • User input placed inside <script> blocks, event attributes such as onclick, or href links. A link that starts with javascript: can run code, so only allow http: and https: links.

If users really need formatting, such as bold text in a comment, use a well-maintained sanitiser library such as DOMPurify rather than writing your own filter. A Content Security Policy header adds another layer. You will see it in lesson 5.

Command injection

Command injection happens when user input is joined into a command that runs in the operating system shell. Characters such as ;, && and | let an attacker add their own commands.

Node.js:

const { exec, execFile } = require('child_process');

// Bad: exec runs the whole string in a shell
exec('ping -c 1 ' + host, callback);

// Good: execFile runs the program directly, with arguments as a list
execFile('ping', ['-c', '1', host], callback);

Python:

import subprocess

# Bad: shell=True sends the whole string to the shell
subprocess.run("ping -c 1 " + host, shell=True)

# Good: a list of arguments, no shell
subprocess.run(["ping", "-c", "1", host], check=True)

The safe versions do not use a shell, so ; and && have no special meaning. Still validate the value. If host started with -, the program might read it as an option. Allow only letters, numbers, dots and hyphens, and do not allow a leading hyphen.

Better still, ask whether you need a shell command at all. Most languages have a library that does the job directly, such as resizing an image or creating a zip file, with no shell involved.

Practise safely

Try these on your own computer, in a project you own:

  1. Search your code for risky patterns: SQL text joined with + or built with f-strings, innerHTML, dangerouslySetInnerHTML, exec(, os.system and shell=True.
  2. For each one, decide whether user input can reach it.
  3. Rewrite it using the safe pattern from this lesson.
  4. Test with harmless input such as O'Brien or <b>test</b>. A correct fix stores and shows these exactly as typed, with no errors and no bold text.

Only test applications you own or have written permission to test.

HANDS-ON LAB

Find the Injectable Function

Review three files of a small Node.js shop API and find the one function open to injection.

Start the lab →

Check your understanding

Answer every question correctly to complete this lesson. If you miss one, try the quiz again.

1. Which line is the safe way to look up a user by email in Python with sqlite3?

2. Your page shows a user's display name with element.innerHTML = name. What is the safer change?

3. Why is an allowlist usually better than a blocklist for validation?

Locked: answer every quiz question above correctly to complete this lesson.

Spotted a mistake or something unclear? Report a mistake