---
title: "Input Sanitization | FiveStudy"
description: "How control characters let input break out into commands, and how a verification function that sanitizes or rejects input stops SQL injection, XSS, and directory traversal."
url: https://fivestudy.com/guides/ap-cybersecurity-5-5-b-input-sanitization
---

[AP Cybersecurity](https://fivestudy.com/ap-cybersecurity) · Study guide

# Input Sanitization

[Figure: FiveStudy]

FiveStudy

AP® Cybersecurity · Unit 5 · Applications, Data & Cryptography

AP® Cybersecurity · Unit 5 · Applications, Data & Cryptography

# Input Sanitization

Why control characters in user input are dangerous, and how a verification function that sanitizes or rejects input blocks SQL injection, cross-site scripting, and directory traversal.

1. Why user input is dangerous 2. Control characters 3. Sanitize or reject 4. Both checks on real input 5. Worked examples 6. Common mistakes

## 1 Why user input is dangerous

Many application attacks work the same way: the adversary types something that the application treats as part of a *command* instead of as plain data. A search box becomes a way to rewrite a database query; a comment box becomes a way to run a script in other people's browsers; a filename becomes a path to a system file.

**Figure 1.** Every piece of user input passes the check before the application uses it. Either way, the control characters never reach the system.

## 2 Control characters

When users enter input, the application typically encases that input in special characters to process it. These **control characters** include the **single quote** `'`, the **double quote** `"`, and the **semicolon** `;`. An application might build this query around a typed name:

The quotes encase the input

```
SELECT * FROM students WHERE name = 'name typed here'
```

If the input itself contains a quote, it closes the application's quote early, and whatever follows is read as part of the command. A semicolon can end one command and start another.

## 3 Sanitize or reject

Programmers should use a **function that verifies user input** meets the expected criteria and contains no control characters that could manipulate the system. That function can do one of two things:

| Approach | What it does | Example |
| --- | --- | --- |
| **Sanitize** | Removes potentially malicious characters, then uses what is left | `x' OR '1'='1` becomes `x OR 1=1`, a harmless (and unmatched) name |
| **Reject** | Gives the user an error and forces them to provide different input | “Please enter a name using letters only” |

Two verification functions (Python)

```
def sanitize(text):
    # remove characters a name never needs
    blocked = "'\";<>/\\"
    return "".join(ch for ch in text if ch not in blocked)

def validate(text):
    # accept only letters, spaces, periods, hyphens; 1 to 40 characters
    if re.fullmatch(r"[A-Za-z][A-Za-z .-]{0,39}", text):
        return "accepted"
    return "rejected: please enter a name"
```

This can protect against many application attacks, including **SQL injection**, **cross-site scripting (XSS)**, and **directory traversal**.

## 4 Both checks on real input

Here is what the two functions above actually return for five inputs to a name field:

| Input | Typed | After sanitize() | validate() |
| --- | --- | --- | --- |
| A normal name | `Ana Lima` | `Ana Lima` | accepted |
| A name with a hyphen | `Jean-Paul Diaz` | `Jean-Paul Diaz` | accepted |
| SQL injection | `x' OR '1'='1` | `x OR 1=1` | rejected: please enter a name |
| Cross-site scripting | `<script>steal()</script>` | `scriptsteal()script` | rejected: please enter a name |
| Directory traversal | `../../../etc/passwd` | `......etcpasswd` | rejected: please enter a name |

And here is the SQL injection run against a real four-student database, before and after sanitizing:

Query results

```
input typed:   x' OR '1'='1
raw query:     SELECT * FROM students WHERE name = 'x' OR '1'='1'
rows returned: 4   every student's grade

sanitized:     x OR 1=1
query:         SELECT * FROM students WHERE name = 'x OR 1=1'
rows returned: 0
```

Rejecting by an allow-list (only letters, spaces, periods, hyphens) is usually stronger than removing a list of known-bad characters, because it also blocks attacks the programmer did not think of. The two can also be combined.

The key idea

Control characters such as `'`, `"`, and `;` let input break out of the place the application put it. A verification function that sanitizes or rejects input before it is used protects against SQL injection, XSS, and directory traversal.

## 5 Worked examples

Worked Example 1 Trace the attack

### The login box

A login form builds `SELECT * FROM users WHERE name = 'INPUT'`. An attacker types `admin'; DROP TABLE users;`. Which control characters matter, and what would a sanitizing function do?

1. 1

   The `'` closes the application's quote early.

2. 2

   The `;` ends the query and starts a new command: delete the users table.

3. 3

   Sanitizing removes `'` and `;`, leaving `admin DROP TABLE users`, which is treated as one odd name.

**Answer:** The quote and semicolon. Removed, the input is just text that matches no user.

Worked Example 2 Choose the approach

### Phone number field

A form asks for a phone number. Should the verification function sanitize or reject input like `555-0142<script>`?

1. 1

   A phone number has a very clear expected pattern: digits, spaces, hyphens, parentheses.

2. 2

   Anything outside that pattern is either a mistake or an attack.

3. 3

   Rejecting with an error lets a real user fix a typo, and stops the attack.

**Answer:** Reject. When the expected format is clear, refuse anything that does not match it.

Worked Example 3 Which attack?

### Name the attack each check stops

A sanitizer removes `<` and `>`; another removes `../`; another removes `'` and `;`. Which attack does each block?

1. 1

   `<` and `>` build HTML tags like `<script>`: cross-site scripting.

2. 2

   `../` climbs out of a folder: directory traversal.

3. 3

   `'` and `;` break out of a database query: SQL injection.

**Answer:** XSS, directory traversal, SQL injection.

Worked Example 4 Explain the protection

### Why the grade lookup is safe now

Using the query results above, explain why the sanitized input returned 0 rows instead of 4.

1. 1

   Without sanitizing, the quotes in the input closed the name and added `OR '1'='1'`, which is true for every row.

2. 2

   Sanitizing removed the quotes, so the whole input stayed inside the name.

3. 3

   No student is named `x OR 1=1`, so nothing matched.

**Answer:** The input could no longer change the query's logic; it was only data.

## 6 Common mistakes

Common Mistake 1 · Checking input only in the browser

An attacker can skip the web page and send requests directly. The server must verify input too.

Common Mistake 2 · Blocking only one character

Removing `'` alone leaves `"`, `;`, `<`, and `../`. Check against what the field *should* contain.

Common Mistake 3 · Thinking sanitizing is only for SQL

The same idea protects web pages from XSS and file systems from directory traversal.

Explain input sanitization like this

“The name field passes its input to a verification function before it reaches the database. The function removes control characters such as the single quote and semicolon, so an input like `x' OR '1'='1` can no longer close the query’s quote and change its logic; it is treated as an ordinary name.”

Name the control characters, say whether the function sanitizes or rejects, and connect it to the attack it stops.

FiveStudy AP® Cybersecurity · Input Sanitization
