The best examples of injection flaws: input validation errors explained

If you work with web or mobile apps long enough, you’ll eventually meet the villain of the story: injection. The best way to understand it is through concrete stories, so in this guide we’ll walk through real examples of injection flaws: input validation errors explained in plain English, with code you can recognize. From classic SQL injection to modern template and JSON injection in 2024-era stacks, the pattern is the same: the app trusts user input way more than it should. You’ll see how a single missing validation check can turn a login form into a data exfiltration tool, or how a poorly written search box can leak entire customer tables. These examples of injection flaws aren’t “edge cases” either; they keep showing up in OWASP Top 10 reports and big-name breaches year after year. We’ll break down how they happen, how attackers abuse them, and—most importantly—how to stop repeating the same mistakes in your own code.
Written by
Jamie
Published

Security people love theory. Developers need examples. So let’s start with concrete, code-level examples of injection flaws: input validation errors explained in the context of everyday features—login forms, search boxes, admin tools, and APIs.

At a high level, every injection bug has the same skeleton:

  • Untrusted input (user, API client, third-party system)
  • String concatenation or unsafe interpolation into a command
  • Interpreter that runs the command (SQL engine, shell, template engine, LDAP server, etc.)

When the interpreter can’t tell where data ends and code begins, you get an injection flaw.


Classic SQL injection: the “login bypass” everyone still ships

Despite two decades of warnings, SQL injection is still one of the best examples of injection flaws in production systems.

Imagine a login endpoint doing something like this in 2024:

// Bad Node.js / Express pseudo-code
const user = req.body.username;
const pass = req.body.password;

const query = `SELECT * FROM users WHERE username = '\({user}' AND password = '}\(pass}'`;
const result = db.query(query);

An attacker sends this username:

' OR '1'='1

The resulting query becomes:

SELECT * FROM users
WHERE username = '' OR '1'='1'
  AND password = 'anything';

Depending on how the database parses precedence, the condition can be forced to always be true, and the app happily logs the attacker in as the first matching user—often an admin.

This is a textbook example of injection flaws: input validation errors explained by a missing boundary between data and code. The app never validates the username format, never uses parameterized queries, and trusts that whatever the user sends is safe to jam into SQL.

OWASP still lists injection in the OWASP Top 10 because this remains one of the most common and damaging classes of bugs in real systems.


Parameter tampering in search: leaking more than you meant to show

Another everyday example of injection flaws shows up in search features. Picture a product search endpoint:

term = request.args.get("q", "")
order = request.args.get("order", "name")

query = f"SELECT * FROM products WHERE name LIKE '%{term}%' ORDER BY {order}"  # bad

A normal user sends q=shoes&order=name. An attacker sends:

q=%' OR 1=1 -- &order=price

Now your query looks like:

SELECT * FROM products WHERE name LIKE '%%' OR 1=1 -- %' ORDER BY price;

The -- comments out the rest, and OR 1=1 returns every product. If this is an internal catalog search, you might suddenly expose unpublished items, internal-only SKUs, or pricing data you didn’t intend to leak.

Again, this is an example of injection flaws: input validation errors explained by the lack of checks on both q and order. The app never restricts order to a whitelist of allowed columns, and never uses query parameters for term.


NoSQL injection in modern stacks: MongoDB and friends

Developers often assume NoSQL databases are safer because they don’t use SQL strings. That’s optimistic.

Consider a MongoDB-based login:

// Bad: directly using request body in Mongo query
const filter = { username: req.body.username, password: req.body.password };
const user = await db.collection('users').findOne(filter);

If your stack or middleware parses JSON in a way that allows nested objects, an attacker might send:

{
  "username": { "$ne": null },
  "password": { "$ne": null }
}

MongoDB now runs a query equivalent to:

{ username: { \(ne: null }, password: { \)ne: null } }

Which happily returns the first user with a non-null username and password—again, often an admin.

This is a modern example of injection flaws: input validation errors explained in a NoSQL context. The input is never validated to be a simple string, and the database interprets attacker-controlled operators like $ne as logic, not data.

The fix: sanitize and validate types, and use strict schemas (for example, with Mongoose or JSON Schema) so that only expected fields and primitive types are allowed.


Command injection: when user input hits the shell

Now let’s step outside the database. Command injection happens any time you build a shell command with user-controlled data.

Consider a file compression feature:

## Bad Python example
filename = request.args.get("file")
os.system(f"tar -czf backup.tar.gz {filename}")

An attacker sends:

file=docs/important.txt; rm -rf /

The shell sees:

tar -czf backup.tar.gz docs/important.txt; rm -rf /

You’ve just handed the attacker your server on a silver platter.

This is one of the starkest examples of injection flaws. Input validation errors explained here are simple: no check that file is a safe path, no escaping, and no use of safer APIs like subprocess.run([...], shell=False) in Python.

The U.S. Cybersecurity & Infrastructure Security Agency (CISA) has repeatedly highlighted injection-based vulnerabilities, including command injection, in their Known Exploited Vulnerabilities Catalog, underscoring how often attackers still use these weaknesses in real-world incidents.


Template injection in modern frontends and backends

Template engines—server-side or client-side—are another fertile ground for injection bugs.

Take a server-side rendering setup using a templating language that supports expression evaluation. A developer might do this to render a custom error page:

// Pseudo-code
const message = req.query.message || "Something went wrong";
res.render('error_template', { message });

If the template language allows logic in variables (for example, {{ message }} can evaluate more than just text), and the template isn’t configured to auto-escape or sandbox expressions, an attacker might inject:

{{ ().__class__.__mro__[1].__subclasses__()[40]('ls', shell=True, stdout=-1).communicate()[0].decode() }}

In some Python template engines, that kind of payload can execute arbitrary commands on the server.

Here, the example of an injection flaw is obvious: user input flows directly into a powerful interpreter. Input validation errors explained in this context mean not restricting what message can contain, and not configuring the template engine to treat it as plain text.


LDAP injection in enterprise authentication

Corporate environments still lean heavily on LDAP for authentication and directory lookups. Injection here can lead to unauthorized access or data disclosure.

Imagine an app building an LDAP filter like this:

String user = request.getParameter("user");
String filter = "(uid=" + user + ")";
NamingEnumeration<SearchResult> results = ctx.search("ou=users,dc=example,dc=com", filter, controls);

An attacker submits:


*)(|(uid=*)(mail=*

The filter becomes:

(uid=*)(|(uid=*)(mail=*))

Depending on the directory configuration, this could return every user or every object with an email address.

This is another example of injection flaws: input validation errors explained by a failure to escape special LDAP characters like *, (, ), and |, and by not using parameterized LDAP query APIs.

NIST guidance on secure coding practices, such as those referenced in NIST SP 800-53, consistently calls out input validation and injection resistance as baseline expectations for federal systems—and by extension, for any serious enterprise application.


JSON and API injection: modern APIs, same old mistakes

By 2024, many teams have moved from server-rendered pages to JSON APIs and SPAs. The bad news: injection just followed us there.

Consider a search API that accepts a JSON body:

{
  "filter": "status = 'ACTIVE'",
  "sort": "created_at DESC"
}

And the backend does this:

String filter = body.get("filter");
String sort = body.get("sort");
String query = "SELECT * FROM accounts WHERE " + filter + " ORDER BY " + sort;

If the client sends:

{
  "filter": "1=1; DROP TABLE accounts; --",
  "sort": "created_at"
}

You’ve got a very modern, JSON-wrapped example of injection flaws. Input validation errors explained here are about trusting the client’s business logic. The server should define allowed filters and sorts, not the client.

This pattern shows up in GraphQL resolvers, custom query languages, and internal admin APIs all the time. The interface looks modern; the vulnerability is classic.


Why these examples keep happening in 2024–2025

If you look at breach reports and security advisories from the last few years, you’ll notice a pattern: injection is old, but not going away. OWASP, NIST, and CISA keep repeating the same advice because the same categories of bugs keep shipping.

Some reasons:

  • Frameworks help, but don’t save you from yourself. ORMs, query builders, and template engines often have safe APIs—but it only takes one string concatenation to bypass those protections.
  • Developer pressure beats security guidance. Under a deadline, people reach for the fastest solution: string interpolation and dynamic building of queries or commands.
  • Input validation is treated as an afterthought. Teams bolt on regex checks or client-side validation instead of designing input contracts from day one.

The result: new frameworks, same old examples of injection flaws.


Input validation: why it’s necessary but not enough

Since we’re talking about examples of injection flaws: input validation errors explained doesn’t mean “just add a regex and you’re done.” Validation is one layer, not the only one.

Think of it in three layers:

1. Input validation and normalization

  • Enforce type: integers must be integers, emails must be strings matching a strict pattern, booleans must be literal booleans.
  • Enforce lengths and allowed character sets. For example, usernames: ^[a-zA-Z0-9_]{3,32}$.
  • Normalize encodings (UTF-8), trim whitespace, and reject malformed input early.

2. Safe APIs and parameterization

  • Always use prepared statements or parameterized queries for SQL and NoSQL.
  • Use high-level APIs that treat arguments as data, not as part of a command string.
  • Avoid eval, exec, Function constructors, or shell invocation with shell=True.

3. Output encoding and sandboxing

  • For template engines, enable automatic escaping and disable dangerous expression features where possible.
  • For logs and error messages, avoid echoing raw user input into places where it will be re-parsed.

The best examples of injection flaws—SQL injection, command injection, template injection—all bypassed at least two of these three layers. That’s why relying on a single regex or a client-side check is asking for trouble.

For more structured guidance on secure coding practices and input handling, the OWASP Cheat Sheet Series is a solid, vendor-neutral reference used by many security teams.


Practical patterns to avoid repeating these examples

To turn these examples of injection flaws into a checklist you can actually use, focus on a few habits:

  • Design input contracts first. For every endpoint or feature, define what fields exist, their types, allowed ranges, and formats. Enforce that server-side.
  • Centralize validation. Don’t scatter ad-hoc checks across controllers. Use middleware, decorators, or schema validators so every request passes through the same gate.
  • Ban dangerous APIs by policy. For example, forbid raw string-based SQL in code review; require query builders or ORM methods. Ban eval and shell execution with interpolated strings.
  • Log rejections, not raw payloads. When you block bad input, log enough context to debug without storing full attacker payloads in a place that might be parsed or viewed unsafely later.
  • Test for injection explicitly. Security testing isn’t just fuzzing. Add test cases with payloads like ' OR 1=1 --, ; rm -rf /, {{7*7}}, and JSON objects with \(ne or \)gt operators to see how your app behaves.

If you treat the examples of injection flaws in this article as test templates, you’ll quickly see where your own validation and query-building logic is too trusting.


FAQ: examples of injection flaws and how to handle them

Q: What are the most common examples of injection flaws developers still introduce?
The most common examples include SQL injection in login and search features, command injection in file utilities and backup scripts, template injection in server-side rendering setups, NoSQL injection in MongoDB-based auth flows, and LDAP injection in enterprise directory lookups. All of them share the same pattern: user input is concatenated into a command or query string without validation or parameterization.

Q: Can you give a simple example of an input validation error that leads to SQL injection?
A classic example of an input validation error is a login form that accepts any string as a username and password, then builds a query like "SELECT * FROM users WHERE username = '" + user + "' AND password = '" + pass + "'". Without validating the username format or using prepared statements, an attacker can send user=' OR '1'='1 and trick the database into returning a valid user record.

Q: If I validate all input with regex, am I safe from injection?
No. Input validation helps, but it doesn’t replace parameterized queries and safe APIs. Many of the best examples of injection flaws bypass weak or overly permissive regex checks. You still need prepared statements for databases, safe shell APIs, and sandboxed template engines.

Q: Are JSON and NoSQL APIs less vulnerable to injection than traditional SQL?
They’re different, not inherently safer. The example of NoSQL injection with MongoDB shows that if you let clients control query objects or operators, you can still end up with serious injection bugs. The same goes for JSON-based filter and sort parameters that get concatenated into SQL or other query languages on the server.

Q: How do I prioritize fixing injection flaws in an existing codebase?
Start with features that touch authentication, authorization, and sensitive data access—login flows, admin consoles, reporting tools, and anything that runs shell commands or database queries. Use the examples of injection flaws in this article as a checklist: anywhere you see string concatenation with user input feeding an interpreter, you have a candidate for immediate refactoring.

Explore More Input Validation Errors

Discover more examples and insights in this category.

View All Input Validation Errors