| |

Web Security 12 🛡️ Injection & Prototype Pollution — Preventing SQL/NoSQL injection, command injection, path traversal, and JS prototype pollution

⏱️ Estimated read: 8 min | |

Injection vulnerabilities are among the most persistent threats in web security because they exploit a fundamental concept of computing: the boundary between data and instructions. When an application accepts untrusted input and feeds it into an interpreter—whether that is a database engine, an operating system shell, or a JavaScript runtime—the interpreter may be tricked into executing that input as code. This results in unauthorized data access, system compromise, or complete application takeover.

This chapter explores the taxonomy of injection flaws. We move from traditional SQL and NoSQL injection, which target data layers, to OS command injection and path traversal, which target the server environment. Finally, we address JavaScript Prototype Pollution, a unique vulnerability in dynamic languages where an attacker modifies the base structure of objects, potentially leading to remote code execution. Understanding these vulnerabilities requires moving away from the dangerous practice of “sanitizing” or “escaping” input and toward the industry-standard practice of using parameterized interfaces and strict input validation.

Key point: Injection occurs when untrusted user input is treated as executable code by an interpreter; preventing it requires strictly separating code from data using parameterized queries, allowlisting, and type-safe schemas, rather than attempting to filter or escape potentially malicious characters.


Why exists

The interpreter boundary.

Every application relies on interpreters: SQL databases, OS shells, file systems, and the JS engine. These interpreters must parse instructions. If they cannot distinguish between the instructions (the query/command) and the parameters (the user data), they are inherently vulnerable to injection.

The legacy of convenience.

Many early frameworks and patterns encouraged developers to concatenate strings to build queries. This is syntactically easy but logically flawed. Developers chose convenience over security, creating the massive backlog of legacy code that is still vulnerable to SQL injection today.

The dynamic nature of JS.

JavaScript’s flexibility is its superpower and its weakness. Because objects can be modified at runtime and prototypes can be accessed and altered, it is possible for an attacker to inject properties that affect the behavior of the entire application, leading to Prototype Pollution.

The complexity of the OS/FS.

Developers often need to interact with the file system or run system commands. Doing this safely is notoriously difficult because path traversal (using ../) and shell injection (using ;, &, |) are often overlooked when building features that require interacting with the underlying OS.

The implicit trust of APIs.

Developers often assume that JSON is “data” and therefore safe. However, NoSQL injection happens because the database sees JSON-like objects (e.g., MongoDB $gt operators) as commands, not just data. The application fails to validate the structure of the input, treating it as a literal value when it is actually a database instruction.


a. Injection Foundations (SQL and NoSQL)

SQL Injection (SQLi) happens when user input is concatenated directly into a query string. The attacker provides SQL syntax (like ' OR '1'='1) to alter the query logic. NoSQL injection is similar but targets the query structure (like MongoDB objects), where an attacker replaces a string with an object containing operators.

// VULNERABLE: SQL string concatenation
const query = "SELECT * FROM users WHERE username = '" + username + "'";
db.execute(query);

The fix is parameterization. By sending the query structure and the data separately, the database engine is instructed to treat the input as a literal value, never as part of the command. In NoSQL, the fix is strict schema validation using libraries like Zod or Joi to ensure that input cannot contain unexpected objects or operators.

// SECURE: Parameterized query (SQL)
const query = "SELECT * FROM users WHERE username = ?";
db.execute(query, [username]);

b. System & Path Injection

Command injection occurs when an application calls OS-level utilities (like ls, grep, or custom binaries) using input that hasn’t been validated for shell meta-characters. Path traversal is a related flaw where an attacker uses ../ sequences to read files outside the intended directory.

// VULNERABLE: OS Command injection
const { exec } = require('child_process');
exec('grep ' + searchTerm + ' file.txt'); // Attacker inputs: "; rm -rf /"

The solution for command injection is to avoid shell execution entirely. If you must use it, use execFile or spawn with an array of arguments, which prevents the shell from interpreting meta-characters. For path traversal, never use the raw file path provided by the user. Map the input to an internal ID or use path.basename() to force the path to a flat structure.

c. Prototype Pollution

Prototype Pollution is a vulnerability where an attacker manipulates the __proto__ or constructor property of an object to add or modify properties on the global Object.prototype. Because almost all objects in JavaScript inherit from this prototype, the injected properties appear in every object in the application, leading to logic bypasses or RCE.

// VULNERABLE: Recursive merge that allows property injection
function merge(target, source) {
  for (let key in source) {
    if (typeof source[key] === 'object') merge(target[key], source[key]);
    else target[key] = source[key];
  }
}
// Payload: { "__proto__": { "isAdmin": true } }

This vulnerability usually happens in recursive merge functions. The fix is to validate key names, reject keys like __proto__, constructor, and prototype explicitly, or use Object.create(null) to create objects without a prototype chain, making them immune to pollution.


Complete Example Session

// ============================================
// PART 1: SQL INJECTION (PREVENTION)
// ============================================
import mysql from 'mysql2/promise';

async function getUser(username: string) {
  // Use '?' as a placeholder, not string interpolation
  const [rows] = await db.execute('SELECT * FROM users WHERE username = ?', [username]);
  return rows;
}

// ============================================
// PART 2: COMMAND INJECTION (PREVENTION)
// ============================================
import { spawn } from 'child_process';

function listFiles(directory: string) {
  // Use spawn with arguments array, prevents shell interpretation
  const child = spawn('ls', ['-l', directory]);
  // ...
}

// ============================================
// PART 3: PATH TRAVERSAL (PREVENTION)
// ============================================
import path from 'path';

function getFile(filename: string) {
  // path.basename strips path separators, forcing it to be a filename
  const safeName = path.basename(filename);
  const fullPath = path.join('/app/uploads', safeName);
  // ...
}

// ============================================
// PART 4: PROTOTYPE POLLUTION (PREVENTION)
// ============================================
function safeMerge(target: any, source: any) {
  for (let key in source) {
    // Block sensitive properties
    if (key === '__proto__' || key === 'constructor') continue;
  
    if (typeof source[key] === 'object') safeMerge(target[key], source[key]);
    else target[key] = source[key];
  }
}

This session demonstrates the standard fix for each injection type: parameterization for SQL, argument separation for OS commands, filename sanitization for path traversal, and explicit key blocking for prototype pollution.


Quick Reference

Vulnerability Sinks

VulnerabilitySink (The Dangerous Function)
SQL Injectiondb.execute(string), query(string)
Command Injectionexec(), eval(), system()
Path Traversalfs.readFile(path), open(path)
Prototype PollutionRecursive merge, Object cloning

Prevention Strategies

TechniqueApplies To
Parameterized QueriesSQL Injection
Avoid ShellsCommand Injection
Input MappingPath Traversal
Key AllowlistingPrototype Pollution

Prototype Pollution Indicators

PropertyAction
__proto__Block this key
constructorBlock this key
prototypeBlock this key

Best Practices

✅ Do This:

// Use parameterized queries
db.execute("SELECT * FROM users WHERE id = ?", [id]);        // ✅

// Use path.basename for files
fs.readFile(path.join(dir, path.basename(input)));           // ✅

// Validate recursive merges
if (key === '__proto__') continue;                           // ✅

// Use Object.create(null)
const safeObj = Object.create(null);                         // ✅

❌ Don’t Do This:

// String concatenation for SQL
db.execute("SELECT * FROM users WHERE id = " + id);          // ❌

// Use exec() with user input
exec("ls " + input);                                         // ❌

// Use eval() on user input
eval(input);                                                 // ❌

// Trust JSON input without schema validation
const data = JSON.parse(input);                              // ❌

Common Pitfalls

PitfallWhy It HappensFix
BlacklistingTrying to block OR, ', ;Use Parameterization
EscapingThinking \ fixes everythingUse Parameterization
JSON TrustAssuming JSON is just dataUse Schema Validation (Zod)
Shell WrappersUsing exec instead of spawnSwitch to Argument Arrays

Real-World Examples

1. Parameterized SQL

db.query('SELECT * FROM posts WHERE id = ?', [id]);

2. OS Command Arguments

spawn('/usr/bin/git', ['log', branchName]);

3. Path Traversal Cleanup

const safe = path.normalize(input).replace(/^(\.\.(\/|\\|$))+/, '');

4. Prototype Blocking

if (key === '__proto__') throw new Error('Unsafe');

5. NoSQL Schema

const schema = z.object({ id: z.string() });

6. Exec Prevention

// Never use exec('grep ' + input);

7. Null Object

const obj = Object.create(null);

8. URL Sanitization

const url = new URL(userInput, 'https://trusted.com');

9. Template Strings (SQL)

// Don't use tagged templates unless they are SQL-aware

10. Deep Freeze

Object.freeze(Object.prototype); // Global protection

Visual

The Interpreter Boundary

┌──────────────────────────────────────────────┐
│  DATA (Input) ──► [PARSER] ──► COMMAND       │
│                                              │
│  INJECTION:                                  │
│  DATA includes COMMAND instructions          │
│       │                                      │
│       ▼                                      │
│  [PARSER] executes DATA as COMMAND           │
└──────────────────────────────────────────────┘

Path Traversal Logic

┌──────────────────────────────────────────────┐
│  USER INPUT: ../../../etc/passwd             │
│                                              │
│  APPLICATION:                                │
│  baseDir = /app/uploads                      │
│  join(baseDir, input)                        │
│       │                                      │
│  RESULT: /app/uploads/../../../etc/passwd    │
│  RESOLVED: /etc/passwd                       │
└──────────────────────────────────────────────┘

Prototype Pollution Chain

┌──────────────────────────────────────────────┐
│  ATTACKER: { "__proto__": { "admin": true } }│
│       │                                      │
│  MERGE FUNCTION:                             │
│  target.__proto__.admin = true               │
│       │                                      │
│  GLOBAL OBJECT:                              │
│  (All objects now have admin: true)          │
└──────────────────────────────────────────────┘

Summary

ItemValue
InjectionInput acting as Code
SQLi FixParameterized Queries
Command FixUse Argument Arrays
Path FixFilename Mapping
Proto FixObject.create(null)

Key takeaways:

  • Separate code from data. The root cause of all injection is the failure to separate data (user input) from instructions (database query, OS command). Parameterization is the only reliable cure.
  • Never trust interpreters. If you are passing input to a shell, a database, or a file system, assume it can be used to escape the intended sandbox.
  • Validation is not enough. Attempting to “clean” input (removing quotes, semicolons) is a losing battle. Attackers will always find encoding tricks to bypass filters. Use allowlisting and structural validation instead.
  • JavaScript is special. Prototype pollution is a logic vulnerability, not a syntactic one. Guard your recursive merges and object initialization logic carefully.
  • Use safe defaults. Use libraries that enforce these patterns, such as ORMs that auto-parameterize and file systems that force path flattening.

Remember: Injection vulnerability is entirely preventable. It does not exist because security is “too hard”; it exists because developers allow data to mix with instructions. By treating all user input as untrusted and using the specific APIs (parameterization, spawn, path.basename) designed to separate them, you eliminate the entire class of vulnerability.

Was this helpful?


Stop using slow, ad-bloated tool sites! 🤮

🔎 Search “KandZ Tools” on Google to use many professional utilities for free.

KandZ.me is the ultimate minimalist hub for:
✅ Finance (Mortgage, Interest, Inflation)
✅ Tech (Base64, JSON, Dev Suite, IP)
✅ Health (BMI, BMR, TDEE)
✅ Productivity (Timer, Workspace, QR)

⚡️ Fast & Private
🔒 No data leaves your device
💎 100% Free

🔗 Use it now: https://tools.kandz.me
🔖 Bookmark it—you’ll need it later!